Regime state machine
Tracks whether a position is open after a regime-based entry, how strong it is, and when it should close.
RegimeStateMachine tracks one position through three states: waiting, or open after a panic, breakdown or trend entry. It opens a position only when the entry input is true on a bar whose regime is PANIC_CRASH (1), BREAKDOWN (3) or STEADY_DECLINE (2), with conviction 1.0, 0.8 or 0.6. An open position closes when the base exit input is true, when the regime turns to CONSOLIDATION (0) or CHOPPY (4), when the close is 15%, 10% or 8% above the entry close (panic, breakdown or trend), or after 150 bars. The state returns to waiting on the bar it closes, and that bar also raises the exit flag.
How to read it
- State and conviction sit in their own panes below the price; the exit flag is drawn as markers on the candles.
- State 0 is waiting, 1 a panic entry, 2 a breakdown entry and 3 a trend entry; a jump from 0 to 1, 2 or 3 marks an entry bar.
- Conviction holds at 1.0, 0.8 or 0.6 for the whole position and drops to 0 when it closes.
- A marker on a bar means the position closed on that bar, and the state reads 0 there.
What it outputs
- Position state
- 0 waiting, 1 panic entry, 2 breakdown entry, 3 trend entry. Changes only on the entry bar and the exit bar.
- Conviction
- 1.0 for a panic entry, 0.8 for breakdown, 0.6 for trend, 0 when flat. Set by the entry type and held. The code's docstring says it scales position size.
- Exit
- Raised on the bar an open position closes, for any reason: base exit, regime turns to CONSOLIDATION or CHOPPY, profit target, or the 150-bar limit.
When it fires
When an open position closes: the base exit input is true, the regime turns to CONSOLIDATION or CHOPPY, the close rises more than 15%, 10% or 8% above the entry close (panic, breakdown or trend), or 150 bars have passed. A new entry never raises this flag.
Pitfalls
- It never fired on the sample: SPY one-minute bars, 1 Sep to 1 Oct 2026, never left waiting. The record does not show what fed the entry input, so a dead input may explain it.
- Only a move to CONSOLIDATION or CHOPPY closes a position on regime. Moves between PANIC_CRASH, BREAKDOWN and STEADY_DECLINE do not close it.
- The 15%, 10% and 8% profit targets and the 150-bar limit are hard-coded and suit a fast-moving symbol, so SPY results are not a test of its intended use.