Engineering / 01

Recovering the
unanswered order.

A lost response creates uncertainty that a second order cannot resolve. Follow the original intent through readback, cancellation, settlement and restart.

Python · SQLite · State machines6 min read + demonstrations

A submit request times out. The order may have failed before reaching the exchange, or it may already be trading. To the client, both situations look like silence. Sending the request again could restore progress—or create a second order.

This Python and SQLite project is a command-line cash-spot trading runtime with paper, demo and live paths, a local journal, and explicit recovery operations. Its most revealing design problem is the interval between asking for an action and learning what actually happened.

The case study follows that interval through the decision modules and an experimental ordinary-order subsystem, which is explicitly marked as not production-ready. The question throughout is concrete: what does the system know well enough to do next?

Preserve the identity of the unanswered order

Take an illustrative limit order for ten units. Submission is authorized, but its response is lost. A later readback finds the order, then reports three units filled. The remaining seven are still open. This is a constructed sequence using the actor’s state model, not a recorded trade.

Interactive explanation

One order. A missing response.

An illustrative ten-unit limit order. Step through what the runtime knows before allowing another effect.

Submission stateUNKNOWN

The request may have reached the venue. A lost response cannot establish whether an order exists.

Requested 10Filled ?Open ?
Actor outputREQUEST_EXACT_READBACK

Do not submit a replacement. Resolve the original order identity first.

Illustrative event sequence using the actor’s actual submission, exchange and cancellation labels. These are separate fields; the display selects the relevant one at each step. No exchange is contacted.

Once dispatch is authorized, the actor records the submission as UNKNOWN: an external effect may have occurred. An unresolved outcome requests REQUEST_EXACT_READBACK of that original order. Readback must match the instrument, side, order type, quantity and price. A familiar identifier attached to a different economic instruction is insufficient.

A single “not found” response also leaves the outcome unknown. The absence of one observation cannot establish that the original write never arrived. Progress may therefore remain blocked while the system seeks stronger evidence.

This is the first recovery decision. The uncertainty belongs to an existing intent. Creating a new intent would not resolve it.

Cancellation answers a different question

Now request cancellation of the seven remaining units. The exchange acknowledges the request. Can the system treat the order as closed?

The actor records ACKED_NOT_TERMINAL and requests another exact readback. Acceptance of a cancellation request says nothing final about fills that may already be in flight. Submission, exchange order state, cancellation and settlement therefore occupy separate fields.

Even a terminal order observation starts more work: a complete fill scan and a settlement watch. If cumulative fills change after apparent completion, settlement reopens and the old completion information is cleared. The record must follow the late evidence instead of preserving an obsolete conclusion.

unknown submission  → read back the original order
cancel acknowledged → read back its terminal state
terminal observed   → scan fills and watch settlement
late fills changed  → reopen settlement

Quantities add another source of ambiguity. A market buy may be requested in quote units while execution is reported in base units. Fees and rebates are separate asset movements. An absent rebate observation remains unknown; treating it as zero would turn missing evidence into an accounting assertion.

Make the local history survive the same uncertainty

External readback is only useful if the process still knows which intent and observations to reconcile after a restart. The experimental ledger stores the intent binding, event, derived projection, linked hash and emitted work hints in one transaction.

That grouping prevents a local split: an event committed without its corresponding state or work instructions. Inside a caller-owned transaction the ledger uses a savepoint; otherwise it owns a BEGIN IMMEDIATE transaction.

Retries are bound to content. An event with the same identifier and the same canonical bytes returns the validated snapshot without emitting new commands. The same identifier with changed content raises a conflict. The identifier cannot be reused to smuggle a different observation into an apparently familiar history.

Replay reconstructs projections and checks event content, commands, revisions and linked hashes. It establishes what the local process recorded. It cannot establish whether an unanswered external request executed. The ledger and exact readback solve different halves of recovery; neither makes the other redundant.

Keep a price signal separate from execution authority

So far, the order has been assumed to have valid intent behind it. Moving one step upstream reveals why that assumption needs its own checks.

The decision_kernel turns a confirmed market event and prior state into a deterministic transition without I/O. For its bounded-window breakout policy, the entry threshold comes from the preceding high window before the current bar is appended. Otherwise, the observation being tested would help redefine its own threshold.

Warm-up and whether entry is armed are serialized with the state. A restart therefore has a defined continuation rather than an implicit fresh start. Duplicate events do not advance it. Missing intervals move it into quarantine; receiving the next valid bar does not automatically release that quarantine.

Implementation map

A decision is not permission to trade.

  1. Decision kernelevent + state → decision

    Pure transition over a confirmed event.

  2. Admissionbindings + validity + authority

    Verify the decision is eligible for execution.

  3. Order actorstate → command

    Reconcile submissions, cancels, fills and unknown outcomes.

  4. Durable ledgertransaction + canonical bytes

    Commit state, events and outbound commands atomically.

Map of the inspected decision, admission and experimental order-actor modules. An identical ledger replay emits no new commands; a conflicting payload is rejected. This is not a claim of exactly-once venue execution.

Admission then checks such things as decision validity, policy bindings, release status, entry permission and capital limits. Risk-reducing flat decisions remain available under its rules while risk increases receive the additional checks. This admission module still returns writer_authorization_required: the authenticated runtime uses a separate writer-authorization and lease path.

The separation gives each failure a home. A gap in market data belongs to the decision sequence. A stale permission belongs to admission. An unanswered submission belongs to the order actor. Mixing them would make “retry” a dangerously imprecise instruction.

Input checks and deterministic replay

The kernel checks instrument, timeframe, confirmation, freshness, starting boundary, timestamp revisions and gaps before updating indicators. Canonical decimal representations and content hashes bind events, states and decisions. Bounded windows keep stored state tied to strategy parameters rather than the full market history.

Checked-in tests compare serialized restarts with uninterrupted execution and check that changed future input cannot alter an earlier decision prefix. Ledger and actor tests cover duplicates, conflicting events, concurrent writers, caller rollback, interrupted chain insertion, mutated history, uncertain dispatch and reopened settlement. These tests were inspected, not rerun for this article.

Give recovery its own command

The command interface reflects the distinction between inspecting, recovering and seeking new exposure. status reads persisted state without API credentials. reconcile recovers authenticated state without evaluating a new entry signal. That matters after an outage: learning what happened should not require asking the strategy to make another trade.

Command Operational purpose
run Execute one cycle or a loop in paper, demo or live mode
status Inspect persisted state through a read-only store
export-journal Export journal tables with integrity and configuration hashes
reconcile Recover external and local state without evaluating a new entry
flatten Attempt to exit bot-owned inventory, subject to ownership and reconciliation

Demo and live modes require their own explicit confirmations. A controlled-entry option is limited to demo. These are implemented runtime operations, distinct from the experimental actor and ledger examined above.

flatten can still return a hold reason while transfers, orders or protective exits remain unresolved. Its name expresses an intended outcome; the persisted evidence determines whether that outcome can safely be pursued at that moment.

“Request accepted,” “order terminal” and “settlement complete” permit different next actions. After the original timeout, preserving those distinctions determines whether a recovery command resolves uncertainty or creates another unresolved effect. The article examines that recovery model; it makes no trading-performance or unattended-operation claim.