Trading bot duplicate orders after a timeout: did it fill?

A timeout on an order does not say whether the order exists, and a bot that simply retries can end up holding twice the position it wanted.

Contents

Your bot buys 1 BTC, the exchange’s answer never arrives, the bot sends the order again, and now it holds 2 BTC instead of 1.

  1. The bot sends a market order to buy 1 BTC. The order reaches the exchange.
  2. The exchange fills it. The bot holds 1 BTC and does not know it yet.
  3. The answer is lost. The bot sees a timeout and decides the order failed.
  4. The bot sends it again. The exchange takes the retry as a new order.
  5. The retry fills too. The bot holds 2 BTC.
  • An error is not an outcome. Only an answer the venue documents as “not accepted” ends an order; a timeout after the send, an “execution status unknown” error, an HTTP server error or an empty body leaves it unknown.
  • A client order ID deduplicates only within its scope. On Binance Spot that is open orders: once the original has filled, the same ID is accepted again.
  • Unknown means reserved. The order counts as filled against limits it adds to, and unfilled against limits it reduces, until the order stream or a lookup by client order ID finds it, or a person confirms it does not exist.
  • “Order does not exist” is not proof. Binance documents no time after which a missing order can no longer appear, so a miss past the escalation window goes to a person, and the hold stays.

Why doesn’t a timeout mean the order failed?

The venue can accept and fill the order while its answer is lost on the way back.

Binance’s spot API waits 10 seconds for the matching engine, then answers that both the send status and the execution status are unknown, which “does not always mean that the request failed in the Matching Engine” (REST API). On the retry, a new client order ID is a new order, and the same ID is accepted too: the first order has filled and is no longer open.

Terms this article uses

The venue is the exchange or broker that takes the order. An order has an unknown outcome when the bot has sent it and holds no venue message that says whether it exists: no acknowledgment, no rejection, no stream event. A confirmed rejection is a response the venue documents as meaning the order was not accepted, so no part of it can execute. A client order ID is the identifier the bot assigns before sending; each venue names the field its own way, and the venue notes give the names. An idempotency key is a value the venue uses to recognize a repeated request for the same order; a client order ID can serve as one. Its scope is the set of orders among which the venue enforces that uniqueness, and the period it remembers an ID; both differ by venue and by interface. The order stream is the feed of order events the venue pushes to the account.

Retry logic that is right for a market-data request is wrong here. Repeating a read changes nothing; every new-order request that arrives can create an order.

Which answers end the order, and which leave it unknown?

An answer ends the order only when the venue documents that the order was not accepted; every other error leaves it unknown, whatever the HTTP status says.

  • Never sent. The request provably never left the bot: send it again with the same ID.
  • Rejected. The venue documents that it did not accept the order: release what was reserved.
  • Unknown. A timeout that may follow the send, an HTTP server error, an empty or unfamiliar answer: find the order, never resend it.
  • The duplicate-ID trap. The venue says the ID is already in use: it rejected this request, not the order, so find the original by its ID.

The duplicate-ID rejection is the trap. Scenario F.1.a of the FIX order-state document rejects a second order for 15,000 under an ID already taken and, in the same message, reports the first order as partially filled. Booking that rejection as a failed order loses a live one. A new attempt after a real rejection is a new order with a new ID.

What counts as never sent, and what as unknown
  • Never sent: a DNS failure, a refused connection, a connect timeout. The request never left the client, so a resend with the same ID is safe.
  • Unknown: a read timeout, a connection reset after the send, an empty body. No venue message arrived at all.

Source: urllib3 2.5.0 Retry, which separates connect errors, raised before the request is sent, from read errors, raised after it. The venue’s own codes for rejected, unknown and duplicate-ID answers are in the venue notes.

What CCXT raises, and why its classes do not settle the outcome

A library sorts these responses into its own classes, and the classes do not follow the venue’s. In CCXT 4.5.78 (released 2026-09-07), the Binance mapping gives:

  • -1007 raises RequestTimeout, and so does CCXT’s own request timeout (AbortError or TimeoutError).
  • -1006 raises OperationFailed.
  • An HTTP 500, 502 or 503 without a Binance code raises ExchangeNotAvailable; a 504 without one, RequestTimeout.
  • RequestTimeout and ExchangeNotAvailable are NetworkError subclasses, the class a generic retry handler catches, and each case above is an unknown outcome unless the request provably never left the client. But OperationFailed is the parent of NetworkError.
  • A body whose Binance code and message CCXT both do not map raises plain ExchangeError, whatever the HTTP status.
  • -1021 (timestamp outside recvWindow) raises InvalidNonce, a NetworkError.
  • A refused connection, a reset and a connect timeout (UND_ERR_CONNECT_TIMEOUT) all raise NetworkError, so telling a failure before the send from one after it takes the HTTP client’s own exception.
  • -2010 becomes InvalidOrder unless its message has its own mapping (insufficient balance raises InsufficientFunds). “Duplicate order sent.” has none, so it arrives as a plain InvalidOrder, the same class as an unmapped matching-engine rejection: read the message.

So the class does not settle the outcome: classify by the venue’s code and message and the transport error, and treat anything unrecognized as unknown. Sources: binance.ts and Exchange.ts at that tag.

Does reusing the client order ID make a retry safe?

Only on a venue that recognizes the ID for as long as you might retry. Where the scope is open orders, a same-ID retry is safe while the original works and doubles the position once it has filled.

Venue Used ID refused after a fill Duplicate ID returns the order Lookup by client ID
Binance Spot No1 No1 Yes2
Coinbase Advanced Trade Not documented3 Yes3 Partial4
Kraken Spot (REST) Not documented5 Not documented5 Yes6
Alpaca Not documented7 No8 Yes9
FIX Not documented10 Partial10 Yes11
Notes and sources
  1. Rejected as a duplicate while the original is open; accepted again once it has filled. Binance trading endpoints.
  2. A lookup by symbol and client order ID.
  3. “The order corresponding with that ID will be returned instead”; no retention period stated. Coinbase Create Order and its API spec.
  4. Its order list has no client-ID filter: match the client order ID in the orders it returns. Coinbase List Orders.
  5. The ID “uniquely identifies an open order for each client”; Kraken Add Order does not document the response to a used one.
  6. Its open-order and closed-order queries accept the client order ID (Kraken changelog).
  7. “A unique identifier for the order”, up to 128 characters; no retention period stated. Alpaca Create an order.
  8. A non-unique ID is rejected, not answered with the order; the error “likely means” the ID “was used for another active order” (Alpaca error guide).
  9. A lookup by client order ID (Alpaca Get order by client order ID).
  10. Only with the possible-resend flag set to yes: an ID the venue has seen gets a report of the order’s current state, an unseen one becomes a new order. Without it, a duplicate is rejected with the original’s status. How long the venue remembers an ID is not specified. Scenario F.1.b of the FIX order-state document.
  11. An order status request by client order ID (FIX).

Where the venue still recognizes the ID, a same-ID resend returns the existing order, but it is a write: for an ID the venue does not recognize, it creates the order. Derive the ID from the strategy’s intent and journal it before the send.

Make the ID survive restarts

Derive the ID from the strategy’s intent and write it to a journal before the send, so a restarted bot resolves the same ID instead of inventing a new one. Never reuse an ID for a different intent: on an open-scope venue an old, filled ID is accepted again, and Binance’s documentation gives no rule for which order a lookup returns when several share an ID. Record the venue’s own order ID from the acknowledgment or the first stream event, and look up by it once you have it. The cost is a durable write on the path of every order.

What should the bot do while the outcome is unknown?

Count the order at its full size, send nothing new for the same intent, and release the reservation only when the order stream or a lookup shows the order final, or a person confirms it does not exist.

The cost is capital held until a person answers, which for an unattended bot can be hours. Releasing automatically after a fixed window instead is a bet that the window outlasts the venue’s delay. Absent is the only state that frees the strategy to try again, with a new order and a new ID.

The state machine, rule by rule
  • Pending - sent, no answer yet. The full quantity is reserved.
  • An acknowledgment moves it to the venue’s working state (new, partially filled), or straight to Final when it already reports a final state, as a market order filled at once does. Fills consume the reservation; a cancel releases the remainder.
  • A confirmed rejection moves it to Rejected and releases the reservation.
  • A duplicate-ID rejection moves it to Unknown: the original holds the ID.
  • Anything else moves it to Unknown. Nothing is released.
  • From Unknown, a stream event or a lookup that finds the order moves it to that order’s state. A lookup that keeps finding nothing past the escalation window raises the order to a person, and the reservation stays.
  • Only that person’s confirmation moves it to Absent and releases the reservation. The ID stays on watch: an order that turns up under it later is applied and flagged.
  • A strategy that cannot act on the signal that produced the order is part of the cost.

The Python version is in the runnable code at the end.

With the OpenPit SDK 0.8.1

The Spot Funds policy holds an order’s amount when it passes the pre-trade check, the reservation is committed “only after the venue accepted the order”, and execution reports carrying the persisted lock consume fills and release, on the final one, the remainder the caller supplies (execution.rs). An unknown outcome is not an acceptance: keep the reservation alive without finalizing it, which keeps the hold, commit once the stream or a lookup shows the order, and roll back once a person confirms it absent.

What can one lost answer hide?

The same timeout can sit on three different states at the venue; the bot tells them apart only from what it learns next.

  • The request never arrived. The stream says nothing, and a lookup answers that the order does not exist. A same-ID retry on Binance is accepted: one order. The full quantity stays reserved until a person confirms the order does not exist.
  • The order is working. The stream and a lookup both show it as new. A same-ID retry on Binance is rejected: the ID is in use. Reported fills consume the hold; the unfilled quantity stays reserved until the order is final.
  • It filled before the first lookup. The stream reports the trade, and a lookup shows the order filled. A same-ID retry on Binance is accepted as a second order that doubles the position once it fills. The fill consumes the reservation.

Only the first case ever needs a resend, and it is the one the bot cannot confirm on its own: presence shows up in the first stream event or lookup, absence never does.

How does the bot resolve an unknown order after a reconnect or a restart?

Stream first, then a lookup by client order ID, then a person for what neither finds. Binance gives the first two in that order: if the status “has not appeared in User Data Stream, please perform an API query for its status” (REST API).

  1. Subscribe to the order stream and buffer it before any query.
  2. Look up every pending and unknown ID from the journal.
  3. Merge lookups and stream by cumulative filled quantity and venue time.
  4. Escalate an ID still missing past the escalation window; keep its hold.
  5. Send the first new order only when every entry is resolved or escalated, sized against the holds escalated entries keep.
Steps 1 to 3 in detail
  1. Subscribe and buffer before any query, so an event that arrives during the lookups is not lost.
  2. Use the venue’s lookup by client order ID; each venue’s is in the venue notes. Where the venue cannot filter by client ID, match the ID in the orders its list returns. Do not resend the order to find out: it is a write, and it creates the order if it is absent.
  3. Merge by cumulative filled quantity and the venue’s transaction time, so an older buffered “new” never overwrites a newer partially filled lookup. Fills that fell into the gap before the subscription come from the venue’s trade history.
Orders the journal never saw

A restart adds one more case: an order that reached the venue but not the journal, because the journal write was not durable before the send or the order came from outside the bot. Recovering those, and the fills missed while the bot was down, is covered in “Why your trading bot’s position drifts from the broker’s”.

Four edge cases decide whether the hold is right:

“Order does not exist” can come before the order

Binance’s timeout error means the API stopped waiting, not that the matching engine stopped processing, so a lookup sent right after it can run before the order exists. Binance’s receive window bounds one part: the API forwards a signed request to the matching engine only while the server time minus the request’s timestamp is within the window (5,000 ms by default, 60,000 ms at most), so a request not forwarded by then never will be. Nothing documented bounds the rest. A request already forwarded may still execute, and the order lookup reads from “Memory => Database”; Binance calls the API “asynchronous” and some delay “normal and expected”. A miss before the timestamp plus the receive window is worthless; a miss after it is a reason to escalate, not proof.

The escalation window is the time after which a lookup miss is raised to a person; start it there, plus a margin you have measured. The cost runs both ways: a short window pages a person for orders that were merely slow, a long one leaves the bot unaware of an order nobody can find.

A modify during a disconnect can leave two live orders

A modify built from a cancel and a new order goes wrong when the cancel times out and the bot sends the replacement anyway: the original may still be working. Binance’s cancel-replace, in the mode that allows the cancel to fail, attempts the new order even when the cancel fails, and one error status covers both splits: the cancel failed and the new order was placed, or the cancel succeeded and the new order failed. Read the two results separately. Keep the original’s open quantity reserved until its cancel resolves, and reserve the replacement on top of it; the cost is a replacement that waits, or double the reserved capacity while both may be live.

A tight lookup loop can get the bot’s IP banned

An order lookup costs 4 request weight on Binance; breaking a limit returns a rate-limit error, and continuing after it brings an automatic IP ban. A bot that polls every unknown order in a tight loop during an outage can lock itself out, cancels included. Prefer the stream, back off between lookups, and give lookups for unknown orders their own share of the rate budget.

Without a journal, a restart has nothing to look up

The journal is what makes unknown orders resolvable after a restart: without the client ID written before the send, the bot has nothing to look up and can only search the venue’s open and recent orders for something that looks like its intent.

How do you test it before it costs money?

Let the venue execute the order, then drop the response, and assert that the position does not double.

An in-memory venue with two ID contracts and a lookup that can lag runs the scenarios without an account; the code is at the end. Its first assertion is the double this article opened with: keep it as proof the test can see one. Its 16-second-lag scenario shows why a lookup miss does not end the hold: a release at 15 seconds frees capacity the venue already filled.

Testing against the venue itself

An in-memory venue tests your state machine, not the venue’s contract. To test against the venue, use its test environment where it has one. For a deterministic test, drop the reply in your own transport only after the stream has shown the order. A short HTTP read timeout on the order call also produces a timeout, but not proof that the venue executed the order: confirm that through the stream or a lookup. The cost of the real test is that a test environment’s latency and deduplication can differ from production.

What should the bot get right before it goes live?

  • Every order-entry response is classified: acknowledgment, fill, confirmed rejection, or unknown; of the error responses, only one that establishes a rejection releases a reservation without a fill.
  • A duplicate-ID rejection means “the original may exist: resolve it”.
  • You know your venue’s ID scope and what it does with a used ID after a fill.
  • The client order ID is journaled before the send, never reused for another intent; the venue’s own order ID is recorded once known.
  • No order-entry call that may have reached the venue is retried automatically; an unknown order is resolved, not resent.
  • Unknown orders count as filled against limits they add to, unfilled against limits they reduce.
  • A lookup miss escalates; only a person marks an order absent, and the ID stays on watch.
  • After a start or reconnect, no new order until every journal entry is resolved or escalated.
  • Lookups back off and have their own share of the rate limit.
  • A test drops the response after a fill and asserts the position does not double.

What does each venue document?

The codes, fields and lookups behind everything above, venue by venue.

Binance Spot
  • Client order ID. newClientOrderId. Its scope is open orders: the REST parameter description says an order with the same ID “can be accepted only when the previous one is filled, otherwise the order will be rejected.” That text names only a fill. The WebSocket API adds that a cancel’s own ID “will replace clientOrderId of the canceled order, freeing it up for new orders”; neither says what happens to the ID of an expired order. Record the venue’s orderId from the acknowledgment or the first stream event.
  • Rejected. -1013 INVALID_MESSAGE (filter failures): “The request is rejected by the API”, it “didn’t reach the Matching Engine”. -2010 NEW_ORDER_REJECTED, for example insufficient balance: an error returned by the matching engine. Release the reservation.
  • ID in use. -2010 with “Duplicate order sent.”: the client order ID “is already in use”. This request is rejected; the original holds the ID.
  • Unknown. -1006 UNEXPECTED_RESP: “Execution status unknown”. -1007 TIMEOUT, the answer after the 10-second wait: “Send status unknown; execution status unknown”. HTTP 5XX: do “NOT treat this as a failure operation”; the status “could have been a success”.
  • Lookup. GET /api/v3/order with symbol and origClientOrderId, 4 request weight; a miss answers -2013 “Order does not exist.” Breaking a limit returns HTTP 429, and continuing after 429 returns 418, an automatic IP ban.
  • Receive window. The API forwards a signed request only while the server time minus its timestamp is within recvWindow: 5,000 ms by default, 60,000 ms at most.
  • Order stream. The user data stream executionReport carries the client order ID in c (in C on a cancel event; match by symbol s and orderId i once known), the execution type in x, the order status in X, the cumulative filled quantity in z and the transaction time in T. A new-order report shows x and X = NEW; a trade report shows x = TRADE, with X = FILLED once the order is fully filled.
  • Cancel-replace. With cancelReplaceMode=ALLOW_FAILURE the new order is attempted even when the cancel fails, and HTTP 409 covers both splits: read cancelResult and newOrderResult separately.

Sources: Binance REST API and error codes.

Coinbase Advanced Trade

The client order ID is client_order_id. Create Order and its API spec say a duplicate ID returns the existing order. It does not say how long Coinbase recognizes an ID, or whether it still does after the order has filled. While it does, a same-ID resend is safe as a write: if the first request never arrived, the resend creates the order; if it did, the resend returns it. The cost is that the resend is a write, not a question. If the first request never arrived and the price has moved, it places an order your strategy may no longer want.

List Orders filters by order_ids, not client IDs: match client_order_id in the orders it returns. Do not resend Create Order to find out: it is a write, and it creates the order if it is absent.

Kraken Spot REST

The client order ID is cl_ord_id; it “uniquely identifies an open order for each client”, the same scope as Binance’s, and Add Order does not document the response to a used one. userref, the older field, is not unique at all; Kraken does not enforce it. OpenOrders and ClosedOrders accept cl_ord_id since 2024-09-05 (Kraken changelog).

Alpaca
  • Client order ID. client_order_id: “A unique identifier for the order”, up to 128 characters; no retention period stated (Create an order).
  • Rejected. 403 (buying power or shares), or 422 for unrecognized input: the documented error responses of POST /v2/orders.
  • ID in use. 422 “client_order_id must be unique” (code 40010001, shared by many validation errors): it “likely means” the ID “was used for another active order”. Resolve the original by its ID.
  • Unknown. A timeout: “The order may have been sent to the market for execution”. Resolve; do not resend.
  • Lookup. GET /v2/orders:by_client_order_id (Get order by client order ID).
  • Stop and wait, not retry. The orders FAQ says not to resend or mark the order canceled until Alpaca confirms it, and the error guide says to check the dashboard first. A bot can still look the order up by its client ID, but the policy it implements is “stop and wait”, not “retry”.
FIX

The client order ID is ClOrdID. Scenario F.1.a of the FIX order-state document rejects a second order under a taken ClOrdID and, in the same message, reports the first order as partially filled. Scenario F.1.b makes PossResend=Y the resend that answers: for a ClOrdID the venue has seen, it returns an order-status report (ExecType=Order Status) with the order’s current state; a second order under the same ClOrdID without the flag is rejected while the original stays live. For a ClOrdID the venue has not seen, F.1.b confirms the same resend as a new order, so it goes through every check a new order goes through. The guarantee holds only for as long as the venue remembers the ClOrdID, which the scenario does not specify. The lookup is OrderStatusRequest (35=H) with ClOrdID (FIX).

Where is the runnable code?

The state machine and the fault-injection test, one runnable file

The in-memory venue has two ID contracts: an ID unique among open orders, and a duplicate ID that returns the existing order, here for the order’s whole life, which Coinbase does not document. Its lookup can lag the matching engine.

# Standard library only. Tested with CPython 3.13 and 3.14.
class Timeout(Exception):
    """No answer: the request may or may not have reached the venue."""


class Rejected(Exception):
    """A documented rejection: the venue did not accept the order."""


class DuplicateId(Exception):
    """This request was rejected because the client order ID is in use."""


ESCALATE_AFTER = 15.0  # seconds; illustrative, see "Order does not exist" above
# Every terminal status the venue documents; these are Binance Spot's.
FINAL = {"REJECTED", "FILLED", "CANCELED", "EXPIRED", "EXPIRED_IN_MATCH"}


class Submission:
    def __init__(self, client_id: str, qty: int, sent_at: float) -> None:
        self.client_id, self.qty, self.sent_at = client_id, qty, sent_at
        self.state, self.filled = "PENDING", 0
        self.updated = float("-inf")  # venue time of the last event applied
        self.escalated = False   # a person has been asked to confirm the outcome
        self.late = False        # the order appeared after it was confirmed absent

    @property
    def reserved(self) -> int:
        """What this order may still add to the position."""
        if self.state in FINAL or self.state == "ABSENT":
            return 0
        return self.qty - self.filled


def submit(link, client_id: str, qty: int, now: float) -> Submission:
    sub = Submission(client_id, qty, now)    # journal it here, before the send
    try:
        on_order(sub, link.place(client_id, qty, now))
    except Rejected:
        sub.state = "REJECTED"               # an outcome: nothing reached the book
    except (Timeout, DuplicateId):
        sub.state = "UNKNOWN"                # not an outcome: keep the reservation
    return sub


def on_order(sub: Submission, order: dict) -> None:
    """An acknowledgment, a user-stream event or a lookup result for this ID."""
    newer = (order["filled"], order["time"]) >= (sub.filled, sub.updated)
    if sub.state in FINAL or not newer:
        return                               # final already, or an older event
    if sub.state == "ABSENT":
        sub.late = True                      # released too early: alert a person
    sub.state, sub.filled = order["status"], order["filled"]
    sub.updated = order["time"]


def resolve(link, sub: Submission, now: float) -> None:
    """Runs on a timer while the user stream has said nothing about the ID."""
    if sub.state == "PENDING":
        sub.state = "UNKNOWN"                # restored from the journal after a crash
    if sub.state not in ("UNKNOWN", "ABSENT"):
        return
    order = link.lookup(sub.client_id, now)
    if order:
        on_order(sub, order)
    elif sub.state == "UNKNOWN" and now - sub.sent_at >= ESCALATE_AFTER:
        sub.escalated = True                 # a miss is not proof: keep the hold


def confirm_absent(sub: Submission) -> None:
    """A person, or the venue's support, confirmed the order does not exist."""
    if sub.state == "UNKNOWN":
        sub.state = "ABSENT"                 # release; the ID stays on watch


# In-memory venue and network, so the scenarios run without an account.
class Venue:
    """One client-order-ID contract.

    scope="open":     an ID is unique among open orders only (Binance Spot, Kraken).
    scope="lifetime": a duplicate ID returns the existing order, forever (an
                      assumption; Coinbase documents no retention period).
    A lookup returns the newest match: synthetic, Binance documents no rule.
    """

    def __init__(self, scope: str, fills: bool = True, lag: float = 0.0) -> None:
        self.scope, self.fills, self.lag = scope, fills, lag
        self.orders: list[dict] = []

    def _find(self, client_id: str, now: float, open_only: bool = False):
        for order in reversed(self.orders):
            if order["id"] == client_id and order["visible_at"] <= now:
                if order["status"] == "NEW" or not open_only:
                    return order
        return None

    def place(self, client_id: str, qty: int, now: float) -> dict:
        known = self._find(client_id, float("inf"), self.scope == "open")
        if known and self.scope == "lifetime":
            return dict(known)
        if known:
            raise DuplicateId(client_id)
        order = {"id": client_id, "status": "FILLED" if self.fills else "NEW",
                 "filled": qty if self.fills else 0, "time": now,
                 "visible_at": now + self.lag}
        self.orders.append(order)
        return dict(order)

    def lookup(self, client_id: str, now: float):
        order = self._find(client_id, now)
        return dict(order) if order else None

    def position(self) -> int:
        return sum(order["filled"] for order in self.orders)


class Link:
    """The network between the bot and the venue, with one injected fault."""

    def __init__(self, venue: Venue, fault: str | None = None) -> None:
        self.venue, self.fault = venue, fault  # "lose_request" or "lose_response"

    def place(self, client_id: str, qty: int, now: float) -> dict:
        fault, self.fault = self.fault, None   # each fault fires once
        if fault == "lose_request":
            raise Timeout
        ack = self.venue.place(client_id, qty, now)
        if fault == "lose_response":
            raise Timeout
        return ack

    def lookup(self, client_id: str, now: float):
        return self.venue.lookup(client_id, now)


def retry_same_id(link: Link, client_id: str, qty: int) -> None:
    """The obvious fix: on a timeout, send again with the same client order ID."""
    for attempt in range(3):
        try:
            link.place(client_id, qty, now=float(attempt))
            return
        except Timeout:
            continue


# The obvious fix doubles the position where IDs are unique among open orders.
venue = Venue("open")
retry_same_id(Link(venue, "lose_response"), "buy-1", 1)
assert venue.position() == 2

# The same retry is safe where a duplicate ID returns the existing order.
venue = Venue("lifetime")
retry_same_id(Link(venue, "lose_response"), "buy-1", 1)
assert venue.position() == 1

# One lost acknowledgment, three truths.
# 1. The request never arrived: a miss escalates, only a person releases.
venue = Venue("open")
link = Link(venue, "lose_request")
sub = submit(link, "buy-1", 1, now=0.0)
resolve(link, sub, now=2.0)
assert (sub.state, sub.reserved, sub.escalated) == ("UNKNOWN", 1, False)
resolve(link, sub, now=15.0)
assert (sub.state, sub.reserved, sub.escalated) == ("UNKNOWN", 1, True)
confirm_absent(sub)
assert (sub.state, sub.reserved, venue.position()) == ("ABSENT", 0, 0)

# 2. The order is working, and the lookup lags the matching engine by 3 seconds.
venue = Venue("open", fills=False, lag=3.0)
link = Link(venue, "lose_response")
sub = submit(link, "buy-1", 1, now=0.0)
resolve(link, sub, now=2.0)
assert (sub.state, sub.reserved) == ("UNKNOWN", 1)
resolve(link, sub, now=4.0)
assert (sub.state, sub.reserved) == ("NEW", 1)

# 3. The order filled before the first lookup.
venue = Venue("open")
link = Link(venue, "lose_response")
sub = submit(link, "buy-1", 1, now=0.0)
resolve(link, sub, now=1.0)
assert (sub.state, sub.reserved, venue.position()) == ("FILLED", 0, 1)

# The lookup lags longer than the escalation window: the hold stays.
venue = Venue("open", lag=16.0)
link = Link(venue, "lose_response")
sub = submit(link, "buy-1", 1, now=0.0)
resolve(link, sub, now=15.0)
assert (sub.state, sub.reserved, sub.escalated) == ("UNKNOWN", 1, True)
assert venue.position() == 1             # filled at the venue, invisible to the bot
confirm_absent(sub)                      # a wrong confirmation releases the hold...
assert (sub.state, sub.reserved) == ("ABSENT", 0)
resolve(link, sub, now=17.0)             # ...and the late order is still caught
assert (sub.state, sub.reserved, sub.late) == ("FILLED", 0, True)

# A duplicate-ID rejection while the original works is not a failed order.
venue = Venue("open", fills=False)
venue.place("buy-1", 1, now=0.0)         # the original, sent by a process now gone
link = Link(venue)
sub = submit(link, "buy-1", 1, now=1.0)
assert (sub.state, sub.reserved) == ("UNKNOWN", 1)
resolve(link, sub, now=2.0)
assert (sub.state, sub.reserved) == ("NEW", 1)

# A PENDING entry restored from the journal after a crash is resolved too.
venue = Venue("open")
venue.place("buy-1", 1, now=0.0)         # sent just before the crash, then filled
sub = Submission("buy-1", 1, sent_at=0.0)
resolve(Link(venue), sub, now=1.0)
assert (sub.state, sub.reserved) == ("FILLED", 0)

# An older event never overwrites a newer one.
sub = Submission("buy-2", 10, sent_at=0.0)
on_order(sub, {"status": "NEW", "filled": 0, "time": 2.0})
on_order(sub, {"status": "PENDING_NEW", "filled": 0, "time": 1.0})
assert sub.state == "NEW"                # equal fills: venue time decides
on_order(sub, {"status": "PARTIALLY_FILLED", "filled": 6, "time": 3.0})
on_order(sub, {"status": "NEW", "filled": 0, "time": 2.0})
assert (sub.state, sub.reserved) == ("PARTIALLY_FILLED", 4)

print("timeout scenarios pass")

What else do people ask?

How do I handle a timeout when I do not know whether the exchange accepted the order?

Mark the order unknown, keep its full size reserved, and send nothing new for the same intent. Wait for the order stream to mention its client order ID; if it does not, look the order up by that ID. A “does not exist” answer is a reason to escalate to a person, not to release: Binance documents no time after which a missing order can no longer appear.

Which order errors are safe to retry?

Only a connection error raised before the request was sent, with the same client order ID. A confirmed rejection - on Binance a filter failure or a matching-engine reject such as insufficient balance, on Alpaca a buying-power error or unrecognized input - is an outcome: fix the cause and send a new order with a new client order ID. A duplicate-ID error is not an outcome, nor is a timeout after the send, an “execution status unknown” error, an HTTP server error, an empty body or an unfamiliar response: resolve the order first, since the original may be live. The codes are in the venue notes.

Is retrying with the same client order ID enough to prevent a duplicate order?

Only while the venue still recognizes the ID. Coinbase Advanced Trade returns the existing order for a duplicate ID, and a FIX resend with the possible-resend flag set to yes returns the current status of an ID the venue has seen, but neither documents how long an ID is recognized. On Binance Spot it is not enough: the ID is unique only among open orders, so once the original has filled the retry is accepted as a second order.

How do I make sure my bot does not send the same order twice after a reconnect?

Journal the client order ID before every send, subscribe to the order stream before querying, resolve every journal entry that is pending or unknown by its client ID, escalate what stays missing, and send nothing new until each entry is resolved or escalated.

Was this article useful?