### Example YAML Configuration Source: https://github.com/disciplinedware/algosmithy/blob/main/docs/agentic-loop.md This YAML configuration defines the environment, test grid, and parameters for a strategy. It's used by the backtester. ```yaml environment: exchange: "alpaca" symbol: "AAPL" timeframe: "15m" start_date: "2023-01-01T00:00:00Z" end_date: "2023-12-31T00:00:00Z" test_grid: param1: - "value1" - "value2" param2: - 100 - 200 params: param1: "value1" # Default value, can be overridden by test_grid param2: 100 # Default value, can be overridden by test_grid ``` -------------------------------- ### Example Go Strategy Code Source: https://github.com/disciplinedware/algosmithy/blob/main/docs/agentic-loop.md This Go code demonstrates the structure of a strategy that can be generated by the LLM. It includes the necessary interface implementation and registration. ```go package main import ( "fmt" "github.com/alpacahq/alpaca-trade-api-go/v2/alpaca" "github.com/alpacahq/alpaca-trade-api-go/v2/marketdata/stream" ) // ICandleStrategy defines the interface for candle-based strategies. type ICandleStrategy interface { Name() string Description() string Initialize(params interface{}) OnCandle(candle stream.Message, candles []stream.Message) (interface{}, error) } // IOrderBookStrategy defines the interface for order-book-based strategies. type IOrderBookStrategy interface { Name() string Description() string Initialize(params interface{}) OnOrderBook(orderBook stream.Message, orderBooks []stream.Message) (interface{}, error) } // ExampleCandleStrategy is a sample implementation of ICandleStrategy. type ExampleCandleStrategy struct { param1 string param2 int } func (s *ExampleCandleStrategy) Name() string { return "ExampleCandleStrategy" } func (s *ExampleCandleStrategy) Description() string { return "A simple example candle strategy." } func (s *ExampleCandleStrategy) Initialize(params interface{}) { fmt.Printf("Initializing ExampleCandleStrategy with params: %+v\n", params) // Type assertion or unmarshalling would happen here to set s.param1 and s.param2 } func (s *ExampleCandleStrategy) OnCandle(candle stream.Message, candles []stream.Message) (interface{}, error) { fmt.Printf("Processing candle: %+v\n", candle) // Strategy logic would go here return nil, nil } // RegisterStrategy registers the strategy with the system. func RegisterStrategy() { // In a real scenario, this would register the strategy class with a factory or registry. fmt.Println("Registering ExampleCandleStrategy") } func init() { RegisterStrategy() } func main() { // Example usage (not part of the generated code itself, but for demonstration) strategy := &ExampleCandleStrategy{} strategy.Initialize(map[string]interface{}{"param1": "value1", "param2": 100}) // Simulate receiving a candle strategy.OnCandle(stream.Message{}, []stream.Message{}) } ``` -------------------------------- ### Example JSON Result Source: https://github.com/disciplinedware/algosmithy/blob/main/docs/agentic-loop.md This JSON structure represents a potential result or output from the LLM, possibly detailing a finalized algorithm. ```json { "name": "ExampleCandleStrategy", "description": "A simple example candle strategy.", "parameters": { "param1": "value1", "param2": 100 }, "performance": { "sharpe_ratio": 1.5, "total_return": 0.25, "max_drawdown": 0.10 } } ``` -------------------------------- ### Registering a Custom Strategy Source: https://context7.com/disciplinedware/algosmithy/llms.txt Use the init function to register a strategy factory with the backtest engine, ensuring it is discoverable. ```go package my_strategy import "trading/libs/7_common/strategy_factories" func init() { strategy_factories.RegisterStrategy("my_strategy", NewMyStrategy) } func NewMyStrategy() types.IStrategy { return &MyStrategy{} } ``` -------------------------------- ### Manage Orders via Strategy Manager Source: https://context7.com/disciplinedware/algosmithy/llms.txt Demonstrates checking available position sizes and registering market orders within the OnCandle event handler. ```go func (st *MyStrategy) OnCandle(sctx types.ISmartContext, candle *types.Candle) error { price := candle.Close // Check available size to sell (current position) pos, err := st.stman.GetAvailableSizeToSell(sctx, st.params.Pair) if err != nil { sctx.Errorf("GetAvailableSizeToSell failed: %v", err) return err } // Check available size to buy based on current capital size, err := st.stman.GetAvailableSizeToBuy(sctx, st.params.Pair, price) if err != nil { sctx.Errorf("GetAvailableSizeToBuy failed: %v", err) return err } // Execute buy order if size.GreaterThan(decimal.Zero) { return st.stman.RegisterOrder(sctx, &types.Order{ Type: types.Market, Side: types.Buy, Pair: st.params.Pair, Size: size, Price: price, Timestamp: candle.Time, }) } // Execute sell order if pos.GreaterThan(decimal.Zero) { return st.stman.RegisterOrder(sctx, &types.Order{ Type: types.Market, Side: types.Sell, Pair: st.params.Pair, Size: pos, Price: price, Timestamp: candle.Time, }) } return nil } ``` -------------------------------- ### Implement Bollinger Bands Indicator in Go Source: https://context7.com/disciplinedware/algosmithy/llms.txt Provides a Go implementation for calculating Bollinger Bands with configurable period and standard deviation. Requires the 'decimal' and 'math' packages. ```go type BollingerBands struct { period int stddev decimal.Decimal prices []decimal.Decimal current decimal.Decimal } func NewBollingerBands(period int, stddev float64) *BollingerBands { return &BollingerBands{ period: period, stddev: decimal.NewFromFloat(stddev), prices: make([]decimal.Decimal, 0), } } func (b *BollingerBands) Update(price decimal.Decimal) (upper, lower, middle decimal.Decimal, ready bool) { b.prices = append(b.prices, price) if len(b.prices) > b.period { b.prices = b.prices[1:] } if len(b.prices) < b.period { return decimal.Zero, decimal.Zero, decimal.Zero, false } // Calculate middle band (SMA) var sum decimal.Decimal for _, p := range b.prices { sum = sum.Add(p) } middle = sum.Div(decimal.NewFromFloat(float64(b.period))) // Calculate standard deviation var varianceSum decimal.Decimal for _, p := range b.prices { varianceSum = varianceSum.Add(p.Sub(middle).Pow(decimal.NewFromFloat(2))) } variance := varianceSum.Div(decimal.NewFromFloat(float64(b.period))) stdDev := decimal.NewFromFloat(math.Sqrt(variance.InexactFloat64())) bandWidth := stdDev.Mul(b.stddev) upper = middle.Add(bandWidth) lower = middle.Sub(bandWidth) return upper, lower, middle, true } ``` -------------------------------- ### EMA Crossover Strategy Structure and Initialization Source: https://context7.com/disciplinedware/algosmithy/llms.txt Defines the parameters and structure for the EMA Crossover strategy. Initialization involves decoding parameters and setting up the necessary EMA indicators. ```go type EmaCrossoverParams struct { ShortWindow int `mapstructure:"short_window"` LongWindow int `mapstructure:"long_window"` SignalWindow int `mapstructure:"signal_window"` Pair types.Pair `mapstructure:"pair"` } var _ types.IStrategy = (*EmaCrossover)(nil) type EmaCrossover struct { stman types.IStrategyManager params *EmaCrossoverParams emaShort *EMA emaLong *EMA emaSignal *EMA lastMACD decimal.Decimal } func NewEmaCrossover() types.IStrategy { return &EmaCrossover{} } func (st *EmaCrossover) Init(stman types.IStrategyManager, raw map[string]any) error { st.stman = stman cfg, err := utils.DecodeParams[EmaCrossoverParams](raw) if err != nil { return fmt.Errorf("failed to decode params: %w", err) } st.params = cfg st.emaShort = NewEMA(cfg.ShortWindow) st.emaLong = NewEMA(cfg.LongWindow) st.emaSignal = NewEMA(cfg.SignalWindow) return nil } ``` -------------------------------- ### Implement IStrategy Interface in Go Source: https://context7.com/disciplinedware/algosmithy/llms.txt Defines a custom strategy structure with parameter binding and lifecycle methods required for registration in the Algosmithy engine. ```go package my_strategy import ( "fmt" "github.com/shopspring/decimal" "trading/libs/7_common/types" "trading/libs/7_common/utils" ) // Define strategy parameters with mapstructure tags for YAML binding type MyStrategyParams struct { ShortWindow int `mapstructure:"short_window"` LongWindow int `mapstructure:"long_window"` Pair types.Pair `mapstructure:"pair"` } // Ensure interface compliance var _ types.IStrategy = (*MyStrategy)(nil) type MyStrategy struct { stman types.IStrategyManager params *MyStrategyParams } // Factory function for strategy registration func NewMyStrategy() types.IStrategy { return &MyStrategy{} } // Initialize strategy with manager and decode parameters from YAML func (st *MyStrategy) Init(stman types.IStrategyManager, raw map[string]any) error { st.stman = stman cfg, err := utils.DecodeParams[MyStrategyParams](raw) if err != nil { return fmt.Errorf("failed to decode params: %w", err) } st.params = cfg return nil } func (st *MyStrategy) OnStart(sctx types.ISmartContext) error { sctx.Infof("Strategy started for %s", st.params.Pair) return nil } func (st *MyStrategy) OnStopped(sctx types.ISmartContext) error { sctx.Infof("Strategy stopped") return nil } func (st *MyStrategy) OnTrade(sctx types.ISmartContext, trade *types.Trade) error { return nil } func (st *MyStrategy) OnCandle(sctx types.ISmartContext, candle *types.Candle) error { // Strategy logic here return nil } ``` -------------------------------- ### Configure Backtests with YAML Source: https://context7.com/disciplinedware/algosmithy/llms.txt Defines the structure for a backtest configuration file in YAML format. It specifies environment settings, test cases, optimizer parameters, and strategy configurations. ```yaml backtest: max_parallel_runs: 10 environment: start_date: "2025-03-01T00:00:00Z" end_date: "2025-03-31T00:00:00Z" tests: ema_crossover: optimizer: method: "grid" parameters: short_window: values: [12] long_window: values: [26] signal_window: values: [9] pair: values: ["bybit:ETHUSDT", "bybit:BTCUSDT"] timeframe: values: ["5m", "1h"] strategies: - class: "ema_crossover" system_params: base_currency: "USDT" initial_position: USDT: "1000.0" ETH: "0.1" subscriptions: - type: candles pair: $pair timeframe: $timeframe params: pair: $pair short_window: $short_window long_window: $long_window signal_window: $signal_window executor: trailing_smart ``` -------------------------------- ### LLM Agentic Tool Definitions Source: https://context7.com/disciplinedware/algosmithy/llms.txt List of available tools for data discovery, strategy execution, and memory management accessible by the LLM engine. ```go // Available LLM Tools: // Data Discovery Tools GetCandles // Retrieve historical candle data GetOrderFlow // Get order flow data GetFundingRates // Fetch funding rate history GetLiquidations // Get liquidation events GetVolumeProfile // Retrieve volume profile GetMarketLevels // Get support/resistance levels GetTrendlines // Detect trendlines GetPatterns // Find chart patterns GetFibonacciLevels // Calculate Fibonacci retracements ListAvailableIndicators // List all available indicators // Execution Tools RunBacktest // Compile Go code + YAML and execute in Docker sandbox FinalizeAlgorithm // Store final strategy name/description // Memory Tools SetShortTermMemory // Store intermediate results GetShortTermMemory // Retrieve stored results InternalThoughts // Persist reasoning traces ``` -------------------------------- ### Backtest Result Structure in JSON Source: https://context7.com/disciplinedware/algosmithy/llms.txt Illustrates the JSON structure for backtest results, detailing performance metrics such as PnL, trade statistics, and win rates for each parameter combination. ```json [ { "test_run_name": "ema_crossover", "combination_results": [ { "environment": { "StartDate": "2025-03-01T00:00:00Z", "EndDate": "2025-03-31T00:00:00Z" }, "strategy_results": { "strategy_0_ema_crossover": { "strategy_id": "strategy_0_ema_crossover", "config": { "Class": "ema_crossover", "SystemParams": { "base_currency": "USDT", "initial_position": {"eth": "0.1", "usdt": "1000.0"}, "subscriptions": [ {"pair": "bybit:BTCUSDT", "timeframe": "1h", "type": "candles"} ] }, "Params": { "long_window": 26, "pair": "bybit:BTCUSDT", "short_window": 12, "signal_window": 9 } }, "initial_cash": {"eth": "0.1", "usdt": "1000"}, "final_cash": {"btc": "0", "eth": "0.1", "usdt": "1049.786060775831484348902887"}, "net_profit": "49.786060775831484348902887", "total_trades": 46, "winning_trades": 45, "win_rate_pct": "97.82608695652174", "avg_trade_profit": "66.472599568318464" } }, "error": "" } ] } ] ``` -------------------------------- ### EMA Crossover Strategy OnCandle Logic Source: https://context7.com/disciplinedware/algosmithy/llms.txt Processes incoming candles to update EMAs, calculate MACD and signal lines, and generate buy/sell orders based on crossover events. Requires EMAs to be ready before generating signals. ```go func (st *EmaCrossover) OnCandle(sctx types.ISmartContext, candle *types.Candle) error { price := candle.Close short := st.emaShort.Update(price) long := st.emaLong.Update(price) if !st.emaShort.Ready() || !st.emaLong.Ready() { return nil } macd := short.Sub(long) signal := st.emaSignal.Update(macd) if !st.emaSignal.Ready() { return nil } prev := st.lastMACD st.lastMACD = macd // Buy signal: MACD crosses above signal line if prev.LessThan(signal) && macd.GreaterThan(signal) { pos, _ := st.stman.GetAvailableSizeToSell(sctx, st.params.Pair) if pos.LessThanOrEqual(decimal.Zero) { size, _ := st.stman.GetAvailableSizeToBuy(sctx, st.params.Pair, price) if size.GreaterThan(decimal.Zero) { return st.stman.RegisterOrder(sctx, &types.Order{ Type: types.Market, Side: types.Buy, Pair: st.params.Pair, Size: size, Price: price, Timestamp: candle.Time, }) } } } // Sell signal: MACD crosses below signal line if prev.GreaterThan(signal) && macd.LessThan(signal) { pos, _ := st.stman.GetAvailableSizeToSell(sctx, st.params.Pair) if pos.GreaterThan(decimal.Zero) { return st.stman.RegisterOrder(sctx, &types.Order{ Type: types.Market, Side: types.Sell, Pair: st.params.Pair, Size: pos, Price: price, Timestamp: candle.Time, }) } } return nil } ``` -------------------------------- ### EMA Indicator with Decimal Precision Source: https://context7.com/disciplinedware/algosmithy/llms.txt Implements an Exponential Moving Average (EMA) indicator using decimal precision to avoid floating-point errors. Initialize with NewEMA and update with Update. ```go package ema_crossover import ( "fmt" "github.com/shopspring/decimal" "trading/libs/7_common/types" "trading/libs/7_common/utils" ) // EMA indicator with decimal precision type EMA struct { period int k decimal.Decimal value decimal.Decimal count int } func NewEMA(period int) *EMA { k := decimal.NewFromFloat(2.0 / (float64(period) + 1.0)) return &EMA{period: period, k: k} } func (e *EMA) Update(price decimal.Decimal) decimal.Decimal { if e.count == 0 { e.value = price } else { e.value = price.Mul(e.k).Add(e.value.Mul(decimal.NewFromFloat(1).Sub(e.k))) } e.count++ return e.value } func (e *EMA) Ready() bool { return e.count >= e.period } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.