Architecture
State machines for trading bots
Explicit states make order handling, restart recovery, and protection logic easier to reason about than scattered flags.
Name the states
A bot might be idle, evaluating, submitting, waiting for a fill, managing a position, closing, halted, or recovering after restart. Naming those states exposes transitions that are otherwise hidden in boolean flags.
Each state should have a clear owner, allowed actions, and exit conditions.
Define transitions and timeouts
An order request can be accepted, rejected, delayed, or partially filled. Add timeouts and recovery paths for each response. A state machine that waits forever is an operational failure even if the entry logic is correct.
- Reject duplicate entry while an order is pending.
- Reconcile platform positions after a terminal restart.
- Move to a safe state after an unknown broker response.
- Make protection halts stronger than signal transitions.
Test the transitions as a story
Write scenarios such as signal-to-fill, rejected entry, partial close, connection loss, and restart with an open position. The expected state sequence becomes both a design document and a test plan.
State clarity reduces the risk that a rare operational event creates an unplanned position or disables a protection rule.
Discuss this article
Ask a setup question, share a backtest, or compare notes with other algorithmic traders. Use a display name; your email remains private.
Create an account or sign in above to join the conversation.
Loading discussion…