examples: fix and harmonize the strategy backtests across all languages (#324)

The strategy_* examples were only syntax-smoked in CI, never run, which hid two
classes of problem:

1. Python strategy_macd_adx / strategy_bollinger_squeeze passed three separate
   arguments to the candle indicators ADX/ATR, whose .update() takes a single
   candle — a TypeError at runtime — and read the ADX tuple at index 0 (plus_di)
   instead of 2 (adx). Both fixed.

2. The Go / C# / R / Java strategies defaulted to synthetic data and used a
   different (annualised) one-line summary, so they printed wildly different
   numbers from the Rust/Python/Node/C/WASM suite. Rewrite them to the shared
   per-trade backtest (load the bundled BTCUSDT CSV by default, same entry/exit
   logic, same print_summary output).

All nine runnable bindings now print byte-identical backtest summaries on the
same data (MACD+ADX 246 trades / -47.19%, RSI 37 / -17.84%, Bollinger 1 / -7.82%),
verified by diffing each language's output against the Python reference. WASM
shares the same logic and bundled dataset (browser-rendered).
This commit is contained in:
kingchenc
2026-06-17 17:56:22 +02:00
committed by GitHub
parent 2e07c07a40
commit 75eefbbd08
20 changed files with 886 additions and 196 deletions
+78 -27
View File
@@ -1,5 +1,13 @@
// Breakout: when Bollinger bandwidth is tight (a "squeeze") and price closes above
// the upper band, go long with an ATR(14) trailing stop.
// Strategy example: Bollinger-squeeze breakout with an ATR(14) trailing stop.
//
// Enters long when Bollinger bandwidth makes a new SQUEEZE_LOOKBACK low (a
// volatility squeeze) and price closes above the upper band; exits on an ATR(14)
// trailing stop or when the upper band falls back below the entry. 0.1% fees per
// trade. The Go counterpart of examples/python/strategy_bollinger_squeeze.py,
// printing the same summary.
//
// Uses the checked-in examples/data/btcusdt-1d.csv dataset (daily bars give an
// interpretable ~6-month-low lookback); pass a CSV path to override.
package main
import (
@@ -11,47 +19,90 @@ import (
"github.com/wickra-lib/wickra/examples/go/internal/market"
)
const (
fee = 0.001
bbPeriod = 20
bbK = 2.0
atrPeriod = 14
atrStopMult = 2.0
squeezeLookback = 180
)
func main() {
bars := loadBars()
bollinger, _ := wickra.NewBollingerBands(20, 2.0)
defer bollinger.Close()
atr, _ := wickra.NewAtr(14)
bb, _ := wickra.NewBollingerBands(bbPeriod, bbK)
defer bb.Close()
atr, _ := wickra.NewAtr(atrPeriod)
defer atr.Close()
var returns []float64
trades := 0
inPosition := false
entry := 0.0
stop := 0.0
entryPrice := 0.0
stopLevel := 0.0
var closedTrades []float64
equity := 1.0
var equityCurve []float64
var bwWindow []float64
for _, b := range bars {
band, okBand := bollinger.Update(b.Close)
atrValue := atr.Update(b.Open, b.High, b.Low, b.Close, b.Volume, b.Timestamp)
if !okBand || math.IsNaN(atrValue) {
band, okBand := bb.Update(b.Close)
atrVal := atr.Update(b.Open, b.High, b.Low, b.Close, b.Volume, b.Timestamp)
price := b.Close
mtm := equity
if inPosition {
mtm = equity * (price / entryPrice)
}
equityCurve = append(equityCurve, mtm)
if !okBand || math.IsNaN(atrVal) {
continue
}
bandwidth := math.MaxFloat64
if band.Middle != 0.0 {
bandwidth = (band.Upper - band.Lower) / band.Middle
upper, middle, lower := band.Upper, band.Middle, band.Lower
if math.Abs(middle) <= 1e-12 {
continue
}
bandwidth := (upper - lower) / middle
bwWindow = append(bwWindow, bandwidth)
if len(bwWindow) > squeezeLookback {
bwWindow = bwWindow[len(bwWindow)-squeezeLookback:]
}
if len(bwWindow) < squeezeLookback {
continue
}
minBw := bwWindow[0]
for _, v := range bwWindow {
if v < minBw {
minBw = v
}
}
if !inPosition && bandwidth < 0.06 && b.Close > band.Upper {
inPosition = true
entry = b.Close
stop = b.Close - 2.0*atrValue
trades++
} else if inPosition {
stop = math.Max(stop, b.Close-2.0*atrValue) // trail the stop up
if b.Close < stop {
returns = append(returns, (b.Close-entry)/entry)
if inPosition {
if price < stopLevel || upper < entryPrice {
tradeRet := price/entryPrice - 1.0
closedTrades = append(closedTrades, tradeRet)
equity *= (1.0 + tradeRet) * (1.0 - fee)
inPosition = false
}
} else {
isNewLow := math.Abs(bandwidth-minBw) < 1e-12
if isNewLow && price > upper {
entryPrice = price
stopLevel = price - atrStopMult*atrVal
equity *= 1.0 - fee
inPosition = true
}
}
}
market.Print("Bollinger squeeze", market.Summarize(returns, trades, 252.0))
if inPosition {
lastPrice := bars[len(bars)-1].Close
tradeRet := lastPrice/entryPrice - 1.0
closedTrades = append(closedTrades, tradeRet)
equity *= (1.0 + tradeRet) * (1.0 - fee)
}
market.PrintSummary("Bollinger Squeeze Breakout (1d, BTCUSDT)",
bars[0].Close, bars[len(bars)-1].Close, len(bars), closedTrades, equity, equityCurve)
}
func loadBars() []market.Bar {
@@ -62,5 +113,5 @@ func loadBars() []market.Bar {
}
return bars
}
return market.SyntheticCandles(2000)
return market.BundledCandles("btcusdt-1d.csv")
}