Position after each trade

running totals

Position after each trade

Zerodha SQL Interview Question

Zerodha has to know what every client is holding at any moment, because margin is charged on the position, not on the trades that built it. The log records buys and sells as separate rows, so a holding at any point is the buys so far minus the sells so far.

Return the client_id, the symbol, the traded_on date, the side of the trade, and the shares the client holds in that symbol immediately after it as position_after. Sort by client_id, then symbol, then traded_on.

Asked of

  • Data Analyst
  • Business Analyst
  • BI Analyst
  • Product Analyst
  • Analytics Engineer
  • Data Engineer
  • Data Scientist

zerodha_tradesTable21 rows

Column NameType
trade_idBIGINT
client_idVARCHAR
symbolVARCHAR
traded_onDATE
sideVARCHAR
quantityBIGINT
priceDOUBLE

zerodha_tradesExample Input

trade_idclient_idsymboltraded_onsidequantityprice
9001Z1001INFY2024-07-01buy1001450
9002Z1001TCS2024-07-02buy403800
9003Z1001INFY2024-07-03buy501480
9004Z1001INFY2024-07-05sell801520
9005Z1001TCS2024-07-06sell153950
9006Z1001INFY2024-07-08sell701495
9007Z1001TCS2024-07-09buy253870
9020Z1004INFY2024-07-02buy1501440
9021Z1004INFY2024-07-10sell1501530

Example Output

client_idsymboltraded_onsideposition_after
Z1001INFY2024-07-01buy100
Z1001INFY2024-07-03buy150
Z1001INFY2024-07-05sell70
Z1001INFY2024-07-08sell0
Z1001TCS2024-07-02buy40
Z1001TCS2024-07-06sell25
Z1001TCS2024-07-09buy50
Z1004INFY2024-07-02buy150
Z1004INFY2024-07-10sell0

Explanation

Z1001 buys 100 shares of INFY and holds 100. A second buy of 50 takes the holding to 150, a sale of 80 brings it down to 70, and a sale of 70 leaves nothing. The TCS holding is counted on its own and is never mixed in with INFY.

The example above is a small slice of the data. Your query runs against the full tables.