GoFlux

GoFlux is a modern technical analysis library for Go, forked from techan by sdcoffey. This project aims to revitalize and expand the library with modern Go best practices, comprehensive testing, and additional technical analysis indicators.
Features
- 35+ technical analysis indicators (trend, momentum, volume, moving averages)
- Performance metrics (Sharpe, Sortino, Calmar, CAGR, drawdown, and more)
- Candlestick pattern detection (20+ patterns)
- Rule-based strategy engine (AND/OR/NOT, trailing stops, time-based exits)
- Backtesting engine with trade & equity analytics
- Time series utilities (resampling, Heikin Ashi, Renko)
Installation
$ go get github.com/irfndi/goflux@latest
Quickstart
package main
import (
"fmt"
"log"
"strconv"
"time"
"github.com/irfndi/goflux/pkg"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
series := goflux.NewTimeSeries()
// fetch this from your preferred exchange
dataset := [][]string{
// Timestamp, Open, Close, High, Low, volume
{"1234567", "1", "2", "3", "5", "6"},
}
for _, datum := range dataset {
start, _ := strconv.ParseInt(datum[0], 10, 64)
period := goflux.NewTimePeriod(time.Unix(start, 0), time.Hour*24)
candle := goflux.NewCandle(period)
open, err := goflux.NewDecimalFromStringWithError(datum[1])
if err != nil {
return err
}
closePrice, err := goflux.NewDecimalFromStringWithError(datum[2])
if err != nil {
return err
}
maxPrice, err := goflux.NewDecimalFromStringWithError(datum[3])
if err != nil {
return err
}
minPrice, err := goflux.NewDecimalFromStringWithError(datum[4])
if err != nil {
return err
}
volume, err := goflux.NewDecimalFromStringWithError(datum[5])
if err != nil {
return err
}
candle.OpenPrice = open
candle.ClosePrice = closePrice
candle.MaxPrice = maxPrice
candle.MinPrice = minPrice
candle.Volume = volume
series.AddCandle(candle)
}
closePrices := goflux.NewClosePriceIndicator(series)
movingAverage := goflux.NewEMAIndicator(closePrices, 10)
fmt.Println(movingAverage.Calculate(0).FormattedString(2))
return nil
}
Creating trading strategies
indicator := goflux.NewClosePriceIndicator(series)
// record trades on this object
record := goflux.NewTradingRecord()
entryConstant := goflux.NewConstantIndicator(30)
exitConstant := goflux.NewConstantIndicator(10)
// Is satisfied when the price ema moves above 30 and the current position is new
entryRule := goflux.And(
goflux.NewCrossUpIndicatorRule(entryConstant, indicator),
goflux.PositionNewRule{})
// Is satisfied when the price ema moves below 10 and the current position is open
exitRule := goflux.And(
goflux.NewCrossDownIndicatorRule(indicator, exitConstant),
goflux.PositionOpenRule{})
strategy := goflux.RuleStrategy{
UnstablePeriod: 10, // Index at or below which ShouldEnter and ShouldExit return false
EntryRule: entryRule,
ExitRule: exitRule,
}
strategy.ShouldEnter(0, record) // returns false
Parameter Optimization
GoFlux includes a parameter optimization framework for systematically discovering optimal strategy parameter combinations via grid search or random search.
import "github.com/irfndi/goflux/pkg/backtest"
config := backtest.OptimizationConfig{
Method: backtest.OptMethodGridSearch,
ParameterSpaces: []backtest.ParameterSpace{
{Name: "ema_window", Min: 5, Max: 20, Step: 5},
{Name: "rsi_threshold", Min: 30, Max: 50, Step: 10},
},
ObjectiveFunc: backtest.ObjectiveNetProfit,
MaxWorkers: 4, // Parallel execution
}
optimizer, err := backtest.NewOptimizer(config)
if err != nil {
log.Fatal(err)
}
result, err := optimizer.Optimize(
series,
func(params map[string]float64) trading.Strategy {
emaWindow := int(params["ema_window"])
rsiThreshold := params["rsi_threshold"]
// Build strategy with these parameters...
return myStrategyFactory(emaWindow, rsiThreshold)
},
backtest.BacktestConfig{
InitialCapital: decimal.New(10000),
AllowLong: true,
},
)
fmt.Printf("Best config: %v\n", result.BestConfig)
fmt.Printf("Best score: %f\n", result.BestScore)
fmt.Printf("Total runs: %d\n", result.TotalRuns)
Built-in objective functions: ObjectiveNetProfit, ObjectiveProfitFactor, ObjectiveWinRate, ObjectiveMaxDrawdown, ObjectiveSharpeRatio. Custom objective functions are also supported.
Event-Driven Backtesting
GoFlux provides an event-driven backtesting engine for realistic order execution simulation. Unlike the vectorized backtester which fills at bar close, the event-driven engine processes bars sequentially and supports limit orders, stop orders, partial fills, slippage, and commission models.
import "github.com/irfndi/goflux/pkg/backtest"
// Create events from your market data
events := []backtest.Event{
{
Type: backtest.EventBar,
Timestamp: time.Now(),
Symbol: "BTC-USD",
Data: backtest.BarEventData{
Candle: candle, // *series.Candle
},
},
}
// Configure a simulated broker with realistic fill models
broker := backtest.NewSimulatedBroker("BTC-USD", decimal.New(10000))
broker.FillPriceSource = backtest.FillAtOpen
broker.CommissionModel = backtest.PercentCommission(0.001) // 0.1%
broker.SlippageModel = backtest.FixedSlippage(decimal.New(0.5))
// Submit a limit order that fills when price crosses the limit
limitOrder := trading.NewOrderDetail(trading.BUY, trading.LimitOrder, "BTC-USD", decimal.New(1))
limitOrder.Price = decimal.New(50000)
broker.SubmitOrder(limitOrder)
// Run the event-driven backtest
edb := backtest.NewEventDrivenBacktester()
edb.Register("BTC-USD", broker, strategy)
results, err := edb.Run(events)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Trades: %d, Net Profit: %s\n",
results["BTC-USD"].TotalTrades,
results["BTC-USD"].NetProfit.FormattedString(2))
The event-driven engine supports:
- Market orders filled at open or close of the bar
- Limit orders filled when price crosses the limit
- Stop orders filled when price crosses the stop trigger
- Partial fills via configurable
PartialFillModel
- Multi-asset backtesting with independent brokers per symbol
Issue Tracking
This project uses Beads for issue tracking - a modern, AI-native tool designed for live directly in your codebase alongside your code.
Learn more: github.com/steveyegge/beads
For Developers
# Find available work
bd ready
# View issue details
bd show <issue-id>
# Claim work
bd update <issue-id> --status in_progress
# Complete work
bd close <issue-id>
# Sync with git
bd sync
Multi-Developer Collaboration
This project uses Protected Branch Mode for team collaboration:
- Issues are automatically committed to
beads-sync branch
main branch stays protected
- Team members review and merge metadata via PR
- See
CONTRIBUTING.md for setup instructions
Installation
# Install Beads
curl -sSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash
# Initialize in this repo (already configured)
bd ready
Roadmap
Run bd ready or bd list to see current planned improvements and tasks in progress.
Past work includes:
- Modern project structure
- Additional indicators and utilities
- Expanded trading and risk-management rules
- Comprehensive testing suite
- Improved documentation
- CI/CD pipeline with GitHub Actions
Migration from Techan
GoFlux maintains backward compatibility with the original techan API. Simply update your imports:
// Old
import "github.com/sdcoffey/techan"
// New
import "github.com/irfndi/goflux/pkg"
The package name is goflux, so you can use it directly:
import "github.com/irfndi/goflux/pkg"
// Usage
series := goflux.NewTimeSeries()
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines on how to contribute.
To contribute:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Submit a pull request
Acknowledgments
GoFlux builds on the pioneering work of the technical analysis community:
- techan (sdcoffey) – the original Go technical analysis library and direct foundation of this project.
- ta4j – a mature Java TA framework whose strategy composition and indicator design patterns heavily influenced GoFlux's architecture.
- TA‑Lib – the long-standing C/C++ technical analysis library (200+ indicators and candlestick patterns) that serves as a reference standard for indicator behavior and naming.
- Pandas TA (Python) – for ideas around indicator catalogs, composition patterns, and declarative strategy definitions.
- YATA (Rust) – for performance-oriented designs and trait-based indicator patterns.
- Backtrader – the Python backtesting framework that inspired GoFlux's analyzer and observer patterns.
- VectorBT – for vectorized operations and portfolio simulation approaches.
GoFlux aims to bring these proven ideas into a modern, idiomatic Go library focused on concurrent, cloud-native trading systems.
Telemetry (Opt-In)
GoFlux includes an optional telemetry system to help us understand which indicators and features are most used, so we can prioritize improvements. Telemetry is completely disabled by default.
Enabling telemetry
Add one line to your application initialization:
import "github.com/irfndi/goflux/pkg/telemetry"
func main() {
telemetry.Enable("https://goflux-telemetry.irfndi.workers.dev/v1/telemetry", "")
// ... rest of your application
}
What is collected
- Library version and Go version (e.g.,
go1.21, 0.0.6)
- Operating system and architecture (e.g.,
linux/amd64)
- Indicator names and parameter sizes (e.g.,
EMA with window=10)
- Error types and hashed error messages (no stack traces or raw errors)
- No IP addresses, no personal data, no financial data
Disabling telemetry
If you previously enabled it, call:
telemetry.Disable()
Or simply remove the telemetry.Enable() call.
License
GoFlux is released under the MIT license. See LICENSE for details.