core

package
v0.0.0-...-583d1ee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2025 License: GPL-3.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StyleBar       = "bar"
	StyleScatter   = "scatter"
	StyleLine      = "line"
	StyleHistogram = "histogram"
	StyleWaterfall = "waterfall"
)

Variables

View Source
var (
	ErrBaseAssetEmpty  = errors.New("empty base asset")
	ErrQuoteAssetEmpty = errors.New("empty quote asset")
	ErrNegativeValue   = errors.New("negative value")
)
View Source
var (
	ErrOutOfMoneyInAccounts = errors.New("out of money in accounts")
)

Errs

Functions

func FormatFloat

func FormatFloat(value float64, precision int) string

FormatFloat formats a float64 with appropriate precision Returns a string representation of the float

func FormatWithOptimalPrecision

func FormatWithOptimalPrecision(value float64) string

FormatWithOptimalPrecision formats a float using its inherent precision It determines the number of decimal places automatically

func NumDecPlaces

func NumDecPlaces(v float64) int64

NumDecPlaces returns the number of decimal places in a float64 Useful for formatting with appropriate precision

func ParseFloat

func ParseFloat(s string) (float64, error)

ParseFloat parses a string into a float64 Returns the float value and any error encountered

func TrimTrailingZeros

func TrimTrailingZeros(s string) string

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 NewAccount(balances []Balance) (Account, error)

func (Account) GetBalance

func (a Account) GetBalance(assetTick, quoteTick string) (Balance, Balance)

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

func (a Account) GetBalanceMap() map[string]Balance

GetBalanceMap returns a map of asset tickers to balances for efficient lookups

func (Account) GetBalances

func (a Account) GetBalances() []Balance

GetBalances returns all balances in the account

func (Account) GetEquity

func (a Account) GetEquity() float64

GetEquity calculates the total equity in the account Equity is defined as the sum of free and locked amounts across all assets

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

func (a *AssetInfo) ChangeMaxPrice(price float64) error

ChangeMaxPrice updates the maximum price with validation

func (*AssetInfo) ChangeMaxQuantity

func (a *AssetInfo) ChangeMaxQuantity(quantity float64) error

ChangeMaxQuantity updates the maximum quantity with validation

func (*AssetInfo) ChangeMinPrice

func (a *AssetInfo) ChangeMinPrice(price float64) error

ChangeMinPrice updates the minimum price with validation

func (*AssetInfo) ChangeMinQuantity

func (a *AssetInfo) ChangeMinQuantity(quantity float64) error

ChangeMinQuantity updates the minimum quantity with validation

func (*AssetInfo) ChangeStepSize

func (a *AssetInfo) ChangeStepSize(size float64) error

ChangeStepSize updates the step size with validation

func (*AssetInfo) ChangeTickSize

func (a *AssetInfo) ChangeTickSize(size float64) error

ChangeTickSize updates the tick size with validation

func (AssetInfo) GetBaseAsset

func (a AssetInfo) GetBaseAsset() string

GetBaseAsset returns the base asset of the trading pair

func (AssetInfo) GetBaseAssetPrecision

func (a AssetInfo) GetBaseAssetPrecision() int

GetBaseAssetPrecision returns the precision of the base asset

func (AssetInfo) GetMaxPrice

func (a AssetInfo) GetMaxPrice() float64

GetMaxPrice returns the maximum price allowed for the trading pair

func (AssetInfo) GetMaxQuantity

func (a AssetInfo) GetMaxQuantity() float64

GetMaxQuantity returns the maximum quantity allowed for the trading pair

func (AssetInfo) GetMinPrice

func (a AssetInfo) GetMinPrice() float64

GetMinPrice returns the minimum price allowed for the trading pair

func (AssetInfo) GetMinQuantity

func (a AssetInfo) GetMinQuantity() float64

GetMinQuantity returns the minimum quantity allowed for the trading pair

func (AssetInfo) GetQuoteAsset

func (a AssetInfo) GetQuoteAsset() string

GetQuoteAsset returns the quote asset of the trading pair

func (AssetInfo) GetQuotePrecision

func (a AssetInfo) GetQuotePrecision() int

GetQuotePrecision returns the precision of the quote asset

func (AssetInfo) GetStepSize

func (a AssetInfo) GetStepSize() float64

GetStepSize returns the step size for quantity increments

func (AssetInfo) GetTickSize

func (a AssetInfo) GetTickSize() float64

GetTickSize returns the tick size for price increments

type Balance

type Balance struct {
	Asset    string
	Free     float64
	Lock     float64
	Leverage float64
}

Balance represents the available funds for a specific asset

func (Balance) GetAsset

func (b Balance) GetAsset() string

GetAsset returns the asset identifier

func (Balance) GetFree

func (b Balance) GetFree() float64

GetFree returns the amount of the asset that is available for trading

func (Balance) GetLeverage

func (b Balance) GetLeverage() float64

GetLeverage returns the leverage value for the asset

func (Balance) GetLock

func (b Balance) GetLock() float64

GetLock returns the amount of the asset that is locked (unavailable for trading)

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) GetClose

func (c Candle) GetClose() float64

GetClose returns the closing price of the candle

func (Candle) GetHigh

func (c Candle) GetHigh() float64

GetHigh returns the highest price during the candle period

func (Candle) GetLow

func (c Candle) GetLow() float64

GetLow returns the lowest price during the candle period

func (Candle) GetMetadata

func (c Candle) GetMetadata() map[string]float64

GetMetadata returns the additional metadata associated with the candle

func (Candle) GetOpen

func (c Candle) GetOpen() float64

GetOpen returns the opening price of the candle

func (Candle) GetPair

func (c Candle) GetPair() string

GetPair returns the trading pair identifier for the candle

func (Candle) GetTime

func (c Candle) GetTime() time.Time

GetTime returns the timestamp of the candle

func (Candle) GetUpdatedAt

func (c Candle) GetUpdatedAt() time.Time

GetUpdatedAt returns the last update time of the candle

func (Candle) GetVolume

func (c Candle) GetVolume() float64

GetVolume returns the trading volume during the candle period

func (Candle) IsComplete

func (c Candle) IsComplete() bool

IsComplete returns whether the candle period is complete

func (Candle) IsEmpty

func (c Candle) IsEmpty() bool

Empty checks if the candle contains no significant data

func (Candle) Less

func (c Candle) Less(j Item) bool

Less implements the Item interface for comparison in priority queue

func (Candle) ToHeikinAshi

func (c Candle) ToHeikinAshi(ha *HeikinAshi) Candle

ToHeikinAshi transforms a regular candle into a Heikin-Ashi candle

func (Candle) ToSlice

func (c Candle) ToSlice(precision int) []string

ToSlice converts a candle to a string slice for serialization with the specified decimal precision

type CandleSubscriber

type CandleSubscriber interface {
	OnCandle(Candle)
}

type ChartIndicator

type ChartIndicator struct {
	Time      []time.Time
	Metrics   []IndicatorMetric
	Overlay   bool
	GroupName string
	Warmup    int
}

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

func (Dataframe) Sample

func (df Dataframe) Sample(positions int) Dataframe

Sample returns a subset of the dataframe with the last 'positions' elements Used for windowing operations on a dataframe

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 Exchange

type Exchange interface {
	Broker
	Feeder
}

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 HighFrequencyStrategy interface {
	Strategy

	// OnPartialCandle will be executed for each new partial candle, after indicators are filled.
	OnPartialCandle(df *Dataframe, broker Broker)
}

type IndicatorMetric

type IndicatorMetric struct {
	Name   string
	Color  string
	Style  MetricStyle // default: line
	Values Series[float64]
}

type Item

type Item interface {
	Less(Item) bool
}

Item is an interface for objects that can be compared for priority ordering

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 Notifier

type Notifier interface {
	Notify(string)
	OnOrder(order Order)
	OnError(err error)
}

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) GetCandle

func (o Order) GetCandle() Candle

GetCandle returns the associated candle

func (Order) GetCreatedAt

func (o Order) GetCreatedAt() time.Time

GetCreatedAt returns the order creation time

func (Order) GetExchangeID

func (o Order) GetExchangeID() int64

GetExchangeID returns the exchange ID

func (Order) GetGroupID

func (o Order) GetGroupID() *int64

GetGroupID returns the group ID for OCO orders

func (Order) GetID

func (o Order) GetID() int64

GetID returns the order ID

func (Order) GetPair

func (o Order) GetPair() string

GetPair returns the trading pair

func (Order) GetPrice

func (o Order) GetPrice() float64

GetPrice returns the order price

func (Order) GetProfit

func (o Order) GetProfit() float64

GetProfit returns the profit percentage

func (Order) GetProfitValue

func (o Order) GetProfitValue() float64

GetProfitValue returns the profit value

func (Order) GetQuantity

func (o Order) GetQuantity() float64

GetQuantity returns the order quantity

func (Order) GetRefPrice

func (o Order) GetRefPrice() float64

GetRefPrice returns the reference price

func (Order) GetSide

func (o Order) GetSide() SideType

GetSide returns the order side (BUY or SELL)

func (Order) GetStatus

func (o Order) GetStatus() OrderStatusType

GetStatus returns the order status

func (Order) GetStop

func (o Order) GetStop() *float64

GetStop returns the stop price for stop orders

func (Order) GetType

func (o Order) GetType() OrderType

GetType returns the order type

func (Order) GetUpdatedAt

func (o Order) GetUpdatedAt() time.Time

GetUpdatedAt returns the order last update time

func (Order) GetValue

func (o Order) GetValue() float64

GetValue returns the total value of the order (price * quantity)

func (Order) IsActive

func (o Order) IsActive() bool

IsActive returns true if the order is in an active state

func (Order) IsBuy

func (o Order) IsBuy() bool

IsBuy returns true if the order is a buy order

func (Order) IsFilled

func (o Order) IsFilled() bool

IsFilled returns true if the order is completely filled

func (Order) IsSell

func (o Order) IsSell() bool

IsSell returns true if the order is a sell order

func (Order) String

func (o Order) String() string

String returns a human-readable representation of the order

type OrderFilter

type OrderFilter func(order Order) bool

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

type ParameterSet map[string]any

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

type PriorityQueue struct {
	sync.Mutex
	// contains filtered or unexported fields
}

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

func (s Series[T]) Cross(ref Series[T]) bool

Cross detects when this series crosses the reference series in either direction

func (Series[T]) Crossover

func (s Series[T]) Crossover(ref Series[T]) bool

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

func (s Series[T]) Crossunder(ref Series[T]) bool

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

func (s Series[T]) Last(position int) T

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

func (s Series[T]) LastValues(size int) Series[T]

LastValues returns a slice with the last 'size' values If size exceeds the length, returns the entire series

func (Series[T]) Length

func (s Series[T]) Length() int

Length returns the number of values in the series

func (Series[T]) Values

func (s Series[T]) Values() []T

Values returns the underlying slice of values

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 SideType

type SideType string

SideType represents the direction of an order (BUY or SELL)

const (
	SideTypeBuy  SideType = "BUY"
	SideTypeSell SideType = "SELL"
)

Order side constants

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL