Backtest Lab Docs
Understanding State Machines
A state machine is a way of describing a process that can be in different situations (or states) and move between them when certain conditions are met.
The central idea is simple:
At any given moment, a state machine is in exactly one active state. It checks the conditions leading out of that state, and when a condition is satisfied, it moves to the connected state.
States and Transitions
A state represents the current stage or situation of a process. For example, a traffic light might be in one of three states: Green, Yellow, or Red.
Each state can have one or more outgoing transitions, which connect it to other states. A transition occurs when its associated condition is satisfied.
The basic operating principles are:
- Only one state is active at a time.
- Only the outgoing conditions of the active state are checked. Conditions belonging to other states are ignored.
- When a condition is satisfied, the machine transitions to the connected state. The new state becomes active, and the process continues from there.
If none of the outgoing conditions are satisfied, the machine remains in its current state.

A Real-World Example: A Traffic Light
Consider a traffic light that cycles through three states: Green, Yellow, and Red.
- Green: The light stays green until its timer expires, then transitions to Yellow.
- Yellow: The light stays yellow until its timer expires, then transitions to Red.
- Red: The light stays red until its timer expires, then transitions back to Green.
At any moment, only one of these states is active. When the light is Green, the machine checks whether it is time to switch to Yellow. It does not check the conditions for switching from Yellow to Red or from Red to Green.
This continues indefinitely, with each transition determining which state becomes active next.
Applying This to Trading Strategies
The same principle can be used to represent trading strategies. Instead of traffic light colors, states can represent stages of a trading setup, and conditions can depend on market prices, indicators, or other information.
This allows a strategy to follow a sequence of decisions rather than evaluating every possible trading condition at once.
Learn how this works in State Machines in Trading Strategies.