Class: DhanHQ::Indicators::ATR

Inherits:
Object
  • Object
show all
Defined in:
lib/DhanHQ/indicators.rb

Overview

Average True Range (ATR)

Volatility indicator measuring market volatility.

Examples:

Calculate ATR

ohlc = [
  { open: 100, high: 105, low: 98, close: 103 },
  { open: 103, high: 108, low: 101, close: 106 },
  ...
]
atr = DhanHQ::Indicators::ATR.calculate(ohlc, period: 14)

Class Method Summary collapse

Class Method Details

.calculate(data, period: 14) ⇒ Array<Float>

Calculate ATR for the given OHLC data.

Parameters:

  • data (Array<Hash>)

    Array of OHLC hashes with :open, :high, :low, :close

  • period (Integer) (defaults to: 14)

    Number of periods (default: 14)

Returns:

  • (Array<Float>)

    ATR values (nil for insufficient data points)



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/DhanHQ/indicators.rb', line 248

def self.calculate(data, period: 14)
  return [] if data.nil? || data.empty? || period < 1
  return [] if data.length < 2

  # Calculate true ranges
  true_ranges = data.each_cons(2).map do |prev, curr|
    high = curr[:high] || curr["high"]
    low = curr[:low] || curr["low"]
    prev_close = prev[:close] || prev["close"]

    [high - low, (high - prev_close).abs, (low - prev_close).abs].max
  end

  # Calculate ATR using smoothed average
  atr_values = [nil] # First value has no true range

  # First ATR is simple average
  if true_ranges.length >= period
    first_atr = true_ranges[0...period].sum.to_f / period
    atr_values.concat(Array.new(period - 1, nil))
    atr_values << first_atr

    # Subsequent ATRs use smoothing
    true_ranges[period..].each do |tr|
      previous_atr = atr_values.last
      atr_values << (((previous_atr * (period - 1)) + tr) / period)
    end
  else
    atr_values.concat(Array.new(true_ranges.length, nil))
  end

  atr_values
end