Documentation ¶
Index ¶
- Constants
- Variables
- func Build(ctx context.Context, userConfig *Config, targetConfig BuildTargetConfig) (string, error)
- func BuildTarget(ctx context.Context, userConfig *Config, target BuildTargetConfig) (string, error)
- func CacheDir() string
- func HomeDir() string
- func LoadExchangeMarketsWithCache(ctx context.Context, ex types.Exchange) (markets types.MarketMap, err error)
- func RegisterStrategy(key string, s interface{})
- func SetWrapperBinary()
- func SourceDir() string
- func WithCache(key string, obj interface{}, fetcher DataFetcher) error
- type AverageCostPnLReporter
- type Backtest
- type BacktestAccount
- type BacktestAccountBalanceMap
- type BasicRiskController
- type BuildConfig
- type BuildTargetConfig
- type Config
- type Context
- type CrossExchangeSessionSubscriber
- type CrossExchangeStrategy
- type DataFetcher
- 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) ConfigureDatabase(ctx context.Context) error
- func (environ *Environment) ConfigureDatabaseDriver(ctx context.Context, driver string, dsn string) error
- func (environ *Environment) ConfigureExchangeSessions(userConfig *Config) error
- func (environ *Environment) ConfigureNotificationRouting(conf *NotificationConfig) error
- func (environ *Environment) ConfigureNotificationSystem(userConfig *Config) error
- func (environ *Environment) ConfigurePersistence(conf *PersistenceConfig) error
- func (environ *Environment) Connect(ctx context.Context) error
- func (environ *Environment) Init(ctx context.Context) (err error)
- func (environ *Environment) IsSyncing() (status SyncStatus)
- 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) SetStartTime(t time.Time) *Environment
- func (environ *Environment) SetSyncStartTime(t time.Time) *Environment
- func (environ *Environment) Sync(ctx context.Context) error
- func (environ *Environment) SyncSession(ctx context.Context, session *ExchangeSession, defaultSymbols ...string) error
- type ExchangeOrderExecutionRouter
- type ExchangeOrderExecutor
- 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) FindPossibleSymbols() (symbols []string, err error)
- func (session *ExchangeSession) FormatOrder(order types.SubmitOrder) (types.SubmitOrder, error)
- func (session *ExchangeSession) Init(ctx context.Context, environ *Environment) error
- func (session *ExchangeSession) InitSymbol(ctx context.Context, environ *Environment, symbol string) error
- func (session *ExchangeSession) InitSymbols(ctx context.Context, environ *Environment) error
- func (session *ExchangeSession) LastPrice(symbol string) (price float64, ok bool)
- func (session *ExchangeSession) LastPrices() map[string]float64
- 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() map[string]types.Market
- func (session *ExchangeSession) OrderStore(symbol string) (store *OrderStore, ok bool)
- func (session *ExchangeSession) OrderStores() map[string]*OrderStore
- func (session *ExchangeSession) Position(symbol string) (pos *Position, ok bool)
- func (session *ExchangeSession) Positions() map[string]*Position
- func (session *ExchangeSession) StandardIndicatorSet(symbol string) (*StandardIndicatorSet, bool)
- func (session *ExchangeSession) StartPrice(symbol string) (price float64, ok bool)
- func (session *ExchangeSession) Subscribe(channel types.Channel, symbol string, options types.SubscribeOptions) *ExchangeSession
- func (session *ExchangeSession) UpdatePrices(ctx context.Context) (err error)
- type ExchangeSessionSubscriber
- type ExchangeStrategyMount
- type ExponentialScale
- type Graceful
- type LinearScale
- type LocalActiveOrderBook
- func (b *LocalActiveOrderBook) Add(orders ...types.Order)
- func (b *LocalActiveOrderBook) Backup() []types.SubmitOrder
- func (b *LocalActiveOrderBook) BindStream(stream types.Stream)
- func (b *LocalActiveOrderBook) EmitFilled(o types.Order)
- func (b *LocalActiveOrderBook) MarshalJSON() ([]byte, error)
- func (b *LocalActiveOrderBook) NumOfAsks() int
- func (b *LocalActiveOrderBook) NumOfBids() int
- func (b *LocalActiveOrderBook) OnFilled(cb func(o types.Order))
- func (b *LocalActiveOrderBook) Orders() types.OrderSlice
- func (b *LocalActiveOrderBook) Print()
- func (b *LocalActiveOrderBook) Remove(order types.Order) bool
- func (b *LocalActiveOrderBook) Update(orders ...types.Order)
- func (b *LocalActiveOrderBook) WriteOff(order types.Order) bool
- type LogarithmicScale
- type Logger
- type Logging
- type MarketDataStore
- func (store *MarketDataStore) AddKLine(kline types.KLine)
- func (store *MarketDataStore) BindStream(stream types.Stream)
- func (store *MarketDataStore) EmitKLineWindowUpdate(interval types.Interval, kline types.KLineWindow)
- func (store *MarketDataStore) EmitOrderBookUpdate(orderBook *types.StreamOrderBook)
- func (store *MarketDataStore) KLinesOfInterval(interval types.Interval) (kLines types.KLineWindow, ok bool)
- func (store *MarketDataStore) OnKLineWindowUpdate(cb func(interval types.Interval, kline types.KLineWindow))
- func (store *MarketDataStore) OnOrderBookUpdate(cb func(orderBook *types.StreamOrderBook))
- func (store *MarketDataStore) OrderBook() types.OrderBook
- func (store *MarketDataStore) SetKLineWindows(windows map[types.Interval]types.KLineWindow)
- type Notifiability
- func (m *Notifiability) AddNotifier(notifier Notifier)
- func (m *Notifiability) Notify(format string, args ...interface{})
- func (m *Notifiability) NotifyTo(channel, format string, 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)
- type NotificationConfig
- type Notifier
- type NullNotifier
- type ObjectChannelHandler
- type ObjectChannelRouter
- type OrderExecutionRouter
- type OrderExecutor
- type OrderStore
- type PatternChannelRouter
- type Persistence
- type PersistenceConfig
- type PersistenceSelector
- type PnLReporter
- type PnLReporterConfig
- type PnLReporterManager
- type Position
- type PriceVolumeScale
- type QuadraticScale
- type Quota
- type QuotaTransaction
- type RiskControlOrderExecutor
- type RiskControls
- type Scale
- type Session
- type SessionBasedRiskControl
- type SilentLogger
- type SingleExchangeStrategy
- type SlackNotification
- type SlackNotificationRouting
- type SlideRule
- type StandardIndicatorSet
- type Stash
- type SymbolBasedRiskController
- type SyncStatus
- 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) ReportPnL() *PnLReporterManager
- 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) SetRiskControls(riskControls *RiskControls)
- func (trader *Trader) Subscribe()
- type Validator
Constants ¶
const TemplateOrderReport = `:handshake: {{ .Symbol }} {{ .Side }} Order Update @ {{ .Price }}`
const TemplateTradeReport = `:handshake: {{ .Symbol }} {{ .Side }} Trade Execution @ {{ .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 ErrSessionAlreadyInitialized = errors.New("session is already initialized")
var IsWrapperBinary = false
var LoadedCrossExchangeStrategies = make(map[string]CrossExchangeStrategy)
var LoadedExchangeStrategies = make(map[string]SingleExchangeStrategy)
var SupportedExchanges = []types.ExchangeName{"binance", "max", "ftx"}
Functions ¶
func BuildTarget ¶
func RegisterStrategy ¶
func RegisterStrategy(key string, s interface{})
func SetWrapperBinary ¶
func SetWrapperBinary()
func WithCache ¶
func WithCache(key string, obj interface{}, fetcher DataFetcher) error
WithCache let you use the cache with the given cache key, variable reference and your data fetcher, The key must be an unique ID. obj is the pointer of your local variable fetcher is the closure that will fetch your remote data or some slow operation.
Types ¶
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 Backtest ¶
type Backtest struct { StartTime string `json:"startTime" yaml:"startTime"` EndTime string `json:"endTime" yaml:"endTime"` Account BacktestAccount `json:"account" yaml:"account"` Symbols []string `json:"symbols" yaml:"symbols"` }
type BacktestAccount ¶
type BacktestAccount struct { MakerCommission fixedpoint.Value `json:"makerCommission"` TakerCommission fixedpoint.Value `json:"takerCommission"` BuyerCommission int `json:"buyerCommission"` SellerCommission int `json:"sellerCommission"` Balances BacktestAccountBalanceMap `json:"balances" yaml:"balances"` }
type BacktestAccountBalanceMap ¶
type BacktestAccountBalanceMap map[string]fixedpoint.Value
func (BacktestAccountBalanceMap) BalanceMap ¶
func (m BacktestAccountBalanceMap) BalanceMap() types.BalanceMap
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 ¶
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 ¶
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 ¶
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"` Notifications *NotificationConfig `json:"notifications,omitempty" yaml:"notifications,omitempty"` Persistence *PersistenceConfig `json:"persistence,omitempty" yaml:"persistence,omitempty"` Sessions map[string]*ExchangeSession `json:"sessions,omitempty" yaml:"sessions,omitempty"` RiskControls *RiskControls `json:"riskControls,omitempty" yaml:"riskControls,omitempty"` ExchangeStrategies []ExchangeStrategyMount `json:"-" yaml:"-"` CrossExchangeStrategies []CrossExchangeStrategy `json:"-" yaml:"-"` PnLReporters []PnLReporterConfig `json:"reportPnL,omitempty" yaml:"reportPnL,omitempty"` }
func LoadBuildConfig ¶
type CrossExchangeSessionSubscriber ¶
type CrossExchangeSessionSubscriber interface {
CrossSubscribe(sessions map[string]*ExchangeSession)
}
type CrossExchangeStrategy ¶
type CrossExchangeStrategy interface { ID() string CrossRun(ctx context.Context, orderExecutionRouter OrderExecutionRouter, sessions map[string]*ExchangeSession) error }
type DataFetcher ¶
type DataFetcher func() (interface{}, error)
type Environment ¶
type Environment struct { // Notifiability here for environment is for the streaming data notification // note that, for back tests, we don't need notification. Notifiability PersistenceServiceFacade *service.PersistenceServiceFacade DatabaseService *service.DatabaseService OrderService *service.OrderService TradeService *service.TradeService RewardService *service.RewardService SyncService *service.SyncService // 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 ¶
func (environ *Environment) AddExchangeSession(name string, session *ExchangeSession) *ExchangeSession
AddExchangeSession adds the existing exchange session or pre-created exchange session
func (*Environment) AddExchangesByViperKeys ¶
func (environ *Environment) AddExchangesByViperKeys() error
func (*Environment) AddExchangesFromSessionConfig ¶
func (environ *Environment) AddExchangesFromSessionConfig(sessions map[string]*ExchangeSession) error
func (*Environment) ConfigureDatabase ¶
func (environ *Environment) ConfigureDatabase(ctx context.Context) error
func (*Environment) ConfigureDatabaseDriver ¶
func (*Environment) ConfigureExchangeSessions ¶
func (environ *Environment) ConfigureExchangeSessions(userConfig *Config) error
func (*Environment) ConfigureNotificationRouting ¶
func (environ *Environment) ConfigureNotificationRouting(conf *NotificationConfig) error
configure notification rules for symbol-based routes, we should register the same symbol rules for each session. for session-based routes, we should set the fixed callbacks for each session
func (*Environment) ConfigureNotificationSystem ¶
func (environ *Environment) ConfigureNotificationSystem(userConfig *Config) error
func (*Environment) ConfigurePersistence ¶
func (environ *Environment) ConfigurePersistence(conf *PersistenceConfig) 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) IsSyncing ¶
func (environ *Environment) IsSyncing() (status SyncStatus)
func (*Environment) SelectSessions ¶
func (environ *Environment) SelectSessions(names ...string) map[string]*ExchangeSession
func (*Environment) Session ¶
func (environ *Environment) Session(name string) (*ExchangeSession, bool)
func (*Environment) Sessions ¶
func (environ *Environment) Sessions() map[string]*ExchangeSession
func (*Environment) SetStartTime ¶
func (environ *Environment) SetStartTime(t time.Time) *Environment
func (*Environment) SetSyncStartTime ¶
func (environ *Environment) SetSyncStartTime(t time.Time) *Environment
SetSyncStartTime overrides the default trade scan time (-7 days)
func (*Environment) Sync ¶
func (environ *Environment) Sync(ctx context.Context) error
Sync syncs all registered exchange sessions
func (*Environment) SyncSession ¶
func (environ *Environment) SyncSession(ctx context.Context, session *ExchangeSession, defaultSymbols ...string) error
type ExchangeOrderExecutionRouter ¶
type ExchangeOrderExecutionRouter struct { Notifiability // contains filtered or unexported fields }
func (*ExchangeOrderExecutionRouter) SubmitOrdersTo ¶
func (e *ExchangeOrderExecutionRouter) SubmitOrdersTo(ctx context.Context, session string, orders ...types.SubmitOrder) (types.OrderSlice, error)
type ExchangeOrderExecutor ¶
type ExchangeOrderExecutor struct { Notifiability `json:"-"` Session *ExchangeSession // contains filtered or unexported fields }
ExchangeOrderExecutor is an order executor wrapper for single exchange instance.
func (*ExchangeOrderExecutor) EmitOrderUpdate ¶
func (e *ExchangeOrderExecutor) EmitOrderUpdate(order types.Order)
func (*ExchangeOrderExecutor) EmitTradeUpdate ¶
func (e *ExchangeOrderExecutor) EmitTradeUpdate(trade types.Trade)
func (*ExchangeOrderExecutor) OnOrderUpdate ¶
func (e *ExchangeOrderExecutor) OnOrderUpdate(cb func(order types.Order))
func (*ExchangeOrderExecutor) OnTradeUpdate ¶
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 based notification system // we make it as a value field so that we can configure it separately Notifiability `json:"-" yaml:"-"` // Exchange Session name 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"` SubAccount string `json:"subAccount,omitempty" yaml:"subAccount,omitempty"` PublicOnly bool `json:"publicOnly,omitempty" yaml:"publicOnly"` Margin bool `json:"margin,omitempty" yaml:"margin"` IsolatedMargin bool `json:"isolatedMargin,omitempty" yaml:"isolatedMargin,omitempty"` IsolatedMarginSymbol string `json:"isolatedMarginSymbol,omitempty" yaml:"isolatedMarginSymbol,omitempty"` // The exchange account states Account *types.Account `json:"-" yaml:"-"` IsInitialized bool `json:"-" yaml:"-"` // Stream is the connection stream of the exchange Stream types.Stream `json:"-" yaml:"-"` Subscriptions map[types.Subscription]types.Subscription `json:"-" yaml:"-"` Exchange types.Exchange `json:"-" yaml:"-"` // 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 NewExchangeSessionFromConfig ¶
func NewExchangeSessionFromConfig(name string, sessionConfig *ExchangeSession) (*ExchangeSession, error)
func (*ExchangeSession) FindPossibleSymbols ¶
func (session *ExchangeSession) FindPossibleSymbols() (symbols []string, err error)
func (*ExchangeSession) FormatOrder ¶
func (session *ExchangeSession) FormatOrder(order types.SubmitOrder) (types.SubmitOrder, error)
func (*ExchangeSession) Init ¶
func (session *ExchangeSession) Init(ctx context.Context, environ *Environment) error
func (*ExchangeSession) InitSymbol ¶
func (session *ExchangeSession) InitSymbol(ctx context.Context, environ *Environment, symbol string) error
InitSymbol loads trades for the symbol, bind stream callbacks, init positions, market data store. please note, InitSymbol can not be called for the same symbol for twice
func (*ExchangeSession) InitSymbols ¶
func (session *ExchangeSession) InitSymbols(ctx context.Context, environ *Environment) error
InitSymbols uses usedSymbols to initialize the related data structure
func (*ExchangeSession) LastPrice ¶
func (session *ExchangeSession) LastPrice(symbol string) (price float64, ok bool)
func (*ExchangeSession) LastPrices ¶
func (session *ExchangeSession) LastPrices() map[string]float64
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) OrderStore ¶
func (session *ExchangeSession) OrderStore(symbol string) (store *OrderStore, ok bool)
func (*ExchangeSession) OrderStores ¶
func (session *ExchangeSession) OrderStores() map[string]*OrderStore
func (*ExchangeSession) Position ¶
func (session *ExchangeSession) Position(symbol string) (pos *Position, ok bool)
func (*ExchangeSession) Positions ¶
func (session *ExchangeSession) Positions() map[string]*Position
func (*ExchangeSession) StandardIndicatorSet ¶
func (session *ExchangeSession) StandardIndicatorSet(symbol string) (*StandardIndicatorSet, bool)
func (*ExchangeSession) StartPrice ¶
func (session *ExchangeSession) StartPrice(symbol string) (price float64, 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) UpdatePrices ¶
func (session *ExchangeSession) UpdatePrices(ctx context.Context) (err error)
type ExchangeSessionSubscriber ¶
type ExchangeSessionSubscriber interface {
Subscribe(session *ExchangeSession)
}
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 ¶
func (m *ExchangeStrategyMount) Map() (map[string]interface{}, error)
type ExponentialScale ¶
type ExponentialScale struct { Domain [2]float64 `json:"domain"` Range [2]float64 `json:"range"` // contains filtered or unexported fields }
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 ¶
func (s *ExponentialScale) Call(x float64) (y float64)
func (*ExponentialScale) Formula ¶
func (s *ExponentialScale) Formula() string
func (*ExponentialScale) FormulaOf ¶
func (s *ExponentialScale) FormulaOf(x float64) string
func (*ExponentialScale) Solve ¶
func (s *ExponentialScale) Solve() error
func (*ExponentialScale) String ¶
func (s *ExponentialScale) String() string
type Graceful ¶
type Graceful struct {
// contains filtered or unexported fields
}
func (*Graceful) EmitShutdown ¶
func (*Graceful) OnShutdown ¶
type LinearScale ¶
type LinearScale struct { Domain [2]float64 `json:"domain"` Range [2]float64 `json:"range"` // contains filtered or unexported fields }
func (*LinearScale) Call ¶
func (s *LinearScale) Call(x float64) (y float64)
func (*LinearScale) Formula ¶
func (s *LinearScale) Formula() string
func (*LinearScale) FormulaOf ¶
func (s *LinearScale) FormulaOf(x float64) string
func (*LinearScale) Solve ¶
func (s *LinearScale) Solve() error
func (*LinearScale) String ¶
func (s *LinearScale) String() string
type LocalActiveOrderBook ¶
type LocalActiveOrderBook struct { Bids *types.SyncOrderMap Asks *types.SyncOrderMap // contains filtered or unexported fields }
LocalActiveOrderBook manages the local active order books.
func NewLocalActiveOrderBook ¶
func NewLocalActiveOrderBook() *LocalActiveOrderBook
func (*LocalActiveOrderBook) Add ¶
func (b *LocalActiveOrderBook) Add(orders ...types.Order)
func (*LocalActiveOrderBook) Backup ¶
func (b *LocalActiveOrderBook) Backup() []types.SubmitOrder
func (*LocalActiveOrderBook) BindStream ¶
func (b *LocalActiveOrderBook) BindStream(stream types.Stream)
func (*LocalActiveOrderBook) EmitFilled ¶
func (b *LocalActiveOrderBook) EmitFilled(o types.Order)
func (*LocalActiveOrderBook) MarshalJSON ¶
func (b *LocalActiveOrderBook) MarshalJSON() ([]byte, error)
func (*LocalActiveOrderBook) NumOfAsks ¶
func (b *LocalActiveOrderBook) NumOfAsks() int
func (*LocalActiveOrderBook) NumOfBids ¶
func (b *LocalActiveOrderBook) NumOfBids() int
func (*LocalActiveOrderBook) OnFilled ¶
func (b *LocalActiveOrderBook) OnFilled(cb func(o types.Order))
func (*LocalActiveOrderBook) Orders ¶
func (b *LocalActiveOrderBook) Orders() types.OrderSlice
func (*LocalActiveOrderBook) Print ¶
func (b *LocalActiveOrderBook) Print()
func (*LocalActiveOrderBook) Update ¶
func (b *LocalActiveOrderBook) Update(orders ...types.Order)
type LogarithmicScale ¶
type LogarithmicScale struct { Domain [2]float64 `json:"domain"` Range [2]float64 `json:"range"` // contains filtered or unexported fields }
func (*LogarithmicScale) Call ¶
func (s *LogarithmicScale) Call(x float64) (y float64)
func (*LogarithmicScale) Formula ¶
func (s *LogarithmicScale) Formula() string
func (*LogarithmicScale) FormulaOf ¶
func (s *LogarithmicScale) FormulaOf(x float64) string
func (*LogarithmicScale) Solve ¶
func (s *LogarithmicScale) Solve() error
func (*LogarithmicScale) String ¶
func (s *LogarithmicScale) String() string
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
func NewMarketDataStore ¶
func NewMarketDataStore(symbol string) *MarketDataStore
func (*MarketDataStore) AddKLine ¶
func (store *MarketDataStore) AddKLine(kline types.KLine)
func (*MarketDataStore) BindStream ¶
func (store *MarketDataStore) BindStream(stream types.Stream)
func (*MarketDataStore) EmitKLineWindowUpdate ¶
func (store *MarketDataStore) EmitKLineWindowUpdate(interval types.Interval, kline types.KLineWindow)
func (*MarketDataStore) EmitOrderBookUpdate ¶
func (store *MarketDataStore) EmitOrderBookUpdate(orderBook *types.StreamOrderBook)
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) OnKLineWindowUpdate ¶
func (store *MarketDataStore) OnKLineWindowUpdate(cb func(interval types.Interval, kline types.KLineWindow))
func (*MarketDataStore) OnOrderBookUpdate ¶
func (store *MarketDataStore) OnOrderBookUpdate(cb func(orderBook *types.StreamOrderBook))
func (*MarketDataStore) OrderBook ¶
func (store *MarketDataStore) OrderBook() types.OrderBook
func (*MarketDataStore) SetKLineWindows ¶
func (store *MarketDataStore) SetKLineWindows(windows map[types.Interval]types.KLineWindow)
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(format string, args ...interface{})
func (*Notifiability) NotifyTo ¶
func (m *Notifiability) NotifyTo(channel, format string, 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)
RouteSession routes symbol name to channel
type NotificationConfig ¶
type NotificationConfig struct { Slack *SlackNotification `json:"slack,omitempty" yaml:"slack,omitempty"` SymbolChannels map[string]string `json:"symbolChannels,omitempty" yaml:"symbolChannels,omitempty"` SessionChannels map[string]string `json:"sessionChannels,omitempty" yaml:"sessionChannels,omitempty"` Routing *SlackNotificationRouting `json:"routing,omitempty" yaml:"routing,omitempty"` }
type NullNotifier ¶
type NullNotifier struct{}
func (*NullNotifier) Notify ¶
func (n *NullNotifier) Notify(format string, args ...interface{})
func (*NullNotifier) NotifyTo ¶
func (n *NullNotifier) NotifyTo(channel, format string, args ...interface{})
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 OrderExecutionRouter ¶
type OrderExecutionRouter interface { // SubmitOrderTo submit order to a specific exchange Session SubmitOrdersTo(ctx context.Context, session string, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error) }
type OrderExecutor ¶
type OrderStore ¶
type OrderStore struct { Symbol string RemoveCancelled bool AddOrderUpdate bool // contains filtered or unexported fields }
func NewOrderStore ¶
func NewOrderStore(symbol string) *OrderStore
func (*OrderStore) Add ¶
func (s *OrderStore) Add(orders ...types.Order)
func (*OrderStore) BindStream ¶
func (s *OrderStore) BindStream(stream types.Stream)
func (*OrderStore) Exists ¶
func (s *OrderStore) Exists(oID uint64) (ok bool)
func (*OrderStore) Orders ¶
func (s *OrderStore) Orders() (orders []types.Order)
func (*OrderStore) Remove ¶
func (s *OrderStore) Remove(o types.Order)
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 Persistence ¶
type Persistence struct { PersistenceSelector *PersistenceSelector `json:"persistence,omitempty" yaml:"persistence,omitempty"` Facade *service.PersistenceServiceFacade `json:"-" yaml:"-"` }
Persistence is used for strategy to inject the persistence.
func (*Persistence) Load ¶
func (p *Persistence) Load(val interface{}, subIDs ...string) error
func (*Persistence) Save ¶
func (p *Persistence) Save(val interface{}, subIDs ...string) error
type PersistenceConfig ¶
type PersistenceConfig struct { Redis *service.RedisPersistenceConfig `json:"redis,omitempty" yaml:"redis,omitempty"` Json *service.JsonPersistenceConfig `json:"json,omitempty" yaml:"json,omitempty"` }
type PersistenceSelector ¶
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 Position ¶
type Position struct { Symbol string `json:"symbol"` BaseCurrency string `json:"baseCurrency"` QuoteCurrency string `json:"quoteCurrency"` Base fixedpoint.Value `json:"base"` Quote fixedpoint.Value `json:"quote"` AverageCost fixedpoint.Value `json:"averageCost"` }
func (*Position) BindStream ¶
type PriceVolumeScale ¶
type PriceVolumeScale struct { ByPrice *SlideRule `json:"byPrice"` ByVolume *SlideRule `json:"byVolume"` }
PriceVolumeScale defines the scale DSL for strategy, e.g.,
scaleQuantity:
byPrice: exp: domain: [10_000, 50_000] range: [0.01, 1.0]
and
scaleQuantity:
byVolume: linear: domain: [10_000, 50_000] range: [0.01, 1.0]
func (*PriceVolumeScale) Scale ¶
func (q *PriceVolumeScale) Scale(price float64, volume float64) (quantity float64, err error)
func (*PriceVolumeScale) ScaleByPrice ¶
func (q *PriceVolumeScale) ScaleByPrice(price float64) (float64, error)
ScaleByPrice scale quantity by the given price
func (*PriceVolumeScale) ScaleByVolume ¶
func (q *PriceVolumeScale) ScaleByVolume(volume float64) (float64, error)
ScaleByVolume scale quantity by the given volume
type QuadraticScale ¶
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 ¶
func (s *QuadraticScale) Call(x float64) (y float64)
func (*QuadraticScale) Formula ¶
func (s *QuadraticScale) Formula() string
func (*QuadraticScale) FormulaOf ¶
func (s *QuadraticScale) FormulaOf(x float64) string
func (*QuadraticScale) Solve ¶
func (s *QuadraticScale) Solve() error
func (*QuadraticScale) String ¶
func (s *QuadraticScale) String() string
type Quota ¶
type Quota struct { Available fixedpoint.Value Locked fixedpoint.Value // contains filtered or unexported fields }
func (*Quota) Add ¶
func (q *Quota) Add(fund fixedpoint.Value)
type QuotaTransaction ¶
type QuotaTransaction struct { BaseAsset Quota QuoteAsset Quota // contains filtered or unexported fields }
func (*QuotaTransaction) Commit ¶
func (m *QuotaTransaction) Commit() bool
func (*QuotaTransaction) Rollback ¶
func (m *QuotaTransaction) Rollback() bool
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 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 SilentLogger ¶
type SilentLogger struct{}
func (*SilentLogger) Errorf ¶
func (logger *SilentLogger) Errorf(message string, args ...interface{})
func (*SilentLogger) Infof ¶
func (logger *SilentLogger) Infof(message string, args ...interface{})
func (*SilentLogger) Warnf ¶
func (logger *SilentLogger) Warnf(message string, args ...interface{})
type SingleExchangeStrategy ¶
type SingleExchangeStrategy interface { ID() string Run(ctx context.Context, orderExecutor OrderExecutor, session *ExchangeSession) error }
SingleExchangeStrategy represents the single Exchange strategy
func NewStrategyFromMap ¶
func NewStrategyFromMap(id string, conf interface{}) (SingleExchangeStrategy, error)
type SlackNotification ¶
type SlideRule ¶
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 StandardIndicatorSet ¶
type StandardIndicatorSet struct { Symbol string // contains filtered or unexported fields }
func NewStandardIndicatorSet ¶
func NewStandardIndicatorSet(symbol string, store *MarketDataStore) *StandardIndicatorSet
func (*StandardIndicatorSet) BOLL ¶
func (set *StandardIndicatorSet) BOLL(iw types.IntervalWindow, bandWidth float64) *indicator.BOLL
BOLL returns the bollinger band indicator of the given interval and the window, Please note that the K for std dev is fixed and defaults to 2.0
func (*StandardIndicatorSet) EWMA ¶
func (set *StandardIndicatorSet) EWMA(iw types.IntervalWindow) *indicator.EWMA
GetEWMA returns the exponential weighed moving average indicator of the given interval and the window size.
func (*StandardIndicatorSet) SMA ¶
func (set *StandardIndicatorSet) SMA(iw types.IntervalWindow) *indicator.SMA
SMA returns the simple moving average indicator of the given interval and the window size.
type SymbolBasedRiskController ¶
type SymbolBasedRiskController struct {
BasicRiskController *BasicRiskController `json:"basic,omitempty" yaml:"basic,omitempty"`
}
type TradeReporter ¶
type TradeReporter struct {
*Notifiability
}
type Trader ¶
type Trader struct { Graceful Graceful // 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) ReportPnL ¶
func (trader *Trader) ReportPnL() *PnLReporterManager
ReportPnL configure and set the PnLReporter with the given notifier
func (*Trader) RunAllSingleExchangeStrategy ¶
func (*Trader) RunSingleExchangeStrategy ¶
func (trader *Trader) RunSingleExchangeStrategy(ctx context.Context, strategy SingleExchangeStrategy, session *ExchangeSession, orderExecutor OrderExecutor) error
func (*Trader) SetRiskControls ¶
func (trader *Trader) SetRiskControls(riskControls *RiskControls)
TODO: provide a more DSL way to configure risk controls
Source Files ¶
- active_book.go
- builder.go
- cache.go
- config.go
- context.go
- environment.go
- errors.go
- exchangeorderexecutor_callbacks.go
- graceful_callbacks.go
- home.go
- injection.go
- localactiveorderbook_callbacks.go
- marketdatastore.go
- marketdatastore_callbacks.go
- notifier.go
- order_execution.go
- order_processor.go
- order_store.go
- persistence.go
- position.go
- quota.go
- reporter.go
- risk_controls.go
- scale.go
- session.go
- string.go
- trader.go
- wrapper.go