On this page
What the broker actually checks
Under the retail algo framework, Indian brokers with retail APIs now check where your orders come from. The rules behind it are in what SEBI's static IP rules require. This post is about the engineering side, which is running the strategy on Lambda, Cloud Run, Railway, or a cron container without tripping that check.
The first thing to know is that the check is narrow. Brokers apply it to order placement, not to every API call. That shapes the whole design, because it tells you which traffic needs the fixed IP and which does not.
| Broker | IP-checked | Not IP-checked | Token note |
|---|---|---|---|
| Zerodha Kite Connect | API order placement | WebSocket market data, order book, positions | Access token expires at 6 AM the next day |
| Upstox | Order placement | Not stated | Changing the IP invalidates the access token |
| Dhan | Orders, Super Order, Forever Order | Order and trade details | Token valid 24 hours |
| Kotak Neo | Place, modify, cancel order | Login, reports, portfolio, data, WebSocket | Session must be created from the IP that sends orders |
Sources for each row are Zerodha, Upstox, Dhan, and Kotak Neo. Each broker takes a primary IP and an optional secondary, and limits changes to about once a week. Zerodha also asks you to confirm the IP is used only by you or your immediate family, which rules out the shared pools most platforms hand out.
Why serverless egress fails the whitelist
A Lambda function outside a VPC, a Cloud Run service on default networking, and a Railway service all leave the internet from addresses the platform picks. Those addresses are shared with other tenants and change as instances come and go. The details per platform are in why serverless egress IPs change. For a broker, a changing IP means rejected orders, and a weekly change limit means you cannot chase it.
Each platform has a native way to pin the address, and each has a catch for this use case.
- AWS Lambda. Attach the function to private subnets and route
0.0.0.0/0to a NAT gateway with an Elastic IP. The NAT gateway bills by the hour in every Availability Zone you cover, before any traffic. See the hidden costs of a NAT gateway. - Google Cloud Run. Reserve a static address, create a Cloud Router and Cloud NAT, then deploy with Direct VPC egress and
--vpc-egress=all-traffic, per Google's guide. It works, and Cloud NAT bills separately. - Railway. Static Outbound IPs are on the Pro plan, but Railway's docs say there is no guarantee the addresses are dedicated, and they change if you move regions. A broker that asks for an IP used only by you is a poor match for an address that may be shared.
- A cron container on a VM. A VM with a reserved public IP is the simplest fix of all, but then you are running a server, not serverless. The tradeoffs are in home static IP vs VPS vs proxy.
The option that works the same on every platform is a static IP proxy. Your code sends selected requests through an HTTP CONNECT or SOCKS5 proxy, and the broker sees the proxy's address. Nothing about the platform's networking changes.
The latency budget from Mumbai
Retail strategies under the framework can send up to 10 orders per second per exchange segment without exchange registration, per Zerodha's summary of the NSE circular. Kite Connect itself caps order placement at 10 requests per second and 400 orders a minute, per its rate limit table. At that pace you are not racing colocated firms. You are trying to avoid adding hundreds of milliseconds you did not plan for.
The biggest number in the budget is distance. Put the code in Mumbai. Lambda has ap-south-1 and Cloud Run has asia-south1. Railway has no India region, and its nearest region is Singapore. A third-party benchmark puts AWS Singapore to Mumbai at about 63 ms of inter-region latency, and every order pays that if your code runs in Singapore.
The second number is connection setup. A request over a new HTTPS connection through a TLS-wrapped CONNECT proxy pays several round trips before the order leaves.
- TCP handshake to the proxy. One round trip to the proxy.
- TLS handshake to the proxy, when the proxy URL is
https://. One round trip with TLS 1.3. - The
CONNECTrequest and the proxy's200reply. One round trip to the proxy, plus the proxy's own TCP connect to the broker. - TLS handshake to the broker inside the tunnel. One full round trip from your code to the broker.
- The order request and response. One more full round trip.
On a kept-alive connection only the last step repeats. If the code and the proxy sit in the same city, steps 1 to 3 are short. If the code is in Singapore and the proxy in Mumbai, each of them crosses the sea. The mechanics are in how an HTTP CONNECT proxy works. The practical rules are to keep code, proxy, and broker in one city, and to reuse one client across invocations so warm calls pay only step 5.
Cold starts and where the strategy runs
A strategy has two shapes. One reacts to events, such as a scheduled entry at 9:20 or a signal from your own scanner. The other runs a loop through the session and reads ticks from a WebSocket. Pick the platform by the shape.
| Platform | Fits | Limit to plan around |
|---|---|---|
| AWS Lambda | Event-driven orders, scheduled entries and exits | 15-minute maximum per invocation |
| Cloud Run service | An HTTP endpoint that receives signals | Scales to zero unless you set minimum instances |
| Cloud Run job | A loop that runs the whole session | Task timeout up to 168 hours, 10 minutes by default |
| Railway cron | Short scheduled runs | UTC schedules, 5 minutes apart at least, overlapping runs skipped |
The limits come from Lambda quotas, Cloud Run minimum instances, Cloud Run task timeout, and Railway cron jobs. A tick loop does not belong on Lambda. A Cloud Run job started before the open, with its timeout set past 15:30, holds a WebSocket and a warm proxy connection for the whole session.
Keeping the first order fast
A cold start adds runtime and package load time before your handler runs. For an order at a fixed time, schedule a warm-up call a few minutes earlier that loads the token and opens the proxy connection. On Lambda, SnapStart supports Python 3.12 and later, Java, and .NET, but not Node.js, and provisioned concurrency keeps environments initialized for a fee. SnapStart has one catch here. AWS says connections opened during initialization are not guaranteed after a restore, so check or reopen the proxy connection in the handler. On Cloud Run, set --min-instances 1 on the service for market hours.
India has no daylight saving time, so IST is always UTC+5:30. That makes UTC-only schedulers easy. 09:10 IST is 03:40 UTC every day of the year.
# 09:10 IST, Monday to Friday, evaluated in Asia/Kolkata.
# MaximumRetryAttempts 0: a failed order run must not be replayed.
aws scheduler create-schedule \
--name entry-0910 \
--schedule-expression "cron(10 9 ? * MON-FRI *)" \
--schedule-expression-timezone "Asia/Kolkata" \
--flexible-time-window '{"Mode": "OFF"}' \
--target '{
"Arn": "arn:aws:lambda:ap-south-1:123456789012:function:entry",
"RoleArn": "arn:aws:iam::123456789012:role/scheduler-invoke",
"RetryPolicy": {"MaximumRetryAttempts": 0, "MaximumEventAgeInSeconds": 60}
}'
# Lambda's own async retries: off for the order function.
aws lambda put-function-event-invoke-config \
--function-name entry \
--maximum-retry-attempts 0# Railway schedules run in UTC. 03:40 UTC is 09:10 IST.
40 3 * * 1-5The schedule types page documents the six-field cron format and the --schedule-expression-timezone parameter used above.
Token refresh on a stateless platform
Broker tokens are short-lived by rule, and a function has nowhere to keep state between invocations. So the token lives in a secret store, a separate step refreshes it each morning, and the trading function reads it.
- Zerodha. The access token is valid until 6 AM the next day, per the Kite Connect user docs. Getting a new one needs the user to log in. Your backend then exchanges the
request_tokenwith a SHA-256 checksum at/session/token. An answer on the Kite Connect forum says the exchange requires a manual login at least once a day and does not recommend automating it. - Upstox. The token lasts until 3:30 AM the next day. The access token request flow fits serverless well. Your code sends the request, the user approves it in the Upstox app or on WhatsApp, and Upstox posts the token to the notifier webhook you set on the app. That webhook can be a small function that writes the token to your secret store.
- Dhan. A token from Dhan Web lasts 24 hours and can be renewed while it is still active, per the DhanHQ authentication docs. The API key flow uses a browser login with 2FA to produce a token.
Two IP details matter here. Kotak Neo validates the session against the IP that sends orders, so the login call must go through the same fixed egress as the orders. Upstox invalidates tokens when you change the registered IP, and Dhan says to regenerate the token if you added the IP after creating it. When a broker ties sessions to IPs, route the session call through the proxy too.
On AWS, SSM Parameter Store with a SecureString or Secrets Manager both work. Cache the value in memory for a few minutes and re-read it on an auth error. On Cloud Run, mount the token from Secret Manager as a volume, not an environment variable. Per Google's docs, Cloud Run fetches a secret env var once before the instance starts, but fetches a mounted secret from Secret Manager on every read. A token refreshed at 8:45 then reaches a job that started at 8:30.
Send only the order calls through the fixed IP
The tempting shortcut is HTTPS_PROXY on the whole function. Avoid it. Python's requests and boto3 read it, so your SSM and S3 calls would leave through the proxy too. Market data WebSockets can carry far more bytes than orders, and they do not need the fixed address at Zerodha, Kotak Neo, or Dhan. Give the proxy to the client that places orders and nothing else. How NO_PROXY and per-client agents behave covers the env var surprises in each language.
The Python client for Kite Connect takes a proxies dict in its constructor and passes it on every request, per its source. Create two clients at module scope, one proxied for orders and one direct for data, so warm invocations reuse their connections.
# requirements.txt: kiteconnect
import os
import time
import boto3
from kiteconnect import KiteConnect
from kiteconnect.exceptions import TokenException
PROXY = os.environ["FIXEDMARK_PROXY_URL"] # not HTTPS_PROXY: boto3 reads that
API_KEY = os.environ["KITE_API_KEY"]
TOKEN_PARAM = os.environ["KITE_TOKEN_PARAM"] # SSM SecureString
ssm = boto3.client("ssm") # direct, no proxy
# Orders leave through the registered IP. Data goes direct.
orders = KiteConnect(api_key=API_KEY, timeout=5,
proxies={"http": PROXY, "https": PROXY})
data = KiteConnect(api_key=API_KEY, timeout=5)
_token = {"value": None, "read_at": 0.0}
def load_token(force=False):
if not force and _token["value"] and time.time() - _token["read_at"] < 300:
return
value = ssm.get_parameter(Name=TOKEN_PARAM, WithDecryption=True)["Parameter"]["Value"]
orders.set_access_token(value)
data.set_access_token(value)
_token.update(value=value, read_at=time.time())
def tick_round(price, tick=0.05):
return round(round(price / tick) * tick, 2)
def handler(event, context):
load_token()
tag = event["tag"] # unique per intended order, 20 chars max
# Never place twice: an earlier attempt may have reached the exchange.
if any(o.get("tag") == tag for o in orders.orders()):
return {"skipped": tag}
ltp = data.ltp(["NSE:INFY"])["NSE:INFY"]["last_price"]
try:
order_id = orders.place_order(
variety=orders.VARIETY_REGULAR,
exchange=orders.EXCHANGE_NSE,
tradingsymbol="INFY",
transaction_type=orders.TRANSACTION_TYPE_BUY,
quantity=1,
product=orders.PRODUCT_CNC,
order_type=orders.ORDER_TYPE_LIMIT,
price=tick_round(ltp * 0.995),
tag=tag,
)
except TokenException:
load_token(force=True) # someone may have refreshed it; alert, do not retry blindly
raise
return {"order_id": order_id}// npm install undici (undici 8 needs Node.js 22.19+)
import { fetch, ProxyAgent } from "undici";
// One agent at module scope, reused by warm invocations.
const viaFixedIp = new ProxyAgent(process.env.FIXEDMARK_PROXY_URL);
const KITE = "https://api.kite.trade";
function headers(accessToken) {
return {
"X-Kite-Version": "3",
Authorization: `token ${process.env.KITE_API_KEY}:${accessToken}`,
};
}
// Data: direct, no dispatcher.
export async function lastPrice(accessToken, key) {
const url = `${KITE}/quote/ltp?i=${encodeURIComponent(key)}`;
const res = await fetch(url, { headers: headers(accessToken) });
const body = await res.json();
return body.data[key].last_price;
}
// Orders: through the registered IP.
export async function placeLimit(accessToken, order) {
const res = await fetch(`${KITE}/orders/regular`, {
method: "POST",
dispatcher: viaFixedIp,
headers: headers(accessToken),
body: new URLSearchParams({
exchange: "NSE",
tradingsymbol: order.symbol,
transaction_type: order.side,
quantity: String(order.quantity),
product: "CNC",
order_type: "LIMIT",
price: order.price.toFixed(2),
validity: "DAY",
tag: order.tag,
}),
});
const body = await res.json();
if (body.status !== "success") {
throw new Error(`${res.status} ${body.error_type}: ${body.message}`);
}
return body.data.order_id;
}The Python sketch reads the order book through the proxied client before placing, because that client holds the same token and the call is cheap. Kite rejects an expired session with a 403 and a TokenException, per its exception docs, so that error means a token problem, not an IP problem. When the IP is the problem, the message differs per broker. Fixing IP not whitelisted errors lists them.
Prove the egress before market hours
Deploy a one-off check that calls an IP echo service through the same proxy config as the order client, and compare the result with the IPs registered at the broker. Run it from the real platform, not your laptop, because the platform is what the broker sees.
import os
import requests
proxy = os.environ["FIXEDMARK_PROXY_URL"]
print("via proxy:", requests.get("https://fixedmark.com/api/ip",
proxies={"http": proxy, "https": proxy},
timeout=10).text)
print("direct: ", requests.get("https://fixedmark.com/api/ip", timeout=10).text)Doing this with Fixedmark
Fixedmark is a static IP proxy built for this pattern. It is in early access, and the prices below are planned launch prices that may change.
- A dedicated pair of IPv4 addresses in Mumbai, near the brokers and the Lambda and Cloud Run regions you would use anyway. Register one as the primary IP and one as the secondary. Why brokers ask for primary and secondary IPs explains the slots.
- One proxy URL in
FIXEDMARK_PROXY_URL, passed only to the order client, exactly as in the code above. Per-language setup is in the Python and Node.js docs. - On Business and larger plans, a destination allowlist on the token, such as
api.kite.tradeon port 443, so a leaked proxy token cannot reach anything else. - Connection logs that show the destination, egress IP, and result of each connection, which helps when an order is rejected at 9:15.
- TLS passes through end to end. Fixedmark never sees your API key, access token, or orders.
The planned India Trader plan includes 5 GB of bandwidth a month in Mumbai. Order traffic fits easily in that, which is one more reason to keep market data on the direct path. See planned India pricing. The trial and Starter run on a shared pair, so do not register their addresses with a broker. Broker-by-broker steps are in the broker guides.
Sources
Checked November 2026. Confirm current details on the vendor's site before you decide. Prices and limits change.
- Zerodha support: static IP for Kite Connect
- Kite Connect docs: user and session
- Kite Connect docs: exceptions and rate limits
- pykiteconnect: connect.py source
- Upstox docs: My Apps support for the algo trading circular
- Upstox docs: access token request
- DhanHQ docs: authentication
- Dhan support: DH-905 invalid IP on API orders
- Kite Connect forum: automating the Kite Connect login
- Google Cloud docs: Cloud Run secrets
- Kotak Neo: static IP details
- Zerodha Z-Connect: overview of NSE's retail algo framework
- AWS docs: Lambda quotas
- AWS docs: Lambda async error handling and retries
- AWS docs: invoke a Lambda function on a schedule
- AWS docs: EventBridge Scheduler schedule types
- AWS docs: Lambda SnapStart
- Google Cloud docs: Cloud Run static outbound IP
- Google Cloud docs: Cloud Run minimum instances
- Google Cloud docs: Cloud Run task timeout
- Railway docs: deployment regions
- Railway docs: static outbound IPs
- Railway docs: cron jobs
- Economize: AWS latency, ap-southeast-1 to ap-south-1

