Building on a Broker API: Rate Limits, Safe Order Placement and Reconcile Loops for Option Sellers
The first script that places an order through a broker's API usually works. That is the dangerous part. A script that works once on a quiet morning with one order tells you almost nothing about what happens at 09:20 on expiry day, when it has to send four orders, one of them times out, the broker's server is slow, and your internet drops for eight seconds.
The code that decides what to trade is the small part of an automated system. The larger part is the code that deals with the fact that the outside world is unreliable: orders that are accepted but not confirmed, calls that are refused for going too fast, positions that do not match what you think you hold. Most of the money lost in home-built systems is lost there, and not in the strategy.
This guide is written for traders who are not full-time developers. It does not need much code. It explains the ideas you need to check, four in particular: staying within rate limits, placing orders so a retry cannot double your position, running a loop that compares your records with the broker's, and keeping logs you can actually use at the worst moment. The examples are about NIFTY and SENSEX weekly option selling, but the engineering is the same for any instrument.
The three books you are really keeping
Start with a mental model that makes the rest easy. At any moment there are three records of what you hold, and they can disagree.
Book What it says Who writes it
Intent What the strategy wants to hold right now Your rules
Ledger What your software has sent and believes was filled Your code
Broker's book What the broker says you actually hold and what orders exist The broker
In a perfect world the three match. In practice they drift apart, for ordinary reasons. An order was sent but the reply never arrived, so the ledger says nothing and the broker's book shows a fill. An order was rejected, but your code did not read the rejection, so the ledger says filled and the broker's book says nothing. You placed a manual trade on the broker's app, so the broker's book has a position that neither intent nor ledger knows about.
The broker's book is the only one that is legally and financially real. Margin, charges and settlement all follow from it. So the engineering aim is simple to state: make your ledger follow the broker's book, and make your intent act on the ledger only when the ledger has been checked against the broker's book. Everything else in this article is a method for doing that.
What to check on any broker API before writing code
Before you write a line, read the broker's documentation for six things. Do this for every broker you plan to use, as these details differ and change between versions.
Authentication and session life. Many broker APIs need a fresh login token every day, sometimes with a second factor. Your system needs a plan for the morning login, and an alert if it fails. A script that cannot log in at 09:10 is a missed day, or worse, a half-managed one.
Rate limits. How many requests per second and per minute, separately for order calls and for data calls. Also look for a daily order cap.
Order types and fields. Which order types exist, whether there is a field you can use to tag your own reference on each order, and how the status is reported.
Status values. The exact words the API uses for pending, open, filled, partly filled, rejected and cancelled. Your code has to handle every one of them.
Positions and order book calls. How fresh the data is, and whether it can lag behind a fill by a few seconds.
Error messages. What a rejection looks like and whether the reason is machine-readable.
If you are still at the stage of working out what is on offer and what the regulatory position is, one published overview of the algo trading API in India is a reasonable starting point for the wider picture. It cannot replace your broker's own documentation, which is the only source for the current limits and fields, so read both.
The rules about who may use an API and how have also been changing under SEBI's retail algo framework. Read the circulars yourself on sebi.gov.in and ask your broker what it needs from you, such as strategy registration or fixed IP addresses. Do not rely on a forum summary.
Rate limits: treat them as a budget
A rate limit is a promise that the broker will refuse some of your calls if you send too many. If your code is not written to expect that, it will eventually hit the limit at the worst time and behave in a way you did not plan.
Think of the limit as a budget and spend it on purpose. A short strangle with two hedges needs four order calls at entry. If your system also polls prices, checks the order book after each order and reads positions, the same minute can easily use dozens of calls. Add a retry loop that fires on every failure, and a single slow response can multiply the traffic exactly when the broker is struggling.
A simple call budget
Here is an illustrative budget. The numbers are made up. Replace them with your broker's current published limits.
Four design rules follow from the budget.
Put every API call through one gate. A single function that all calls use can count requests, sleep when needed and log each call. If calls are scattered around the code, nobody knows the total rate, and the first time you find out is when the broker refuses you.
Back off when you are told to slow down. If the API says you are going too fast, wait and then retry with a growing delay: 1 second, then 2, then 4, with a small random addition so that several parts of your system do not retry in lockstep. A fixed instant retry just makes the problem worse.
Rank calls by importance. Exit orders and the kill switch come first. Reports and nice-to-have data come last. If the budget runs short, the important calls must still go through. A simple way to do this is a priority queue, with exits at the top.
Know the daily cap. Some brokers limit the total orders per day. A strategy with re-entries and stop modifications can use more orders than you expect. Count them on a typical day and add a margin.
The cost of waiting
Rate limits and retries cost time, and time costs money, although less than people fear on the entry. EliteAlgo's desk study of 163 NIFTY and SENSEX weekly expiry sessions between January 2025 and July 2026 tracked the ATM straddle premium against its 09:16 level, averaged over all sessions. By 09:31 the average was 95.4% of the starting level. That is an average drop of 4.6% in fifteen minutes. On a straddle premium of 110 points, 4.6% is about 5 points, which on one NIFTY lot of 65 is roughly Rs 330. This is an average of many days with the strike held fixed. A single day can be far from it, and a fast move can go either way. The practical reading is that a delay of seconds is cheap compared with the cost of a wrong or doubled order, so it is right to let your system pause and check instead of rushing a retry.
Idempotent order placement: surviving the timeout
This is the most important idea in the article and the least known outside software teams. The word sounds technical. The meaning is simple: doing something twice should have the same effect as doing it once.
Placing an order is not naturally idempotent. If you send "sell 65 NIFTY call at market" twice, you sell 130. That matters because of a problem every network call has.
The three outcomes of an order call
When your code sends an order, there are three possible results, not two.
Accepted. The broker replies with an order ID.
Rejected. The broker replies with an error, and no order exists.
Unknown. You sent the request and got no usable answer. A timeout, a dropped connection, a garbled response. The order may or may not exist.
Most beginners' code handles the first two and treats the third as a failure: "it did not work, try again." If the order did in fact go through, the retry doubles the position. In a short-premium strategy, a doubled short leg is exactly the kind of mistake that turns a normal day into a bad one.
The rule for unknown
When the result is unknown, never retry blindly. Look first. Query the broker's order book and positions, find out whether the order exists, and only then decide. To make that lookup possible you need a way to recognise your own order.
Give every order your own reference. Before sending, generate a unique reference such as the date, the strategy name, the leg and a counter, for example 20261104-S1-CE-001. If the broker's API has a field for a tag or remark, put the reference there. After an unknown result, search the order book for that reference. If it is there, treat the order as sent. If it is not there after a short wait, it is safe to send again with the same reference.
Some APIs may offer a proper idempotency key that makes the broker ignore a repeated request. Many do not. Check your broker's documentation, and do not assume. If there is no such key, the tag-and-lookup method is your protection.
Order of operations for a multi-leg entry
With several legs, the order of the calls matters as much as each call. A safe pattern for a hedged short strangle looks like this.
- Check that the day, time, margin and daily-loss limit allow a new trade.
- Send the hedge (bought) legs first.
- Confirm each hedge is filled, by reading the order book, not by trusting the first reply.
- Only then send the short legs.
- Confirm the fills. Compare quantities with intent.
- If any step ends in unknown or partly filled, stop, alert yourself and do not continue to the next leg.
The rule behind this is that you should never be in a state where a naked short leg exists because a hedge is unconfirmed. Slower but safe beats fast but exposed.
Partial fills and price protection
Two more traps. A partly filled order is neither done nor failed. Decide in advance what you do: wait a set time, cancel the remainder, or top up. And a plain market order on a thin option strike can fill at a poor price. Many traders use a limit order with a small buffer to bound the damage, then handle the case where it does not fill. Either way, the rule is written down before the day, not invented when the screen is red.
The reconcile loop
The reconcile loop is a small program that runs while your strategy is live. Every few seconds, it compares the three books and raises a flag if they differ. Here is the idea in plain pseudocode. You do not need to understand any particular programming language to follow it.
every 10 seconds, and again after every order:
broker_positions = ask broker for open positions
broker_orders = ask broker for today's orders
ledger_positions = what my software believes it holds
for each instrument in either list:
if broker quantity != ledger quantity:
record a mismatch (instrument, both numbers, time)
if there is a mismatch:
wait 3 seconds and check again # the broker data may lag
if the mismatch is still there:
stop new orders
alert me loudly
apply the playbook for this kind of mismatch
Three details make the loop work in the real world.
Check twice before panicking. Some APIs show positions a few seconds after a fill. A mismatch that clears on the second look is just lag, and an alarm on every lag will teach you to ignore alarms. A mismatch that survives two looks is real.
Compare more than positions. Also compare open orders. A forgotten pending stop order in the broker's book that your ledger does not know about can fire later and open a position you did not intend. Include order status, quantity and price.
The loop must be able to stop the strategy. A reconcile loop that only prints a message is a decoration. It needs the authority to block new orders until a person has looked, and it should run even when the main strategy code is busy or has crashed. A separate process is the safest way.
Reconcile before the stops are trusted
A stop-loss rule is only as good as the position your software believes it has. If your system thinks it holds two lots and the broker holds four, a stop sized for two leaves half the risk unmanaged. So run a reconciliation before entry, after entry, after any stop or exit, and at the end of the day. The end-of-day one should confirm that you are flat if the strategy is intraday. A leg that was never closed overnight is a risk you should find at 15:35, not the next morning.
A mismatch playbook
Decide what to do for each kind of mismatch before it happens. During a live mismatch, you will be tempted to improvise, and improvisation under stress is how small errors grow.
Two rules cover the table. First, when in doubt, reduce risk and not increase it: pause, cancel pending orders, close if you must. Second, always correct the ledger to match the broker, never the other way round. The broker's book is what exists.
Logging: write for the person at 15:10
Logs are for the version of you who is looking at a problem at 15:10 with ten minutes to act. They need to answer one question fast: what has happened so far, and in what order?
A good log line is boring and complete. For every order action, record the time to the second, the strategy name, your own order reference, the instrument, side, quantity, order type, price, the request you sent, the exact reply or error you received, and the broker's order ID if one came back. For every reconcile run, record both sets of numbers, not just "OK".
What to keep and for how long
Raw requests and replies. Keep the full text, not your summary. When something odd happens, the exact wording of the broker's reply is often the clue.
Decisions. Log why the system did something: "Stop triggered, combined P&L minus Rs 2,700, limit minus Rs 2,600." A log of actions without reasons is a puzzle.
One file per day, with the date in the name. Plain text or CSV is fine. You will want to search and sort it.
Keep it for at least the period your tax and compliance obligations require, and longer if you can. Disk space is cheap and missing evidence is expensive.
Never log secrets. API keys and tokens do not belong in log files. Mask them.
Pair the logs with an alert channel you will really see, such as a message to your phone. Alerts should be few and meaningful: a failed login, a mismatch that persists, a rejected exit, a daily loss limit reached. If your phone buzzes twenty times a day for harmless events, the one that matters will be missed.
Time matters
Make sure the clock on your machine is accurate. Order timestamps, exit times and log lines are only useful if they line up with the exchange's clock. An unsynchronised computer that is off by a minute will make a time exit at 15:15 happen at the wrong moment and make your logs impossible to compare with the broker's records. Turn on automatic time sync and check it.
Testing without losing money
You can test most of this before real money is at risk, and you should. A test plan has four layers.
Dry run. The code runs the whole day's logic but sends no orders. It logs what it would have done. Compare the log with what you would have done by hand.
Paper or sandbox, if the broker offers it. Not all do, and some sandboxes behave differently from the live system, so do not treat a pass here as proof.
Smallest live size. Run a single lot of a cheap, liquid instrument. Real orders, real rejections, small cost.
Fault injection. Break things on purpose while the size is small. Switch off the internet for ten seconds in the middle of an order. Send an order with an invalid quantity. Place a manual trade in the broker's app and see if the reconcile loop catches it. Kill the script and restart it with a position open: does it recognise what it already holds, or does it enter again?
That last test, the restart with an open position, catches more real bugs than any other. A system that forgets what it holds after a restart will place a second set of orders. The fix is to rebuild the ledger from the broker's book on every start, before the system is allowed to do anything.
When your tests pass, run live at small size for several weeks before scaling. Keep the daily report, the mismatch log and the override log. If a month passes with no unexplained mismatch, you have earned a bit of confidence. If there are mismatches, each one is a free lesson from a cheap day.
Frequently Asked Questions
Can I trade through a broker API without knowing how to code?
Partly. No-code builders handle common cases. For custom checks, reconciliation and anything unusual, someone has to write code, whether you, a hired developer or a platform provider. If you hire help, agree in writing who owns the code and who is responsible when an order goes wrong.
What happens if my order request times out?
The result is unknown, not failed. Do not send it again straight away. Look up the broker's order book for your own order reference. If the order exists, treat it as sent. If it does not exist after a short wait, send it again with the same reference.
What is an API rate limit and what happens if I exceed it?
It is a cap on how many requests you can send in a period. If you go over it, the broker refuses some requests, and repeated violations may lead to a block. Route all calls through one gate that counts them, back off with growing delays, and keep the important calls, such as exits, ahead of the rest.
How often should I reconcile my positions with the broker?
Before entry, after every order, after every exit, at a steady interval while a position is open, and once at the end of the day. A common interval is every ten seconds or so, within your call budget. Check a second time before raising an alarm, since broker data can lag.
Is it safe to keep my API key in my script?
It is better not to. Keep keys and tokens in a separate configuration file or in environment variables, keep that file out of any shared folder or code repository, and never write secrets to logs. If a key is ever exposed, generate a new one at once.
Should I use market orders or limit orders for automated option selling?
Both have trade-offs. A market order is likely to fill but the price can be poor on a thin strike. A limit order bounds the price but may not fill. Many traders use a limit with a small buffer and a rule for the case where it does not fill. Decide in advance, and test it.
Conclusion
Building on a broker API is mostly an exercise in distrust. Distrust the reply that never came, the position screen that is a few seconds stale and the retry that might double an order. Keep three books and make the ledger follow the broker's. Treat rate limits as a budget, give every order a reference of your own, never retry an unknown result blindly, and run a reconcile loop that can stop the strategy. Write logs for the person who has ten minutes to fix something.
None of this makes a strategy profitable. It makes the system behave as designed, which is the only thing you can control. Test on small size, break things on purpose, and scale slowly.
Algo trading carries a real risk of loss, including more than you expected on a bad day. EliteAlgo is analytical software and not an investment adviser. Nothing in this article is investment advice, a recommendation to trade, or a promise of any result. Test everything on paper and with small size first.

Top comments (0)