Skip to content
Fixedmark

Algo trading · 11 min read

Updated

Algo Trading on Serverless With a Static IP

Indian brokers check the source IP on order placement, and serverless platforms do not give you a fixed one by default. Run the strategy in Mumbai, send the order calls (and any session call the broker ties to an IP) through a fixed egress IP you registered, and keep market data and cloud API calls on the direct path.

On this page

What the broker actually checks

This post is general technical information, not legal, regulatory, or investment advice. Confirm your broker's current rules before you register an IP or change how you trade.

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.

What each broker's own documentation says the IP check covers
BrokerIP-checkedNot IP-checkedToken note
Zerodha Kite ConnectAPI order placementWebSocket market data, order book, positionsAccess token expires at 6 AM the next day
UpstoxOrder placementNot statedChanging the IP invalidates the access token
DhanOrders, Super Order, Forever OrderOrder and trade detailsToken valid 24 hours
Kotak NeoPlace, modify, cancel orderLogin, reports, portfolio, data, WebSocketSession 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/0 to 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.

  1. TCP handshake to the proxy. One round trip to the proxy.
  2. TLS handshake to the proxy, when the proxy URL is https://. One round trip with TLS 1.3.
  3. The CONNECT request and the proxy's 200 reply. One round trip to the proxy, plus the proxy's own TCP connect to the broker.
  4. TLS handshake to the broker inside the tunnel. One full round trip from your code to the broker.
  5. 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.

Matching the strategy shape to the platform
PlatformFitsLimit to plan around
AWS LambdaEvent-driven orders, scheduled entries and exits15-minute maximum per invocation
Cloud Run serviceAn HTTP endpoint that receives signalsScales to zero unless you set minimum instances
Cloud Run jobA loop that runs the whole sessionTask timeout up to 168 hours, 10 minutes by default
Railway cronShort scheduled runsUTC 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
Retries are the serverless trap for trading. EventBridge Scheduler invokes Lambda asynchronously, and by default Lambda retries a failed async invocation twice. AWS also warns that the same event can arrive more than once. An order call that timed out may still have reached the exchange. Turn retries off for order functions, tag each order, and check the order book for that tag before you place it again.

The 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_token with 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}

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.

check_egress.py
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.trade on 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.

Each new connection through a Fixedmark pair can leave from either IP, so register both with the broker. Kotak Neo needs the session created from the IP that sends the orders, so ask Fixedmark support before you rely on the pair with Kotak Neo.

Sources

Checked November 2026. Confirm current details on the vendor's site before you decide. Prices and limits change.

Blog

Frequently asked questions

Can I run an algo trading bot on AWS Lambda in India?

Yes, for event-driven strategies. Run it in ap-south-1 (Mumbai), send order calls through a fixed IP you registered with the broker, and turn off async retries for any function that places orders. A tick-by-tick loop does not fit Lambda's 15-minute limit.

Do market data calls need the static IP?

Not at most brokers. Zerodha, Kotak Neo, and Dhan apply the IP check to order placement. Zerodha and Kotak Neo say WebSocket data works from any IP. Check your broker's page, since rules differ.

Is Railway's static outbound IP enough for a broker?

Railway's docs say its static IPs are not guaranteed to be dedicated. Brokers such as Zerodha ask you to confirm the IP is used only by you or your family, so a possibly shared address is a risk.

Should I set HTTPS_PROXY on my function?

No. Python requests and boto3 read it, so cloud API calls would go through the proxy too. Use a dedicated variable such as FIXEDMARK_PROXY_URL and pass it only to the order client.

Can I automate the daily broker login?

It depends on the broker. Upstox has an access token request flow that delivers the token to a webhook after the user approves it. Zerodha's moderators say a manual login once a day is an exchange requirement and do not recommend automating it.

Make it fixed.

Fixedmark is in early access. Join the list to get dedicated static IPs when your region opens.