Subscribe

Cleaning up orphaned GTT orders in Zerodha using Python

A Zerodha GTT does not know its stock was sold, and if it fires later it sells short in delivery. Here is the Python script I use to find orphaned GTTs, delete them after a dry run, and trail the stop on the ones that are left.

Cleaning up orphaned GTT orders in Zerodha using Python

A while back I wrote a post on cleaning up unused security groups in AWS with golang. This one is the same idea, but for Zerodha GTT orders. Things you created for a reason, the reason went away, and nobody deleted them.

A GTT (good till triggered) sits on Zerodha's side and places an order when price crosses a trigger. I use them as stop and target for delivery (CNC) holdings. The catch is that a GTT does not know its stock was sold. Sell the holding by hand, or let a different GTT fire, and the old one stays there. Zerodha won't remove it for you.

In this blog we will look at why that's dangerous and the small Python script I use to find and delete them, plus how the same script trails the stop on the GTTs that are still valid.

As always with these trading posts, this is about the code and order mechanics. It's not investment advice.

Why an orphan is not harmless

My first thought was that an orphaned GTT is just clutter. It's not. It looks like protection in the GTT tab, and if it fires it places a real SELL order in CNC for stock you no longer hold. That's a short sale in the delivery segment. A short delivery doesn't square off at the end of the day like MIS does. The exchange settles it through an auction and you pay a penalty on top.

The stop loss leg is the one to worry about. It fires on a fall, and a fall is exactly when you're not watching your old GTTs.

Talking to Kite

The script uses the Kite Connect REST API directly with urllib. Every request carries X-Kite-Version: 3 and an Authorization header built from your API key and the day's access token.

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

AUTH = "token {}:{}".format(os.environ["KITE_API_KEY"],
                            os.environ["KITE_ACCESS_TOKEN"])


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,
                                 method=method,
                                 headers={"X-Kite-Version": "3",
                                          "Authorization": AUTH})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)["data"]

The four calls we need are GET /gtt/triggers, GET /portfolio/holdings, GET /portfolio/positions and DELETE /gtt/triggers/{id}.

Working out what you actually own

This is the part I got wrong first. My first version only looked at quantity in holdings. That's settled stock. Stock you bought yesterday isn't settled yet, it sits in t1_quantity. You own it and you can sell it, but quantity says zero.

So the script reported six live GTTs as orphaned and two more as oversized, when every one of them was sized correctly. If I had run it with delete on, it would have removed real stop losses on positions I'd opened the day before. That one scared me a bit.

The fix is to add three things together: settled quantity, T1 quantity and today's CNC buys or sells from positions. MIS is left out because it squares off on its own and isn't deliverable.

def owned_delivery():
    holdings = {h["tradingsymbol"]: h for h in api("/portfolio/holdings")}
    cnc = {p["tradingsymbol"]: p["quantity"]
           for p in api("/portfolio/positions")["net"]
           if p["product"] == "CNC" and p["quantity"]}
    out = {}
    for sym in set(holdings) | set(cnc):
        h = holdings.get(sym)
        held = h["quantity"] + h["t1_quantity"] if h else 0
        qty = held + cnc.get(sym, 0)
        if qty > 0:
            out[sym] = qty
    return out

Finding the orphans

Now we go through the active GTTs and compare them with what's owned.

There's one more detail here. I keep two OCO GTTs per holding, half the quantity each, with different targets but the same stop. So if price falls through the stop, both stop legs fire together. You can't check each GTT on its own against the holding. You have to add up the stop leg quantities per symbol, and compare the total.

def clean(apply_):
    active = [g for g in api("/gtt/triggers") if g["status"] == "active"]
    owned = owned_delivery()

    per_sym = {}
    for g in active:
        sym = g["condition"]["tradingsymbol"]
        d = per_sym.setdefault(sym, {"gtts": [], "stopqty": 0})
        d["gtts"].append(g)
        d["stopqty"] += g["orders"][0]["quantity"]

    orphans = []
    for sym, d in sorted(per_sym.items()):
        have = owned.get(sym, 0)
        if have <= 0:
            orphans.extend(d["gtts"])
        elif d["stopqty"] > have:
            print(f"OVERSIZED {sym}: stop legs sell {d['stopqty']}, holding {have}")

    for g in orphans:
        stop, target = g["condition"]["trigger_values"]
        print(f"ORPHAN id {g['id']:<10} {g['condition']['tradingsymbol']:<12} "
              f"qty {g['orders'][0]['quantity']:>5} stop {stop:>9.2f} target {target:>9.2f}")

    if not orphans:
        print("no orphans, every live GTT has a holding behind it")
    elif apply_:
        for g in orphans:
            api(f"/gtt/triggers/{g['id']}", "DELETE")
            print(f"deleted {g['id']}")
    else:
        print("dry run. Re-run with --clean --create to delete. It can't be undone.")


if __name__ == "__main__":
    if "--clean" in sys.argv:
        clean("--create" in sys.argv)

Oversized ones only get reported. Fixing those is a modify, not a delete, and which of the two GTTs to shrink depends on how you planned your exits. I didn't want the script guessing.

Running it is the same two step thing I do with security group cleanup.

export KITE_API_KEY=your_api_key
export KITE_ACCESS_TOKEN=todays_access_token
python3 holdings_gtt.py --clean
python3 holdings_gtt.py --clean --create

Read the first output properly before running the second. Deleting a GTT is final.

The output looks something like this (made up symbols and numbers).

OVERSIZED TCS: stop legs sell 30, holding 20
ORPHAN id 123456     INFY         qty    25 stop   1402.50 target   1561.00
ORPHAN id 123457     INFY         qty    25 stop   1402.50 target   1620.40
dry run. Re-run with --clean --create to delete. It can't be undone.

Trailing the stop on the GTTs that stay

Once the orphans are gone, the same script keeps the remaining stops moving up. Zerodha GTTs have no trailing stop built in. The trigger is a fixed price. So "trailing" here means working out a new level and modifying the GTT. A GTT you never modify is not a trailing stop, whatever you call it.

I use a chandelier stop. Take the highest daily close since entry and subtract two times ATR(14). Closes, not intraday highs, so one spike can't drag the stop up to a level the stock never actually held. Once the position is one ATR in profit, the stop is at least the average price. And the stop is always kept at least one ATR below the last price.

TRAIL_ATR, MIN_ATR, BREAKEVEN, RATCHET_ATR = 2.0, 1.0, 1.0, 0.3


def snap(price, tick):
    return round(round(price / tick) * tick, 2)


def new_stop(closes_since_entry, ltp, avg, atr, tick):
    stop = max(closes_since_entry + [ltp]) - TRAIL_ATR * atr
    if ltp - avg >= BREAKEVEN * atr:
        stop = max(stop, avg)
    stop = min(stop, ltp - MIN_ATR * atr)
    return snap(stop, tick)


live_stop = 1402.50
stop = new_stop([1450.0, 1478.5, 1502.0, 1496.0], ltp=1499.0,
                avg=1440.0, atr=22.0, tick=0.05)
move = stop - live_stop
print(stop, "MODIFY" if move >= RATCHET_ATR * 22.0 else "hold")

That prints 1458.0 MODIFY. The script only modifies a GTT when the new stop is at least 0.3 ATR above the live one. It saves a pile of tiny API calls, and since it only ever acts when the move is upward, the stop never goes down.

The modify is a PUT /gtt/triggers/{id} with the full GTT again: a two-leg type, the condition with both trigger values (stop first, then target) and the two SELL LIMIT orders as JSON strings. I put the limit price half a percent under the trigger so the order has room to fill on a fast drop.

import json


def gtt_body(sym, qty, ltp, stop, target, tick):
    def leg(trigger):
        return {"exchange": "NSE", "tradingsymbol": sym,
                "transaction_type": "SELL", "quantity": qty,
                "order_type": "LIMIT", "product": "CNC",
                "price": snap(trigger * 0.995, tick)}
    return {"type": "two-leg",
            "condition": json.dumps({"exchange": "NSE", "tradingsymbol": sym,
                                     "trigger_values": [stop, target],
                                     "last_price": ltp}),
            "orders": json.dumps([leg(stop), leg(target)])}


print(gtt_body("INFY", 25, 1499.0, 1458.0, 1561.0, 0.05))

A price that isn't a multiple of the stock's tick size gets rejected with a 400. Snap everything. I read tick sizes from the instruments dump at https://api.kite.trade/instruments/NSE rather than assuming 0.05, because they're not all the same.

When to run it

Run --clean on any day a delivery holding gets sold, and after any GTT fires. Delete only after the dry run looks right. The script doesn't care how the stock left, sold by hand, sold by a GTT or rotated out by one of my jobs. If the holding is zero and the GTT is still active, it's an orphan.