Module: DhanHQ

Defined in:
lib/dhan_hq.rb,
lib/DhanHQ/ai.rb,
lib/DhanHQ/ws.rb,
lib/DhanHQ/mcp.rb,
lib/DhanHQ/auth.rb,
lib/DhanHQ/risk.rb,
lib/DhanHQ/agent.rb,
lib/DhanHQ/client.rb,
lib/DhanHQ/errors.rb,
lib/DhanHQ/events.rb,
lib/DhanHQ/skills.rb,
lib/DhanHQ/version.rb,
lib/DhanHQ/strategy.rb,
lib/DhanHQ/constants.rb,
lib/DhanHQ/ws/client.rb,
lib/DhanHQ/ws/orders.rb,
lib/DhanHQ/agent/tool.rb,
lib/DhanHQ/events/bus.rb,
lib/DhanHQ/indicators.rb,
lib/DhanHQ/mcp/server.rb,
lib/DhanHQ/ws/cmd_bus.rb,
lib/DhanHQ/ws/decoder.rb,
lib/DhanHQ/deprecation.rb,
lib/DhanHQ/events/base.rb,
lib/DhanHQ/json_loader.rb,
lib/DhanHQ/market_data.rb,
lib/DhanHQ/models/edis.rb,
lib/DhanHQ/skills/base.rb,
lib/DhanHQ/write_paths.rb,
lib/DhanHQ/ws/registry.rb,
lib/DhanHQ/ws/segments.rb,
lib/DhanHQ/agent/policy.rb,
lib/DhanHQ/error_object.rb,
lib/DhanHQ/models/funds.rb,
lib/DhanHQ/models/order.rb,
lib/DhanHQ/models/trade.rb,
lib/DhanHQ/rate_limiter.rb,
lib/DhanHQ/write_result.rb,
lib/DhanHQ/ws/sub_state.rb,
lib/DhanHQ/configuration.rb,
lib/DhanHQ/core/auth_api.rb,
lib/DhanHQ/core/base_api.rb,
lib/DhanHQ/models/margin.rb,
lib/DhanHQ/risk/pipeline.rb,
lib/DhanHQ/strategy/base.rb,
lib/DhanHQ/ws/connection.rb,
lib/DhanHQ/dry_run/ledger.rb,
lib/DhanHQ/models/holding.rb,
lib/DhanHQ/models/profile.rb,
lib/DhanHQ/resources/edis.rb,
lib/DhanHQ/core/base_model.rb,
lib/DhanHQ/models/pnl_exit.rb,
lib/DhanHQ/models/position.rb,
lib/DhanHQ/models/postback.rb,
lib/DhanHQ/resources/funds.rb,
lib/DhanHQ/skills/registry.rb,
lib/DhanHQ/skills/workflow.rb,
lib/DhanHQ/ws/market_depth.rb,
lib/DhanHQ/option_analytics.rb,
lib/DhanHQ/resources/orders.rb,
lib/DhanHQ/resources/trades.rb,
lib/DhanHQ/ws/orders/client.rb,
lib/DhanHQ/ai/prompt_helpers.rb,
lib/DhanHQ/dry_run/simulator.rb,
lib/DhanHQ/models/instrument.rb,
lib/DhanHQ/models/twap_order.rb,
lib/DhanHQ/resources/profile.rb,
lib/DhanHQ/ws/packets/header.rb,
lib/DhanHQ/ws/singleton_lock.rb,
lib/DhanHQ/agent/key_coercion.rb,
lib/DhanHQ/agent/tool_schemas.rb,
lib/DhanHQ/ai/context_builder.rb,
lib/DhanHQ/auth/token_manager.rb,
lib/DhanHQ/auth/token_renewal.rb,
lib/DhanHQ/core/base_resource.rb,
lib/DhanHQ/core/error_handler.rb,
lib/DhanHQ/helpers/api_helper.rb,
lib/DhanHQ/models/alert_order.rb,
lib/DhanHQ/models/kill_switch.rb,
lib/DhanHQ/models/market_feed.rb,
lib/DhanHQ/models/multi_order.rb,
lib/DhanHQ/models/super_order.rb,
lib/DhanHQ/resources/holdings.rb,
lib/DhanHQ/resources/ip_setup.rb,
lib/DhanHQ/resources/pnl_exit.rb,
lib/DhanHQ/ws/base_connection.rb,
lib/DhanHQ/agent/order_preview.rb,
lib/DhanHQ/agent/tool_handlers.rb,
lib/DhanHQ/agent/tool_registry.rb,
lib/DhanHQ/models/ledger_entry.rb,
lib/DhanHQ/models/option_chain.rb,
lib/DhanHQ/models/order_update.rb,
lib/DhanHQ/resources/positions.rb,
lib/DhanHQ/risk/checks/asm_gsm.rb,
lib/DhanHQ/risk/checks/options.rb,
lib/DhanHQ/agent/tool_catalogue.rb,
lib/DhanHQ/auth/token_generator.rb,
lib/DhanHQ/concerns/bang_writes.rb,
lib/DhanHQ/concerns/order_audit.rb,
lib/DhanHQ/helpers/model_helper.rb,
lib/DhanHQ/models/forever_order.rb,
lib/DhanHQ/models/iceberg_order.rb,
lib/DhanHQ/models/search_result.rb,
lib/DhanHQ/resources/statements.rb,
lib/DhanHQ/risk/checks/max_loss.rb,
lib/DhanHQ/risk/checks/quantity.rb,
lib/DhanHQ/ws/orders/connection.rb,
lib/DhanHQ/ws/packets/oi_packet.rb,
lib/DhanHQ/models/token_response.rb,
lib/DhanHQ/resources/instruments.rb,
lib/DhanHQ/resources/kill_switch.rb,
lib/DhanHQ/resources/market_feed.rb,
lib/DhanHQ/resources/twap_orders.rb,
lib/DhanHQ/helpers/request_helper.rb,
lib/DhanHQ/models/historical_data.rb,
lib/DhanHQ/resources/alert_orders.rb,
lib/DhanHQ/resources/multi_orders.rb,
lib/DhanHQ/resources/option_chain.rb,
lib/DhanHQ/resources/super_orders.rb,
lib/DhanHQ/risk/checks/order_type.rb,
lib/DhanHQ/ws/market_depth/client.rb,
lib/DhanHQ/ws/packets/full_packet.rb,
lib/DhanHQ/concerns/tracked_writes.rb,
lib/DhanHQ/contracts/base_contract.rb,
lib/DhanHQ/contracts/edis_contract.rb,
lib/DhanHQ/helpers/response_helper.rb,
lib/DhanHQ/market_data/ohlc_series.rb,
lib/DhanHQ/skills/builtin/straddle.rb,
lib/DhanHQ/skills/builtin/strangle.rb,
lib/DhanHQ/utils/network_inspector.rb,
lib/DhanHQ/ws/market_depth/decoder.rb,
lib/DhanHQ/ws/packets/index_packet.rb,
lib/DhanHQ/ws/packets/quote_packet.rb,
lib/DhanHQ/contracts/order_contract.rb,
lib/DhanHQ/contracts/trade_contract.rb,
lib/DhanHQ/helpers/attribute_helper.rb,
lib/DhanHQ/resources/forever_orders.rb,
lib/DhanHQ/resources/iceberg_orders.rb,
lib/DhanHQ/resources/trader_control.rb,
lib/DhanHQ/risk/checks/market_hours.rb,
lib/DhanHQ/ws/packets/ticker_packet.rb,
lib/DhanHQ/helpers/validation_helper.rb,
lib/DhanHQ/models/instrument_helpers.rb,
lib/DhanHQ/option_analytics/max_pain.rb,
lib/DhanHQ/resources/historical_data.rb,
lib/DhanHQ/risk/checks/concentration.rb,
lib/DhanHQ/contracts/user_ip_contract.rb,
lib/DhanHQ/models/global_stocks/funds.rb,
lib/DhanHQ/models/global_stocks/order.rb,
lib/DhanHQ/models/global_stocks/trade.rb,
lib/DhanHQ/skills/builtin/iron_condor.rb,
lib/DhanHQ/ws/websocket_packet_parser.rb,
lib/DhanHQ/market_data/market_snapshot.rb,
lib/DhanHQ/market_data/option_snapshot.rb,
lib/DhanHQ/models/expired_options_data.rb,
lib/DhanHQ/models/global_stocks/margin.rb,
lib/DhanHQ/resources/margin_calculator.rb,
lib/DhanHQ/risk/checks/position_limits.rb,
lib/DhanHQ/risk/checks/product_support.rb,
lib/DhanHQ/skills/builtin/buy_atm_call.rb,
lib/DhanHQ/skills/builtin/covered_call.rb,
lib/DhanHQ/models/global_stocks/holding.rb,
lib/DhanHQ/ws/packets/disconnect_packet.rb,
lib/DhanHQ/ws/packets/prev_close_packet.rb,
lib/DhanHQ/contracts/twap_order_contract.rb,
lib/DhanHQ/resources/global_stocks/funds.rb,
lib/DhanHQ/skills/builtin/protective_put.rb,
lib/DhanHQ/skills/builtin/square_off_all.rb,
lib/DhanHQ/ws/packets/depth_delta_packet.rb,
lib/DhanHQ/ws/packets/market_depth_level.rb,
lib/DhanHQ/contracts/alert_order_contract.rb,
lib/DhanHQ/contracts/market_feed_contract.rb,
lib/DhanHQ/contracts/multi_order_contract.rb,
lib/DhanHQ/contracts/place_order_contract.rb,
lib/DhanHQ/contracts/slice_order_contract.rb,
lib/DhanHQ/option_analytics/black_scholes.rb,
lib/DhanHQ/resources/expired_options_data.rb,
lib/DhanHQ/resources/global_stocks/orders.rb,
lib/DhanHQ/resources/global_stocks/trades.rb,
lib/DhanHQ/risk/checks/trading_permission.rb,
lib/DhanHQ/skills/builtin/bull_put_spread.rb,
lib/DhanHQ/contracts/modify_order_contract.rb,
lib/DhanHQ/contracts/option_chain_contract.rb,
lib/DhanHQ/skills/builtin/bear_call_spread.rb,
lib/DhanHQ/ws/packets/market_status_packet.rb,
lib/dhanhq/analysis/options_buying_advisor.rb,
lib/DhanHQ/contracts/forever_order_contract.rb,
lib/DhanHQ/contracts/iceberg_order_contract.rb,
lib/DhanHQ/contracts/trade_history_contract.rb,
lib/DhanHQ/resources/global_stocks/holdings.rb,
lib/dhanhq/analysis/helpers/bias_aggregator.rb,
lib/DhanHQ/contracts/pnl_based_exit_contract.rb,
lib/dhanhq/analysis/helpers/moneyness_helper.rb,
lib/dhanhq/analysis/multi_timeframe_analyzer.rb,
lib/DhanHQ/contracts/historical_data_contract.rb,
lib/DhanHQ/contracts/instrument_list_contract.rb,
lib/DhanHQ/models/global_stocks/market_status.rb,
lib/DhanHQ/skills/builtin/square_off_position.rb,
lib/DhanHQ/models/global_stocks/order_estimate.rb,
lib/DhanHQ/contracts/margin_calculator_contract.rb,
lib/DhanHQ/contracts/trade_by_order_id_contract.rb,
lib/DhanHQ/models/concerns/api_response_handler.rb,
lib/DhanHQ/resources/global_stocks/market_status.rb,
lib/DhanHQ/skills/builtin/market_data_summarizer.rb,
lib/DhanHQ/contracts/global_stocks_order_contract.rb,
lib/DhanHQ/contracts/position_conversion_contract.rb,
lib/DhanHQ/contracts/expired_options_data_contract.rb,
lib/DhanHQ/resources/global_stocks/margin_calculator.rb,
lib/dhanhq/contracts/options_buying_advisor_contract.rb,
lib/DhanHQ/contracts/global_stocks_estimator_contract.rb,
lib/DhanHQ/contracts/intraday_historical_data_contract.rb,
lib/DhanHQ/contracts/global_stocks_place_order_contract.rb,
lib/DhanHQ/contracts/global_stocks_modify_order_contract.rb,
lib/DhanHQ/contracts/multi_scrip_margin_calc_request_contract.rb,
sig/DhanHQ.rbs

Overview

The top-level module for the DhanHQ client library.

Provides configuration management for setting credentials and API-related settings.

Defined Under Namespace

Modules: AI, APIHelper, Agent, Analysis, AttributeHelper, Auth, Concerns, Constants, Contracts, Deprecation, DryRun, Events, Indicators, JSONLoader, MCP, MarketData, ModelHelper, Models, OptionAnalytics, RequestHelper, Resources, ResponseHelper, Risk, Skills, Strategy, Utils, ValidationHelper, WS, WritePaths, WriteResult Classes: AuthAPI, AuthenticationError, AuthenticationFailedError, BaseAPI, BaseModel, BaseResource, Client, Configuration, DataError, Error, ErrorHandler, ErrorObject, InputExceptionError, InternalServerError, InvalidAccessError, InvalidAuthenticationError, InvalidClientIDError, InvalidRequestError, InvalidTokenError, LiveTradingDisabledError, ModificationLimitError, NetworkError, NoHoldingsError, NotFoundError, OrderError, OtherError, RateLimitError, RateLimiter, RiskViolation, TokenEndpointError, TokenExpiredError, UserAccountError, ValidationError

Constant Summary collapse

LOADER =
Zeitwerk::Loader.new
BASE_URL =

Default REST API host used when no custom base URL is provided.

Returns:

  • (String)
Constants::Urls::REST_API_BASE
VERSION =

Semantic version of the DhanHQ client gem.

Returns:

  • (String)
"3.3.0"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.configurationDhanHQ::Configuration?

The current configuration instance.

Returns:



93
94
95
# File 'lib/dhan_hq.rb', line 93

def configuration
  @configuration
end

.loggerLogger

default logger so calls like DhanHQ.logger&.info never explode Accessor for the logger instance used by the SDK.

Returns:

  • (Logger)

    The configured logger, defaulting to STDOUT at INFO level.



117
118
119
# File 'lib/dhan_hq.rb', line 117

def logger
  @logger ||= Logger.new($stdout, level: Logger::INFO)
end

Class Method Details

.configure {|configuration| ... } ⇒ void

This method returns an undefined value.

Configures the DhanHQ client with user-defined settings.

Examples:

DhanHQ.configure do |config|
  config.access_token = 'your_access_token'
  config.client_id = 'your_client_id'
end

Yield Parameters:



107
108
109
110
111
# File 'lib/dhan_hq.rb', line 107

def configure
  self.configuration ||= Configuration.new
  yield(configuration)
  self.logger ||= Logger.new($stdout, level: Logger::INFO)
end

.configure_from_dashboard(bearer_token:, url: "http://localhost:3011/api/dhan_access_token") ⇒ DhanHQ::Configuration

Configures the DhanHQ client by fetching credentials from a dashboard API.

Parameters:

  • bearer_token (String)

    Secret dashboard token (e.g. YOUR_DASHBOARD_TOKEN)

  • url (String) (defaults to: "http://localhost:3011/api/dhan_access_token")

    The full URL of the dashboard API

Returns:

Raises:



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
# File 'lib/dhan_hq.rb', line 208

def configure_from_dashboard(bearer_token:, url: "http://localhost:3011/api/dhan_access_token")
  raise DhanHQ::TokenEndpointError, "bearer_token is required" if bearer_token.to_s.empty?

  conn = ::Faraday.new(url: url) do |c|
    c.request :url_encoded
    c.adapter ::Faraday.default_adapter
  end

  response = conn.get("") do |req|
    req.headers["Authorization"] = "Bearer #{bearer_token}"
    req.headers["Accept"] = "application/json"
  end

  unless response.success?
    body = parse_json_body(response.body)
    msg = body["error"] || body["message"] || body["errorMessage"] || response.body.to_s
    raise DhanHQ::TokenEndpointError, "Dashboard returned #{response.status}: #{msg}"
  end

  data = parse_json_body(response.body)
  data = data.transform_keys(&:to_s) if data.is_a?(Hash)

  access_token = data["access_token"] || data["accessToken"] || data["dhan_access_token"] || data["dhanaccesstoken"]
  client_id = data["client_id"] || data["clientId"] || data["dhan_client_id"] || data["dhanClientId"]
  client_id ||= self.configuration&.client_id || ENV.fetch("DHAN_CLIENT_ID", nil)

  raise DhanHQ::TokenEndpointError, "Dashboard response missing access_token (tried access_token, dhan_access_token, dhanaccesstoken)" if access_token.to_s.empty?
  raise DhanHQ::TokenEndpointError, "Dashboard response missing client_id, and no fallback client_id was found in config or ENV['DHAN_CLIENT_ID']" if client_id.to_s.empty?

  self.configuration ||= Configuration.new
  configuration.access_token = access_token.to_s
  configuration.client_id = client_id.to_s
  dhan_base = data["base_url"] || data["baseUrl"]
  configuration.base_url = dhan_base.to_s if dhan_base.to_s != ""
  configuration
end

.configure_from_token_endpoint(base_url: nil, bearer_token: nil) ⇒ DhanHQ::Configuration

Configures the DhanHQ client by fetching credentials from a token endpoint.

Performs GET <base_url>/auth/dhan/token with Authorization: Bearer <bearer_token>. Expects JSON with at least access_token and client_id. Optional base_url in the response overrides the Dhan API base URL.

Examples:

Explicit

DhanHQ.configure_from_token_endpoint(base_url: "https://myapp.com", bearer_token: "secret-token")

From ENV (DHAN_TOKEN_ENDPOINT_BASE_URL and DHAN_TOKEN_ENDPOINT_BEARER set)

DhanHQ.configure_from_token_endpoint

Parameters:

  • base_url (String, nil) (defaults to: nil)

    Base URL of your app (e.g. https://myapp.com). If nil, uses ENV.

  • bearer_token (String, nil) (defaults to: nil)

    Secret token for the endpoint. If nil, uses ENV.

Returns:

Raises:



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
# File 'lib/dhan_hq.rb', line 164

def configure_from_token_endpoint(base_url: nil, bearer_token: nil)
  base_url ||= ENV.fetch("DHAN_TOKEN_ENDPOINT_BASE_URL", nil)
  bearer_token ||= ENV.fetch("DHAN_TOKEN_ENDPOINT_BEARER", nil)

  raise DhanHQ::TokenEndpointError, "base_url and bearer_token (or ENV DHAN_TOKEN_ENDPOINT_*) are required" if base_url.to_s.empty? || bearer_token.to_s.empty?

  url = "#{base_url.to_s.chomp("/")}/auth/dhan/token"
  conn = ::Faraday.new(url: url) do |c|
    c.request :url_encoded
    c.adapter ::Faraday.default_adapter
  end

  response = conn.get("") do |req|
    req.headers["Authorization"] = "Bearer #{bearer_token}"
    req.headers["Accept"] = "application/json"
  end

  unless response.success?
    body = parse_json_body(response.body)
    msg = body["error"] || body["message"] || body["errorMessage"] || response.body.to_s
    raise DhanHQ::TokenEndpointError, "Token endpoint returned #{response.status}: #{msg}"
  end

  data = parse_json_body(response.body)
  data = data.transform_keys(&:to_s) if data.is_a?(Hash)

  access_token = data["access_token"] || data[:access_token]
  client_id = data["client_id"] || data[:client_id]
  raise DhanHQ::TokenEndpointError, "Token endpoint response missing access_token or client_id" if access_token.to_s.empty? || client_id.to_s.empty?

  self.configuration ||= Configuration.new
  configuration.access_token = access_token.to_s
  configuration.client_id = client_id.to_s
  dhan_base = data["base_url"] || data[:base_url]
  configuration.base_url = dhan_base.to_s if dhan_base.to_s != ""
  configuration
end

.configure_with_envvoid

This method returns an undefined value.

Configures the DhanHQ client using environment variables.

When credentials are injected via DHAN_ACCESS_TOKEN and DHAN_CLIENT_ID this helper can be used to initialise a configuration without a block.

Examples:

DhanHQ.configure_with_env


130
131
132
# File 'lib/dhan_hq.rb', line 130

def configure_with_env
  self.configuration = Configuration.new
end

.ensure_configuration!DhanHQ::Configuration

Ensures configuration exists, bootstrapping from ENV when nil. Called automatically when building a Client so env-only integrations work without an explicit configure/configure_with_env call. Idempotent when configuration is already set.



139
140
141
# File 'lib/dhan_hq.rb', line 139

def ensure_configuration!
  self.configuration ||= Configuration.new
end

.parse_json_body(body) ⇒ Hash

Returns Parsed hash; empty hash on parse failure or empty string.

Parameters:

  • body (String, Hash)

    Raw response body

Returns:

  • (Hash)

    Parsed hash; empty hash on parse failure or empty string



247
248
249
250
251
252
253
254
255
# File 'lib/dhan_hq.rb', line 247

def parse_json_body(body)
  return {} if body.nil?
  return body if body.is_a?(Hash)
  return {} if body.to_s.strip.empty?

  JSON.parse(body.to_s)
rescue StandardError
  {}
end

.reset_configuration!Object

Resets the configuration to nil.



144
145
146
# File 'lib/dhan_hq.rb', line 144

def reset_configuration!
  self.configuration = nil
end