Skip to content

Commit

Permalink
add true range indicator
Browse files Browse the repository at this point in the history
  • Loading branch information
sdcoffey committed Feb 23, 2021
1 parent 9dc17f9 commit f766c9e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
26 changes: 26 additions & 0 deletions indicator_true_range.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package techan

import "github.com/sdcoffey/big"

type trueRangeIndicator struct {
series *TimeSeries
}

// NewTrueRangeIndicator returns a base indicator
// which calculates the true rangat the current point in time for a series
// https://www.investopedia.com/terms/a/atr.asp
func NewTrueRangeIndicator(series *TimeSeries) Indicator {
return trueRangeIndicator{
series: series,
}
}

func (tri trueRangeIndicator) Calculate(index int) big.Decimal {
candle := tri.series.Candles[index]
previousClose := tri.series.Candles[index-1].ClosePrice

trueHigh := big.MaxSlice(candle.MaxPrice, previousClose)
trueLow := big.MinSlice(candle.MinPrice, previousClose)

return trueHigh.Sub(trueLow)
}
23 changes: 23 additions & 0 deletions indicator_true_range_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package techan

import (
"testing"
)

func TestTrueRangeIndicator(t *testing.T) {
ts := mockTimeSeriesOCHL(
[]float64{10, 15, 20, 10},
[]float64{11, 16, 21, 11},
[]float64{12, 17, 22, 12},
[]float64{13, 18, 23, 13},
[]float64{14, 19, 24, 14},
[]float64{15, 20, 25, 15},
)

trueRangeIndicator := NewTrueRangeIndicator(ts)

decimalEquals(t, 10, trueRangeIndicator.Calculate(4))
decimalEquals(t, 10, trueRangeIndicator.Calculate(3))
decimalEquals(t, 10, trueRangeIndicator.Calculate(2))
decimalEquals(t, 10, trueRangeIndicator.Calculate(1))
}

0 comments on commit f766c9e

Please sign in to comment.