2020-10-16 02:14:36 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
2021-02-21 08:52:47 +00:00
|
|
|
"bytes"
|
2020-10-16 02:14:36 +00:00
|
|
|
"context"
|
2020-10-20 04:11:44 +00:00
|
|
|
"fmt"
|
2021-02-21 08:52:47 +00:00
|
|
|
"image/png"
|
|
|
|
"io/ioutil"
|
2020-12-06 11:36:04 +00:00
|
|
|
"os"
|
2021-02-21 08:52:47 +00:00
|
|
|
"strings"
|
2021-02-20 03:29:33 +00:00
|
|
|
"sync"
|
2020-10-16 02:14:36 +00:00
|
|
|
"time"
|
|
|
|
|
2020-12-07 03:43:17 +00:00
|
|
|
"github.com/codingconcepts/env"
|
2021-02-21 08:52:47 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/pquerna/otp"
|
2020-10-17 16:06:08 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2020-12-29 08:00:03 +00:00
|
|
|
"github.com/spf13/viper"
|
2021-02-21 08:52:47 +00:00
|
|
|
"gopkg.in/tucnak/telebot.v2"
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2020-12-29 08:00:03 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/cmd/cmdutil"
|
2021-02-21 08:52:47 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/notifier/slacknotifier"
|
|
|
|
"github.com/c9s/bbgo/pkg/notifier/telegramnotifier"
|
2020-10-16 02:14:36 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/service"
|
2021-02-21 08:52:47 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/slack/slacklog"
|
2020-10-16 02:14:36 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2020-10-30 21:21:17 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2020-10-16 02:14:36 +00:00
|
|
|
)
|
|
|
|
|
2020-10-20 06:21:46 +00:00
|
|
|
var LoadedExchangeStrategies = make(map[string]SingleExchangeStrategy)
|
|
|
|
var LoadedCrossExchangeStrategies = make(map[string]CrossExchangeStrategy)
|
|
|
|
|
2020-10-28 23:54:59 +00:00
|
|
|
func RegisterStrategy(key string, s interface{}) {
|
2020-12-31 09:13:55 +00:00
|
|
|
loaded := 0
|
2021-01-14 07:10:11 +00:00
|
|
|
if d, ok := s.(SingleExchangeStrategy); ok {
|
2020-10-28 23:54:59 +00:00
|
|
|
LoadedExchangeStrategies[key] = d
|
2020-12-31 09:13:55 +00:00
|
|
|
loaded++
|
|
|
|
}
|
2020-10-28 23:54:59 +00:00
|
|
|
|
2021-01-14 07:10:11 +00:00
|
|
|
if d, ok := s.(CrossExchangeStrategy); ok {
|
2020-10-28 23:54:59 +00:00
|
|
|
LoadedCrossExchangeStrategies[key] = d
|
2020-12-31 09:13:55 +00:00
|
|
|
loaded++
|
|
|
|
}
|
2020-11-15 05:23:26 +00:00
|
|
|
|
2020-12-31 09:13:55 +00:00
|
|
|
if loaded == 0 {
|
|
|
|
panic(fmt.Errorf("%T does not implement SingleExchangeStrategy or CrossExchangeStrategy", s))
|
2020-10-28 23:54:59 +00:00
|
|
|
}
|
2020-10-20 06:21:46 +00:00
|
|
|
}
|
2020-10-20 05:52:25 +00:00
|
|
|
|
2020-11-06 18:57:50 +00:00
|
|
|
var emptyTime time.Time
|
|
|
|
|
2021-02-22 06:14:39 +00:00
|
|
|
type SyncStatus int
|
|
|
|
|
|
|
|
const (
|
|
|
|
SyncNotStarted SyncStatus = iota
|
|
|
|
Syncing
|
|
|
|
SyncDone
|
|
|
|
)
|
|
|
|
|
2020-10-16 02:14:36 +00:00
|
|
|
// Environment presents the real exchange data layer
|
|
|
|
type Environment struct {
|
2020-10-30 20:36:45 +00:00
|
|
|
// Notifiability here for environment is for the streaming data notification
|
|
|
|
// note that, for back tests, we don't need notification.
|
|
|
|
Notifiability
|
|
|
|
|
2021-02-20 16:45:56 +00:00
|
|
|
PersistenceServiceFacade *service.PersistenceServiceFacade
|
2021-02-20 16:58:34 +00:00
|
|
|
DatabaseService *service.DatabaseService
|
|
|
|
OrderService *service.OrderService
|
|
|
|
TradeService *service.TradeService
|
2021-05-06 17:50:38 +00:00
|
|
|
BacktestService *service.BacktestService
|
2021-02-23 08:39:48 +00:00
|
|
|
RewardService *service.RewardService
|
|
|
|
SyncService *service.SyncService
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2020-11-06 18:57:50 +00:00
|
|
|
// startTime is the time of start point (which is used in the backtest)
|
2021-02-20 03:29:33 +00:00
|
|
|
startTime time.Time
|
|
|
|
|
|
|
|
// syncStartTime is the time point we want to start the sync (for trades and orders)
|
|
|
|
syncStartTime time.Time
|
|
|
|
syncMutex sync.Mutex
|
|
|
|
|
2021-02-21 11:36:03 +00:00
|
|
|
syncStatusMutex sync.Mutex
|
2021-02-22 06:14:39 +00:00
|
|
|
syncStatus SyncStatus
|
2021-02-21 11:36:03 +00:00
|
|
|
|
2021-02-20 03:29:33 +00:00
|
|
|
sessions map[string]*ExchangeSession
|
2020-10-16 02:14:36 +00:00
|
|
|
}
|
|
|
|
|
2020-10-26 07:06:39 +00:00
|
|
|
func NewEnvironment() *Environment {
|
2020-10-16 02:14:36 +00:00
|
|
|
return &Environment{
|
2020-10-26 05:48:59 +00:00
|
|
|
// default trade scan time
|
2021-02-20 03:29:33 +00:00
|
|
|
syncStartTime: time.Now().AddDate(-1, 0, 0), // defaults to sync from 1 year ago
|
2020-10-20 05:11:04 +00:00
|
|
|
sessions: make(map[string]*ExchangeSession),
|
2021-02-02 18:26:41 +00:00
|
|
|
startTime: time.Now(),
|
2021-02-20 16:58:34 +00:00
|
|
|
|
2021-02-22 07:01:05 +00:00
|
|
|
syncStatus: SyncNotStarted,
|
2021-02-20 16:58:34 +00:00
|
|
|
PersistenceServiceFacade: &service.PersistenceServiceFacade{
|
|
|
|
Memory: service.NewMemoryService(),
|
|
|
|
},
|
2020-10-16 02:14:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-19 17:46:17 +00:00
|
|
|
func (environ *Environment) Session(name string) (*ExchangeSession, bool) {
|
|
|
|
s, ok := environ.sessions[name]
|
|
|
|
return s, ok
|
|
|
|
}
|
|
|
|
|
2020-11-07 12:34:34 +00:00
|
|
|
func (environ *Environment) Sessions() map[string]*ExchangeSession {
|
|
|
|
return environ.sessions
|
|
|
|
}
|
|
|
|
|
2021-02-18 14:40:46 +00:00
|
|
|
func (environ *Environment) SelectSessions(names ...string) map[string]*ExchangeSession {
|
|
|
|
if len(names) == 0 {
|
|
|
|
return environ.sessions
|
|
|
|
}
|
|
|
|
|
|
|
|
sessions := make(map[string]*ExchangeSession)
|
|
|
|
for _, name := range names {
|
2021-02-20 03:29:33 +00:00
|
|
|
if s, ok := environ.Session(name); ok {
|
2021-02-18 14:40:46 +00:00
|
|
|
sessions[name] = s
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sessions
|
|
|
|
}
|
|
|
|
|
2021-02-20 16:58:34 +00:00
|
|
|
func (environ *Environment) ConfigureDatabase(ctx context.Context) error {
|
|
|
|
// configureDB configures the database service based on the environment variable
|
|
|
|
if driver, ok := os.LookupEnv("DB_DRIVER"); ok {
|
|
|
|
|
|
|
|
if dsn, ok := os.LookupEnv("DB_DSN"); ok {
|
|
|
|
return environ.ConfigureDatabaseDriver(ctx, driver, dsn)
|
|
|
|
}
|
|
|
|
|
|
|
|
} else if dsn, ok := os.LookupEnv("SQLITE3_DSN"); ok {
|
|
|
|
|
|
|
|
return environ.ConfigureDatabaseDriver(ctx, "sqlite3", dsn)
|
|
|
|
|
|
|
|
} else if dsn, ok := os.LookupEnv("MYSQL_URL"); ok {
|
|
|
|
|
|
|
|
return environ.ConfigureDatabaseDriver(ctx, "mysql", dsn)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (environ *Environment) ConfigureDatabaseDriver(ctx context.Context, driver string, dsn string) error {
|
2021-02-06 01:48:05 +00:00
|
|
|
environ.DatabaseService = service.NewDatabaseService(driver, dsn)
|
|
|
|
err := environ.DatabaseService.Connect()
|
2021-02-02 09:26:35 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-01-14 07:10:11 +00:00
|
|
|
|
2021-02-16 08:30:01 +00:00
|
|
|
if err := environ.DatabaseService.Upgrade(ctx); err != nil {
|
2021-02-02 09:26:35 +00:00
|
|
|
return err
|
2021-01-14 07:10:11 +00:00
|
|
|
}
|
|
|
|
|
2021-02-06 01:48:05 +00:00
|
|
|
// get the db connection pool object to create other services
|
|
|
|
db := environ.DatabaseService.DB
|
2021-01-14 07:10:11 +00:00
|
|
|
environ.OrderService = &service.OrderService{DB: db}
|
2020-10-26 05:48:59 +00:00
|
|
|
environ.TradeService = &service.TradeService{DB: db}
|
2021-02-23 08:39:48 +00:00
|
|
|
environ.RewardService = &service.RewardService{DB: db}
|
|
|
|
|
|
|
|
environ.SyncService = &service.SyncService{
|
2021-03-14 03:04:56 +00:00
|
|
|
TradeService: environ.TradeService,
|
|
|
|
OrderService: environ.OrderService,
|
|
|
|
RewardService: environ.RewardService,
|
|
|
|
WithdrawService: &service.WithdrawService{DB: db},
|
|
|
|
DepositService: &service.DepositService{DB: db},
|
2020-10-26 05:48:59 +00:00
|
|
|
}
|
|
|
|
|
2021-02-06 01:48:05 +00:00
|
|
|
return nil
|
2020-10-26 05:48:59 +00:00
|
|
|
}
|
|
|
|
|
2021-01-19 17:46:17 +00:00
|
|
|
// AddExchangeSession adds the existing exchange session or pre-created exchange session
|
|
|
|
func (environ *Environment) AddExchangeSession(name string, session *ExchangeSession) *ExchangeSession {
|
2021-01-30 12:03:59 +00:00
|
|
|
// update Notifiability from the environment
|
|
|
|
session.Notifiability = environ.Notifiability
|
|
|
|
|
2020-10-16 02:14:36 +00:00
|
|
|
environ.sessions[name] = session
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
2021-01-19 17:46:17 +00:00
|
|
|
// AddExchange adds the given exchange with the session name, this is the default
|
|
|
|
func (environ *Environment) AddExchange(name string, exchange types.Exchange) (session *ExchangeSession) {
|
|
|
|
session = NewExchangeSession(name, exchange)
|
|
|
|
return environ.AddExchangeSession(name, session)
|
|
|
|
}
|
|
|
|
|
2021-02-21 08:52:47 +00:00
|
|
|
func (environ *Environment) ConfigureExchangeSessions(userConfig *Config) error {
|
2020-12-29 08:00:03 +00:00
|
|
|
if len(userConfig.Sessions) == 0 {
|
|
|
|
return environ.AddExchangesByViperKeys()
|
|
|
|
}
|
|
|
|
|
|
|
|
return environ.AddExchangesFromSessionConfig(userConfig.Sessions)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (environ *Environment) AddExchangesByViperKeys() error {
|
2021-05-26 16:35:51 +00:00
|
|
|
for _, n := range types.SupportedExchanges {
|
2020-12-29 08:00:03 +00:00
|
|
|
if viper.IsSet(string(n) + "-api-key") {
|
|
|
|
exchange, err := cmdutil.NewExchangeWithEnvVarPrefix(n, "")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
environ.AddExchange(n.String(), exchange)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-02 09:26:35 +00:00
|
|
|
func (environ *Environment) AddExchangesFromSessionConfig(sessions map[string]*ExchangeSession) error {
|
2021-05-12 03:59:29 +00:00
|
|
|
for sessionName, session := range sessions {
|
|
|
|
if err := InitExchangeSession(sessionName, session); err != nil {
|
2021-02-02 03:44:07 +00:00
|
|
|
return err
|
2020-12-21 08:38:41 +00:00
|
|
|
}
|
|
|
|
|
2021-01-19 17:46:17 +00:00
|
|
|
environ.AddExchangeSession(sessionName, session)
|
2020-12-29 08:00:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-10-28 08:27:25 +00:00
|
|
|
// Init prepares the data that will be used by the strategies
|
2020-10-16 02:14:36 +00:00
|
|
|
func (environ *Environment) Init(ctx context.Context) (err error) {
|
2020-10-28 08:27:25 +00:00
|
|
|
for n := range environ.sessions {
|
|
|
|
var session = environ.sessions[n]
|
2021-05-07 16:45:24 +00:00
|
|
|
if err = session.Init(ctx, environ); err != nil {
|
2021-02-02 18:26:41 +00:00
|
|
|
// we can skip initialized sessions
|
|
|
|
if err != ErrSessionAlreadyInitialized {
|
|
|
|
return err
|
|
|
|
}
|
2020-11-06 18:57:50 +00:00
|
|
|
}
|
2021-05-07 16:45:24 +00:00
|
|
|
}
|
2020-11-06 18:57:50 +00:00
|
|
|
|
2021-05-07 16:45:24 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (environ *Environment) Start(ctx context.Context) (err error) {
|
|
|
|
for n := range environ.sessions {
|
|
|
|
var session = environ.sessions[n]
|
|
|
|
if err = session.InitSymbols(ctx, environ); err != nil {
|
2021-05-02 15:58:34 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-10-28 08:27:25 +00:00
|
|
|
}
|
2021-05-07 16:45:24 +00:00
|
|
|
return
|
2020-10-28 08:27:25 +00:00
|
|
|
}
|
|
|
|
|
2020-12-07 03:43:17 +00:00
|
|
|
func (environ *Environment) ConfigurePersistence(conf *PersistenceConfig) error {
|
2020-12-06 11:36:04 +00:00
|
|
|
if conf.Redis != nil {
|
2020-12-07 04:03:56 +00:00
|
|
|
if err := env.Set(conf.Redis); err != nil {
|
2020-12-07 03:43:17 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-02-20 16:58:34 +00:00
|
|
|
environ.PersistenceServiceFacade.Redis = service.NewRedisPersistenceService(conf.Redis)
|
2020-12-06 11:36:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if conf.Json != nil {
|
2020-12-07 03:43:17 +00:00
|
|
|
if _, err := os.Stat(conf.Json.Directory); os.IsNotExist(err) {
|
|
|
|
if err2 := os.MkdirAll(conf.Json.Directory, 0777); err2 != nil {
|
2020-12-06 11:36:04 +00:00
|
|
|
log.WithError(err2).Errorf("can not create directory: %s", conf.Json.Directory)
|
2020-12-07 03:43:17 +00:00
|
|
|
return err2
|
2020-12-06 11:36:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-20 16:58:34 +00:00
|
|
|
environ.PersistenceServiceFacade.Json = &service.JsonPersistenceService{Directory: conf.Json.Directory}
|
2020-12-06 11:36:04 +00:00
|
|
|
}
|
2020-12-07 03:43:17 +00:00
|
|
|
|
|
|
|
return nil
|
2020-12-06 11:36:04 +00:00
|
|
|
}
|
|
|
|
|
2021-05-09 17:38:01 +00:00
|
|
|
// ConfigureNotificationRouting configures the notification rules
|
2020-10-30 21:21:17 +00:00
|
|
|
// for symbol-based routes, we should register the same symbol rules for each session.
|
|
|
|
// for session-based routes, we should set the fixed callbacks for each session
|
2021-02-21 08:52:47 +00:00
|
|
|
func (environ *Environment) ConfigureNotificationRouting(conf *NotificationConfig) error {
|
2020-10-30 21:21:17 +00:00
|
|
|
// configure routing here
|
|
|
|
if conf.SymbolChannels != nil {
|
|
|
|
environ.SymbolChannelRouter.AddRoute(conf.SymbolChannels)
|
|
|
|
}
|
|
|
|
if conf.SessionChannels != nil {
|
|
|
|
environ.SessionChannelRouter.AddRoute(conf.SessionChannels)
|
|
|
|
}
|
|
|
|
|
|
|
|
if conf.Routing != nil {
|
|
|
|
// configure passive object notification routing
|
|
|
|
switch conf.Routing.Trade {
|
2020-11-17 00:19:22 +00:00
|
|
|
case "$silent": // silent, do not setup notification
|
|
|
|
|
2020-10-30 21:21:17 +00:00
|
|
|
case "$session":
|
|
|
|
defaultTradeUpdateHandler := func(trade types.Trade) {
|
2021-05-12 04:43:03 +00:00
|
|
|
environ.Notify(&trade)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
for name := range environ.sessions {
|
|
|
|
session := environ.sessions[name]
|
|
|
|
|
|
|
|
// if we can route session name to channel successfully...
|
|
|
|
channel, ok := environ.SessionChannelRouter.Route(name)
|
|
|
|
if ok {
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnTradeUpdate(func(trade types.Trade) {
|
2021-05-12 04:43:03 +00:00
|
|
|
environ.NotifyTo(channel, &trade)
|
2020-10-30 21:21:17 +00:00
|
|
|
})
|
|
|
|
} else {
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnTradeUpdate(defaultTradeUpdateHandler)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
case "$symbol":
|
|
|
|
// configure object routes for Trade
|
|
|
|
environ.ObjectChannelRouter.Route(func(obj interface{}) (channel string, ok bool) {
|
|
|
|
trade, matched := obj.(*types.Trade)
|
|
|
|
if !matched {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
channel, ok = environ.SymbolChannelRouter.Route(trade.Symbol)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
|
|
|
|
// use same handler for each session
|
|
|
|
handler := func(trade types.Trade) {
|
2020-10-30 21:31:26 +00:00
|
|
|
channel, ok := environ.RouteObject(&trade)
|
2020-10-30 21:21:17 +00:00
|
|
|
if ok {
|
2021-05-12 04:43:03 +00:00
|
|
|
environ.NotifyTo(channel, &trade)
|
2020-10-30 21:21:17 +00:00
|
|
|
} else {
|
2021-05-12 04:43:03 +00:00
|
|
|
environ.Notify(&trade)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, session := range environ.sessions {
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnTradeUpdate(handler)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch conf.Routing.Order {
|
|
|
|
|
2020-11-17 00:19:22 +00:00
|
|
|
case "$silent": // silent, do not setup notification
|
|
|
|
|
2020-10-30 21:21:17 +00:00
|
|
|
case "$session":
|
|
|
|
defaultOrderUpdateHandler := func(order types.Order) {
|
|
|
|
text := util.Render(TemplateOrderReport, order)
|
2020-10-30 21:31:26 +00:00
|
|
|
environ.Notify(text, &order)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
for name := range environ.sessions {
|
|
|
|
session := environ.sessions[name]
|
|
|
|
|
|
|
|
// if we can route session name to channel successfully...
|
|
|
|
channel, ok := environ.SessionChannelRouter.Route(name)
|
|
|
|
if ok {
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnOrderUpdate(func(order types.Order) {
|
2020-10-30 21:21:17 +00:00
|
|
|
text := util.Render(TemplateOrderReport, order)
|
2020-10-30 21:31:26 +00:00
|
|
|
environ.NotifyTo(channel, text, &order)
|
2020-10-30 21:21:17 +00:00
|
|
|
})
|
|
|
|
} else {
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnOrderUpdate(defaultOrderUpdateHandler)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
case "$symbol":
|
|
|
|
// add object route
|
|
|
|
environ.ObjectChannelRouter.Route(func(obj interface{}) (channel string, ok bool) {
|
|
|
|
order, matched := obj.(*types.Order)
|
|
|
|
if !matched {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
channel, ok = environ.SymbolChannelRouter.Route(order.Symbol)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
|
|
|
|
// use same handler for each session
|
|
|
|
handler := func(order types.Order) {
|
|
|
|
text := util.Render(TemplateOrderReport, order)
|
2020-10-30 21:31:26 +00:00
|
|
|
channel, ok := environ.RouteObject(&order)
|
2020-10-30 21:21:17 +00:00
|
|
|
if ok {
|
2020-10-30 21:31:26 +00:00
|
|
|
environ.NotifyTo(channel, text, &order)
|
2020-10-30 21:21:17 +00:00
|
|
|
} else {
|
2020-10-30 21:31:26 +00:00
|
|
|
environ.Notify(text, &order)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, session := range environ.sessions {
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnOrderUpdate(handler)
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch conf.Routing.SubmitOrder {
|
2020-11-17 00:19:22 +00:00
|
|
|
|
|
|
|
case "$silent": // silent, do not setup notification
|
|
|
|
|
2020-10-30 21:21:17 +00:00
|
|
|
case "$symbol":
|
|
|
|
// add object route
|
|
|
|
environ.ObjectChannelRouter.Route(func(obj interface{}) (channel string, ok bool) {
|
|
|
|
order, matched := obj.(*types.SubmitOrder)
|
|
|
|
if !matched {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
channel, ok = environ.SymbolChannelRouter.Route(order.Symbol)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2021-12-04 18:16:48 +00:00
|
|
|
// currently, not used
|
|
|
|
// FIXME: this is causing cyclic import
|
|
|
|
/*
|
2020-10-30 21:21:17 +00:00
|
|
|
switch conf.Routing.PnL {
|
|
|
|
case "$symbol":
|
|
|
|
environ.ObjectChannelRouter.Route(func(obj interface{}) (channel string, ok bool) {
|
|
|
|
report, matched := obj.(*pnl.AverageCostPnlReport)
|
|
|
|
if !matched {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
channel, ok = environ.SymbolChannelRouter.Route(report.Symbol)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|
2021-12-04 18:16:48 +00:00
|
|
|
*/
|
2020-10-30 21:21:17 +00:00
|
|
|
|
|
|
|
}
|
2020-12-07 03:43:17 +00:00
|
|
|
return nil
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
|
2020-11-10 06:19:33 +00:00
|
|
|
func (environ *Environment) SetStartTime(t time.Time) *Environment {
|
|
|
|
environ.startTime = t
|
|
|
|
return environ
|
|
|
|
}
|
|
|
|
|
2021-02-20 03:29:33 +00:00
|
|
|
// SetSyncStartTime overrides the default trade scan time (-7 days)
|
|
|
|
func (environ *Environment) SetSyncStartTime(t time.Time) *Environment {
|
|
|
|
environ.syncStartTime = t
|
2020-10-28 08:27:25 +00:00
|
|
|
return environ
|
|
|
|
}
|
|
|
|
|
|
|
|
func (environ *Environment) Connect(ctx context.Context) 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]
|
|
|
|
var logger = log.WithField("session", n)
|
|
|
|
|
2020-10-19 14:26:43 +00:00
|
|
|
if len(session.Subscriptions) == 0 {
|
2021-05-17 12:03:42 +00:00
|
|
|
logger.Warnf("exchange session %s has no subscriptions", session.Name)
|
2020-11-15 05:27:33 +00:00
|
|
|
} else {
|
|
|
|
// add the subscribe requests to the stream
|
|
|
|
for _, s := range session.Subscriptions {
|
|
|
|
logger.Infof("subscribing %s %s %v", s.Symbol, s.Channel, s.Options)
|
2021-05-27 07:09:04 +00:00
|
|
|
session.MarketDataStream.Subscribe(s.Channel, s.Symbol, s.Options)
|
2020-11-15 05:27:33 +00:00
|
|
|
}
|
2020-10-28 08:27:25 +00:00
|
|
|
}
|
|
|
|
|
2021-05-27 07:09:04 +00:00
|
|
|
logger.Infof("connecting %s market data stream...", session.Name)
|
|
|
|
if err := session.MarketDataStream.Connect(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-28 11:01:55 +00:00
|
|
|
if !session.PublicOnly {
|
|
|
|
logger.Infof("connecting %s user data stream...", session.Name)
|
|
|
|
if err := session.UserDataStream.Connect(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-10-16 02:14:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2020-11-08 13:52:44 +00:00
|
|
|
|
2021-02-22 06:14:39 +00:00
|
|
|
func (environ *Environment) IsSyncing() (status SyncStatus) {
|
2021-02-21 11:36:03 +00:00
|
|
|
environ.syncStatusMutex.Lock()
|
2021-02-22 06:14:39 +00:00
|
|
|
status = environ.syncStatus
|
|
|
|
environ.syncStatusMutex.Unlock()
|
|
|
|
return status
|
2021-02-21 11:36:03 +00:00
|
|
|
}
|
|
|
|
|
2021-02-22 06:14:39 +00:00
|
|
|
func (environ *Environment) setSyncing(status SyncStatus) {
|
2021-02-21 11:36:03 +00:00
|
|
|
environ.syncStatusMutex.Lock()
|
2021-02-22 06:14:39 +00:00
|
|
|
environ.syncStatus = status
|
2021-02-21 11:36:03 +00:00
|
|
|
environ.syncStatusMutex.Unlock()
|
2021-02-20 03:29:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Sync syncs all registered exchange sessions
|
|
|
|
func (environ *Environment) Sync(ctx context.Context) error {
|
2021-02-28 07:05:49 +00:00
|
|
|
if environ.SyncService == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-20 03:29:33 +00:00
|
|
|
environ.syncMutex.Lock()
|
|
|
|
defer environ.syncMutex.Unlock()
|
2021-02-21 11:36:03 +00:00
|
|
|
|
2021-02-22 06:14:39 +00:00
|
|
|
environ.setSyncing(Syncing)
|
|
|
|
defer environ.setSyncing(SyncDone)
|
2021-02-20 03:29:33 +00:00
|
|
|
|
|
|
|
for _, session := range environ.sessions {
|
|
|
|
if err := environ.syncSession(ctx, session); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (environ *Environment) SyncSession(ctx context.Context, session *ExchangeSession, defaultSymbols ...string) error {
|
2021-04-09 04:44:30 +00:00
|
|
|
if environ.SyncService == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-20 03:29:33 +00:00
|
|
|
environ.syncMutex.Lock()
|
|
|
|
defer environ.syncMutex.Unlock()
|
|
|
|
|
2021-02-22 06:14:39 +00:00
|
|
|
environ.setSyncing(Syncing)
|
|
|
|
defer environ.setSyncing(SyncDone)
|
2021-02-20 03:29:33 +00:00
|
|
|
|
|
|
|
return environ.syncSession(ctx, session, defaultSymbols...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (environ *Environment) syncSession(ctx context.Context, session *ExchangeSession, defaultSymbols ...string) error {
|
2021-02-19 02:42:24 +00:00
|
|
|
symbols, err := getSessionSymbols(session, defaultSymbols...)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-02-22 07:01:05 +00:00
|
|
|
log.Infof("syncing symbols %v from session %s", symbols, session.Name)
|
|
|
|
|
2021-02-23 08:39:48 +00:00
|
|
|
return environ.SyncService.SyncSessionSymbols(ctx, session.Exchange, environ.syncStartTime, symbols...)
|
2020-11-08 13:52:44 +00:00
|
|
|
}
|
2021-02-19 02:42:24 +00:00
|
|
|
|
|
|
|
func getSessionSymbols(session *ExchangeSession, defaultSymbols ...string) ([]string, error) {
|
|
|
|
if session.IsolatedMargin {
|
|
|
|
return []string{session.IsolatedMarginSymbol}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(defaultSymbols) > 0 {
|
|
|
|
return defaultSymbols, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return session.FindPossibleSymbols()
|
|
|
|
}
|
2021-02-21 08:52:47 +00:00
|
|
|
|
|
|
|
func (environ *Environment) ConfigureNotificationSystem(userConfig *Config) error {
|
|
|
|
environ.Notifiability = Notifiability{
|
|
|
|
SymbolChannelRouter: NewPatternChannelRouter(nil),
|
|
|
|
SessionChannelRouter: NewPatternChannelRouter(nil),
|
|
|
|
ObjectChannelRouter: NewObjectChannelRouter(),
|
|
|
|
}
|
|
|
|
|
|
|
|
slackToken := viper.GetString("slack-token")
|
|
|
|
if len(slackToken) > 0 && userConfig.Notifications != nil {
|
|
|
|
if conf := userConfig.Notifications.Slack; conf != nil {
|
|
|
|
if conf.ErrorChannel != "" {
|
2021-02-22 09:06:43 +00:00
|
|
|
log.Debugf("found slack configured, setting up log hook...")
|
2021-02-21 08:52:47 +00:00
|
|
|
log.AddHook(slacklog.NewLogHook(slackToken, conf.ErrorChannel))
|
|
|
|
}
|
|
|
|
|
2021-02-22 09:06:43 +00:00
|
|
|
log.Debugf("adding slack notifier with default channel: %s", conf.DefaultChannel)
|
2021-02-21 08:52:47 +00:00
|
|
|
var notifier = slacknotifier.New(slackToken, conf.DefaultChannel)
|
|
|
|
environ.AddNotifier(notifier)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-21 08:55:45 +00:00
|
|
|
persistence := environ.PersistenceServiceFacade.Get()
|
2021-02-21 08:52:47 +00:00
|
|
|
telegramBotToken := viper.GetString("telegram-bot-token")
|
|
|
|
if len(telegramBotToken) > 0 {
|
|
|
|
tt := strings.Split(telegramBotToken, ":")
|
|
|
|
telegramID := tt[0]
|
|
|
|
|
|
|
|
bot, err := telebot.NewBot(telebot.Settings{
|
|
|
|
// You can also set custom API URL.
|
|
|
|
// If field is empty it equals to "https://api.telegram.org".
|
|
|
|
// URL: "http://195.129.111.17:8012",
|
|
|
|
Token: telegramBotToken,
|
|
|
|
Poller: &telebot.LongPoller{Timeout: 10 * time.Second},
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// allocate a store, so that we can save the chatID for the owner
|
|
|
|
var sessionStore = persistence.NewStore("bbgo", "telegram", telegramID)
|
|
|
|
var interaction = telegramnotifier.NewInteraction(bot, sessionStore)
|
|
|
|
|
|
|
|
authToken := viper.GetString("telegram-bot-auth-token")
|
|
|
|
if len(authToken) > 0 {
|
|
|
|
interaction.SetAuthToken(authToken)
|
|
|
|
|
2021-02-22 09:06:43 +00:00
|
|
|
log.Debugf("telegram bot auth token is set, using fixed token for authorization...")
|
2021-02-21 08:52:47 +00:00
|
|
|
|
|
|
|
printTelegramAuthTokenGuide(authToken)
|
|
|
|
}
|
|
|
|
|
|
|
|
var session telegramnotifier.Session
|
2021-05-09 17:38:01 +00:00
|
|
|
var qrcodeImagePath = fmt.Sprintf("otp-%s.png", telegramID)
|
2021-02-21 08:52:47 +00:00
|
|
|
if err := sessionStore.Load(&session); err != nil || session.Owner == nil {
|
|
|
|
log.Warnf("telegram session not found, generating new one-time password key for new telegram session...")
|
|
|
|
|
|
|
|
key, err := setupNewOTPKey(qrcodeImagePath)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to setup totp (time-based one time password) key")
|
|
|
|
}
|
|
|
|
|
2021-05-09 17:38:01 +00:00
|
|
|
printTelegramOtpAuthGuide(qrcodeImagePath)
|
|
|
|
|
2021-02-21 08:52:47 +00:00
|
|
|
session = telegramnotifier.NewSession(key)
|
|
|
|
if err := sessionStore.Save(&session); err != nil {
|
|
|
|
return errors.Wrap(err, "failed to save session")
|
|
|
|
}
|
2021-05-09 17:38:01 +00:00
|
|
|
} else if session.OneTimePasswordKey != nil {
|
|
|
|
log.Infof("telegram session loaded: %+v", session)
|
|
|
|
|
|
|
|
printTelegramOtpAuthGuide(qrcodeImagePath)
|
2021-02-21 08:52:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
go interaction.Start(session)
|
|
|
|
|
2021-10-15 08:10:39 +00:00
|
|
|
var opts []telegramnotifier.Option
|
|
|
|
|
|
|
|
if userConfig.Notifications != nil && userConfig.Notifications.Telegram != nil {
|
2021-11-25 10:49:29 +00:00
|
|
|
log.Infof("telegram broadcast is enabled")
|
2021-10-15 08:10:39 +00:00
|
|
|
opts = append(opts, telegramnotifier.UseBroadcast())
|
|
|
|
}
|
|
|
|
|
|
|
|
var notifier = telegramnotifier.New(interaction, opts...)
|
2021-02-21 08:52:47 +00:00
|
|
|
environ.Notifiability.AddNotifier(notifier)
|
|
|
|
}
|
|
|
|
|
2021-12-04 02:37:21 +00:00
|
|
|
if userConfig.Notifications == nil {
|
|
|
|
userConfig.Notifications = &NotificationConfig{
|
|
|
|
Routing : &SlackNotificationRouting{
|
|
|
|
Trade: "$session",
|
|
|
|
Order: "$session",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-21 08:52:47 +00:00
|
|
|
if userConfig.Notifications != nil {
|
|
|
|
if err := environ.ConfigureNotificationRouting(userConfig.Notifications); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func writeOTPKeyAsQRCodePNG(key *otp.Key, imagePath string) error {
|
|
|
|
// Convert TOTP key into a PNG
|
|
|
|
var buf bytes.Buffer
|
|
|
|
img, err := key.Image(512, 512)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := png.Encode(&buf, img); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := ioutil.WriteFile(imagePath, buf.Bytes(), 0644); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// setupNewOTPKey generates a new otp key and save the secret as a qrcode image
|
|
|
|
func setupNewOTPKey(qrcodeImagePath string) (*otp.Key, error) {
|
|
|
|
key, err := service.NewDefaultTotpKey()
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "failed to setup totp (time-based one time password) key")
|
|
|
|
}
|
|
|
|
|
|
|
|
printOtpKey(key)
|
|
|
|
|
|
|
|
if err := writeOTPKeyAsQRCodePNG(key, qrcodeImagePath); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func printOtpKey(key *otp.Key) {
|
|
|
|
fmt.Println("")
|
|
|
|
fmt.Println("====================PLEASE STORE YOUR OTP KEY=======================")
|
|
|
|
fmt.Println("")
|
|
|
|
fmt.Printf("Issuer: %s\n", key.Issuer())
|
|
|
|
fmt.Printf("AccountName: %s\n", key.AccountName())
|
|
|
|
fmt.Printf("Secret: %s\n", key.Secret())
|
|
|
|
fmt.Printf("Key URL: %s\n", key.URL())
|
|
|
|
fmt.Println("")
|
|
|
|
fmt.Println("====================================================================")
|
|
|
|
fmt.Println("")
|
|
|
|
}
|
|
|
|
|
|
|
|
func printTelegramOtpAuthGuide(qrcodeImagePath string) {
|
2021-02-22 09:06:43 +00:00
|
|
|
fmt.Printf(`
|
|
|
|
To scan your OTP QR code, please run the following command:
|
|
|
|
|
|
|
|
open %s
|
|
|
|
|
|
|
|
send the auth command with the generated one-time password to the bbgo bot you created to enable the notification:
|
|
|
|
|
|
|
|
/auth {code}
|
|
|
|
|
|
|
|
`, qrcodeImagePath)
|
2021-02-21 08:52:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func printTelegramAuthTokenGuide(token string) {
|
2021-02-22 09:06:43 +00:00
|
|
|
fmt.Printf(`
|
|
|
|
send the following command to the bbgo bot you created to enable the notification:
|
|
|
|
|
|
|
|
/auth %s
|
|
|
|
|
|
|
|
`, token)
|
2021-02-21 08:52:47 +00:00
|
|
|
}
|