Class: DhanHQ::Models::HistoricalData

Inherits:
BaseModel
  • Object
show all
Defined in:
lib/DhanHQ/models/historical_data.rb

Overview

Note:

For intraday data, only 90 days of data can be polled at once for any time interval. It is recommended to store this data locally for day-to-day analysis.

Model for fetching historical candle data (OHLC) for desired instruments across segments and exchanges.

This API provides historical price data in the form of candlestick data with timestamp, open, high, low, close, and volume information. Data is available in two formats:

  • Daily: Daily candle data available back to the date of instrument inception
  • Intraday: Minute-level candle data (1, 5, 15, 25, 60 minutes) available for the last 5 years

Examples:

Fetch daily historical data

data = DhanHQ::Models::HistoricalData.daily(
  security_id: "1333",
  exchange_segment: "NSE_EQ",
  instrument: "EQUITY",
  from_date: "2022-01-08",
  to_date: "2022-02-08"
)
puts "First day close: #{data[:close].first}"

Fetch intraday historical data

data = DhanHQ::Models::HistoricalData.intraday(
  security_id: "1333",
  exchange_segment: "NSE_EQ",
  instrument: "EQUITY",
  interval: "15",
  from_date: "2024-09-11",
  to_date: "2024-09-15"
)
puts "Total candles: #{data[:open].size}"

Constant Summary collapse

HTTP_PATH =

Base path for historical data endpoints.

"/v2/charts"

Constants included from ResponseHelper

ResponseHelper::STATUS_ERROR_FALLBACK

Instance Attribute Summary

Attributes inherited from BaseModel

#attributes, #errors

Class Method Summary collapse

Methods inherited from BaseModel

all, api, api_type, #assign_attributes, attributes, create, #delete, #destroy, find, #id, #initialize, #new_record?, #optionchain_api?, parse_collection_response, #persisted?, resource_path, #save, #save!, #to_request_params, #update, #valid?, validate_attributes, validation_contract, #validation_contract, where

Methods included from APIHelper

#handle_response

Methods included from AttributeHelper

#camelize_keys, #inspect, #normalize_keys, #snake_case, #titleize_keys

Methods included from ValidationHelper

#valid?, #validate!, #validate_params!

Methods included from RequestHelper

#build_from_response

Constructor Details

This class inherits a constructor from DhanHQ::BaseModel

Class Method Details

.daily(params) ⇒ HashWithIndifferentAccess{Symbol => Array<Float, Integer>}

Fetches daily OHLC (Open, High, Low, Close) and volume data for the desired instrument.

Retrieves daily candle data for any scrip available back to the date of its inception. The data is returned as arrays where each index corresponds to a single trading day.

Examples:

Fetch daily data for equity

data = DhanHQ::Models::HistoricalData.daily(
  security_id: "1333",
  exchange_segment: "NSE_EQ",
  instrument: "EQUITY",
  from_date: "2022-01-08",
  to_date: "2022-02-08"
)
data[:open].size  # => Number of trading days
data[:close].first  # => First day's close price

Fetch daily data with open interest for futures

data = DhanHQ::Models::HistoricalData.daily(
  security_id: "13",
  exchange_segment: "NSE_FNO",
  instrument: "FUTIDX",
  expiry_code: 0,
  oi: true,
  from_date: "2024-01-01",
  to_date: "2024-01-31"
)
puts "OI data available: #{data.key?(:open_interest)}"

Parameters:

  • params (Hash{Symbol => String, Integer, Boolean})

    Request parameters @option params [String] :security_id (required) Exchange standard ID for each scrip @option params [String] :exchange_segment (required) Exchange and segment for which data is to be fetched. Valid values: See Constants::CHART_EXCHANGE_SEGMENTS @option params [String] :instrument (required) Instrument type of the scrip. Valid values: See Constants::INSTRUMENTS @option params [Integer] :expiry_code (optional) Expiry of the instruments in case of derivatives. Valid values: See Constants::ExpiryCode::ALL (0, 1, 2) @option params [Boolean] :oi (optional) Include Open Interest data for Futures & Options. Default: false @option params [String] :from_date (required) Start date of the desired range in YYYY-MM-DD format @option params [String] :to_date (required) End date of the desired range (non-inclusive) in YYYY-MM-DD format

Returns:

  • (HashWithIndifferentAccess{Symbol => Array<Float, Integer>})

    Historical data hash containing:

    • :open [Array] Open prices for each trading day
    • :high [Array] High prices for each trading day
    • :low [Array] Low prices for each trading day
    • :close [Array] Close prices for each trading day
    • :volume [Array] Volume traded for each trading day
    • :timestamp [Array] Epoch timestamps (Unix time in seconds) for each trading day
    • :open_interest [Array] Open interest values (only included if oi: true was specified)

Raises:



102
103
104
105
106
# File 'lib/DhanHQ/models/historical_data.rb', line 102

def daily(params)
  validated_params = validate_params!(params, DhanHQ::Contracts::HistoricalDataContract)
  response = resource.daily(validated_params)
  normalize(response)
end

.intraday(params) ⇒ HashWithIndifferentAccess{Symbol => Array<Float, Integer>}

Note:

Maximum 90 days of data can be fetched in a single request. For longer periods, make multiple requests or store data locally for analysis.

Fetches intraday OHLC (Open, High, Low, Close) and volume data for minute-level timeframes.

Retrieves minute-level candle data (1, 5, 15, 25, or 60 minutes) for desired instruments. Data is available for the last 5 years for all exchanges and segments for all active instruments.

Important: Only 90 days of data can be polled at once for any of the time intervals. It is recommended that you store this data locally for day-to-day analysis.

Examples:

Fetch 15-minute intraday data

data = DhanHQ::Models::HistoricalData.intraday(
  security_id: "1333",
  exchange_segment: "NSE_EQ",
  instrument: "EQUITY",
  interval: "15",
  from_date: "2024-09-11",
  to_date: "2024-09-15"
)
puts "Total 15-min candles: #{data[:open].size}"

Fetch 1-minute data with specific time range

data = DhanHQ::Models::HistoricalData.intraday(
  security_id: "1333",
  exchange_segment: "NSE_EQ",
  instrument: "EQUITY",
  interval: "1",
  from_date: "2024-09-11 09:30:00",
  to_date: "2024-09-11 15:30:00"
)
# Returns 1-minute candles for the specified time range

Fetch intraday data for futures with open interest

data = DhanHQ::Models::HistoricalData.intraday(
  security_id: "13",
  exchange_segment: "NSE_FNO",
  instrument: "FUTIDX",
  interval: "5",
  expiry_code: 0,
  oi: true,
  from_date: "2024-01-01",
  to_date: "2024-01-31"
)

Parameters:

  • params (Hash{Symbol => String, Integer, Boolean})

    Request parameters @option params [String] :security_id (required) Exchange standard ID for each scrip @option params [String] :exchange_segment (required) Exchange and segment for which data is to be fetched. Valid values: See Constants::EXCHANGE_SEGMENTS @option params [String] :instrument (required) Instrument type of the scrip. Valid values: See Constants::INSTRUMENTS @option params [String] :interval (required) Minute intervals for the timeframe. Valid values: "1", "5", "15", "25", "60" @option params [Integer] :expiry_code (optional) Expiry of the instruments in case of derivatives. Valid values: 0, 1, 2 @option params [Boolean] :oi (optional) Include Open Interest data for Futures & Options. Default: false @option params [String] :from_date (required) Start date of the desired range. Format: YYYY-MM-DD or YYYY-MM-DD HH:MM:SS (e.g., "2024-09-11" or "2024-09-11 09:30:00") @option params [String] :to_date (required) End date of the desired range. Format: YYYY-MM-DD or YYYY-MM-DD HH:MM:SS (e.g., "2024-09-15" or "2024-09-15 13:00:00")

Returns:

  • (HashWithIndifferentAccess{Symbol => Array<Float, Integer>})

    Historical data hash containing:

    • :open [Array] Open prices for each timeframe
    • :high [Array] High prices for each timeframe
    • :low [Array] Low prices for each timeframe
    • :close [Array] Close prices for each timeframe
    • :volume [Array] Volume traded for each timeframe
    • :timestamp [Array] Epoch timestamps (Unix time in seconds) for each timeframe
    • :open_interest [Array] Open interest values (only included if oi: true was specified)

Raises:



180
181
182
183
184
# File 'lib/DhanHQ/models/historical_data.rb', line 180

def intraday(params)
  validated_params = validate_params!(params, DhanHQ::Contracts::IntradayHistoricalDataContract)
  response = resource.intraday(validated_params)
  normalize(response)
end

.resourceDhanHQ::Resources::HistoricalData

Provides a shared instance of the HistoricalData resource.

Returns:



46
47
48
# File 'lib/DhanHQ/models/historical_data.rb', line 46

def resource
  @resource ||= DhanHQ::Resources::HistoricalData.new
end