-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrading_client.py
More file actions
506 lines (416 loc) · 17 KB
/
Copy pathtrading_client.py
File metadata and controls
506 lines (416 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#!/usr/bin/env python3
"""
Trading Client — Groww API wrapper for portfolio management and order execution.
Companion to stock_analyser.py (which handles analysis via yfinance + TA-Lib).
Usage:
python trading_client.py holdings # View DEMAT holdings
python trading_client.py positions # View open positions
python trading_client.py margin # Check available margin
python trading_client.py quote ONGC # Live quote with depth
python trading_client.py ltp ONGC TCS RELIANCE # LTP for multiple stocks
python trading_client.py search "reliance" # Search instruments
python trading_client.py buy ONGC 100 --price 265 # Place limit buy
python trading_client.py buy ONGC 100 # Place market buy
python trading_client.py sell ONGC 100 --price 290 # Place limit sell
python trading_client.py option-chain NIFTY 2026-03-27 # Option chain with Greeks
python trading_client.py greeks NIFTY NIFTY26MAR22000CE 2026-03-27 # Greeks for specific contract
Environment:
GROWW_API_KEY — from Groww developer console
GROWW_API_SECRET — TOTP secret for auto-authentication
Set these in ~/.claude/trading/.env or export them.
"""
import os
import sys
import json
import time
import argparse
from pathlib import Path
from typing import Optional
# Load .env from trading directory
ENV_PATH = Path.home() / ".claude" / "trading" / ".env"
if ENV_PATH.exists():
for line in ENV_PATH.read_text().splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, _, value = line.partition("=")
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
def get_client():
"""Get authenticated Groww API client."""
try:
import pyotp
from growwapi import GrowwAPI
except ImportError:
print(json.dumps({"error": "Missing dependencies. Run: pip install growwapi pyotp"}))
sys.exit(1)
api_key = os.environ.get("GROWW_API_KEY")
api_secret = os.environ.get("GROWW_API_SECRET")
if not api_key or not api_secret:
print(json.dumps({
"error": "GROWW_API_KEY and GROWW_API_SECRET not set.",
"hint": f"Create {ENV_PATH} with:\nGROWW_API_KEY=your_key\nGROWW_API_SECRET=your_totp_secret"
}))
sys.exit(1)
totp = pyotp.TOTP(api_secret).now()
try:
access_token = GrowwAPI.get_access_token(api_key=api_key, totp=totp)
# Suppress "Ready to Groww!" print from SDK
import io, contextlib
with contextlib.redirect_stdout(io.StringIO()):
client = GrowwAPI(access_token)
return client
except Exception as e:
print(json.dumps({"error": f"Authentication failed: {e}"}))
sys.exit(1)
def _fmt_amount(val):
if val is None:
return "N/A"
try:
return f"{float(val):,.2f}"
except (TypeError, ValueError):
return str(val)
# ─── Commands ─────────────────────────────────────────────────────────────────
def cmd_holdings(args):
"""Fetch DEMAT holdings."""
client = get_client()
response = client.get_holdings_for_user()
holdings = response.get("holdings", [])
result = []
total_value = 0
total_pnl = 0
for h in holdings:
current_value = float(h.get("current_value", 0))
pnl = float(h.get("pnl", 0))
total_value += current_value
total_pnl += pnl
result.append({
"symbol": h.get("trading_symbol"),
"exchange": h.get("exchange"),
"quantity": h.get("quantity"),
"avg_price": h.get("average_price"),
"ltp": h.get("ltp"),
"current_value": round(current_value, 2),
"pnl": round(pnl, 2),
"pnl_pct": round(float(h.get("pnl_percentage", 0)), 2),
})
print(json.dumps({
"holdings": result,
"total_value": round(total_value, 2),
"total_pnl": round(total_pnl, 2),
"count": len(result),
}, indent=2))
def cmd_positions(args):
"""Fetch open positions."""
client = get_client()
segment = getattr(args, "segment", None)
response = client.get_positions_for_user(segment=segment)
positions = response.get("positions", [])
result = []
total_pnl = 0
for p in positions:
pnl = float(p.get("pnl", 0))
total_pnl += pnl
result.append({
"symbol": p.get("trading_symbol"),
"exchange": p.get("exchange"),
"segment": p.get("segment"),
"net_qty": p.get("net_quantity"),
"avg_price": p.get("average_price"),
"ltp": p.get("ltp"),
"pnl": round(pnl, 2),
"product": p.get("product"),
})
print(json.dumps({
"positions": result,
"total_pnl": round(total_pnl, 2),
"count": len(result),
}, indent=2))
def cmd_margin(args):
"""Check available margin."""
client = get_client()
response = client.get_available_margin_details()
equity = response.get("equity_margin_details", {})
fno = response.get("fno_margin_details", {})
print(json.dumps({
"clear_cash": response.get("clear_cash"),
"net_margin_used": response.get("net_margin_used"),
"collateral_available": response.get("collateral_available"),
"equity": {
"cnc_available": equity.get("cnc_balance_available"),
"mis_available": equity.get("mis_balance_available"),
"cnc_used": equity.get("cnc_margin_used"),
"mis_used": equity.get("mis_margin_used"),
},
"fno": {
"future_available": fno.get("future_balance_available"),
"option_buy_available": fno.get("option_buy_balance_available"),
"option_sell_available": fno.get("option_sell_balance_available"),
"span_used": fno.get("span_margin_used"),
"exposure_used": fno.get("exposure_margin_used"),
},
}, indent=2))
def cmd_quote(args):
"""Live quote with market depth."""
client = get_client()
symbol = args.symbol.upper()
exchange = args.exchange or "NSE"
segment = args.segment or "CASH"
response = client.get_quote(
trading_symbol=symbol,
exchange=exchange,
segment=segment,
)
ohlc = response.get("ohlc", {})
print(json.dumps({
"symbol": symbol,
"exchange": exchange,
"ltp": response.get("last_price"),
"change": response.get("day_change"),
"change_pct": response.get("day_change_perc"),
"open": ohlc.get("open"),
"high": ohlc.get("high"),
"low": ohlc.get("low"),
"close": ohlc.get("close"),
"volume": response.get("volume"),
"bid": response.get("bid_price"),
"ask": response.get("offer_price"),
"bid_qty": response.get("bid_quantity"),
"ask_qty": response.get("offer_quantity"),
"upper_circuit": response.get("upper_circuit_limit"),
"lower_circuit": response.get("lower_circuit_limit"),
"open_interest": response.get("open_interest"),
"oi_change": response.get("oi_day_change"),
"oi_change_pct": response.get("oi_day_change_percentage"),
"implied_volatility": response.get("implied_volatility"),
"52w_high": response.get("week_52_high"),
"52w_low": response.get("week_52_low"),
"depth": response.get("depth"),
}, indent=2))
def cmd_ltp(args):
"""LTP for multiple instruments."""
client = get_client()
segment = args.segment or "CASH"
symbols = []
for s in args.symbols:
s = s.upper()
if "_" not in s:
symbols.append(f"NSE_{s}")
else:
symbols.append(s)
response = client.get_ltp(
exchange_trading_symbols=tuple(symbols),
segment=segment,
)
result = {}
for sym, data in response.items():
if isinstance(data, (int, float)):
result[sym] = data
elif isinstance(data, dict):
result[sym] = data.get("ltp")
else:
result[sym] = data
print(json.dumps(result, indent=2))
def cmd_search(args):
"""Search instruments."""
client = get_client()
instruments_df = client.get_all_instruments()
query = args.query.lower()
mask = (
instruments_df["name"].str.lower().str.contains(query, na=False)
| instruments_df["trading_symbol"].str.lower().str.contains(query, na=False)
)
if args.exchange and args.exchange != "ALL":
mask &= instruments_df["exchange"] == args.exchange.upper()
if args.segment and args.segment != "ALL":
mask &= instruments_df["segment"] == args.segment.upper()
results = instruments_df[mask].head(args.limit)
output = []
for _, row in results.iterrows():
entry = {
"trading_symbol": row.get("trading_symbol"),
"exchange": row.get("exchange"),
"name": row.get("name"),
"segment": row.get("segment"),
"instrument_type": row.get("instrument_type"),
"lot_size": row.get("lot_size"),
}
if row.get("expiry_date") and str(row.get("expiry_date")) != "":
entry["expiry"] = str(row.get("expiry_date"))
if row.get("strike_price") and str(row.get("strike_price")) != "":
entry["strike"] = row.get("strike_price")
output.append(entry)
print(json.dumps({"results": output, "total_found": int(mask.sum())}, indent=2))
def cmd_buy(args):
"""Place buy order."""
_place_order(args, "BUY")
def cmd_sell(args):
"""Place sell order."""
_place_order(args, "SELL")
def _place_order(args, transaction_type):
"""Place an order."""
client = get_client()
symbol = args.symbol.upper()
exchange = args.exchange or "NSE"
segment = args.segment or "CASH"
product = args.product or "CNC"
if args.price:
order_type = "LIMIT"
price = args.price
else:
order_type = "MARKET"
price = None
trigger_price = args.trigger_price
order_params = {
"trading_symbol": symbol,
"quantity": args.quantity,
"exchange": exchange,
"segment": segment,
"product": product,
"order_type": order_type,
"transaction_type": transaction_type,
"validity": "DAY",
}
if price is not None:
order_params["price"] = price
if trigger_price is not None:
order_params["trigger_price"] = trigger_price
response = client.place_order(**order_params)
print(json.dumps({
"status": "order_placed",
"transaction": transaction_type,
"symbol": symbol,
"quantity": args.quantity,
"order_type": order_type,
"price": price,
"response": response,
}, indent=2))
def cmd_option_chain(args):
"""Fetch option chain with Greeks."""
client = get_client()
underlying = args.underlying.upper()
expiry = args.expiry
exchange = args.exchange or "NSE"
response = client.get_option_chain(
exchange=exchange,
underlying=underlying,
expiry_date=expiry,
)
print(json.dumps(response, indent=2, default=str))
def cmd_greeks(args):
"""Fetch Greeks for a specific contract."""
client = get_client()
underlying = args.underlying.upper()
symbol = args.symbol.upper()
expiry = args.expiry
exchange = args.exchange or "NSE"
response = client.get_greeks(
exchange=exchange,
underlying=underlying,
trading_symbol=symbol,
expiry=expiry,
)
print(json.dumps(response, indent=2, default=str))
def cmd_order_list(args):
"""Get today's orders."""
client = get_client()
segment = getattr(args, "segment", None)
response = client.get_order_list(segment=segment)
print(json.dumps(response, indent=2, default=str))
def cmd_cancel(args):
"""Cancel an order."""
client = get_client()
response = client.cancel_order(
groww_order_id=args.order_id,
segment=args.segment or "CASH",
)
print(json.dumps({"status": "cancelled", "response": response}, indent=2, default=str))
# ─── Main ─────────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="Groww Trading Client")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Holdings
subparsers.add_parser("holdings", help="View DEMAT holdings")
# Positions
p_pos = subparsers.add_parser("positions", help="View open positions")
p_pos.add_argument("--segment", help="CASH or FNO")
# Margin
subparsers.add_parser("margin", help="Check available margin")
# Quote
p_quote = subparsers.add_parser("quote", help="Live quote with depth")
p_quote.add_argument("symbol", help="Trading symbol")
p_quote.add_argument("--exchange", default="NSE")
p_quote.add_argument("--segment", default="CASH")
# LTP
p_ltp = subparsers.add_parser("ltp", help="LTP for multiple symbols")
p_ltp.add_argument("symbols", nargs="+", help="Trading symbols")
p_ltp.add_argument("--segment", default="CASH")
# Search
p_search = subparsers.add_parser("search", help="Search instruments")
p_search.add_argument("query", help="Search query")
p_search.add_argument("--exchange", default="ALL")
p_search.add_argument("--segment", default="ALL")
p_search.add_argument("--limit", type=int, default=10)
# Buy
p_buy = subparsers.add_parser("buy", help="Place buy order")
p_buy.add_argument("symbol", help="Trading symbol")
p_buy.add_argument("quantity", type=int, help="Quantity")
p_buy.add_argument("--price", type=float, help="Limit price (omit for market)")
p_buy.add_argument("--trigger-price", type=float, help="Trigger price for SL orders")
p_buy.add_argument("--exchange", default="NSE")
p_buy.add_argument("--segment", default="CASH")
p_buy.add_argument("--product", default="CNC", help="CNC/MIS/NRML")
# Sell
p_sell = subparsers.add_parser("sell", help="Place sell order")
p_sell.add_argument("symbol", help="Trading symbol")
p_sell.add_argument("quantity", type=int, help="Quantity")
p_sell.add_argument("--price", type=float, help="Limit price (omit for market)")
p_sell.add_argument("--trigger-price", type=float, help="Trigger price for SL orders")
p_sell.add_argument("--exchange", default="NSE")
p_sell.add_argument("--segment", default="CASH")
p_sell.add_argument("--product", default="CNC", help="CNC/MIS/NRML")
# Option chain
p_oc = subparsers.add_parser("option-chain", help="Option chain with Greeks")
p_oc.add_argument("underlying", help="Underlying (NIFTY, BANKNIFTY, RELIANCE, etc.)")
p_oc.add_argument("expiry", help="Expiry date (YYYY-MM-DD)")
p_oc.add_argument("--exchange", default="NSE")
# Greeks
p_greeks = subparsers.add_parser("greeks", help="Greeks for specific contract")
p_greeks.add_argument("underlying", help="Underlying symbol")
p_greeks.add_argument("symbol", help="Option trading symbol")
p_greeks.add_argument("expiry", help="Expiry date (YYYY-MM-DD)")
p_greeks.add_argument("--exchange", default="NSE")
# Orders
p_orders = subparsers.add_parser("orders", help="Today's orders")
p_orders.add_argument("--segment", help="CASH or FNO")
# Cancel
p_cancel = subparsers.add_parser("cancel", help="Cancel an order")
p_cancel.add_argument("order_id", help="Groww order ID")
p_cancel.add_argument("--segment", default="CASH")
args = parser.parse_args()
if not args.command:
parser.print_help()
sys.exit(1)
commands = {
"holdings": cmd_holdings,
"positions": cmd_positions,
"margin": cmd_margin,
"quote": cmd_quote,
"ltp": cmd_ltp,
"search": cmd_search,
"buy": cmd_buy,
"sell": cmd_sell,
"option-chain": cmd_option_chain,
"greeks": cmd_greeks,
"orders": cmd_order_list,
"cancel": cmd_cancel,
}
cmd_func = commands.get(args.command)
if cmd_func:
try:
cmd_func(args)
except Exception as e:
print(json.dumps({"error": str(e)}, indent=2))
sys.exit(1)
else:
parser.print_help()
if __name__ == "__main__":
main()