I built almost exactly this for my own Upstox account (a max-trades rule that closes everything and turns on Upstox’s kill switch), so here is what I ran into. Counting the 7th BUY. Use the trade book, but count orders, not rows: one order that fills in parts gives several trade rows with the same order_id.