bbgo_origin/pkg/bbgo/environment.go

260 lines
6.9 KiB
Go
Raw Normal View History

2020-10-16 02:14:36 +00:00
package bbgo
import (
"context"
2020-10-20 04:11:44 +00:00
"fmt"
2020-10-21 11:52:55 +00:00
"regexp"
2020-10-16 02:14:36 +00:00
"strings"
"time"
"github.com/jmoiron/sqlx"
2020-10-20 04:11:44 +00:00
"github.com/pkg/errors"
2020-10-17 16:06:08 +00:00
log "github.com/sirupsen/logrus"
2020-10-16 02:14:36 +00:00
"github.com/spf13/viper"
2020-10-21 07:58:58 +00:00
"github.com/c9s/bbgo/pkg/cmd/cmdutil"
2020-10-16 02:14:36 +00:00
"github.com/c9s/bbgo/pkg/service"
2020-10-18 04:23:00 +00:00
"github.com/c9s/bbgo/pkg/store"
2020-10-16 02:14:36 +00:00
"github.com/c9s/bbgo/pkg/types"
2020-10-21 11:52:55 +00:00
"github.com/c9s/bbgo/pkg/util"
2020-10-16 02:14:36 +00:00
)
var LoadedExchangeStrategies = make(map[string]SingleExchangeStrategy)
2020-10-20 05:52:25 +00:00
func RegisterExchangeStrategy(key string, configmap SingleExchangeStrategy) {
LoadedExchangeStrategies[key] = configmap
2020-10-20 05:52:25 +00:00
}
var LoadedCrossExchangeStrategies = make(map[string]CrossExchangeStrategy)
func RegisterCrossExchangeStrategy(key string, configmap CrossExchangeStrategy) {
LoadedCrossExchangeStrategies[key] = configmap
}
2020-10-20 05:52:25 +00:00
2020-10-21 11:52:55 +00:00
type TradeReporter struct {
notifier Notifier
channel string
channelRoutes map[*regexp.Regexp]string
}
func NewTradeReporter(notifier Notifier) *TradeReporter {
return &TradeReporter{
notifier: notifier,
channelRoutes: make(map[*regexp.Regexp]string),
}
}
func (reporter *TradeReporter) Channel(channel string) *TradeReporter {
reporter.channel = channel
return reporter
}
func (reporter *TradeReporter) ChannelBySymbol(routes map[string]string) *TradeReporter {
for pattern, channel := range routes {
reporter.channelRoutes[regexp.MustCompile(pattern)] = channel
}
return reporter
}
func (reporter *TradeReporter) getChannel(symbol string) string {
for pattern, channel := range reporter.channelRoutes {
if pattern.MatchString(symbol) {
return channel
}
}
return reporter.channel
}
func (reporter *TradeReporter) Report(trade types.Trade) {
var channel = reporter.getChannel(trade.Symbol)
var text = util.Render(`:handshake: {{ .Symbol }} {{ .Side }} Trade Execution @ {{ .Price }}`, trade)
2020-10-22 02:47:54 +00:00
if err := reporter.notifier.NotifyTo(channel, text, trade); err != nil {
log.WithError(err).Errorf("notifier error, channel=%s", channel)
2020-10-21 11:52:55 +00:00
}
}
2020-10-16 02:14:36 +00:00
// Environment presents the real exchange data layer
type Environment struct {
TradeService *service.TradeService
TradeSync *service.TradeSync
2020-10-20 05:11:04 +00:00
tradeScanTime time.Time
sessions map[string]*ExchangeSession
2020-10-22 02:47:54 +00:00
tradeReporter *TradeReporter
2020-10-16 02:14:36 +00:00
}
// NewDefaultEnvironment prepares the exchange sessions from the viper settings.
2020-10-16 02:14:36 +00:00
func NewDefaultEnvironment(db *sqlx.DB) *Environment {
environment := NewEnvironment(db)
for _, n := range SupportedExchanges {
if viper.IsSet(string(n) + "-api-key") {
exchange, err := cmdutil.NewExchange(n)
if err != nil {
panic(err)
}
environment.AddExchange(string(n), exchange)
}
}
return environment
}
func NewEnvironment(db *sqlx.DB) *Environment {
tradeService := &service.TradeService{DB: db}
return &Environment{
TradeService: tradeService,
TradeSync: &service.TradeSync{
Service: tradeService,
},
2020-10-20 05:11:04 +00:00
tradeScanTime: time.Now().AddDate(0, 0, -7), // sync from 7 days ago
sessions: make(map[string]*ExchangeSession),
2020-10-16 02:14:36 +00:00
}
}
func (environ *Environment) AddExchange(name string, exchange types.Exchange) (session *ExchangeSession) {
2020-10-17 15:51:44 +00:00
session = NewExchangeSession(name, exchange)
2020-10-16 02:14:36 +00:00
environ.sessions[name] = session
return session
}
2020-10-22 02:47:54 +00:00
func (environ *Environment) ReportTrade(notifier Notifier) *TradeReporter {
environ.tradeReporter = NewTradeReporter(notifier)
return environ.tradeReporter
}
2020-10-16 02:14:36 +00:00
func (environ *Environment) Init(ctx context.Context) (err error) {
for _, session := range environ.sessions {
2020-10-20 04:11:44 +00:00
var markets types.MarketMap
err = WithCache(fmt.Sprintf("%s-markets", session.Exchange.Name()), &markets, func() (interface{}, error) {
2020-10-20 04:11:44 +00:00
return session.Exchange.QueryMarkets(ctx)
})
2020-10-16 02:14:36 +00:00
if err != nil {
return err
}
2020-10-20 04:11:44 +00:00
if len(markets) == 0 {
return errors.Errorf("market config should not be empty")
}
2020-10-18 04:30:13 +00:00
session.markets = markets
2020-10-22 02:47:54 +00:00
2020-10-22 02:54:03 +00:00
if session.tradeReporter != nil {
session.Stream.OnTrade(func(trade types.Trade) {
session.tradeReporter.Report(trade)
})
} else if environ.tradeReporter != nil {
2020-10-22 02:47:54 +00:00
session.Stream.OnTrade(func(trade types.Trade) {
environ.tradeReporter.Report(trade)
})
}
2020-10-19 13:58:50 +00:00
}
return nil
}
2020-10-20 05:11:04 +00:00
// SetTradeScanTime overrides the default trade scan time (-7 days)
func (environ *Environment) SetTradeScanTime(t time.Time) *Environment {
environ.tradeScanTime = t
return environ
}
2020-10-19 13:58:50 +00:00
func (environ *Environment) Connect(ctx context.Context) error {
var err error
for n := range environ.sessions {
// avoid using the placeholder variable for the session because we use that in the callbacks
var session = environ.sessions[n]
2020-10-19 14:26:43 +00:00
var log = log.WithField("session", n)
2020-10-19 13:58:50 +00:00
loadedSymbols := make(map[string]struct{})
for _, s := range session.Subscriptions {
symbol := strings.ToUpper(s.Symbol)
loadedSymbols[symbol] = struct{}{}
log.Infof("subscribing %s %s %v", s.Symbol, s.Channel, s.Options)
session.Stream.Subscribe(s.Channel, s.Symbol, s.Options)
}
2020-10-19 14:02:05 +00:00
// trade sync and market data store depends on subscribed symbols so we have to do this here.
2020-10-16 02:14:36 +00:00
for symbol := range loadedSymbols {
2020-10-17 16:06:08 +00:00
log.Infof("syncing trades from %s for symbol %s...", session.Exchange.Name(), symbol)
2020-10-20 05:11:04 +00:00
if err := environ.TradeSync.Sync(ctx, session.Exchange, symbol, environ.tradeScanTime); err != nil {
2020-10-16 02:14:36 +00:00
return err
}
var trades []types.Trade
tradingFeeCurrency := session.Exchange.PlatformFeeCurrency()
if strings.HasPrefix(symbol, tradingFeeCurrency) {
trades, err = environ.TradeService.QueryForTradingFeeCurrency(symbol, tradingFeeCurrency)
} else {
trades, err = environ.TradeService.Query(symbol)
}
if err != nil {
return err
}
2020-10-17 16:06:08 +00:00
log.Infof("symbol %s: %d trades loaded", symbol, len(trades))
2020-10-16 02:14:36 +00:00
session.Trades[symbol] = trades
currentPrice, err := session.Exchange.QueryAveragePrice(ctx, symbol)
if err != nil {
return err
}
session.lastPrices[symbol] = currentPrice
2020-10-17 16:06:08 +00:00
marketDataStore := store.NewMarketDataStore(symbol)
2020-10-19 13:58:50 +00:00
marketDataStore.BindStream(session.Stream)
session.marketDataStores[symbol] = marketDataStore
2020-10-16 02:14:36 +00:00
}
2020-10-19 14:00:44 +00:00
log.Infof("querying balances...")
balances, err := session.Exchange.QueryAccountBalances(ctx)
if err != nil {
return err
}
session.Account.UpdateBalances(balances)
session.Account.BindStream(session.Stream)
2020-10-16 02:14:36 +00:00
// update last prices
2020-10-19 13:58:50 +00:00
session.Stream.OnKLineClosed(func(kline types.KLine) {
log.Infof("kline closed: %+v", kline)
session.lastPrices[kline.Symbol] = kline.Close
session.marketDataStores[kline.Symbol].AddKLine(kline)
2020-10-16 02:14:36 +00:00
})
session.Stream.OnTrade(func(trade types.Trade) {
2020-10-16 02:14:36 +00:00
// append trades
session.Trades[trade.Symbol] = append(session.Trades[trade.Symbol], trade)
2020-10-16 02:14:36 +00:00
if err := environ.TradeService.Insert(trade); err != nil {
log.WithError(err).Errorf("trade insert error: %+v", trade)
2020-10-16 02:14:36 +00:00
}
})
2020-10-17 16:06:08 +00:00
2020-10-19 14:26:43 +00:00
if len(session.Subscriptions) == 0 {
log.Warnf("no subscriptions, exchange session %s will not be connected", session.Name)
continue
}
2020-10-17 16:06:08 +00:00
log.Infof("connecting session %s...", session.Name)
2020-10-16 02:14:36 +00:00
if err := session.Stream.Connect(ctx); err != nil {
return err
}
}
return nil
}