DhanHQ 3.2.0 → 3.3.0

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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/AGENTS.md +23 -0
  3. data/CHANGELOG.md +74 -0
  4. data/CODE_OF_CONDUCT.md +132 -0
  5. data/GUIDE.md +16 -0
  6. data/README.md +54 -1
  7. data/docs/CONFIGURATION.md +38 -14
  8. data/docs/RELEASE_GUIDE.md +1 -1
  9. data/lib/DhanHQ/ai/prompt_helpers.rb +17 -7
  10. data/lib/DhanHQ/client.rb +53 -34
  11. data/lib/DhanHQ/concerns/bang_writes.rb +69 -0
  12. data/lib/DhanHQ/concerns/tracked_writes.rb +56 -0
  13. data/lib/DhanHQ/configuration.rb +20 -1
  14. data/lib/DhanHQ/core/base_model.rb +6 -13
  15. data/lib/DhanHQ/deprecation.rb +62 -0
  16. data/lib/DhanHQ/models/alert_order.rb +8 -1
  17. data/lib/DhanHQ/models/forever_order.rb +9 -0
  18. data/lib/DhanHQ/models/global_stocks/order.rb +9 -0
  19. data/lib/DhanHQ/models/iceberg_order.rb +9 -0
  20. data/lib/DhanHQ/models/multi_order.rb +7 -0
  21. data/lib/DhanHQ/models/order.rb +28 -0
  22. data/lib/DhanHQ/models/pnl_exit.rb +7 -0
  23. data/lib/DhanHQ/models/super_order.rb +9 -0
  24. data/lib/DhanHQ/models/twap_order.rb +9 -0
  25. data/lib/DhanHQ/risk/pipeline.rb +0 -2
  26. data/lib/DhanHQ/version.rb +1 -1
  27. data/lib/DhanHQ/write_result.rb +163 -0
  28. data/lib/dhan_hq.rb +9 -0
  29. data/skills/dhanhq-ruby/SKILL.md +208 -0
  30. data/skills/dhanhq-ruby/examples/fetch_option_chain.rb +54 -0
  31. data/skills/dhanhq-ruby/examples/gtt_forever_order.rb +65 -0
  32. data/skills/dhanhq-ruby/examples/historical_data_analysis.rb +89 -0
  33. data/skills/dhanhq-ruby/examples/iron_condor.rb +137 -0
  34. data/skills/dhanhq-ruby/examples/live_feed_setup.rb +43 -0
  35. data/skills/dhanhq-ruby/examples/margin_check.rb +42 -0
  36. data/skills/dhanhq-ruby/examples/order_management.rb +112 -0
  37. data/skills/dhanhq-ruby/examples/place_equity_order.rb +36 -0
  38. data/skills/dhanhq-ruby/examples/place_fno_order.rb +76 -0
  39. data/skills/dhanhq-ruby/examples/portfolio_summary.rb +74 -0
  40. data/skills/dhanhq-ruby/examples/super_order_with_sl.rb +57 -0
  41. data/skills/dhanhq-ruby/references/backtesting-with-dhan.md +65 -0
  42. data/skills/dhanhq-ruby/references/common-workflows.md +76 -0
  43. data/skills/dhanhq-ruby/references/error-codes.md +50 -0
  44. data/skills/dhanhq-ruby/references/funds.md +67 -0
  45. data/skills/dhanhq-ruby/references/instruments.md +91 -0
  46. data/skills/dhanhq-ruby/references/live-feed.md +83 -0
  47. data/skills/dhanhq-ruby/references/market-data.md +119 -0
  48. data/skills/dhanhq-ruby/references/option-chain.md +71 -0
  49. data/skills/dhanhq-ruby/references/options-analysis-patterns.md +76 -0
  50. data/skills/dhanhq-ruby/references/orders.md +203 -0
  51. data/skills/dhanhq-ruby/references/portfolio.md +100 -0
  52. data/skills/dhanhq-ruby/references/scanx-data.md +62 -0
  53. data/skills/dhanhq-ruby/scripts/dhan_helpers.rb +323 -0
  54. data/skills/dhanhq-ruby/scripts/resolve_security.rb +168 -0
  55. data/skills/dhanhq-ruby/scripts/trade_logger.rb +131 -0
  56. data/skills/dhanhq-ruby/scripts/validate_order.rb +169 -0
  57. metadata +36 -2
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+ # rubocop:disable Style/FormatStringToken
3
+ # rubocop:disable Naming/AccessorMethodName
4
+
5
+ require "json"
6
+ require "fileutils"
7
+ require "date"
8
+
9
+ def _get_log_path
10
+ plugin_data = ENV.fetch("CLAUDE_PLUGIN_DATA", nil)
11
+ if plugin_data && !plugin_data.empty?
12
+ FileUtils.mkdir_p(plugin_data)
13
+ File.join(plugin_data, "trades.jsonl")
14
+ else
15
+ default_dir = File.expand_path("../data", __dir__)
16
+ FileUtils.mkdir_p(default_dir)
17
+ File.join(default_dir, "trades.jsonl")
18
+ end
19
+ end
20
+
21
+ def log_order(order_params, response, notes = "")
22
+ log_path = _get_log_path
23
+ FileUtils.mkdir_p(File.dirname(log_path))
24
+
25
+ status = response[:status] || response["status"]
26
+ data = response[:data] || response["data"]
27
+ order_id = data.is_a?(Hash) ? (data[:orderId] || data["orderId"]) : nil
28
+
29
+ record = {
30
+ "timestamp" => Time.now.strftime("%Y-%m-%dT%H:%M:%S%:z"),
31
+ "order_params" => order_params,
32
+ "response" => response,
33
+ "order_id" => order_id,
34
+ "status" => status,
35
+ "notes" => notes
36
+ }
37
+
38
+ File.open(log_path, "a") do |f|
39
+ f.write("#{JSON.dump(record)}\n")
40
+ end
41
+
42
+ record
43
+ end
44
+
45
+ def _read_all_records
46
+ log_path = _get_log_path
47
+ return [] unless File.exist?(log_path)
48
+
49
+ records = []
50
+ File.foreach(log_path) do |line|
51
+ line_trimmed = line.strip
52
+ next if line_trimmed.empty?
53
+
54
+ records << JSON.parse(line_trimmed)
55
+ rescue JSON::ParserError
56
+ # skip invalid lines
57
+ end
58
+ records
59
+ end
60
+
61
+ def get_today_orders
62
+ today_str = begin
63
+ Date.today.isoformat
64
+ rescue StandardError
65
+ Date.today.strftime("%Y-%m-%d")
66
+ end
67
+ _read_all_records.select { |r| r["timestamp"].start_with?(today_str) }
68
+ end
69
+
70
+ def get_trade_history(days = 7)
71
+ cutoff_time = Time.now - (days * 24 * 60 * 60)
72
+ cutoff_str = cutoff_time.strftime("%Y-%m-%dT%H:%M:%S%:z")
73
+
74
+ records = _read_all_records.select { |r| r["timestamp"] >= cutoff_str }
75
+ records.sort_by { |r| r["timestamp"] }.reverse
76
+ end
77
+
78
+ def get_trade_summary(days = 7)
79
+ records = get_trade_history(days)
80
+ summary = {
81
+ "period_days" => days,
82
+ "total_orders" => records.size,
83
+ "successful" => records.count { |r| r["status"] == "success" },
84
+ "failed" => records.count { |r| r["status"] != "success" },
85
+ "buy_count" => 0,
86
+ "sell_count" => 0,
87
+ "instruments_traded" => []
88
+ }
89
+
90
+ instruments = []
91
+ records.each do |r|
92
+ params = r["order_params"] || {}
93
+ txn = params["transaction_type"] || params[:transaction_type] || ""
94
+ if txn.to_s.upcase == DhanHQ::Constants::TransactionType::BUY
95
+ summary["buy_count"] += 1
96
+ elsif txn.to_s.upcase == DhanHQ::Constants::TransactionType::SELL
97
+ summary["sell_count"] += 1
98
+ end
99
+
100
+ sid = params["security_id"] || params[:security_id] || params["trading_symbol"] || params[:trading_symbol]
101
+ instruments << sid.to_s if sid
102
+ end
103
+
104
+ summary["instruments_traded"] = instruments.uniq
105
+ summary
106
+ end
107
+
108
+ def print_today_orders
109
+ orders = get_today_orders
110
+ if orders.empty?
111
+ puts "No orders placed today."
112
+ return
113
+ end
114
+
115
+ puts "--- Today's Orders (#{orders.size} total) ---"
116
+ orders.each do |r|
117
+ params = r["order_params"] || {}
118
+ status = r["status"] || "unknown"
119
+ oid = r["order_id"] || "N/A"
120
+ txn = params["transaction_type"] || params[:transaction_type] || "?"
121
+ sym = params["trading_symbol"] || params[:trading_symbol] || params["security_id"] || params[:security_id] || "?"
122
+ qty = params["quantity"] || params[:quantity] || "?"
123
+ price = params["price"] || params[:price] || "MKT"
124
+
125
+ time_part = r["timestamp"].split("T")[1] ? r["timestamp"].split("T")[1][0...8] : "00:00:00"
126
+
127
+ printf(" [%s] %-8s | %-4s %dx %s @ %s | ID: %s\n", time_part, status.to_s.upcase, txn.to_s.upcase, qty, sym, price, oid)
128
+ end
129
+ end
130
+
131
+ print_today_orders if __FILE__ == $PROGRAM_NAME
@@ -0,0 +1,169 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+ # rubocop:disable Metrics/AbcSize
4
+ # rubocop:disable Metrics/CyclomaticComplexity
5
+ # rubocop:disable Metrics/PerceivedComplexity
6
+ # rubocop:disable Metrics/ParameterLists
7
+ # rubocop:disable Style/FormatString
8
+
9
+ require "date"
10
+
11
+ LOT_SIZES = {
12
+ "NIFTY" => 75,
13
+ "BANKNIFTY" => 15,
14
+ "FINNIFTY" => 25,
15
+ "MIDCPNIFTY" => 50,
16
+ "SENSEX" => 10
17
+ }.freeze
18
+
19
+ FREEZE_QTY = {
20
+ "NIFTY" => 1800,
21
+ "BANKNIFTY" => 900,
22
+ "FINNIFTY" => 1000,
23
+ "MIDCPNIFTY" => 2800,
24
+ "SENSEX" => 500
25
+ }.freeze
26
+
27
+ VALID_EXCHANGE_SEGMENTS = %w[
28
+ NSE_EQ BSE_EQ NSE_FNO BSE_FNO MCX_COMM NSE_CURRENCY BSE_CURRENCY
29
+ ].freeze
30
+
31
+ EQUITY_SEGMENTS = %w[NSE_EQ BSE_EQ].freeze
32
+ DERIVATIVE_SEGMENTS = %w[NSE_FNO BSE_FNO MCX_COMM NSE_CURRENCY BSE_CURRENCY].freeze
33
+
34
+ EQUITY_PRODUCT_TYPES = %w[CNC INTRADAY MARGIN MTF].freeze
35
+ DERIVATIVE_PRODUCT_TYPES = %w[INTRADAY MARGIN].freeze
36
+
37
+ VALID_ORDER_TYPES = %w[LIMIT MARKET STOP_LOSS STOP_LOSS_MARKET].freeze
38
+ VALID_TRANSACTION_TYPES = %w[BUY SELL].freeze
39
+ VALID_VALIDITY = %w[DAY IOC].freeze
40
+
41
+ NOTIONAL_WARNING_THRESHOLD = 50_000
42
+
43
+ def _infer_lot_size(trading_symbol)
44
+ return nil if trading_symbol.nil? || trading_symbol.to_s.empty?
45
+
46
+ symbol_upper = trading_symbol.to_s.upcase
47
+ LOT_SIZES.each do |name, lot_size|
48
+ return lot_size if symbol_upper.include?(name)
49
+ end
50
+ nil
51
+ end
52
+
53
+ def _infer_freeze_qty(trading_symbol)
54
+ return nil if trading_symbol.nil? || trading_symbol.to_s.empty?
55
+
56
+ symbol_upper = trading_symbol.to_s.upcase
57
+ FREEZE_QTY.each do |name, freeze_qty|
58
+ return freeze_qty if symbol_upper.include?(name)
59
+ end
60
+ nil
61
+ end
62
+
63
+ def validate_order(
64
+ security_id: nil,
65
+ exchange_segment: nil,
66
+ transaction_type: nil,
67
+ quantity: nil,
68
+ order_type: nil,
69
+ product_type: nil,
70
+ price: 0.0,
71
+ trigger_price: 0.0,
72
+ validity: DhanHQ::Constants::Validity::DAY,
73
+ after_market_order: false,
74
+ trading_symbol: nil,
75
+ lot_size: nil
76
+ )
77
+ errors = []
78
+ warnings = []
79
+
80
+ exchange_segment = exchange_segment&.to_s&.upcase
81
+ transaction_type = transaction_type&.to_s&.upcase
82
+ order_type = order_type&.to_s&.upcase
83
+ product_type = product_type&.to_s&.upcase
84
+ validity = validity&.to_s&.upcase
85
+
86
+ errors << "security_id is required" if security_id.nil? || security_id.to_s.empty?
87
+ errors << "exchange_segment is required" if exchange_segment.nil? || exchange_segment.to_s.empty?
88
+ errors << "transaction_type is required" if transaction_type.nil? || transaction_type.to_s.empty?
89
+ errors << "quantity must be a positive integer" if quantity.nil? || quantity.to_i <= 0
90
+ errors << "order_type is required" if order_type.nil? || order_type.to_s.empty?
91
+ errors << "product_type is required" if product_type.nil? || product_type.to_s.empty?
92
+
93
+ errors << "Invalid exchange_segment: #{exchange_segment}" if exchange_segment && !VALID_EXCHANGE_SEGMENTS.include?(exchange_segment)
94
+ errors << "Invalid transaction_type: #{transaction_type}" if transaction_type && !VALID_TRANSACTION_TYPES.include?(transaction_type)
95
+ errors << "Invalid order_type: #{order_type}" if order_type && !VALID_ORDER_TYPES.include?(order_type)
96
+ errors << "Invalid validity: #{validity}" if validity && !VALID_VALIDITY.include?(validity)
97
+
98
+ errors << "price is required for #{order_type} orders" if %w[LIMIT STOP_LOSS].include?(order_type) && price.to_f <= 0
99
+ errors << "trigger_price is required for #{order_type} orders" if %w[STOP_LOSS STOP_LOSS_MARKET].include?(order_type) && trigger_price.to_f <= 0
100
+
101
+ if exchange_segment && EQUITY_SEGMENTS.include?(exchange_segment) && product_type && !EQUITY_PRODUCT_TYPES.include?(product_type)
102
+ errors << "Invalid product_type '#{product_type}' for equity segment '#{exchange_segment}'. Valid values: #{EQUITY_PRODUCT_TYPES.sort}"
103
+ end
104
+
105
+ if exchange_segment && DERIVATIVE_SEGMENTS.include?(exchange_segment) && product_type && !DERIVATIVE_PRODUCT_TYPES.include?(product_type)
106
+ errors << "Invalid product_type '#{product_type}' for derivative segment '#{exchange_segment}'. Valid values: #{DERIVATIVE_PRODUCT_TYPES.sort}"
107
+ end
108
+
109
+ warnings << "Dhan's current order docs say API market orders are converted to limit orders with MPP." if order_type == DhanHQ::Constants::OrderType::MARKET
110
+
111
+ effective_lot_size = lot_size || _infer_lot_size(trading_symbol)
112
+ if exchange_segment && DERIVATIVE_SEGMENTS.include?(exchange_segment) && quantity
113
+ if effective_lot_size && quantity.to_i % effective_lot_size != 0
114
+ errors << "Derivative quantity must be a multiple of lot size #{effective_lot_size}. Got #{quantity}."
115
+ elsif effective_lot_size.nil?
116
+ warnings << "Could not resolve a lot size from the provided data. Confirm lot size from the security master before placing."
117
+ end
118
+
119
+ freeze_qty = _infer_freeze_qty(trading_symbol)
120
+ if freeze_qty && quantity.to_i > freeze_qty
121
+ warnings << "Quantity #{quantity} exceeds fallback freeze quantity #{freeze_qty}. Consider place_slice_order() after verifying the latest exchange freeze limits."
122
+ end
123
+ end
124
+
125
+ if price.to_f.positive? && quantity
126
+ notional = price.to_f * quantity.to_i
127
+ warnings << "High notional value: Rs. #{"%.2f" % notional} exceeds the Rs. 50,000 warning threshold." if notional > NOTIONAL_WARNING_THRESHOLD
128
+ end
129
+
130
+ unless after_market_order
131
+ now = Time.now
132
+ if now.saturday? || now.sunday?
133
+ warnings << "Market is closed on weekends. Use AMO only if that is intentional."
134
+ elsif now.hour < 9 || (now.hour == 9 && now.min < 15)
135
+ warnings << "Regular market is not yet open."
136
+ elsif now.hour > 15 || (now.hour == 15 && now.min > 30)
137
+ warnings << "Regular market is closed. Use AMO only if that is intentional."
138
+ end
139
+ end
140
+
141
+ {
142
+ "valid" => errors.empty?,
143
+ "errors" => errors,
144
+ "warnings" => warnings
145
+ }
146
+ end
147
+
148
+ def print_validation(result)
149
+ if result["valid"]
150
+ puts "Order validation: PASS"
151
+ else
152
+ puts "Order validation: FAIL"
153
+ result["errors"].each { |error| puts " ERROR: #{error}" }
154
+ end
155
+ result["warnings"].each { |warning| puts " WARNING: #{warning}" }
156
+ end
157
+
158
+ if __FILE__ == $PROGRAM_NAME
159
+ sample = validate_order(
160
+ security_id: "2885",
161
+ exchange_segment: DhanHQ::Constants::ExchangeSegment::NSE_EQ,
162
+ transaction_type: DhanHQ::Constants::TransactionType::BUY,
163
+ quantity: 10,
164
+ order_type: DhanHQ::Constants::OrderType::LIMIT,
165
+ product_type: DhanHQ::Constants::ProductType::CNC,
166
+ price: 2450
167
+ )
168
+ print_validation(sample)
169
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: DhanHQ
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.2.0
4
+ version: 3.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Shubham Taywade
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-07-25 00:00:00.000000000 Z
11
+ date: 2026-07-26 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activesupport
@@ -176,8 +176,10 @@ executables:
176
176
  extensions: []
177
177
  extra_rdoc_files: []
178
178
  files:
179
+ - AGENTS.md
179
180
  - ARCHITECTURE.md
180
181
  - CHANGELOG.md
182
+ - CODE_OF_CONDUCT.md
181
183
  - GUIDE.md
182
184
  - LICENSE.txt
183
185
  - README.md
@@ -227,7 +229,9 @@ files:
227
229
  - lib/DhanHQ/auth/token_manager.rb
228
230
  - lib/DhanHQ/auth/token_renewal.rb
229
231
  - lib/DhanHQ/client.rb
232
+ - lib/DhanHQ/concerns/bang_writes.rb
230
233
  - lib/DhanHQ/concerns/order_audit.rb
234
+ - lib/DhanHQ/concerns/tracked_writes.rb
231
235
  - lib/DhanHQ/configuration.rb
232
236
  - lib/DhanHQ/constants.rb
233
237
  - lib/DhanHQ/contracts/alert_order_contract.rb
@@ -264,6 +268,7 @@ files:
264
268
  - lib/DhanHQ/core/base_model.rb
265
269
  - lib/DhanHQ/core/base_resource.rb
266
270
  - lib/DhanHQ/core/error_handler.rb
271
+ - lib/DhanHQ/deprecation.rb
267
272
  - lib/DhanHQ/dry_run/ledger.rb
268
273
  - lib/DhanHQ/dry_run/simulator.rb
269
274
  - lib/DhanHQ/error_object.rb
@@ -389,6 +394,7 @@ files:
389
394
  - lib/DhanHQ/utils/network_inspector.rb
390
395
  - lib/DhanHQ/version.rb
391
396
  - lib/DhanHQ/write_paths.rb
397
+ - lib/DhanHQ/write_result.rb
392
398
  - lib/DhanHQ/ws.rb
393
399
  - lib/DhanHQ/ws/base_connection.rb
394
400
  - lib/DhanHQ/ws/client.rb
@@ -435,6 +441,34 @@ files:
435
441
  - lib/ta/market_calendar.rb
436
442
  - lib/ta/technical_analysis.rb
437
443
  - sig/DhanHQ.rbs
444
+ - skills/dhanhq-ruby/SKILL.md
445
+ - skills/dhanhq-ruby/examples/fetch_option_chain.rb
446
+ - skills/dhanhq-ruby/examples/gtt_forever_order.rb
447
+ - skills/dhanhq-ruby/examples/historical_data_analysis.rb
448
+ - skills/dhanhq-ruby/examples/iron_condor.rb
449
+ - skills/dhanhq-ruby/examples/live_feed_setup.rb
450
+ - skills/dhanhq-ruby/examples/margin_check.rb
451
+ - skills/dhanhq-ruby/examples/order_management.rb
452
+ - skills/dhanhq-ruby/examples/place_equity_order.rb
453
+ - skills/dhanhq-ruby/examples/place_fno_order.rb
454
+ - skills/dhanhq-ruby/examples/portfolio_summary.rb
455
+ - skills/dhanhq-ruby/examples/super_order_with_sl.rb
456
+ - skills/dhanhq-ruby/references/backtesting-with-dhan.md
457
+ - skills/dhanhq-ruby/references/common-workflows.md
458
+ - skills/dhanhq-ruby/references/error-codes.md
459
+ - skills/dhanhq-ruby/references/funds.md
460
+ - skills/dhanhq-ruby/references/instruments.md
461
+ - skills/dhanhq-ruby/references/live-feed.md
462
+ - skills/dhanhq-ruby/references/market-data.md
463
+ - skills/dhanhq-ruby/references/option-chain.md
464
+ - skills/dhanhq-ruby/references/options-analysis-patterns.md
465
+ - skills/dhanhq-ruby/references/orders.md
466
+ - skills/dhanhq-ruby/references/portfolio.md
467
+ - skills/dhanhq-ruby/references/scanx-data.md
468
+ - skills/dhanhq-ruby/scripts/dhan_helpers.rb
469
+ - skills/dhanhq-ruby/scripts/resolve_security.rb
470
+ - skills/dhanhq-ruby/scripts/trade_logger.rb
471
+ - skills/dhanhq-ruby/scripts/validate_order.rb
438
472
  homepage: https://github.com/shubhamtaywade82/dhanhq-client
439
473
  licenses:
440
474
  - MIT