Subscribe

Building OCO orders on Zerodha Kite with a Python watcher

Regular Kite orders have no one-cancels-other, so a stop and a target placed together can leave you in a fresh position the other way. Here is the small Python watcher I run to cancel or shrink the surviving leg.

Building OCO orders on Zerodha Kite with a Python watcher

When I enter a trade on Zerodha I want two exits sitting in the book: a stop loss below and a target above (the other way round for a short). Some brokers give you a one-cancels-other order for this. Regular Kite orders don't have it. You place two separate orders, and when one fills the other is still live.

That sounds like a small thing. It isn't. In this blog we will look at what goes wrong and the small Python watcher I wrote to fix it.

This is not investment advice. It's about order mechanics and code.

How it bit me

Say you are long 50 shares of INFY. You place a SELL SL at 1480 and a SELL LIMIT at 1530. Price runs up, the target fills, you are flat. Good. But the SL for 50 shares is still sitting there. If price later falls back through 1480 it triggers, and now you are short 50 shares in a stock you just finished trading.

That happened six times in two days on my account, in September, on six different stocks. Each time I had placed both legs because it felt like the safe thing to do. Without something watching, both legs is actually the worst setup you can have. With something watching, it's the best.

What the watcher has to do

I wrote down the rules first, before any code. Every few seconds it should do this.

  1. Read the order book and the net position of every symbol.
  2. Find exit pairs. Same symbol, same product, same transaction type, one SL or SL-M and one LIMIT.
  3. If one leg filled, cancel the other.
  4. If the position got smaller (a partial exit), shrink whatever is still bigger than the position.

And one rule about itself. It never places an order and never widens a stop. It only cancels and shrinks. If it has a bug, the worst case is I'm left without a stop, which I can see in the order book. It can't open something I didn't ask for.

The "same transaction type" part is how it tells exits apart without any tagging. Both exits of a long are SELL orders. Both exits of a short are BUY. An entry order sitting next to an exit points the other way, so it never gets paired.

Talking to Kite

My script talks to the Kite Connect REST API with plain urllib, not the kiteconnect package. It only needs a handful of calls, so the standard library is enough. Every call needs two headers. The access token is the one you get after the daily login. I keep mine in a database, here it's just an env var.

#!/usr/bin/env python3
import argparse
import json
import os
import time
import urllib.parse
import urllib.request

HDR = {
    "X-Kite-Version": "3",
    "Authorization": "token {}:{}".format(
        os.environ["KITE_API_KEY"], os.environ["KITE_ACCESS_TOKEN"]),
}

OPEN_STATES = {"OPEN", "TRIGGER PENDING", "OPEN PENDING",
               "VALIDATION PENDING", "MODIFY PENDING"}
STOP_TYPES = {"SL", "SL-M"}
TARGET_TYPES = {"LIMIT"}


def api(path, method="GET", body=None):
    data = urllib.parse.urlencode(body).encode() if body else None
    req = urllib.request.Request("https://api.kite.trade" + path,
                                 data=data, headers=HDR, method=method)
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)["data"]


def net_positions():
    """(symbol, product) -> signed net quantity, skipping flat ones."""
    return {(p["tradingsymbol"], p["product"]): p["quantity"]
            for p in api("/portfolio/positions")["net"] if p["quantity"]}

GET /orders gives the day's order book. GET /portfolio/positions gives net and day lists, I only use net. Cancelling is DELETE /orders/regular/{order_id} and modifying is PUT on the same path.

Watch the list of open states. A stop that hasn't triggered yet shows up as TRIGGER PENDING, not OPEN. If you only check for OPEN you won't see a single stop.

Finding the pairs

def exit_pairs(orders):
    groups = {}
    for o in orders:
        key = (o["tradingsymbol"], o["product"], o["transaction_type"])
        groups.setdefault(key, []).append(o)

    pairs = []
    for key, group in groups.items():
        stops = [o for o in group if o["order_type"] in STOP_TYPES]
        targets = [o for o in group if o["order_type"] in TARGET_TYPES]
        for s in stops:
            for t in targets:
                pairs.append((key, s, t))
    return pairs

Nothing clever. Group, then pair every stop with every target in the group.

One pass of the watcher

All cancels and modifies go through one function. That way dry run really is dry, there is no other code path that can touch an order.

def act(apply_, what, order_id, body=None):
    if not apply_:
        return "(dry run)"
    if what == "cancel":
        api(f"/orders/regular/{order_id}", "DELETE")
        return "CANCELLED"
    api(f"/orders/regular/{order_id}", "PUT", body)
    return "RESIZED"

My first idea for rule 3 was to look inside each pair for a COMPLETE leg. The trouble is the order book has the whole day in it. A target that filled at 10 in the morning is still COMPLETE at 2 in the afternoon, and it would happily pair with the stop of a brand new trade on the same stock and cancel it. So I check the position instead. When one leg fills fully on an MIS trade, the net position goes to zero, and anything still resting against a flat position is the leftover leg.

def sweep(apply_):
    orders = api("/orders")
    positions = net_positions()
    live = [o for o in orders if o["status"] in OPEN_STATES]
    traded = {(o["tradingsymbol"], o["product"]) for o in orders
              if o["status"] == "COMPLETE" and o.get("filled_quantity")}
    acted = 0

    # 1. a leg filled and the MIS position is flat: cancel what is left
    for o in live:
        key = (o["tradingsymbol"], o["product"])
        if key in positions or key not in traded:
            continue
        if o["product"] != "MIS":
            continue
        if o["order_type"] not in STOP_TYPES | TARGET_TYPES:
            continue
        r = act(apply_, "cancel", o["order_id"])
        print(f"  {o['tradingsymbol']:<12} {o['order_type']:<5} "
              f"qty {o['quantity']} against a FLAT position -> {r}")
        acted += 1

    # 2. partial exit: shrink whatever is bigger than the position
    for (sym, product, side), stop, tgt in exit_pairs(live):
        held = abs(positions.get((sym, product), 0))
        if not held:
            continue
        for o in (stop, tgt):
            if o["quantity"] <= held:
                continue
            body = {"quantity": held, "order_type": o["order_type"],
                    "validity": o.get("validity", "DAY")}
            if o["order_type"] in STOP_TYPES and o.get("trigger_price"):
                body["trigger_price"] = o["trigger_price"]
            if o["order_type"] == "LIMIT" and o.get("price"):
                body["price"] = o["price"]
            r = act(apply_, "modify", o["order_id"], body)
            print(f"  {sym:<12} {o['order_type']:<5} qty {o['quantity']} "
                  f"vs {held} held -> {r}")
            acted += 1

    if not acted:
        print(f"  nothing to do, {len(live)} live order(s)")
    return acted

Two filters in step 1 are there on purpose. The symbol must have had a fill today, otherwise a flat symbol never had a position at all and its resting LIMIT is an entry waiting to fill, not a leftover exit. And it only acts on MIS. For CNC I can't tell an entry from an exit on a flat symbol, so I leave those alone. For MIS, flat plus a fill today means the trade is done and nothing should still be resting.

The partial case is the one people forget. Say I scale out half at the first target. The position is now 25 but the stop is still for 50. If price drops, that stop sells 50 and I'm short 25. So the watcher doesn't cancel the stop there, it resizes it down to 25. The PUT body sends the quantity plus the trigger price or limit price it already had, so nothing else about the order changes.

The loop

Dry run is the default. You have to say --apply to touch anything.

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--apply", action="store_true", help="actually cancel/resize")
    ap.add_argument("--once", action="store_true", help="one pass, then exit")
    ap.add_argument("--interval", type=int, default=5)
    ap.add_argument("--until", default="15:20", help="stop at this IST time")
    args = ap.parse_args()

    print("APPLY" if args.apply else "DRY RUN, nothing will be cancelled")
    while True:
        print(f"[{time.strftime('%H:%M:%S')}]")
        try:
            sweep(args.apply)
        except Exception as e:
            print(f"  sweep failed: {e}")
        if args.once or time.strftime("%H:%M") >= args.until:
            return
        time.sleep(args.interval)


if __name__ == "__main__":
    main()

It stops at 15:20 by default because that's when Zerodha starts squaring off MIS positions itself. The try around each sweep matters. One timeout from the API should not kill the watcher for rest of the day, it just prints and tries again in five seconds. The time check uses the machine's clock, so run it on a box set to IST.

Running it looks like this.

export KITE_API_KEY=your_api_key
export KITE_ACCESS_TOKEN=todays_access_token
python3 oco_watch.py --once
python3 oco_watch.py --apply

Do one --once dry run after placing the exits. If the output says what you expect, start it again with --apply and leave it running till the close.

Things I'd watch out for

Five seconds is a gap. If the target fills and price comes all the way back through the stop inside that gap, both legs fill. On liquid stocks that's rare, on a thin stock less so. You can go lower on the interval, but Kite has rate limits on the API, so don't go silly with it.

Also, the watcher has to be running. Both legs with nothing watching is exactly the setup that caused those six reverse positions. So starting the watcher has to be part of the same habit as placing the exits, not something you remember later.

GTTs are a separate story. They're CNC only and live outside the regular order book, so this script doesn't look at them. I have a different script for those.