Zerodha's own documentation steers individual developers away from postbacks. The postbacks page says the feature "is meant for platforms and public apps where a single api_key will place orders for multiple users", and it points everyone else at the websocket, which already carries the same order payload. If you are one person running one bot, you probably don't need a public URL for order updates at all.
That matters because the order call itself tells you very little. As I set out in placing a first order through Kite Connect, place_order() returns an order ID, not a fill. This guide covers the three ways to find out what happened next, what an update contains, and Python for both push methods.
Three ways to learn what happened to an order
| Polling | Postback | Websocket order update | |
|---|---|---|---|
| How it arrives | You call GET /orders/:order_id |
HTTP POST to your registered URL | JSON text message on the ticker connection |
| Which orders | Any order you ask about | Only orders placed with your app's API key | All of the user's orders, from any platform |
| Needs a public server | No | Yes | No |
| Needs an open connection | No | No | Yes |
| Works when the user is not logged in | No (needs a valid token) | Yes, the docs say | No (needs a valid token) |
Polling is the simplest and the one Zerodha's orders page warns about: for anything other than a market order, it says continuous polling is impractical and that postbacks "are ideal as they sent order updates asynchronously as they happen". Read that next to the postbacks page, which sends individual developers to the websocket version, and the practical advice is "use a push method"; for one person's bot, that means the websocket. Polling still has a place. GET /orders/:order_id returns one record per state change, so it is the way to rebuild an order's full path after the fact.
The "which orders" row is the one that surprises people. If you place an order by hand in the Kite app while your bot is running, a postback will not tell your bot about it. The websocket will.
What one update contains
Both push methods send the same object. The websocket page says the data field of an order message "will contain the full order Postback payload". The fields worth reading first:
| Field | What it tells you |
|---|---|
status |
The order's state at this moment |
filled_quantity, pending_quantity |
How much has traded and how much is still working |
cancelled_quantity, unfilled_quantity |
What will never trade |
average_price |
Average fill price; the docs say it is set for COMPLETE orders |
status_message |
A readable reason when something fails |
exchange_order_id |
Null if the order never reached the exchange |
placed_by |
Who placed it; can differ from user_id for orders from a dealer terminal |
tag |
Your own label, alphanumeric, up to 20 characters |
checksum |
SHA-256 proof that Zerodha sent it |
The tag is cheap and useful. Set it when you place the order, and every update about that order comes back carrying it, so your handler can match updates to your own records without a lookup.
The statuses between "sent" and "done"
Postbacks fire on four events: COMPLETE, CANCEL, REJECTED and UPDATE, where UPDATE covers a modification or a partial fill. One inconsistency to plan for: the postback page lists the cancel event as CANCEL, while its own attribute table and the orders page use CANCELLED. I treat both as the same state.
The orders page names four common statuses (COMPLETE, REJECTED, CANCELLED and OPEN) and eight intermediate ones, from PUT ORDER REQ RECEIVED and VALIDATION PENDING through TRIGGER PENDING and CANCEL PENDING. It also says "there may be other values as well". So a handler should act on the states it knows and log anything else rather than crash on it.
A partly filled order produces several updates with the same order_id. Write the handler so that receiving the same update twice changes nothing: key your records on the order ID and overwrite the quantities, rather than adding to them.
Websocket order updates in Python
In the official kiteconnect library, KiteTicker routes text messages whose type is order (and whose data field is not empty) to an on_order_update callback. Prices come in as binary messages and go to on_ticks, so one connection serves both.
import logging
from kiteconnect import KiteTicker
FINAL = {"COMPLETE", "CANCELLED", "CANCEL", "REJECTED"}
kws = KiteTicker(api_key, access_token)
def on_order_update(ws, data):
logging.info("order %s %s filled=%s pending=%s tag=%s",
data["order_id"], data["status"],
data.get("filled_quantity"), data.get("pending_quantity"),
data.get("tag"))
record_update(data) # your own store, keyed on order_id
if data["status"] in FINAL:
logging.info("order %s finished", data["order_id"])
def on_error(ws, code, reason):
logging.error("ticker error %s %s", code, reason)
kws.on_order_update = on_order_update
kws.on_error = on_error
kws.connect(threaded=True)
Three details from the library source are worth knowing. A message that is not valid JSON is silently dropped. Server messages of type error go to on_error, not to the order callback. And reconnection is on by default: up to 50 attempts unless you change reconnect_max_tries (the library caps it at 300), with the wait between attempts growing to at most 60 seconds by default.
That last point is the websocket's weak spot. The documentation doesn't say whether updates sent during a disconnect are replayed, so assume they are not. After every reconnect, I'd fetch the order book once and reconcile it against your records. That is the same habit I described in the guards a trading bot needs: never assume the state in memory is the state at the broker.
If you already stream prices, the limits are the same ones covered in the Kite websocket guide: up to 3,000 instruments on one connection and up to three connections per API key.
Receiving postbacks on a server
A postback needs an endpoint that Zerodha's servers can reach (the docs don't spell out an HTTPS requirement, but it would be odd to receive order data over anything else), and the URL is a field in your Kite Connect app's settings (listed in the same API key guide). The docs say the JSON arrives as the raw request body, so read the body and decode it yourself. Then check the checksum before trusting anything in it.
import hashlib, hmac, json, os
from flask import Flask, request, abort
app = Flask(__name__)
API_SECRET = os.environ["KITE_API_SECRET"]
@app.post("/kite/postback")
def postback():
order = json.loads(request.get_data())
raw = order["order_id"] + order["order_timestamp"] + API_SECRET
expected = hashlib.sha256(raw.encode()).hexdigest()
if not hmac.compare_digest(expected, order.get("checksum") or ""):
abort(400)
record_update(order) # the same handler as the websocket uses
return "", 200
The checksum is the SHA-256 hash of order_id, order_timestamp and your api_secret, joined with no separator in the documentation's formula. hmac.compare_digest compares in constant time, which is good practice for any secret-based check. Keep the secret in an environment variable or a secrets store, never in the code.
Where each method falls short
Each method leaves a gap. Postbacks miss orders placed outside your API key, and the page I read says nothing about retries or what your endpoint must return, so I wouldn't assume a missed delivery is resent. The websocket has the disconnect gap described above and needs a valid access token, which has to be renewed every day (how the daily token works). Polling is late by however long you wait between calls.
That is why a careful setup uses two of them: a push method for speed, and one order-book fetch on start-up, after every reconnect and at the end of the day as the record of truth. If you are still at the stage of paper trading before going live, build the same handler into the paper engine so that simulated fills arrive in the same shape as real ones.
Sources
- Postbacks, payload fields, checksum formula and who postbacks are for: Kite Connect documentation, Postbacks
- Websocket text messages, order message format, connection and instrument limits: Kite Connect documentation, WebSocket streaming
- Order statuses, order history and the guidance on polling: Kite Connect documentation, Orders
on_order_updatedispatch and reconnect defaults: pykiteconnectticker.py
This guide explains a broker API for information only. It is not investment advice or a recommendation to buy or sell any security. I am not registered with SEBI as an investment adviser or research analyst.