Kite Connect API Guide: Build a Safer Trading Integration

Kite Connect API Guide: Build a Safer Trading Integration

Reviewed 13 August 2026

A dependable Kite Connect integration needs more than a successful order request. It needs an interactive login flow, server-side secret handling, strict validation, duplicate-event protection, risk checks, order-state tracking, rate-limit handling, and a clear response when the broker or network is unavailable.

The safest mental model is a pipeline:

TradingView signal
    -> HTTPS webhook receiver
    -> authentication and schema validation
    -> duplicate check
    -> symbol and risk validation
    -> Kite Connect order request
    -> order-state updates
    -> audit log and failure notification

Do not send a TradingView webhook directly to the broker API. A server-side receiver is needed to validate the signal, protect credentials, enforce risk rules, and reconcile the final order state.

What you need before writing code

Kite Connect’s current documentation lists these core prerequisites:

  • an active Zerodha trading account;
  • two-factor authentication with TOTP enabled;
  • a Kite Connect developer app;
  • the app’s registered redirect URL;
  • an api_key and api_secret;
  • a server-side application for the login handshake and API calls.

The API is not designed to be called directly from browser JavaScript. Keep api_secret on the server. The access token is also sensitive and should never be published or placed in a Pine script or webhook message.

Understand the login lifecycle first

The documented login flow is interactive:

  1. Send the user to the public Kite login URL with the app’s api_key.
  2. After successful login, Kite redirects to the registered URL with a short-lived request_token.
  3. On the server, calculate the SHA-256 checksum of api_key + request_token + api_secret.
  4. Send the request token and checksum to /session/token.
  5. Store the returned access_token securely and use it in authenticated requests.

Kite’s documentation states that the access token normally expires at 6 AM the following day unless it is invalidated earlier. Design for a daily user login rather than trying to automate credentials or TOTP.

When the API returns a TokenException with an expired or invalid session, clear the application session and start the official login flow again. Do not keep retrying an invalid token.

A better TradingView webhook message

Pine Script should describe a signal, not contain broker credentials or place a broker order itself. The receiver decides whether the event is still valid and allowed.

This educational Pine v6 example emits a close-confirmed JSON event:

//@version=6
indicator("Confirmed webhook event example", overlay = true)

float fastEma = ta.ema(close, 10)
float slowEma = ta.ema(close, 30)
bool buySignal = ta.crossover(fastEma, slowEma) and barstate.isconfirmed

if buySignal
    string eventId = syminfo.tickerid + "-" + str.tostring(time) + "-BUY"
    string payload = "{\"event_id\":\"" + eventId +
        "\",\"action\":\"BUY\",\"ticker\":\"" + syminfo.tickerid +
        "\",\"timeframe\":\"" + timeframe.period +
        "\",\"bar_time\":" + str.tostring(time) + "}"
    alert(payload, alert.freq_once_per_bar_close)

plot(fastEma, "Fast EMA", color.teal)
plot(slowEma, "Slow EMA", color.orange)

The crossover is only an example payload trigger. It is not a trading recommendation. Create the TradingView alert with the intended symbol, timeframe, inputs, close-only frequency, and HTTPS webhook URL. If the code or inputs change, recreate the running alert because TradingView stores a server-side copy when the alert is created.

Validate before considering an order

Reject the request before it reaches the broker unless every required check passes. At minimum:

  • the request arrived over HTTPS;
  • the webhook has the expected authentication value or signed envelope;
  • content type and body size are allowed;
  • JSON matches an explicit schema;
  • event_id has not already been accepted;
  • action is in an allowlist;
  • symbol and exchange map to an approved instrument;
  • timeframe and event age are within the strategy’s rules;
  • market/session rule permits processing;
  • quantity is calculated on the server and is inside configured limits;
  • maximum daily loss, position, order-count, and notional controls permit the order;
  • a kill switch is not active;
  • the broker session is valid.

Do not trust a quantity or product value supplied by the webhook. A client message can be delayed, duplicated, malformed, or deliberately altered. Resolve instrument tokens and calculate quantity from controlled server-side configuration.

Make event handling idempotent

Trading alerts and HTTP clients can retry. A timeout does not prove that the broker rejected the request; the response may have been lost after the broker received it. Blindly retrying can create a duplicate order.

Use a stable event_id and an atomic record before order placement:

begin transaction
    if event_id already exists:
        return the recorded result

    save event_id with state = "accepted"
commit

run risk checks
place one broker request
save broker order_id and state = "submitted"
wait for order updates

If the order call times out, reconcile the order book and your application tag before deciding whether another request is safe. A client-generated event ID and a broker order tag help connect the signal, request, and final order record, but they do not replace reconciliation.

An order ID is not an executed trade

Kite’s order documentation makes an important distinction: a successful placement response returns an order_id, but the order’s final status is not known at that moment. Funds, risk checks, market hours, exchange receipt, price, and liquidity can still affect what happens next.

Track states such as:

  • accepted by your webhook;
  • rejected by validation or risk policy;
  • submitted to Kite;
  • open or pending;
  • partially filled;
  • complete;
  • rejected;
  • cancelled;
  • unknown and awaiting reconciliation.

For an individual developer, Kite recommends order updates over its WebSocket connection. Public multi-user apps can use the documented Postback webhook. Postback payloads include a checksum based on order_id + order_timestamp + api_secret; verify it before trusting the update.

Do not report “order complete” to a user merely because the placement endpoint returned HTTP success.

Use rate limits as design constraints

The current Kite exception documentation lists these limits:

OperationDocumented limit
Quote endpoint1 request per second
Historical candle endpoint3 requests per second
Order placement10 requests per second
Other endpoints10 requests per second
Orders400 per minute and 5,000 per day per user/API key
ModificationsMaximum 25 modifications per order

Limits can change, so link to the official page and verify them when this guide is reviewed. Build separate queues for market data and orders, use bounded exponential backoff for safe read requests, and respect 429 responses.

Do not automatically retry an order-placement timeout unless reconciliation proves the request was not accepted. Order writes require different retry logic from quote reads.

Handle failures by category

FailureSafer response
Invalid or expired tokenStop processing, clear the session, require official login
Schema or authentication failureReject and log without calling the broker
Duplicate event_idReturn the stored result; do not place another order
Margin, holding, or input errorMark rejected and notify with a safe summary
Rate limitQueue or back off according to operation type
OMS/network error on a writeMark outcome unknown, reconcile before retrying
WebSocket disconnectedReconnect with backoff and reconcile order state
Partial fillRecord filled and remaining quantities; apply the defined policy
Receiver or database unavailableFail closed; do not bypass validation

Each event needs timestamps, correlation IDs, safe error categories, and enough context to investigate without logging secrets. Redact authorization headers, tokens, raw credentials, and personal account data.

Security checklist

  • Keep api_secret and access tokens in a server-side secret store.
  • Restrict secret access to the component that needs it.
  • Use HTTPS and reject unexpected methods and content types.
  • Rate-limit the public webhook endpoint.
  • Authenticate webhook requests and rotate that credential safely.
  • Store only the personal data required for the service.
  • Encrypt sensitive stored data and backups.
  • Redact secrets from logs and error reports.
  • Separate test and live environments.
  • Use an explicit live-trading enable switch and emergency stop.
  • Notify the owner when login expires, processing stops, or order state is unknown.
  • Review dependencies and the official API changelog before releases.

A staged implementation plan

Stage 1: observe only

Receive and validate TradingView events, calculate the proposed action, and log what would happen. Send no broker request.

Stage 2: broker read access

Complete the official login and read profile, margins, instruments, and order state. Test token expiry and reconnection behavior.

Stage 3: controlled non-production testing

Exercise validation, duplicate handling, timeouts, stale events, partial data, and reconciliation without exposing real capital. Use a paper or demo workflow where available.

Stage 4: tightly limited live use

If the owner explicitly chooses live use, start with strict quantity and notional caps, an allowlist, a kill switch, and active monitoring. A successful backtest is not sufficient approval for live execution.

Frequently asked questions

Can Pine Script call Kite Connect directly?

Pine scripts do not securely hold a broker API secret or run a custom server-side login flow. Use a TradingView alert to send a minimal event to your HTTPS receiver, then let the server validate it and call the official broker API.

Should the webhook contain quantity?

Prefer calculating quantity on the server from controlled configuration and current risk limits. Treat every client-supplied value as untrusted.

Can I reuse the access token indefinitely?

No. The current Kite login documentation says the session token expires at 6 AM the next day unless invalidated earlier. Build a clear daily login and stopped-session state.

Should I retry every failed order call?

No. A network failure can leave the outcome unknown. Reconcile with broker order data and your stored event/tag before another order is considered.

Does an order_id mean the order filled?

No. It identifies the submitted order. Track WebSocket or Postback updates and the final order/trade data.

Primary sources

Leave a Reply

Your email address will not be published. Required fields are marked *