ReliabilityIntermediate

API Errors

An API error is any response indicating a request did not complete as intended, and handling them means classifying each as transient or permanent, reading its code and message, and never assuming a call succeeded without confirming the resulting state.

Quick answer: An API error is any response indicating a request did not complete as intended, and handling them means classifying each as transient or permanent, reading its code and message, and never assuming a call succeeded without confirming the resulting state.

In simple words

API errors are the API's way of telling you something went wrong — bad input, no permission, too many requests, or its own server failing. The skill is not avoiding errors, which is impossible, but reacting correctly: some you retry, some you fix, and some you must escalate. Above all, you never assume an order worked just because you did not see an error.

Purpose

Understanding API errors matters because a trading system spends much of its life handling failure; the difference between a robust and a dangerous system is how precisely it classifies and responds to each kind of error.

Professional explanation

A taxonomy of failures

API errors fall into recognisable classes, and the class dictates the response. Client errors (HTTP 4xx) mean your request was wrong: 400 malformed, 401 unauthenticated, 403 forbidden, 404 not found, 422 semantically invalid, 429 rate-limited. Server errors (5xx) mean the broker failed: 500 internal, 502/503/504 gateway or availability. Beyond HTTP status, brokers layer their own business errors in the response body — insufficient funds, margin shortfall, order rejected by exchange, market closed, instrument not tradable. And below HTTP entirely sit network errors: connection refused, DNS failure, timeout, or the dreaded case where the request was sent but no response returned. Each layer needs its own handling.

Transient versus permanent

The most important axis is whether an error is transient (likely to succeed if retried later) or permanent (will keep failing until something changes). Timeouts, 429s, 502/503/504 and brief connectivity blips are typically transient and belong in a retry-with-backoff path. A 400 bad request, a 401 with genuinely wrong credentials, insufficient funds, or an invalid instrument are permanent — retrying them unchanged is pointless and, in the rate-limit case, harmful. Misclassifying a permanent error as transient produces a retry loop that hammers the API and never recovers; misclassifying a transient error as permanent gives up on a request that would have worked. Getting this axis right is the core of error handling.

Reading codes and messages precisely

Robust handling reads both the HTTP status and the broker's structured error body, which usually contains a machine-readable code and a human message naming the problem — often the exact offending field or the business reason. Programming against the numeric or string code, not the free-text message, is essential because messages get reworded across versions while codes are more stable. A good client maps known codes to explicit policies: this code means refresh the token, that one means the market is closed, another means reduce quantity. Logging the full error — code, message, request id — is what makes post-mortem debugging possible when something fails at 9:20 am.

The ambiguous failure: never assume success

The most dangerous error is the one where you do not get a clear answer: you sent an order request and the connection dropped before the response returned. You now do not know whether the order was placed. Assuming it failed and re-sending risks a duplicate; assuming it succeeded and moving on risks an unmanaged live position. The only safe resolution is to query the true state — check the order book by your client reference or list recent orders — before deciding. This is why order placement should never be fire-and-forget: every critical action is followed by confirmation, because the absence of an error is not proof of success.

Business errors from the exchange

Some errors originate not from the broker's server but from the exchange rejecting the order: price outside the circuit limit, order in a frozen quantity band, trading halted, or post-market timing. These arrive as successful HTTP responses carrying a rejection status or as an order-update event marking the order REJECTED. Your system must treat an accepted HTTP call whose order later shows REJECTED as a failure to act, not a success. Watching the order lifecycle — not just the placement response — is how you catch exchange-level rejections that a naive client would miss.

Escalation: when handling becomes alerting

Not every error should be swallowed and retried silently. Persistent failures, repeated rejections, or errors on critical paths (cannot cancel, cannot fetch positions) should escalate — raise an alert, and in severe cases trigger the kill switch to halt trading and flatten or freeze positions. The design principle is that the system degrades safely: when it can no longer trust its own ability to act correctly, it stops rather than continuing blind. An error-handling strategy that only ever retries, with no escalation path, will eventually keep trading through a condition it should have shut down for.

Transient vs permanent errors

AspectTransientPermanent
ExamplesTimeout, 429, 503, blip400, wrong creds, no funds
Right responseRetry with backoffFix input or escalate
Retrying unchangedOften succeedsAlways fails
Danger if misreadGive up too earlyInfinite harmful loop

Practical example

Illustrative example (Indian market)

Your system sends an order and receives a timeout — no response. Rather than re-sending (which could double the order), it queries recent orders by the client reference it attached: the order is absent, so it was never placed, and the client safely retries once. Later, a different order returns HTTP 200, but the order-update stream reports status REJECTED with a code meaning price outside circuit limit. The system treats this as a failure to enter, logs the code, and does not assume a position exists. A third request returns 401; the client refreshes the token and retries. Each error class gets a different, deliberate response.

On NSE, orders can be rejected for exchange-specific reasons — price beyond the daily circuit band, quantity above the freeze limit, or orders sent outside the product's permitted window. These often surface as an accepted API call whose order later shows REJECTED, so a system that only checks the placement response and not the order lifecycle will wrongly believe it holds a position it never got.

Advantages

  • Correct classification lets the system recover from transient faults automatically
  • Reading codes precisely enables specific, safe responses per error type
  • Confirming state after ambiguous failures prevents duplicate or phantom orders
  • An escalation path lets the system stop safely when it can no longer act correctly

Limitations

  • Some failures are genuinely ambiguous, requiring a state query to resolve, which adds latency
  • Error codes and messages differ per broker and change across API versions
  • Exchange rejections arrive as successful HTTP calls, so naive clients miss them
  • Over-aggressive retrying of permanent errors can hammer the API and trigger bans
  • No amount of handling removes the underlying risk of acting on wrong state if you skip confirmation

Common mistakes

  • Assuming an order succeeded because no error was raised, without confirming the order state
  • Retrying a permanent error (400, insufficient funds) unchanged in an infinite loop
  • Re-sending an order after a timeout instead of first querying whether it was placed
  • Programming against the free-text error message instead of the stable error code
  • Checking only the placement response and ignoring a later REJECTED order-update event
  • Swallowing errors silently with no logging and no escalation path for persistent failures

Professional usage

Professional systems centralise error handling in the API client, mapping each HTTP status and broker error code to an explicit policy — retry, refresh, fix, reject, escalate — rather than scattering ad hoc try/except blocks through strategy code. Every critical action is confirmation-based: nothing is assumed successful without reading the resulting state. Ambiguous failures trigger a reconciliation query, persistent or critical errors raise alerts and can invoke the kill switch, and every error is logged with a correlation id for reconstruction.

Key takeaways

  • Classify every error: HTTP client (4xx), server (5xx), business, or network — the class sets the response
  • The key axis is transient vs permanent: retry the first with backoff, fix or escalate the second
  • Read the stable error code, not the free-text message, and log everything for debugging
  • Never assume success — confirm state after ambiguous failures, and escalate persistent or critical errors

Frequently asked questions

What is an API error?
It is any response indicating a request did not complete as intended — a bad-input rejection, an auth failure, a rate limit, a server fault, a business error like insufficient funds, or a network failure. Handling them well is central to a reliable trading system.
What is the difference between transient and permanent errors?
Transient errors (timeouts, 429s, 503s, brief blips) are likely to succeed if retried later, so they belong in a backoff-retry path. Permanent errors (400, wrong credentials, insufficient funds) will keep failing until you change something, so retrying them unchanged is pointless.
Should I retry every failed API call?
No. Retry transient errors with exponential backoff, but never retry permanent errors unchanged — a 400 or an insufficient-funds error will just fail again. And retry order placement only after confirming the first attempt did not already go through.
Why should I never assume an API call succeeded?
Because the request can be sent while the response is lost, leaving you unsure whether the order was placed. Assuming success risks an unmanaged position; assuming failure risks a duplicate. The safe path is to query the true state before acting further.
How do I read an API error?
Inspect both the HTTP status code and the broker's structured error body, which usually carries a machine-readable code and a message naming the problem. Program against the stable code rather than the free-text message, and log the full error for later debugging.
What does a 4xx versus 5xx error mean?
A 4xx means your request was at fault — malformed, unauthorised, forbidden, not found, or rate-limited — and needs a change. A 5xx means the server failed and may succeed on retry. The families map onto different recovery actions.
What is an ambiguous failure?
It is when you send a request but get no clear response — typically a timeout after the request left. You cannot tell if it succeeded, so you must query the resulting state (for example, look up the order by your client reference) rather than guessing.
How do exchange rejections appear?
Often as a successful HTTP response whose order later shows status REJECTED, with a code such as price outside circuit limit or quantity above freeze. A system that checks only the placement response, not the order lifecycle, will miss these and wrongly assume a fill.
Should I program against the error message or code?
Against the code. Error messages are free text that gets reworded across API versions, while codes are more stable and machine-readable. Mapping known codes to explicit handling policies makes your system robust to wording changes.
When should an error trigger an alert or kill switch?
When failures persist or hit critical paths — you cannot cancel an order, cannot fetch positions, or orders are repeatedly rejected. At that point the system can no longer trust its ability to act, so it should escalate and, in severe cases, halt trading rather than continue blind.
What are network errors versus API errors?
Network errors — connection refused, DNS failure, timeout — happen below the HTTP layer, before the server even replies with a status. They are usually transient and often ambiguous, so they need both retry logic and state confirmation for critical actions.
Can good error handling remove trading risk?
No. It reduces operational risk from failures, but it cannot make a strategy profitable or remove market risk. Its job is to ensure the system acts on correct state and fails safely, which is a precondition for, not a substitute for, sound strategy and risk control.

Voice search & related questions

Natural-language questions people ask about API Errors.

What are API errors in trading?
They are the API telling you something went wrong — bad input, no permission, too many requests, or its own server failing. The skill is reacting correctly, not avoiding them.
Should I retry every API error?
No. Retry the temporary ones like timeouts and rate limits with a delay, but fix the permanent ones like bad input or no funds. Retrying those just loops forever.
Why can't I assume my order went through?
Because the reply can get lost even after the order was placed. If you assume and re-send, you might double it. Always check the order status before acting again.
What is a transient error?
It is a temporary failure, like a timeout or a busy server, that will probably work if you wait and try again. Permanent errors, like bad credentials, will not.
How do I know why an order was rejected?
Read the error code and message the API returns, and watch the order status for a REJECTED update. The code usually names the reason, like a circuit-limit breach.
When should my system stop trading on errors?
When failures keep happening on critical actions, like being unable to cancel or check positions. Then it should alert you and, if serious, hit the kill switch.

Sources & references

    Last reviewed 11 July 2026. Educational content only — not investment advice. Markets and rules change; verify current conventions with SEBI, NSE/BSE and your broker.

    Educational content only — not investment advice. Examples use illustrative numbers and simplified models. Algorithmic trading and derivatives involve substantial risk. See our Risk Disclosure and SEBI Disclaimer.