Introduction
Trading strategies are built on rules and conditions, but as strategies grow more complex, hardcoding logic becomes messy, error-prone, and difficult to debug. Enter the Finite State Machine (FSM) library for TradingView—a revolutionary approach to scripting that makes your trading rules explicit, flexible, and easier to manage.
This is the first FSM library on TradingView, designed to bring structure, clarity, and validation to Pine Script® development. Whether you’re building a simple logic flow like a traffic light or a multi-condition trading strategy with concurrent rules, the FSM framework gives you the tools to handle complexity with confidence.
In this article, we’ll break down how FSMs work, why they’re game-changing for Pine Script coders, and how to use both the matrix-based and map-based implementations in your scripts.
What is a Finite State Machine (FSM)?
A Finite State Machine is a computational model that manages states and transitions based on events. Instead of embedding all your rules directly in conditional logic (if/else chaos), FSMs use a clear set of transition rules that define how states change in response to events.
Why FSMs are useful in trading scripts:
- Explicit logic: All rules are visible side by side.
- Easier debugging: Validation tables show errors and warnings directly on the chart.
- Flexibility: Handle both simple sequential events and complex concurrent conditions.
- Robustness: Built-in type safety with enums and string compatibility.
- Scalability: Add new rules without breaking old ones.
Think of FSMs as your script’s traffic controller, ensuring every condition flows logically without conflicts.
Key Benefits of the TradingView FSM Library
This FSM library introduces several unique advantages for traders and developers:
- Explicit Logic: Rules are transparent, structured, and easy to read.
- Validation System: Detects errors like duplicate states, unreachable states, conflicting transitions, and redundant wildcards.
- Dual Approach:
- Matrix-based FSM: Simple, sequential transitions (perfect for traffic lights).
- Map-based FSM: Concurrent conditions with priority handling (ideal for trading strategies).
- Wildcard Matching: Use
""or"ANY"to create flexible rules. - Priority Control: Explicit rule precedence ensures the correct condition is applied first.
- Practical Examples: Includes traffic lights, trading strategies, and error-handling demonstrations.
Matrix-Based FSM: Simple & Sequential
The matrix FSM is a straightforward way to define transitions using a state > event > next state table.
- Each row = one rule.
- The first matching row wins (top-down priority).
- Supports wildcards for flexible pattern matching.
Example: Traffic Lights
A classic traffic light system:
- Red → Red+Amber → Green → Amber → Red
- Events like “timer” or “break” trigger transitions.
- Wildcards can handle exceptions (like repairs or overrides).
This method is perfect for single-event transitions, where only one thing happens at a time.
Map-Based FSM: Concurrent & Complex
The map FSM uses a map of states, where each state holds multiple event rules. This allows concurrent conditions to be managed with explicit priority.
- Each state = key.
- Each key = array of event rules.
- Priority = order rules are added.
Example: Trading Strategy
A realistic strategy might include conditions such as:
- EMA crossovers
- RSI levels
- Gap detection
- Fractal patterns
Here’s how it works:
- Map FSM processes conditions and outputs events.
- Matrix FSM manages higher-level state transitions (idle → setup → entry → exit).
- Together, they handle multi-layered logic that would be painful to hardcode.
This makes the map FSM perfect for trading strategies with multiple simultaneous signals.
Technical Implementation & Wildcards
Both FSMs support wildcards for maximum flexibility.
Matching Priority Order:
- Exact state + exact event
- Exact state + event wildcard
- State wildcard + exact event
- Full wildcard (both empty)
Why this matters:
You can design layered fallback rules—for example, a general rule for “ANY” event, overridden by specific conditions when necessary.
Validation & Error Handling
One of the library’s strongest features is its built-in validation system.
Errors Detected:
- Empty next states
- Invalid states not listed in array
- Duplicate/conflicting rules
- Unreachable states
Warnings Issued:
- Redundant wildcards
- Empty states/events (unintended wildcards)
- Duplicate conditions in the same state
Validation tables are printed directly on the TradingView chart, giving instant feedback.
Practical Examples
1. Traffic Light FSM
- Uses matrix-based FSM.
- Demonstrates sequential rules and wildcard flexibility.
- Visualizes explicit priority control.
2. Trading Strategy FSM
- Combines map FSM (for concurrent signals) + matrix FSM (for state management).
- Implements real-world features like entries, exits, stop losses, and re-entries.
3. Error Demonstrations
- Includes intentionally broken FSMs to showcase validation catching common mistakes.
How to Use the FSM Library in Pine Script®
Importing the Library
import SimpleCryptoLife/FiniteStateMachine/1
Example Usage – Matrix FSM
// Load rules from text
matrix_rules = matrix.new<string>()
matrix_rules.m_loadMatrixRulesFromText("""
Idle | Signal | Setup
Setup | Confirm | Entry
Entry | Exit | Idle
""")
Example Usage – Map FSM
map_rules = map.new<string, o_eventRuleWrapper>()
map_rules.m_addEventRulesToMapFromText("""
Idle | EMAcross > Setup | RSIoversold > Setup
Setup | GapDetected > Entry
Entry | StopLoss > Exit | TakeProfit > Exit
""")
With these functions, you can test, validate, and visualize your FSM directly in TradingView.
Why This Library Matters for Traders
Traditional Pine Script logic becomes tangled as conditions grow. FSMs bring:
- Structure: Clear state/event tables.
- Flexibility: Easy to add/modify rules.
- Clarity: Debugging is simpler with validation.
- Scalability: Works for small demos (traffic lights) and large systems (multi-indicator trading strategies).
For traders serious about building robust, bug-resistant strategies, this FSM library is a must-have.
Conclusion
The Finite State Machine library for TradingView represents a major leap forward for Pine Script developers. By structuring logic into states, events, and explicit rules, it eliminates ambiguity, reduces bugs, and makes complex strategies manageable.
- Use the matrix FSM for simple, sequential flows.
- Use the map FSM for concurrent, condition-heavy logic.
- Combine both for hybrid strategies that demand precision and flexibility.
Ultimately, the FSM framework saves time, prevents costly errors, and makes your TradingView scripts more professional. Whether you’re coding traffic lights or trading strategies, FSMs provide the clarity and control you need.
FAQs
Q1. What is the main advantage of FSMs in trading strategies?
FSMs make logic explicit, preventing hidden bugs and unintended interactions that plague complex scripts.
Q2. Can beginners use this FSM library, or is it for advanced developers only?
Beginners can start with the matrix FSM (traffic light example), while advanced users benefit from the map FSM for multi-condition strategies.
Q3. How does validation help traders?
Validation instantly flags issues like duplicate rules, unreachable states, or redundant wildcards—saving hours of debugging.
Q4. Do FSMs slow down Pine Script performance?
No. Most validation checks run only once (barstate.isfirst), so runtime performance remains efficient.
Q5. Can I combine both matrix and map FSMs?
Yes. The library is designed to let you mix both approaches for maximum flexibility in strategy design.