Subscribe

Implementing SuperTrend, ATR and RSI indicators in Go

I didn't want a big dependency just for three indicators, so I wrote ATR, RSI and SuperTrend in plain golang. Here is the code, the small tests I use to sanity check it, and how I round prices to the NSE tick for limit orders.

Implementing SuperTrend, ATR and RSI indicators in Go

When I started my algo-trade repo in May, the strategies needed a few technical indicators: EMA, RSI, ATR and SuperTrend to begin with. I didn't want to pull in a library for this. These are small loops over slices. So I wrote them myself in a package called indicators, with no dependencies except math.

In this blog we will look at ATR, RSI and SuperTrend, how I sanity check them with tests, and one related helper that rounds prices to the NSE tick size before placing a limit order. This is about the code only, it is not investment advice and the indicators don't predict anything by themselves.

All functions take plain []float64 slices and return a slice of the same length. Bars before the indicator has enough data are left at zero. I like this shape because index i always means the same candle everywhere, and the strategies can just checks s.RSI14[i] without any offset maths.

ATR

Average True Range measures how much a stock moves per bar. True range is the biggest of three numbers: high minus low, high minus previous close, and low minus previous close (both as absolute values). The previous close bits matter when a stock gaps.

ATR is then Wilder's smoothing of the true range. The first value is a simple average of the first period true ranges, and after that each value is (prev*(period-1) + tr) / period.

package indicators

import "math"

func ATR(highs, lows, closes []float64, period int) []float64 {
    if len(highs) == 0 || period <= 0 || len(highs) != len(lows) || len(lows) != len(closes) {
        return nil
    }
    tr := make([]float64, len(highs))
    for i := 0; i < len(highs); i++ {
        if i == 0 {
            tr[i] = highs[i] - lows[i]
            continue
        }
        hml := highs[i] - lows[i]
        hpc := math.Abs(highs[i] - closes[i-1])
        lpc := math.Abs(lows[i] - closes[i-1])
        tr[i] = math.Max(hml, math.Max(hpc, lpc))
    }

    out := make([]float64, len(highs))
    var sum float64
    for i := 0; i < len(tr) && i < period; i++ {
        sum += tr[i]
    }
    if len(tr) >= period {
        out[period-1] = sum / float64(period)
        for i := period; i < len(tr); i++ {
            out[i] = (out[i-1]*float64(period-1) + tr[i]) / float64(period)
        }
    }
    return out
}

The first bar has no previous close, so its true range is just high minus low. The first ATR value lands on index period-1.

RSI

RSI uses the same smoothing idea, applied to gains and losses separately. Average the first period ups and downs, then smooth. The value is 100 - 100/(1 + avgGain/avgLoss).

func RSI(values []float64, period int) []float64 {
    if len(values) == 0 || period <= 0 {
        return nil
    }
    out := make([]float64, len(values))
    var gainSum, lossSum float64
    for i := 1; i <= period && i < len(values); i++ {
        change := values[i] - values[i-1]
        if change >= 0 {
            gainSum += change
        } else {
            lossSum -= change
        }
    }
    if len(values) > period {
        avgGain := gainSum / float64(period)
        avgLoss := lossSum / float64(period)
        out[period] = rsiFromAverages(avgGain, avgLoss)
        for i := period + 1; i < len(values); i++ {
            change := values[i] - values[i-1]
            var gain, loss float64
            if change >= 0 {
                gain = change
            } else {
                loss = -change
            }
            avgGain = (avgGain*float64(period-1) + gain) / float64(period)
            avgLoss = (avgLoss*float64(period-1) + loss) / float64(period)
            out[i] = rsiFromAverages(avgGain, avgLoss)
        }
    }
    return out
}

func rsiFromAverages(avgGain, avgLoss float64) float64 {
    if avgLoss == 0 {
        return 100
    }
    rs := avgGain / avgLoss
    return 100 - (100 / (1 + rs))
}

Note the first RSI is at index period, one later than ATR. That's because you need period changes, which means period+1 closes. Easy to mix up.

The avgLoss == 0 check is not optional. A stock that only went up for 14 bars would divide by zero and you'd get NaN or +Inf flowing into every comparison after it. Go doesn't panic on float division by zero, it just quietly gives you +Inf, so the bug would be silent.

SuperTrend

SuperTrend is the one that takes a bit of reading. It draws two bands around the middle of each bar, (high+low)/2, at mult * ATR above and below. The trend is up while the close stays above the lower band and flips down when a close drops below it. And the other way round.

The part thats easy to get wrong is that the bands only move in one direction while the trend holds. The lower band can rise but not fall, unless the previous close was already below it. The upper band can fall but not rise. That ratchet is what makes it trail the price.

// SuperTrend returns per-bar trend direction (+1 bullish, -1 bearish) and the
// active line (lower band when bullish, upper when bearish).
func SuperTrend(highs, lows, closes []float64, atrPeriod int, mult float64) ([]int, []float64) {
    n := len(closes)
    if n == 0 || atrPeriod <= 1 || len(highs) != n || len(lows) != n {
        return nil, nil
    }
    atr := ATR(highs, lows, closes, atrPeriod)
    dir := make([]int, n)
    line := make([]float64, n)
    finalUp := make([]float64, n)
    finalDn := make([]float64, n)

    first := atrPeriod - 1
    trend := 1

    for i := 0; i < n; i++ {
        if atr[i] <= 0 {
            continue
        }
        hl2 := (highs[i] + lows[i]) / 2
        bUp := hl2 + mult*atr[i]
        bDn := hl2 - mult*atr[i]
        if i < first || atr[i-1] <= 0 {
            finalUp[i] = bUp
            finalDn[i] = bDn
        } else {
            finalUp[i] = bUp
            if !(bUp < finalUp[i-1] || closes[i-1] > finalUp[i-1]) {
                finalUp[i] = finalUp[i-1]
            }
            finalDn[i] = bDn
            if !(bDn > finalDn[i-1] || closes[i-1] < finalDn[i-1]) {
                finalDn[i] = finalDn[i-1]
            }
        }

        if i < first {
            continue
        }
        if i == first {
            dir[i] = trend
            line[i] = finalDn[i]
            continue
        }
        if trend == 1 && closes[i] < finalDn[i-1] {
            trend = -1
        } else if trend == -1 && closes[i] > finalUp[i-1] {
            trend = 1
        }
        dir[i] = trend
        if trend == 1 {
            line[i] = finalDn[i]
        } else {
            line[i] = finalUp[i]
        }
    }
    return dir, line
}

This is slightly tidied from the version in my repo (the original spells out both branches of each if), but it does the same thing. The trend starts as up on the first bar that has an ATR. That is an arbitrary choice. It washes out after the first real flip, but it means you shouldn't read anything into the first few bars.

My strategies use SuperTrend(highs, lows, closes, 10, 3), ATR period 10 and multiplier 3. The comment in the file says those are meant to follow the same rules as pandas_ta and TradingView. If you port this, put the output next to one of those for the same candles and compare. Expect the first bars to differ a bit, since every library seeds the smoothing slightly differently, and then the numbers should line up.

Small aside about the same package. My EMA function in the same package seeds with the first close, not with a simple average of the first period closes like a lot of libraries do. Both are common. But it means my early EMA values won't match a library that uses the SMA seed, and that is fine as long as you know.

Testing with numbers you can work out by hand

I don't have a big fixture file for these. I prefer inputs where I already know the answer.

package indicators

import "testing"

func TestRSIOnlyGains(t *testing.T) {
    closes := make([]float64, 30)
    for i := range closes {
        closes[i] = 100 + float64(i)
    }
    rsi := RSI(closes, 14)
    if rsi[13] != 0 || rsi[14] != 100 {
        t.Fatalf("rsi[13]=%v rsi[14]=%v", rsi[13], rsi[14])
    }
}

func TestATRConstantRange(t *testing.T) {
    n := 20
    highs, lows, closes := make([]float64, n), make([]float64, n), make([]float64, n)
    for i := 0; i < n; i++ {
        highs[i], lows[i], closes[i] = 102, 98, 100
    }
    atr := ATR(highs, lows, closes, 10)
    if atr[8] != 0 || atr[9] != 4 || atr[n-1] != 4 {
        t.Fatalf("atr = %v", atr)
    }
}

func TestSuperTrendFlips(t *testing.T) {
    // 40 bars up by 1, then 40 bars down by 1
    var closes []float64
    for i := 0; i < 40; i++ {
        closes = append(closes, 100+float64(i))
    }
    for i := 0; i < 40; i++ {
        closes = append(closes, 139-float64(i))
    }
    highs, lows := make([]float64, len(closes)), make([]float64, len(closes))
    for i, c := range closes {
        highs[i], lows[i] = c+0.5, c-0.5
    }
    dir, line := SuperTrend(highs, lows, closes, 10, 3)
    if dir[39] != 1 || line[39] >= closes[39] {
        t.Fatalf("bar 39: dir=%d line=%.2f close=%.2f", dir[39], line[39], closes[39])
    }
    for i := 40; i < len(dir); i++ {
        if dir[i] == -1 {
            t.Logf("flipped bearish at bar %d, close %.1f", i, closes[i])
            return
        }
    }
    t.Fatal("never flipped to bearish")
}

A stock that only rises has RSI 100. A bar range that never changes has ATR equal to that range. And a clean up then down series must flip SuperTrend at some point after the top.

go test -v -run SuperTrend ./...
=== RUN   TestSuperTrendFlips
    indicators_test.go:47: flipped bearish at bar 45, close 134.0
--- PASS: TestSuperTrendFlips (0.00s)

The top is at bar 39 and the flip comes six bars later, five rupees below the top. That lag is the whole point of a trailing indicator, and seeing it in a test makes it very real.

Rounding to the tick for limit orders

This lives in my Kite package, not in indicators, but it's the last step before any of these numbers turn into an order. Exchange rejects a limit price that isn't a multiple of the tick size.

// DefaultPriceTick rounds equity prices to a common NSE cash tick.
const DefaultPriceTick = 0.10

// RoundToTick rounds value to the nearest multiple of tick.
func RoundToTick(value, tick float64) float64 {
    if tick <= 0 {
        return value
    }
    return math.Round(value/tick) * tick
}

// LimitPriceAggressiveBuy is a buy LIMIT slightly above ref to improve fill probability.
func LimitPriceAggressiveBuy(ref float64) float64 {
    if ref <= 0 {
        return 0
    }
    return RoundToTick(ref*1.002, DefaultPriceTick)
}

// LimitPriceAggressiveSell is a sell LIMIT slightly below ref.
func LimitPriceAggressiveSell(ref float64) float64 {
    if ref <= 0 {
        return 0
    }
    return RoundToTick(ref*0.998, DefaultPriceTick)
}

Buying 0.2% above the last price is a way to get a limit order that fills almost like a market order, but with a cap on how bad the fill can be. For a stock at 2500 that gives a buy limit of 2505 and a sell limit of 2495. The same file has two helpers for stop loss orders, because on Zerodha the limit leg of a sell stop must be at or below the trigger, and for a buy stop at or above it. They nudge by 0.1% in the right direction.

Two things to watch. First, tick sizes are not the same for every stock, so 0.10 is a simplification. Rounding to 0.10 is safe only when the stock's actual tick divides into 0.10. The Kite instruments dump has a tick_size column if you want to do it properly. Second, floats. When I printed RoundToTick(1234.56, 0.10) in a test it came out as 1234.6000000000001. The value is fine for comparisons but if you ever build a price string yourself, format it with %.2f first.