Preventing Duplicate Orders in an Algo Bot

A software design checklist for handling ambiguous broker responses, retries, process restarts and order reconciliation without blindly repeating orders.

By Shiv Shankar Kumar · Algorithmic Trading Developer

Start with the ambiguous timeout

Suppose a bot sends an order and the HTTP request times out. The timeout tells the bot that it did not receive a usable response. It does not establish whether the broker accepted the order. Immediately repeating the same request can create a second position.

Model this outcome as unknown rather than rejected. Pause the affected order workflow and reconcile it with the broker before deciding whether another submission is appropriate.

Persist an intent before submitting

Give each intended action a stable identifier and record its strategy, instrument, side, quantity and signal time before contacting the broker. Repeated processing of the same signal should locate that intent rather than create a new one.

Where the broker supports a documented idempotency mechanism, use it according to its contract. A locally generated identifier alone does not force the broker to deduplicate requests. A database uniqueness constraint can prevent duplicate local intents, but cannot resolve an uncertain remote order by itself.

Reconcile order state and positions

Record the broker order identifier as soon as it is available. Handle partial fills, cancellation requests and late status updates explicitly. A request to cancel is not the same as a confirmed cancellation; fills may occur while the cancellation is pending.

After a disconnect or restart, fetch the available broker order and position state and compare it with the local record. If the available evidence cannot identify the pending action reliably, require operator review instead of guessing.

Test failures at the boundaries

Exercise a timeout after submission, a crash before the response is saved, duplicate status messages, a partial fill followed by cancellation, and a reconnect during an open order. For each scenario, check the final orders, fills and exposure, not only whether the process stayed running.

Log state transitions with correlation identifiers, but redact credentials. Define an alert and a pause condition for unresolved discrepancies. These controls reduce implementation errors; they do not guarantee execution quality or trading returns.

Implementation support

Discuss your system

Trading involves risk, including loss of capital. Backtest results do not guarantee future trading performance. Development and educational content are not investment advice. Read the trading-risk disclaimer.