Subscribe

Unit testing trading strategies in Go with synthetic candles

Strategy tests that call a broker API are slow and never give the same answer twice. Here is the small golang helper I use to build fake five minute sessions from a price function, and the tests I write on top of it.

Unit testing trading strategies in Go with synthetic candles

I have a small intraday paper trader written in golang. Every morning it backtests a set of strategies on NIFTY 50 stocks, picks one per stock and then simulates trades through the day. This post is only about how I test that code. It is not investment advice and nothing here says any strategy makes money.

The problem with testing trading code is the data. Real candles come from the Kite Connect API, they need a login token that expires every day, and they change every day. A test that passes on Monday can fail on Tuesday for no reason in my code. So I stopped using real candles in tests at all.

In this blog we will look at the tiny synth package I wrote to build fake sessions, and how the strategy and exit tests use it.

What a session looks like

NSE cash market opens at 09:15 and the last five minute candle starts at 15:25. That is 75 candles. My strategies only care about the candle times, open, high, low, close and volume, so a fake session needs exactly that and nothing else.

The trick is to describe the day as a function. You give it price(i), the close of bar i, and the package builds the candles around it. The open of each bar is the previous close. The high and low sit 0.05% either side of the bigger and smaller of the two. Volume is a flat 1000, since none of the tests I care about here depend on volume.

package papertest

import "time"

type Candle struct {
    Time                   time.Time
    Open, High, Low, Close float64
    Volume                 float64
}

var IST = time.FixedZone("IST", 5*3600+1800)

// Session returns 75 five-minute candles for day (09:15 to 15:25), each with
// the close given by price(i) and a high/low 0.05% either side.
func Session(day time.Time, price func(i int) float64) []Candle {
    open := time.Date(day.Year(), day.Month(), day.Day(), 9, 15, 0, 0, IST)
    out := make([]Candle, 0, 75)
    prev := price(0)
    for i := 0; i < 75; i++ {
        c := price(i)
        hi, lo := max(prev, c)*1.0005, min(prev, c)*0.9995
        out = append(out, Candle{
            Time: open.Add(time.Duration(i) * 5 * time.Minute),
            Open: prev, High: hi, Low: lo, Close: c, Volume: 1000,
        })
        prev = c
    }
    return out
}

// Flat is a quiet session oscillating 0.1% around base.
func Flat(base float64) func(int) float64 {
    return func(i int) float64 {
        if i%2 == 0 {
            return base * 1.001
        }
        return base * 0.999
    }
}

In the real repo Candle is the type from my Kite wrapper. I copied it here so the snippet builds by itself. The built-in min and max need Go 1.21 or newer.

I used a fixed zone for IST instead of time.LoadLocation("Asia/Kolkata"). India has no daylight saving, so the fixed offset is always right, and the tests don't depend on the tz database being present on the machine. One less thing to break in CI.

Flat is the boring day. It wiggles 0.1% up and down and goes nowhere. Most strategies need a few days of history to warm up their indicators (my series needs 50 bars before any strategy fires), so I put a few flat days in front of the day that matters.

A first check on the shape

Before trusting it, a quick test on the session itself.

var day = time.Date(2026, 10, 1, 0, 0, 0, 0, IST)

func TestSessionShape(t *testing.T) {
    c := Session(day, Flat(100))
    if len(c) != 75 {
        t.Fatalf("got %d candles, want 75", len(c))
    }
    first, last := c[0].Time.Format("15:04"), c[74].Time.Format("15:04")
    if first != "09:15" || last != "15:25" {
        t.Fatalf("session runs %s to %s", first, last)
    }
}

Boring. But it pins the session times, and a lot of the later logic (entry window, square off at 15:15) depends on them.

Writing a day as a story

This is the part I like. Each test day is a short function that reads like what happens in the market. Here is a breakout: the price sits at 100 for the first three bars, which is the 15 minute opening range, then jumps to 100.3 and climbs step percent per bar after that.

// breakout holds 100 through the opening range, breaks out at bar 3 and
// then trends by step% per bar.
func breakout(step float64) func(int) float64 {
    return func(i int) float64 {
        if i < 3 {
            return 100
        }
        return 100.3 * (1 + step/100*float64(i-3))
    }
}

The real opening range breakout strategy works on a Series that carries all the indicators, which is too long to paste here. So for this post I wrote a cut down version that only looks at one day. It returns the first bar that closes outside the high and low of the first three bars.

// ORBSignal returns the index of the first bar that closes outside the
// high/low of the first three bars (the 15 minute opening range), and the
// side of the break. It returns -1 when the range never breaks.
func ORBSignal(day []Candle) (int, Side) {
    if len(day) < 4 {
        return -1, 0
    }
    hi, lo := day[0].High, day[0].Low
    for _, c := range day[1:3] {
        hi, lo = max(hi, c.High), min(lo, c.Low)
    }
    for i := 3; i < len(day); i++ {
        switch {
        case day[i].Close > hi:
            return i, Long
        case day[i].Close < lo:
            return i, Short
        }
    }
    return -1, 0
}

Now the test is three days, each one line.

func TestORB(t *testing.T) {
    if i, _ := ORBSignal(Session(day, Flat(100))); i != -1 {
        t.Fatalf("flat day fired at bar %d", i)
    }
    i, side := ORBSignal(Session(day, breakout(0.3)))
    if i != 3 || side != Long {
        t.Fatalf("got bar %d side %d, want bar 3 long", i, side)
    }
    down := func(i int) float64 { return 2*100 - breakout(0.3)(i) }
    if i, side := ORBSignal(Session(day, down)); i != 3 || side != Short {
        t.Fatalf("got bar %d side %d, want bar 3 short", i, side)
    }
}

The short case is just the breakout mirrored around 100. I didn't plan that, it just fell out of the price function idea and saved me writing another helper.

You know exactly why every number is what it is. When this test fails, I can work out by hand what bar 3 should be. With real data I'd be opening a chart and squinting.

Testing the exit rules on their own

The exits are the fiddly part. The rules are simple to say. Book half at +1%. After that, sell the rest at +1.5%, or as soon as profit drops back under +1%. Hard stop at -1.5%. In the real code there is also a recovery check at -1% that looks at RSI, EMAs and VWAP before giving up, and a square off at 15:15.

One design choice made testing much easier. The backtest and the live engine both call the same exits.Evaluate function. A comment at the top of that package says it plainly: a strategy is chosen under exactly the exits it will later be traded with. If there was two copies of the rules, I would need two sets of tests and they would drift.

Evaluate takes a position and a price and returns a decision. No candles, no clock. So the test is a plain table. This is trimmed from the real one (I dropped the recovery cases to keep it short):

var rules = Rules{FirstTargetPct: 1, FinalTargetPct: 1.5, FloorAfterHalfPct: 1, StopLossPct: 1.5}

func TestEvaluate(t *testing.T) {
    long := Position{Side: Long, EntryPrice: 100, Qty: 10, Remaining: 10}
    short := Position{Side: Short, EntryPrice: 100, Qty: 10, Remaining: 10}
    half := long
    half.Remaining, half.HalfBooked = 5, true

    cases := []struct {
        name    string
        pos     Position
        price   float64
        qty     int
        reason  string
        halfSet bool
    }{
        {"hold small gain", long, 100.5, 0, "", false},
        {"first target books half", long, 101, 5, "first_target", true},
        {"gap through both targets books all", long, 101.6, 10, "final_target", true},
        {"after half: hold above floor", half, 101.2, 0, "", false},
        {"after half: below floor exits rest", half, 100.9, 5, "below_floor_after_half", false},
        {"stop loss", long, 98.5, 10, "stop_loss", false},
        {"short first target", short, 99, 5, "first_target", true},
        {"short stop", short, 101.5, 10, "stop_loss", false},
        {"single share marks half without selling", Position{Side: Long, EntryPrice: 100, Qty: 1, Remaining: 1}, 101, 0, "first_target", true},
    }
    for _, c := range cases {
        d := Evaluate(c.pos, c.price, rules)
        if d.Qty != c.qty || d.Reason != c.reason || d.HalfBooked != c.halfSet {
            t.Errorf("%s: got qty=%d reason=%q half=%v, want qty=%d reason=%q half=%v",
                c.name, d.Qty, d.Reason, d.HalfBooked, c.qty, c.reason, c.halfSet)
        }
    }
}

Two rows in there are edge cases that are easy to miss. The gap row: if price jumps from +0.5% straight to +1.6% between two checks, it should book everything at once, not half. And the single share row. You can't sell half of one share, 1 / 2 is zero in Go, so the position gets marked as half booked without selling anything and then rides to the final target under the same floor. A table makes these cheap to add, its one more line.

Putting them together

The last test feeds a synthetic breakout day bar by bar into the exit rules. It is a tiny backtest with no indicators.

func TestBreakoutDayExits(t *testing.T) {
    candles := Session(day, breakout(0.3))
    i, side := ORBSignal(candles)
    pos := Position{Side: side, EntryPrice: candles[i].Close, Qty: 49, Remaining: 49}
    var reasons []string
    for _, c := range candles[i+1:] {
        d := Evaluate(pos, c.Close, rules)
        if d.HalfBooked {
            pos.HalfBooked = true
        }
        if d.Qty == 0 {
            continue
        }
        reasons = append(reasons, d.Reason)
        pos.Remaining -= d.Qty
        if pos.Remaining == 0 {
            break
        }
    }
    if len(reasons) != 2 || reasons[0] != "first_target" || reasons[1] != "final_target" {
        t.Fatalf("reasons = %v", reasons)
    }
}

Why 49 shares? In the real backtest test the notional is ₹5000 and the entry is 100.3, so floor(5000 / 100.3) is 49. The real test then checks the money too: 24 shares closed at +1% and 25 at +1.5%. I check it with a tolerance of one paisa, because float maths.

The real backtest is stricter than this loop. It walks each bar as open, then the adverse extreme, then the favourable one, then close, so a bar that touches both the stop and the target counts as a stop. That's the pessimistic assumption when you don't know the path inside the bar. The synthetic candles make that easy to test as well, you just write a day that collapses right after the breakout and check the loss is never worse than the 1.5% stop.

Run everything with the usual command.

go test -v ./...
=== RUN   TestSessionShape
--- PASS: TestSessionShape (0.00s)
=== RUN   TestORB
--- PASS: TestORB (0.00s)
=== RUN   TestEvaluate
--- PASS: TestEvaluate (0.00s)
=== RUN   TestBreakoutDayExits
--- PASS: TestBreakoutDayExits (0.00s)
PASS

Where synthetic candles fall short

They are too clean. Real days have gaps at the open, a dead lunch hour and volume spikes at 15:00, and my Session has none of that. So these tests tell me the code does what I meant. They say nothing about whether what I meant is any good on real prices. I try to keep those two questions separate in my head.

The same helper also drives the engine tests in the repo, which set up a few flat days and then one day with a move, and check positions open and close at the right times. The paper trader started as its own repo at the end of October and moved into my main algo-trade repo in November, where it also picked up futures lot sizing. The tests came along with it, and they are how I know the exits still behave the same after all that shuffling.

If you write your own, start with Flat and one trending day. You'll add the weird days later, when a bug shows you which ones you need.