API Error Handling: Building a Bot That Survives a Bad Day

In testing, everything works. On a quiet Tuesday, everything works. However, on a hectic Friday, the market may open with a large gap, volatility may be very high, and there may be a 3-second delay in your network connection. All of a sudden, your bot is blind, has a large exposure, and is throwing timeout errors. At this point it becomes clear: error handling is critical.

The Nightmare of the Dropped Session

Connection issues and expiry issues are common on the internet. However, if the connection drops while you have a position open, your script can no longer manage the trade.

Ensure that in your script, you have a strong re-authentication system. If a request is made with an expired token, your bot should automatically request a new token and attempt the request again. In addition to this, if a WebSocket connection drops, you should poll your REST endpoints to see what positions you currently have open. We do not want to lose money due to a temporary network issue.

Idempotency: The Cure for the Double Order

If there is a timeout, you may not know if your order went through. Your script may panic and attempt to make the request again. As a result, you may end up buying double the number of shares you wanted and wipe out your account.

Idempotency will save you here. Every order sent must have a unique client order ID. If the same order is sent twice (with the same ID), the second order will be rejected. Before attempting to resend failed requests, use the Algo Trading API to check the order book to see whether or not your order went through. Do not blindly resend timeout errors.

The Messy Reality of Partial Fills

You attempt to buy 100 lots. However, only 60 of these were filled, and 40 are in the pending queue. To tap a period, wait until the very end. Many retail bots will assume that if an order is not completely filled, it has been completely rejected. However, this is dangerous.

Be sure to track filled_quantity and order_quantity separately. If you have partially filled positions, you still have a position. Decide whether to cancel the remaining quantity or leave it. If you wish to cancel the entire order, be careful that you do not inadvertently cancel the 60 lots which were filled.

Don’t Guess Your Margin

When you have multiple positions, your available capital changes every second. You may have had enough capital to make a trade 30 seconds ago, but now due to a sharp increase in implied volatility, you may be over your limits.

Do not hard code margin requirements. Just before placing an order, make a request to the margin calculator endpoint. Send in the trade details, and receive exactly how much margin would be blocked. If the margin required is larger than your available cash, do not make the trade. By making this one check, you can avoid a chain of rejected orders with margin penalties.

Retry Logic That Doesn’t Blow Up

Don’t make a while loop with requests made every millisecond. You will get your IP blocked.

Implement exponential delays. If a request fails, wait 1 second. If it fails again, wait 2 seconds. Then 4, then 8.

Distinguish between fatal and non-fatal errors. If there is a network timeout or a server error, this is non-fatal. It is a good idea to retry. However, if there is an invalid trading symbol or not enough funds, this is a fatal error. Retrying will cause you to send bad data repeatedly. In this case, log the error, stop the loop, and notify you.

The Bottom Line

Even if your bot is performing perfectly in a stable market, if it crashes in a flash crash, it is useless. To make your bot as resilient as possible, code it to handle the worst day possible. Be prepared to handle connection drops. Expect duplicate clicks. And always, always check your margins.

Leave a Reply