Documentation ¶
Index ¶
- Constants
- Variables
- func AdjustFloatQuantityByMaxAmount(quantity fixedpoint.Value, price fixedpoint.Value, maxAmount fixedpoint.Value) fixedpoint.Value
- func AdjustFloatQuantityByMinAmount(quantity, currentPrice, minAmount fixedpoint.Value) fixedpoint.Value
- func AdjustQuantityByMaxAmount(quantity, currentPrice, maxAmount fixedpoint.Value) fixedpoint.Value
- func AdjustQuantityByMinAmount(quantity, currentPrice, minAmount fixedpoint.Value) fixedpoint.Value
- func BacktestFeeModeStrings() []string
- func BatchPlaceOrder(ctx context.Context, exchange types.Exchange, orderCallback OrderCallback, ...) (types.OrderSlice, []int, error)
- func BatchRetryPlaceOrder(ctx context.Context, exchange types.Exchange, errIdx []int, ...) (types.OrderSlice, []int, error)
- func BootstrapBacktestEnvironment(ctx context.Context, environ *Environment) error
- func BootstrapEnvironment(ctx context.Context, environ *Environment, userConfig *Config) error
- func BootstrapEnvironmentLightweight(ctx context.Context, environ *Environment, userConfig *Config) error
- func Build(ctx context.Context, userConfig *Config, targetConfig BuildTargetConfig) (string, error)
- func BuildTarget(ctx context.Context, userConfig *Config, target BuildTargetConfig) (string, error)
- func CalculateBaseQuantity(session *ExchangeSession, market types.Market, ...) (fixedpoint.Value, error)
- func CalculateQuoteQuantity(ctx context.Context, session *ExchangeSession, quoteCurrency string, ...) (fixedpoint.Value, error)
- func ConfigurePersistence(ctx context.Context, environ *Environment, conf *PersistenceConfig) error
- func GetCurrentEnv() string
- func NewContextWithDefaultIsolation(parent context.Context) context.Context
- func NewContextWithIsolation(parent context.Context, isolation *Isolation) context.Context
- func NewLogFormatter(logFormatter LogFormatterType) log.Formatter
- func NewLogFormatterWithEnv(env string) log.Formatter
- func NewPersistenceServiceFacade(conf *PersistenceConfig) (*service.PersistenceServiceFacade, error)
- func NewTodoContextWithExistingIsolation(parent context.Context) context.Context
- func Notify(obj interface{}, args ...interface{})
- func NotifyTo(channel string, obj interface{}, args ...interface{})
- func OnShutdown(ctx context.Context, f ShutdownHandler)
- func RegisterCommand(command, desc string, f interface{}) *interact.Command
- func RegisterModifier(s interface{})
- func RegisterStrategy(key string, s interface{})
- func SendPhoto(buffer *bytes.Buffer)
- func SendPhotoTo(channel string, buffer *bytes.Buffer)
- func SetBackTesting(s *service.BacktestService)
- func SetWrapperBinary()
- func Shutdown(shutdownCtx context.Context)
- func Sync(ctx context.Context, obj interface{})
- type AccountValueCalculator
- func (c *AccountValueCalculator) AvailableQuote(ctx context.Context) (fixedpoint.Value, error)
- func (c *AccountValueCalculator) DebtValue(ctx context.Context) (fixedpoint.Value, error)
- func (c *AccountValueCalculator) MarginLevel(ctx context.Context) (fixedpoint.Value, error)
- func (c *AccountValueCalculator) MarketValue(ctx context.Context) (fixedpoint.Value, error)
- func (c *AccountValueCalculator) NetValue(ctx context.Context) (fixedpoint.Value, error)
- func (c *AccountValueCalculator) UpdatePrices(ctx context.Context) error
- type ActiveOrderBook
- func (b *ActiveOrderBook) Add(orders ...types.Order)
- func (b *ActiveOrderBook) Backup() []types.SubmitOrder
- func (b *ActiveOrderBook) BindStream(stream types.Stream)
- func (b *ActiveOrderBook) EmitCanceled(o types.Order)
- func (b *ActiveOrderBook) EmitFilled(o types.Order)
- func (b *ActiveOrderBook) EmitNew(o types.Order)
- func (b *ActiveOrderBook) Exists(order types.Order) bool
- func (b *ActiveOrderBook) FastCancel(ctx context.Context, ex types.Exchange, orders ...types.Order) error
- func (b *ActiveOrderBook) Get(orderID uint64) (types.Order, bool)
- func (b *ActiveOrderBook) GracefulCancel(ctx context.Context, ex types.Exchange, specifiedOrders ...types.Order) error
- func (b *ActiveOrderBook) Lookup(f func(o types.Order) bool) *types.Order
- func (b *ActiveOrderBook) MarshalJSON() ([]byte, error)
- func (b *ActiveOrderBook) NumOfOrders() int
- func (b *ActiveOrderBook) OnCanceled(cb func(o types.Order))
- func (b *ActiveOrderBook) OnFilled(cb func(o types.Order))
- func (b *ActiveOrderBook) OnNew(cb func(o types.Order))
- func (b *ActiveOrderBook) Orders() types.OrderSlice
- func (b *ActiveOrderBook) Print()
- func (b *ActiveOrderBook) Remove(order types.Order) bool
- func (b *ActiveOrderBook) SetCancelOrderWaitTime(duration time.Duration)
- func (b *ActiveOrderBook) Update(order types.Order)
- type AverageCostPnLReporter
- type BA
- type Backtest
- type BacktestAccount
- type BacktestAccountBalanceMap
- type BacktestFeeMode
- func (i BacktestFeeMode) IsABacktestFeeMode() bool
- func (i BacktestFeeMode) MarshalJSON() ([]byte, error)
- func (i BacktestFeeMode) MarshalYAML() (interface{}, error)
- func (i BacktestFeeMode) String() string
- func (i *BacktestFeeMode) UnmarshalJSON(data []byte) error
- func (i *BacktestFeeMode) UnmarshalYAML(unmarshal func(interface{}) error) error
- type BaseOrderExecutor
- type BasicRiskController
- type BuildConfig
- type BuildTargetConfig
- type Config
- type CoreInteraction
- type CrossExchangeSessionSubscriber
- type CrossExchangeStrategy
- type CumulatedVolumeTakeProfit
- type DatabaseConfig
- type EmergencyStopper
- type Environment
- func (environ *Environment) AddExchange(name string, exchange types.Exchange) (session *ExchangeSession)
- func (environ *Environment) AddExchangeSession(name string, session *ExchangeSession) *ExchangeSession
- func (environ *Environment) AddExchangesByViperKeys() error
- func (environ *Environment) AddExchangesFromSessionConfig(sessions map[string]*ExchangeSession) error
- func (environ *Environment) BindSync(config *SyncConfig)
- func (environ *Environment) ConfigureDatabase(ctx context.Context, config *Config) error
- func (environ *Environment) ConfigureDatabaseDriver(ctx context.Context, driver string, dsn string, extraPkgNames ...string) error
- func (environ *Environment) ConfigureExchangeSessions(userConfig *Config) error
- func (environ *Environment) ConfigureNotification(config *NotificationConfig) error
- func (environ *Environment) ConfigureNotificationSystem(ctx context.Context, userConfig *Config) error
- func (environ *Environment) ConfigureService(ctx context.Context, srvConfig *ServiceConfig) error
- func (environ *Environment) Connect(ctx context.Context) error
- func (environ *Environment) Init(ctx context.Context) (err error)
- func (environ *Environment) IsBackTesting() bool
- func (environ *Environment) IsSyncing() (status SyncStatus)
- func (environ *Environment) Logger() log.FieldLogger
- func (environ *Environment) RecordAsset(t time.Time, session *ExchangeSession, assets types.AssetMap)
- func (environ *Environment) RecordPosition(position *types.Position, trade types.Trade, profit *types.Profit)
- func (environ *Environment) RecordProfit(profit types.Profit)
- func (environ *Environment) SelectSessions(names ...string) map[string]*ExchangeSession
- func (environ *Environment) Session(name string) (*ExchangeSession, bool)
- func (environ *Environment) Sessions() map[string]*ExchangeSession
- func (environ *Environment) SetLogging(config *LoggingConfig)
- func (environ *Environment) SetStartTime(t time.Time) *Environment
- func (environ *Environment) SetSyncStartTime(t time.Time) *Environment
- func (environ *Environment) Start(ctx context.Context) (err error)
- func (environ *Environment) StartTime() time.Time
- func (environ *Environment) Sync(ctx context.Context, userConfig ...*Config) error
- func (environ *Environment) SyncSession(ctx context.Context, session *ExchangeSession, defaultSymbols ...string) error
- type EnvironmentConfig
- type ExchangeOrderExecutionRouter
- type ExchangeOrderExecutor
- func (e *ExchangeOrderExecutor) CancelOrders(ctx context.Context, orders ...types.Order) error
- func (e *ExchangeOrderExecutor) EmitOrderUpdate(order types.Order)
- func (e *ExchangeOrderExecutor) EmitTradeUpdate(trade types.Trade)
- func (e *ExchangeOrderExecutor) OnOrderUpdate(cb func(order types.Order))
- func (e *ExchangeOrderExecutor) OnTradeUpdate(cb func(trade types.Trade))
- func (e *ExchangeOrderExecutor) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (types.OrderSlice, error)
- type ExchangeSession
- func (session *ExchangeSession) AllLastPrices() map[string]fixedpoint.Value
- func (session *ExchangeSession) FindPossibleAssetSymbols() (symbols []string, err error)
- func (session *ExchangeSession) FormatOrder(order types.SubmitOrder) (types.SubmitOrder, error)
- func (session *ExchangeSession) FormatOrders(orders []types.SubmitOrder) (formattedOrders []types.SubmitOrder, err error)
- func (session *ExchangeSession) GetAccount() (a *types.Account)
- func (session *ExchangeSession) Indicators(symbol string) *IndicatorSet
- func (session *ExchangeSession) Init(ctx context.Context, environ *Environment) error
- func (session *ExchangeSession) InitExchange(name string, ex types.Exchange) error
- func (session *ExchangeSession) InitSymbols(ctx context.Context, environ *Environment) error
- func (session *ExchangeSession) LastPrice(symbol string) (price fixedpoint.Value, ok bool)
- func (session *ExchangeSession) LastPrices() map[string]fixedpoint.Value
- func (session *ExchangeSession) MarginType() types.MarginType
- func (session *ExchangeSession) Market(symbol string) (market types.Market, ok bool)
- func (session *ExchangeSession) MarketDataStore(symbol string) (s *MarketDataStore, ok bool)
- func (session *ExchangeSession) Markets() types.MarketMap
- func (session *ExchangeSession) OrderBook(symbol string) (s *types.StreamOrderBook, ok bool)
- func (session *ExchangeSession) OrderStore(symbol string) (store *core.OrderStore, ok bool)
- func (session *ExchangeSession) OrderStores() map[string]*core.OrderStore
- func (session *ExchangeSession) Position(symbol string) (pos *types.Position, ok bool)
- func (session *ExchangeSession) Positions() map[string]*types.Position
- func (session *ExchangeSession) SerialMarketDataStore(ctx context.Context, symbol string, intervals []types.Interval, ...) (store *SerialMarketDataStore, ok bool)
- func (session *ExchangeSession) SetMarkets(markets types.MarketMap)
- func (session *ExchangeSession) SlackAttachment() slack.Attachment
- func (session *ExchangeSession) StandardIndicatorSet(symbol string) *StandardIndicatorSet
- func (session *ExchangeSession) StartPrice(symbol string) (price fixedpoint.Value, ok bool)
- func (session *ExchangeSession) Subscribe(channel types.Channel, symbol string, options types.SubscribeOptions) *ExchangeSession
- func (session *ExchangeSession) UpdateAccount(ctx context.Context) (*types.Account, error)
- func (session *ExchangeSession) UpdatePrices(ctx context.Context, currencies []string, fiat string) (err error)
- type ExchangeSessionSubscriber
- type ExchangeStrategyMount
- type ExitMethod
- type ExitMethodSet
- type ExponentialScale
- type FastOrderExecutor
- type GeneralOrderExecutor
- func (e *GeneralOrderExecutor) Bind()
- func (e *GeneralOrderExecutor) BindEnvironment(environ *Environment)
- func (e *GeneralOrderExecutor) BindProfitStats(profitStats *types.ProfitStats)
- func (e *GeneralOrderExecutor) BindTradeStats(tradeStats *types.TradeStats)
- func (e *GeneralOrderExecutor) CancelOrders(ctx context.Context, orders ...types.Order) error
- func (e *GeneralOrderExecutor) ClosePosition(ctx context.Context, percentage fixedpoint.Value, tags ...string) error
- func (e *GeneralOrderExecutor) CurrentPosition() *types.Position
- func (e *GeneralOrderExecutor) DisableNotify()
- func (e *GeneralOrderExecutor) GracefulCancel(ctx context.Context, orders ...types.Order) error
- func (e *GeneralOrderExecutor) GracefulCancelActiveOrderBook(ctx context.Context, activeOrders *ActiveOrderBook) error
- func (e *GeneralOrderExecutor) NewOrderFromOpenPosition(ctx context.Context, options *OpenPositionOptions) (*types.SubmitOrder, error)
- func (e *GeneralOrderExecutor) OpenPosition(ctx context.Context, options OpenPositionOptions) (types.OrderSlice, error)
- func (e *GeneralOrderExecutor) Position() *types.Position
- func (e *GeneralOrderExecutor) ResetPosition() error
- func (e *GeneralOrderExecutor) Session() *ExchangeSession
- func (e *GeneralOrderExecutor) SetLogger(logger log.FieldLogger)
- func (e *GeneralOrderExecutor) SetMaxRetries(maxRetries uint)
- func (e *GeneralOrderExecutor) SubmitOrders(ctx context.Context, submitOrders ...types.SubmitOrder) (types.OrderSlice, error)
- func (e *GeneralOrderExecutor) TradeCollector() *core.TradeCollector
- type GoogleSpreadSheetServiceConfig
- type GracefulShutdown
- type HigherHighLowerLowStop
- type IndicatorSet
- func (i *IndicatorSet) ADX(interval types.Interval, window int) *indicatorv2.ADXStream
- func (i *IndicatorSet) ATR(interval types.Interval, window int) *indicatorv2.ATRStream
- func (i *IndicatorSet) ATRP(interval types.Interval, window int) *indicatorv2.ATRPStream
- func (i *IndicatorSet) BOLL(iw types.IntervalWindow, k float64) *indicatorv2.BOLLStream
- func (i *IndicatorSet) CLOSE(interval types.Interval) *indicatorv2.PriceStream
- func (i *IndicatorSet) EMA(iw types.IntervalWindow) *indicatorv2.EWMAStream
- func (i *IndicatorSet) EWMA(iw types.IntervalWindow) *indicatorv2.EWMAStream
- func (i *IndicatorSet) HIGH(interval types.Interval) *indicatorv2.PriceStream
- func (i *IndicatorSet) KLines(interval types.Interval) *indicatorv2.KLineStream
- func (i *IndicatorSet) Keltner(iw types.IntervalWindow, atrLength int) *indicatorv2.KeltnerStream
- func (i *IndicatorSet) LOW(interval types.Interval) *indicatorv2.PriceStream
- func (i *IndicatorSet) MACD(interval types.Interval, shortWindow, longWindow, signalWindow int) *indicatorv2.MACDStream
- func (i *IndicatorSet) OPEN(interval types.Interval) *indicatorv2.PriceStream
- func (i *IndicatorSet) RSI(iw types.IntervalWindow) *indicatorv2.RSIStream
- func (i *IndicatorSet) STOCH(iw types.IntervalWindow, dPeriod int) *indicatorv2.StochStream
- func (i *IndicatorSet) VOLUME(interval types.Interval) *indicatorv2.PriceStream
- type Isolation
- type LayerScale
- type LinearScale
- type LogFormatterType
- type LogarithmicScale
- type Logger
- type Logging
- type LoggingConfig
- type LowerShadowTakeProfit
- type MACDConfig
- type MarketDataStore
- func (store *MarketDataStore) AddKLine(k types.KLine)
- func (store *MarketDataStore) BindStream(stream types.Stream)
- func (store *MarketDataStore) EmitKLineClosed(k types.KLine)
- func (store *MarketDataStore) EmitKLineWindowUpdate(interval types.Interval, klines types.KLineWindow)
- func (store *MarketDataStore) KLinesOfInterval(interval types.Interval) (kLines *types.KLineWindow, ok bool)
- func (store *MarketDataStore) OnKLineClosed(cb func(k types.KLine))
- func (store *MarketDataStore) OnKLineWindowUpdate(cb func(interval types.Interval, klines types.KLineWindow))
- func (store *MarketDataStore) SetKLineWindows(windows map[types.Interval]*types.KLineWindow)
- type MovingAverageSettings
- type Notifiability
- func (m *Notifiability) AddNotifier(notifier Notifier)
- func (m *Notifiability) Notify(obj interface{}, args ...interface{})
- func (m *Notifiability) NotifyTo(channel string, obj interface{}, args ...interface{})
- func (m *Notifiability) RouteObject(obj interface{}) (channel string, ok bool)
- func (m *Notifiability) RouteSession(session string) (channel string, ok bool)
- func (m *Notifiability) RouteSymbol(symbol string) (channel string, ok bool)
- func (m *Notifiability) SendPhoto(buffer *bytes.Buffer)
- func (m *Notifiability) SendPhotoTo(channel string, buffer *bytes.Buffer)
- type NotificationConfig
- type NotificationSwitches
- type Notifier
- type NullNotifier
- type ObjectChannelHandler
- type ObjectChannelRouter
- type OpenPositionOptions
- type OrderCallback
- type OrderExecutionRouter
- type OrderExecutor
- type OrderExecutorExtended
- type PatternChannelRouter
- type PercentageScale
- type PersistenceConfig
- type PnLReporter
- type PnLReporterConfig
- type PnLReporterManager
- type PositionCloser
- type PositionReader
- type PositionResetter
- type PriceVolumeScale
- type ProtectiveStopLoss
- type QuadraticScale
- type QuantityOrAmount
- type Quota
- type QuotaTransaction
- type RiskControlOrderExecutor
- type RiskControls
- type RoiStopLoss
- type RoiTakeProfit
- type Scale
- type SerialMarketDataStore
- type ServiceConfig
- type Session
- type SessionBasedRiskControl
- type ShutdownHandler
- type SilentLogger
- type SimpleInteraction
- type SimpleOrderExecutor
- type SingleExchangeStrategy
- type SlackNotification
- type SlackNotificationRouting
- type SlideRule
- type SourceFunc
- type SourceSelector
- type StandardIndicatorSet
- func (s *StandardIndicatorSet) ATR(iw types.IntervalWindow) *indicator.ATR
- func (s *StandardIndicatorSet) ATRP(iw types.IntervalWindow) *indicator.ATRP
- func (s *StandardIndicatorSet) BOLL(iw types.IntervalWindow, bandWidth float64) *indicator.BOLL
- func (s *StandardIndicatorSet) CCI(iw types.IntervalWindow) *indicator.CCI
- func (s *StandardIndicatorSet) EMV(iw types.IntervalWindow) *indicator.EMV
- func (s *StandardIndicatorSet) EWMA(iw types.IntervalWindow) *indicator.EWMA
- func (s *StandardIndicatorSet) GHFilter(iw types.IntervalWindow) *indicator.GHFilter
- func (s *StandardIndicatorSet) HULL(iw types.IntervalWindow) *indicator.HULL
- func (s *StandardIndicatorSet) KalmanFilter(iw types.IntervalWindow) *indicator.KalmanFilter
- func (s *StandardIndicatorSet) MACD(iw types.IntervalWindow, shortPeriod, longPeriod int) *indicator.MACDLegacy
- func (s *StandardIndicatorSet) PivotHigh(iw types.IntervalWindow) *indicator.PivotHigh
- func (s *StandardIndicatorSet) PivotLow(iw types.IntervalWindow) *indicator.PivotLow
- func (s *StandardIndicatorSet) RSI(iw types.IntervalWindow) *indicator.RSI
- func (s *StandardIndicatorSet) SMA(iw types.IntervalWindow) *indicator.SMA
- func (s *StandardIndicatorSet) STOCH(iw types.IntervalWindow) *indicator.STOCH
- func (s *StandardIndicatorSet) VWMA(iw types.IntervalWindow) *indicator.VWMA
- type Stash
- type StopEMA
- type StrategyController
- func (s *StrategyController) EmergencyStop() error
- func (s *StrategyController) EmitEmergencyStop()
- func (s *StrategyController) EmitResume()
- func (s *StrategyController) EmitSuspend()
- func (s *StrategyController) GetStatus() types.StrategyStatus
- func (s *StrategyController) OnEmergencyStop(cb func())
- func (s *StrategyController) OnResume(cb func())
- func (s *StrategyController) OnSuspend(cb func())
- func (s *StrategyController) Resume() error
- func (s *StrategyController) Suspend() error
- type StrategyControllerEventHub
- type StrategyDefaulter
- type StrategyID
- type StrategyInitializer
- type StrategyShutdown
- type StrategyStatusReader
- type StrategyToggler
- type StrategyValidator
- type SupportTakeProfit
- type SymbolBasedRiskController
- type SyncConfig
- type SyncStatus
- type SyncSymbol
- type TelegramNotification
- type TradeReporter
- type Trader
- func (trader *Trader) AttachCrossExchangeStrategy(strategy CrossExchangeStrategy) *Trader
- func (trader *Trader) AttachStrategyOn(session string, strategies ...SingleExchangeStrategy) error
- func (trader *Trader) Configure(userConfig *Config) error
- func (trader *Trader) DisableLogging()
- func (trader *Trader) EnableLogging()
- func (trader *Trader) Initialize(ctx context.Context) error
- func (trader *Trader) IterateStrategies(f func(st StrategyID) error) error
- func (trader *Trader) LoadState(ctx context.Context) error
- func (trader *Trader) Run(ctx context.Context) error
- func (trader *Trader) RunAllSingleExchangeStrategy(ctx context.Context) error
- func (trader *Trader) RunSingleExchangeStrategy(ctx context.Context, strategy SingleExchangeStrategy, session *ExchangeSession, ...) error
- func (trader *Trader) SaveState(ctx context.Context) error
- func (trader *Trader) SetRiskControls(riskControls *RiskControls)
- func (trader *Trader) Shutdown(ctx context.Context)
- type TrailingStop2
- type TrendEMA
Constants ¶
const CapacityOfKLineWindowLimit = 5_000
const DefaultCancelOrderWaitTime = 20 * time.Millisecond
const IsolationContextKey = "bbgo"
const MaxNumOfKLines = 5_000
const MaxNumOfKLinesTruncate = 100
const TemplateOrderReport = `:handshake: {{ .Symbol }} {{ .Side }} Order Update @ {{ .Price }}`
Variables ¶
var ( ErrQuoteBalanceLevelTooLow = errors.New("quote balance level is too low") ErrInsufficientQuoteBalance = errors.New("insufficient quote balance") ErrAssetBalanceLevelTooLow = errors.New("asset balance level too low") ErrInsufficientAssetBalance = errors.New("insufficient asset balance") ErrAssetBalanceLevelTooHigh = errors.New("asset balance level too high") )
var BackTestService *service.BacktestService
var DefaultBacktestAccount = BacktestAccount{ MakerFeeRate: fixedpoint.MustNewFromString("0.050%"), TakerFeeRate: fixedpoint.MustNewFromString("0.075%"), Balances: BacktestAccountBalanceMap{ "USDT": fixedpoint.NewFromFloat(10000), }, }
var DefaultFeeRate = fixedpoint.NewFromFloat(0.075 * 0.01)
DefaultFeeRate set the fee rate for most cases BINANCE uses 0.1% for both maker and taker
for BNB holders, it's 0.075% for both maker and taker
MAX uses 0.050% for maker and 0.15% for taker
var DefaultSubmitOrderRetryTimeout = 5 * time.Minute
var ErrEmptyMarketInfo = errors.New("market info should not be empty, 0 markets loaded")
var ErrExceededSubmitOrderRetryLimit = errors.New("exceeded submit order retry limit")
var ErrPositionAlreadyClosing = errors.New("position is already in closing process")
var ErrSessionAlreadyInitialized = errors.New("session is already initialized")
var IsBackTesting = false
IsBackTesting is a global variable that indicates the current environment is back-test or not.
var IsWrapperBinary = false
var KLinePreloadLimit int64 = 1000
var LoadedCrossExchangeStrategies = make(map[string]CrossExchangeStrategy)
var LoadedExchangeStrategies = make(map[string]SingleExchangeStrategy)
var LocalTimeZone *time.Location
var Notification = &Notifiability{ SymbolChannelRouter: NewPatternChannelRouter(nil), SessionChannelRouter: NewPatternChannelRouter(nil), ObjectChannelRouter: NewObjectChannelRouter(), }
Functions ¶
func AdjustFloatQuantityByMaxAmount ¶ added in v1.17.0
func AdjustFloatQuantityByMaxAmount(quantity fixedpoint.Value, price fixedpoint.Value, maxAmount fixedpoint.Value) fixedpoint.Value
func AdjustFloatQuantityByMinAmount ¶ added in v1.17.0
func AdjustFloatQuantityByMinAmount(quantity, currentPrice, minAmount fixedpoint.Value) fixedpoint.Value
AdjustFloatQuantityByMinAmount adjusts the quantity to make the amount greater than the given minAmount
func AdjustQuantityByMaxAmount ¶ added in v1.16.0
func AdjustQuantityByMaxAmount(quantity, currentPrice, maxAmount fixedpoint.Value) fixedpoint.Value
AdjustQuantityByMaxAmount adjusts the quantity to make the amount less than the given maxAmount
func AdjustQuantityByMinAmount ¶ added in v1.16.0
func AdjustQuantityByMinAmount(quantity, currentPrice, minAmount fixedpoint.Value) fixedpoint.Value
AdjustQuantityByMinAmount adjusts the quantity to make the amount greater than the given minAmount
func BacktestFeeModeStrings ¶ added in v1.40.0
func BacktestFeeModeStrings() []string
BacktestFeeModeStrings returns a slice of all String values of the enum
func BatchPlaceOrder ¶ added in v1.40.3
func BatchPlaceOrder(ctx context.Context, exchange types.Exchange, orderCallback OrderCallback, submitOrders ...types.SubmitOrder) (types.OrderSlice, []int, error)
BatchPlaceOrder
func BatchRetryPlaceOrder ¶ added in v1.40.3
func BatchRetryPlaceOrder(ctx context.Context, exchange types.Exchange, errIdx []int, orderCallback OrderCallback, logger log.FieldLogger, submitOrders ...types.SubmitOrder) (types.OrderSlice, []int, error)
BatchRetryPlaceOrder places the orders and retries the failed orders
func BootstrapBacktestEnvironment ¶ added in v1.40.2
func BootstrapBacktestEnvironment(ctx context.Context, environ *Environment) error
func BootstrapEnvironment ¶ added in v1.40.2
func BootstrapEnvironment(ctx context.Context, environ *Environment, userConfig *Config) error
func BootstrapEnvironmentLightweight ¶ added in v1.41.0
func BootstrapEnvironmentLightweight(ctx context.Context, environ *Environment, userConfig *Config) error
BootstrapEnvironmentLightweight bootstrap the environment in lightweight mode - no database configuration - no notification
func Build ¶ added in v1.9.0
Build builds the bbgo wrapper binary with the given build target config
func BuildTarget ¶ added in v1.9.0
BuildTarget builds the one of the targets.
func CalculateBaseQuantity ¶ added in v1.40.3
func CalculateBaseQuantity(session *ExchangeSession, market types.Market, price, quantity, leverage fixedpoint.Value) (fixedpoint.Value, error)
func CalculateQuoteQuantity ¶ added in v1.40.3
func CalculateQuoteQuantity(ctx context.Context, session *ExchangeSession, quoteCurrency string, leverage fixedpoint.Value) (fixedpoint.Value, error)
func ConfigurePersistence ¶ added in v1.42.0
func ConfigurePersistence(ctx context.Context, environ *Environment, conf *PersistenceConfig) error
func GetCurrentEnv ¶ added in v1.55.0
func GetCurrentEnv() string
func NewContextWithDefaultIsolation ¶ added in v1.42.0
NewContextWithDefaultIsolation creates a new context from the parent context with a default isolation
func NewContextWithIsolation ¶ added in v1.42.0
NewContextWithIsolation creates a new context from the parent context with a custom isolation
func NewLogFormatter ¶ added in v1.55.0
func NewLogFormatter(logFormatter LogFormatterType) log.Formatter
func NewLogFormatterWithEnv ¶ added in v1.55.0
func NewPersistenceServiceFacade ¶ added in v1.42.0
func NewPersistenceServiceFacade(conf *PersistenceConfig) (*service.PersistenceServiceFacade, error)
func NewTodoContextWithExistingIsolation ¶ added in v1.42.0
NewTodoContextWithExistingIsolation creates a new context object with the existing isolation of the parent context.
func NotifyTo ¶ added in v1.36.0
func NotifyTo(channel string, obj interface{}, args ...interface{})
func OnShutdown ¶ added in v1.36.0
func OnShutdown(ctx context.Context, f ShutdownHandler)
OnShutdown helps you register your shutdown handler the first context object is where you want to register your shutdown handler, where the context has the isolated storage. in your handler, you will get another context for the timeout context.
func RegisterCommand ¶ added in v1.39.0
func RegisterModifier ¶ added in v1.41.0
func RegisterModifier(s interface{})
func RegisterStrategy ¶
func RegisterStrategy(key string, s interface{})
func SendPhotoTo ¶ added in v1.39.0
func SetBackTesting ¶ added in v1.36.0
func SetBackTesting(s *service.BacktestService)
func SetWrapperBinary ¶ added in v1.9.0
func SetWrapperBinary()
Types ¶
type AccountValueCalculator ¶ added in v1.40.3
type AccountValueCalculator struct {
// contains filtered or unexported fields
}
func NewAccountValueCalculator ¶ added in v1.40.3
func NewAccountValueCalculator(session *ExchangeSession, quoteCurrency string) *AccountValueCalculator
func (*AccountValueCalculator) AvailableQuote ¶ added in v1.40.3
func (c *AccountValueCalculator) AvailableQuote(ctx context.Context) (fixedpoint.Value, error)
func (*AccountValueCalculator) DebtValue ¶ added in v1.40.3
func (c *AccountValueCalculator) DebtValue(ctx context.Context) (fixedpoint.Value, error)
func (*AccountValueCalculator) MarginLevel ¶ added in v1.40.3
func (c *AccountValueCalculator) MarginLevel(ctx context.Context) (fixedpoint.Value, error)
MarginLevel calculates the margin level from the asset market value and the debt value See https://www.binance.com/en/support/faq/360030493931
func (*AccountValueCalculator) MarketValue ¶ added in v1.40.3
func (c *AccountValueCalculator) MarketValue(ctx context.Context) (fixedpoint.Value, error)
func (*AccountValueCalculator) NetValue ¶ added in v1.40.3
func (c *AccountValueCalculator) NetValue(ctx context.Context) (fixedpoint.Value, error)
func (*AccountValueCalculator) UpdatePrices ¶ added in v1.40.3
func (c *AccountValueCalculator) UpdatePrices(ctx context.Context) error
type ActiveOrderBook ¶ added in v1.33.0
type ActiveOrderBook struct { Symbol string // sig is the order update signal // this signal will be emitted when a new order is added or removed. C sigchan.Chan // contains filtered or unexported fields }
ActiveOrderBook manages the local active order books.
func NewActiveOrderBook ¶ added in v1.33.0
func NewActiveOrderBook(symbol string) *ActiveOrderBook
func (*ActiveOrderBook) Add ¶ added in v1.33.0
func (b *ActiveOrderBook) Add(orders ...types.Order)
func (*ActiveOrderBook) Backup ¶ added in v1.33.0
func (b *ActiveOrderBook) Backup() []types.SubmitOrder
func (*ActiveOrderBook) BindStream ¶ added in v1.33.0
func (b *ActiveOrderBook) BindStream(stream types.Stream)
func (*ActiveOrderBook) EmitCanceled ¶ added in v1.43.0
func (b *ActiveOrderBook) EmitCanceled(o types.Order)
func (*ActiveOrderBook) EmitFilled ¶ added in v1.33.0
func (b *ActiveOrderBook) EmitFilled(o types.Order)
func (*ActiveOrderBook) EmitNew ¶ added in v1.44.0
func (b *ActiveOrderBook) EmitNew(o types.Order)
func (*ActiveOrderBook) Exists ¶ added in v1.33.0
func (b *ActiveOrderBook) Exists(order types.Order) bool
func (*ActiveOrderBook) FastCancel ¶ added in v1.43.0
func (b *ActiveOrderBook) FastCancel(ctx context.Context, ex types.Exchange, orders ...types.Order) error
FastCancel cancels the orders without verification It calls the exchange cancel order api and then remove the orders from the active orderbook directly.
func (*ActiveOrderBook) Get ¶ added in v1.44.0
func (b *ActiveOrderBook) Get(orderID uint64) (types.Order, bool)
func (*ActiveOrderBook) GracefulCancel ¶ added in v1.33.0
func (b *ActiveOrderBook) GracefulCancel(ctx context.Context, ex types.Exchange, specifiedOrders ...types.Order) error
GracefulCancel cancels the active orders gracefully
func (*ActiveOrderBook) MarshalJSON ¶ added in v1.33.0
func (b *ActiveOrderBook) MarshalJSON() ([]byte, error)
func (*ActiveOrderBook) NumOfOrders ¶ added in v1.33.0
func (b *ActiveOrderBook) NumOfOrders() int
func (*ActiveOrderBook) OnCanceled ¶ added in v1.43.0
func (b *ActiveOrderBook) OnCanceled(cb func(o types.Order))
func (*ActiveOrderBook) OnFilled ¶ added in v1.33.0
func (b *ActiveOrderBook) OnFilled(cb func(o types.Order))
func (*ActiveOrderBook) OnNew ¶ added in v1.44.0
func (b *ActiveOrderBook) OnNew(cb func(o types.Order))
func (*ActiveOrderBook) Orders ¶ added in v1.33.0
func (b *ActiveOrderBook) Orders() types.OrderSlice
func (*ActiveOrderBook) Print ¶ added in v1.33.0
func (b *ActiveOrderBook) Print()
func (*ActiveOrderBook) Remove ¶ added in v1.33.0
func (b *ActiveOrderBook) Remove(order types.Order) bool
func (*ActiveOrderBook) SetCancelOrderWaitTime ¶ added in v1.55.0
func (b *ActiveOrderBook) SetCancelOrderWaitTime(duration time.Duration)
func (*ActiveOrderBook) Update ¶ added in v1.33.0
func (b *ActiveOrderBook) Update(order types.Order)
Update updates the order by the order status and emit the related events. When order is filled, the order will be removed from the internal order storage. When order is New or PartiallyFilled, the internal order will be updated according to the latest order update. When the order is cancelled, it will be removed from the internal order storage.
type AverageCostPnLReporter ¶
type AverageCostPnLReporter struct { Sessions []string Symbols []string // contains filtered or unexported fields }
func (*AverageCostPnLReporter) Of ¶
func (reporter *AverageCostPnLReporter) Of(sessions ...string) *AverageCostPnLReporter
func (*AverageCostPnLReporter) Run ¶
func (reporter *AverageCostPnLReporter) Run()
func (*AverageCostPnLReporter) When ¶
func (reporter *AverageCostPnLReporter) When(specs ...string) *AverageCostPnLReporter
type BA ¶ added in v1.30.3
type BA BacktestAccount
type Backtest ¶
type Backtest struct { StartTime types.LooseFormatTime `json:"startTime,omitempty" yaml:"startTime,omitempty"` EndTime *types.LooseFormatTime `json:"endTime,omitempty" yaml:"endTime,omitempty"` // RecordTrades is an option, if set to true, back-testing should record the trades into database RecordTrades bool `json:"recordTrades,omitempty" yaml:"recordTrades,omitempty"` // Deprecated: // Account is deprecated, use Accounts instead Account map[string]BacktestAccount `json:"account" yaml:"account"` FeeMode BacktestFeeMode `json:"feeMode" yaml:"feeMode"` Accounts map[string]BacktestAccount `json:"accounts" yaml:"accounts"` Symbols []string `json:"symbols" yaml:"symbols"` Sessions []string `json:"sessions" yaml:"sessions"` // sync 1 second interval KLines SyncSecKLines bool `json:"syncSecKLines,omitempty" yaml:"syncSecKLines,omitempty"` }
func (*Backtest) GetAccount ¶ added in v1.33.0
func (b *Backtest) GetAccount(n string) BacktestAccount
type BacktestAccount ¶
type BacktestAccount struct { MakerFeeRate fixedpoint.Value `json:"makerFeeRate,omitempty" yaml:"makerFeeRate,omitempty"` TakerFeeRate fixedpoint.Value `json:"takerFeeRate,omitempty" yaml:"takerFeeRate,omitempty"` Balances BacktestAccountBalanceMap `json:"balances" yaml:"balances"` }
func (*BacktestAccount) UnmarshalJSON ¶ added in v1.30.3
func (b *BacktestAccount) UnmarshalJSON(input []byte) error
func (*BacktestAccount) UnmarshalYAML ¶ added in v1.30.3
func (b *BacktestAccount) UnmarshalYAML(value *yaml.Node) error
type BacktestAccountBalanceMap ¶
type BacktestAccountBalanceMap map[string]fixedpoint.Value
func (BacktestAccountBalanceMap) BalanceMap ¶
func (m BacktestAccountBalanceMap) BalanceMap() types.BalanceMap
type BacktestFeeMode ¶ added in v1.40.0
type BacktestFeeMode int
const ( // BackTestFeeModeQuoteFee is designed for clean position but which also counts the fee in the quote balance. // buy order = quote currency fee // sell order = quote currency fee BacktestFeeModeQuote BacktestFeeMode = iota // quote // BackTestFeeModeNativeFee is the default crypto exchange fee mode. // buy order = base currency fee // sell order = quote currency fee BacktestFeeModeNative // BackTestFeeMode = "native" // BackTestFeeModeFeeToken is the mode which calculates fee from the outside of the balances. // the fee will not be included in the balances nor the profit. BacktestFeeModeToken // BackTestFeeMode = "token" )
func BacktestFeeModeString ¶ added in v1.40.0
func BacktestFeeModeString(s string) (BacktestFeeMode, error)
BacktestFeeModeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func BacktestFeeModeValues ¶ added in v1.40.0
func BacktestFeeModeValues() []BacktestFeeMode
BacktestFeeModeValues returns all values of the enum
func (BacktestFeeMode) IsABacktestFeeMode ¶ added in v1.40.0
func (i BacktestFeeMode) IsABacktestFeeMode() bool
IsABacktestFeeMode returns "true" if the value is listed in the enum definition. "false" otherwise
func (BacktestFeeMode) MarshalJSON ¶ added in v1.40.0
func (i BacktestFeeMode) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface for BacktestFeeMode
func (BacktestFeeMode) MarshalYAML ¶ added in v1.40.0
func (i BacktestFeeMode) MarshalYAML() (interface{}, error)
MarshalYAML implements a YAML Marshaler for BacktestFeeMode
func (BacktestFeeMode) String ¶ added in v1.40.0
func (i BacktestFeeMode) String() string
func (*BacktestFeeMode) UnmarshalJSON ¶ added in v1.40.0
func (i *BacktestFeeMode) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for BacktestFeeMode
func (*BacktestFeeMode) UnmarshalYAML ¶ added in v1.40.0
func (i *BacktestFeeMode) UnmarshalYAML(unmarshal func(interface{}) error) error
UnmarshalYAML implements a YAML Unmarshaler for BacktestFeeMode
type BaseOrderExecutor ¶ added in v1.52.0
type BaseOrderExecutor struct {
// contains filtered or unexported fields
}
BaseOrderExecutor provides the common accessors for order executor
func (*BaseOrderExecutor) ActiveMakerOrders ¶ added in v1.52.0
func (e *BaseOrderExecutor) ActiveMakerOrders() *ActiveOrderBook
func (*BaseOrderExecutor) GracefulCancel ¶ added in v1.52.0
GracefulCancel cancels all active maker orders if orders are not given, otherwise cancel all the given orders
func (*BaseOrderExecutor) OrderStore ¶ added in v1.52.0
func (e *BaseOrderExecutor) OrderStore() *core.OrderStore
type BasicRiskController ¶
type BasicRiskController struct { Logger *log.Logger MaxOrderAmount fixedpoint.Value `json:"maxOrderAmount,omitempty" yaml:"maxOrderAmount,omitempty"` MinQuoteBalance fixedpoint.Value `json:"minQuoteBalance,omitempty" yaml:"minQuoteBalance,omitempty"` MaxBaseAssetBalance fixedpoint.Value `json:"maxBaseAssetBalance,omitempty" yaml:"maxBaseAssetBalance,omitempty"` MinBaseAssetBalance fixedpoint.Value `json:"minBaseAssetBalance,omitempty" yaml:"minBaseAssetBalance,omitempty"` }
func (*BasicRiskController) ProcessOrders ¶
func (c *BasicRiskController) ProcessOrders(session *ExchangeSession, orders ...types.SubmitOrder) (outOrders []types.SubmitOrder, errs []error)
ProcessOrders filters and modifies the submit order objects by: 1. Increase the quantity by the minimal requirement 2. Decrease the quantity by risk controls 3. If the quantity does not meet minimal requirement, we should ignore the submit order.
type BuildConfig ¶ added in v1.9.0
type BuildConfig struct { BuildDir string `json:"buildDir,omitempty" yaml:"buildDir,omitempty"` Imports []string `json:"imports,omitempty" yaml:"imports,omitempty"` Targets []BuildTargetConfig `json:"targets,omitempty" yaml:"targets,omitempty"` }
type BuildTargetConfig ¶ added in v1.9.0
type BuildTargetConfig struct { Name string `json:"name" yaml:"name"` Arch string `json:"arch" yaml:"arch"` OS string `json:"os" yaml:"os"` LDFlags datatype.StringSlice `json:"ldflags,omitempty" yaml:"ldflags,omitempty"` GCFlags datatype.StringSlice `json:"gcflags,omitempty" yaml:"gcflags,omitempty"` Imports []string `json:"imports,omitempty" yaml:"imports,omitempty"` }
func GetNativeBuildTargetConfig ¶ added in v1.9.0
func GetNativeBuildTargetConfig() BuildTargetConfig
type Config ¶
type Config struct { Build *BuildConfig `json:"build,omitempty" yaml:"build,omitempty"` // Imports is deprecated // Deprecated: use BuildConfig instead Imports []string `json:"imports,omitempty" yaml:"imports,omitempty"` Backtest *Backtest `json:"backtest,omitempty" yaml:"backtest,omitempty"` Sync *SyncConfig `json:"sync,omitempty" yaml:"sync,omitempty"` Notifications *NotificationConfig `json:"notifications,omitempty" yaml:"notifications,omitempty"` Persistence *PersistenceConfig `json:"persistence,omitempty" yaml:"persistence,omitempty"` Service *ServiceConfig `json:"services,omitempty" yaml:"services,omitempty"` DatabaseConfig *DatabaseConfig `json:"database,omitempty" yaml:"database,omitempty"` Environment *EnvironmentConfig `json:"environment,omitempty" yaml:"environment,omitempty"` Sessions map[string]*ExchangeSession `json:"sessions,omitempty" yaml:"sessions,omitempty"` RiskControls *RiskControls `json:"riskControls,omitempty" yaml:"riskControls,omitempty"` Logging *LoggingConfig `json:"logging,omitempty"` ExchangeStrategies []ExchangeStrategyMount `json:"-" yaml:"-"` CrossExchangeStrategies []CrossExchangeStrategy `json:"-" yaml:"-"` PnLReporters []PnLReporterConfig `json:"reportPnL,omitempty" yaml:"reportPnL,omitempty"` }
func LoadBuildConfig ¶ added in v1.3.1
func (*Config) GetSignature ¶ added in v1.33.0
type CoreInteraction ¶ added in v1.26.0
type CoreInteraction struct {
// contains filtered or unexported fields
}
func NewCoreInteraction ¶ added in v1.26.0
func NewCoreInteraction(environment *Environment, trader *Trader) *CoreInteraction
func (*CoreInteraction) Commands ¶ added in v1.26.0
func (it *CoreInteraction) Commands(i *interact.Interact)
func (*CoreInteraction) Initialize ¶ added in v1.26.0
func (it *CoreInteraction) Initialize() error
type CrossExchangeSessionSubscriber ¶ added in v1.2.0
type CrossExchangeSessionSubscriber interface {
CrossSubscribe(sessions map[string]*ExchangeSession)
}
type CrossExchangeStrategy ¶
type CrossExchangeStrategy interface { StrategyID CrossRun(ctx context.Context, orderExecutionRouter OrderExecutionRouter, sessions map[string]*ExchangeSession) error }
type CumulatedVolumeTakeProfit ¶ added in v1.36.0
type CumulatedVolumeTakeProfit struct { Symbol string `json:"symbol"` types.IntervalWindow Ratio fixedpoint.Value `json:"ratio"` MinQuoteVolume fixedpoint.Value `json:"minQuoteVolume"` // contains filtered or unexported fields }
CumulatedVolumeTakeProfit This exit method cumulate the volume by N bars, if the cumulated volume exceeded a threshold, then we take profit.
To query the historical quote volume, use the following query:
> SELECT start_time, `interval`, quote_volume, open, close FROM binance_klines WHERE symbol = 'ETHUSDT' AND `interval` = '5m' ORDER BY quote_volume DESC LIMIT 20;
func (*CumulatedVolumeTakeProfit) Bind ¶ added in v1.36.0
func (s *CumulatedVolumeTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
type DatabaseConfig ¶ added in v1.56.0
type EmergencyStopper ¶ added in v1.29.0
type EmergencyStopper interface {
EmergencyStop() error
}
type Environment ¶
type Environment struct { // built-in service DatabaseService *service.DatabaseService OrderService *service.OrderService TradeService *service.TradeService ProfitService *service.ProfitService PositionService *service.PositionService BacktestService *service.BacktestService RewardService *service.RewardService MarginService *service.MarginService SyncService *service.SyncService AccountService *service.AccountService WithdrawService *service.WithdrawService DepositService *service.DepositService PersistentService *service.PersistenceServiceFacade // external services GoogleSpreadSheetService *googleservice.SpreadSheetService // contains filtered or unexported fields }
Environment presents the real exchange data layer
func NewEnvironment ¶
func NewEnvironment() *Environment
func (*Environment) AddExchange ¶
func (environ *Environment) AddExchange(name string, exchange types.Exchange) (session *ExchangeSession)
AddExchange adds the given exchange with the session name, this is the default
func (*Environment) AddExchangeSession ¶ added in v1.8.0
func (environ *Environment) AddExchangeSession(name string, session *ExchangeSession) *ExchangeSession
AddExchangeSession adds the existing exchange session or pre-created exchange session
func (*Environment) AddExchangesByViperKeys ¶ added in v1.5.0
func (environ *Environment) AddExchangesByViperKeys() error
func (*Environment) AddExchangesFromSessionConfig ¶ added in v1.5.0
func (environ *Environment) AddExchangesFromSessionConfig(sessions map[string]*ExchangeSession) error
func (*Environment) BindSync ¶ added in v1.28.0
func (environ *Environment) BindSync(config *SyncConfig)
func (*Environment) ConfigureDatabase ¶ added in v1.7.0
func (environ *Environment) ConfigureDatabase(ctx context.Context, config *Config) error
func (*Environment) ConfigureDatabaseDriver ¶ added in v1.12.0
func (*Environment) ConfigureExchangeSessions ¶ added in v1.12.0
func (environ *Environment) ConfigureExchangeSessions(userConfig *Config) error
func (*Environment) ConfigureNotification ¶
func (environ *Environment) ConfigureNotification(config *NotificationConfig) error
func (*Environment) ConfigureNotificationSystem ¶ added in v1.12.0
func (environ *Environment) ConfigureNotificationSystem(ctx context.Context, userConfig *Config) error
func (*Environment) ConfigureService ¶ added in v1.51.0
func (environ *Environment) ConfigureService(ctx context.Context, srvConfig *ServiceConfig) error
func (*Environment) Init ¶
func (environ *Environment) Init(ctx context.Context) (err error)
Init prepares the data that will be used by the strategies
func (*Environment) IsBackTesting ¶ added in v1.33.0
func (environ *Environment) IsBackTesting() bool
func (*Environment) IsSyncing ¶ added in v1.12.0
func (environ *Environment) IsSyncing() (status SyncStatus)
func (*Environment) Logger ¶ added in v1.52.0
func (environ *Environment) Logger() log.FieldLogger
func (*Environment) RecordAsset ¶ added in v1.32.0
func (environ *Environment) RecordAsset(t time.Time, session *ExchangeSession, assets types.AssetMap)
func (*Environment) RecordPosition ¶ added in v1.28.0
func (*Environment) RecordProfit ¶ added in v1.28.0
func (environ *Environment) RecordProfit(profit types.Profit)
func (*Environment) SelectSessions ¶ added in v1.11.1
func (environ *Environment) SelectSessions(names ...string) map[string]*ExchangeSession
func (*Environment) Session ¶ added in v1.8.0
func (environ *Environment) Session(name string) (*ExchangeSession, bool)
func (*Environment) Sessions ¶
func (environ *Environment) Sessions() map[string]*ExchangeSession
func (*Environment) SetLogging ¶ added in v1.44.0
func (environ *Environment) SetLogging(config *LoggingConfig)
func (*Environment) SetStartTime ¶
func (environ *Environment) SetStartTime(t time.Time) *Environment
func (*Environment) SetSyncStartTime ¶ added in v1.12.0
func (environ *Environment) SetSyncStartTime(t time.Time) *Environment
SetSyncStartTime overrides the default trade scan time (-7 days)
func (*Environment) Start ¶ added in v1.15.5
func (environ *Environment) Start(ctx context.Context) (err error)
Start initializes the symbols data streams
func (*Environment) StartTime ¶ added in v1.38.0
func (environ *Environment) StartTime() time.Time
func (*Environment) Sync ¶ added in v1.12.0
func (environ *Environment) Sync(ctx context.Context, userConfig ...*Config) error
Sync syncs all registered exchange sessions
func (*Environment) SyncSession ¶ added in v1.11.1
func (environ *Environment) SyncSession(ctx context.Context, session *ExchangeSession, defaultSymbols ...string) error
type EnvironmentConfig ¶ added in v1.54.0
type EnvironmentConfig struct { DisableDefaultKLineSubscription bool `json:"disableDefaultKLineSubscription"` DisableHistoryKLinePreload bool `json:"disableHistoryKLinePreload"` // DisableStartUpBalanceQuery disables the balance query in the startup process // which initializes the session.Account with the QueryAccount method. DisableStartupBalanceQuery bool `json:"disableStartupBalanceQuery"` DisableSessionTradeBuffer bool `json:"disableSessionTradeBuffer"` DisableMarketDataStore bool `json:"disableMarketDataStore"` MaxSessionTradeBufferSize int `json:"maxSessionTradeBufferSize"` SyncBufferPeriod *types.Duration `json:"syncBufferPeriod"` }
type ExchangeOrderExecutionRouter ¶
type ExchangeOrderExecutionRouter struct {
// contains filtered or unexported fields
}
func (*ExchangeOrderExecutionRouter) CancelOrdersTo ¶ added in v1.29.0
func (*ExchangeOrderExecutionRouter) SubmitOrdersTo ¶
func (e *ExchangeOrderExecutionRouter) SubmitOrdersTo(ctx context.Context, session string, orders ...types.SubmitOrder) (types.OrderSlice, error)
type ExchangeOrderExecutor ¶
type ExchangeOrderExecutor struct { Session *ExchangeSession `json:"-" yaml:"-"` // contains filtered or unexported fields }
ExchangeOrderExecutor is an order executor wrapper for single exchange instance.
func (*ExchangeOrderExecutor) CancelOrders ¶ added in v1.29.0
func (*ExchangeOrderExecutor) EmitOrderUpdate ¶ added in v1.5.0
func (e *ExchangeOrderExecutor) EmitOrderUpdate(order types.Order)
func (*ExchangeOrderExecutor) EmitTradeUpdate ¶ added in v1.5.0
func (e *ExchangeOrderExecutor) EmitTradeUpdate(trade types.Trade)
func (*ExchangeOrderExecutor) OnOrderUpdate ¶ added in v1.5.0
func (e *ExchangeOrderExecutor) OnOrderUpdate(cb func(order types.Order))
func (*ExchangeOrderExecutor) OnTradeUpdate ¶ added in v1.5.0
func (e *ExchangeOrderExecutor) OnTradeUpdate(cb func(trade types.Trade))
func (*ExchangeOrderExecutor) SubmitOrders ¶
func (e *ExchangeOrderExecutor) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (types.OrderSlice, error)
type ExchangeSession ¶
type ExchangeSession struct { // Exchange Session name Name string `json:"name,omitempty" yaml:"name,omitempty"` ExchangeName types.ExchangeName `json:"exchange" yaml:"exchange"` EnvVarPrefix string `json:"envVarPrefix" yaml:"envVarPrefix"` Key string `json:"key,omitempty" yaml:"key,omitempty"` Secret string `json:"secret,omitempty" yaml:"secret,omitempty"` Passphrase string `json:"passphrase,omitempty" yaml:"passphrase,omitempty"` SubAccount string `json:"subAccount,omitempty" yaml:"subAccount,omitempty"` // Withdrawal is used for enabling withdrawal functions Withdrawal bool `json:"withdrawal,omitempty" yaml:"withdrawal,omitempty"` MakerFeeRate fixedpoint.Value `json:"makerFeeRate" yaml:"makerFeeRate"` TakerFeeRate fixedpoint.Value `json:"takerFeeRate" yaml:"takerFeeRate"` ModifyOrderAmountForFee bool `json:"modifyOrderAmountForFee" yaml:"modifyOrderAmountForFee"` // PublicOnly is used for setting the session to public only (without authentication, no private user data) PublicOnly bool `json:"publicOnly,omitempty" yaml:"publicOnly"` // PrivateChannels is used for filtering the private user data channel, .e.g, orders, trades, balances.. etc // This option is exchange-specific, currently only MAX exchange reads this option PrivateChannels []string `json:"privateChannels,omitempty" yaml:"privateChannels,omitempty"` // PrivateChannelSymbols is used for filtering the private user data channel, .e.g, order symbol subscription. // This option is exchange-specific, currently only Bitget exchange reads this option PrivateChannelSymbols []string `json:"privateChannelSymbols,omitempty" yaml:"privateChannelSymbols,omitempty"` Margin bool `json:"margin,omitempty" yaml:"margin"` IsolatedMargin bool `json:"isolatedMargin,omitempty" yaml:"isolatedMargin,omitempty"` IsolatedMarginSymbol string `json:"isolatedMarginSymbol,omitempty" yaml:"isolatedMarginSymbol,omitempty"` Futures bool `json:"futures,omitempty" yaml:"futures"` IsolatedFutures bool `json:"isolatedFutures,omitempty" yaml:"isolatedFutures,omitempty"` IsolatedFuturesSymbol string `json:"isolatedFuturesSymbol,omitempty" yaml:"isolatedFuturesSymbol,omitempty"` // The exchange account states Account *types.Account `json:"-" yaml:"-"` IsInitialized bool `json:"-" yaml:"-"` OrderExecutor *ExchangeOrderExecutor `json:"orderExecutor,omitempty" yaml:"orderExecutor,omitempty"` // UserDataStream is the connection stream of the exchange UserDataStream types.Stream `json:"-" yaml:"-"` MarketDataStream types.Stream `json:"-" yaml:"-"` // Subscriptions // this is a read-only field when running strategy Subscriptions map[types.Subscription]types.Subscription `json:"-" yaml:"-"` Exchange types.Exchange `json:"-" yaml:"-"` UseHeikinAshi bool `json:"heikinAshi,omitempty" yaml:"heikinAshi,omitempty"` // Trades collects the executed trades from the exchange // map: symbol -> []trade Trades map[string]*types.TradeSlice `json:"-" yaml:"-"` // contains filtered or unexported fields }
ExchangeSession presents the exchange connection Session It also maintains and collects the data returned from the stream.
func NewExchangeSession ¶
func NewExchangeSession(name string, exchange types.Exchange) *ExchangeSession
func (*ExchangeSession) AllLastPrices ¶ added in v1.33.0
func (session *ExchangeSession) AllLastPrices() map[string]fixedpoint.Value
func (*ExchangeSession) FindPossibleAssetSymbols ¶ added in v1.55.3
func (session *ExchangeSession) FindPossibleAssetSymbols() (symbols []string, err error)
func (*ExchangeSession) FormatOrder ¶ added in v1.5.0
func (session *ExchangeSession) FormatOrder(order types.SubmitOrder) (types.SubmitOrder, error)
func (*ExchangeSession) FormatOrders ¶ added in v1.36.0
func (session *ExchangeSession) FormatOrders(orders []types.SubmitOrder) (formattedOrders []types.SubmitOrder, err error)
func (*ExchangeSession) GetAccount ¶ added in v1.31.0
func (session *ExchangeSession) GetAccount() (a *types.Account)
func (*ExchangeSession) Indicators ¶ added in v1.50.0
func (session *ExchangeSession) Indicators(symbol string) *IndicatorSet
Indicators returns the IndicatorSet struct that maintains the kLines stream cache and price stream cache It also provides helper methods
func (*ExchangeSession) Init ¶ added in v1.11.0
func (session *ExchangeSession) Init(ctx context.Context, environ *Environment) error
Init initializes the basic data structure and market information by its exchange. Note that the subscribed symbols are not loaded in this stage.
func (*ExchangeSession) InitExchange ¶ added in v1.21.0
func (session *ExchangeSession) InitExchange(name string, ex types.Exchange) error
InitExchange initialize the exchange instance and allocate memory for fields In this stage, the session var could be loaded from the JSON config, so the pointer fields are still nil The Init method will be called after this stage, environment.Init will call the session.Init method later.
func (*ExchangeSession) InitSymbols ¶ added in v1.11.0
func (session *ExchangeSession) InitSymbols(ctx context.Context, environ *Environment) error
func (*ExchangeSession) LastPrice ¶
func (session *ExchangeSession) LastPrice(symbol string) (price fixedpoint.Value, ok bool)
func (*ExchangeSession) LastPrices ¶ added in v1.11.0
func (session *ExchangeSession) LastPrices() map[string]fixedpoint.Value
func (*ExchangeSession) MarginType ¶ added in v1.21.0
func (session *ExchangeSession) MarginType() types.MarginType
func (*ExchangeSession) Market ¶
func (session *ExchangeSession) Market(symbol string) (market types.Market, ok bool)
func (*ExchangeSession) MarketDataStore ¶
func (session *ExchangeSession) MarketDataStore(symbol string) (s *MarketDataStore, ok bool)
MarketDataStore returns the market data store of a symbol
func (*ExchangeSession) Markets ¶ added in v1.11.0
func (session *ExchangeSession) Markets() types.MarketMap
func (*ExchangeSession) OrderBook ¶ added in v1.17.0
func (session *ExchangeSession) OrderBook(symbol string) (s *types.StreamOrderBook, ok bool)
OrderBook returns the personal orderbook of a symbol
func (*ExchangeSession) OrderStore ¶ added in v1.11.0
func (session *ExchangeSession) OrderStore(symbol string) (store *core.OrderStore, ok bool)
func (*ExchangeSession) OrderStores ¶ added in v1.11.0
func (session *ExchangeSession) OrderStores() map[string]*core.OrderStore
func (*ExchangeSession) Position ¶ added in v1.9.0
func (session *ExchangeSession) Position(symbol string) (pos *types.Position, ok bool)
func (*ExchangeSession) Positions ¶ added in v1.11.0
func (session *ExchangeSession) Positions() map[string]*types.Position
func (*ExchangeSession) SerialMarketDataStore ¶ added in v1.40.3
func (session *ExchangeSession) SerialMarketDataStore( ctx context.Context, symbol string, intervals []types.Interval, useAggTrade ...bool, ) (store *SerialMarketDataStore, ok bool)
KLine updates will be received in the order listend in intervals array
func (*ExchangeSession) SetMarkets ¶ added in v1.58.0
func (session *ExchangeSession) SetMarkets(markets types.MarketMap)
func (*ExchangeSession) SlackAttachment ¶ added in v1.32.0
func (session *ExchangeSession) SlackAttachment() slack.Attachment
func (*ExchangeSession) StandardIndicatorSet ¶
func (session *ExchangeSession) StandardIndicatorSet(symbol string) *StandardIndicatorSet
func (*ExchangeSession) StartPrice ¶
func (session *ExchangeSession) StartPrice(symbol string) (price fixedpoint.Value, ok bool)
func (*ExchangeSession) Subscribe ¶
func (session *ExchangeSession) Subscribe( channel types.Channel, symbol string, options types.SubscribeOptions, ) *ExchangeSession
Subscribe save the subscription info, later it will be assigned to the stream
func (*ExchangeSession) UpdateAccount ¶ added in v1.31.0
UpdateAccount locks the account mutex and update the account object
func (*ExchangeSession) UpdatePrices ¶ added in v1.11.0
type ExchangeSessionSubscriber ¶
type ExchangeSessionSubscriber interface {
Subscribe(session *ExchangeSession)
}
ExchangeSessionSubscriber provides an interface for collecting subscriptions from different strategies Subscribe method will be called before the user data stream connection is created.
type ExchangeStrategyMount ¶
type ExchangeStrategyMount struct { // Mounts contains the ExchangeSession name to mount Mounts []string `json:"mounts"` // Strategy is the strategy we loaded from config Strategy SingleExchangeStrategy `json:"strategy"` }
ExchangeStrategyMount wraps the SingleExchangeStrategy with the ExchangeSession name for mounting
func (*ExchangeStrategyMount) Map ¶ added in v1.11.0
func (m *ExchangeStrategyMount) Map() (map[string]interface{}, error)
type ExitMethod ¶ added in v1.36.0
type ExitMethod struct { RoiStopLoss *RoiStopLoss `json:"roiStopLoss"` ProtectiveStopLoss *ProtectiveStopLoss `json:"protectiveStopLoss"` RoiTakeProfit *RoiTakeProfit `json:"roiTakeProfit"` TrailingStop *TrailingStop2 `json:"trailingStop"` HigherHighLowerLowStop *HigherHighLowerLowStop `json:"higherHighLowerLowStopLoss"` // Exit methods for short positions // ================================================= LowerShadowTakeProfit *LowerShadowTakeProfit `json:"lowerShadowTakeProfit"` CumulatedVolumeTakeProfit *CumulatedVolumeTakeProfit `json:"cumulatedVolumeTakeProfit"` SupportTakeProfit *SupportTakeProfit `json:"supportTakeProfit"` }
func (*ExitMethod) Bind ¶ added in v1.36.0
func (m *ExitMethod) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*ExitMethod) Inherit ¶ added in v1.36.0
func (m *ExitMethod) Inherit(parent interface{})
Inherit is used for inheriting properties from the given strategy struct for example, some exit method requires the default interval and symbol name from the strategy param object
func (ExitMethod) String ¶ added in v1.39.2
func (e ExitMethod) String() string
func (*ExitMethod) Subscribe ¶ added in v1.36.0
func (m *ExitMethod) Subscribe(session *ExchangeSession)
type ExitMethodSet ¶ added in v1.36.0
type ExitMethodSet []ExitMethod
func (*ExitMethodSet) Bind ¶ added in v1.37.0
func (s *ExitMethodSet) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*ExitMethodSet) SetAndSubscribe ¶ added in v1.36.0
func (s *ExitMethodSet) SetAndSubscribe(session *ExchangeSession, parent interface{})
type ExponentialScale ¶ added in v1.13.0
type ExponentialScale struct { Domain [2]float64 `json:"domain"` Range [2]float64 `json:"range"` // contains filtered or unexported fields }
f(x) := ab^x y := ab^x shift xs[0] to 0 (x - h) a = y1
y := ab^(x-h) y2/a = b^(x2-h) y2/y1 = b^(x2-h)
also posted at https://play.golang.org/p/JlWlwZjoebE
func (*ExponentialScale) Call ¶ added in v1.13.0
func (s *ExponentialScale) Call(x float64) (y float64)
func (*ExponentialScale) Formula ¶ added in v1.13.0
func (s *ExponentialScale) Formula() string
func (*ExponentialScale) FormulaOf ¶ added in v1.13.0
func (s *ExponentialScale) FormulaOf(x float64) string
func (*ExponentialScale) Solve ¶ added in v1.13.0
func (s *ExponentialScale) Solve() error
func (*ExponentialScale) String ¶ added in v1.13.0
func (s *ExponentialScale) String() string
func (*ExponentialScale) Sum ¶ added in v1.48.0
func (s *ExponentialScale) Sum(step float64) float64
type FastOrderExecutor ¶ added in v1.48.0
type FastOrderExecutor struct {
*GeneralOrderExecutor
}
FastOrderExecutor provides shorter submit order / cancel order round-trip time for strategies that need to response more faster, e.g. 1s kline or market trades related strategies.
func NewFastOrderExecutor ¶ added in v1.48.0
func NewFastOrderExecutor(session *ExchangeSession, symbol, strategy, strategyInstanceID string, position *types.Position) *FastOrderExecutor
func (*FastOrderExecutor) Cancel ¶ added in v1.48.0
Cancel cancels all active maker orders if orders is not given, otherwise cancel the given orders
func (*FastOrderExecutor) SubmitOrders ¶ added in v1.48.0
func (e *FastOrderExecutor) SubmitOrders(ctx context.Context, submitOrders ...types.SubmitOrder) (types.OrderSlice, error)
SubmitOrders sends []types.SubmitOrder directly to the exchange without blocking wait on the status update. This is a faster version of GeneralOrderExecutor.SubmitOrders(). Created orders will be consumed in newly created goroutine (in non-backteset session). @param ctx: golang context type. @param submitOrders: Lists of types.SubmitOrder to be sent to the exchange. @return *types.SubmitOrder: SubmitOrder with calculated quantity and price. @return error: Error message.
type GeneralOrderExecutor ¶ added in v1.36.0
type GeneralOrderExecutor struct { BaseOrderExecutor // contains filtered or unexported fields }
GeneralOrderExecutor implements the general order executor for strategy
func NewGeneralOrderExecutor ¶ added in v1.36.0
func NewGeneralOrderExecutor( session *ExchangeSession, symbol, strategy, strategyInstanceID string, position *types.Position, ) *GeneralOrderExecutor
NewGeneralOrderExecutor allocates a GeneralOrderExecutor which has its own order store, trade collector
func (*GeneralOrderExecutor) Bind ¶ added in v1.36.0
func (e *GeneralOrderExecutor) Bind()
func (*GeneralOrderExecutor) BindEnvironment ¶ added in v1.36.0
func (e *GeneralOrderExecutor) BindEnvironment(environ *Environment)
func (*GeneralOrderExecutor) BindProfitStats ¶ added in v1.36.0
func (e *GeneralOrderExecutor) BindProfitStats(profitStats *types.ProfitStats)
func (*GeneralOrderExecutor) BindTradeStats ¶ added in v1.36.0
func (e *GeneralOrderExecutor) BindTradeStats(tradeStats *types.TradeStats)
func (*GeneralOrderExecutor) CancelOrders ¶ added in v1.36.0
CancelOrders cancels the given order objects directly
func (*GeneralOrderExecutor) ClosePosition ¶ added in v1.36.0
func (e *GeneralOrderExecutor) ClosePosition(ctx context.Context, percentage fixedpoint.Value, tags ...string) error
ClosePosition closes the current position by a percentage. percentage 0.1 means close 10% position tag is the order tag you want to attach, you may pass multiple tags, the tags will be combined into one tag string by commas.
func (*GeneralOrderExecutor) CurrentPosition ¶ added in v1.41.0
func (e *GeneralOrderExecutor) CurrentPosition() *types.Position
This implements PositionReader interface
func (*GeneralOrderExecutor) DisableNotify ¶ added in v1.43.0
func (e *GeneralOrderExecutor) DisableNotify()
func (*GeneralOrderExecutor) GracefulCancel ¶ added in v1.36.0
GracefulCancel cancels all active maker orders if orders are not given, otherwise cancel all the given orders
func (*GeneralOrderExecutor) GracefulCancelActiveOrderBook ¶ added in v1.36.0
func (e *GeneralOrderExecutor) GracefulCancelActiveOrderBook(ctx context.Context, activeOrders *ActiveOrderBook) error
GracefulCancelActiveOrderBook cancels the orders from the active orderbook.
func (*GeneralOrderExecutor) NewOrderFromOpenPosition ¶ added in v1.43.0
func (e *GeneralOrderExecutor) NewOrderFromOpenPosition( ctx context.Context, options *OpenPositionOptions, ) (*types.SubmitOrder, error)
Create new submitOrder from OpenPositionOptions. @param ctx: golang context type. @param options: OpenPositionOptions to control the generated SubmitOrder in a higher level way. Notice that the Price in options will be updated as the submitOrder price. @return *types.SubmitOrder: SubmitOrder with calculated quantity and price. @return error: Error message.
func (*GeneralOrderExecutor) OpenPosition ¶ added in v1.40.3
func (e *GeneralOrderExecutor) OpenPosition( ctx context.Context, options OpenPositionOptions, ) (types.OrderSlice, error)
OpenPosition sends the orders generated from OpenPositionOptions to the exchange by calling SubmitOrders or reduceQuantityAndSubmitOrder. @param ctx: golang context type. @param options: OpenPositionOptions to control the generated SubmitOrder in a higher level way. Notice that the Price in options will be updated as the submitOrder price. @return types.OrderSlice: Created orders with information from exchange. @return error: Error message.
func (*GeneralOrderExecutor) Position ¶ added in v1.36.0
func (e *GeneralOrderExecutor) Position() *types.Position
func (*GeneralOrderExecutor) ResetPosition ¶ added in v1.41.0
func (e *GeneralOrderExecutor) ResetPosition() error
This implements PositionResetter interface
func (*GeneralOrderExecutor) Session ¶ added in v1.36.0
func (e *GeneralOrderExecutor) Session() *ExchangeSession
func (*GeneralOrderExecutor) SetLogger ¶ added in v1.44.0
func (e *GeneralOrderExecutor) SetLogger(logger log.FieldLogger)
func (*GeneralOrderExecutor) SetMaxRetries ¶ added in v1.45.0
func (e *GeneralOrderExecutor) SetMaxRetries(maxRetries uint)
func (*GeneralOrderExecutor) SubmitOrders ¶ added in v1.36.0
func (e *GeneralOrderExecutor) SubmitOrders( ctx context.Context, submitOrders ...types.SubmitOrder, ) (types.OrderSlice, error)
func (*GeneralOrderExecutor) TradeCollector ¶ added in v1.36.0
func (e *GeneralOrderExecutor) TradeCollector() *core.TradeCollector
type GoogleSpreadSheetServiceConfig ¶ added in v1.51.0
type GracefulShutdown ¶ added in v1.42.0
type GracefulShutdown struct {
// contains filtered or unexported fields
}
func (*GracefulShutdown) EmitShutdown ¶ added in v1.42.0
func (g *GracefulShutdown) EmitShutdown(ctx context.Context, wg *sync.WaitGroup)
func (*GracefulShutdown) OnShutdown ¶ added in v1.42.0
func (g *GracefulShutdown) OnShutdown(cb ShutdownHandler)
func (*GracefulShutdown) Shutdown ¶ added in v1.42.0
func (g *GracefulShutdown) Shutdown(shutdownCtx context.Context)
Shutdown is a blocking call to emit all shutdown callbacks at the same time. The context object here should not be canceled context, you need to create a todo context.
type HigherHighLowerLowStop ¶ added in v1.46.0
type HigherHighLowerLowStop struct { Symbol string `json:"symbol"` // Interval is the kline interval used by this exit. Window is used as the range to determining higher highs and // lower lows types.IntervalWindow // HighLowWindow is the range to calculate the number of higher highs and lower lows HighLowWindow int `json:"highLowWindow"` // If the number of higher highs or lower lows with in HighLowWindow is more than MaxHighLow, the exit is triggered. // 0 disables this parameter. Either one of MaxHighLow and MinHighLow must be larger than 0 MaxHighLow int `json:"maxHighLow"` // If the number of higher highs or lower lows with in HighLowWindow is less than MinHighLow, the exit is triggered. // 0 disables this parameter. Either one of MaxHighLow and MinHighLow must be larger than 0 MinHighLow int `json:"minHighLow"` // ActivationRatio is the trigger condition // When the price goes higher (lower for short position) than this ratio, the stop will be activated. // You can use this to combine several exits ActivationRatio fixedpoint.Value `json:"activationRatio"` // DeactivationRatio is the kill condition // When the price goes higher (lower for short position) than this ratio, the stop will be deactivated. // You can use this to combine several exits DeactivationRatio fixedpoint.Value `json:"deactivationRatio"` // If true, looking for lower lows in long position and higher highs in short position. If false, looking for higher // highs in long position and lower lows in short position OppositeDirectionAsPosition bool `json:"oppositeDirectionAsPosition"` // contains filtered or unexported fields }
func (*HigherHighLowerLowStop) Bind ¶ added in v1.46.0
func (s *HigherHighLowerLowStop) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*HigherHighLowerLowStop) Subscribe ¶ added in v1.46.0
func (s *HigherHighLowerLowStop) Subscribe(session *ExchangeSession)
Subscribe required k-line stream
type IndicatorSet ¶ added in v1.50.0
type IndicatorSet struct { Symbol string // contains filtered or unexported fields }
IndicatorSet is the v2 standard indicator set This will replace StandardIndicator in the future
func NewIndicatorSet ¶ added in v1.50.0
func NewIndicatorSet(symbol string, stream types.Stream, store *MarketDataStore) *IndicatorSet
func (*IndicatorSet) ADX ¶ added in v1.59.0
func (i *IndicatorSet) ADX(interval types.Interval, window int) *indicatorv2.ADXStream
func (*IndicatorSet) ATR ¶ added in v1.50.0
func (i *IndicatorSet) ATR(interval types.Interval, window int) *indicatorv2.ATRStream
func (*IndicatorSet) ATRP ¶ added in v1.50.0
func (i *IndicatorSet) ATRP(interval types.Interval, window int) *indicatorv2.ATRPStream
func (*IndicatorSet) BOLL ¶ added in v1.50.0
func (i *IndicatorSet) BOLL(iw types.IntervalWindow, k float64) *indicatorv2.BOLLStream
func (*IndicatorSet) CLOSE ¶ added in v1.50.0
func (i *IndicatorSet) CLOSE(interval types.Interval) *indicatorv2.PriceStream
func (*IndicatorSet) EMA ¶ added in v1.50.0
func (i *IndicatorSet) EMA(iw types.IntervalWindow) *indicatorv2.EWMAStream
func (*IndicatorSet) EWMA ¶ added in v1.50.0
func (i *IndicatorSet) EWMA(iw types.IntervalWindow) *indicatorv2.EWMAStream
func (*IndicatorSet) HIGH ¶ added in v1.50.0
func (i *IndicatorSet) HIGH(interval types.Interval) *indicatorv2.PriceStream
func (*IndicatorSet) KLines ¶ added in v1.50.0
func (i *IndicatorSet) KLines(interval types.Interval) *indicatorv2.KLineStream
func (*IndicatorSet) Keltner ¶ added in v1.57.0
func (i *IndicatorSet) Keltner(iw types.IntervalWindow, atrLength int) *indicatorv2.KeltnerStream
func (*IndicatorSet) LOW ¶ added in v1.50.0
func (i *IndicatorSet) LOW(interval types.Interval) *indicatorv2.PriceStream
func (*IndicatorSet) MACD ¶ added in v1.50.0
func (i *IndicatorSet) MACD(interval types.Interval, shortWindow, longWindow, signalWindow int) *indicatorv2.MACDStream
func (*IndicatorSet) OPEN ¶ added in v1.50.0
func (i *IndicatorSet) OPEN(interval types.Interval) *indicatorv2.PriceStream
func (*IndicatorSet) RSI ¶ added in v1.50.0
func (i *IndicatorSet) RSI(iw types.IntervalWindow) *indicatorv2.RSIStream
func (*IndicatorSet) STOCH ¶ added in v1.50.0
func (i *IndicatorSet) STOCH(iw types.IntervalWindow, dPeriod int) *indicatorv2.StochStream
func (*IndicatorSet) VOLUME ¶ added in v1.50.0
func (i *IndicatorSet) VOLUME(interval types.Interval) *indicatorv2.PriceStream
type Isolation ¶ added in v1.42.0
type Isolation struct {
// contains filtered or unexported fields
}
func GetIsolationFromContext ¶ added in v1.42.0
func NewDefaultIsolation ¶ added in v1.42.0
func NewDefaultIsolation() *Isolation
func NewIsolation ¶ added in v1.42.0
func NewIsolation(persistenceFacade *service.PersistenceServiceFacade) *Isolation
type LayerScale ¶ added in v1.16.0
type LayerScale struct {
LayerRule *SlideRule `json:"byLayer"`
}
LayerScale defines the scale DSL for maker layers, e.g.,
quantityScale:
byLayer: exp: domain: [1, 5] range: [0.01, 1.0]
and
quantityScale:
byLayer: linear: domain: [1, 3] range: [0.01, 1.0]
func (*LayerScale) Scale ¶ added in v1.16.0
func (s *LayerScale) Scale(layer int) (quantity float64, err error)
func (*LayerScale) UnmarshalJSON ¶ added in v1.55.0
func (s *LayerScale) UnmarshalJSON(data []byte) error
type LinearScale ¶ added in v1.13.0
type LinearScale struct { Domain [2]float64 `json:"domain"` Range [2]float64 `json:"range"` // contains filtered or unexported fields }
func (*LinearScale) Call ¶ added in v1.13.0
func (s *LinearScale) Call(x float64) (y float64)
func (*LinearScale) Formula ¶ added in v1.13.0
func (s *LinearScale) Formula() string
func (*LinearScale) FormulaOf ¶ added in v1.13.0
func (s *LinearScale) FormulaOf(x float64) string
func (*LinearScale) Solve ¶ added in v1.13.0
func (s *LinearScale) Solve() error
func (*LinearScale) String ¶ added in v1.13.0
func (s *LinearScale) String() string
func (*LinearScale) Sum ¶ added in v1.48.0
func (s *LinearScale) Sum(step float64) float64
type LogFormatterType ¶ added in v1.55.0
type LogFormatterType string
const ( LogFormatterTypePrefixed LogFormatterType = "prefixed" LogFormatterTypeText LogFormatterType = "text" LogFormatterTypeJson LogFormatterType = "json" )
type LogarithmicScale ¶ added in v1.13.0
type LogarithmicScale struct { Domain [2]float64 `json:"domain"` Range [2]float64 `json:"range"` // contains filtered or unexported fields }
func (*LogarithmicScale) Call ¶ added in v1.13.0
func (s *LogarithmicScale) Call(x float64) (y float64)
func (*LogarithmicScale) Formula ¶ added in v1.13.0
func (s *LogarithmicScale) Formula() string
func (*LogarithmicScale) FormulaOf ¶ added in v1.13.0
func (s *LogarithmicScale) FormulaOf(x float64) string
func (*LogarithmicScale) Solve ¶ added in v1.13.0
func (s *LogarithmicScale) Solve() error
func (*LogarithmicScale) String ¶ added in v1.13.0
func (s *LogarithmicScale) String() string
func (*LogarithmicScale) Sum ¶ added in v1.48.0
func (s *LogarithmicScale) Sum(step float64) float64
type LoggingConfig ¶ added in v1.44.0
type LowerShadowTakeProfit ¶ added in v1.36.0
type LowerShadowTakeProfit struct { // inherit from the strategy types.IntervalWindow // inherit from the strategy Symbol string `json:"symbol"` Ratio fixedpoint.Value `json:"ratio"` // contains filtered or unexported fields }
func (*LowerShadowTakeProfit) Bind ¶ added in v1.36.0
func (s *LowerShadowTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*LowerShadowTakeProfit) Subscribe ¶ added in v1.36.0
func (s *LowerShadowTakeProfit) Subscribe(session *ExchangeSession)
type MACDConfig ¶ added in v1.41.0
type MACDConfig struct {
types.IntervalWindow
}
type MarketDataStore ¶
type MarketDataStore struct { Symbol string // KLineWindows stores all loaded klines per interval KLineWindows map[types.Interval]*types.KLineWindow `json:"-"` // contains filtered or unexported fields }
MarketDataStore receives and maintain the public market data of a single symbol
func NewMarketDataStore ¶
func NewMarketDataStore(symbol string) *MarketDataStore
func (*MarketDataStore) AddKLine ¶
func (store *MarketDataStore) AddKLine(k types.KLine)
func (*MarketDataStore) BindStream ¶
func (store *MarketDataStore) BindStream(stream types.Stream)
func (*MarketDataStore) EmitKLineClosed ¶ added in v1.38.0
func (store *MarketDataStore) EmitKLineClosed(k types.KLine)
func (*MarketDataStore) EmitKLineWindowUpdate ¶
func (store *MarketDataStore) EmitKLineWindowUpdate(interval types.Interval, klines types.KLineWindow)
func (*MarketDataStore) KLinesOfInterval ¶
func (store *MarketDataStore) KLinesOfInterval(interval types.Interval) (kLines *types.KLineWindow, ok bool)
KLinesOfInterval returns the kline window of the given interval
func (*MarketDataStore) OnKLineClosed ¶ added in v1.38.0
func (store *MarketDataStore) OnKLineClosed(cb func(k types.KLine))
func (*MarketDataStore) OnKLineWindowUpdate ¶
func (store *MarketDataStore) OnKLineWindowUpdate(cb func(interval types.Interval, klines types.KLineWindow))
func (*MarketDataStore) SetKLineWindows ¶
func (store *MarketDataStore) SetKLineWindows(windows map[types.Interval]*types.KLineWindow)
type MovingAverageSettings ¶ added in v1.17.1
type MovingAverageSettings struct { Type string `json:"type"` Interval types.Interval `json:"interval"` Window int `json:"window"` Side *types.SideType `json:"side"` QuantityOrAmount }
func (*MovingAverageSettings) Indicator ¶ added in v1.17.1
func (settings *MovingAverageSettings) Indicator(indicatorSet *StandardIndicatorSet) (inc types.Float64Indicator, err error)
func (MovingAverageSettings) IntervalWindow ¶ added in v1.17.1
func (settings MovingAverageSettings) IntervalWindow() types.IntervalWindow
type Notifiability ¶
type Notifiability struct { SessionChannelRouter *PatternChannelRouter `json:"-"` SymbolChannelRouter *PatternChannelRouter `json:"-"` ObjectChannelRouter *ObjectChannelRouter `json:"-"` // contains filtered or unexported fields }
func (*Notifiability) AddNotifier ¶
func (m *Notifiability) AddNotifier(notifier Notifier)
AddNotifier adds the notifier that implements the Notifier interface.
func (*Notifiability) Notify ¶
func (m *Notifiability) Notify(obj interface{}, args ...interface{})
func (*Notifiability) NotifyTo ¶
func (m *Notifiability) NotifyTo(channel string, obj interface{}, args ...interface{})
func (*Notifiability) RouteObject ¶
func (m *Notifiability) RouteObject(obj interface{}) (channel string, ok bool)
RouteObject routes object to channel
func (*Notifiability) RouteSession ¶
func (m *Notifiability) RouteSession(session string) (channel string, ok bool)
RouteSession routes Session name to channel
func (*Notifiability) RouteSymbol ¶
func (m *Notifiability) RouteSymbol(symbol string) (channel string, ok bool)
RouteSymbol routes symbol name to channel
func (*Notifiability) SendPhoto ¶ added in v1.39.0
func (m *Notifiability) SendPhoto(buffer *bytes.Buffer)
func (*Notifiability) SendPhotoTo ¶ added in v1.39.0
func (m *Notifiability) SendPhotoTo(channel string, buffer *bytes.Buffer)
type NotificationConfig ¶
type NotificationConfig struct { Slack *SlackNotification `json:"slack,omitempty" yaml:"slack,omitempty"` Telegram *TelegramNotification `json:"telegram,omitempty" yaml:"telegram,omitempty"` Switches *NotificationSwitches `json:"switches" yaml:"switches"` }
type NotificationSwitches ¶ added in v1.41.0
type NullNotifier ¶
type NullNotifier struct{}
func (*NullNotifier) Notify ¶
func (n *NullNotifier) Notify(obj interface{}, args ...interface{})
func (*NullNotifier) NotifyTo ¶
func (n *NullNotifier) NotifyTo(channel string, obj interface{}, args ...interface{})
func (*NullNotifier) SendPhoto ¶ added in v1.39.0
func (n *NullNotifier) SendPhoto(buffer *bytes.Buffer)
func (*NullNotifier) SendPhotoTo ¶ added in v1.39.0
func (n *NullNotifier) SendPhotoTo(channel string, buffer *bytes.Buffer)
type ObjectChannelHandler ¶
type ObjectChannelRouter ¶
type ObjectChannelRouter struct {
// contains filtered or unexported fields
}
func NewObjectChannelRouter ¶
func NewObjectChannelRouter() *ObjectChannelRouter
func (*ObjectChannelRouter) AddRoute ¶
func (router *ObjectChannelRouter) AddRoute(f ObjectChannelHandler)
func (*ObjectChannelRouter) Route ¶
func (router *ObjectChannelRouter) Route(obj interface{}) (channel string, ok bool)
type OpenPositionOptions ¶ added in v1.40.3
type OpenPositionOptions struct { // Long is for open a long position // Long or Short must be set, avoid loading it from the config file // it should be set from the strategy code Long bool `json:"-" yaml:"-"` // Short is for open a short position // Long or Short must be set Short bool `json:"-" yaml:"-"` // Leverage is used for leveraged position and account // Leverage is not effected when using non-leverage spot account Leverage fixedpoint.Value `json:"leverage,omitempty" modifiable:"true"` // Quantity will be used first, it will override the leverage if it's given Quantity fixedpoint.Value `json:"quantity,omitempty" modifiable:"true"` // LimitOrder set to true to open a position with a limit order // default is false, and will send MarketOrder LimitOrder bool `json:"limitOrder,omitempty" modifiable:"true"` // LimitOrderTakerRatio is used when LimitOrder = true, it adjusts the price of the limit order with a ratio. // So you can ensure that the limit order can be a taker order. Higher the ratio, higher the chance it could be a taker order. // // limitOrderTakerRatio is the price ratio to adjust your limit order as a taker order. e.g., 0.1% // for sell order, 0.1% ratio means your final price = price * (1 - 0.1%) // for buy order, 0.1% ratio means your final price = price * (1 + 0.1%) // this is only enabled when the limitOrder option set to true LimitOrderTakerRatio fixedpoint.Value `json:"limitOrderTakerRatio,omitempty"` Price fixedpoint.Value `json:"-" yaml:"-"` Tags []string `json:"-" yaml:"-"` }
type OrderCallback ¶ added in v1.44.0
type OrderExecutionRouter ¶
type OrderExecutionRouter interface { // SubmitOrdersTo submit order to a specific exchange Session SubmitOrdersTo(ctx context.Context, session string, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error) CancelOrdersTo(ctx context.Context, session string, orders ...types.Order) error }
type OrderExecutor ¶
type OrderExecutorExtended ¶ added in v1.51.0
type PatternChannelRouter ¶
type PatternChannelRouter struct {
// contains filtered or unexported fields
}
func NewPatternChannelRouter ¶
func NewPatternChannelRouter(routes map[string]string) *PatternChannelRouter
func (*PatternChannelRouter) AddRoute ¶
func (router *PatternChannelRouter) AddRoute(routes map[string]string)
type PercentageScale ¶ added in v1.28.0
type PercentageScale struct {
ByPercentage *SlideRule `json:"byPercentage"`
}
type PersistenceConfig ¶ added in v1.3.1
type PersistenceConfig struct { Redis *service.RedisPersistenceConfig `json:"redis,omitempty" yaml:"redis,omitempty"` Json *service.JsonPersistenceConfig `json:"json,omitempty" yaml:"json,omitempty"` }
type PnLReporter ¶
type PnLReporter interface {
Run()
}
type PnLReporterConfig ¶
type PnLReporterConfig struct { AverageCostBySymbols datatype.StringSlice `json:"averageCostBySymbols" yaml:"averageCostBySymbols"` Of datatype.StringSlice `json:"of" yaml:"of"` When datatype.StringSlice `json:"when" yaml:"when"` }
type PnLReporterManager ¶
type PnLReporterManager struct {
// contains filtered or unexported fields
}
func NewPnLReporter ¶
func NewPnLReporter(notifier Notifier) *PnLReporterManager
func (*PnLReporterManager) AverageCostBySymbols ¶
func (manager *PnLReporterManager) AverageCostBySymbols(symbols ...string) *AverageCostPnLReporter
type PositionCloser ¶ added in v1.26.0
type PositionCloser interface {
ClosePosition(ctx context.Context, percentage fixedpoint.Value) error
}
type PositionReader ¶ added in v1.26.0
type PositionResetter ¶ added in v1.40.3
type PositionResetter interface {
ResetPosition() error
}
type PriceVolumeScale ¶ added in v1.13.0
type PriceVolumeScale struct { ByPriceRule *SlideRule `json:"byPrice"` ByVolumeRule *SlideRule `json:"byVolume"` }
PriceVolumeScale defines the scale DSL for strategy, e.g.,
quantityScale:
byPrice: exp: domain: [10_000, 50_000] range: [0.01, 1.0]
and
quantityScale:
byVolume: linear: domain: [10_000, 50_000] range: [0.01, 1.0]
func (*PriceVolumeScale) Scale ¶ added in v1.13.0
func (s *PriceVolumeScale) Scale(price float64, volume float64) (quantity float64, err error)
func (*PriceVolumeScale) ScaleByPrice ¶ added in v1.13.0
func (s *PriceVolumeScale) ScaleByPrice(price float64) (float64, error)
ScaleByPrice scale quantity by the given price
func (*PriceVolumeScale) ScaleByVolume ¶ added in v1.13.0
func (s *PriceVolumeScale) ScaleByVolume(volume float64) (float64, error)
ScaleByVolume scale quantity by the given volume
type ProtectiveStopLoss ¶ added in v1.36.0
type ProtectiveStopLoss struct { Symbol string `json:"symbol"` // ActivationRatio is the trigger condition of this ROI protection stop loss // When the price goes lower (for short position) with the ratio, the protection stop will be activated. // This number should be positive to protect the profit ActivationRatio fixedpoint.Value `json:"activationRatio"` // StopLossRatio is the ratio for stop loss. This number should be positive to protect the profit. // negative ratio will cause loss. StopLossRatio fixedpoint.Value `json:"stopLossRatio"` // PlaceStopOrder places the stop order on exchange and lock the balance PlaceStopOrder bool `json:"placeStopOrder"` // Interval is the time resolution to update the stop order // KLine per Interval will be used for updating the stop order Interval types.Interval `json:"interval,omitempty"` // contains filtered or unexported fields }
ProtectiveStopLoss provides a way to protect your profit but also keep a room for the price volatility Set ActivationRatio to 1% means if the price is away from your average cost by 1%, we will activate the protective stop loss and the StopLossRatio is the minimal profit ratio you want to keep for your position. If you set StopLossRatio to 0.1% and ActivationRatio to 1%, when the price goes away from your average cost by 1% and then goes back to below your (average_cost * (1 - 0.1%)) The stop will trigger.
func (*ProtectiveStopLoss) Bind ¶ added in v1.36.0
func (s *ProtectiveStopLoss) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*ProtectiveStopLoss) Subscribe ¶ added in v1.37.0
func (s *ProtectiveStopLoss) Subscribe(session *ExchangeSession)
type QuadraticScale ¶ added in v1.13.0
type QuadraticScale struct { Domain [3]float64 `json:"domain"` Range [3]float64 `json:"range"` // contains filtered or unexported fields }
see also: http://www.vb-helper.com/howto_find_quadratic_curve.html
func (*QuadraticScale) Call ¶ added in v1.13.0
func (s *QuadraticScale) Call(x float64) (y float64)
func (*QuadraticScale) Formula ¶ added in v1.13.0
func (s *QuadraticScale) Formula() string
func (*QuadraticScale) FormulaOf ¶ added in v1.13.0
func (s *QuadraticScale) FormulaOf(x float64) string
func (*QuadraticScale) Solve ¶ added in v1.13.0
func (s *QuadraticScale) Solve() error
func (*QuadraticScale) String ¶ added in v1.13.0
func (s *QuadraticScale) String() string
func (*QuadraticScale) Sum ¶ added in v1.48.0
func (s *QuadraticScale) Sum(step float64) float64
type QuantityOrAmount ¶ added in v1.28.0
type QuantityOrAmount struct { // Quantity is the base order quantity for your buy/sell order. // when quantity is set, the amount option will be not used. Quantity fixedpoint.Value `json:"quantity"` // Amount is the order quote amount for your buy/sell order. Amount fixedpoint.Value `json:"amount,omitempty"` }
QuantityOrAmount is a setting structure used for quantity/amount settings You can embed this struct into your strategy to share the setting methods
func (*QuantityOrAmount) CalculateQuantity ¶ added in v1.28.0
func (qa *QuantityOrAmount) CalculateQuantity(currentPrice fixedpoint.Value) fixedpoint.Value
CalculateQuantity calculates the equivalent quantity of the given price when amount is set it returns the quantity if the quantity is set
func (*QuantityOrAmount) IsSet ¶ added in v1.28.0
func (qa *QuantityOrAmount) IsSet() bool
func (*QuantityOrAmount) Validate ¶ added in v1.28.0
func (qa *QuantityOrAmount) Validate() error
type Quota ¶ added in v1.2.0
type Quota struct { Available fixedpoint.Value Locked fixedpoint.Value // contains filtered or unexported fields }
func (*Quota) Add ¶ added in v1.2.0
func (q *Quota) Add(fund fixedpoint.Value)
Add adds the fund to the available quota
func (*Quota) Lock ¶ added in v1.2.0
func (q *Quota) Lock(fund fixedpoint.Value) bool
Lock locks the fund from the available quota returns true if the fund is locked successfully returns false if the fund is not enough
type QuotaTransaction ¶ added in v1.2.0
type QuotaTransaction struct { BaseAsset Quota QuoteAsset Quota // contains filtered or unexported fields }
QuotaTransaction is a transactional quota manager
func (*QuotaTransaction) Commit ¶ added in v1.2.0
func (m *QuotaTransaction) Commit() bool
Commit commits the transaction
func (*QuotaTransaction) Rollback ¶ added in v1.2.0
func (m *QuotaTransaction) Rollback() bool
Rollback rolls back the transaction
type RiskControlOrderExecutor ¶
type RiskControlOrderExecutor struct { *ExchangeOrderExecutor // Symbol => Executor config BySymbol map[string]*SymbolBasedRiskController `json:"bySymbol,omitempty" yaml:"bySymbol,omitempty"` }
func (*RiskControlOrderExecutor) SubmitOrders ¶
func (e *RiskControlOrderExecutor) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (retOrders types.OrderSlice, err error)
type RiskControls ¶
type RiskControls struct {
SessionBasedRiskControl map[string]*SessionBasedRiskControl `json:"sessionBased,omitempty" yaml:"sessionBased,omitempty"`
}
type RoiStopLoss ¶ added in v1.36.0
type RoiStopLoss struct { Symbol string Percentage fixedpoint.Value `json:"percentage"` CancelActiveOrders bool `json:"cancelActiveOrders"` // Interval is the time resolution to update the stop order // KLine per Interval will be used for updating the stop order Interval types.Interval `json:"interval,omitempty"` // contains filtered or unexported fields }
func (*RoiStopLoss) Bind ¶ added in v1.36.0
func (s *RoiStopLoss) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*RoiStopLoss) Subscribe ¶ added in v1.36.0
func (s *RoiStopLoss) Subscribe(session *ExchangeSession)
type RoiTakeProfit ¶ added in v1.36.0
type RoiTakeProfit struct { Symbol string `json:"symbol"` Percentage fixedpoint.Value `json:"percentage"` CancelActiveOrders bool `json:"cancelActiveOrders"` // Interval is the time resolution to update the stop order // KLine per Interval will be used for updating the stop order Interval types.Interval `json:"interval,omitempty"` // contains filtered or unexported fields }
RoiTakeProfit force takes the profit by the given ROI percentage.
func (*RoiTakeProfit) Bind ¶ added in v1.36.0
func (s *RoiTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*RoiTakeProfit) Subscribe ¶ added in v1.38.0
func (s *RoiTakeProfit) Subscribe(session *ExchangeSession)
type SerialMarketDataStore ¶ added in v1.40.3
type SerialMarketDataStore struct { *MarketDataStore UseMarketTrade bool KLines map[types.Interval]*types.KLine MinInterval types.Interval Subscription []types.Interval // contains filtered or unexported fields }
func NewSerialMarketDataStore ¶ added in v1.40.3
func NewSerialMarketDataStore(symbol string, minInterval types.Interval, useMarketTrade ...bool) *SerialMarketDataStore
@param symbol: symbol to trace on @param minInterval: unit interval, related to your signal timeframe @param useMarketTrade: if not assigned, default to false. if assigned to true, will use MarketTrade signal to generate klines
func (*SerialMarketDataStore) AddKLine ¶ added in v1.40.3
func (store *SerialMarketDataStore) AddKLine(kline types.KLine, async ...bool)
func (*SerialMarketDataStore) BindStream ¶ added in v1.40.3
func (store *SerialMarketDataStore) BindStream(ctx context.Context, stream types.Stream)
func (*SerialMarketDataStore) Subscribe ¶ added in v1.40.3
func (store *SerialMarketDataStore) Subscribe(interval types.Interval)
type ServiceConfig ¶ added in v1.51.0
type ServiceConfig struct {
GoogleSpreadSheetService *GoogleSpreadSheetServiceConfig `json:"googleSpreadSheet" yaml:"googleSpreadSheet"`
}
type Session ¶
type Session struct { Name string `json:"name,omitempty" yaml:"name,omitempty"` ExchangeName string `json:"exchange" yaml:"exchange"` EnvVarPrefix string `json:"envVarPrefix" yaml:"envVarPrefix"` Key string `json:"key,omitempty" yaml:"key,omitempty"` Secret string `json:"secret,omitempty" yaml:"secret,omitempty"` PublicOnly bool `json:"publicOnly,omitempty" yaml:"publicOnly"` Margin bool `json:"margin,omitempty" yaml:"margin,omitempty"` IsolatedMargin bool `json:"isolatedMargin,omitempty" yaml:"isolatedMargin,omitempty"` IsolatedMarginSymbol string `json:"isolatedMarginSymbol,omitempty" yaml:"isolatedMarginSymbol,omitempty"` }
type SessionBasedRiskControl ¶
type SessionBasedRiskControl struct {
OrderExecutor *RiskControlOrderExecutor `json:"orderExecutor,omitempty" yaml:"orderExecutor"`
}
func (*SessionBasedRiskControl) SetBaseOrderExecutor ¶
func (control *SessionBasedRiskControl) SetBaseOrderExecutor(executor *ExchangeOrderExecutor)
type ShutdownHandler ¶ added in v1.38.0
type SilentLogger ¶
type SilentLogger struct{}
func (*SilentLogger) Errorf ¶
func (logger *SilentLogger) Errorf(string, ...interface{})
func (*SilentLogger) Infof ¶
func (logger *SilentLogger) Infof(string, ...interface{})
func (*SilentLogger) Warnf ¶
func (logger *SilentLogger) Warnf(string, ...interface{})
type SimpleInteraction ¶ added in v1.39.0
type SimpleInteraction struct { Command string Description string F interface{} Cmd *interact.Command }
func (*SimpleInteraction) Commands ¶ added in v1.39.0
func (it *SimpleInteraction) Commands(i *interact.Interact)
type SimpleOrderExecutor ¶ added in v1.52.0
type SimpleOrderExecutor struct { BaseOrderExecutor // contains filtered or unexported fields }
SimpleOrderExecutor implements the minimal order executor This order executor does not handle position and profit stats update
func NewSimpleOrderExecutor ¶ added in v1.52.0
func NewSimpleOrderExecutor(session *ExchangeSession) *SimpleOrderExecutor
func (*SimpleOrderExecutor) Bind ¶ added in v1.52.0
func (e *SimpleOrderExecutor) Bind()
func (*SimpleOrderExecutor) CancelOrders ¶ added in v1.52.0
CancelOrders cancels the given order objects directly
func (*SimpleOrderExecutor) SubmitOrders ¶ added in v1.52.0
func (e *SimpleOrderExecutor) SubmitOrders(ctx context.Context, submitOrders ...types.SubmitOrder) (types.OrderSlice, error)
type SingleExchangeStrategy ¶
type SingleExchangeStrategy interface { StrategyID Run(ctx context.Context, orderExecutor OrderExecutor, session *ExchangeSession) error }
SingleExchangeStrategy represents the single Exchange strategy
func NewStrategyFromMap ¶ added in v1.11.0
func NewStrategyFromMap(id string, conf interface{}) (SingleExchangeStrategy, error)
type SlackNotification ¶
type SlackNotificationRouting ¶ added in v1.12.0
type SlideRule ¶ added in v1.13.0
type SlideRule struct { // Scale type could be one of "log", "exp", "linear", "quadratic" // this is similar to the d3.scale LinearScale *LinearScale `json:"linear"` LogScale *LogarithmicScale `json:"log"` ExpScale *ExponentialScale `json:"exp"` QuadraticScale *QuadraticScale `json:"quadratic"` }
type SourceFunc ¶ added in v1.40.3
type SourceFunc func(*types.KLine) fixedpoint.Value
type SourceSelector ¶ added in v1.40.3
type SourceSelector struct {
Source selectorInternal `json:"source,omitempty"`
}
func (*SourceSelector) GetSource ¶ added in v1.40.3
func (s *SourceSelector) GetSource(kline *types.KLine) fixedpoint.Value
lazy init if empty struct is passed in
type StandardIndicatorSet ¶
type StandardIndicatorSet struct { Symbol string // contains filtered or unexported fields }
func NewStandardIndicatorSet ¶
func NewStandardIndicatorSet(symbol string, stream types.Stream, store *MarketDataStore) *StandardIndicatorSet
func (*StandardIndicatorSet) ATR ¶ added in v1.38.0
func (s *StandardIndicatorSet) ATR(iw types.IntervalWindow) *indicator.ATR
func (*StandardIndicatorSet) ATRP ¶ added in v1.38.0
func (s *StandardIndicatorSet) ATRP(iw types.IntervalWindow) *indicator.ATRP
func (*StandardIndicatorSet) BOLL ¶
func (s *StandardIndicatorSet) BOLL(iw types.IntervalWindow, bandWidth float64) *indicator.BOLL
BOLL returns the bollinger band indicator of the given interval, the window and bandwidth
func (*StandardIndicatorSet) CCI ¶ added in v1.38.0
func (s *StandardIndicatorSet) CCI(iw types.IntervalWindow) *indicator.CCI
func (*StandardIndicatorSet) EMV ¶ added in v1.38.0
func (s *StandardIndicatorSet) EMV(iw types.IntervalWindow) *indicator.EMV
func (*StandardIndicatorSet) EWMA ¶
func (s *StandardIndicatorSet) EWMA(iw types.IntervalWindow) *indicator.EWMA
EWMA is a helper function that returns the exponential weighed moving average indicator of the given interval and the window size.
func (*StandardIndicatorSet) GHFilter ¶ added in v1.40.2
func (s *StandardIndicatorSet) GHFilter(iw types.IntervalWindow) *indicator.GHFilter
GHFilter is a helper function that returns the G-H (alpha beta) digital filter of the given interval and the window size.
func (*StandardIndicatorSet) HULL ¶ added in v1.38.0
func (s *StandardIndicatorSet) HULL(iw types.IntervalWindow) *indicator.HULL
func (*StandardIndicatorSet) KalmanFilter ¶ added in v1.40.2
func (s *StandardIndicatorSet) KalmanFilter(iw types.IntervalWindow) *indicator.KalmanFilter
KalmanFilter is a helper function that returns the Kalman digital filter of the given interval and the window size. Note that the additional smooth window is set to zero in standard indicator set. Users have to create their own instance and push K-lines if a smoother filter is needed.
func (*StandardIndicatorSet) MACD ¶ added in v1.41.0
func (s *StandardIndicatorSet) MACD(iw types.IntervalWindow, shortPeriod, longPeriod int) *indicator.MACDLegacy
func (*StandardIndicatorSet) PivotHigh ¶ added in v1.40.0
func (s *StandardIndicatorSet) PivotHigh(iw types.IntervalWindow) *indicator.PivotHigh
func (*StandardIndicatorSet) PivotLow ¶ added in v1.38.0
func (s *StandardIndicatorSet) PivotLow(iw types.IntervalWindow) *indicator.PivotLow
func (*StandardIndicatorSet) RSI ¶ added in v1.44.0
func (s *StandardIndicatorSet) RSI(iw types.IntervalWindow) *indicator.RSI
func (*StandardIndicatorSet) SMA ¶
func (s *StandardIndicatorSet) SMA(iw types.IntervalWindow) *indicator.SMA
SMA is a helper function that returns the simple moving average indicator of the given interval and the window size.
func (*StandardIndicatorSet) STOCH ¶ added in v1.17.0
func (s *StandardIndicatorSet) STOCH(iw types.IntervalWindow) *indicator.STOCH
func (*StandardIndicatorSet) VWMA ¶ added in v1.40.0
func (s *StandardIndicatorSet) VWMA(iw types.IntervalWindow) *indicator.VWMA
VWMA
type StopEMA ¶ added in v1.40.0
type StopEMA struct { types.IntervalWindow Range fixedpoint.Value `json:"range"` // contains filtered or unexported fields }
func (*StopEMA) Allowed ¶ added in v1.40.0
func (s *StopEMA) Allowed(closePrice fixedpoint.Value) bool
func (*StopEMA) Bind ¶ added in v1.40.0
func (s *StopEMA) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
type StrategyController ¶ added in v1.29.0
type StrategyController struct { Status types.StrategyStatus // contains filtered or unexported fields }
func (*StrategyController) EmergencyStop ¶ added in v1.31.0
func (s *StrategyController) EmergencyStop() error
func (*StrategyController) EmitEmergencyStop ¶ added in v1.31.0
func (s *StrategyController) EmitEmergencyStop()
func (*StrategyController) EmitResume ¶ added in v1.31.0
func (s *StrategyController) EmitResume()
func (*StrategyController) EmitSuspend ¶ added in v1.31.0
func (s *StrategyController) EmitSuspend()
func (*StrategyController) GetStatus ¶ added in v1.31.0
func (s *StrategyController) GetStatus() types.StrategyStatus
func (*StrategyController) OnEmergencyStop ¶ added in v1.31.0
func (s *StrategyController) OnEmergencyStop(cb func())
func (*StrategyController) OnResume ¶ added in v1.31.0
func (s *StrategyController) OnResume(cb func())
func (*StrategyController) OnSuspend ¶ added in v1.31.0
func (s *StrategyController) OnSuspend(cb func())
func (*StrategyController) Resume ¶ added in v1.31.0
func (s *StrategyController) Resume() error
func (*StrategyController) Suspend ¶ added in v1.31.0
func (s *StrategyController) Suspend() error
type StrategyControllerEventHub ¶ added in v1.36.0
type StrategyControllerEventHub interface { OnSuspend(cb func()) OnResume(cb func()) OnEmergencyStop(cb func()) }
type StrategyDefaulter ¶ added in v1.38.0
type StrategyDefaulter interface {
Defaults() error
}
type StrategyID ¶ added in v1.33.0
type StrategyID interface {
ID() string
}
Strategy method calls: -> Defaults() (optional method)
setup default static values from constants
-> Initialize() (optional method)
initialize dynamic runtime objects
-> Subscribe()
register the subscriptions
-> Validate() (optional method) -> Run() (optional method) -> Shutdown(shutdownCtx context.Context, wg *sync.WaitGroup)
type StrategyInitializer ¶ added in v1.28.0
type StrategyInitializer interface {
Initialize() error
}
StrategyInitializer's Initialize method is called before the Subscribe method call.
type StrategyShutdown ¶ added in v1.38.0
type StrategyStatusReader ¶ added in v1.31.0
type StrategyStatusReader interface {
GetStatus() types.StrategyStatus
}
type StrategyToggler ¶ added in v1.31.0
type StrategyToggler interface { StrategyStatusReader Suspend() error Resume() error }
type StrategyValidator ¶ added in v1.38.0
type StrategyValidator interface {
Validate() error
}
type SupportTakeProfit ¶ added in v1.40.0
type SupportTakeProfit struct { Symbol string types.IntervalWindow Ratio fixedpoint.Value `json:"ratio"` // contains filtered or unexported fields }
SupportTakeProfit finds the previous support price and take profit at the previous low.
func (*SupportTakeProfit) Bind ¶ added in v1.40.0
func (s *SupportTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*SupportTakeProfit) Subscribe ¶ added in v1.40.0
func (s *SupportTakeProfit) Subscribe(session *ExchangeSession)
type SymbolBasedRiskController ¶
type SymbolBasedRiskController struct {
BasicRiskController *BasicRiskController `json:"basic,omitempty" yaml:"basic,omitempty"`
}
type SyncConfig ¶ added in v1.27.0
type SyncConfig struct { // Sessions to sync, if ignored, all defined sessions will sync Sessions []string `json:"sessions,omitempty" yaml:"sessions,omitempty"` // Symbols is the list of session:symbol pair to sync, if ignored, symbols wlll be discovered by your existing crypto balances // Valid formats are: {session}:{symbol}, {symbol} or in YAML object form {symbol: "BTCUSDT", session:"max" } Symbols []SyncSymbol `json:"symbols,omitempty" yaml:"symbols,omitempty"` // DepositHistory is for syncing deposit history DepositHistory bool `json:"depositHistory" yaml:"depositHistory"` // WithdrawHistory is for syncing withdraw history WithdrawHistory bool `json:"withdrawHistory" yaml:"withdrawHistory"` // RewardHistory is for syncing reward history RewardHistory bool `json:"rewardHistory" yaml:"rewardHistory"` // MarginHistory is for syncing margin related history: loans, repays, interests and liquidations MarginHistory bool `json:"marginHistory" yaml:"marginHistory"` MarginAssets []string `json:"marginAssets" yaml:"marginAssets"` // Since is the date where you want to start syncing data Since *types.LooseFormatTime `json:"since,omitempty"` // UserDataStream is for real-time sync with websocket user data stream UserDataStream *struct { Trades bool `json:"trades,omitempty" yaml:"trades,omitempty"` FilledOrders bool `json:"filledOrders,omitempty" yaml:"filledOrders,omitempty"` } `json:"userDataStream,omitempty" yaml:"userDataStream,omitempty"` }
type SyncStatus ¶ added in v1.12.0
type SyncStatus int
const ( SyncNotStarted SyncStatus = iota Syncing SyncDone )
type SyncSymbol ¶ added in v1.34.0
type SyncSymbol struct { Symbol string `json:"symbol" yaml:"symbol"` Session string `json:"session" yaml:"session"` }
func (*SyncSymbol) UnmarshalYAML ¶ added in v1.34.0
func (ss *SyncSymbol) UnmarshalYAML(unmarshal func(a interface{}) error) (err error)
type TelegramNotification ¶ added in v1.18.0
type TelegramNotification struct {
Broadcast bool `json:"broadcast" yaml:"broadcast"`
}
type TradeReporter ¶
type TradeReporter struct {
*Notifiability
}
type Trader ¶
type Trader struct {
// contains filtered or unexported fields
}
func NewTrader ¶
func NewTrader(environ *Environment) *Trader
func (*Trader) AttachCrossExchangeStrategy ¶
func (trader *Trader) AttachCrossExchangeStrategy(strategy CrossExchangeStrategy) *Trader
AttachCrossExchangeStrategy attaches the cross exchange strategy
func (*Trader) AttachStrategyOn ¶
func (trader *Trader) AttachStrategyOn(session string, strategies ...SingleExchangeStrategy) error
AttachStrategyOn attaches the single exchange strategy on an exchange Session. Single exchange strategy is the default behavior.
func (*Trader) DisableLogging ¶
func (trader *Trader) DisableLogging()
func (*Trader) EnableLogging ¶
func (trader *Trader) EnableLogging()
func (*Trader) Initialize ¶ added in v1.55.2
Initialize initializes the strategies, this method is called before the Run method. It sets the default values and validates the strategy configurations. And calls the Initialize method if the strategy implements the Initialize method.
func (*Trader) IterateStrategies ¶ added in v1.33.0
func (trader *Trader) IterateStrategies(f func(st StrategyID) error) error
func (*Trader) RunAllSingleExchangeStrategy ¶ added in v1.11.1
func (*Trader) RunSingleExchangeStrategy ¶ added in v1.11.1
func (trader *Trader) RunSingleExchangeStrategy( ctx context.Context, strategy SingleExchangeStrategy, session *ExchangeSession, orderExecutor OrderExecutor, ) error
func (*Trader) SaveState ¶ added in v1.33.0
NOTICE: the ctx here is the trading context, which could already be canceled.
func (*Trader) SetRiskControls ¶
func (trader *Trader) SetRiskControls(riskControls *RiskControls)
SetRiskControls sets the risk controller TODO: provide a more DSL way to configure risk controls
type TrailingStop2 ¶ added in v1.36.0
type TrailingStop2 struct { Symbol string // CallbackRate is the callback rate from the previous high price CallbackRate fixedpoint.Value `json:"callbackRate,omitempty"` ActivationRatio fixedpoint.Value `json:"activationRatio,omitempty"` // ClosePosition is a percentage of the position to be closed ClosePosition fixedpoint.Value `json:"closePosition,omitempty"` // MinProfit is the percentage of the minimum profit ratio. // Stop order will be activated only when the price reaches above this threshold. MinProfit fixedpoint.Value `json:"minProfit,omitempty"` // Interval is the time resolution to update the stop order // KLine per Interval will be used for updating the stop order Interval types.Interval `json:"interval,omitempty"` Side types.SideType `json:"side,omitempty"` // contains filtered or unexported fields }
func (*TrailingStop2) Bind ¶ added in v1.36.0
func (s *TrailingStop2) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*TrailingStop2) Subscribe ¶ added in v1.36.0
func (s *TrailingStop2) Subscribe(session *ExchangeSession)
type TrendEMA ¶ added in v1.40.0
type TrendEMA struct { types.IntervalWindow // MaxGradient is the maximum gradient allowed for the entry. MaxGradient float64 `json:"maxGradient"` MinGradient float64 `json:"minGradient"` // contains filtered or unexported fields }
func (*TrendEMA) Bind ¶ added in v1.40.0
func (s *TrendEMA) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)
func (*TrendEMA) GradientAllowed ¶ added in v1.40.0
Source Files ¶
- activeorderbook.go
- activeorderbook_callbacks.go
- backtestfeemode_enumer.go
- bootstrap.go
- builder.go
- config.go
- consts.go
- doc.go
- environment.go
- envvar.go
- errors.go
- exchangeorderexecutor_callbacks.go
- exit.go
- exit_cumulated_volume_take_profit.go
- exit_hh_ll_stop.go
- exit_lower_shadow_take_profit.go
- exit_protective_stop_loss.go
- exit_roi_stop_loss.go
- exit_roi_take_profit.go
- exit_support_take_profit.go
- exit_trailing_stop.go
- graceful_shutdown.go
- gracefulshutdown_callbacks.go
- indicator_set.go
- interact.go
- interact_modify.go
- isolation.go
- log.go
- marketdatastore.go
- marketdatastore_callbacks.go
- metrics.go
- moving_average_settings.go
- notification.go
- order_execution.go
- order_executor_fast.go
- order_executor_general.go
- order_executor_simple.go
- order_processor.go
- persistence.go
- profitstats.go
- quantity_amount.go
- quota.go
- reflect.go
- reporter.go
- risk.go
- risk_controls.go
- scale.go
- serialmarketdatastore.go
- session.go
- source.go
- standard_indicator_set.go
- stop_ema.go
- strategy_controller.go
- strategycontroller_callbacks.go
- string.go
- time.go
- trader.go
- trend_ema.go
- wrapper.go