DhanHQ 2.1.5 → 2.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +7 -0
  3. data/GUIDE.md +215 -73
  4. data/README.md +416 -132
  5. data/README1.md +267 -26
  6. data/docs/live_order_updates.md +319 -0
  7. data/docs/rails_websocket_integration.md +847 -0
  8. data/docs/standalone_ruby_websocket_integration.md +1588 -0
  9. data/docs/websocket_integration.md +871 -0
  10. data/examples/comprehensive_websocket_examples.rb +148 -0
  11. data/examples/instrument_finder_test.rb +195 -0
  12. data/examples/live_order_updates.rb +118 -0
  13. data/examples/market_depth_example.rb +144 -0
  14. data/examples/market_feed_example.rb +81 -0
  15. data/examples/order_update_example.rb +105 -0
  16. data/examples/trading_fields_example.rb +215 -0
  17. data/lib/DhanHQ/configuration.rb +16 -1
  18. data/lib/DhanHQ/contracts/expired_options_data_contract.rb +103 -0
  19. data/lib/DhanHQ/contracts/trade_contract.rb +70 -0
  20. data/lib/DhanHQ/errors.rb +2 -0
  21. data/lib/DhanHQ/models/expired_options_data.rb +331 -0
  22. data/lib/DhanHQ/models/instrument.rb +96 -2
  23. data/lib/DhanHQ/models/order_update.rb +235 -0
  24. data/lib/DhanHQ/models/trade.rb +118 -31
  25. data/lib/DhanHQ/resources/expired_options_data.rb +22 -0
  26. data/lib/DhanHQ/version.rb +1 -1
  27. data/lib/DhanHQ/ws/base_connection.rb +249 -0
  28. data/lib/DhanHQ/ws/connection.rb +2 -2
  29. data/lib/DhanHQ/ws/decoder.rb +3 -3
  30. data/lib/DhanHQ/ws/market_depth/client.rb +376 -0
  31. data/lib/DhanHQ/ws/market_depth/decoder.rb +131 -0
  32. data/lib/DhanHQ/ws/market_depth.rb +74 -0
  33. data/lib/DhanHQ/ws/orders/client.rb +175 -11
  34. data/lib/DhanHQ/ws/orders/connection.rb +40 -81
  35. data/lib/DhanHQ/ws/orders.rb +28 -0
  36. data/lib/DhanHQ/ws/segments.rb +18 -2
  37. data/lib/DhanHQ/ws.rb +3 -2
  38. data/lib/dhan_hq.rb +5 -0
  39. metadata +35 -1
data/README.md CHANGED
@@ -4,8 +4,8 @@ A clean Ruby client for **Dhan API v2** with ORM-like models (Orders, Positions,
4
4
 
5
5
  * ActiveRecord-style models: `find`, `all`, `where`, `save`, `update`, `cancel`
6
6
  * Validations & errors exposed via ActiveModel-like interfaces
7
- * REST coverage: Orders, Super Orders, Forever Orders, Trades, Positions, Holdings, Funds/Margin, HistoricalData, OptionChain, MarketFeed
8
- * **WebSocket**: subscribe/unsubscribe dynamically, auto-reconnect with backoff, 429 cool-off, idempotent subs, header+payload binary parsing, normalized ticks
7
+ * REST coverage: Orders, Super Orders, Forever Orders, Trades, Positions, Holdings, Funds/Margin, HistoricalData, OptionChain, MarketFeed, ExpiredOptionsData
8
+ * **WebSocket**: Orders, Market Feed, Market Depth - subscribe/unsubscribe dynamically, auto-reconnect with backoff, 429 cool-off, idempotent subs, header+payload binary parsing, normalized ticks
9
9
 
10
10
  ## ⚠️ BREAKING CHANGE NOTICE
11
11
 
@@ -146,153 +146,194 @@ initializers, service objects, workers, and ActionCable wiring tailored for the
146
146
 
147
147
  ---
148
148
 
149
- ## WebSocket Market Feed (NEW)
149
+ ## WebSocket Integration (Orders, Market Feed, Market Depth)
150
150
 
151
- ### What you get
151
+ The DhanHQ gem provides comprehensive WebSocket integration with three distinct WebSocket types, featuring improved architecture, security, and reliability:
152
152
 
153
- * **Modes**
153
+ ### Key Features
154
154
 
155
- * `:ticker` LTP + LTT
156
- * `:quote` → OHLCV + totals (recommended default)
157
- * `:full` → quote + **OI** + **best-5 depth**
158
- * **Normalized ticks** (Hash):
155
+ - **🔒 Secure Logging** - Sensitive information (access tokens) are automatically sanitized from logs
156
+ - **⚡ Rate Limit Protection** - Built-in protection against 429 errors with proper connection management
157
+ - **🔄 Automatic Reconnection** - Exponential backoff with 60-second cool-off periods
158
+ - **🧵 Thread-Safe Operation** - Safe for Rails applications and multi-threaded environments
159
+ - **📊 Comprehensive Examples** - Ready-to-use examples for all WebSocket types
160
+ - **🛡️ Error Handling** - Robust error handling and connection management
161
+ - **🔍 Dynamic Symbol Resolution** - Easy instrument lookup using `.find()` method
159
162
 
160
- ```ruby
161
- {
162
- kind: :quote, # :ticker | :quote | :full | :oi | :prev_close | :misc
163
- segment: "NSE_FNO", # string enum
164
- security_id: "12345",
165
- ltp: 101.5,
166
- ts: 1723791300, # LTT epoch (sec) if present
167
- vol: 123456, # quote/full
168
- atp: 100.9, # quote/full
169
- day_open: 100.1, day_high: 102.4, day_low: 99.5, day_close: nil,
170
- oi: 987654, # full or OI packet
171
- bid: 101.45, ask: 101.55 # from depth (mode :full)
172
- }
173
- ```
163
+ ### 1. Orders WebSocket - Real-time Order Updates
174
164
 
175
- ### Start, subscribe, stop
165
+ Receive live updates whenever your orders transition between states (placed → traded → cancelled, etc.).
176
166
 
177
167
  ```ruby
178
- require 'dhan_hq'
179
-
180
- DhanHQ.configure_with_env
181
- DhanHQ.logger.level = (ENV["DHAN_LOG_LEVEL"] || "INFO").upcase.then { |level| Logger.const_get(level) }
182
-
183
- ws = DhanHQ::WS::Client.new(mode: :quote).start
184
-
185
- ws.on(:tick) do |t|
186
- puts "[#{t[:segment]}:#{t[:security_id]}] LTP=#{t[:ltp]} kind=#{t[:kind]}"
168
+ # Simple connection
169
+ DhanHQ::WS::Orders.connect do |order_update|
170
+ puts "Order Update: #{order_update.order_no} - #{order_update.status}"
171
+ puts " Symbol: #{order_update.symbol}"
172
+ puts " Quantity: #{order_update.quantity}"
173
+ puts " Traded Qty: #{order_update.traded_qty}"
174
+ puts " Price: #{order_update.price}"
175
+ puts " Execution: #{order_update.execution_percentage}%"
187
176
  end
188
177
 
189
- # Subscribe instruments (≤100 per frame; send multiple frames if needed)
190
- ws.subscribe_one(segment: "IDX_I", security_id: "13") # NIFTY index value
191
- ws.subscribe_one(segment: "NSE_FNO", security_id: "12345") # an option
192
-
193
- # Unsubscribe
194
- ws.unsubscribe_one(segment: "NSE_FNO", security_id: "12345")
178
+ # Advanced usage with multiple event handlers
179
+ client = DhanHQ::WS::Orders.client
180
+ client.on(:update) { |order| puts "📝 Order updated: #{order.order_no}" }
181
+ client.on(:status_change) { |change| puts "🔄 Status: #{change[:previous_status]} -> #{change[:new_status]}" }
182
+ client.on(:execution) { |exec| puts "✅ Executed: #{exec[:new_traded_qty]} shares" }
183
+ client.on(:order_rejected) { |order| puts " Rejected: #{order.order_no}" }
184
+ client.start
185
+ ```
195
186
 
196
- # Graceful disconnect (sends broker disconnect code 12, no reconnect)
197
- ws.disconnect!
187
+ ### 2. Market Feed WebSocket - Live Market Data
198
188
 
199
- # Or hard stop (no broker message, just closes and halts loop)
200
- ws.stop
189
+ Subscribe to real-time market data for indices and stocks.
201
190
 
202
- # Safety: kill all local sockets (useful in IRB)
203
- DhanHQ::WS.disconnect_all_local!
204
- ```
191
+ ```ruby
192
+ # Ticker data (LTP updates) - Recommended for most use cases
193
+ market_client = DhanHQ::WS.connect(mode: :ticker) do |tick|
194
+ timestamp = tick[:ts] ? Time.at(tick[:ts]) : Time.now
195
+ puts "Market Data: #{tick[:segment]}:#{tick[:security_id]} = #{tick[:ltp]} at #{timestamp}"
196
+ end
205
197
 
206
- ### Under the hood
198
+ # Subscribe to major Indian indices
199
+ market_client.subscribe_one(segment: "IDX_I", security_id: "13") # NIFTY
200
+ market_client.subscribe_one(segment: "IDX_I", security_id: "25") # BANKNIFTY
201
+ market_client.subscribe_one(segment: "IDX_I", security_id: "29") # NIFTYIT
202
+ market_client.subscribe_one(segment: "IDX_I", security_id: "51") # SENSEX
207
203
 
208
- * **Request codes** (per Dhan docs)
204
+ # Quote data (LTP + volume + OHLC)
205
+ DhanHQ::WS.connect(mode: :quote) do |quote|
206
+ puts "#{quote[:symbol]}: LTP=#{quote[:ltp]}, Volume=#{quote[:vol]}"
207
+ end
209
208
 
210
- * Subscribe: **15** (ticker), **17** (quote), **21** (full)
211
- * Unsubscribe: **16**, **18**, **22**
212
- * Disconnect: **12**
213
- * **Limits**
209
+ # Full market data
210
+ DhanHQ::WS.connect(mode: :full) do |full|
211
+ puts "#{full[:symbol]}: #{full.inspect}"
212
+ end
213
+ ```
214
214
 
215
- * Up to **100 instruments per SUB/UNSUB** message (client auto-chunks)
216
- * Up to 5 WS connections per user (per Dhan)
217
- * **Backoff & 429 cool-off**
215
+ ### 3. Market Depth WebSocket - Real-time Market Depth
218
216
 
219
- * Exponential backoff with jitter
220
- * Handshake **429** triggers a **60s cool-off** before retry
221
- * **Reconnect & resubscribe**
217
+ Get real-time market depth data including bid/ask levels and order book information.
222
218
 
223
- * On reconnect the client resends the **current subscription snapshot** (idempotent)
224
- * **Graceful shutdown**
219
+ ```ruby
220
+ # Real-time market depth for stocks (using dynamic symbol resolution with underlying_symbol)
221
+ reliance = DhanHQ::Models::Instrument.find("NSE_EQ", "RELIANCE")
222
+ tcs = DhanHQ::Models::Instrument.find("NSE_EQ", "TCS")
225
223
 
226
- * `ws.disconnect!` or `ws.stop` prevents reconnects
227
- * An `at_exit` hook stops all registered WS clients to avoid leaked sockets
224
+ symbols = []
225
+ if reliance
226
+ symbols << { symbol: "RELIANCE", exchange_segment: reliance.exchange_segment, security_id: reliance.security_id }
227
+ end
228
+ if tcs
229
+ symbols << { symbol: "TCS", exchange_segment: tcs.exchange_segment, security_id: tcs.security_id }
230
+ end
228
231
 
229
- ---
232
+ DhanHQ::WS::MarketDepth.connect(symbols: symbols) do |depth_data|
233
+ puts "Market Depth: #{depth_data[:symbol]}"
234
+ puts " Best Bid: #{depth_data[:best_bid]}"
235
+ puts " Best Ask: #{depth_data[:best_ask]}"
236
+ puts " Spread: #{depth_data[:spread]}"
237
+ puts " Bid Levels: #{depth_data[:bids].size}"
238
+ puts " Ask Levels: #{depth_data[:asks].size}"
239
+ end
240
+ ```
230
241
 
231
- ## Order Update WebSocket (NEW)
242
+ ### Unified WebSocket Architecture
232
243
 
233
- Receive live updates whenever your orders transition between states (placed → traded → cancelled, etc.).
244
+ All WebSocket connections provide:
245
+ - **Automatic reconnection** with exponential backoff
246
+ - **Thread-safe operation** for Rails applications
247
+ - **Consistent event handling** patterns
248
+ - **Built-in error handling** and logging
249
+ - **429 rate limiting** protection with cool-off periods
250
+ - **Secure logging** with automatic credential sanitization
234
251
 
235
- ### Standalone Ruby script
252
+ ### Connection Management
236
253
 
237
254
  ```ruby
238
- require 'dhan_hq'
255
+ # Sequential connections to avoid rate limiting (recommended)
256
+ orders_client = DhanHQ::WS::Orders.connect { |order| puts "Order: #{order.order_no}" }
257
+ orders_client.stop
258
+ sleep(2) # Wait between connections
239
259
 
240
- DhanHQ.configure_with_env
241
- DhanHQ.logger.level = (ENV["DHAN_LOG_LEVEL"] || "INFO").upcase.then { |level| Logger.const_get(level) }
260
+ market_client = DhanHQ::WS.connect(mode: :ticker) { |tick| puts "Market: #{tick[:symbol]}" }
261
+ market_client.stop
262
+ sleep(2)
242
263
 
243
- ou = DhanHQ::WS::Orders::Client.new.start
264
+ depth_client = DhanHQ::WS::MarketDepth.connect(symbols: symbols) { |depth| puts "Depth: #{depth[:symbol]}" }
265
+ depth_client.stop
244
266
 
245
- ou.on(:update) do |payload|
246
- data = payload[:Data] || {}
247
- puts "ORDER #{data[:OrderNo]} #{data[:Status]} traded=#{data[:TradedQty]} avg=#{data[:AvgTradedPrice]}"
248
- end
267
+ # Check connection status
268
+ puts "Orders connected: #{orders_client.connected?}"
269
+ puts "Market connected: #{market_client.connected?}"
270
+ puts "Depth connected: #{depth_client.connected?}"
249
271
 
250
- # Keep the script alive (CTRL+C to exit)
251
- sleep
252
-
253
- # Later, stop the socket
254
- ou.stop
272
+ # Graceful shutdown
273
+ DhanHQ::WS.disconnect_all_local!
255
274
  ```
256
275
 
257
- Or, if you just need a quick callback:
276
+ ### Examples
258
277
 
259
- ```ruby
260
- DhanHQ::WS::Orders.connect do |payload|
261
- # handle :update callbacks only
262
- end
263
- ```
278
+ The gem includes comprehensive examples in the `examples/` directory:
264
279
 
265
- ### Rails bot integration
280
+ - `market_feed_example.rb` - Market Feed WebSocket with major indices
281
+ - `order_update_example.rb` - Order Update WebSocket with event handling
282
+ - `market_depth_example.rb` - Market Depth WebSocket with RELIANCE and TCS
283
+ - `comprehensive_websocket_examples.rb` - All three WebSocket types
266
284
 
267
- Mirror the market-feed supervisor by adding an Order Update hub singleton that hydrates your local DB and hands off to execution services.
285
+ Run examples:
268
286
 
269
- 1. **Service** – `app/services/live/order_update_hub.rb`
287
+ ```bash
288
+ # Individual examples
289
+ bundle exec ruby examples/market_feed_example.rb
290
+ bundle exec ruby examples/order_update_example.rb
291
+ bundle exec ruby examples/market_depth_example.rb
270
292
 
271
- ```ruby
272
- Live::OrderUpdateHub.instance.start!
273
- ```
293
+ # Comprehensive example
294
+ bundle exec ruby examples/comprehensive_websocket_examples.rb
295
+ ```
274
296
 
275
- The hub wires `DhanHQ::WS::Orders::Client` to:
297
+ ### Instrument Model with Trading Fields
276
298
 
277
- * Upsert local `BrokerOrder` rows so UIs always reflect current broker status.
278
- * Auto-subscribe traded entry legs on your existing `Live::WsHub` (if defined).
279
- * Refresh `Execution::PositionGuard` (if present) with fill prices/qty for trailing exits.
299
+ The Instrument model now includes comprehensive trading fields for order validation, risk management, and compliance:
280
300
 
281
- 2. **Initializer** – `config/initializers/order_update_hub.rb`
301
+ ```ruby
302
+ # Find instrument with trading fields
303
+ reliance = DhanHQ::Models::Instrument.find("NSE_EQ", "RELIANCE")
304
+
305
+ # Trading permissions and restrictions
306
+ puts "Trading Allowed: #{reliance.buy_sell_indicator == 'A'}"
307
+ puts "Bracket Orders: #{reliance.bracket_flag == 'Y' ? 'Supported' : 'Not Supported'}"
308
+ puts "Cover Orders: #{reliance.cover_flag == 'Y' ? 'Supported' : 'Not Supported'}"
309
+ puts "ASM/GSM Status: #{reliance.asm_gsm_flag == 'Y' ? reliance.asm_gsm_category : 'No Restrictions'}"
310
+
311
+ # Margin and leverage information
312
+ puts "ISIN: #{reliance.isin}"
313
+ puts "MTF Leverage: #{reliance.mtf_leverage}x"
314
+ puts "Buy Margin %: #{reliance.buy_co_min_margin_per}%"
315
+ puts "Sell Margin %: #{reliance.sell_co_min_margin_per}%"
316
+ ```
282
317
 
283
- ```ruby
284
- if ENV["ENABLE_WS"] == "true"
285
- Rails.application.config.to_prepare do
286
- Live::OrderUpdateHub.instance.start!
287
- end
318
+ **Available Trading Fields:**
319
+ - `isin` - International Securities Identification Number
320
+ - `instrument_type` - Classification (ES, INDEX, FUT, OPT)
321
+ - `expiry_flag` - Whether instrument has expiry
322
+ - `bracket_flag` - Bracket order support
323
+ - `cover_flag` - Cover order support
324
+ - `asm_gsm_flag` - Additional Surveillance Measure status
325
+ - `buy_sell_indicator` - Trading permission
326
+ - `buy_co_min_margin_per` - Buy CO minimum margin percentage
327
+ - `sell_co_min_margin_per` - Sell CO minimum margin percentage
328
+ - `mtf_leverage` - Margin Trading Facility leverage
288
329
 
289
- at_exit { Live::OrderUpdateHub.instance.stop! }
290
- end
291
- ```
330
+ ### Comprehensive Documentation
292
331
 
293
- Flip `ENABLE_WS=true` in your Procfile or `.env` to boot the hub alongside the existing feed supervisor. On shutdown the client is stopped cleanly to avoid leaked sockets.
332
+ The gem includes detailed documentation for different integration scenarios:
294
333
 
295
- The hub is resilient to missing dependencies—if you do not have a `BrokerOrder` model, it safely skips persistence while keeping downstream callbacks alive.
334
+ - **[WebSocket Integration Guide](docs/websocket_integration.md)** - Complete guide covering all WebSocket types and trading fields
335
+ - **[Rails Integration Guide](docs/rails_websocket_integration.md)** - Rails-specific patterns and best practices
336
+ - **[Standalone Ruby Guide](docs/standalone_ruby_websocket_integration.md)** - Scripts, daemons, and CLI tools
296
337
 
297
338
  ---
298
339
 
@@ -397,40 +438,283 @@ end
397
438
 
398
439
  ---
399
440
 
400
- ## Super Orders (example)
441
+ ## Super Orders
401
442
 
402
- ```ruby
403
- intent = {
404
- exchange_segment: "NSE_FNO",
405
- security_id: "12345", # option
406
- transaction_type: "BUY",
407
- quantity: 50,
408
- # derived risk params from ATR/ADX
409
- take_profit: 0.35, # 35% target
410
- stop_loss: 0.18, # 18% SL
411
- trailing_sl: 0.12 # 12% trail
443
+ Super orders are built for smart execution. They club the entry, target, and stop-loss legs (with optional trailing jump) into a single request so you can manage risk immediately after entry.
444
+
445
+ This gem exposes the full REST surface to create, modify, cancel, and list super orders across all supported exchanges and segments.
446
+
447
+ ### Endpoints
448
+
449
+ | Method | Path | Description |
450
+ | -------- | -------------------------------------- | ------------------------------------- |
451
+ | `POST` | `/super/orders` | Create a new super order |
452
+ | `PUT` | `/super/orders/{order_id}` | Modify a pending super order |
453
+ | `DELETE` | `/super/orders/{order_id}/{order_leg}` | Cancel a pending super order leg |
454
+ | `GET` | `/super/orders` | Retrieve the list of all super orders |
455
+
456
+ ### Place Super Order
457
+
458
+ The place endpoint lets you submit a new super order that can include entry, target, stop-loss, and optional trailing jump definitions. It is available across exchanges and segments, and supports intraday, carry-forward, or MTF orders.
459
+
460
+ > ℹ️ Static IP whitelisting with Dhan support is required before invoking this API.
461
+
462
+ ```bash
463
+ curl --request POST \
464
+ --url https://api.dhan.co/v2/super/orders \
465
+ --header 'Content-Type: application/json' \
466
+ --header 'access-token: JWT' \
467
+ --data '{Request JSON}'
468
+ ```
469
+
470
+ #### Request body
471
+
472
+ ```json
473
+ {
474
+ "dhan_client_id": "1000000003",
475
+ "correlation_id": "123abc678",
476
+ "transaction_type": "BUY",
477
+ "exchange_segment": "NSE_EQ",
478
+ "product_type": "CNC",
479
+ "order_type": "LIMIT",
480
+ "security_id": "11536",
481
+ "quantity": 5,
482
+ "price": 1500,
483
+ "target_price": 1600,
484
+ "stop_loss_price": 1400,
485
+ "trailing_jump": 10
412
486
  }
487
+ ```
413
488
 
414
- # If your SuperOrder model exposes create/modify:
415
- o = DhanHQ::Models::SuperOrder.create(intent)
416
- # or fallback:
417
- mkt = DhanHQ::Models::Order.new(
418
- transaction_type: "BUY", exchange_segment: "NSE_FNO",
419
- order_type: "MARKET", validity: "DAY",
420
- security_id: "12345", quantity: 50
421
- ).save
489
+ #### Parameters
490
+
491
+ | Field | Type | Description |
492
+ | ------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
493
+ | `dhan_client_id` | string *(required)* | User specific identification generated by Dhan. When you call through `DhanHQ::Models::SuperOrder`, the gem injects your configured client id so you can omit this key locally. |
494
+ | `correlation_id` | string | Caller generated correlation identifier |
495
+ | `transaction_type` | enum string *(required)* | Trading side. `BUY` or `SELL`. |
496
+ | `exchange_segment` | enum string *(required)* | Exchange segment (see appendix). |
497
+ | `product_type` | enum string *(required)* | Product type. `CNC`, `INTRADAY`, `MARGIN`, or `MTF`. |
498
+ | `order_type` | enum string *(required)* | Order type. `LIMIT` or `MARKET`. |
499
+ | `security_id` | string *(required)* | Exchange standard security identifier. |
500
+ | `quantity` | integer *(required)* | Number of shares for the order. |
501
+ | `price` | float *(required)* | Price at which the entry leg is placed. |
502
+ | `target_price` | float *(required)* | Target price for the super order. |
503
+ | `stop_loss_price` | float *(required)* | Stop-loss price for the super order. |
504
+ | `trailing_jump` | float *(required)* | Price jump size used to trail the stop-loss. |
505
+
506
+ > 🐍 When you call `DhanHQ::Models::SuperOrder.create`, pass snake_case keys as shown above. The client automatically camelizes
507
+ > them before posting to Dhan's REST API and injects your configured `dhan_client_id`, so you can omit that key in Ruby code.
508
+
509
+ #### Response
510
+
511
+ ```json
512
+ {
513
+ "order_id": "112111182198",
514
+ "order_status": "PENDING"
515
+ }
422
516
  ```
423
517
 
424
- If you placed a Super Order and want to trail SL upward using WS ticks:
518
+ | Field | Type | Description |
519
+ | -------------- | ----------- | --------------------------------------------------- |
520
+ | `order_id` | string | Order identifier generated by Dhan |
521
+ | `order_status` | enum string | Latest status. `TRANSIT`, `PENDING`, or `REJECTED`. |
425
522
 
426
- ```ruby
427
- DhanHQ::Models::SuperOrder.modify(
428
- order_id: o.order_id,
429
- stop_loss: new_abs_price, # broker API permitting
430
- trailing_sl: nil
431
- )
523
+ ### Modify Super Order
524
+
525
+ Use the modify endpoint to update any leg while the super order remains in `PENDING` or `PART_TRADED` status.
526
+
527
+ > ℹ️ Static IP whitelisting with Dhan support is required before invoking this API.
528
+
529
+ ```bash
530
+ curl --request PUT \
531
+ --url https://api.dhan.co/v2/super/orders/{order_id} \
532
+ --header 'Content-Type: application/json' \
533
+ --header 'access-token: JWT' \
534
+ --data '{Request JSON}'
535
+ ```
536
+
537
+ #### Request body
538
+
539
+ ```json
540
+ {
541
+ "dhan_client_id": "1000000009",
542
+ "order_id": "112111182045",
543
+ "order_type": "LIMIT",
544
+ "leg_name": "ENTRY_LEG",
545
+ "quantity": 40,
546
+ "price": 1300,
547
+ "target_price": 1450,
548
+ "stop_loss_price": 1350,
549
+ "trailing_jump": 20
550
+ }
551
+ ```
552
+
553
+ #### Parameters
554
+
555
+ | Field | Type | Description |
556
+ | ----------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
557
+ | `dhan_client_id` | string *(required)* | User specific identification generated by Dhan. Automatically added when you call through the Ruby models. |
558
+ | `order_id` | string *(required)* | Super order identifier generated by Dhan. |
559
+ | `order_type` | enum string *(conditionally required)* | `LIMIT` or `MARKET`. Required when modifying `ENTRY_LEG`. |
560
+ | `leg_name` | enum string *(required)* | `ENTRY_LEG`, `TARGET_LEG`, or `STOP_LOSS_LEG`. Entry leg updates entire order while status is `PENDING` or `PART_TRADED`. |
561
+ | `quantity` | integer *(conditionally required)* | Quantity update for `ENTRY_LEG`. |
562
+ | `price` | float *(conditionally required)* | Entry price update for `ENTRY_LEG`. |
563
+ | `target_price` | float *(conditionally required)* | Target price update for `ENTRY_LEG` or `TARGET_LEG`. |
564
+ | `stop_loss_price` | float *(conditionally required)* | Stop-loss price update for `ENTRY_LEG` or `STOP_LOSS_LEG`. |
565
+ | `trailing_jump` | float *(conditionally required)* | Trailing jump update for `ENTRY_LEG` or `STOP_LOSS_LEG`. Omit or set to `0` to cancel trailing. |
566
+
567
+ > ℹ️ Once the entry leg status becomes `TRADED`, only the `TARGET_LEG` and `STOP_LOSS_LEG` can be modified (price and trailing jump).
568
+
569
+ #### Response
570
+
571
+ ```json
572
+ {
573
+ "order_id": "112111182045",
574
+ "order_status": "TRANSIT"
575
+ }
432
576
  ```
433
577
 
578
+ | Field | Type | Description |
579
+ | -------------- | ----------- | ------------------------------------------------------------- |
580
+ | `order_id` | string | Order identifier generated by Dhan |
581
+ | `order_status` | enum string | Latest status. `TRANSIT`, `PENDING`, `REJECTED`, or `TRADED`. |
582
+
583
+ ### Cancel Super Order
584
+
585
+ Cancel a pending or active super order leg using the order ID. Cancelling the entry leg removes every leg. Cancelling a specific target or stop-loss leg removes only that leg and it cannot be re-added.
586
+
587
+ > ℹ️ Static IP whitelisting with Dhan support is required before invoking this API.
588
+
589
+ ```bash
590
+ curl --request DELETE \
591
+ --url https://api.dhan.co/v2/super/orders/{order_id}/{order_leg} \
592
+ --header 'Content-Type: application/json' \
593
+ --header 'access-token: JWT'
594
+ ```
595
+
596
+ #### Path parameters
597
+
598
+ | Field | Description | Example |
599
+ | ----------- | ------------------------------------------------------------- | ------------- |
600
+ | `order_id` | Super order identifier. | `11211182198` |
601
+ | `order_leg` | Leg to cancel. `ENTRY_LEG`, `TARGET_LEG`, or `STOP_LOSS_LEG`. | `ENTRY_LEG` |
602
+
603
+ #### Response
604
+
605
+ ```json
606
+ {
607
+ "order_id": "112111182045",
608
+ "order_status": "CANCELLED"
609
+ }
610
+ ```
611
+
612
+ | Field | Type | Description |
613
+ | -------------- | ----------- | ---------------------------------------------------------------- |
614
+ | `order_id` | string | Order identifier generated by Dhan |
615
+ | `order_status` | enum string | Latest status. `TRANSIT`, `PENDING`, `REJECTED`, or `CANCELLED`. |
616
+
617
+ ### Super Order List
618
+
619
+ List every super order placed during the trading day. The API nests leg details under the entry leg, and individual legs also appear in the main order book.
620
+
621
+ ```bash
622
+ curl --request GET \
623
+ --url https://api.dhan.co/v2/super/orders \
624
+ --header 'Content-Type: application/json' \
625
+ --header 'access-token: JWT'
626
+ ```
627
+
628
+ #### Response
629
+
630
+ ```json
631
+ [
632
+ {
633
+ "dhan_client_id": "1100003626",
634
+ "order_id": "5925022734212",
635
+ "correlation_id": "string",
636
+ "order_status": "PENDING",
637
+ "transaction_type": "BUY",
638
+ "exchange_segment": "NSE_EQ",
639
+ "product_type": "CNC",
640
+ "order_type": "LIMIT",
641
+ "validity": "DAY",
642
+ "trading_symbol": "HDFCBANK",
643
+ "security_id": "1333",
644
+ "quantity": 10,
645
+ "remaining_quantity": 10,
646
+ "ltp": 1660.95,
647
+ "price": 1500,
648
+ "after_market_order": false,
649
+ "leg_name": "ENTRY_LEG",
650
+ "exchange_order_id": "11925022734212",
651
+ "create_time": "2025-02-27 19:09:42",
652
+ "update_time": "2025-02-27 19:09:42",
653
+ "exchange_time": "2025-02-27 19:09:42",
654
+ "oms_error_description": "",
655
+ "average_traded_price": 0,
656
+ "filled_qty": 0,
657
+ "leg_details": [
658
+ {
659
+ "order_id": "5925022734212",
660
+ "leg_name": "STOP_LOSS_LEG",
661
+ "transaction_type": "SELL",
662
+ "total_quantity": 0,
663
+ "remaining_quantity": 0,
664
+ "triggered_quantity": 0,
665
+ "price": 1400,
666
+ "order_status": "PENDING",
667
+ "trailing_jump": 10
668
+ },
669
+ {
670
+ "order_id": "5925022734212",
671
+ "leg_name": "TARGET_LEG",
672
+ "transaction_type": "SELL",
673
+ "remaining_quantity": 0,
674
+ "triggered_quantity": 0,
675
+ "price": 1550,
676
+ "order_status": "PENDING",
677
+ "trailing_jump": 0
678
+ }
679
+ ]
680
+ }
681
+ ]
682
+ ```
683
+
684
+ #### Parameters
685
+
686
+ | Field | Type | Description |
687
+ | ----------------------- | ----------- | --------------------------------------------------------------------------------------------------- |
688
+ | `dhan_client_id` | string | User specific identification generated by Dhan. |
689
+ | `order_id` | string | Order identifier generated by Dhan. |
690
+ | `correlation_id` | string | Correlation identifier supplied by the caller. |
691
+ | `order_status` | enum string | Latest status. `TRANSIT`, `PENDING`, `CLOSED`, `REJECTED`, `CANCELLED`, `PART_TRADED`, or `TRADED`. |
692
+ | `transaction_type` | enum string | Trading side. `BUY` or `SELL`. |
693
+ | `exchange_segment` | enum string | Exchange segment. |
694
+ | `product_type` | enum string | Product type. `CNC`, `INTRADAY`, `MARGIN`, or `MTF`. |
695
+ | `order_type` | enum string | Order type. `LIMIT` or `MARKET`. |
696
+ | `validity` | enum string | Order validity. `DAY`. |
697
+ | `trading_symbol` | string | Trading symbol reference. |
698
+ | `security_id` | string | Exchange security identifier. |
699
+ | `quantity` | integer | Ordered quantity. |
700
+ | `remaining_quantity` | integer | Quantity pending execution. |
701
+ | `ltp` | float | Last traded price. |
702
+ | `price` | float | Order price. |
703
+ | `after_market_order` | boolean | Indicates if the order was placed after market hours. |
704
+ | `leg_name` | enum string | Leg identifier: `ENTRY_LEG`, `TARGET_LEG`, or `STOP_LOSS_LEG`. |
705
+ | `trailing_jump` | float | Trailing jump for stop-loss. |
706
+ | `exchange_order_id` | string | Exchange-generated order identifier. |
707
+ | `create_time` | string | Order creation timestamp. |
708
+ | `update_time` | string | Latest update timestamp. |
709
+ | `exchange_time` | string | Exchange timestamp. |
710
+ | `oms_error_description` | string | OMS error description when applicable. |
711
+ | `average_traded_price` | float | Average traded price. |
712
+ | `filled_qty` | integer | Quantity traded on the exchange. |
713
+ | `triggered_quantity` | integer | Quantity triggered for stop-loss or target legs. |
714
+ | `leg_details` | array | Nested leg details for the super order. |
715
+
716
+ > ✅ `CLOSED` indicates the entry leg plus either target or stop-loss leg completed for the entire quantity. `TRIGGERED` appears on target and stop-loss legs to show which leg fired; inspect `triggered_quantity` for the executed quantity.
717
+
434
718
  ---
435
719
 
436
720
  ## Packet parsing (for reference)