ZigZag++ + 4 EMA89 Trend Candles + BUY/SELL LabelsThis script combines ZigZag patterns, EMA89 trend detection, and custom buy/sell scalp signals. It helps identify trend direction and potential entry points in trending markets.
Features:
- ZigZag structure points
- EMA89 as dynamic trend filter
- Buy/Sell scalp markers
- HL/HH swing labels
- Works best on 15m–4h timeframes
Indicators and strategies
Weinstein Stage Analyzer — Table Only (more padding)What it does
This indicator applies Stan Weinstein’s Stage Analysis (Stages 1–4) and presents the result in a clean, compact table only—no lines, labels, or overlays. It shows:
• Previous Stage
• Current Stage (with Early / Mature / Late tag)
• Duration (how long price has been in the current stage, in HTF bars)
• Sentiment (Bullish / Bearish / Balanced / Cautious, derived from stage & maturity)
Timeframe-aware logic
• Weekly charts: classic 30-period MA (Weinstein’s original 30-week concept).
• Daily & Intraday: computed on Daily 150 as a practical daily translation of the 30-week idea.
• Monthly: ~7-period MA (~30 weeks ≈ 7 months).
The stage classification itself is evaluated on this HTF context and then displayed on your active chart.
EMA/SMA toggle
Choose EMA (default) or SMA for the trend line used in stage detection.
How stages are decided (practical rules)
• Stage 2 (Advance): MA rising with price above an upper band.
• Stage 4 (Decline): MA falling with price below a lower band.
• Flat MA zones become Stage 1 (Base) or Stage 3 (Top) depending on the prior trend.
“Maturity” tags (Early/Mature/Late) come from run length and extension beyond the band.
Inputs you can tweak
• MA Type: EMA / SMA
• Price Band (±%) and Slope Threshold to tighten/loosen stage flips
• Maturity thresholds: min/max bars & late-extension %
Notes
• Duration is for the entire current stage (e.g., total time in Stage 4), not just the maturity slice.
• A Top Padding Rows input is included to nudge the table lower if it overlaps your OHLC readout.
Disclaimer
For educational use only. Not financial advice. Always confirm with your own analysis, risk management, and market context.
PSDIGreen Zone → Potential Buy Area
Price is near support.
Red Zone → Potential Sell Area
Price is near resistance.
EMA Lines
Blue (EMA50) above Orange (EMA200): Trend up → favors buys.
Blue below Orange: Trend down → favors sells.
How to Use
Look at zones and trend.
Price near green + trend up → consider long.
Price near red + trend down → consider short.
NOTE: When in uptrend, only follow green zones. When in down trend only follow red zones.
Swing Oracle Stock 2.0- Gradient Enhanced# 🌈 Swing Oracle Pro - Advanced Gradient Trading Indicator
**Transform your technical analysis with stunning gradient visualizations that make market trends instantly recognizable.**
## 🚀 **What Makes This Indicator Special?**
The **Swing Oracle Pro** revolutionizes traditional technical analysis by combining advanced NDOS (Normalized Distance from Origin of Source) calculations with a sophisticated gradient color system. This isn't just another indicator—it's a complete visual trading experience that adapts colors based on market strength, making trend identification effortless and intuitive.
## 🎨 **10 Professional Gradient Themes**
Choose from carefully crafted color schemes designed for optimal visual clarity:
- **🌅 Sunset** - Warm oranges and purples for classic elegance
- **🌊 Ocean** - Cool blues and teals for calm analysis
- **🌲 Forest** - Natural greens and browns for organic feel
- **✨ Aurora** - Ethereal greens and magentas for mystique
- **⚡ Neon** - Vibrant electric colors for high-energy trading
- **🌌 Galaxy** - Deep purples and cosmic hues for night sessions
- **🔥 Fire** - Intense reds and golds for volatile markets
- **❄️ Ice** - Cool whites and blues for clear-headed decisions
- **🌈 Rainbow** - Full spectrum for comprehensive analysis
- **⚫ Monochrome** - Professional grays for focused trading
## 📊 **Core Features**
### **Advanced NDOS System**
- Normalized Distance from Origin of Source calculation with 231-period length
- Smoothed with customizable EMA for reduced noise
- Multi-timeframe confirmation with H1 filter option
- Dynamic gradient coloring based on oscillator position
### **Intelligent Visual Feedback**
- **Primary Gradient Line** - Main NDOS plot with dynamic color transitions
- **Gradient Fill Zones** - Beautiful color-coded areas for bullish, neutral, and bearish regions
- **Smart Transparency** - Colors adjust intensity based on market volatility
- **Dynamic Backgrounds** - Subtle gradient backgrounds that respond to market conditions
### **Enhanced EMA Projection System**
- 75/760 period EMA normalization with 50-period lookback
- Gradient-colored projection line for trend forecasting
- Toggleable display with advanced gradient controls
- Price tracking for precise level identification
### **Multi-Timeframe Analysis Table**
- Real-time trend analysis across 6 timeframes (1m, 3m, 5m, 15m, 1H, 4H)
- Gradient-colored cells showing trend strength
- Customizable table size and position
- Professional emoji indicators (🚀 UP, 📉 DOWN, ➡️ FLAT)
### **Signal System**
- **Gradient Buy Signals** - Triangle up arrows with intensity-based coloring
- **Gradient Sell Signals** - Triangle down arrows with strength indicators
- **Alert Conditions** - Built-in alerts for all signal types
- **7-Day Cycle Tracking** - Tuesday-to-Tuesday weekly cycle visualization
## ⚙️ **Customization Controls**
### **🎨 Gradient Controls**
- **Gradient Intensity** - Adjust color vibrancy (0.1-1.0)
- **Gradient Smoothing** - Control color transition smoothness (1-10 periods)
- **Dynamic Background** - Toggle animated background gradients
- **Advanced Gradients** - Enable/disable EMA projection and enhanced features
### **🛠️ Custom Color System**
- **Bullish Colors** - Define custom start/end colors for bull markets
- **Bearish Colors** - Set personalized bear market gradients
- **Full Theme Override** - Create completely custom color schemes
- **Real-time Preview** - See changes instantly on your chart
## 📈 **How to Use**
1. **Choose Your Theme** - Select from 10 professional gradient themes
2. **Configure Levels** - Adjust high/low levels (default 60/40) for your timeframe
3. **Set Smoothing** - Fine-tune gradient smoothing for your trading style
4. **Enable Features** - Toggle background gradients, candlestick coloring, and advanced EMA projection
5. **Monitor Signals** - Watch for gradient buy/sell arrows and multi-timeframe confirmations
## 🎯 **Trading Applications**
- **Swing Trading** - Perfect for identifying medium-term trend changes
- **Scalping** - Multi-timeframe table provides quick trend confirmation
- **Position Sizing** - Gradient intensity shows signal strength for risk management
- **Market Analysis** - Beautiful visualizations make complex data instantly understandable
- **Education** - Ideal for learning market dynamics through visual feedback
## ⚡ **Performance Optimized**
- **Smart Rendering** - Colors update only on significant changes
- **Efficient Calculations** - Optimized algorithms for smooth performance
- **Memory Management** - Minimal resource usage even with complex gradients
- **Real-time Updates** - Responsive to market changes without lag
## 🚨 **Alert System**
Built-in alert conditions notify you when:
- NDOS crosses above high level (Buy Signal)
- NDOS crosses below low level (Sell Signal)
- Multi-timeframe confirmations align
- Customizable alert messages with emoji indicators
## 🔧 **Technical Specifications**
- **PineScript Version**: v6 (Latest)
- **Overlay**: True (plots on main chart)
- **Calculations**: NDOS, EMA normalization, volatility-based transparency
- **Timeframes**: Compatible with all timeframes
- **Markets**: Stocks, Forex, Crypto, Commodities, Indices
## 💡 **Why Choose Swing Oracle Pro?**
This isn't just another technical indicator—it's a complete visual transformation of your trading experience. The gradient system provides instant visual feedback that traditional indicators simply can't match. Whether you're a beginner learning to read market trends or an experienced trader seeking clearer signals, the Swing Oracle Pro delivers professional-grade analysis with unprecedented visual clarity.
**Experience the future of technical analysis. Your charts will never look the same.**
---
*⚠️ Disclaimer: This indicator is for educational and informational purposes only. Past performance does not guarantee future results. Always conduct your own research and consider risk management before making trading decisions.*
**🔔 Like this indicator? Please leave a comment and boost! Your feedback helps improve future updates.**
---
**📝 Tags:** #GradientTrading #SwingTrading #NDOS #MultiTimeframe #TechnicalAnalysis #VisualTrading #TrendAnalysis #ColorCoded #ProfessionalCharts #TradingToo
MTF QFG (Quarter Fib Grid)The MTF QFG (Quarter Fib Grid) calculates quarter Fibonacci levels based on the previous daily, weekly, or monthly high/low. These levels act as potential support and resistance zones. Suitable for scalping, swing trading, or identifying key price reactions.
RSI DCA StrategyThis strategy combines RSI oversold signals with a Dollar-Cost Averaging (DCA) buying approach.
Trigger:
When the RSI (Relative Strength Index) crosses below 30, the strategy marks an oversold condition.
DCA Entry:
Once triggered, the strategy executes up to three consecutive daily entries (1 per day), splitting the predefined capital equally (configurable by user).
Position Management:
Take Profit at a configurable % above the average entry price.
Stop Loss at a configurable % below the average entry price.
Exit Conditions:
The strategy automatically exits either on reaching Take Profit or Stop Loss.
Visualization:
RSI plotted with oversold line (30).
Take Profit and Stop Loss lines displayed after entry.
Performance Reporting:
Includes an optional monthly performance table for evaluating results by month.
Note:
This strategy is for testing RSI-based mean reversion with staggered entries. It is not financial advice and should be optimized and validated for each market or timeframe before practical use.
RSI DivergenceThe code originally belongs to Matthew J. Slabosz, the founder of Zen Trading (The Art of Trading). ✍️📈
👉 My contribution and improvement was adding a divergence line directly on the RSI chart.
Why? Because most people can’t confirm correctness just by reading the code. 🧑💻❌
They need to see it with their own eyes 👀✔️ — this prevents misinterpretation and makes divergences crystal clear.
✨ By adding these visual confirmations, the efficiency and usability of the code has been significantly enhanced. 🚀📊
RMA Smoothed RSIRMA Smoothed RSI
Description:
An enhanced RSI built for cleaner intraday and swing reads. It applies RMA smoothing to damp noise.
How It Works
RSI (RMA-Smoothed):
Computes classic RSI from price changes and smooths the result with an additional RMA (user-controlled 3–7, where 5 is the sweet spot). This reduces whipsaw while preserving shifts in momentum.
How to Interpret
50 Midline = Bias Filter: Above 50 favors strength; below 50 favors weakness.
RSI vs RSI-MA Crosses: Cross up can precede thrust or mean-revert toward 50; cross down the opposite.
Inputs
Length: RSI period (default 14).
Source: Price source for RSI (default Close).
Smoothing: RMA smoothing length on RSI (3–7; default 3; 5 sweet spot).
Calculate Divergence: Toggle to compute pivots/divergences and enable alerts.
Moving Average Type: None, SMA, EMA, WMA, VWMA (default EMA).
MA Length: Length of the RSI-based MA (separate from RSI length).
Best For
Traders who want a cleaner RSI read without losing responsiveness.
Scalpers timing momentum shifts around the 50 line and MA crosses.
Swing traders using divergences as early reversal context.
Pro Tips
For fast intraday charts, start with Length 14, Smoothing 3–5, and EMA as the RSI-MA.
Use 50 reclaims/rejections as a simple regime filter.
Combine divergence labels with volume surges, key S/R, or volatility tools (e.g., BBW/TTM squeeze) to time entries.
Divergence alerts fire only if Calculate Divergence is enabled—keep it on if you rely on signals.
Fibo RSIThis is a customized Relative Strength Index (RSI) indicator designed to replicate TradingView’s default RSI while adding additional reference levels for deeper market analysis.
🔹 Features:
RSI length set to 8 by default (user adjustable).
Calculates RSI using the standard ta.rsi() function.
Plots the RSI line in a clean, separate panel.
Adds 7 key levels for analysis: 0, 20, 30, 50, 70, 80, 100.
Levels are drawn as thin, solid straight lines for a cleaner look (instead of default dashed).
🔹 Use cases:
Identify momentum shifts with enhanced precision.
Use intermediate levels (20, 30, 50, 70, 80) as potential support/resistance zones.
Ideal for traders who want a Fibonacci-like structure in RSI analysis.
Set & Forget – AlexG Club – ChecklistThe Set & Forget – AlexG Club – Checklist is built to help traders apply the well-known Set and Forget strategy from the famous AlexG (falexg) and the G-Club community.
This indicator displays a clear, on-chart checklist table of trading confluences. Each confluence adds to a total score, making it easier to objectively evaluate whether a trade setup aligns with the AlexG / G-Club strategy.
✅ Features:
• Customizable confluence checklist (trend alignment, S/R levels, candlestick signals, momentum, etc.)
• Automatic scoring system to calculate the Set & Forget readiness of a trade
• Clean table visualization on your chart
• Flexible thresholds — you decide how many confluences equal a strong setup
🚀 How to Use:
Add the indicator to your chart.
Adjust the confluences to reflect your own AlexG / G-Club inspired checklist.
Use the total score to validate trades before you pull the trigger.
⚠️ Disclaimer: This indicator is for educational purposes only. It is not financial advice and does not guarantee profitability. Always manage your risk and test before using live.
WTI Futures Premarket Breakout Strategy Premarket Breakout Strategy (Adjust prices on source code at 9:00 AM EST and 9:30 AM EST)
RSI HIGHs and LOWs MarkerThis indicator marks significant RSI (14) pivot points directly on the price chart.
Red markers above candles highlight confirmed RSI highs where the RSI value exceeded 75 (overbought zone).
Green markers below candles highlight confirmed RSI lows where the RSI value dropped below 25 (oversold zone).
These signals help traders quickly identify potential reversal zones and overextended market conditions without having to monitor the RSI window separately.
Iani SMC Sniper XAU v2.2 (Long+Short + News Countdown, v6)Iani SMC Sniper v2.6 — Anytime • Auto Pip • FVG 50% • OB • News Panel
Smart-Money Concepts made simple for intraday XAU/USD (works on any symbol).
Finds BOS, 50% FVG “sniper” entries, optional Order Blocks, London H/L, news countdown, and a mini info panel.
What it does
BOS (Break of Structure): detects bullish/bearish BOS after London sweep logic.
FVG 50% entries: plots precise long/short entry dots at the midpoint of the gap.
Auto TP/SL: TP = RR × risk, SL below/above recent swing with a small buffer.
Order Blocks (optional): marks the last opposite candle after BOS and alerts on OB revisit.
London High/Low: tracks session range; session filter is optional.
News countdown: shows next event time and minutes left (user-selectable timezone).
Mini Panel: top-left table with Trend (last BOS), Next news, R:R, Pip size.
Inputs (key)
Auto pip size: uses syminfo.mintick. Manual override available.
Risk:Reward (RR): default 2.0.
Pivot length: swing sensitivity.
Sessions: enable if you want signals only 12:00–20:00 (symbol timezone). Off = anytime.
News timezone: pick your own (e.g., Europe/Brussels, America/New_York).
Absolute & daily times: add your events (strings like 2025-09-17 20:00 or 14:30,16:00…).
Show labels/levels/OBs: toggle on/off.
Alerts included
BOS Bullish / BOS Bearish
BUY Entry / SELL Entry (return to 50% FVG)
Bullish OB revisit / Bearish OB revisit
TP Long/Short reached, SL Long/Short hit
NEWS WARNING (warning window only; does not block signals)
To use: Add Alert → Condition: this indicator → choose any of the alertconditions.
Best use
Bias: H1 for structure.
Execution: M15 (standard) or M5 (aggressive).
Works great on XAUUSD, but is symbol-agnostic (auto pip adapts).
Notes
News times display in the timezone you pick in settings.
OBs are a simple implementation meant for quick visual guidance.
Labels: BUY/SELL near entries, TP/SL on set and when hit, BOS up/down.
Risk disclaimer
This tool is for education only. Not financial advice. Backtest and manage risk.
Hazel nut BB Strategy, volume base- lite versionHazel nut BB Strategy, volume base — lite version
Having knowledge and information in financial markets is only useful when a trader operates with a well-defined trading strategy. Trading strategies assist in capital management, profit-taking, and reducing potential losses.
This strategy is built upon the core principle of supply and demand dynamics. Alongside this foundation, one of the widely used technical tools — the Bollinger Bands — is employed to structure a framework for profit management and risk control.
In this strategy, the interaction of these tools is explained in detail. A key point to note is that for calculating buy and sell volumes, a lower timeframe function is used. When applied with a tick-level resolution, this provides the most precise measurement of buyer/seller flows. However, this comes with a limitation of reduced historical depth. Users should be aware of this trade-off: if precise tick-level data is required, shorter timeframes should be considered to extend historical coverage .
The strategy offers multiple configuration options. Nevertheless, it should be treated strictly as a supportive tool rather than a standalone trading system. Decisions must integrate personal analysis and other instruments. For example, in highly volatile assets with narrow ranges, it is recommended to adjust profit-taking and stop-loss percentages to smaller values.
◉ Volume Settings
• Buyer and seller volume (up/down volume) are requested from a lower timeframe, with an option to override the automatic resolution.
• A global lookback period is applied to calculate moving averages and cumulative sums of buy/sell/delta volumes.
• Ratios of buyers/sellers to total volume are derived both on the current bar and across the lookback window.
◉ Bollinger Band
• Bands are computed using configurable moving averages (SMA, EMA, RMA, WMA, VWMA).
• Inputs allow control of length, standard deviation multiplier, and offset.
• The basis, upper, and lower bands are plotted, with a shaded background between them.
◉ Progress & Proximity
• Relative position of the price to the Bollinger basis is expressed as percentages (qPlus/qMinus).
• “Near band” conditions are triggered when price progress toward the upper or lower band exceeds a user-defined threshold (%).
• A signed score (sScore) represents how far the close has moved above or below the basis relative to band width.
◉ Info Table
• Optional compact table summarizing:
• - Upper/lower band margins
• - Buyer/seller volumes with moving averages
• - Delta and cumulative delta
• - Buyer/seller ratios per bar and across the window
• - Money flow values (buy/sell/delta × price) for bar-level and summed periods
• The table is neutral-colored and resizable for different chart layouts.
◉ Zone Event Gate
• Tracks entry into and exit from “near band” zones.
• Arming logic: a side is armed when price enters a band proximity zone.
• Trigger logic: on exit, a trade event is generated if cumulative buyer or seller volume dominates over a configurable window.
◉ Trading Logic
• Orders are placed only on zone-exit events, conditional on volume dominance.
• Position sizing is defined as a fixed percentage of strategy equity.
• Long entries occur when leaving the lower zone with buyer dominance; short entries occur when leaving the upper zone with seller dominance.
◉ Exit Rules
• Open positions are managed by a strict priority sequence:
• 1. Stop-loss (% of entry price)
• 2. Take-profit (% of entry price)
• 3. Opposite-side event (zone exit with dominance in the other direction)
• Stop-loss and take-profit levels are configurable
◉ Notes
• This lite version is intended to demonstrate the interaction of Bollinger Bands and volume-based dominance logic.
• It provides a framework to observe how price reacts at band boundaries under varying buy/sell pressure, and how zone exits can be systematically converted into entry/exit signals.
When configuring this strategy, it is essential to carefully review the settings within the Strategy Tester. Ensure that the chosen parameters and historical data options are correctly aligned with the intended use. Accurate back testing depends on applying proper configurations for historical reference. The figure below illustrates sample result and configuration type.
Smart Money Flow Index (SMFI) - This tool is useful for comparing price action with underlying money flow and spotting where smart money may be entering or exiting the market.
Short Sellingell signal when RSI < 40, MACD crosses zero or signal line downward in negative zone, close below 50 EMA, candle bearish.
Strong sell signal confirmed on 5-minute higher timeframe with same conditions.
Square off half/full signals as defined.
Target lines drawn bold based on previous swing lows and extended as described.
Blue candle color when RSI below 30.
One sell and one full square off per cycle, blocking repeated sells until full square off.
Percentage Change per 5 Candles
🔎 What this indicator does
This indicator calculates and displays the percentage change of each candlestick directly on the chart.
• If a candle closed higher than it opened (bullish candle), it shows a positive % change (green).
• If a candle closed lower than it opened (bearish candle), it shows a negative % change (red).
• Small moves below your chosen threshold (e.g., 0.1%) are ignored to avoid clutter.
• The labels are placed above, below, or in the center of the candle (you choose).
So essentially, every candle “tells you in numbers” exactly how much it changed relative to its opening price.
________________________________________
⚙️ How it operates (the logic inside)
1. Calculate the change
o Formula:
\text{% Change} = \frac{(\text{Close} - \text{Open})}{\text{Open}} \times 100
o Example: If a candle opens at 100 and closes at 105, that’s a +5% change.
2. Round it nicely
o You can control decimals (e.g., show 2 decimals → +5.23%).
3. Filter out noise
o If a candle barely moved (say 0.02%), the label won’t appear unless you reduce the threshold.
4. Style the labels
o Bullish = green text, slightly transparent green background.
o Bearish = red text, slightly transparent red background.
o Neutral (0%) = gray.
5. Place the labels
o Options: above the candle, below the candle, or centered.
o Small vertical offset is applied so labels don’t overlap the candle itself.
________________________________________
📊 How this helps traders
This indicator turns visual candles into quantifiable numbers at a glance. Instead of guessing whether a move was “big” or “small,” you see it clearly.
Key Benefits:
1. Quick volatility analysis
o You can instantly see if candles are making big % swings or just small moves.
o This is especially useful on higher timeframes (daily/weekly) where moves can be large.
2. Pattern confirmation
o For example, you might spot a strong bullish engulfing candle — the % change label helps confirm whether it was truly significant (e.g., +4.5%) or just modest (+0.7%).
3. Noise filtering
o By setting a minimum % threshold, you only see labels when moves are meaningful (say > 0.5%). This keeps focus on important candles.
4. Backtesting & comparison
o You can compare moves across time:
“How strong was this breakout candle compared to the last one?”
“Are today’s bearish candles weaker or stronger than yesterday’s bullish candles?”
5. Better decision-making
o If you’re trading breakouts, reversals, or trend-following, knowing the % size of each candle helps confirm if the move has enough momentum.
________________________________________
✅ In short:
This indicator quantifies price action. Instead of just seeing “green” or “red” candles, you now know exactly how much the price changed in percentage terms, directly on the chart, in real time. It helps you distinguish between strong and weak moves and makes your analysis more precise.
________________________________________
10-Crypto Normalized IndexOverview
This indicator builds a custom index for up to 10 cryptocurrencies and plots their combined trend as a single line. Each coin is normalized to 100 at a user-selected base date (or at its first available bar), then averaged (equally or by your custom weights). The result lets you see the market direction of your basket at a glance.
How it works
For each symbol, the script finds a base price (first bar ≥ the chosen base date; or the first bar in history if base-date normalization is off).
It converts the current price to a normalized value: price / base × 100.
It then computes a weighted average of those normalized values to form the index.
A dotted baseline at 100 marks the starting point; values above/below 100 represent % performance vs. the base.
Key inputs
Symbols (10 max): Default set: BTC, ETH, SOL, POL, OKB, BNB, SUI, LINK, 1INCH, TRX (USDT pairs). You can change exchange/quote (keep all the same quote, e.g., all USDT).
Weights: Toggle equal weights or enter custom weights. Custom weights are auto-normalized internally, so they don’t need to sum to 1.
Base date: Year/Month/Day (default: 2025-06-01). Turning normalization off uses each symbol’s first available bar as its base.
Smoothing: Optional SMA to reduce noise.
Show baseline: Toggle the horizontal line at 100.
Interpretation
Index > 100 and rising → your basket is up since the base date.
Index < 100 and falling → down since the base date.
Use shorter timeframes for intraday sentiment, higher timeframes for swing/trend context.
Default basket & weights (editable)
Order: BTC, ETH, SOL, POL, OKB, BNB, SUI, LINK, 1INCH, TRX.
Default custom weight factors: 30, 30, 20, 10, 10, 5, 5, 5, 5, 5 (auto-normalized).
Base date: 2025-06-01.
FiniteStateMachine🟩 OVERVIEW
A flexible framework for creating, testing and implementing a Finite State Machine (FSM) in your script. FSMs use rules to control how states change in response to events.
This is the first Finite State Machine library on TradingView and it's quite a different way to think about your script's logic. Advantages of using this vs hardcoding all your logic include:
• Explicit logic : You can see all rules easily side-by-side.
• Validation : Tables show your rules and validation results right on the chart.
• Dual approach : Simple matrix for straightforward transitions; map implementation for concurrent scenarios. You can combine them for complex needs.
• Type safety : Shows how to use enums for robustness while maintaining string compatibility.
• Real-world examples : Includes both conceptual (traffic lights) and practical (trading strategy) demonstrations.
• Priority control : Explicit control over which rules take precedence when multiple conditions are met.
• Wildcard system : Flexible pattern matching for states and events.
The library seems complex, but it's not really. Your conditions, events, and their potential interactions are complex. The FSM makes them all explicit, which is some work. However, like all "good" pain in life, this is front-loaded, and *saves* pain later, in the form of unintended interactions and bugs that are very hard to find and fix.
🟩 SIMPLE FSM (MATRIX-BASED)
The simple FSM uses a matrix to define transition rules with the structure: state > event > state. We look up the current state, check if the event in that row matches, and if it does, output the resulting state.
Each row in the matrix defines one rule, and the first matching row, counting from the top down, is applied.
A limitation of this method is that you can supply only ONE event.
You can design layered rules using widlcards. Use an empty string "" or the special string "ANY" for any state or event wildcard.
The matrix FSM is foruse where you have clear, sequential state transitions triggered by single events. Think traffic lights, or any logic where only one thing can happen at a time.
The demo for this FSM is of traffic lights.
🟩 CONCURRENT FSM (MAP-BASED)
The map FSM uses a more complex structure where each state is a key in the map, and its value is an array of event rules. Each rule maps a named condition to an output (event or next state).
This FSM can handle multiple conditions simultaneously. Rules added first have higher priority.
Adding more rules to existing states combines the entries in the map (if you use the supplied helper function) rather than overwriting them.
This FSM is for more complex scenarios where multiple conditions can be true simultaneously, and you need to control which takes precedence. Like trading strategies, or any system with concurrent conditions.
The demo for this FSM is a trading strategy.
🟩 HOW TO USE
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For example, for version 1 of this library, import it like this:
import SimpleCryptoLife/FiniteStateMachine/1
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
🟩 TECHNICAL IMPLEMENTATION
Both FSM implementations support wildcards using blank strings "" or the special string "ANY". Wildcards match in this priority order:
• Exact state + exact event match
• Exact state + empty event (event wildcard)
• Empty state + exact event (state wildcard)
• Empty state + empty event (full wildcard)
When multiple rules match the same state + event combination, the FIRST rule encountered takes priority. In the matrix FSM, this means row order determines priority. In the map FSM, it's the order you add rules to each state.
The library uses user-defined types for the map FSM:
• o_eventRule : Maps a condition name to an output
• o_eventRuleWrapper : Wraps an array of rules (since maps can't contain arrays directly)
Everything uses strings for maximum library compatibility, though the examples show how to use enums for type safety by converting them to strings.
Unlike normal maps where adding a duplicate key overwrites the value, this library's `m_addRuleToEventMap()` method *combines* rules, making it intuitive to build rule sets without breaking them.
🟩 VALIDATION & ERROR HANDLING
The library includes comprehensive validation functions that catch common FSM design errors:
Error detection:
• Empty next states
• Invalid states not in the states array
• Duplicate rules
• Conflicting transitions
• Unreachable states (no entry/exit rules)
Warning detection:
• Redundant wildcards
• Empty states/events (potential unintended wildcards)
• Duplicate conditions within states
You can display validation results in tables on the chart, with tooltips providing detailed explanations. The helper functions to display the tables are exported so you can call them from your own script.
🟩 PRACTICAL EXAMPLES
The library includes four comprehensive demos:
Traffic Light Demo (Simple FSM) : Uses the matrix FSM to cycle through traffic light states (red → red+amber → green → amber → red) with timer events. Includes pseudo-random "break" events and repair logic to demonstrate wildcards and priority handling.
Trading Strategy Demo (Concurrent FSM) : Implements a realistic long-only trading strategy using BOTH FSM types:
• Map FSM converts multiple technical conditions (EMA crosses, gaps, fractals, RSI) into prioritised events
• Matrix FSM handles state transitions (idle → setup → entry → position → exit → re-entry)
• Includes position management, stop losses, and re-entry logic
Error Demonstrations : Both FSM types include error demos with intentionally malformed rules to showcase the validation system's capabilities.
🟩 BRING ON THE FUNCTIONS
f_printFSMMatrix(_mat_rules, _a_states, _tablePosition)
Prints a table of states and rules to the specified position on the chart. Works only with the matrix-based FSM.
Parameters:
_mat_rules (matrix)
_a_states (array)
_tablePosition (simple string)
Returns: The table of states and rules.
method m_loadMatrixRulesFromText(_mat_rules, _rulesText)
Loads rules into a rules matrix from a multiline string where each line is of the form "current state | event | next state" (ignores empty lines and trims whitespace).
This is the most human-readable way to define rules because it's a visually aligned, table-like format.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_rulesText (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_addRuleToMatrix(_mat_rules, _currentState, _event, _nextState)
Adds a single rule to the rules matrix. This can also be quite readble if you use short variable names and careful spacing.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_nextState (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_validateRulesMatrix(_mat_rules, _a_states, _showTable, _tablePosition)
Validates a rules matrix and a states array to check that they are well formed. Works only with the matrix-based FSM.
Checks: matrix has exactly 3 columns; no empty next states; all states defined in array; no duplicate states; no duplicate rules; all states have entry/exit rules; no conflicting transitions; no redundant wildcards. To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the rules and states are ready.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_a_states (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the rules and states are valid; `false` if errors or warnings exist.
method m_getStateFromMatrix(_mat_rules, _currentState, _event, _strictInput, _strictTransitions)
Returns the next state based on the current state and event, or `na` if no matching transition is found. Empty (not na) entries are treated as wildcards if `strictInput` is false.
Priority: exact match > event wildcard > state wildcard > full wildcard.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_strictInput (bool)
_strictTransitions (bool)
Returns: The next state or `na`.
method m_addRuleToEventMap(_map_eventRules, _state, _condName, _output)
Adds a single event rule to the event rules map. If the state key already exists, appends the new rule to the existing array (if different). If the state key doesn't exist, creates a new entry.
Namespace types: map
Parameters:
_map_eventRules (map)
_state (string)
_condName (string)
_output (string)
Returns: No explicit return. The map is modified as a side-effect.
method m_addEventRulesToMapFromText(_map_eventRules, _configText)
Loads event rules from a multiline text string into a map structure.
Format: "state | condName > output | condName > output | ..." . Pairs are ordered by priority. You can have multiple rules on the same line for one state.
Supports wildcards: Use an empty string ("") or the special string "ANY" for state or condName to create wildcard rules.
Examples: " | condName > output" (state wildcard), "state | > output" (condition wildcard), " | > output" (full wildcard).
Splits lines by , extracts state as key, creates/appends to array with new o_eventRule(condName, output).
Call once, e.g., on barstate.isfirst for best performance.
Namespace types: map
Parameters:
_map_eventRules (map)
_configText (string)
Returns: No explicit return. The map is modified as a side-effect.
f_printFSMMap(_map_eventRules, _a_states, _tablePosition)
Prints a table of map-based event rules to the specified position on the chart.
Parameters:
_map_eventRules (map)
_a_states (array)
_tablePosition (simple string)
Returns: The table of map-based event rules.
method m_validateEventRulesMap(_map_eventRules, _a_states, _a_validEvents, _showTable, _tablePosition)
Validates an event rules map to check that it's well formed.
Checks: map is not empty; wrappers contain non-empty arrays; no duplicate condition names per state; no empty fields in o_eventRule objects; optionally validates outputs against matrix events.
NOTE: Both "" and "ANY" are treated identically as wildcards for both states and conditions.
To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the map is ready.
Namespace types: map
Parameters:
_map_eventRules (map)
_a_states (array)
_a_validEvents (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the event rules map is valid; `false` if errors or warnings exist.
method m_getEventFromConditionsMap(_currentState, _a_activeConditions, _map_eventRules)
Returns a single event or state string based on the current state and active conditions.
Uses a map of event rules where rules are pre-sorted by implicit priority via load order.
Supports wildcards using empty string ("") or "ANY" for flexible rule matching.
Priority: exact match > condition wildcard > state wildcard > full wildcard.
Namespace types: series string, simple string, input string, const string
Parameters:
_currentState (string)
_a_activeConditions (array)
_map_eventRules (map)
Returns: The output string (event or state) for the first matching condition, or na if no match found.
o_eventRule
o_eventRule defines a condition-to-output mapping for the concurrent FSM.
Fields:
condName (series string) : The name of the condition to check.
output (series string) : The output (event or state) when the condition is true.
o_eventRuleWrapper
o_eventRuleWrapper wraps an array of o_eventRule for use as map values (maps cannot contain collections directly).
Fields:
a_rules (array) : Array of o_eventRule objects for a specific state.
BK AK-Flag Formations🏴☠️ Introducing BK AK-Flag Formations — Raise the standard. Drive the line. Continue the assault. 🏴☠️
Built for traders who exploit momentum with discipline: flagpoles, flags, and pennants detected, tagged, and briefed—so you can press advantage instead of hesitating.
🎖️ Full Credit
The pattern engine, detection logic, and architecture are Trendoscope—one of the absolute best coders on TradingView and the original creator of this indicator’s core. I asked for interface upgrades and knew he was deep in other builds, so I forged the add-ons and released them for the community that values them.
My enhancements (on top of Trendoscope):
Label transparency (text + background)
Short-form labels (BF/BeF/BP/BeP/…)
Transparency controls for short-form labels
Hover tooltips with full pattern name + bullish/bearish bias (toggle)
Everything else is Trendoscope. Respect where it’s due.
🧠 What It Does
Locks onto flags and pennants after strong impulses (flagpoles).
Prints clean battlefield tags (BF, BeF, BP, BeP…) so the setup is obvious without burying price.
Mouse-over for the brief: full pattern name + directional bias exactly when you need it.
Multi-zigzag sweep for micro→macro detection, overlap control, bar-ratio verification, max-pattern caps, dark/light aware palette + custom colors.
🧭 Read the Continuation
BF — Bull Flag: strong pole, orderly pullback; look for break and measured move continuity.
BP — Bull Pennant: tight triangle after thrust; expansion confirms carry.
BeF — Bear Flag: weak rallies in a downtrend; break = continuation lower.
BeP — Bear Pennant: compressed pause beneath resistance; release favors trend.
Standards are not decoration—they are orders.
🤝 Acknowledgments
Original engine & libraries: Trendoscope (legend).
Enhancement layer (UX): transparency, short codes, tooltip system — BK.
Mentor: A.K. — clarity, patience, judgment. His discipline guides every choice here.
🫡 Give Forward
Don’t be cheap with your knowledge. If my indicators sharpen your edge:
Teach someone to read structure with discipline.
Share your process, not just screenshots.
Contribute code, context, or courage to those behind you.
Tools are force multipliers. Character decides how they’re used.
🙏 Final Word
“Plans are established by counsel; by wise guidance wage war.” — Proverbs 20:18
Impulse → formation → continuation.
Raise the banner, hold formation, and execute with wisdom.
BK AK-Flag Formations — when the standard rises, the line advances.
Gd bless. 🙏
ZigZag++ + 4 EMA89 Trend Candles + BUY/SELL LabelsThis script combines ZigZag patterns, EMA89 trend detection, and custom buy/sell scalp signals. It helps identify trend direction and potential entry points in trending markets.
Features:
- ZigZag structure points
- EMA89 as dynamic trend filter
- Buy/Sell scalp markers
- HL/HH swing labels
- Works best on 15m–4h timeframes
High and Low - MS - 2.0"Showing the high and low points with numbers.
Micha the leftist didn’t say how it’s called in his video.
#LeftismIsAMentalIllness"
נותן לראות את הנקודות הגבוהות והנמוכות עם מספרים
מיכה השמאלן לא אמר איך קוראים לזה בסרטון שלו
#שמאלנותזומחלתנפש
14/09/2025