Class: TA::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ta/fetcher.rb

Overview

Historical data fetching with windowing and throttling

Instance Method Summary collapse

Constructor Details

#initialize(throttle_seconds: 3.0, max_retries: 3) ⇒ Fetcher

Returns a new instance of Fetcher.



8
9
10
11
# File 'lib/ta/fetcher.rb', line 8

def initialize(throttle_seconds: 3.0, max_retries: 3)
  @throttle_seconds = throttle_seconds.to_f
  @max_retries = max_retries.to_i
end

Instance Method Details

#intraday(params, interval) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ta/fetcher.rb', line 13

def intraday(params, interval)
  with_retries(":intraday/#{interval}") do
    DhanHQ::Models::HistoricalData.intraday(
      security_id: params[:security_id],
      exchange_segment: params[:exchange_segment],
      instrument: params[:instrument],
      interval: interval.to_s,
      from_date: params[:from_date],
      to_date: params[:to_date]
    )
  end
end

#intraday_windowed(params, interval) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ta/fetcher.rb', line 26

def intraday_windowed(params, interval)
  from_d = Date.parse(params[:from_date])
  to_d   = Date.parse(params[:to_date])
  max_span = 90
  return intraday(params, interval) if (to_d - from_d).to_i <= max_span

  merged = { "open" => [], "high" => [], "low" => [], "close" => [], "volume" => [], "timestamp" => [] }
  cursor = from_d
  while cursor <= to_d
    chunk_to = [cursor + max_span, to_d].min
    chunk_params = params.merge(from_date: cursor.strftime("%Y-%m-%d"), to_date: chunk_to.strftime("%Y-%m-%d"))
    part = intraday(chunk_params, interval)
    %w[open high low close volume timestamp].each do |k|
      ary = (part[k] || part[k.to_sym]) || []
      merged[k].concat(Array(ary))
    end
    cursor = chunk_to + 1
    sleep_with_jitter
  end
  merged
end