Peshraw strategy 1//@version=5
indicator("Peshraw strategy 1", overlay=false)
// --- Stochastic Settings
kPeriod = 100
dPeriod = 3
slowing = 3
k = ta.sma(ta.stoch(close, high, low, kPeriod), slowing)
d = ta.sma(k, dPeriod)
// --- Moving Average on Stochastic %K
maLength = 2
maOnK = ta.sma(k, maLength)
// --- Plot Stochastic
plot(k, color=color.blue, title="%K")
plot(d, color=color.orange, title="%D")
// --- Plot MA(2) on %K
plot(maOnK, color=color.red, title="MA(2) on %K")
// --- Levels (fix hline error)
hline(9, "Level 9", color=color.gray, linestyle=hline.style_dotted)
hline(18, "Level 18", color=color.gray, linestyle=hline.style_dotted)
hline(27, "Level 27", color=color.gray, linestyle=hline.style_dotted)
hline(36, "Level 36", color=color.gray, linestyle=hline.style_dotted)
hline(45, "Level 45", color=color.gray, linestyle=hline.style_dotted)
hline(54, "Level 54", color=color.gray, linestyle=hline.style_dotted)
hline(63, "Level 63", color=color.gray, linestyle=hline.style_dotted)
hline(72, "Level 72", color=color.gray, linestyle=hline.style_dotted)
hline(81, "Level 81", color=color.gray, linestyle=hline.style_dotted)
hline(91, "Level 91", color=color.gray, linestyle=hline.style_dotted)
Penunjuk dan strategi
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. 🙏
Penny Stock Short ScalpPenny Stock Short Scalp:
This Penny Stock Short Scalp Strategy is designed for traders aiming to capitalize on rapid, short-term price declines in penny stocks using TradingView. Focused on high-volatility periods, this strategy leverages quick entries and exits to capture small, consistent profits.
Strategy Overview
Timeframe: 1-minute or 2-minute charts for precise entries and exits.
Market: Penny stocks (low-priced, high-volatility stocks, typically under $5).
Trading Window: Best executed during the first 1-2 hours of market open (9:30 AM - 11:30 AM EST) when volatility is highest.
Position Type: Short positions only, targeting rapid price drops.
Key Indicators
Exponential Moving Average (EMA): 20-period EMA to identify short-term trends. A price below the EMA signals a potential short opportunity.
Relative Strength Index (RSI): 14-period RSI to detect overbought conditions (RSI > 70) for short entry signals.
Volume: High trading volume confirms momentum and liquidity for quick exits.
Bollinger Bands: Used to identify overextended price movements. A price touching or breaking above the upper band suggests a potential reversal for shorting.
Entry Rules
Price Action: Price breaks above the 20 EMA and touches or exceeds the upper Bollinger Band.
RSI Confirmation: RSI is above 70, indicating overbought conditions.
Volume Surge: A spike in volume supports the potential for a quick reversal.
Support/Resistance: Identify a nearby resistance level (intraday or daily) to confirm the short setup.
Exit Rules
Profit Target: Aim for a 2-5% price drop or a fixed profit target (e.g., $0.05-$0.10 per share, depending on stock price).
Stop Loss: Set a stop loss above the recent high or 2% above entry to limit risk.
Close Position: Exit if the price crosses back above the 20 EMA or RSI drops below 50, signaling a potential reversal.
Risk Management
Position Sizing: Risk no more than 1-2% of your account per trade.
Liquidity Check: Ensure the stock has sufficient volume to avoid slippage.
Time Limit: Exit trades within 5-10 minutes to avoid holding through unpredictable swings.
Notes
Market Conditions: Best suited for ranging or slightly bearish markets where pullbacks are frequent.
Caution: Penny stocks are highly volatile; use tight stops and avoid overleveraging.
Platform: Configure TradingView with the above indicators and use real-time data for accurate signals.
Disclaimer: This strategy involves significant risk due to the volatile nature of penny stocks. Always conduct your own research and consult a financial advisor before trading. Past performance is not indicative of future results.
Weekly Setup Scanner (Trend + Momentum + Squeeze)Trend → price above weekly 20 EMA.
Momentum → weekly MACD bullish (MACD > Signal).
Volatility → weekly squeeze (Bollinger Bands inside Keltner Channels).
If all 3 conditions align → it flags the setup
Dual-Frame Momentum OscillatorDual-Frame Momentum Oscillator (DFMO)
This is not just another oscillator. This is a confluence engine, built for the discerning trader who reads the story of price action and needs an objective tool to confirm the climax.
The Dual-Frame Momentum Oscillator was designed to solve a specific problem: how to differentiate a genuine, sustainable breakout from an exhaustive liquidity grab. It provides a visual confirmation for high-probability reversal and scalp setups by measuring momentum across two distinct time frames simultaneously.
This tool is for the trader who understands that indicators should not dictate trades, but rather confirm a well-defined thesis based on market structure, volume, and liquidity.
The Core Concept: Context Meets Trigger
The DFMO fuses a slow, methodical Stochastic with a hyper-sensitive RSI to give you a complete picture of momentum.
The Context (Slow Stochastic %K - default 40,4,4): This acts as your long-term momentum gauge. It tells you if the underlying trend is healthy or nearing exhaustion. A high reading suggests the market is overextended and vulnerable, while a low reading suggests the opposite.
The Trigger (Fast RSI - default 3): This is your immediate impulse reader. It measures the velocity and intensity of the current price thrust, making it incredibly sensitive to exhaustive moves, spikes, and bounces.
By themselves, they are useful. Together, they are formidable.
The Confluence Engine: Your Visual Edge
The true power of the DFMO lies in its "Confluence Engine." The indicator's background highlights in real-time when both oscillators are in agreement, visually flagging moments of maximum opportunity.
Bearish Confluence Zone (Red): The background turns red only when the Stochastic is overbought AND the RSI is overbought. This is your signal that the broader trend is exhausted and the current buying impulse has reached a climax. It is the ideal confirmation for a short entry following a liquidity sweep above a key high.
Bullish Confluence Zone (Green): The background turns green only when the Stochastic is oversold AND the RSI is oversold. This signals that the downtrend is tired and the immediate selling pressure is exhaustive, providing high-probability confirmation for a long entry at a key support level.
When these zones appear, the indicator is telling you that both the context and the trigger are aligned. This removes ambiguity and allows for decisive, confident execution.
Practical Application: The Liquidity Sweep
Imagine you're stalking a short on a futures contract like MCL or MES. You've marked the high of the day (HOD) as a key resistance level where liquidity is resting. You see a sharp, vertical impulse move that breaks the HOD, clearing out the stops.
Is this a real breakout, or is it a manipulation move—a classic liquidity grab?
You glance down at the DFMO. The moment price swept the high, the background flashed red. That's your objective confirmation. The slow Stoch was already overbought, and the fast RSI spiking confirmed the exhaustive, terminal nature of that price thrust. You now have the confidence to enter your short scalp, knowing you are aligned with the probable direction of the market's next move.
This is how you move from "feeling" the market to systematically executing a high-probability edge. This is how you aspire for greatness.
Add the Dual-Frame Momentum Oscillator to your toolkit and transform your ability to time entries with surgical precision.
BK AK-Warfare Formations👑 Introducing BK AK-Warfare Formations — Form the pride. Take the high ground. Strike with wisdom. 👑
This is my 9th release—built for traders who think like commanders: see the formation, decide the maneuver, deliver the strike.
🎖️ Full Credit
The pattern engine, detection logic, and architecture come from Trendoscope—one of the absolute best coders on TradingView and the original creator of this indicator’s core.
I asked for a few interface upgrades and knew he was driving bigger builds. So I forged the add-ons myself and am releasing them for those who value a cleaner, more tactical read.
My enhancements (on top of Trendoscope):
Label transparency (text + background)
Short-form pattern codes (AC/DC/RC/RWE/...)
Transparency controls for short-form labels
Hover tooltips with full pattern name + bullish/bearish/neutral bias (toggle)
Everything else is Trendoscope. Respect where it’s due.
🧠 What It Does
Auto-detects Channels, Wedges (expanding/contracting), and Triangles (ascending/descending/converging/diverging).
Prints clean battlefield tags (AC, DC, RWE, …) so structure is visible without drowning price.
Hover for the brief: long name + directional bias exactly when you need it.
Multi-zigzag sweep, overlap control, bar-ratio verification, max-pattern caps, dark/light aware palette + custom colors.
🧭 Read the Battlefield
AC — Ascending Channel: trend carry; respect higher-lows and ride the lane.
RWE — Rising Wedge: distribution bias; watch the fracture and the retest.
Converging/Diverging Triangles: compression → expansion; stage entries at the edges.
DC — Descending Channel: late down-leg + momentum shift = tactical long.
Structure is the map. Bias is the compass. Your risk plan is the sword.
🤝 Acknowledgments
Original engine & libraries: Trendoscope (legend).
Enhancement layer (UX): transparency, short codes, tooltip system — BK.
Mentor: A.K. — discipline, patience, and clarity. His standard lives in every decision here.
🫡 Give Forward
Don’t be cheap with your knowledge. If my indicators sharpen your edge:
Teach someone how to read formations with discipline.
Share your process, not just screenshots.
Contribute code, context, or courage to those behind you.
A king’s wisdom multiplies the camp. A lion’s courage protects the pride.
🙏 Final Word
“By wise guidance you will wage your war, and victory lies in many counselors.” — Proverbs 24:6
See the array. Choose the strike. Lead with wisdom.
BK AK-Warfare Formations — where formation meets judgment, and judgment meets execution.
Gd bless. 🙏
EMA Cross By Crypto collective Xეს ინდიკატორი გაძლევთ საშუალებას ნახოთ ყველაზე პოპულარული EMA წყვილები ერთ გრაფიკზე:
EMA 9/21
EMA 20/50
EMA 50/200
EMA 100/200
და საკუთარი, მომხმარებლის მიერ შერჩეული Custom წყვილი.
👉 თითოეულ წყვილს შეგიძლია ჩართო/გამორთო ინდიკატორის პარამეტრებიდან.
👉 შესაძლებელია ფერების შეცვლა, ასევე სურვილის შემთხვევაში EMA-ების higher timeframe-ზე გამოტანა (მაგ. 1D EMA 4H გრაფიკზე).
ეს ინსტრუმენტი განსაკუთრებით გამოსადეგია:
ტრენდების დადგენისთვის
გრძელვადიანი და მოკლევადიანი გადაკვეთების შესადარებლად
საკუთარი სტრატეგიის ტესტირებისთვის
This indicator lets you plot and compare the most commonly used EMA pairs on a single chart:
EMA 9/21
EMA 20/50
EMA 50/200
EMA 100/200
plus a fully customizable user-defined EMA pair.
👉 Each pair can be toggled on/off from the settings.
👉 Colors are customizable, and you can optionally display EMAs from a higher timeframe (e.g., show Daily EMAs on a 4H chart).
This tool is especially useful for:
Trend confirmation
Comparing short-term vs. long-term crosses
Backtesting your own strategies
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.
Bitcoin Cycles IndicatorTrack Bitcoin's cyclical price patterns across multiple timeframes with this cycle analysis tool. The indicator automatically identifies cycle lows and highs, marking them with clear visual labels that show cycle day counts and failed cycle detection.
Key Features:
Multi-Time frame Support - Optimized settings for Daily, Weekly, Monthly, and Custom time frames
Cycle Tracking - Identifies and labels cycle lows (green) and highs (red) with day counts
Failed Cycle Detection - Highlights when cycles break below previous lows
Customizable Settings - Adjust cycle lengths, colors, and display options for each timeframe
Info Box - Real-time cycle information display with current cycle day count
Projection Boxes - Visual cycle length projections for better analysis
Perfect for Bitcoin traders and analysts who want to understand market cycles and timing. Works best on Daily charts for short-term cycles and Weekly/Monthly charts for longer-term analysis.
Reference timesThe theory behind this indicator is that sometimes the graph reaches a certain price at at a certain time according to the price it had at the same time and day in any of the previous weeks. If you could easily see what happened a few weeks ago on this day's weekday and half an hour from now, you might theoretically gain more assurance as to where the graph might go in the next half an hour.
This of course relies of the premise that some traders choose to enter or exit positions according to historical times they are referencing. Hence the name - Reference times.
Example:
it is now 08:00 ET Wednesday. I want to guess what the graph will do in the next half hour. I enter in the indicator the weekday "Wednesday", the time "8:30", and go to 30 minute candles.
I will then see all the candles the graph has been on historical Wednesdays at 8:30. If the candles are below the 08:00 price, we might guess that the graph might want to descent. If they are above the graph, we might guess that the graph might ascend.
How it works:
The user defines a weekday and time he wants to inquire on.
The script searches for past weekdays and similar hours.
It marks these bars at their wicks.
The user can also inquire "opposite hours" - 12 hours ahead or earlier.
The user can also inquire "opposite days" - Monday<->Wednesday, Tuesday<->Thursday.
In addition, the User may inquire the previous day of his selected weekday, which will mark the most recent previous day existent.
Side note: The Time zone offset is set for Jerusalem time. and so it may need future adjustment.
send debugging instances if you find any
Thank you
Assaf Fogelman 2025
Weekly Close Positive After Breaking Prior LowClosing positive after breaking prior low on weekly basis
Reference TimesThe theory behind this indicator is that sometime the graph will change its direction at a point that is the point it reached at that weekday on that time in the previous weeks. If you can easily see what happened a few weeks ago on this day's weekday and a half an hour from now, you might theoretically gain more assurance as to where the graph might go in the next half an hour.
This of course relies of the premise that some traders choose to enter or exit positions according to historical times they are referencing. Hence the name - Reference times.
Example:
it is now 08:00 ET Wednesday. I want to guess what the graph will do in half an hour. I enter in the indicator the weekday "Wednesday", the time "8:30", and go to 30 minute candles.
I will then see all the candles the graph has been on historical Wednesdays at 8:30. If the candles are below the 08:00 price, we might guess that the graph might want to descent. If they are above the graph, we would guess the graph might want to ascend.
How it works:
The user defines a weekday and time he wants to inquire on.
The script searches for past weekdays and similar hours.
It marks these bars at their wicks.
The user can also inquire "opposite hours" - 12 hours ahead or earlier.
The user can also inquire "opposite days" - Monday<->Wednesday, Tuesday<->Thursday.
In addition, the User may inquire the previous day of his selected weekday, which will mark the most recent previous day existent.
Side note: The Time zone offset is set for Jerusalem time. and so it may need future adjustment.
send debugging instances if you find any
Thank you
Assaf Fogelman 2025
Iani SMC Sniper XAU v2.2 (Long+Short + News Countdown, v6)Iani SMC Sniper XAU (v2.2) — smart-money logic for XAUUSD.
This indicator hunts “sniper entries” using a simple SMC sequence:
Sweep → BOS → 50% FVG entry
• After London session builds its range, we wait for a liquidity sweep (price dips below London Low for longs / wicks above London High for shorts).
• A BOS confirms direction (close breaks the last swing).
• First FVG that prints after BOS gives the entry at 50% (mid-gap).
• SL anchored to the protective swing (with a small safety buffer). TP is plotted using your Risk:Reward.
News countdown (non-blocking):
The script does not auto-fetch news; you set daily times (e.g., 14:30, 16:00) and/or specific dates (“YYYY-MM-DD HH:MM”). A countdown label shows “NEWS in Xm”. Signals are not blocked—this is just a safety heads-up for prop-firm rules.
Inputs: pivot length, RR, pip size (XAU default 0.10), session filter (after London), news times (recurring & absolute), show/hide levels & labels.
Plots & labels: London High/Low (daily), Entry/SL/TP lines, BOS/Sweep/BUY/SELL markers, news badge.
Alerts: BOS Bull/Bear, BUY/SELL Entry touch, TP/SL hit, NEWS WARNING.
Notes:
• Designed for XAUUSD intraday; works on other symbols if you adjust pip size.
• Uses symbol timezone; adjust your news times for DST if needed.
• Indicator only—no orders, no backtest. Manage risk and execution in MT5/your platform.
Changelog (v2.2): Pine v6, robust time parsing, one-line logical expressions (fixed EOL errors), mirrored short logic, cleaner London H/L reset, countdown label.
Disclaimer: Educational tool, not financial advice. Past performance ≠ future results.
Tags: SMC, ICT, XAUUSD, Gold, Liquidity Sweep, BOS, FVG, London Session, News, Intraday, Scalping, DayTrading.
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.
Higher High Lower Low Higher High Lower Low 🦉{Phanchai} — TradingView Description
Structure detector with dynamic Support/Resistance, customizable labels, and ready-made alerts (Pine v6).
This script marks market structure turning points — HH (Higher High), HL (Higher Low), LH (Lower High), LL (Lower Low) — and builds segmented Support/Resistance lines from those turns. Labels and colors are fully customizable and the script ships with multiple alert conditions.
What it does
Detects swing pivots using left/right bar windows, then classifies each confirmed swing as HH/HL/LH/LL.
Plots compact labels at the confirmed pivot bars with tooltips (English).
Derives dynamic Support / Resistance : every time structure flips, the previous level is closed and a new segment starts, extending to the right .
Provides alert conditions for any label and for specific first-occurrence shifts (e.g., first HH after a bearish label).
How it works (in short)
A pivot high/low confirms only after Right Bars candles have closed; labels and S/R appear at that confirmation bar.
An internal backbone (zigzag-like) is built from confirmed pivots, with light consistency checks to avoid contradictory sequences.
Structure rules compare the recent five pivots (A…E) to decide HH/HL/LH/LL.
S/R is updated from structure: e.g., in an up leg, new HLs refresh Support; in a down leg, new LHs refresh Resistance.
Alerts included
Any structure label (HH/HL/LH/LL) — Fires on any new label.
First LL after HL/HH — First bearish break after a bullish label.
First HH after LL/LH — First bullish break after a bearish label.
LL or HL formed — Any low-side label.
LH or HH formed — Any high-side label.
HL formed
HH formed
LL formed
LH formed
How to use (quick start)
Add the indicator to your chart.
Choose Left/Right Bars for your timeframe (e.g., 5–10 for intraday; larger for higher timeframes).
Pick your label colors/sizes and S/R style.
Right-click the chart → Add alert… → Condition: this indicator → select the desired alert.
Notes & tips
Because pivots require Right Bars to confirm, labels and S/R appear with a natural delay of that many bars. This avoids repainting.
Raising Left/Right Bars reduces noise and increases the average distance between pivots; lowering them increases sensitivity.
Structure is strict: sometimes you may see two HL (or two LH) in a row if the intermediate opposite swing didn’t qualify as HH/LH (or LL/HL).
S/R segments are drawn with line objects ; they are controlled via Inputs (style/width/color), not the Style tab.
This tool highlights structure; it’s not a standalone entry/exit system. Combine with volume, trend, or risk management rules.
Built with Pine v6. Clean, compact labels; segmented S/R that updates only on confirmed changes; comprehensive alerts ready for automation.
BSL/SSL Sweep + FVG Strategy Jobin (c) The New York ATM Model is a structured intraday strategy designed to capture algorithmic stop-hunts and reversals during the New York session open. It focuses on liquidity sweeps—either Buy-Side or Sell-Side—followed by a confirmation using Fair Value Gaps (FVGs).
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
EITS - Market StructureThis script marks the Swing Lows and Highs of a chosen pair. H,HH,L,LL,HL,LH will be marked on chart. Have fun!!
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.
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
ZigZag+4 EMA89 Trend Candles + BUY/SELL SCALPThis 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