Documentation
¶
Index ¶
- Constants
- Variables
- func FormatFloat(value float64, precision int) string
- func FormatWithOptimalPrecision(value float64) string
- func NumDecPlaces(v float64) int64
- func ParseFloat(s string) (float64, error)
- func TrimTrailingZeros(s string) string
- type Account
- type AssetInfo
- func (a *AssetInfo) ChangeMaxPrice(price float64) error
- func (a *AssetInfo) ChangeMaxQuantity(quantity float64) error
- func (a *AssetInfo) ChangeMinPrice(price float64) error
- func (a *AssetInfo) ChangeMinQuantity(quantity float64) error
- func (a *AssetInfo) ChangeStepSize(size float64) error
- func (a *AssetInfo) ChangeTickSize(size float64) error
- func (a AssetInfo) GetBaseAsset() string
- func (a AssetInfo) GetBaseAssetPrecision() int
- func (a AssetInfo) GetMaxPrice() float64
- func (a AssetInfo) GetMaxQuantity() float64
- func (a AssetInfo) GetMinPrice() float64
- func (a AssetInfo) GetMinQuantity() float64
- func (a AssetInfo) GetQuoteAsset() string
- func (a AssetInfo) GetQuotePrecision() int
- func (a AssetInfo) GetStepSize() float64
- func (a AssetInfo) GetTickSize() float64
- type Balance
- type Broker
- type Candle
- func (c Candle) GetClose() float64
- func (c Candle) GetHigh() float64
- func (c Candle) GetLow() float64
- func (c Candle) GetMetadata() map[string]float64
- func (c Candle) GetOpen() float64
- func (c Candle) GetPair() string
- func (c Candle) GetTime() time.Time
- func (c Candle) GetUpdatedAt() time.Time
- func (c Candle) GetVolume() float64
- func (c Candle) IsComplete() bool
- func (c Candle) IsEmpty() bool
- func (c Candle) Less(j Item) bool
- func (c Candle) ToHeikinAshi(ha *HeikinAshi) Candle
- func (c Candle) ToSlice(precision int) []string
- type CandleSubscriber
- type ChartIndicator
- type Dataframe
- type Evaluator
- type Exchange
- type Feeder
- type HeikinAshi
- type HighFrequencyStrategy
- type IndicatorMetric
- type Item
- type Level
- type Logger
- type MetricName
- type MetricStyle
- type Notifier
- type NotifierWithStart
- type OptimizableStrategy
- type Optimizer
- type OptimizerResult
- type Order
- func (o Order) GetCandle() Candle
- func (o Order) GetCreatedAt() time.Time
- func (o Order) GetExchangeID() int64
- func (o Order) GetGroupID() *int64
- func (o Order) GetID() int64
- func (o Order) GetPair() string
- func (o Order) GetPrice() float64
- func (o Order) GetProfit() float64
- func (o Order) GetProfitValue() float64
- func (o Order) GetQuantity() float64
- func (o Order) GetRefPrice() float64
- func (o Order) GetSide() SideType
- func (o Order) GetStatus() OrderStatusType
- func (o Order) GetStop() *float64
- func (o Order) GetType() OrderType
- func (o Order) GetUpdatedAt() time.Time
- func (o Order) GetValue() float64
- func (o Order) IsActive() bool
- func (o Order) IsBuy() bool
- func (o Order) IsFilled() bool
- func (o Order) IsSell() bool
- func (o Order) String() string
- type OrderFilter
- type OrderStatusType
- type OrderSubscriber
- type OrderType
- type Parameter
- type ParameterSet
- type ParameterType
- type PriorityQueue
- type Series
- type Settings
- type SideType
- type Storage
- type Strategy
- type StrategyEvaluator
- type TelegramSettings
Constants ¶
const ( StyleBar = "bar" StyleScatter = "scatter" StyleLine = "line" StyleHistogram = "histogram" StyleWaterfall = "waterfall" )
Variables ¶
var ( ErrBaseAssetEmpty = errors.New("empty base asset") ErrQuoteAssetEmpty = errors.New("empty quote asset") ErrNegativeValue = errors.New("negative value") )
var (
ErrOutOfMoneyInAccounts = errors.New("out of money in accounts")
)
Errs
Functions ¶
func FormatFloat ¶
FormatFloat formats a float64 with appropriate precision Returns a string representation of the float
func FormatWithOptimalPrecision ¶
FormatWithOptimalPrecision formats a float using its inherent precision It determines the number of decimal places automatically
func NumDecPlaces ¶
NumDecPlaces returns the number of decimal places in a float64 Useful for formatting with appropriate precision
func ParseFloat ¶
ParseFloat parses a string into a float64 Returns the float value and any error encountered
func TrimTrailingZeros ¶
TrimTrailingZeros removes unnecessary zeros after the decimal point
Types ¶
type Account ¶
type Account struct {
Balances []Balance
}
Account represents a trading account with multiple asset balances
func NewAccount ¶
func (Account) GetBalance ¶
GetBalance retrieves the balance for a specific asset and quote pair Returns two Balance objects: one for the asset and one for the quote If a balance is not found for either ticker, an empty Balance is returned
func (Account) GetBalanceMap ¶
GetBalanceMap returns a map of asset tickers to balances for efficient lookups
func (Account) GetBalances ¶
GetBalances returns all balances in the account
type AssetInfo ¶
type AssetInfo struct { BaseAsset string QuoteAsset string MinPrice float64 MaxPrice float64 MinQuantity float64 MaxQuantity float64 StepSize float64 TickSize float64 QuotePrecision int BaseAssetPrecision int }
AssetInfo contains market information about a trading pair
func NewAssetInfo ¶
func NewAssetInfo( baseAsset string, quoteAsset string, minPrice float64, maxPrice float64, minQuantity float64, maxQuantity float64, stepSize float64, tickSize float64, quotePrecision int, baseAssetPrecision int, ) (AssetInfo, error)
NewAssetInfo creates a new AssetInfo instance with validation
func (*AssetInfo) ChangeMaxPrice ¶
ChangeMaxPrice updates the maximum price with validation
func (*AssetInfo) ChangeMaxQuantity ¶
ChangeMaxQuantity updates the maximum quantity with validation
func (*AssetInfo) ChangeMinPrice ¶
ChangeMinPrice updates the minimum price with validation
func (*AssetInfo) ChangeMinQuantity ¶
ChangeMinQuantity updates the minimum quantity with validation
func (*AssetInfo) ChangeStepSize ¶
ChangeStepSize updates the step size with validation
func (*AssetInfo) ChangeTickSize ¶
ChangeTickSize updates the tick size with validation
func (AssetInfo) GetBaseAsset ¶
GetBaseAsset returns the base asset of the trading pair
func (AssetInfo) GetBaseAssetPrecision ¶
GetBaseAssetPrecision returns the precision of the base asset
func (AssetInfo) GetMaxPrice ¶
GetMaxPrice returns the maximum price allowed for the trading pair
func (AssetInfo) GetMaxQuantity ¶
GetMaxQuantity returns the maximum quantity allowed for the trading pair
func (AssetInfo) GetMinPrice ¶
GetMinPrice returns the minimum price allowed for the trading pair
func (AssetInfo) GetMinQuantity ¶
GetMinQuantity returns the minimum quantity allowed for the trading pair
func (AssetInfo) GetQuoteAsset ¶
GetQuoteAsset returns the quote asset of the trading pair
func (AssetInfo) GetQuotePrecision ¶
GetQuotePrecision returns the precision of the quote asset
func (AssetInfo) GetStepSize ¶
GetStepSize returns the step size for quantity increments
func (AssetInfo) GetTickSize ¶
GetTickSize returns the tick size for price increments
type Balance ¶
Balance represents the available funds for a specific asset
func (Balance) GetLeverage ¶
GetLeverage returns the leverage value for the asset
type Broker ¶
type Broker interface { Account(ctx context.Context) (Account, error) Position(ctx context.Context, pair string) (asset, quote float64, err error) Order(ctx context.Context, pair string, id int64) (Order, error) CreateOrderOCO(ctx context.Context, side SideType, pair string, size, price, stop, stopLimit float64) ([]Order, error) CreateOrderLimit(ctx context.Context, side SideType, pair string, size float64, limit float64) (Order, error) CreateOrderMarket(ctx context.Context, side SideType, pair string, size float64) (Order, error) CreateOrderMarketQuote(ctx context.Context, side SideType, pair string, quote float64) (Order, error) CreateOrderStop(ctx context.Context, pair string, quantity float64, limit float64) (Order, error) Cancel(ctx context.Context, order Order) error }
type Candle ¶
type Candle struct { Pair string Time time.Time UpdatedAt time.Time Open float64 Close float64 Low float64 High float64 Volume float64 Complete bool // Additional columns from CSV inputs Metadata map[string]float64 }
Candle represents a trading candle with OHLCV data
func (Candle) GetMetadata ¶
GetMetadata returns the additional metadata associated with the candle
func (Candle) GetUpdatedAt ¶
GetUpdatedAt returns the last update time of the candle
func (Candle) IsComplete ¶
IsComplete returns whether the candle period is complete
func (Candle) ToHeikinAshi ¶
func (c Candle) ToHeikinAshi(ha *HeikinAshi) Candle
ToHeikinAshi transforms a regular candle into a Heikin-Ashi candle
type CandleSubscriber ¶
type CandleSubscriber interface {
OnCandle(Candle)
}
type ChartIndicator ¶
type Dataframe ¶
type Dataframe struct { Pair string Close Series[float64] Open Series[float64] High Series[float64] Low Series[float64] Volume Series[float64] Time []time.Time LastUpdate time.Time // Custom user metadata for indicators Metadata map[string]Series[float64] }
Dataframe is a time series container for OHLCV and custom indicator data
type Evaluator ¶
type Evaluator interface { // Evaluate runs a backtest with the given parameters and returns performance metrics Evaluate(ctx context.Context, params ParameterSet) (*OptimizerResult, error) }
Evaluator defines the interface for evaluating a parameter set
type Feeder ¶
type Feeder interface { AssetsInfo(pair string) (AssetInfo, error) LastQuote(ctx context.Context, pair string) (float64, error) CandlesByPeriod(ctx context.Context, pair, period string, start, end time.Time) ([]Candle, error) CandlesByLimit(ctx context.Context, pair, period string, limit int) ([]Candle, error) CandlesSubscription(ctx context.Context, pair, timeframe string) (chan Candle, chan error) }
type HeikinAshi ¶
type HeikinAshi struct {
PreviousHACandle Candle
}
HeikinAshi handles the calculation of Heikin-Ashi candles Heikin-Ashi is a candlestick charting technique that filters out market noise
func NewHeikinAshi ¶
func NewHeikinAshi() *HeikinAshi
NewHeikinAshi creates a new HeikinAshi calculator
func (*HeikinAshi) CalculateHeikinAshi ¶
func (ha *HeikinAshi) CalculateHeikinAshi(c Candle) Candle
CalculateHeikinAshi transforms a standard candle into a Heikin-Ashi candle Formula: - HA_Close = (Open + High + Low + Close) / 4 - HA_Open = (Previous HA_Open + Previous HA_Close) / 2 - HA_High = Max(High, HA_Open, HA_Close) - HA_Low = Min(Low, HA_Open, HA_Close)
type HighFrequencyStrategy ¶
type IndicatorMetric ¶
type IndicatorMetric struct { Name string Color string Style MetricStyle // default: line Values Series[float64] }
type Level ¶
type Level int8
const ( Disabled Level = -1 // Disabled is used for disabled logging. TraceLevel Level = iota // TraceLevel is used for detailed debugging information. DebugLevel // DebugLevel is used for debugging information. InfoLevel // InfoLevel is used for informational messages. WarnLevel // WarnLevel is used for warning messages. ErrorLevel // ErrorLevel is used for error messages. FatalLevel // FatalLevel is used for fatal messages that cause the program to exit. PanicLevel // PanicLevel is used for panic messages that cause the program to panic. NoLevel // NoLevel is used for no logging level. )
type Logger ¶
type Logger interface { // Returns a logger based off the root logger and decorates it with the given context and arguments. WithField(key string, value any) Logger // WithField returns a logger with the given key-value pair. WithFields(fields map[string]any) Logger // WithFields returns a logger with the given fields. WithError(err error) Logger // WithError returns a logger with the given error. // Default log functions Print(args ...any) // Print logs the message with the default level. Trace(args ...any) // Trace logs the message with the trace level. Debug(args ...any) // Debug logs the message with the debug level. Info(args ...any) // Info logs the message with the info level. Warn(args ...any) // Warn logs the message with the warning level. Error(args ...any) // Error logs the message with the error level. Fatal(args ...any) // Fatal logs the message and then exits the program. Panic(args ...any) // Panic logs the message and then panics. // Log functions with format Printf(format string, args ...any) // Printf formats and logs the message with the given format and arguments. Tracef(format string, args ...any) // Tracef formats and logs the message with the given format and arguments. Debugf(format string, args ...any) // Debugf formats and logs the message with the given format and arguments. Infof(format string, args ...any) // Infof formats and logs the message with the given format and arguments. Warnf(format string, args ...any) // Warnf formats and logs the message with the given format and arguments. Errorf(format string, args ...any) // Errorf formats and logs the message with the given format and arguments. Fatalf(format string, args ...any) // Fatalf formats and logs the message with the given format and arguments. Panicf(format string, args ...any) // Panicf formats and logs the message with the given format and arguments. // Log level functions SetLevel(level Level) // SetLevel sets the logging level for the core. GetLevel() Level // GetLevel returns the logging level for the core. }
type MetricName ¶
type MetricName string
MetricName defines standard metric names for optimization
const ( // MetricProfit represents the total profit MetricProfit MetricName = "profit" // MetricWinRate represents the percentage of winning trades MetricWinRate MetricName = "win_rate" // MetricPayoff represents the payoff ratio MetricPayoff MetricName = "payoff" // MetricProfitFactor represents the profit factor MetricProfitFactor MetricName = "profit_factor" // MetricSQN represents the System Quality Number MetricSQN MetricName = "sqn" // MetricDrawdown represents the maximum drawdown MetricDrawdown MetricName = "drawdown" // MetricSharpeRatio represents the Sharpe ratio MetricSharpeRatio MetricName = "sharpe_ratio" // MetricTradeCount represents the total number of trades MetricTradeCount MetricName = "trade_count" )
type MetricStyle ¶
type MetricStyle string
type NotifierWithStart ¶
type NotifierWithStart interface { Notifier Start() }
type OptimizableStrategy ¶
type OptimizableStrategy interface { Strategy StrategyEvaluator }
OptimizableStrategy is an interface for strategies that can be optimized
type Optimizer ¶
type Optimizer interface { // Optimize runs the optimization process and returns the best parameter sets Optimize(ctx context.Context, evaluator Evaluator, targetMetric MetricName, maximize bool) ([]*OptimizerResult, error) // SetParameters sets the parameters to be optimized SetParameters(params []Parameter) error // SetMaxIterations sets the maximum number of iterations for the optimization SetMaxIterations(iterations int) // SetParallelism sets the number of parallel evaluations SetParallelism(n int) }
Optimizer defines the interface for optimization algorithms
type OptimizerResult ¶
type OptimizerResult struct { Parameters ParameterSet // The parameter values used Metrics map[string]float64 // Performance metrics Duration time.Duration // How long the evaluation took }
Result represents the outcome of a single optimization run
type Order ¶
type Order struct { ID int64 `db:"id" json:"id" gorm:"primaryKey,autoIncrement"` ExchangeID int64 `db:"exchange_id" json:"exchange_id"` Pair string `db:"pair" json:"pair"` Side SideType `db:"side" json:"side"` Type OrderType `db:"type" json:"type"` Status OrderStatusType `db:"status" json:"status"` Price float64 `db:"price" json:"price"` Quantity float64 `db:"quantity" json:"quantity"` CreatedAt time.Time `db:"created_at" json:"created_at"` UpdatedAt time.Time `db:"updated_at" json:"updated_at"` // OCO (One-Cancels-the-Other) Orders properties Stop *float64 `db:"stop" json:"stop"` GroupID *int64 `db:"group_id" json:"group_id"` // Internal use for visualization and analysis RefPrice float64 `json:"ref_price" gorm:"-"` Profit float64 `json:"profit" gorm:"-"` ProfitValue float64 `json:"profit_value" gorm:"-"` Candle Candle `json:"-" gorm:"-"` }
Order represents a trading order with its properties and status
func (Order) GetCreatedAt ¶
GetCreatedAt returns the order creation time
func (Order) GetExchangeID ¶
GetExchangeID returns the exchange ID
func (Order) GetGroupID ¶
GetGroupID returns the group ID for OCO orders
func (Order) GetProfitValue ¶
GetProfitValue returns the profit value
func (Order) GetQuantity ¶
GetQuantity returns the order quantity
func (Order) GetRefPrice ¶
GetRefPrice returns the reference price
func (Order) GetStatus ¶
func (o Order) GetStatus() OrderStatusType
GetStatus returns the order status
func (Order) GetUpdatedAt ¶
GetUpdatedAt returns the order last update time
type OrderFilter ¶
OrderFilter defines a function type for filtering orders
func WithPair ¶
func WithPair(pair string) OrderFilter
func WithStatus ¶
func WithStatus(status OrderStatusType) OrderFilter
func WithStatusIn ¶
func WithStatusIn(status ...OrderStatusType) OrderFilter
func WithUpdateAtBeforeOrEqual ¶
func WithUpdateAtBeforeOrEqual(time time.Time) OrderFilter
type OrderStatusType ¶
type OrderStatusType string
OrderStatusType represents the status of an order (NEW, FILLED, etc.)
const ( OrderStatusTypeNew OrderStatusType = "NEW" OrderStatusTypePartiallyFilled OrderStatusType = "PARTIALLY_FILLED" OrderStatusTypeFilled OrderStatusType = "FILLED" OrderStatusTypeCanceled OrderStatusType = "CANCELED" OrderStatusTypePendingCancel OrderStatusType = "PENDING_CANCEL" OrderStatusTypeRejected OrderStatusType = "REJECTED" OrderStatusTypeExpired OrderStatusType = "EXPIRED" )
Order status constants
type OrderSubscriber ¶
type OrderSubscriber interface {
OnOrder(Order)
}
type OrderType ¶
type OrderType string
OrderType represents the type of order (LIMIT, MARKET, etc.)
const ( OrderTypeLimit OrderType = "LIMIT" OrderTypeMarket OrderType = "MARKET" OrderTypeLimitMaker OrderType = "LIMIT_MAKER" OrderTypeStopLoss OrderType = "STOP_LOSS" OrderTypeStopLossLimit OrderType = "STOP_LOSS_LIMIT" OrderTypeTakeProfit OrderType = "TAKE_PROFIT" OrderTypeTakeProfitLimit OrderType = "TAKE_PROFIT_LIMIT" )
Order type constants
type Parameter ¶
type Parameter struct { Name string // Name of the parameter Description string // Description of what the parameter does Default any // Default value Min any // Minimum value (for numeric parameters) Max any // Maximum value (for numeric parameters) Step any // Step size (for numeric parameters in grid search) Options []any // Possible values (for categorical parameters) Type ParameterType // Type of the parameter }
Parameter represents a configurable parameter that can be optimized
type ParameterSet ¶
ParameterSet represents a collection of parameters with specific values
type ParameterType ¶
type ParameterType string
ParameterType defines the data type of a parameter
const ( // TypeInt represents integer parameters TypeInt ParameterType = "int" // TypeFloat represents floating-point parameters TypeFloat ParameterType = "float" // TypeBool represents boolean parameters TypeBool ParameterType = "bool" // TypeString represents string parameters TypeString ParameterType = "string" // TypeCategorical represents categorical parameters with predefined options TypeCategorical ParameterType = "categorical" )
type PriorityQueue ¶
PriorityQueue implements a thread-safe min-heap priority queue Lower priority items (as determined by Less) are dequeued first
func NewPriorityQueue ¶
func NewPriorityQueue(data []Item) *PriorityQueue
NewPriorityQueue creates a new priority queue with the provided items The items will be heapified during initialization
func (*PriorityQueue) Len ¶
func (q *PriorityQueue) Len() int
Len returns the number of items in the queue Thread-safe operation
func (*PriorityQueue) Peek ¶
func (q *PriorityQueue) Peek() Item
Peek returns the highest priority item without removing it Thread-safe operation
func (*PriorityQueue) Pop ¶
func (q *PriorityQueue) Pop() Item
Pop removes and returns the highest priority (lowest) item Thread-safe operation
func (*PriorityQueue) PopLock ¶
func (q *PriorityQueue) PopLock() <-chan Item
PopLock returns a channel that will receive the next item when one becomes available
func (*PriorityQueue) Push ¶
func (q *PriorityQueue) Push(item Item)
Push adds an item to the priority queue Thread-safe operation
type Series ¶
type Series[T constraints.Ordered] []T
Series is a time series of ordered values It provides methods for analyzing time series data
func (Series[T]) Cross ¶
Cross detects when this series crosses the reference series in either direction
func (Series[T]) Crossover ¶
Crossover detects when this series crosses above the reference series Returns true when the current value is higher, but the previous value was not
func (Series[T]) Crossunder ¶
Crossunder detects when this series crosses below the reference series Returns true when the current value is lower/equal, but the previous value was higher
func (Series[T]) Last ¶
Last returns the value at a specified position from the end position 0 is the last value, 1 is the second-to-last, etc.
func (Series[T]) LastValues ¶
LastValues returns a slice with the last 'size' values If size exceeds the length, returns the entire series
type Settings ¶
type Settings struct { Pairs []string // List of trading pairs to monitor Telegram TelegramSettings // Telegram notification settings }
Settings represents the main configuration for the application
type Storage ¶
type Storage interface { // CreateOrder stores a new order CreateOrder(ctx context.Context, order *Order) error // UpdateOrder updates an existing order UpdateOrder(ctx context.Context, order *Order) error // Orders retrieves orders based on provided filters Orders(ctx context.Context, filters ...OrderFilter) ([]*Order, error) }
Storage defines the interface for order storage operations
type Strategy ¶
type Strategy interface { // Timeframe is the time interval in which the strategy will be executed. eg: 1h, 1d, 1w Timeframe() string // WarmupPeriod is the necessary time to wait before executing the strategy, to load data for indicators. // This time is measured in the period specified in the `Timeframe` function. WarmupPeriod() int // Indicators will be executed for each new candle, in order to fill indicators before `OnCandle` function is called. Indicators(df *Dataframe) []ChartIndicator // OnCandle will be executed for each new candle, after indicators are filled, here you can do your trading logic. // OnCandle is executed after the candle close. OnCandle(ctx context.Context, df *Dataframe, broker Broker) }
type StrategyEvaluator ¶
type StrategyEvaluator interface { // GetParameters returns the parameters that can be optimized GetParameters() []Parameter // SetParameterValues sets parameter values for evaluation SetParameterValues(params ParameterSet) error }
StrategyEvaluator is an interface for strategies that can be optimized
type TelegramSettings ¶
type TelegramSettings struct { Enabled bool // Whether Telegram notifications are enabled Token string // Telegram bot token Users []int // List of authorized user IDs }
TelegramSettings holds configuration for Telegram integration