bbgo_origin/pkg/bbgo/trader.go

325 lines
8.8 KiB
Go
Raw Normal View History

2020-07-10 13:34:39 +00:00
package bbgo
import (
"context"
"reflect"
2020-07-13 04:57:18 +00:00
log "github.com/sirupsen/logrus"
2020-10-11 08:46:15 +00:00
"github.com/c9s/bbgo/pkg/types"
_ "github.com/go-sql-driver/mysql"
2020-07-10 13:34:39 +00:00
)
2020-10-16 02:09:30 +00:00
var SupportedExchanges = []types.ExchangeName{"binance", "max"}
// SingleExchangeStrategy represents the single Exchange strategy
type SingleExchangeStrategy interface {
Run(ctx context.Context, orderExecutor OrderExecutor, session *ExchangeSession) error
2020-07-14 06:54:23 +00:00
}
type ExchangeSessionSubscriber interface {
Subscribe(session *ExchangeSession)
}
type CrossExchangeStrategy interface {
Run(ctx context.Context, orderExecutionRouter OrderExecutionRouter, sessions map[string]*ExchangeSession) error
}
2020-11-09 08:34:35 +00:00
type Logging interface {
EnableLogging()
DisableLogging()
}
type Logger interface {
Warnf(message string, args ...interface{})
Errorf(message string, args ...interface{})
Infof(message string, args ...interface{})
}
type SilentLogger struct{}
func (logger *SilentLogger) Infof(message string, args ...interface{}) {}
func (logger *SilentLogger) Warnf(message string, args ...interface{}) {}
func (logger *SilentLogger) Errorf(message string, args ...interface{}) {}
type Trader struct {
environment *Environment
2020-09-28 07:01:10 +00:00
riskControls *RiskControls
crossExchangeStrategies []CrossExchangeStrategy
exchangeStrategies map[string][]SingleExchangeStrategy
2020-11-09 08:34:35 +00:00
logger Logger
2020-07-13 05:25:48 +00:00
}
func NewTrader(environ *Environment) *Trader {
2020-09-07 06:20:03 +00:00
return &Trader{
environment: environ,
exchangeStrategies: make(map[string][]SingleExchangeStrategy),
2020-11-09 08:34:35 +00:00
logger: log.StandardLogger(),
2020-09-07 06:20:03 +00:00
}
}
2020-11-09 08:34:35 +00:00
func (trader *Trader) EnableLogging() {
trader.logger = log.StandardLogger()
}
func (trader *Trader) DisableLogging() {
trader.logger = &SilentLogger{}
}
// AttachStrategyOn attaches the single exchange strategy on an exchange session.
// Single exchange strategy is the default behavior.
func (trader *Trader) AttachStrategyOn(session string, strategies ...SingleExchangeStrategy) *Trader {
if _, ok := trader.environment.sessions[session]; !ok {
log.Panicf("session %s is not defined", session)
}
2020-09-19 03:25:48 +00:00
for _, s := range strategies {
trader.exchangeStrategies[session] = append(trader.exchangeStrategies[session], s)
}
2020-10-16 05:52:18 +00:00
return trader
}
2020-09-28 07:01:10 +00:00
// AttachCrossExchangeStrategy attaches the cross exchange strategy
2020-10-16 05:52:18 +00:00
func (trader *Trader) AttachCrossExchangeStrategy(strategy CrossExchangeStrategy) *Trader {
trader.crossExchangeStrategies = append(trader.crossExchangeStrategies, strategy)
2020-10-16 05:52:18 +00:00
return trader
}
2020-09-28 07:01:10 +00:00
// TODO: provide a more DSL way to configure risk controls
func (trader *Trader) SetRiskControls(riskControls *RiskControls) {
trader.riskControls = riskControls
}
func (trader *Trader) Run(ctx context.Context) error {
2020-09-28 07:01:10 +00:00
// pre-subscribe the data
for sessionName, strategies := range trader.exchangeStrategies {
session := trader.environment.sessions[sessionName]
for _, strategy := range strategies {
if subscriber, ok := strategy.(ExchangeSessionSubscriber); ok {
subscriber.Subscribe(session)
}
}
}
if err := trader.environment.Init(ctx); err != nil {
return err
}
// load and run session strategies
for sessionName, strategies := range trader.exchangeStrategies {
var session = trader.environment.sessions[sessionName]
var baseOrderExecutor = &ExchangeOrderExecutor{
2020-10-30 21:21:17 +00:00
// copy the environment notification system so that we can route
Notifiability: trader.environment.Notifiability,
session: session,
2020-11-09 08:34:35 +00:00
logger: trader.logger,
}
// default to base order executor
var orderExecutor OrderExecutor = baseOrderExecutor
// Since the risk controls are loaded from the config file
if riskControls := trader.riskControls; riskControls != nil {
if trader.riskControls.SessionBasedRiskControl != nil {
control, ok := trader.riskControls.SessionBasedRiskControl[sessionName]
if ok {
control.SetBaseOrderExecutor(baseOrderExecutor)
// pick the order executor
if control.OrderExecutor != nil {
orderExecutor = control.OrderExecutor
}
}
}
}
for _, strategy := range strategies {
rs := reflect.ValueOf(strategy)
if rs.Elem().Kind() == reflect.Struct {
2020-10-27 11:33:11 +00:00
// get the struct element
rs = rs.Elem()
2020-10-27 11:33:11 +00:00
2020-10-30 21:21:17 +00:00
if err := injectField(rs, "Notifiability", &trader.environment.Notifiability, false); err != nil {
log.WithError(err).Errorf("strategy Notifiability injection failed")
}
if err := injectField(rs, "OrderExecutor", orderExecutor, false); err != nil {
log.WithError(err).Errorf("strategy OrderExecutor injection failed")
}
if symbol, ok := isSymbolBasedStrategy(rs); ok {
log.Infof("found symbol based strategy from %s", rs.Type())
if hasField(rs, "Market") {
if market, ok := session.Market(symbol); ok {
// let's make the market object passed by pointer
if err := injectField(rs, "Market", &market, false); err != nil {
log.WithError(err).Errorf("strategy %T Market injection failed", strategy)
}
}
}
// StandardIndicatorSet
if hasField(rs, "StandardIndicatorSet") {
if indicatorSet, ok := session.StandardIndicatorSet(symbol); ok {
if err := injectField(rs, "StandardIndicatorSet", indicatorSet, true); err != nil {
log.WithError(err).Errorf("strategy %T StandardIndicatorSet injection failed", strategy)
}
}
}
if hasField(rs, "MarketDataStore") {
if store, ok := session.MarketDataStore(symbol); ok {
if err := injectField(rs, "MarketDataStore", store, true); err != nil {
log.WithError(err).Errorf("strategy %T MarketDataStore injection failed", strategy)
}
}
}
}
}
err := strategy.Run(ctx, orderExecutor, session)
2020-09-28 07:01:10 +00:00
if err != nil {
return err
}
}
}
2020-09-28 07:01:10 +00:00
router := &ExchangeOrderExecutionRouter{
2020-10-30 21:21:17 +00:00
Notifiability: trader.environment.Notifiability,
2020-10-16 02:09:30 +00:00
sessions: trader.environment.sessions,
}
for _, strategy := range trader.crossExchangeStrategies {
if err := strategy.Run(ctx, router, trader.environment.sessions); err != nil {
return err
}
}
return trader.environment.Connect(ctx)
2020-09-07 06:20:03 +00:00
}
/*
2020-10-13 10:08:02 +00:00
func (trader *OrderExecutor) RunStrategyWithHotReload(ctx context.Context, strategy SingleExchangeStrategy, configFile string) (chan struct{}, error) {
var done = make(chan struct{})
var configWatcherDone = make(chan struct{})
log.Infof("watching config file: %v", configFile)
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
defer watcher.Close()
if err := watcher.Add(configFile); err != nil {
return nil, err
}
go func() {
strategyContext, strategyCancel := context.WithCancel(ctx)
defer strategyCancel()
defer close(done)
traderDone, err := trader.RunStrategy(strategyContext, strategy)
if err != nil {
return
}
var configReloadTimer *time.Timer = nil
defer close(configWatcherDone)
for {
select {
case <-ctx.Done():
return
case <-traderDone:
log.Infof("reloading config file %s", configFile)
if err := config.LoadConfigFile(configFile, strategy); err != nil {
log.WithError(err).Error("error load config file")
}
2020-10-22 02:47:54 +00:00
trader.NotifyTo("config reloaded, restarting trader")
traderDone, err = trader.RunStrategy(strategyContext, strategy)
if err != nil {
log.WithError(err).Error("[trader] error:", err)
return
}
case event := <-watcher.Events:
log.Infof("[fsnotify] event: %+v", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Info("[fsnotify] modified file:", event.Name)
}
if configReloadTimer != nil {
configReloadTimer.Stop()
}
configReloadTimer = time.AfterFunc(3*time.Second, func() {
strategyCancel()
})
case err := <-watcher.Errors:
log.WithError(err).Error("[fsnotify] error:", err)
return
}
}
}()
return done, nil
}
*/
/*
2020-10-13 10:08:02 +00:00
func (trader *OrderExecutor) RunStrategy(ctx context.Context, strategy SingleExchangeStrategy) (chan struct{}, error) {
2020-07-13 16:20:15 +00:00
trader.reportTimer = time.AfterFunc(1*time.Second, func() {
2020-09-07 06:33:58 +00:00
trader.reportPnL()
2020-07-13 05:25:48 +00:00
})
stream.OnTradeUpdate(func(trade *types.Trade) {
2020-09-19 03:09:20 +00:00
trader.NotifyTrade(trade)
2020-07-16 07:36:02 +00:00
trader.ProfitAndLossCalculator.AddTrade(*trade)
2020-09-05 08:22:46 +00:00
_, err := trader.Context.StockManager.AddTrades([]types.Trade{*trade})
2020-08-04 11:05:20 +00:00
if err != nil {
log.WithError(err).Error("stock manager load trades error")
}
2020-07-13 05:25:48 +00:00
2020-07-13 16:20:15 +00:00
if trader.reportTimer != nil {
trader.reportTimer.Stop()
2020-07-13 05:25:48 +00:00
}
2020-08-10 05:27:28 +00:00
trader.reportTimer = time.AfterFunc(1*time.Minute, func() {
2020-09-07 06:33:58 +00:00
trader.reportPnL()
2020-07-13 05:25:48 +00:00
})
})
2020-07-10 13:34:39 +00:00
}
*/
2020-07-10 13:34:39 +00:00
2020-10-26 08:44:05 +00:00
// ReportPnL configure and set the PnLReporter with the given notifier
func (trader *Trader) ReportPnL() *PnLReporterManager {
2020-10-30 21:21:17 +00:00
return NewPnLReporter(&trader.environment.Notifiability)
2020-10-22 07:57:50 +00:00
}
type OrderExecutor interface {
SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error)
}
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)
}