bbgo

package
v0.0.0-...-8d88297 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2023 License: AGPL-3.0 Imports: 57 Imported by: 3

Documentation

Index

Constants

View Source
const CancelOrderWaitTime = 20 * time.Millisecond
View Source
const IsolationContextKey = "bbgo"
View Source
const MaxNumOfKLines = 5_000
View Source
const MaxNumOfKLinesTruncate = 100
View Source
const PruneTriggerNumOfTrades = 10_000
View Source
const TemplateOrderReport = `:handshake: {{ .Symbol }} {{ .Side }} Order Update @ {{ .Price  }}`
View Source
const TradeExpiryTime = 24 * time.Hour

Variables

View Source
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")
)
View Source
var BackTestService *service.BacktestService
View Source
var DefaultBacktestAccount = BacktestAccount{
	MakerFeeRate: fixedpoint.MustNewFromString("0.050%"),
	TakerFeeRate: fixedpoint.MustNewFromString("0.075%"),
	Balances: BacktestAccountBalanceMap{
		"USDT": fixedpoint.NewFromFloat(10000),
	},
}
View Source
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

View Source
var ErrExceededSubmitOrderRetryLimit = errors.New("exceeded submit order retry limit")
View Source
var ErrSessionAlreadyInitialized = errors.New("session is already initialized")
View Source
var IsBackTesting = false

IsBackTesting is a global variable that indicates the current environment is back-test or not.

View Source
var IsWrapperBinary = false
View Source
var KLinePreloadLimit int64 = 1000
View Source
var LoadedCrossExchangeStrategies = make(map[string]CrossExchangeStrategy)
View Source
var LoadedExchangeStrategies = make(map[string]SingleExchangeStrategy)
View Source
var LocalTimeZone *time.Location
View Source
var Notification = &Notifiability{
	SymbolChannelRouter:  NewPatternChannelRouter(nil),
	SessionChannelRouter: NewPatternChannelRouter(nil),
	ObjectChannelRouter:  NewObjectChannelRouter(),
}

Functions

func AdjustFloatQuantityByMaxAmount

func AdjustFloatQuantityByMaxAmount(quantity fixedpoint.Value, price fixedpoint.Value, maxAmount fixedpoint.Value) fixedpoint.Value

func AdjustFloatQuantityByMinAmount

func AdjustFloatQuantityByMinAmount(quantity, currentPrice, minAmount fixedpoint.Value) fixedpoint.Value

AdjustFloatQuantityByMinAmount adjusts the quantity to make the amount greater than the given minAmount

func AdjustQuantityByMaxAmount

func AdjustQuantityByMaxAmount(quantity, currentPrice, maxAmount fixedpoint.Value) fixedpoint.Value

AdjustQuantityByMaxAmount adjusts the quantity to make the amount less than the given maxAmount

func AdjustQuantityByMinAmount

func AdjustQuantityByMinAmount(quantity, currentPrice, minAmount fixedpoint.Value) fixedpoint.Value

AdjustQuantityByMinAmount adjusts the quantity to make the amount greater than the given minAmount

func BacktestFeeModeStrings

func BacktestFeeModeStrings() []string

BacktestFeeModeStrings returns a slice of all String values of the enum

func BatchPlaceOrder

func BatchPlaceOrder(ctx context.Context, exchange types.Exchange, submitOrders ...types.SubmitOrder) (types.OrderSlice, []int, error)

BatchPlaceOrder

func BatchRetryPlaceOrder

func BatchRetryPlaceOrder(ctx context.Context, exchange types.Exchange, errIdx []int, orderCallback OrderCallback, submitOrders ...types.SubmitOrder) (types.OrderSlice, error)

BatchRetryPlaceOrder places the orders and retries the failed orders

func BootstrapBacktestEnvironment

func BootstrapBacktestEnvironment(ctx context.Context, environ *Environment) error

func BootstrapEnvironment

func BootstrapEnvironment(ctx context.Context, environ *Environment, userConfig *Config) error

func BootstrapEnvironmentLightweight

func BootstrapEnvironmentLightweight(ctx context.Context, environ *Environment, userConfig *Config) error

BootstrapEnvironmentLightweight bootstrap the environment in lightweight mode - no database configuration - no notification

func Build

func Build(ctx context.Context, userConfig *Config, targetConfig BuildTargetConfig) (string, error)

Build builds the bbgo wrapper binary with the given build target config

func BuildTarget

func BuildTarget(ctx context.Context, userConfig *Config, target BuildTargetConfig) (string, error)

BuildTarget builds the one of the targets.

func CalculateBaseQuantity

func CalculateBaseQuantity(session *ExchangeSession, market types.Market, price, quantity, leverage fixedpoint.Value) (fixedpoint.Value, error)

func CalculateQuoteQuantity

func CalculateQuoteQuantity(ctx context.Context, session *ExchangeSession, quoteCurrency string, leverage fixedpoint.Value) (fixedpoint.Value, error)

func ConfigurePersistence

func ConfigurePersistence(ctx context.Context, conf *PersistenceConfig) error

func NewContextWithDefaultIsolation

func NewContextWithDefaultIsolation(parent context.Context) context.Context

NewContextWithDefaultIsolation creates a new context from the parent context with a default isolation

func NewContextWithIsolation

func NewContextWithIsolation(parent context.Context, isolation *Isolation) context.Context

NewContextWithIsolation creates a new context from the parent context with a custom isolation

func NewPersistenceServiceFacade

func NewPersistenceServiceFacade(conf *PersistenceConfig) (*service.PersistenceServiceFacade, error)

func NewTodoContextWithExistingIsolation

func NewTodoContextWithExistingIsolation(parent context.Context) context.Context

NewTodoContextWithExistingIsolation creates a new context object with the existing isolation of the parent context.

func Notify

func Notify(obj interface{}, args ...interface{})

func NotifyTo

func NotifyTo(channel string, obj interface{}, args ...interface{})

func OnShutdown

func OnShutdown(ctx context.Context, f ShutdownHandler)

func RegisterCommand

func RegisterCommand(command, desc string, f interface{}) *interact.Command

func RegisterModifier

func RegisterModifier(s interface{})

func RegisterStrategy

func RegisterStrategy(key string, s interface{})

func SendPhoto

func SendPhoto(buffer *bytes.Buffer)

func SendPhotoTo

func SendPhotoTo(channel string, buffer *bytes.Buffer)

func SetBackTesting

func SetBackTesting(s *service.BacktestService)

func SetWrapperBinary

func SetWrapperBinary()

func Shutdown

func Shutdown(shutdownCtx context.Context)

func Sync

func Sync(ctx context.Context, obj interface{})

Sync syncs the object properties into the persistence layer

Types

type AccountValueCalculator

type AccountValueCalculator struct {
	// contains filtered or unexported fields
}

func NewAccountValueCalculator

func NewAccountValueCalculator(session *ExchangeSession, quoteCurrency string) *AccountValueCalculator

func (*AccountValueCalculator) AvailableQuote

func (c *AccountValueCalculator) AvailableQuote(ctx context.Context) (fixedpoint.Value, error)

func (*AccountValueCalculator) DebtValue

func (*AccountValueCalculator) MarginLevel

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

func (*AccountValueCalculator) NetValue

func (*AccountValueCalculator) UpdatePrices

func (c *AccountValueCalculator) UpdatePrices(ctx context.Context) error

type ActiveOrderBook

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

func NewActiveOrderBook(symbol string) *ActiveOrderBook

func (*ActiveOrderBook) Add

func (b *ActiveOrderBook) Add(orders ...types.Order)

func (*ActiveOrderBook) Backup

func (b *ActiveOrderBook) Backup() []types.SubmitOrder

func (*ActiveOrderBook) BindStream

func (b *ActiveOrderBook) BindStream(stream types.Stream)

func (*ActiveOrderBook) EmitCanceled

func (b *ActiveOrderBook) EmitCanceled(o types.Order)

func (*ActiveOrderBook) EmitFilled

func (b *ActiveOrderBook) EmitFilled(o types.Order)

func (*ActiveOrderBook) EmitNew

func (b *ActiveOrderBook) EmitNew(o types.Order)

func (*ActiveOrderBook) Exists

func (b *ActiveOrderBook) Exists(order types.Order) bool

func (*ActiveOrderBook) FastCancel

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

func (b *ActiveOrderBook) Get(orderID uint64) (types.Order, bool)

func (*ActiveOrderBook) GracefulCancel

func (b *ActiveOrderBook) GracefulCancel(ctx context.Context, ex types.Exchange, orders ...types.Order) error

GracefulCancel cancels the active orders gracefully

func (*ActiveOrderBook) Lookup

func (b *ActiveOrderBook) Lookup(f func(o types.Order) bool) *types.Order

func (*ActiveOrderBook) MarshalJSON

func (b *ActiveOrderBook) MarshalJSON() ([]byte, error)

func (*ActiveOrderBook) NumOfOrders

func (b *ActiveOrderBook) NumOfOrders() int

func (*ActiveOrderBook) OnCanceled

func (b *ActiveOrderBook) OnCanceled(cb func(o types.Order))

func (*ActiveOrderBook) OnFilled

func (b *ActiveOrderBook) OnFilled(cb func(o types.Order))

func (*ActiveOrderBook) OnNew

func (b *ActiveOrderBook) OnNew(cb func(o types.Order))

func (*ActiveOrderBook) Orders

func (b *ActiveOrderBook) Orders() types.OrderSlice

func (*ActiveOrderBook) Print

func (b *ActiveOrderBook) Print()

func (*ActiveOrderBook) Remove

func (b *ActiveOrderBook) Remove(order types.Order) bool

func (*ActiveOrderBook) Update

func (b *ActiveOrderBook) Update(orders ...types.Order)

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

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

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

func (b *BacktestAccount) UnmarshalJSON(input []byte) error

func (*BacktestAccount) UnmarshalYAML

func (b *BacktestAccount) UnmarshalYAML(value *yaml.Node) error

type BacktestAccountBalanceMap

type BacktestAccountBalanceMap map[string]fixedpoint.Value

func (BacktestAccountBalanceMap) BalanceMap

type BacktestFeeMode

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

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

func BacktestFeeModeValues() []BacktestFeeMode

BacktestFeeModeValues returns all values of the enum

func (BacktestFeeMode) IsABacktestFeeMode

func (i BacktestFeeMode) IsABacktestFeeMode() bool

IsABacktestFeeMode returns "true" if the value is listed in the enum definition. "false" otherwise

func (BacktestFeeMode) MarshalJSON

func (i BacktestFeeMode) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for BacktestFeeMode

func (BacktestFeeMode) MarshalYAML

func (i BacktestFeeMode) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for BacktestFeeMode

func (BacktestFeeMode) String

func (i BacktestFeeMode) String() string

func (*BacktestFeeMode) UnmarshalJSON

func (i *BacktestFeeMode) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for BacktestFeeMode

func (*BacktestFeeMode) UnmarshalYAML

func (i *BacktestFeeMode) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for BacktestFeeMode

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"`

	Sync *SyncConfig `json:"sync,omitempty" yaml:"sync,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"`

	Logging *LoggingConfig `json:"logging,omitempty"`

	ExchangeStrategies      []ExchangeStrategyMount `json:"-" yaml:"-"`
	CrossExchangeStrategies []CrossExchangeStrategy `json:"-" yaml:"-"`

	PnLReporters []PnLReporterConfig `json:"reportPnL,omitempty" yaml:"reportPnL,omitempty"`
	Code         []byte              `json:"-" yaml:"-"`
}

func Load

func Load(configFile string, loadStrategies bool) (*Config, error)

Load parses the config

func LoadBuildConfig

func LoadBuildConfig(configFile string) (*Config, error)

func (*Config) GetSignature

func (c *Config) GetSignature() string

func (*Config) Map

func (c *Config) Map() (map[string]interface{}, error)

func (*Config) YAML

func (c *Config) YAML() ([]byte, error)

type CoreInteraction

type CoreInteraction struct {
	// contains filtered or unexported fields
}

func NewCoreInteraction

func NewCoreInteraction(environment *Environment, trader *Trader) *CoreInteraction

func (*CoreInteraction) Commands

func (it *CoreInteraction) Commands(i *interact.Interact)

func (*CoreInteraction) Initialize

func (it *CoreInteraction) Initialize() error

type CrossExchangeSessionSubscriber

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

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

func (s *CumulatedVolumeTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

type EmergencyStopper

type EmergencyStopper interface {
	EmergencyStop() error
}

type Environment

type Environment struct {
	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
	// 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) BindSync

func (environ *Environment) BindSync(config *SyncConfig)

func (*Environment) ConfigureDatabase

func (environ *Environment) ConfigureDatabase(ctx context.Context) error

func (*Environment) ConfigureDatabaseDriver

func (environ *Environment) ConfigureDatabaseDriver(ctx context.Context, driver string, dsn string) error

func (*Environment) ConfigureExchangeSessions

func (environ *Environment) ConfigureExchangeSessions(userConfig *Config) error

func (*Environment) ConfigureNotification

func (environ *Environment) ConfigureNotification(config *NotificationConfig) error

func (*Environment) ConfigureNotificationSystem

func (environ *Environment) ConfigureNotificationSystem(userConfig *Config) error

func (*Environment) Connect

func (environ *Environment) Connect(ctx context.Context) 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

func (environ *Environment) IsBackTesting() bool

func (*Environment) IsSyncing

func (environ *Environment) IsSyncing() (status SyncStatus)

func (*Environment) RecordAsset

func (environ *Environment) RecordAsset(t time.Time, session *ExchangeSession, assets types.AssetMap)

func (*Environment) RecordPosition

func (environ *Environment) RecordPosition(position *types.Position, trade types.Trade, profit *types.Profit)

func (*Environment) RecordProfit

func (environ *Environment) RecordProfit(profit types.Profit)

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

func (environ *Environment) SetLogging(config *LoggingConfig)

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

func (environ *Environment) Start(ctx context.Context) (err error)

Start initializes the symbols data streams

func (*Environment) StartTime

func (environ *Environment) StartTime() time.Time

func (*Environment) Sync

func (environ *Environment) Sync(ctx context.Context, userConfig ...*Config) 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 {
	// contains filtered or unexported fields
}

func (*ExchangeOrderExecutionRouter) CancelOrdersTo

func (e *ExchangeOrderExecutionRouter) CancelOrdersTo(ctx context.Context, session string, orders ...types.Order) error

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

func (e *ExchangeOrderExecutor) CancelOrders(ctx context.Context, orders ...types.Order) error

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 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           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"`

	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

func (session *ExchangeSession) AllLastPrices() map[string]fixedpoint.Value

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

func (session *ExchangeSession) FormatOrders(orders []types.SubmitOrder) (formattedOrders []types.SubmitOrder, err error)

func (*ExchangeSession) GetAccount

func (session *ExchangeSession) GetAccount() (a *types.Account)

func (*ExchangeSession) Init

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

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

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

func (session *ExchangeSession) LastPrices() map[string]fixedpoint.Value

func (*ExchangeSession) MarginType

func (session *ExchangeSession) MarginType() string

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

func (session *ExchangeSession) Markets() map[string]types.Market

func (*ExchangeSession) OrderBook

func (session *ExchangeSession) OrderBook(symbol string) (s *types.StreamOrderBook, ok bool)

OrderBook returns the personal orderbook 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 *types.Position, ok bool)

func (*ExchangeSession) Positions

func (session *ExchangeSession) Positions() map[string]*types.Position

func (*ExchangeSession) SerialMarketDataStore

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

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

func (session *ExchangeSession) UpdateAccount(ctx context.Context) (*types.Account, error)

UpdateAccount locks the account mutex and update the account object

func (*ExchangeSession) UpdatePrices

func (session *ExchangeSession) UpdatePrices(ctx context.Context, currencies []string, fiat string) (err error)

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

func (m *ExchangeStrategyMount) Map() (map[string]interface{}, error)

type ExitMethod

type ExitMethod struct {
	RoiStopLoss        *RoiStopLoss        `json:"roiStopLoss"`
	ProtectiveStopLoss *ProtectiveStopLoss `json:"protectiveStopLoss"`
	RoiTakeProfit      *RoiTakeProfit      `json:"roiTakeProfit"`
	TrailingStop       *TrailingStop2      `json:"trailingStop"`

	// Exit methods for short positions
	// =================================================
	LowerShadowTakeProfit     *LowerShadowTakeProfit     `json:"lowerShadowTakeProfit"`
	CumulatedVolumeTakeProfit *CumulatedVolumeTakeProfit `json:"cumulatedVolumeTakeProfit"`
	SupportTakeProfit         *SupportTakeProfit         `json:"supportTakeProfit"`
}

func (*ExitMethod) Bind

func (m *ExitMethod) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*ExitMethod) Inherit

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

func (e ExitMethod) String() string

func (*ExitMethod) Subscribe

func (m *ExitMethod) Subscribe(session *ExchangeSession)

type ExitMethodSet

type ExitMethodSet []ExitMethod

func (*ExitMethodSet) Bind

func (s *ExitMethodSet) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*ExitMethodSet) SetAndSubscribe

func (s *ExitMethodSet) SetAndSubscribe(session *ExchangeSession, parent interface{})

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 GeneralOrderExecutor

type GeneralOrderExecutor struct {
	// contains filtered or unexported fields
}

GeneralOrderExecutor implements the general order executor for strategy

func NewGeneralOrderExecutor

func NewGeneralOrderExecutor(session *ExchangeSession, symbol, strategy, strategyInstanceID string, position *types.Position) *GeneralOrderExecutor

func (*GeneralOrderExecutor) ActiveMakerOrders

func (e *GeneralOrderExecutor) ActiveMakerOrders() *ActiveOrderBook

func (*GeneralOrderExecutor) Bind

func (e *GeneralOrderExecutor) Bind()

func (*GeneralOrderExecutor) BindEnvironment

func (e *GeneralOrderExecutor) BindEnvironment(environ *Environment)

func (*GeneralOrderExecutor) BindProfitStats

func (e *GeneralOrderExecutor) BindProfitStats(profitStats *types.ProfitStats)

func (*GeneralOrderExecutor) BindTradeStats

func (e *GeneralOrderExecutor) BindTradeStats(tradeStats *types.TradeStats)

func (*GeneralOrderExecutor) CancelOrders

func (e *GeneralOrderExecutor) CancelOrders(ctx context.Context, orders ...types.Order) error

CancelOrders cancels the given order objects directly

func (*GeneralOrderExecutor) ClosePosition

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

func (e *GeneralOrderExecutor) CurrentPosition() *types.Position

This implements PositionReader interface

func (*GeneralOrderExecutor) DisableNotify

func (e *GeneralOrderExecutor) DisableNotify()

func (*GeneralOrderExecutor) FastCancel

func (e *GeneralOrderExecutor) FastCancel(ctx context.Context, orders ...types.Order) error

FastCancel cancels all active maker orders if orders is not given, otherwise cancel the given orders

func (*GeneralOrderExecutor) FastSubmitOrders

func (e *GeneralOrderExecutor) FastSubmitOrders(ctx context.Context, submitOrders ...types.SubmitOrder) (types.OrderSlice, error)

FastSubmitOrders send []types.SubmitOrder directly to the exchange without blocking wait on the status update. This is a faster version of 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.

func (*GeneralOrderExecutor) GracefulCancel

func (e *GeneralOrderExecutor) GracefulCancel(ctx context.Context, orders ...types.Order) error

GracefulCancel cancels all active maker orders if orders are not given, otherwise cancel all the given orders

func (*GeneralOrderExecutor) GracefulCancelActiveOrderBook

func (e *GeneralOrderExecutor) GracefulCancelActiveOrderBook(ctx context.Context, activeOrders *ActiveOrderBook) error

GracefulCancelActiveOrderBook cancels the orders from the active orderbook.

func (*GeneralOrderExecutor) NewOrderFromOpenPosition

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

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

func (e *GeneralOrderExecutor) OrderStore() *OrderStore

func (*GeneralOrderExecutor) Position

func (e *GeneralOrderExecutor) Position() *types.Position

func (*GeneralOrderExecutor) ResetPosition

func (e *GeneralOrderExecutor) ResetPosition() error

This implements PositionResetter interface

func (*GeneralOrderExecutor) Session

func (e *GeneralOrderExecutor) Session() *ExchangeSession

func (*GeneralOrderExecutor) SubmitOrders

func (e *GeneralOrderExecutor) SubmitOrders(ctx context.Context, submitOrders ...types.SubmitOrder) (types.OrderSlice, error)

func (*GeneralOrderExecutor) TradeCollector

func (e *GeneralOrderExecutor) TradeCollector() *TradeCollector

type GracefulShutdown

type GracefulShutdown struct {
	// contains filtered or unexported fields
}

func (*GracefulShutdown) EmitShutdown

func (g *GracefulShutdown) EmitShutdown(ctx context.Context, wg *sync.WaitGroup)

func (*GracefulShutdown) OnShutdown

func (g *GracefulShutdown) OnShutdown(cb ShutdownHandler)

func (*GracefulShutdown) Shutdown

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 Isolation

type Isolation struct {
	// contains filtered or unexported fields
}

func GetIsolationFromContext

func GetIsolationFromContext(ctx context.Context) *Isolation

func NewDefaultIsolation

func NewDefaultIsolation() *Isolation

func NewIsolation

func NewIsolation(persistenceFacade *service.PersistenceServiceFacade) *Isolation

type LayerScale

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

func (s *LayerScale) Scale(layer int) (quantity float64, err error)

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 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 Logger

type Logger interface {
	Warnf(message string, args ...interface{})
	Errorf(message string, args ...interface{})
	Infof(message string, args ...interface{})
}

type Logging

type Logging interface {
	EnableLogging()
	DisableLogging()
}

type LoggingConfig

type LoggingConfig struct {
	Trade bool `json:"trade,omitempty"`
	Order bool `json:"order,omitempty"`
}

type LowerShadowTakeProfit

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

func (s *LowerShadowTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*LowerShadowTakeProfit) Subscribe

func (s *LowerShadowTakeProfit) Subscribe(session *ExchangeSession)

type MACDConfig

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

func (store *MarketDataStore) EmitKLine(k types.KLine)

func (*MarketDataStore) EmitKLineClosed

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

func (store *MarketDataStore) OnKLine(cb func(k types.KLine))

func (*MarketDataStore) OnKLineClosed

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

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

func (settings *MovingAverageSettings) Indicator(indicatorSet *StandardIndicatorSet) (inc types.Float64Indicator, err error)

func (MovingAverageSettings) IntervalWindow

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

func (m *Notifiability) SendPhoto(buffer *bytes.Buffer)

func (*Notifiability) SendPhotoTo

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

type NotificationSwitches struct {
	Trade       bool `json:"trade" yaml:"trade"`
	Position    bool `json:"position" yaml:"position"`
	OrderUpdate bool `json:"orderUpdate" yaml:"orderUpdate"`
	SubmitOrder bool `json:"submitOrder" yaml:"submitOrder"`
}

type Notifier

type Notifier interface {
	NotifyTo(channel string, obj interface{}, args ...interface{})
	Notify(obj interface{}, args ...interface{})
	SendPhotoTo(channel string, buffer *bytes.Buffer)
	SendPhoto(buffer *bytes.Buffer)
}

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

func (n *NullNotifier) SendPhoto(buffer *bytes.Buffer)

func (*NullNotifier) SendPhotoTo

func (n *NullNotifier) SendPhotoTo(channel string, buffer *bytes.Buffer)

type ObjectChannelHandler

type ObjectChannelHandler func(obj interface{}) (channel string, ok bool)

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

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

type OrderCallback func(order types.Order)

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 OrderExecutor interface {
	SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error)
	CancelOrders(ctx context.Context, orders ...types.Order) error
}

type OrderStore

type OrderStore struct {
	Symbol          string
	RemoveCancelled bool
	RemoveFilled    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) AllFilled

func (s *OrderStore) AllFilled() bool

func (*OrderStore) BindStream

func (s *OrderStore) BindStream(stream types.Stream)

func (*OrderStore) Exists

func (s *OrderStore) Exists(oID uint64) (ok bool)

func (*OrderStore) Get

func (s *OrderStore) Get(oID uint64) (order types.Order, ok bool)

Get a single order from the order store by order ID Should check ok to make sure the order is returned successfully

func (*OrderStore) HandleOrderUpdate

func (s *OrderStore) HandleOrderUpdate(order types.Order)

func (*OrderStore) NumOfOrders

func (s *OrderStore) NumOfOrders() (num int)

func (*OrderStore) Orders

func (s *OrderStore) Orders() (orders []types.Order)

func (*OrderStore) Remove

func (s *OrderStore) Remove(o types.Order)

func (*OrderStore) Update

func (s *OrderStore) Update(o types.Order) bool

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)

func (*PatternChannelRouter) Route

func (router *PatternChannelRouter) Route(text string) (channel string, ok bool)

type PercentageScale

type PercentageScale struct {
	ByPercentage *SlideRule `json:"byPercentage"`
}

func (*PercentageScale) Scale

func (s *PercentageScale) Scale(percentage float64) (float64, 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 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

type PositionCloser interface {
	ClosePosition(ctx context.Context, percentage fixedpoint.Value) error
}

type PositionReader

type PositionReader interface {
	CurrentPosition() *types.Position
}

type PositionResetter

type PositionResetter interface {
	ResetPosition() error
}

type PriceVolumeScale

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

func (s *PriceVolumeScale) Scale(price float64, volume float64) (quantity float64, err error)

func (*PriceVolumeScale) ScaleByPrice

func (s *PriceVolumeScale) ScaleByPrice(price float64) (float64, error)

ScaleByPrice scale quantity by the given price

func (*PriceVolumeScale) ScaleByVolume

func (s *PriceVolumeScale) ScaleByVolume(volume float64) (float64, error)

ScaleByVolume scale quantity by the given volume

type ProtectiveStopLoss

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"`
	// 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

func (s *ProtectiveStopLoss) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*ProtectiveStopLoss) Subscribe

func (s *ProtectiveStopLoss) Subscribe(session *ExchangeSession)

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 QuantityOrAmount

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

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

func (qa *QuantityOrAmount) IsSet() bool

func (*QuantityOrAmount) Validate

func (qa *QuantityOrAmount) Validate() error

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)

func (*Quota) Commit

func (q *Quota) Commit()

func (*Quota) Lock

func (q *Quota) Lock(fund fixedpoint.Value) bool

func (*Quota) Rollback

func (q *Quota) Rollback()

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 RoiStopLoss

type RoiStopLoss struct {
	Symbol             string
	Percentage         fixedpoint.Value `json:"percentage"`
	CancelActiveOrders bool             `json:"cancelActiveOrders"`
	// contains filtered or unexported fields
}

func (*RoiStopLoss) Bind

func (s *RoiStopLoss) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*RoiStopLoss) Subscribe

func (s *RoiStopLoss) Subscribe(session *ExchangeSession)

type RoiTakeProfit

type RoiTakeProfit struct {
	Symbol             string           `json:"symbol"`
	Percentage         fixedpoint.Value `json:"percentage"`
	CancelActiveOrders bool             `json:"cancelActiveOrders"`
	// contains filtered or unexported fields
}

RoiTakeProfit force takes the profit by the given ROI percentage.

func (*RoiTakeProfit) Bind

func (s *RoiTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*RoiTakeProfit) Subscribe

func (s *RoiTakeProfit) Subscribe(session *ExchangeSession)

type Scale

type Scale interface {
	Solve() error
	Formula() string
	FormulaOf(x float64) string
	Call(x float64) (y float64)
}

type SerialMarketDataStore

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

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

func (store *SerialMarketDataStore) AddKLine(kline types.KLine, async ...bool)

func (*SerialMarketDataStore) BindStream

func (store *SerialMarketDataStore) BindStream(ctx context.Context, stream types.Stream)

func (*SerialMarketDataStore) Subscribe

func (store *SerialMarketDataStore) Subscribe(interval types.Interval)

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

type ShutdownHandler func(ctx context.Context, wg *sync.WaitGroup)

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

type SimpleInteraction struct {
	Command     string
	Description string
	F           interface{}
	Cmd         *interact.Command
}

func (*SimpleInteraction) Commands

func (it *SimpleInteraction) Commands(i *interact.Interact)

type SingleExchangeStrategy

type SingleExchangeStrategy interface {
	StrategyID
	StrategyNewJsVm
	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 SlackNotification struct {
	DefaultChannel string `json:"defaultChannel,omitempty"  yaml:"defaultChannel,omitempty"`
	ErrorChannel   string `json:"errorChannel,omitempty"  yaml:"errorChannel,omitempty"`
}

type SlackNotificationRouting

type SlackNotificationRouting struct {
	Trade       string `json:"trade,omitempty" yaml:"trade,omitempty"`
	Order       string `json:"order,omitempty" yaml:"order,omitempty"`
	SubmitOrder string `json:"submitOrder,omitempty" yaml:"submitOrder,omitempty"`
	PnL         string `json:"pnL,omitempty" yaml:"pnL,omitempty"`
}

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"`
}

func (*SlideRule) Range

func (rule *SlideRule) Range() ([2]float64, error)

func (*SlideRule) Scale

func (rule *SlideRule) Scale() (Scale, error)

type SourceFunc

type SourceFunc func(*types.KLine) fixedpoint.Value

type SourceSelector

type SourceSelector struct {
	Source selectorInternal `json:"source,omitempty"`
}

func (*SourceSelector) GetSource

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

func (*StandardIndicatorSet) ATRP

func (*StandardIndicatorSet) BOLL

BOLL returns the bollinger band indicator of the given interval, the window and bandwidth

func (*StandardIndicatorSet) CCI

func (*StandardIndicatorSet) EMV

func (*StandardIndicatorSet) 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

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

func (*StandardIndicatorSet) 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

func (s *StandardIndicatorSet) MACD(iw types.IntervalWindow, shortPeriod, longPeriod int) *indicator.MACD

func (*StandardIndicatorSet) PivotHigh

func (*StandardIndicatorSet) PivotLow

func (*StandardIndicatorSet) RSI

func (*StandardIndicatorSet) SMA

SMA is a helper function that returns the simple moving average indicator of the given interval and the window size.

func (*StandardIndicatorSet) STOCH

func (*StandardIndicatorSet) VWMA

VWMA

type Stash

type Stash map[string]interface{}

type StopEMA

type StopEMA struct {
	types.IntervalWindow
	Range fixedpoint.Value `json:"range"`
	// contains filtered or unexported fields
}

func (*StopEMA) Allowed

func (s *StopEMA) Allowed(closePrice fixedpoint.Value) bool

func (*StopEMA) Bind

func (s *StopEMA) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

type StrategyController

type StrategyController struct {
	Status types.StrategyStatus
	// contains filtered or unexported fields
}

func (*StrategyController) EmergencyStop

func (s *StrategyController) EmergencyStop() error

func (*StrategyController) EmitEmergencyStop

func (s *StrategyController) EmitEmergencyStop()

func (*StrategyController) EmitResume

func (s *StrategyController) EmitResume()

func (*StrategyController) EmitSuspend

func (s *StrategyController) EmitSuspend()

func (*StrategyController) GetStatus

func (s *StrategyController) GetStatus() types.StrategyStatus

func (*StrategyController) OnEmergencyStop

func (s *StrategyController) OnEmergencyStop(cb func())

func (*StrategyController) OnResume

func (s *StrategyController) OnResume(cb func())

func (*StrategyController) OnSuspend

func (s *StrategyController) OnSuspend(cb func())

func (*StrategyController) Resume

func (s *StrategyController) Resume() error

func (*StrategyController) Suspend

func (s *StrategyController) Suspend() error

type StrategyControllerEventHub

type StrategyControllerEventHub interface {
	OnSuspend(cb func())

	OnResume(cb func())

	OnEmergencyStop(cb func())
}

type StrategyDefaulter

type StrategyDefaulter interface {
	Defaults() error
}

type StrategyID

type StrategyID interface {
	ID() string
}

Strategy method calls: -> Defaults() (optional method) -> Initialize() (optional method) -> Validate() (optional method) -> Run() (optional method) -> Shutdown(shutdownCtx context.Context, wg *sync.WaitGroup)

type StrategyInitializer

type StrategyInitializer interface {
	Initialize() error
}

StrategyInitializer's Initialize method is called before the Subscribe method call.

type StrategyNewJsVm

type StrategyNewJsVm interface {
	RunCode(file string, options map[string]interface{}) (goja.Value, error)
}

type StrategyShutdown

type StrategyShutdown interface {
	Shutdown(ctx context.Context, wg *sync.WaitGroup)
}

type StrategyStatusReader

type StrategyStatusReader interface {
	GetStatus() types.StrategyStatus
}

type StrategyToggler

type StrategyToggler interface {
	StrategyStatusReader
	Suspend() error
	Resume() error
}

type StrategyValidator

type StrategyValidator interface {
	Validate() error
}

type SupportTakeProfit

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

func (s *SupportTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*SupportTakeProfit) Subscribe

func (s *SupportTakeProfit) Subscribe(session *ExchangeSession)

type SymbolBasedRiskController

type SymbolBasedRiskController struct {
	BasicRiskController *BasicRiskController `json:"basic,omitempty" yaml:"basic,omitempty"`
}

type SyncConfig

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

type SyncStatus int
const (
	SyncNotStarted SyncStatus = iota
	Syncing
	SyncDone
)

type SyncSymbol

type SyncSymbol struct {
	Symbol  string `json:"symbol" yaml:"symbol"`
	Session string `json:"session" yaml:"session"`
}

func (*SyncSymbol) UnmarshalYAML

func (ss *SyncSymbol) UnmarshalYAML(unmarshal func(a interface{}) error) (err error)

type TelegramNotification

type TelegramNotification struct {
	Broadcast bool `json:"broadcast" yaml:"broadcast"`
}

type TradeCollector

type TradeCollector struct {
	Symbol string
	// contains filtered or unexported fields
}

func NewTradeCollector

func NewTradeCollector(symbol string, position *types.Position, orderStore *OrderStore) *TradeCollector

func (*TradeCollector) BindStream

func (c *TradeCollector) BindStream(stream types.Stream)

func (*TradeCollector) BindStreamForBackground

func (c *TradeCollector) BindStreamForBackground(stream types.Stream)

BindStreamForBackground bind the stream callback for background processing

func (*TradeCollector) Emit

func (c *TradeCollector) Emit()

Emit triggers the trade processing (position update) If you sent order, and the order store is updated, you can call this method so that trades will be processed in the next round of the goroutine loop

func (*TradeCollector) EmitPositionUpdate

func (c *TradeCollector) EmitPositionUpdate(position *types.Position)

func (*TradeCollector) EmitProfit

func (c *TradeCollector) EmitProfit(trade types.Trade, profit *types.Profit)

func (*TradeCollector) EmitRecover

func (c *TradeCollector) EmitRecover(trade types.Trade)

func (*TradeCollector) EmitTrade

func (c *TradeCollector) EmitTrade(trade types.Trade, profit fixedpoint.Value, netProfit fixedpoint.Value)

func (*TradeCollector) OnPositionUpdate

func (c *TradeCollector) OnPositionUpdate(cb func(position *types.Position))

func (*TradeCollector) OnProfit

func (c *TradeCollector) OnProfit(cb func(trade types.Trade, profit *types.Profit))

func (*TradeCollector) OnRecover

func (c *TradeCollector) OnRecover(cb func(trade types.Trade))

func (*TradeCollector) OnTrade

func (c *TradeCollector) OnTrade(cb func(trade types.Trade, profit fixedpoint.Value, netProfit fixedpoint.Value))

func (*TradeCollector) OrderStore

func (c *TradeCollector) OrderStore() *OrderStore

OrderStore returns the order store used by the trade collector

func (*TradeCollector) Position

func (c *TradeCollector) Position() *types.Position

Position returns the position used by the trade collector

func (*TradeCollector) Process

func (c *TradeCollector) Process() bool

Process filters the received trades and see if there are orders matching the trades if we have the order in the order store, then the trade will be considered for the position. profit will also be calculated.

func (*TradeCollector) ProcessTrade

func (c *TradeCollector) ProcessTrade(trade types.Trade) bool

return true when the given trade is added return false when the given trade is not added

func (*TradeCollector) QueueTrade

func (c *TradeCollector) QueueTrade(trade types.Trade)

QueueTrade sends the trade object to the trade channel, so that the goroutine can receive the trade and process in the background.

func (*TradeCollector) Recover

func (*TradeCollector) Run

func (c *TradeCollector) Run(ctx context.Context)

Run is a goroutine executed in the background Do not use this function if you need back-testing

func (*TradeCollector) SetPosition

func (c *TradeCollector) SetPosition(position *types.Position)

func (*TradeCollector) TradeStore

func (c *TradeCollector) TradeStore() *TradeStore

type TradeFilter

type TradeFilter func(trade types.Trade) bool

type TradeReporter

type TradeReporter struct {
	*Notifiability
}

type TradeStore

type TradeStore struct {
	// any created trades for tracking trades
	sync.Mutex

	EnablePrune bool
	// contains filtered or unexported fields
}

func NewTradeStore

func NewTradeStore() *TradeStore

func (*TradeStore) Add

func (s *TradeStore) Add(trades ...types.Trade)

func (*TradeStore) BindStream

func (s *TradeStore) BindStream(stream types.Stream)

func (*TradeStore) Clear

func (s *TradeStore) Clear()

func (*TradeStore) Exists

func (s *TradeStore) Exists(oID uint64) (ok bool)

func (*TradeStore) Filter

func (s *TradeStore) Filter(filter TradeFilter)

func (*TradeStore) GetAndClear

func (s *TradeStore) GetAndClear() (trades []types.Trade)

func (*TradeStore) GetOrderTrades

func (s *TradeStore) GetOrderTrades(o types.Order) (trades []types.Trade)

func (*TradeStore) Num

func (s *TradeStore) Num() (num int)

func (*TradeStore) Prune

func (s *TradeStore) Prune(curTime time.Time)

func (*TradeStore) Trades

func (s *TradeStore) Trades() (trades []types.Trade)

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

func (trader *Trader) Configure(ctx context.Context, userConfig *Config) error

func (*Trader) DisableLogging

func (trader *Trader) DisableLogging()

func (*Trader) EnableLogging

func (trader *Trader) EnableLogging()

func (*Trader) IterateStrategies

func (trader *Trader) IterateStrategies(f func(st StrategyID) error) error

func (*Trader) LoadState

func (trader *Trader) LoadState() error

func (*Trader) Run

func (trader *Trader) Run(ctx context.Context) error

func (*Trader) RunAllSingleExchangeStrategy

func (trader *Trader) RunAllSingleExchangeStrategy(ctx context.Context) error

func (*Trader) RunSingleExchangeStrategy

func (trader *Trader) RunSingleExchangeStrategy(ctx context.Context, strategy SingleExchangeStrategy, session *ExchangeSession, orderExecutor OrderExecutor) error

func (*Trader) SaveState

func (trader *Trader) SaveState() error

func (*Trader) SetRiskControls

func (trader *Trader) SetRiskControls(riskControls *RiskControls)

SetRiskControls sets the risk controller TODO: provide a more DSL way to configure risk controls

func (*Trader) Shutdown

func (trader *Trader) Shutdown(ctx context.Context)

type TrailingStop2

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

func (s *TrailingStop2) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*TrailingStop2) Subscribe

func (s *TrailingStop2) Subscribe(session *ExchangeSession)

type TrendEMA

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

func (s *TrendEMA) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor)

func (*TrendEMA) Gradient

func (s *TrendEMA) Gradient() float64

func (*TrendEMA) GradientAllowed

func (s *TrendEMA) GradientAllowed() bool

type TwapExecution

type TwapExecution struct {
	Session        *ExchangeSession
	Symbol         string
	Side           types.SideType
	TargetQuantity fixedpoint.Value
	SliceQuantity  fixedpoint.Value
	StopPrice      fixedpoint.Value
	NumOfTicks     int
	UpdateInterval time.Duration
	DeadlineTime   time.Time
	// contains filtered or unexported fields
}

func (*TwapExecution) Done

func (e *TwapExecution) Done() (c <-chan struct{})

func (*TwapExecution) Run

func (e *TwapExecution) Run(parentCtx context.Context) error

func (*TwapExecution) Shutdown

func (e *TwapExecution) Shutdown(shutdownCtx context.Context)

Shutdown stops the execution If we call this method, it means the execution is still running, We need to: 1. stop the order updater (by using the execution context) 2. the order updater cancels all open orders and close the user data stream

Jump to

Keyboard shortcuts

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