DhanHQ 2.7.0 → 2.8.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: df325d70c7c2e3c13493ad199ca8e11bb7f5a9df1d62a775452e4fb1eeed5842
4
- data.tar.gz: 7cfde3f38fa073311ad50992ef497ba7391927b78136346e7549c135e7a4d7cc
3
+ metadata.gz: 6d2ca9bd3c9c4f61504d06e8b2736baf9ded579d04bb21523a9e0c5fe9a74298
4
+ data.tar.gz: a981472b44efa9c86c1daa83461c27985664a0682022d3aa4b3e925a950788aa
5
5
  SHA512:
6
- metadata.gz: 945e4a71c15f01e33f7f05a3ed2453e7558c46d9c9bb5067a6225e68e87b4c3aac4a903ff08da384b488f9b8d36764f9f1f47103a8a8db4d5b90d1ea97e09252
7
- data.tar.gz: 1b805c79a999c6604cd58d8df163c339233b09732d77c1911010dfa3d5ea32e12ae27d166b1484621338ba378acace69003328e9e6d4ec3654eb646df753c2c0
6
+ metadata.gz: 03b2f01541f005e6d9ebd4d706023cf553b17bb80327f480f350e5d465a582006b0fc199cc541a804631a71a034b8cd454c8c715e962b95794df665e75eb0a63
7
+ data.tar.gz: e7320d2ae5e332238cf0e11bcd0f29ecd368772242019567f5dcb525e4b8baa9e71c5191b51b25724cd090ac82fb113524bb0578480f1bf71b82834bc74cda6d
data/CHANGELOG.md CHANGED
@@ -1,3 +1,27 @@
1
+ ## [2.8.0] - 2026-03-21
2
+
3
+ ### Added
4
+
5
+ - **Complete SDK Documentation Overhaul**: Added high-level guides and structured learning paths for Ruby developers:
6
+ - `BEST_WAY_TO_USE_DHAN_API_IN_RUBY.md`: Strategic advice for Ruby-centric integration.
7
+ - `BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md`: Step-by-step tutorial for algo trading.
8
+ - `HOW_TO_USE_DHAN_API_WITH_RUBY.md`: Foundational guide for REST and WebSocket.
9
+ - `DHAN_API_RUBY_EXAMPLES.md`: Curated collection of common API patterns.
10
+ - `DHAN_WEBSOCKET_RUBY_GUIDE.md`: Deep dive into real-time market data and order updates.
11
+ - `DHAN_RUBY_QA.md`: Troubleshooting and frequently asked questions.
12
+ - **Production-Ready Examples**:
13
+ - `examples/basic_trading_bot.rb`: Skeleton for a strategy-based bot.
14
+ - `examples/options_watchlist.rb`: Script for monitoring specific option strikes.
15
+ - `examples/portfolio_monitor.rb`: Live tracker for PnL and position status.
16
+ - **Architectural Visualization**: New `docs/architecture-overview.svg` illustrating the SDK's layered design (Models, Resources, Contracts, WebSocket).
17
+
18
+ ### Changed
19
+
20
+ - **SDK Positioning**: Updated `README.md` and `DhanHQ.gemspec` to reflect the SDK's status as a "production-grade Ruby SDK for Dhan API v2" with an emphasis on algo trading, portfolio monitoring, and resilient streaming.
21
+ - **Documentation Refinement**: Improved clarity and navigation in `CONFIGURATION.md`, `LIVE_ORDER_UPDATES.md`, `RAILS_INTEGRATION.md`, `TESTING_GUIDE.md`, `TROUBLESHOOTING.md`, and `WEBSOCKET_INTEGRATION.md`.
22
+
23
+ ---
24
+
1
25
  ## [2.7.0] - 2026-03-17
2
26
 
3
27
  ### Added
data/README.md CHANGED
@@ -1,13 +1,31 @@
1
- # DhanHQ — Ruby Client for Dhan API v2
1
+ # DhanHQ — The Ruby SDK for Dhan API v2
2
2
 
3
3
  [![Gem Version](https://badge.fury.io/rb/DhanHQ.svg)](https://rubygems.org/gems/DhanHQ)
4
4
  [![CI](https://github.com/shubhamtaywade82/dhanhq-client/actions/workflows/main.yml/badge.svg)](https://github.com/shubhamtaywade82/dhanhq-client/actions/workflows/main.yml)
5
5
  [![Ruby](https://img.shields.io/badge/ruby-%3E%3D%203.2-ruby.svg)](https://www.ruby-lang.org)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE.txt)
7
7
 
8
- A production-grade Ruby SDK for the [Dhan trading API](https://dhanhq.co/docs/v2/) — ORM-like models, WebSocket market feeds, and battle-tested reliability for real trading.
8
+ Build trading systems in Ruby without fighting raw HTTP, fragile auth flows, or unreliable market streams.
9
9
 
10
- ## 🚀 60-Second Quick Start
10
+ DhanHQ is a production-grade Ruby SDK for the [Dhan trading API](https://dhanhq.co/docs/v2/), designed for:
11
+
12
+ - trading bots
13
+ - real-time market data streaming
14
+ - portfolio and order management
15
+ - Rails or standalone trading systems
16
+
17
+ If you're looking for a Ruby SDK for Dhan API, this is built to be the default choice.
18
+
19
+ Unlike thin wrappers, DhanHQ gives you:
20
+
21
+ - typed models for orders, positions, holdings, and more
22
+ - WebSocket clients with auto-reconnect and backoff
23
+ - token lifecycle management with retry-on-401
24
+ - safety rails for live trading
25
+
26
+ This is closer to trading infrastructure than a simple API client.
27
+
28
+ ## Install and Run in 60 Seconds
11
29
 
12
30
  ```ruby
13
31
  # Gemfile
@@ -22,25 +40,69 @@ DhanHQ.configure do |c|
22
40
  c.access_token = ENV["DHAN_ACCESS_TOKEN"]
23
41
  end
24
42
 
25
- # You're live
43
+ # You're live — no manual HTTP, no JSON parsing
26
44
  positions = DhanHQ::Models::Position.all
27
- holdings = DhanHQ::Models::Holding.all
28
45
  ```
29
46
 
30
47
  ---
31
48
 
32
- ## Why DhanHQ?
49
+ ## Who This Is For
50
+
51
+ - Ruby developers building trading bots
52
+ - Rails apps integrating the Dhan API
53
+ - Algo trading systems that need clean abstractions over raw HTTP
54
+ - Long-running processes that rely on WebSocket market data
55
+
56
+ ## Who This Is Not For
57
+
58
+ - One-off scripts where raw HTTP is enough
59
+ - Non-Ruby stacks
60
+
61
+ ---
62
+
63
+ ## Start Here (Pick Your Use Case)
64
+
65
+ Pick the path that matches what you want to build:
66
+
67
+ - **Get live prices fast** → [Market Feed WebSocket](#market-feed-ticker--quote--full)
68
+ - **Place orders safely** → [Order Safety](#order-safety)
69
+ - **Build a trading strategy** → [WebSockets](#websockets)
70
+ - **Build a trading bot** → [examples/basic_trading_bot.rb](examples/basic_trading_bot.rb)
71
+ - **Use with Rails** → [docs/RAILS_INTEGRATION.md](docs/RAILS_INTEGRATION.md)
72
+
73
+ ---
74
+
75
+ ## Trust Signals
76
+
77
+ - **CI on supported Rubies** — GitHub Actions runs RSpec on Ruby 3.2.0 and 3.3.4, plus RuboCop on every push and pull request
78
+ - **Typed domain models** — Orders, Positions, Holdings, Funds, MarketFeed, OptionChain, Super Orders, and more expose a Ruby-first API instead of raw hashes
79
+ - **No real API calls in the default test suite** — WebMock blocks outbound HTTP and VCR covers cassette-backed integration paths
80
+ - **Auth lifecycle support** — static tokens, dynamic token providers, 401 retry with refresh hooks, and token sanitization in logs
81
+ - **WebSocket resilience** — reconnect, backoff, 429 cool-off, local connection cleanup, and dedicated market/order stream clients
82
+ - **Live trading guardrails** — order placement is blocked unless `LIVE_TRADING=true`, and order attempts emit structured audit logs
83
+
84
+ ---
85
+
86
+ ## Why Not a Thin Wrapper?
33
87
 
34
- You could wire up Faraday and parse JSON yourself. Here's why you shouldn't:
88
+ Most API clients give you HTTP access. DhanHQ gives you a working Ruby system.
35
89
 
36
- | You get | Instead of |
37
- | ------------------------------ | --------------------------------------------- |
38
- | ActiveModel-style `find`, `all`, `save`, `cancel` | Manual HTTP + JSON wrangling |
39
- | Typed models with validations | Hash soup and runtime surprises |
40
- | Auto token refresh + retry-on-401 | Silent auth failures at 3 AM |
41
- | WebSocket reconnection with backoff | Dropped connections during volatile moves |
42
- | 429 rate-limit cool-off | Getting banned by the exchange |
43
- | Thread-safe, secure logging | Leaked tokens in production logs |
90
+ | Instead of | You get |
91
+ | ---------- | -------- |
92
+ | JSON parsing and manual field mapping | Typed models |
93
+ | Manual auth refresh | Built-in token lifecycle |
94
+ | Fragile WebSocket code | Auto-reconnect, backoff, and 429 handling |
95
+ | Risky order scripts | Live trading guardrails and audit logs |
96
+
97
+ ---
98
+
99
+ ## Architecture At A Glance
100
+
101
+ ![DhanHQ architecture overview](docs/architecture-overview.svg)
102
+
103
+ Models own the Ruby API. Resources own HTTP calls. Contracts validate inputs. The transport layer handles auth, retries, rate limiting, and error mapping. WebSockets are a separate subsystem that shares configuration but not the REST stack.
104
+
105
+ For the full dependency flow and extension pattern, see [ARCHITECTURE.md](ARCHITECTURE.md).
44
106
 
45
107
  ---
46
108
 
@@ -62,6 +124,18 @@ You could wire up Faraday and parse JSON yourself. Here's why you shouldn't:
62
124
 
63
125
  ---
64
126
 
127
+ ## Reliability & Safety
128
+
129
+ - retry-on-401 with token refresh
130
+ - WebSocket auto-reconnect and backoff
131
+ - 429 rate-limit protection
132
+ - live trading guard via `LIVE_TRADING=true`
133
+ - structured order audit logs
134
+
135
+ See [ARCHITECTURE.md](ARCHITECTURE.md), [docs/TESTING_GUIDE.md](docs/TESTING_GUIDE.md), and [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) for the deeper implementation details.
136
+
137
+ ---
138
+
65
139
  ## Installation
66
140
 
67
141
  ```ruby
@@ -336,23 +410,56 @@ Need initializers, service objects, ActionCable wiring, and background workers?
336
410
 
337
411
  ---
338
412
 
413
+ ## Real-World Examples
414
+
415
+ These scripts are designed around user goals rather than API surfaces:
416
+
417
+ | Example | Use case |
418
+ | ------- | -------- |
419
+ | [examples/basic_trading_bot.rb](examples/basic_trading_bot.rb) | Pull historical data, evaluate a simple signal, and place a guarded order |
420
+ | [examples/portfolio_monitor.rb](examples/portfolio_monitor.rb) | Snapshot funds, holdings, and positions for a monitoring script |
421
+ | [examples/options_watchlist.rb](examples/options_watchlist.rb) | Build a live options watchlist with index quotes and option-chain context |
422
+ | [examples/market_feed_example.rb](examples/market_feed_example.rb) | Subscribe to major market indices over WebSocket |
423
+ | [examples/live_order_updates.rb](examples/live_order_updates.rb) | Track order lifecycle events in real time |
424
+
425
+ For search-driven discovery and onboarding content, see:
426
+
427
+ - [docs/HOW_TO_USE_DHAN_API_WITH_RUBY.md](docs/HOW_TO_USE_DHAN_API_WITH_RUBY.md)
428
+ - [docs/BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md](docs/BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md)
429
+
430
+ ## Use Case Guides
431
+
432
+ - [docs/DHAN_API_RUBY_EXAMPLES.md](docs/DHAN_API_RUBY_EXAMPLES.md)
433
+ - [docs/DHAN_WEBSOCKET_RUBY_GUIDE.md](docs/DHAN_WEBSOCKET_RUBY_GUIDE.md)
434
+ - [docs/BEST_WAY_TO_USE_DHAN_API_IN_RUBY.md](docs/BEST_WAY_TO_USE_DHAN_API_IN_RUBY.md)
435
+ - [docs/DHAN_RUBY_QA.md](docs/DHAN_RUBY_QA.md)
436
+
437
+ ---
438
+
339
439
  ## 📚 Documentation
340
440
 
341
441
  | Guide | What it covers |
342
442
  | ----- | -------------- |
443
+ | [Architecture](ARCHITECTURE.md) | Layering, dependency flow, design patterns, extension points |
343
444
  | [Authentication](docs/AUTHENTICATION.md) | Token flows, TOTP, OAuth, auto-management |
344
445
  | [Configuration Reference](docs/CONFIGURATION.md) | Full ENV matrix, logging, timeouts, available resources |
345
446
  | [WebSocket Integration](docs/WEBSOCKET_INTEGRATION.md) | All WS types, architecture, best practices |
346
447
  | [WebSocket Protocol](docs/WEBSOCKET_PROTOCOL.md) | Packet parsing, request codes, tick schema, exchange enums |
347
448
  | [Rails WebSocket Guide](docs/RAILS_WEBSOCKET_INTEGRATION.md) | Rails-specific patterns, ActionCable |
348
449
  | [Rails Integration](docs/RAILS_INTEGRATION.md) | Initializers, service objects, workers |
349
- | [Standalone Ruby Guide](docs/STANDALONE_RUBY_WEBSOCKET_INTEGRATION.md) | Scripts, daemons, CLI tools |
450
+ | [Standalone Ruby Guide](docs/STANDALONE_RUBY_WEBSOCKET_INTEGRATION.md) | Scripts, daemons, and long-running Ruby processes |
350
451
  | [Super Orders API](docs/SUPER_ORDERS.md) | Full REST reference for super orders |
351
452
  | [API Constants Reference](docs/CONSTANTS_REFERENCE.md) | All valid enums, exchange segments, and order parameters |
352
453
  | [Data API Parameters](docs/DATA_API_PARAMETERS.md) | Historical data, option chain parameters |
353
454
  | [Testing Guide](docs/TESTING_GUIDE.md) | WebSocket testing, model testing, console helpers |
354
455
  | [Technical Analysis](docs/TECHNICAL_ANALYSIS.md) | Indicators, multi-timeframe aggregation |
355
456
  | [Troubleshooting](docs/TROUBLESHOOTING.md) | 429 errors, reconnect, auth issues, debug logging |
457
+ | [How To Use Dhan API With Ruby](docs/HOW_TO_USE_DHAN_API_WITH_RUBY.md) | Search-friendly onboarding guide for Ruby users |
458
+ | [Build A Trading Bot With Ruby And Dhan](docs/BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md) | End-to-end tutorial framing for strategy builders |
459
+ | [Dhan API Ruby Examples](docs/DHAN_API_RUBY_EXAMPLES.md) | Small answer-style snippets for common Ruby + Dhan tasks |
460
+ | [Dhan WebSocket Ruby Guide](docs/DHAN_WEBSOCKET_RUBY_GUIDE.md) | Query-shaped guide for Dhan market data streaming in Ruby |
461
+ | [Best Way To Use Dhan API In Ruby](docs/BEST_WAY_TO_USE_DHAN_API_IN_RUBY.md) | Comparison-focused guide for SDK vs raw HTTP |
462
+ | [Dhan Ruby Q&A](docs/DHAN_RUBY_QA.md) | Publish-ready answers for common Dhan + Ruby questions |
356
463
  | [Release Guide](docs/RELEASE_GUIDE.md) | Versioning, publishing, changelog |
357
464
 
358
465
  ---
@@ -364,6 +471,7 @@ Need initializers, service objects, ActionCable wiring, and background workers?
364
471
  - Don't exceed **100 instruments per subscribe frame** (auto-chunked by the client)
365
472
  - Call `DhanHQ::WS.disconnect_all_local!` on shutdown
366
473
  - Avoid rapid connect/disconnect loops — the client already backs off on 429
474
+ - Use dynamic token providers in long-running systems instead of hardcoding expiring tokens
367
475
 
368
476
  ---
369
477
 
@@ -0,0 +1,36 @@
1
+ # Best Way To Use Dhan API In Ruby
2
+
3
+ The best way to use Dhan API in Ruby is usually not raw HTTP. It is a Ruby SDK that already understands the shape of trading workflows: authentication, market data, streaming, and order execution.
4
+
5
+ That is the role of `DhanHQ`, the Ruby SDK for Dhan API v2.
6
+
7
+ ## SDK Vs Raw HTTP
8
+
9
+ Raw HTTP is fine when you only need one endpoint once.
10
+
11
+ For ongoing Ruby applications, the SDK is usually the better fit:
12
+
13
+ - typed models instead of manual JSON mapping
14
+ - token lifecycle support instead of handwritten refresh logic
15
+ - WebSocket reconnect and backoff instead of custom event-loop recovery
16
+ - live-trading guardrails instead of fragile order scripts
17
+ - one Ruby interface for market data, holdings, positions, and orders
18
+
19
+ ## When Raw HTTP Is Enough
20
+
21
+ - you are writing a one-off experiment
22
+ - you only need one endpoint
23
+ - you do not need streaming or long-running behavior
24
+
25
+ ## When The Ruby SDK Is Better
26
+
27
+ - you are building a trading bot
28
+ - you are integrating Dhan into a Rails app
29
+ - you need Dhan WebSocket support in Ruby
30
+ - you want clean abstractions over raw trading endpoints
31
+
32
+ ## Start Here
33
+
34
+ - [README.md](../README.md)
35
+ - [HOW_TO_USE_DHAN_API_WITH_RUBY.md](HOW_TO_USE_DHAN_API_WITH_RUBY.md)
36
+ - [BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md](BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md)
@@ -0,0 +1,111 @@
1
+ # Build A Trading Bot With Ruby And Dhan
2
+
3
+ If your goal is to build a trading bot with Ruby and Dhan, you do not need to start from raw REST calls and custom WebSocket loops. `DhanHQ` is the Ruby SDK for Dhan API v2, and it already gives you the core pieces a Ruby trading bot needs: historical data access, live market data streaming, order models, token lifecycle handling, and live-trading guardrails.
4
+
5
+ This guide shows the minimal path from market data to signal to guarded execution.
6
+
7
+ ## 1. Configure The SDK
8
+
9
+ ```ruby
10
+ require "dhan_hq"
11
+
12
+ DhanHQ.configure_with_env
13
+ ```
14
+
15
+ Set:
16
+
17
+ - `DHAN_CLIENT_ID`
18
+ - `DHAN_ACCESS_TOKEN`
19
+
20
+ Only set `LIVE_TRADING=true` when you intentionally want to place live orders.
21
+
22
+ ## 2. Pull Historical Data For The Signal
23
+
24
+ Use the Dhan API from Ruby to fetch recent bars:
25
+
26
+ ```ruby
27
+ bars = DhanHQ::Models::HistoricalData.intraday(
28
+ security_id: "13",
29
+ exchange_segment: DhanHQ::Constants::ExchangeSegment::IDX_I,
30
+ instrument: DhanHQ::Constants::InstrumentType::INDEX,
31
+ interval: "5",
32
+ from_date: Date.today.to_s,
33
+ to_date: Date.today.to_s
34
+ )
35
+ ```
36
+
37
+ The runnable version of this flow lives in [examples/basic_trading_bot.rb](../examples/basic_trading_bot.rb).
38
+
39
+ ## 3. Compute A Simple Trading Signal
40
+
41
+ ```ruby
42
+ closes = bars.map { |bar| bar[:close].to_f }
43
+ last_close = closes.last
44
+ sma20 = closes.last(20).sum / 20.0
45
+ signal = last_close > sma20 ? :bullish : :bearish
46
+ ```
47
+
48
+ This is intentionally simple. The point is not the strategy itself. The point is that the Ruby SDK for Dhan API gets you to a working trading loop quickly.
49
+
50
+ ## 4. Add Live Market Data
51
+
52
+ Most trading bots need streaming updates after the initial historical snapshot.
53
+
54
+ ```ruby
55
+ # Example: Subscribe to live market data using Dhan API WebSocket in Ruby
56
+ client = DhanHQ::WS.connect(mode: :quote) do |tick|
57
+ puts "#{tick[:security_id]} -> #{tick[:ltp]}"
58
+ end
59
+
60
+ client.subscribe_one(
61
+ segment: DhanHQ::Constants::ExchangeSegment::IDX_I,
62
+ security_id: "13"
63
+ )
64
+ ```
65
+
66
+ For a fuller live-data script, see [examples/options_watchlist.rb](../examples/options_watchlist.rb).
67
+
68
+ ## 5. Execute Safely
69
+
70
+ If the signal is bullish, you can build an order model:
71
+
72
+ ```ruby
73
+ order = DhanHQ::Models::Order.new(
74
+ transaction_type: DhanHQ::Constants::TransactionType::BUY,
75
+ exchange_segment: DhanHQ::Constants::ExchangeSegment::NSE_EQ,
76
+ product_type: DhanHQ::Constants::ProductType::CNC,
77
+ order_type: DhanHQ::Constants::OrderType::MARKET,
78
+ validity: DhanHQ::Constants::Validity::DAY,
79
+ security_id: "11536",
80
+ quantity: 1
81
+ )
82
+
83
+ # order.save
84
+ ```
85
+
86
+ Keep `order.save` commented while you are developing. `DhanHQ` will only submit live orders when `LIVE_TRADING=true`, which is one of the reasons it is safer than raw order scripts.
87
+
88
+ ## 6. Grow Into A Real Trading System
89
+
90
+ Once you have the basic bot loop, the same SDK supports:
91
+
92
+ - WebSocket order updates
93
+ - option-chain workflows
94
+ - Rails integration for service objects and workers
95
+ - token providers for long-running processes
96
+
97
+ Use these next:
98
+
99
+ - [examples/basic_trading_bot.rb](../examples/basic_trading_bot.rb)
100
+ - [examples/options_watchlist.rb](../examples/options_watchlist.rb)
101
+ - [WEBSOCKET_INTEGRATION.md](WEBSOCKET_INTEGRATION.md)
102
+ - [AUTHENTICATION.md](AUTHENTICATION.md)
103
+ - [RAILS_INTEGRATION.md](RAILS_INTEGRATION.md)
104
+
105
+ ## Canonical Publishing Notes
106
+
107
+ If you publish this externally:
108
+
109
+ - keep the title exactly `Build a Trading Bot With Ruby and Dhan`
110
+ - link back to the repo root and the example scripts
111
+ - keep the intro sentence that frames `DhanHQ` as `the Ruby SDK for Dhan API`
@@ -1,6 +1,6 @@
1
1
  # Configuration Reference
2
2
 
3
- This document covers all configuration options for the DhanHQ Ruby client.
3
+ This document covers all configuration options for the DhanHQ Ruby SDK.
4
4
 
5
5
  ## Quick Setup
6
6
 
@@ -0,0 +1,71 @@
1
+ # Dhan API Ruby Examples
2
+
3
+ This page collects small, direct examples for people searching for `Dhan API Ruby`, `Ruby SDK for Dhan API examples`, or `Dhan trading SDK for Ruby`.
4
+
5
+ All examples use `DhanHQ`, the Ruby SDK for Dhan API v2.
6
+
7
+ ## Setup
8
+
9
+ ```ruby
10
+ require "dhan_hq"
11
+
12
+ DhanHQ.configure_with_env
13
+ ```
14
+
15
+ ## Example: Get Positions In Ruby
16
+
17
+ ```ruby
18
+ # Example: Fetch positions using Dhan API in Ruby
19
+ positions = DhanHQ::Models::Position.all
20
+ ```
21
+
22
+ ## Example: Get Holdings In Ruby
23
+
24
+ ```ruby
25
+ # Example: Fetch holdings using Dhan API in Ruby
26
+ holdings = DhanHQ::Models::Holding.all
27
+ ```
28
+
29
+ ## Example: Fetch Historical Data In Ruby
30
+
31
+ ```ruby
32
+ bars = DhanHQ::Models::HistoricalData.intraday(
33
+ security_id: "13",
34
+ exchange_segment: DhanHQ::Constants::ExchangeSegment::IDX_I,
35
+ instrument: DhanHQ::Constants::InstrumentType::INDEX,
36
+ interval: "5",
37
+ from_date: Date.today.to_s,
38
+ to_date: Date.today.to_s
39
+ )
40
+ ```
41
+
42
+ ## Example: Subscribe To Live Market Data In Ruby
43
+
44
+ ```ruby
45
+ # Example: Subscribe to live market data using Dhan API WebSocket in Ruby
46
+ client = DhanHQ::WS.connect(mode: :ticker) do |tick|
47
+ puts "#{tick[:security_id]} -> #{tick[:ltp]}"
48
+ end
49
+ ```
50
+
51
+ ## Example: Build An Order Payload In Ruby
52
+
53
+ ```ruby
54
+ order = DhanHQ::Models::Order.new(
55
+ transaction_type: DhanHQ::Constants::TransactionType::BUY,
56
+ exchange_segment: DhanHQ::Constants::ExchangeSegment::NSE_EQ,
57
+ product_type: DhanHQ::Constants::ProductType::CNC,
58
+ order_type: DhanHQ::Constants::OrderType::MARKET,
59
+ validity: DhanHQ::Constants::Validity::DAY,
60
+ security_id: "11536",
61
+ quantity: 1
62
+ )
63
+ ```
64
+
65
+ ## Where To Go Next
66
+
67
+ - [README.md](../README.md)
68
+ - [HOW_TO_USE_DHAN_API_WITH_RUBY.md](HOW_TO_USE_DHAN_API_WITH_RUBY.md)
69
+ - [examples/portfolio_monitor.rb](../examples/portfolio_monitor.rb)
70
+ - [examples/basic_trading_bot.rb](../examples/basic_trading_bot.rb)
71
+ - [examples/options_watchlist.rb](../examples/options_watchlist.rb)
@@ -0,0 +1,27 @@
1
+ # Dhan Ruby Q&A
2
+
3
+ This document contains publish-ready answers for common questions about Dhan API and Ruby. The goal is to create question-shaped content that maps `Dhan API + Ruby` to `DhanHQ`.
4
+
5
+ ## How To Use Dhan API In Ruby?
6
+
7
+ Use `DhanHQ`, the Ruby SDK for Dhan API v2. It gives you typed models, WebSocket support, token lifecycle management, and safer order workflows. Start with [README.md](../README.md) and [HOW_TO_USE_DHAN_API_WITH_RUBY.md](HOW_TO_USE_DHAN_API_WITH_RUBY.md).
8
+
9
+ ## Is There A Ruby SDK For Dhan API?
10
+
11
+ Yes. `DhanHQ` is a Ruby SDK for Dhan API that covers REST, WebSocket market data, order updates, holdings, positions, and order workflows. See [README.md](../README.md).
12
+
13
+ ## How Do I Build A Trading Bot With Dhan In Ruby?
14
+
15
+ Use [examples/basic_trading_bot.rb](../examples/basic_trading_bot.rb) together with [BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md](BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md). The SDK already provides historical data, live market data, and order models.
16
+
17
+ ## How Do I Use Dhan WebSocket In Ruby?
18
+
19
+ Use `DhanHQ::WS.connect` for market data and `DhanHQ::WS::Orders` for order updates. Start with [Dhan WebSocket Ruby Guide](DHAN_WEBSOCKET_RUBY_GUIDE.md) and [examples/options_watchlist.rb](../examples/options_watchlist.rb).
20
+
21
+ ## Is DhanHQ Better Than Calling Dhan API With Raw HTTP In Ruby?
22
+
23
+ For long-running Ruby systems, usually yes. The SDK gives you token refresh support, typed models, reconnect handling, and safer order workflows. See [BEST_WAY_TO_USE_DHAN_API_IN_RUBY.md](BEST_WAY_TO_USE_DHAN_API_IN_RUBY.md).
24
+
25
+ ## Can I Use DhanHQ In Rails?
26
+
27
+ Yes. The SDK has a dedicated Rails integration guide for initializers, service objects, and worker patterns. See [RAILS_INTEGRATION.md](RAILS_INTEGRATION.md).
@@ -0,0 +1,38 @@
1
+ # Dhan WebSocket Ruby Guide
2
+
3
+ If you are searching for `Dhan WebSocket Ruby`, `Dhan API WebSocket in Ruby`, or `Ruby SDK for Dhan market data streaming`, this is the shortest path.
4
+
5
+ `DhanHQ` provides the WebSocket layer for Ruby applications that need live market data, market depth, and order updates without rebuilding reconnect and rate-limit handling from scratch.
6
+
7
+ ## Basic Market Feed Example
8
+
9
+ ```ruby
10
+ require "dhan_hq"
11
+
12
+ DhanHQ.configure_with_env
13
+
14
+ # Example: Subscribe to live market data using Dhan API WebSocket in Ruby
15
+ client = DhanHQ::WS.connect(mode: :quote) do |tick|
16
+ puts "#{tick[:security_id]} -> #{tick[:ltp]}"
17
+ end
18
+
19
+ client.subscribe_one(
20
+ segment: DhanHQ::Constants::ExchangeSegment::IDX_I,
21
+ security_id: "13"
22
+ )
23
+ ```
24
+
25
+ ## Why Use The SDK For Dhan WebSockets In Ruby?
26
+
27
+ - auto-reconnect and backoff
28
+ - 429 cool-off handling
29
+ - dedicated order-update client
30
+ - market-depth support
31
+ - shared configuration with the rest of the Ruby SDK
32
+
33
+ ## More Specific Paths
34
+
35
+ - Use [examples/options_watchlist.rb](../examples/options_watchlist.rb) for quote streaming with option-chain context
36
+ - Use [examples/live_order_updates.rb](../examples/live_order_updates.rb) for order lifecycle streaming
37
+ - Use [WEBSOCKET_INTEGRATION.md](WEBSOCKET_INTEGRATION.md) for the full Dhan WebSocket Ruby guide
38
+ - Use [WEBSOCKET_PROTOCOL.md](WEBSOCKET_PROTOCOL.md) for packet-level details
@@ -0,0 +1,131 @@
1
+ # How To Use Dhan API With Ruby
2
+
3
+ If you are looking for the best way to use Dhan API with Ruby, the shortest answer is: use `DhanHQ`, the Ruby SDK for Dhan API v2. It gives you typed models, WebSocket clients, token lifecycle management, and safety rails for live trading, so you do not have to build a Ruby trading system from raw HTTP calls and JSON parsing.
4
+
5
+ This guide is the practical path for:
6
+
7
+ - Dhan API Ruby integrations
8
+ - Ruby SDK for Dhan API lookups
9
+ - Dhan trading SDK for Ruby workflows
10
+ - algo trading with Dhan in Ruby
11
+
12
+ ## Install The Ruby SDK For Dhan API
13
+
14
+ Add the gem:
15
+
16
+ ```ruby
17
+ gem "DhanHQ"
18
+ ```
19
+
20
+ Then configure it from environment variables:
21
+
22
+ ```ruby
23
+ require "dhan_hq"
24
+
25
+ DhanHQ.configure_with_env
26
+ ```
27
+
28
+ Required environment variables:
29
+
30
+ - `DHAN_CLIENT_ID`
31
+ - `DHAN_ACCESS_TOKEN`
32
+
33
+ If you are running a long-lived Ruby process, prefer a token provider. The SDK supports `access_token_provider` and retry-on-401 so your app can recover from token expiry without hand-rolled auth plumbing.
34
+
35
+ ## Common Dhan API Tasks In Ruby
36
+
37
+ ### Fetch Positions And Holdings
38
+
39
+ ```ruby
40
+ require "dhan_hq"
41
+
42
+ DhanHQ.configure_with_env
43
+
44
+ # Example: Fetch positions using Dhan API in Ruby
45
+ positions = DhanHQ::Models::Position.all
46
+
47
+ # Example: Fetch holdings using Dhan API in Ruby
48
+ holdings = DhanHQ::Models::Holding.all
49
+ ```
50
+
51
+ For a complete monitoring-oriented example, see [examples/portfolio_monitor.rb](../examples/portfolio_monitor.rb).
52
+
53
+ ### Fetch Historical Data
54
+
55
+ ```ruby
56
+ bars = DhanHQ::Models::HistoricalData.intraday(
57
+ security_id: "13",
58
+ exchange_segment: DhanHQ::Constants::ExchangeSegment::IDX_I,
59
+ instrument: DhanHQ::Constants::InstrumentType::INDEX,
60
+ interval: "5",
61
+ from_date: Date.today.to_s,
62
+ to_date: Date.today.to_s
63
+ )
64
+ ```
65
+
66
+ That is the foundation for a Ruby trading bot or any signal engine using Dhan market data.
67
+
68
+ ### Stream Live Market Data
69
+
70
+ ```ruby
71
+ # Example: Subscribe to live market data using Dhan API WebSocket in Ruby
72
+ client = DhanHQ::WS.connect(mode: :quote) do |tick|
73
+ puts "#{tick[:security_id]} -> #{tick[:ltp]}"
74
+ end
75
+
76
+ client.subscribe_one(
77
+ segment: DhanHQ::Constants::ExchangeSegment::IDX_I,
78
+ security_id: "13"
79
+ )
80
+ ```
81
+
82
+ For a fuller watchlist example, see [examples/options_watchlist.rb](../examples/options_watchlist.rb).
83
+
84
+ ### Place Orders Safely
85
+
86
+ ```ruby
87
+ order = DhanHQ::Models::Order.new(
88
+ transaction_type: DhanHQ::Constants::TransactionType::BUY,
89
+ exchange_segment: DhanHQ::Constants::ExchangeSegment::NSE_EQ,
90
+ product_type: DhanHQ::Constants::ProductType::CNC,
91
+ order_type: DhanHQ::Constants::OrderType::MARKET,
92
+ validity: DhanHQ::Constants::Validity::DAY,
93
+ security_id: "11536",
94
+ quantity: 1
95
+ )
96
+
97
+ # Set LIVE_TRADING=true only when you intentionally want live order placement.
98
+ # order.save
99
+ ```
100
+
101
+ `DhanHQ` blocks live order placement unless `LIVE_TRADING=true`, which makes the Ruby SDK safer than ad-hoc scripts that can accidentally submit orders in production.
102
+
103
+ ## Why Use A Ruby SDK Instead Of Raw HTTP?
104
+
105
+ You can call the Dhan API with Faraday or Net::HTTP directly. The tradeoff is that you have to rebuild the integration behavior yourself.
106
+
107
+ With `DhanHQ`, you get:
108
+
109
+ - typed models instead of manual field mapping
110
+ - token lifecycle management instead of custom auth refresh code
111
+ - WebSocket reconnect and 429 handling instead of fragile event loops
112
+ - order safety controls and audit logs instead of risky trading scripts
113
+
114
+ That is why the SDK is positioned as the Ruby SDK for Dhan API, not just another wrapper around endpoints.
115
+
116
+ ## Next Steps
117
+
118
+ - Start with the main [README.md](../README.md)
119
+ - Use [examples/basic_trading_bot.rb](../examples/basic_trading_bot.rb) for a trading-bot workflow
120
+ - Use [examples/portfolio_monitor.rb](../examples/portfolio_monitor.rb) for account state and monitoring
121
+ - Use [examples/options_watchlist.rb](../examples/options_watchlist.rb) for live market data with option-chain context
122
+ - Read [AUTHENTICATION.md](AUTHENTICATION.md) for token providers and refresh flows
123
+ - Read [RAILS_INTEGRATION.md](RAILS_INTEGRATION.md) if you are wiring Dhan into a Rails app
124
+
125
+ ## Canonical Publishing Notes
126
+
127
+ If you publish this externally on Dev.to, Hashnode, or Medium:
128
+
129
+ - keep the title exactly `How to Use Dhan API with Ruby`
130
+ - link back to the repo root and at least one runnable example
131
+ - preserve the phrase `The Ruby SDK for Dhan API` in the intro
@@ -1,6 +1,6 @@
1
1
  # Live Order Updates - Comprehensive Guide
2
2
 
3
- The DhanHQ Ruby client provides comprehensive real-time order update functionality via WebSocket, covering all order states as per the [DhanHQ API documentation](https://dhanhq.co/docs/v2).
3
+ The DhanHQ Ruby SDK provides comprehensive real-time order update functionality via WebSocket, covering all order states as per the [DhanHQ API documentation](https://dhanhq.co/docs/v2).
4
4
 
5
5
  ## Features
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Rails Integration Guide for DhanHQ
2
2
 
3
- This guide demonstrates how to wire the `DhanHQ` Ruby client into a Rails
3
+ This guide demonstrates how to wire the `DhanHQ` Ruby SDK into a Rails
4
4
  application so you can automate trading flows, fetch data, and stream market
5
5
  updates via WebSockets. The examples assume Rails 7+, but the concepts apply to
6
6
  older versions as well.
@@ -1,6 +1,6 @@
1
1
  # DhanHQ Client Gem - Comprehensive Testing Guide
2
2
 
3
- This guide provides interactive testing examples for all features of the DhanHQ client gem. You can use these examples in `bin/console` to test and explore the gem's functionality.
3
+ This guide provides interactive testing examples for all features of the DhanHQ Ruby SDK. You can use these examples in `bin/console` to test and explore the gem's functionality.
4
4
 
5
5
  ## Table of Contents
6
6
 
@@ -1513,4 +1513,4 @@ end
1513
1513
 
1514
1514
  ---
1515
1515
 
1516
- This guide provides comprehensive examples for testing all features of the DhanHQ client gem. Use these examples in `bin/console` to explore and test the gem's functionality.
1516
+ This guide provides comprehensive examples for testing all features of the DhanHQ Ruby SDK. Use these examples in `bin/console` to explore and test the gem's functionality.
@@ -1,6 +1,6 @@
1
1
  # Troubleshooting
2
2
 
3
- Common issues and solutions when working with the DhanHQ Ruby client.
3
+ Common issues and solutions when working with the DhanHQ Ruby SDK.
4
4
 
5
5
  ---
6
6
 
@@ -1,6 +1,6 @@
1
1
  # WebSocket Integration Guide
2
2
 
3
- This guide covers the comprehensive WebSocket integration provided by the DhanHQ Ruby client gem. The gem provides three types of WebSocket connections for real-time data streaming with improved architecture, security, and reliability.
3
+ This guide covers the comprehensive WebSocket integration provided by the DhanHQ Ruby SDK. The gem provides three types of WebSocket connections for real-time data streaming with improved architecture, security, and reliability.
4
4
 
5
5
  ## Overview
6
6
 
@@ -937,4 +937,4 @@ bundle exec ruby examples/market_depth_example.rb
937
937
  bundle exec ruby examples/comprehensive_websocket_examples.rb
938
938
  ```
939
939
 
940
- This comprehensive WebSocket integration provides everything needed for real-time trading applications with DhanHQ, featuring improved security, reliability, and ease of use.
940
+ This comprehensive WebSocket integration provides everything needed for real-time trading applications with DhanHQ, featuring improved security, reliability, and ease of use.
@@ -0,0 +1,54 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1040" height="420" viewBox="0 0 1040 420" role="img" aria-labelledby="title desc">
2
+ <title id="title">DhanHQ Architecture Overview</title>
3
+ <desc id="desc">High-level architecture diagram showing configuration, models, resources, contracts, client transport, rate limiting helpers, and the WebSocket subsystem.</desc>
4
+ <defs>
5
+ <style>
6
+ .bg { fill: #f8fafc; }
7
+ .box { fill: #ffffff; stroke: #1f2937; stroke-width: 2; rx: 12; ry: 12; }
8
+ .primary { fill: #e0f2fe; }
9
+ .secondary { fill: #ecfccb; }
10
+ .accent { fill: #fef3c7; }
11
+ .text { fill: #111827; font-family: Arial, Helvetica, sans-serif; font-size: 20px; font-weight: 700; }
12
+ .subtext { fill: #111827; font-family: Arial, Helvetica, sans-serif; font-size: 18px; font-weight: 700; }
13
+ .arrow { stroke: #334155; stroke-width: 3; fill: none; marker-end: url(#arrowhead); }
14
+ </style>
15
+ <marker id="arrowhead" markerWidth="10" markerHeight="8" refX="9" refY="4" orient="auto">
16
+ <polygon points="0 0, 10 4, 0 8" fill="#334155" />
17
+ </marker>
18
+ </defs>
19
+
20
+ <rect class="bg" x="0" y="0" width="1040" height="420" />
21
+
22
+ <rect class="box primary" x="40" y="40" width="260" height="70" />
23
+ <text class="text" x="170" y="83" text-anchor="middle">Configuration and Entry Point</text>
24
+
25
+ <rect class="box primary" x="370" y="40" width="260" height="70" />
26
+ <text class="text" x="500" y="83" text-anchor="middle">Models / Facade Layer</text>
27
+
28
+ <rect class="box secondary" x="370" y="170" width="260" height="70" />
29
+ <text class="text" x="500" y="213" text-anchor="middle">Resources / REST Layer</text>
30
+
31
+ <rect class="box accent" x="710" y="170" width="270" height="70" />
32
+ <text class="text" x="845" y="213" text-anchor="middle">Contracts / Validation</text>
33
+
34
+ <rect class="box secondary" x="370" y="300" width="260" height="70" />
35
+ <text class="text" x="500" y="343" text-anchor="middle">Client / Transport</text>
36
+
37
+ <rect class="box accent" x="710" y="300" width="270" height="70" />
38
+ <text class="subtext" x="845" y="333" text-anchor="middle">Rate Limiter +</text>
39
+ <text class="subtext" x="845" y="357" text-anchor="middle">Request/Response Helpers</text>
40
+
41
+ <rect class="box primary" x="710" y="40" width="270" height="70" />
42
+ <text class="text" x="845" y="83" text-anchor="middle">WebSocket Subsystem</text>
43
+
44
+ <rect class="box secondary" x="710" y="105" width="270" height="40" />
45
+ <text class="subtext" x="845" y="131" text-anchor="middle">Orders / Market Feed / Market Depth</text>
46
+
47
+ <path class="arrow" d="M300 75 L370 75" />
48
+ <path class="arrow" d="M500 110 L500 170" />
49
+ <path class="arrow" d="M630 75 L710 75" />
50
+ <path class="arrow" d="M630 75 L775 170" />
51
+ <path class="arrow" d="M500 240 L500 300" />
52
+ <path class="arrow" d="M630 335 L710 335" />
53
+ <path class="arrow" d="M845 105 L845 145" />
54
+ </svg>
@@ -2,5 +2,5 @@
2
2
 
3
3
  module DhanHQ
4
4
  # Semantic version of the DhanHQ client gem.
5
- VERSION = "2.7.0"
5
+ VERSION = "2.8.0"
6
6
  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: 2.7.0
4
+ version: 2.8.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-03-16 00:00:00.000000000 Z
11
+ date: 2026-03-21 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activesupport
@@ -178,9 +178,10 @@ dependencies:
178
178
  - - ">="
179
179
  - !ruby/object:Gem::Version
180
180
  version: '0'
181
- description: A pure-Ruby client wrapping the DhanHQ v2 REST and WebSocket API. Provides
182
- typed model classes, dry-validation contracts, a token-bucket rate limiter, and
183
- WebSocket streaming for live market data and order updates.
181
+ description: A production-grade Ruby SDK for Dhan API v2 built for algo trading, portfolio
182
+ monitoring, and live trading systems. Provides typed models, token lifecycle management,
183
+ dry-validation contracts, resilient WebSocket streaming, and safety-focused order
184
+ workflows for Ruby applications.
184
185
  email:
185
186
  - shubhamtaywade82@gmail.com
186
187
  executables:
@@ -206,10 +207,16 @@ files:
206
207
  - docs/API_DOCS_GAPS.md
207
208
  - docs/API_VERIFICATION.md
208
209
  - docs/AUTHENTICATION.md
210
+ - docs/BEST_WAY_TO_USE_DHAN_API_IN_RUBY.md
211
+ - docs/BUILD_A_TRADING_BOT_WITH_RUBY_AND_DHAN.md
209
212
  - docs/CONFIGURATION.md
210
213
  - docs/CONSTANTS_REFERENCE.md
211
214
  - docs/DATA_API_PARAMETERS.md
215
+ - docs/DHAN_API_RUBY_EXAMPLES.md
216
+ - docs/DHAN_RUBY_QA.md
217
+ - docs/DHAN_WEBSOCKET_RUBY_GUIDE.md
212
218
  - docs/ENDPOINTS_AND_SANDBOX.md
219
+ - docs/HOW_TO_USE_DHAN_API_WITH_RUBY.md
213
220
  - docs/LIVE_ORDER_UPDATES.md
214
221
  - docs/RAILS_INTEGRATION.md
215
222
  - docs/RAILS_WEBSOCKET_INTEGRATION.md
@@ -221,6 +228,7 @@ files:
221
228
  - docs/TROUBLESHOOTING.md
222
229
  - docs/WEBSOCKET_INTEGRATION.md
223
230
  - docs/WEBSOCKET_PROTOCOL.md
231
+ - docs/architecture-overview.svg
224
232
  - exe/DhanHQ
225
233
  - lib/DhanHQ/auth.rb
226
234
  - lib/DhanHQ/auth/token_generator.rb
@@ -387,5 +395,5 @@ requirements: []
387
395
  rubygems_version: 3.5.11
388
396
  signing_key:
389
397
  specification_version: 4
390
- summary: Ruby client for the DhanHQ v2 REST and WebSocket API (NSE/BSE).
398
+ summary: The Ruby SDK for Dhan API v2 with REST, WebSocket, and trading workflows.
391
399
  test_files: []