[Trading Infrastructure · State Machines · Backend Automation]
Risk Management & Trade Lifecycle Automation
A controlled lifecycle for trading operations: every signal is validated against risk rules, tracked through explicit states and closed with a recorded result.
01Project overview
Generating a signal is only half of the problem. The other half is what happens afterwards: validating parameters, applying account-level risk settings, tracking the position and deciding when and how it is finished.
This subsystem models that lifecycle explicitly. A trade moves through defined states, and each transition is guarded by validation and recorded in the database.
02Engineering challenge
Trading automation fails in quiet ways: a missed update, a partial fill that is never reconciled, or an exchange error that leaves the local state out of sync. The lifecycle has to make those cases visible and recoverable.
- A
Reject dangerous parameter combinations before any operation is attempted.
- B
Support different risk modes and leverage settings per account.
- C
Keep local state consistent when an external call fails or times out.
- D
Produce a final, auditable result for every operation.
03Solution architecture
Hover or tap each stage.
Incoming Signal
A structured signal arrives from the signal engine or another producer.
04Main components
- 01
Parameter validator
Checks entry, stop loss and take profit relationships, numeric bounds and required fields.
- 02
Risk engine
Applies account settings — risk mode, leverage, exposure limits — and blocks operations that violate them.
- 03
State machine
Created → Validated → Active → Partially Closed → Closed, with explicit Rejected and Error states.
- 04
Exchange integration
Wraps API calls with error classification so a failure becomes a known state, not a crash.
- 05
Event log
Every transition is stored with a timestamp and reason, forming the trade history.
- 06
Result checker
Evaluates closed operations and feeds automated reports.
05Technology stack
Core
- Python
- asyncio
- State machine design
Integration
- Binance Futures API ecosystem
- Error classification
Data
- SQL
- Event history
- Reports
06Interactive demonstration
Trade lifecycle state machine
IllustrativeIllustrative demo. Fire events and see which transitions the lifecycle allows. Simplified model, no exchange connection.
state = created · fire an event
07Engineering decisions
- 01
Explicit states over flags
A single state field with allowed transitions is easier to validate and audit than a set of booleans that can contradict each other.
- 02
Errors are states
API failures move an operation into an Error state with a reason, so it can be inspected and resolved instead of silently disappearing.
- 03
Risk rules in code
Limits are enforced by the system before execution. A configuration mistake cannot bypass them.
- 04
History is append-only
Transitions are recorded as events, which makes reconstructing what happened straightforward.
08Reliability & testing
- Transition guards reject impossible state changes.
- Classification of exchange errors into retryable and terminal.
- Reconciliation of local state with external state after failures.
- Regression tests around risk validation rules.
09Code example
from enum import Enum
class TradeState(str, Enum):
CREATED = "created"
VALIDATED = "validated"
ACTIVE = "active"
PARTIALLY_CLOSED = "partially_closed"
CLOSED = "closed"
REJECTED = "rejected"
ERROR = "error"
ALLOWED: dict[TradeState, set[TradeState]] = {
TradeState.CREATED: {TradeState.VALIDATED, TradeState.REJECTED},
TradeState.VALIDATED: {TradeState.ACTIVE, TradeState.REJECTED, TradeState.ERROR},
TradeState.ACTIVE: {TradeState.PARTIALLY_CLOSED, TradeState.CLOSED, TradeState.ERROR},
TradeState.PARTIALLY_CLOSED: {TradeState.CLOSED, TradeState.ERROR},
TradeState.ERROR: {TradeState.ACTIVE, TradeState.CLOSED},
}
class InvalidTransition(Exception):
pass
def transition(current: TradeState, target: TradeState) -> TradeState:
if target not in ALLOWED.get(current, set()):
raise InvalidTransition(f"{current.value} -> {target.value} is not allowed")
return targetIllustrative Illustrative Engineering Example — simplified transition table.
Production source is private. Examples here show the engineering approach, not proprietary logic. More in the Engineering Lab.
10Possible extensions
- Per-account risk dashboards built on the stored event history.
- Simulation mode that runs the full lifecycle against recorded data.
- Alerting on operations that stay in Error longer than a threshold.