Skip to content

Broker (src/fyers_store/broker.py)

The Broker translates between Backtrader order semantics and FYERS order/trade updates. It also owns crash-safe runtime state and enforces fail-fast reconciliation rules.

Order Lifecycle Flow

sequenceDiagram
    participant Strategy
    participant Broker as FyersBroker
    participant Store as FyersStore
    participant REST as REST Adapter
    participant OrderWS as Order WS Adapter

    Strategy->>Broker: buy()/sell()
    Broker->>Store: place_order(intent)
    Store->>REST: place_order(payload)
    REST-->>Store: response (id or request_id)
    Store-->>Broker: response

    Note over Broker,OrderWS: Order and trade notifications arrive via WS.
    OrderWS-->>Store: queue message
    Store-->>Broker: routed message batch
    Broker-->>Strategy: notify_order(bt.Order updates)

Reconciliation and Fail-Fast

Reconciliation runs at startup, on reconnect, and optionally on a timer. If REST snapshots cannot be trusted, the broker raises a hard exception to prevent trading on stale state.

flowchart TD
    START["start() / reconnect event"] --> RECONCILE["sync_order_state() via Store"]
    RECONCILE -->|success| CONTINUE["consume WS messages and continue trading"]
    RECONCILE -->|failure| HALT["raise ReconcileFailureError<br/>(exit for scheduler restart)"]

Order Safety Failures

flowchart TD
    SUBMIT["submit order intent"] --> GUARD{"environment allows live?"}
    GUARD -->|no| BLOCK["TradingSafetyError<br/>block order"]
    GUARD -->|yes| PLACE["place_order()"]
    PLACE -->|timeout| UNKNOWN["OrderUnknownStateError<br/>manual reconcile"]