2020-10-16 02:14:36 +00:00
|
|
|
package bbgo
|
|
|
|
|
2020-10-18 04:23:00 +00:00
|
|
|
import (
|
2021-01-26 09:21:18 +00:00
|
|
|
"context"
|
2020-12-21 05:47:40 +00:00
|
|
|
"fmt"
|
2021-01-30 02:51:01 +00:00
|
|
|
"strings"
|
2021-01-26 09:21:18 +00:00
|
|
|
"time"
|
2020-12-21 05:47:40 +00:00
|
|
|
|
2021-12-27 09:16:30 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2021-12-26 07:29:42 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
2021-06-10 11:05:07 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/cmd/cmdutil"
|
2021-05-16 07:03:36 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2020-10-28 01:13:57 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/indicator"
|
2021-01-30 02:51:01 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/service"
|
2020-10-18 04:23:00 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2021-02-19 02:42:24 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2020-10-18 04:23:00 +00:00
|
|
|
)
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2021-10-18 07:23:22 +00:00
|
|
|
var (
|
|
|
|
debugEWMA = false
|
2021-10-18 09:26:03 +00:00
|
|
|
debugSMA = false
|
2021-10-18 07:23:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2021-11-21 18:14:44 +00:00
|
|
|
// when using --dotenv option, the dotenv is loaded from command.PersistentPreRunE, not init.
|
|
|
|
// hence here the env var won't enable the debug flag
|
2021-10-18 09:26:03 +00:00
|
|
|
util.SetEnvVarBool("DEBUG_EWMA", &debugEWMA)
|
|
|
|
util.SetEnvVarBool("DEBUG_SMA", &debugSMA)
|
2021-10-18 07:23:22 +00:00
|
|
|
}
|
|
|
|
|
2020-10-28 01:13:57 +00:00
|
|
|
type StandardIndicatorSet struct {
|
|
|
|
Symbol string
|
|
|
|
// Standard indicators
|
|
|
|
// interval -> window
|
2021-12-19 06:16:44 +00:00
|
|
|
sma map[types.IntervalWindow]*indicator.SMA
|
|
|
|
ewma map[types.IntervalWindow]*indicator.EWMA
|
|
|
|
boll map[types.IntervalWindow]*indicator.BOLL
|
|
|
|
stoch map[types.IntervalWindow]*indicator.STOCH
|
|
|
|
volatility map[types.IntervalWindow]*indicator.VOLATILITY
|
2020-10-28 23:40:02 +00:00
|
|
|
|
|
|
|
store *MarketDataStore
|
2020-10-28 01:13:57 +00:00
|
|
|
}
|
|
|
|
|
2020-10-28 23:40:02 +00:00
|
|
|
func NewStandardIndicatorSet(symbol string, store *MarketDataStore) *StandardIndicatorSet {
|
2020-10-28 01:13:57 +00:00
|
|
|
set := &StandardIndicatorSet{
|
2021-12-19 06:16:44 +00:00
|
|
|
Symbol: symbol,
|
|
|
|
sma: make(map[types.IntervalWindow]*indicator.SMA),
|
|
|
|
ewma: make(map[types.IntervalWindow]*indicator.EWMA),
|
|
|
|
boll: make(map[types.IntervalWindow]*indicator.BOLL),
|
|
|
|
stoch: make(map[types.IntervalWindow]*indicator.STOCH),
|
|
|
|
volatility: make(map[types.IntervalWindow]*indicator.VOLATILITY),
|
|
|
|
store: store,
|
2020-10-28 01:13:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// let us pre-defined commonly used intervals
|
2020-10-28 01:43:19 +00:00
|
|
|
for interval := range types.SupportedIntervals {
|
2020-10-28 01:13:57 +00:00
|
|
|
for _, window := range []int{7, 25, 99} {
|
2020-10-29 05:08:33 +00:00
|
|
|
iw := types.IntervalWindow{Interval: interval, Window: window}
|
2020-11-30 05:06:35 +00:00
|
|
|
set.sma[iw] = &indicator.SMA{IntervalWindow: iw}
|
|
|
|
set.sma[iw].Bind(store)
|
2021-10-18 07:23:22 +00:00
|
|
|
if debugSMA {
|
|
|
|
set.sma[iw].OnUpdate(func(value float64) {
|
|
|
|
log.Infof("%s SMA %s: %f", symbol, iw.String(), value)
|
|
|
|
})
|
|
|
|
}
|
2020-10-28 23:40:02 +00:00
|
|
|
|
2020-11-30 05:06:35 +00:00
|
|
|
set.ewma[iw] = &indicator.EWMA{IntervalWindow: iw}
|
|
|
|
set.ewma[iw].Bind(store)
|
2021-10-18 07:23:22 +00:00
|
|
|
|
2021-10-18 09:26:03 +00:00
|
|
|
// if debug EWMA is enabled, we add the debug handler
|
2021-10-18 07:23:22 +00:00
|
|
|
if debugEWMA {
|
|
|
|
set.ewma[iw].OnUpdate(func(value float64) {
|
|
|
|
log.Infof("%s EWMA %s: %f", symbol, iw.String(), value)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-10-28 01:13:57 +00:00
|
|
|
}
|
2020-10-29 09:51:20 +00:00
|
|
|
|
2020-11-30 05:06:35 +00:00
|
|
|
// setup boll indicator, we may refactor boll indicator by subscribing SMA indicator,
|
2020-10-29 09:51:20 +00:00
|
|
|
// however, since general used BOLLINGER band use window 21, which is not in the existing SMA indicator sets.
|
2020-11-30 05:06:35 +00:00
|
|
|
// Pull out the bandwidth configuration as the boll Key
|
2020-10-29 09:51:20 +00:00
|
|
|
iw := types.IntervalWindow{Interval: interval, Window: 21}
|
2020-11-30 05:06:35 +00:00
|
|
|
set.boll[iw] = &indicator.BOLL{IntervalWindow: iw, K: 2.0}
|
|
|
|
set.boll[iw].Bind(store)
|
2020-10-28 01:13:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return set
|
|
|
|
}
|
|
|
|
|
2020-11-30 05:06:35 +00:00
|
|
|
// BOLL returns the bollinger band indicator of the given interval and the window,
|
2020-10-29 10:02:19 +00:00
|
|
|
// Please note that the K for std dev is fixed and defaults to 2.0
|
2020-11-30 05:06:35 +00:00
|
|
|
func (set *StandardIndicatorSet) BOLL(iw types.IntervalWindow, bandWidth float64) *indicator.BOLL {
|
|
|
|
inc, ok := set.boll[iw]
|
2020-10-29 10:02:19 +00:00
|
|
|
if !ok {
|
2021-05-26 00:20:31 +00:00
|
|
|
inc = &indicator.BOLL{IntervalWindow: iw, K: bandWidth}
|
2020-10-29 10:02:19 +00:00
|
|
|
inc.Bind(set.store)
|
2020-11-30 05:06:35 +00:00
|
|
|
set.boll[iw] = inc
|
2020-10-29 10:02:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return inc
|
|
|
|
}
|
|
|
|
|
2020-11-30 05:06:35 +00:00
|
|
|
// SMA returns the simple moving average indicator of the given interval and the window size.
|
|
|
|
func (set *StandardIndicatorSet) SMA(iw types.IntervalWindow) *indicator.SMA {
|
|
|
|
inc, ok := set.sma[iw]
|
2020-10-28 23:40:02 +00:00
|
|
|
if !ok {
|
2021-05-26 00:20:31 +00:00
|
|
|
inc = &indicator.SMA{IntervalWindow: iw}
|
2020-10-28 23:40:02 +00:00
|
|
|
inc.Bind(set.store)
|
2020-11-30 05:06:35 +00:00
|
|
|
set.sma[iw] = inc
|
2020-10-28 01:13:57 +00:00
|
|
|
}
|
|
|
|
|
2020-10-28 23:40:02 +00:00
|
|
|
return inc
|
2020-10-28 01:13:57 +00:00
|
|
|
}
|
|
|
|
|
2021-05-02 12:58:32 +00:00
|
|
|
// EWMA returns the exponential weighed moving average indicator of the given interval and the window size.
|
2020-11-30 05:06:35 +00:00
|
|
|
func (set *StandardIndicatorSet) EWMA(iw types.IntervalWindow) *indicator.EWMA {
|
|
|
|
inc, ok := set.ewma[iw]
|
2020-10-28 23:44:22 +00:00
|
|
|
if !ok {
|
2021-05-26 00:20:31 +00:00
|
|
|
inc = &indicator.EWMA{IntervalWindow: iw}
|
2020-10-28 23:44:22 +00:00
|
|
|
inc.Bind(set.store)
|
2020-11-30 05:06:35 +00:00
|
|
|
set.ewma[iw] = inc
|
2020-10-28 23:44:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return inc
|
|
|
|
}
|
|
|
|
|
2021-05-26 00:20:31 +00:00
|
|
|
func (set *StandardIndicatorSet) STOCH(iw types.IntervalWindow) *indicator.STOCH {
|
|
|
|
inc, ok := set.stoch[iw]
|
|
|
|
if !ok {
|
|
|
|
inc = &indicator.STOCH{IntervalWindow: iw}
|
|
|
|
inc.Bind(set.store)
|
|
|
|
set.stoch[iw] = inc
|
|
|
|
}
|
|
|
|
|
|
|
|
return inc
|
|
|
|
}
|
|
|
|
|
2021-12-19 06:16:44 +00:00
|
|
|
// VOLATILITY returns the volatility(stddev) indicator of the given interval and the window size.
|
|
|
|
func (set *StandardIndicatorSet) VOLATILITY(iw types.IntervalWindow) *indicator.VOLATILITY {
|
|
|
|
inc, ok := set.volatility[iw]
|
|
|
|
if !ok {
|
|
|
|
inc = &indicator.VOLATILITY{IntervalWindow: iw}
|
|
|
|
inc.Bind(set.store)
|
|
|
|
set.volatility[iw] = inc
|
|
|
|
}
|
|
|
|
|
|
|
|
return inc
|
|
|
|
}
|
|
|
|
|
2020-11-17 00:19:22 +00:00
|
|
|
// ExchangeSession presents the exchange connection Session
|
2020-10-16 02:14:36 +00:00
|
|
|
// It also maintains and collects the data returned from the stream.
|
|
|
|
type ExchangeSession struct {
|
2020-11-17 00:19:22 +00:00
|
|
|
// exchange Session based notification system
|
2020-10-30 20:36:45 +00:00
|
|
|
// we make it as a value field so that we can configure it separately
|
2021-02-02 18:26:41 +00:00
|
|
|
Notifiability `json:"-" yaml:"-"`
|
2020-10-29 15:06:36 +00:00
|
|
|
|
2021-02-02 09:26:35 +00:00
|
|
|
// ---------------------------
|
|
|
|
// Session config fields
|
|
|
|
// ---------------------------
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2021-02-02 09:26:35 +00:00
|
|
|
// Exchange Session name
|
2021-05-30 07:25:00 +00:00
|
|
|
Name string `json:"name,omitempty" yaml:"name,omitempty"`
|
2021-05-30 06:46:48 +00:00
|
|
|
ExchangeName types.ExchangeName `json:"exchange" yaml:"exchange"`
|
2021-05-30 07:25:00 +00:00
|
|
|
EnvVarPrefix string `json:"envVarPrefix" yaml:"envVarPrefix"`
|
|
|
|
Key string `json:"key,omitempty" yaml:"key,omitempty"`
|
|
|
|
Secret string `json:"secret,omitempty" yaml:"secret,omitempty"`
|
2021-12-25 15:28:00 +00:00
|
|
|
Passphrase string `json:"passphrase,omitempty" yaml:"passphrase,omitempty"`
|
2021-05-30 07:25:00 +00:00
|
|
|
SubAccount string `json:"subAccount,omitempty" yaml:"subAccount,omitempty"`
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2021-05-12 03:16:20 +00:00
|
|
|
// Withdrawal is used for enabling withdrawal functions
|
2021-05-16 09:58:51 +00:00
|
|
|
Withdrawal bool `json:"withdrawal,omitempty" yaml:"withdrawal,omitempty"`
|
|
|
|
MakerFeeRate fixedpoint.Value `json:"makerFeeRate,omitempty" yaml:"makerFeeRate,omitempty"`
|
|
|
|
TakerFeeRate fixedpoint.Value `json:"takerFeeRate,omitempty" yaml:"takerFeeRate,omitempty"`
|
2021-05-12 03:16:20 +00:00
|
|
|
|
2021-02-02 09:26:35 +00:00
|
|
|
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"`
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-12-13 15:16:58 +00:00
|
|
|
Futures bool `json:"futures,omitempty" yaml:"futures"`
|
|
|
|
IsolatedFutures bool `json:"isolatedFutures,omitempty" yaml:"isolatedFutures,omitempty"`
|
|
|
|
IsolatedFuturesSymbol string `json:"isolatedFuturesSymbol,omitempty" yaml:"isolatedFuturesSymbol,omitempty"`
|
|
|
|
|
2021-02-02 09:26:35 +00:00
|
|
|
// ---------------------------
|
|
|
|
// Runtime fields
|
|
|
|
// ---------------------------
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-02-02 09:26:35 +00:00
|
|
|
// The exchange account states
|
2021-02-03 01:34:53 +00:00
|
|
|
Account *types.Account `json:"-" yaml:"-"`
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-02-03 01:34:53 +00:00
|
|
|
IsInitialized bool `json:"-" yaml:"-"`
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-05-12 10:58:20 +00:00
|
|
|
OrderExecutor *ExchangeOrderExecutor `json:"orderExecutor,omitempty" yaml:"orderExecutor,omitempty"`
|
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
// UserDataStream is the connection stream of the exchange
|
|
|
|
UserDataStream types.Stream `json:"-" yaml:"-"`
|
|
|
|
MarketDataStream types.Stream `json:"-" yaml:"-"`
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2021-12-25 13:04:47 +00:00
|
|
|
// Subscriptions
|
|
|
|
// this is a read-only field when running strategy
|
2021-02-02 18:26:41 +00:00
|
|
|
Subscriptions map[types.Subscription]types.Subscription `json:"-" yaml:"-"`
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
Exchange types.Exchange `json:"-" yaml:"-"`
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2021-05-12 03:59:29 +00:00
|
|
|
// Trades collects the executed trades from the exchange
|
|
|
|
// map: symbol -> []trade
|
|
|
|
Trades map[string]*types.TradeSlice `json:"-" yaml:"-"`
|
|
|
|
|
2020-10-18 04:30:13 +00:00
|
|
|
// markets defines market configuration of a symbol
|
2021-01-25 06:32:46 +00:00
|
|
|
markets map[string]types.Market
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2021-06-10 11:05:07 +00:00
|
|
|
// orderBooks stores the streaming order book
|
|
|
|
orderBooks map[string]*types.StreamOrderBook
|
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
// startPrices is used for backtest
|
2021-01-25 06:32:46 +00:00
|
|
|
startPrices map[string]float64
|
2020-11-10 11:06:20 +00:00
|
|
|
|
2021-01-26 09:23:40 +00:00
|
|
|
lastPrices map[string]float64
|
|
|
|
lastPriceUpdatedAt time.Time
|
2020-10-16 02:14:36 +00:00
|
|
|
|
2020-10-28 01:13:57 +00:00
|
|
|
// marketDataStores contains the market data store of each market
|
2021-01-25 06:32:46 +00:00
|
|
|
marketDataStores map[string]*MarketDataStore
|
2020-10-22 02:54:03 +00:00
|
|
|
|
2021-12-11 11:16:16 +00:00
|
|
|
positions map[string]*types.Position
|
2021-01-20 08:28:27 +00:00
|
|
|
|
2020-10-28 01:13:57 +00:00
|
|
|
// standard indicators of each market
|
2021-01-25 06:32:46 +00:00
|
|
|
standardIndicatorSets map[string]*StandardIndicatorSet
|
2020-10-28 01:13:57 +00:00
|
|
|
|
2021-01-25 06:32:46 +00:00
|
|
|
orderStores map[string]*OrderStore
|
2021-01-21 06:51:37 +00:00
|
|
|
|
2021-01-30 02:51:01 +00:00
|
|
|
usedSymbols map[string]struct{}
|
|
|
|
initializedSymbols map[string]struct{}
|
2021-02-01 09:13:54 +00:00
|
|
|
|
|
|
|
logger *log.Entry
|
2020-10-17 15:51:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewExchangeSession(name string, exchange types.Exchange) *ExchangeSession {
|
2021-05-27 07:11:44 +00:00
|
|
|
userDataStream := exchange.NewStream()
|
|
|
|
marketDataStream := exchange.NewStream()
|
|
|
|
marketDataStream.SetPublicOnly()
|
|
|
|
|
2021-05-12 03:59:29 +00:00
|
|
|
session := &ExchangeSession{
|
2020-10-29 15:06:36 +00:00
|
|
|
Notifiability: Notifiability{
|
|
|
|
SymbolChannelRouter: NewPatternChannelRouter(nil),
|
|
|
|
SessionChannelRouter: NewPatternChannelRouter(nil),
|
|
|
|
ObjectChannelRouter: NewObjectChannelRouter(),
|
|
|
|
},
|
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
Name: name,
|
|
|
|
Exchange: exchange,
|
2021-05-27 07:11:44 +00:00
|
|
|
UserDataStream: userDataStream,
|
|
|
|
MarketDataStream: marketDataStream,
|
2021-05-27 06:45:06 +00:00
|
|
|
Subscriptions: make(map[types.Subscription]types.Subscription),
|
|
|
|
Account: &types.Account{},
|
|
|
|
Trades: make(map[string]*types.TradeSlice),
|
2020-10-28 08:27:25 +00:00
|
|
|
|
2021-06-10 11:05:07 +00:00
|
|
|
orderBooks: make(map[string]*types.StreamOrderBook),
|
2020-10-28 08:27:25 +00:00
|
|
|
markets: make(map[string]types.Market),
|
2020-11-10 11:06:20 +00:00
|
|
|
startPrices: make(map[string]float64),
|
2020-10-28 08:27:25 +00:00
|
|
|
lastPrices: make(map[string]float64),
|
2021-12-11 11:16:16 +00:00
|
|
|
positions: make(map[string]*types.Position),
|
2020-10-28 08:27:25 +00:00
|
|
|
marketDataStores: make(map[string]*MarketDataStore),
|
|
|
|
standardIndicatorSets: make(map[string]*StandardIndicatorSet),
|
2021-01-21 06:51:37 +00:00
|
|
|
orderStores: make(map[string]*OrderStore),
|
2021-01-30 12:03:59 +00:00
|
|
|
usedSymbols: make(map[string]struct{}),
|
|
|
|
initializedSymbols: make(map[string]struct{}),
|
2021-02-01 09:13:54 +00:00
|
|
|
logger: log.WithField("session", name),
|
2021-01-30 02:51:01 +00:00
|
|
|
}
|
2021-05-12 03:59:29 +00:00
|
|
|
|
2021-05-12 10:58:20 +00:00
|
|
|
session.OrderExecutor = &ExchangeOrderExecutor{
|
2021-05-12 03:59:29 +00:00
|
|
|
// copy the notification system so that we can route
|
|
|
|
Notifiability: session.Notifiability,
|
|
|
|
Session: session,
|
|
|
|
}
|
|
|
|
|
|
|
|
return session
|
2021-01-30 02:51:01 +00:00
|
|
|
}
|
|
|
|
|
2021-05-02 15:58:34 +00:00
|
|
|
// Init initializes the basic data structure and market information by its exchange.
|
|
|
|
// Note that the subscribed symbols are not loaded in this stage.
|
2021-01-30 02:51:01 +00:00
|
|
|
func (session *ExchangeSession) Init(ctx context.Context, environ *Environment) error {
|
|
|
|
if session.IsInitialized {
|
2021-02-02 18:26:41 +00:00
|
|
|
return ErrSessionAlreadyInitialized
|
2021-01-30 02:51:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var log = log.WithField("session", session.Name)
|
|
|
|
|
2021-12-08 09:26:25 +00:00
|
|
|
// load markets first
|
|
|
|
|
|
|
|
var disableMarketsCache = false
|
|
|
|
var markets types.MarketMap
|
|
|
|
var err error
|
|
|
|
if util.SetEnvVarBool("DISABLE_MARKETS_CACHE", &disableMarketsCache); disableMarketsCache {
|
|
|
|
markets, err = session.Exchange.QueryMarkets(ctx)
|
2021-03-22 07:46:55 +00:00
|
|
|
} else {
|
2021-12-08 09:26:25 +00:00
|
|
|
markets, err = LoadExchangeMarketsWithCache(ctx, session.Exchange)
|
2021-03-22 07:46:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-08 09:26:25 +00:00
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-12-08 09:26:25 +00:00
|
|
|
if len(markets) == 0 {
|
|
|
|
return fmt.Errorf("market config should not be empty")
|
2021-03-22 07:46:55 +00:00
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-12-08 09:26:25 +00:00
|
|
|
session.markets = markets
|
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
// query and initialize the balances
|
2021-12-26 07:29:42 +00:00
|
|
|
if !session.PublicOnly {
|
|
|
|
log.Infof("querying balances from session %s...", session.Name)
|
|
|
|
balances, err := session.Exchange.QueryAccountBalances(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-12-26 07:29:42 +00:00
|
|
|
log.Infof("%s account", session.Name)
|
|
|
|
balances.Print()
|
|
|
|
session.Account.UpdateBalances(balances)
|
2021-02-02 18:26:41 +00:00
|
|
|
|
2021-12-26 07:29:42 +00:00
|
|
|
// forward trade updates and order updates to the order executor
|
|
|
|
session.UserDataStream.OnTradeUpdate(session.OrderExecutor.EmitTradeUpdate)
|
|
|
|
session.UserDataStream.OnOrderUpdate(session.OrderExecutor.EmitOrderUpdate)
|
|
|
|
session.Account.BindStream(session.UserDataStream)
|
2021-12-27 09:16:30 +00:00
|
|
|
|
2021-12-27 09:27:16 +00:00
|
|
|
session.metricsBalancesUpdater(balances)
|
2021-12-27 09:16:30 +00:00
|
|
|
session.bindUserDataStreamMetrics(session.UserDataStream)
|
2021-12-26 07:29:42 +00:00
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-12-05 17:42:53 +00:00
|
|
|
// TODO: move this logic to Environment struct
|
|
|
|
// if back-test service is not set, meaning we are not back-testing
|
|
|
|
// we should insert trade into db right before everything
|
|
|
|
if environ.BacktestService == nil {
|
|
|
|
// if trade service is configured, we have the db configured
|
|
|
|
if environ.TradeService != nil {
|
|
|
|
session.UserDataStream.OnTradeUpdate(func(trade types.Trade) {
|
|
|
|
if err := environ.TradeService.Insert(trade); err != nil {
|
|
|
|
log.WithError(err).Errorf("trade insert error: %+v", trade)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
}
|
|
|
|
|
2021-12-15 03:23:07 +00:00
|
|
|
session.MarketDataStream.OnKLine(func(kline types.KLine) {
|
2021-12-26 16:54:10 +00:00
|
|
|
log.WithField("marketData", "kline").Infof("kline: %+v", kline)
|
2021-12-15 03:23:07 +00:00
|
|
|
})
|
|
|
|
|
2021-05-27 07:09:04 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2021-02-10 14:40:36 +00:00
|
|
|
log.WithField("marketData", "kline").Infof("kline closed: %+v", kline)
|
2021-01-30 02:51:01 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
// update last prices
|
2021-05-27 07:09:04 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2021-01-30 02:51:01 +00:00
|
|
|
if _, ok := session.startPrices[kline.Symbol]; !ok {
|
|
|
|
session.startPrices[kline.Symbol] = kline.Open
|
|
|
|
}
|
|
|
|
|
|
|
|
session.lastPrices[kline.Symbol] = kline.Close
|
|
|
|
})
|
|
|
|
|
2021-05-02 15:58:34 +00:00
|
|
|
session.IsInitialized = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (session *ExchangeSession) InitSymbols(ctx context.Context, environ *Environment) error {
|
2021-04-09 04:43:13 +00:00
|
|
|
if err := session.initUsedSymbols(ctx, environ); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-01-30 02:51:01 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-04-09 04:43:13 +00:00
|
|
|
// initUsedSymbols uses usedSymbols to initialize the related data structure
|
|
|
|
func (session *ExchangeSession) initUsedSymbols(ctx context.Context, environ *Environment) error {
|
2021-01-30 02:51:01 +00:00
|
|
|
for symbol := range session.usedSymbols {
|
2021-05-02 15:58:34 +00:00
|
|
|
if err := session.initSymbol(ctx, environ, symbol); err != nil {
|
2021-01-30 02:51:01 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-05-02 15:58:34 +00:00
|
|
|
// initSymbol loads trades for the symbol, bind stream callbacks, init positions, market data store.
|
|
|
|
// please note, initSymbol can not be called for the same symbol for twice
|
|
|
|
func (session *ExchangeSession) initSymbol(ctx context.Context, environ *Environment, symbol string) error {
|
2021-01-30 02:51:01 +00:00
|
|
|
if _, ok := session.initializedSymbols[symbol]; ok {
|
2021-04-09 04:43:13 +00:00
|
|
|
// return fmt.Errorf("symbol %s is already initialized", symbol)
|
|
|
|
return nil
|
2021-01-30 02:51:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
market, ok := session.markets[symbol]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("market %s is not defined", symbol)
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
var trades []types.Trade
|
2021-12-23 15:20:35 +00:00
|
|
|
if environ.SyncService != nil && environ.BacktestService == nil {
|
2021-01-30 02:51:01 +00:00
|
|
|
tradingFeeCurrency := session.Exchange.PlatformFeeCurrency()
|
|
|
|
if strings.HasPrefix(symbol, tradingFeeCurrency) {
|
|
|
|
trades, err = environ.TradeService.QueryForTradingFeeCurrency(session.Exchange.Name(), symbol, tradingFeeCurrency)
|
|
|
|
} else {
|
|
|
|
trades, err = environ.TradeService.Query(service.QueryTradesOptions{
|
|
|
|
Exchange: session.Exchange.Name(),
|
|
|
|
Symbol: symbol,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Infof("symbol %s: %d trades loaded", symbol, len(trades))
|
|
|
|
}
|
|
|
|
|
|
|
|
session.Trades[symbol] = &types.TradeSlice{Trades: trades}
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnTradeUpdate(func(trade types.Trade) {
|
2021-12-27 08:32:30 +00:00
|
|
|
if trade.Symbol == symbol {
|
|
|
|
session.Trades[symbol].Append(trade)
|
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
})
|
|
|
|
|
2021-12-11 11:16:16 +00:00
|
|
|
position := &types.Position{
|
2021-01-30 02:51:01 +00:00
|
|
|
Symbol: symbol,
|
|
|
|
BaseCurrency: market.BaseCurrency,
|
|
|
|
QuoteCurrency: market.QuoteCurrency,
|
|
|
|
}
|
|
|
|
position.AddTrades(trades)
|
2021-05-27 06:45:06 +00:00
|
|
|
position.BindStream(session.UserDataStream)
|
2021-01-30 02:51:01 +00:00
|
|
|
session.positions[symbol] = position
|
|
|
|
|
|
|
|
orderStore := NewOrderStore(symbol)
|
|
|
|
orderStore.AddOrderUpdate = true
|
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
orderStore.BindStream(session.UserDataStream)
|
2021-01-30 02:51:01 +00:00
|
|
|
session.orderStores[symbol] = orderStore
|
|
|
|
|
|
|
|
marketDataStore := NewMarketDataStore(symbol)
|
2021-05-27 07:09:04 +00:00
|
|
|
marketDataStore.BindStream(session.MarketDataStream)
|
2021-01-30 02:51:01 +00:00
|
|
|
session.marketDataStores[symbol] = marketDataStore
|
|
|
|
|
|
|
|
standardIndicatorSet := NewStandardIndicatorSet(symbol, marketDataStore)
|
|
|
|
session.standardIndicatorSets[symbol] = standardIndicatorSet
|
|
|
|
|
|
|
|
// used kline intervals by the given symbol
|
2021-06-10 11:05:07 +00:00
|
|
|
var klineSubscriptions = map[types.Interval]struct{}{}
|
2021-01-30 02:51:01 +00:00
|
|
|
|
|
|
|
// always subscribe the 1m kline so we can make sure the connection persists.
|
2021-06-10 11:05:07 +00:00
|
|
|
klineSubscriptions[types.Interval1m] = struct{}{}
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-11-21 18:14:44 +00:00
|
|
|
// Aggregate the intervals that we are using in the subscriptions.
|
2021-01-30 02:51:01 +00:00
|
|
|
for _, sub := range session.Subscriptions {
|
2021-06-10 11:05:07 +00:00
|
|
|
switch sub.Channel {
|
|
|
|
case types.BookChannel:
|
|
|
|
book := types.NewStreamBook(sub.Symbol)
|
|
|
|
book.BindStream(session.MarketDataStream)
|
|
|
|
session.orderBooks[sub.Symbol] = book
|
|
|
|
|
|
|
|
case types.KLineChannel:
|
|
|
|
if sub.Options.Interval == "" {
|
|
|
|
continue
|
|
|
|
}
|
2021-02-13 08:03:11 +00:00
|
|
|
|
2021-06-10 11:05:07 +00:00
|
|
|
if sub.Symbol == symbol {
|
|
|
|
klineSubscriptions[types.Interval(sub.Options.Interval)] = struct{}{}
|
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
}
|
2020-10-17 15:51:44 +00:00
|
|
|
}
|
2021-01-30 02:51:01 +00:00
|
|
|
|
2021-06-10 11:05:07 +00:00
|
|
|
for interval := range klineSubscriptions {
|
2021-01-30 02:51:01 +00:00
|
|
|
// avoid querying the last unclosed kline
|
2021-10-16 05:49:00 +00:00
|
|
|
endTime := environ.startTime
|
2021-01-30 02:51:01 +00:00
|
|
|
kLines, err := session.Exchange.QueryKLines(ctx, symbol, interval, types.KLineQueryOptions{
|
|
|
|
EndTime: &endTime,
|
|
|
|
Limit: 1000, // indicators need at least 100
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(kLines) == 0 {
|
2021-12-07 06:34:05 +00:00
|
|
|
log.Warnf("no kline data for %s %s (end time <= %s)", symbol, interval, environ.startTime)
|
2021-01-30 02:51:01 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// update last prices by the given kline
|
|
|
|
lastKLine := kLines[len(kLines)-1]
|
2021-10-13 05:41:02 +00:00
|
|
|
if interval == types.Interval1m {
|
|
|
|
log.Infof("last kline %+v", lastKLine)
|
2021-01-30 02:51:01 +00:00
|
|
|
session.lastPrices[symbol] = lastKLine.Close
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, k := range kLines {
|
|
|
|
// let market data store trigger the update, so that the indicator could be updated too.
|
|
|
|
marketDataStore.AddKLine(k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-02 12:58:32 +00:00
|
|
|
log.Infof("%s last price: %f", symbol, session.lastPrices[symbol])
|
2021-01-30 02:51:01 +00:00
|
|
|
|
|
|
|
session.initializedSymbols[symbol] = struct{}{}
|
|
|
|
return nil
|
2020-10-16 02:14:36 +00:00
|
|
|
}
|
|
|
|
|
2020-10-28 01:13:57 +00:00
|
|
|
func (session *ExchangeSession) StandardIndicatorSet(symbol string) (*StandardIndicatorSet, bool) {
|
|
|
|
set, ok := session.standardIndicatorSets[symbol]
|
|
|
|
return set, ok
|
|
|
|
}
|
|
|
|
|
2021-12-11 11:16:16 +00:00
|
|
|
func (session *ExchangeSession) Position(symbol string) (pos *types.Position, ok bool) {
|
2021-01-20 08:29:15 +00:00
|
|
|
pos, ok = session.positions[symbol]
|
2021-04-28 11:32:49 +00:00
|
|
|
if ok {
|
|
|
|
return pos, ok
|
|
|
|
}
|
|
|
|
|
|
|
|
market, ok := session.markets[symbol]
|
|
|
|
if !ok {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
2021-12-11 11:16:16 +00:00
|
|
|
pos = &types.Position{
|
2021-04-28 11:32:49 +00:00
|
|
|
Symbol: symbol,
|
|
|
|
BaseCurrency: market.BaseCurrency,
|
|
|
|
QuoteCurrency: market.QuoteCurrency,
|
|
|
|
}
|
|
|
|
ok = true
|
|
|
|
session.positions[symbol] = pos
|
2021-01-20 08:29:15 +00:00
|
|
|
return pos, ok
|
|
|
|
}
|
|
|
|
|
2021-12-11 11:16:16 +00:00
|
|
|
func (session *ExchangeSession) Positions() map[string]*types.Position {
|
2021-02-02 18:26:41 +00:00
|
|
|
return session.positions
|
|
|
|
}
|
|
|
|
|
2020-10-18 12:41:17 +00:00
|
|
|
// MarketDataStore returns the market data store of a symbol
|
2020-10-28 08:27:25 +00:00
|
|
|
func (session *ExchangeSession) MarketDataStore(symbol string) (s *MarketDataStore, ok bool) {
|
2020-10-18 12:24:16 +00:00
|
|
|
s, ok = session.marketDataStores[symbol]
|
2020-10-18 04:27:11 +00:00
|
|
|
return s, ok
|
|
|
|
}
|
|
|
|
|
2021-06-10 11:05:07 +00:00
|
|
|
// MarketDataStore returns the market data store of a symbol
|
|
|
|
func (session *ExchangeSession) OrderBook(symbol string) (s *types.StreamOrderBook, ok bool) {
|
|
|
|
s, ok = session.orderBooks[symbol]
|
|
|
|
return s, ok
|
|
|
|
}
|
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
func (session *ExchangeSession) StartPrice(symbol string) (price float64, ok bool) {
|
|
|
|
price, ok = session.startPrices[symbol]
|
|
|
|
return price, ok
|
|
|
|
}
|
|
|
|
|
2020-10-18 04:29:38 +00:00
|
|
|
func (session *ExchangeSession) LastPrice(symbol string) (price float64, ok bool) {
|
|
|
|
price, ok = session.lastPrices[symbol]
|
|
|
|
return price, ok
|
|
|
|
}
|
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
func (session *ExchangeSession) LastPrices() map[string]float64 {
|
|
|
|
return session.lastPrices
|
|
|
|
}
|
|
|
|
|
2020-10-18 04:29:38 +00:00
|
|
|
func (session *ExchangeSession) Market(symbol string) (market types.Market, ok bool) {
|
2020-10-18 04:30:13 +00:00
|
|
|
market, ok = session.markets[symbol]
|
2020-10-18 04:29:38 +00:00
|
|
|
return market, ok
|
|
|
|
}
|
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
func (session *ExchangeSession) Markets() map[string]types.Market {
|
|
|
|
return session.markets
|
|
|
|
}
|
|
|
|
|
2021-01-24 11:08:12 +00:00
|
|
|
func (session *ExchangeSession) OrderStore(symbol string) (store *OrderStore, ok bool) {
|
|
|
|
store, ok = session.orderStores[symbol]
|
|
|
|
return store, ok
|
|
|
|
}
|
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
func (session *ExchangeSession) OrderStores() map[string]*OrderStore {
|
|
|
|
return session.orderStores
|
|
|
|
}
|
|
|
|
|
2020-10-16 02:14:36 +00:00
|
|
|
// Subscribe save the subscription info, later it will be assigned to the stream
|
|
|
|
func (session *ExchangeSession) Subscribe(channel types.Channel, symbol string, options types.SubscribeOptions) *ExchangeSession {
|
2021-02-13 08:03:11 +00:00
|
|
|
if channel == types.KLineChannel && len(options.Interval) == 0 {
|
|
|
|
panic("subscription interval for kline can not be empty")
|
|
|
|
}
|
|
|
|
|
2020-10-16 02:14:36 +00:00
|
|
|
sub := types.Subscription{
|
|
|
|
Channel: channel,
|
|
|
|
Symbol: symbol,
|
|
|
|
Options: options,
|
|
|
|
}
|
|
|
|
|
2020-10-28 08:27:25 +00:00
|
|
|
// add to the loaded symbol table
|
2021-01-30 02:51:01 +00:00
|
|
|
session.usedSymbols[symbol] = struct{}{}
|
2020-10-16 02:14:36 +00:00
|
|
|
session.Subscriptions[sub] = sub
|
|
|
|
return session
|
|
|
|
}
|
2020-12-21 05:47:40 +00:00
|
|
|
|
|
|
|
func (session *ExchangeSession) FormatOrder(order types.SubmitOrder) (types.SubmitOrder, error) {
|
|
|
|
market, ok := session.Market(order.Symbol)
|
|
|
|
if !ok {
|
|
|
|
return order, fmt.Errorf("market is not defined: %s", order.Symbol)
|
|
|
|
}
|
|
|
|
|
|
|
|
order.Market = market
|
|
|
|
|
|
|
|
switch order.Type {
|
|
|
|
case types.OrderTypeStopMarket, types.OrderTypeStopLimit:
|
|
|
|
order.StopPriceString = market.FormatPrice(order.StopPrice)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
switch order.Type {
|
|
|
|
case types.OrderTypeMarket, types.OrderTypeStopMarket:
|
|
|
|
order.Price = 0.0
|
|
|
|
order.PriceString = ""
|
|
|
|
|
|
|
|
default:
|
|
|
|
order.PriceString = market.FormatPrice(order.Price)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
order.QuantityString = market.FormatQuantity(order.Quantity)
|
|
|
|
return order, nil
|
|
|
|
}
|
2021-01-26 09:21:18 +00:00
|
|
|
|
|
|
|
func (session *ExchangeSession) UpdatePrices(ctx context.Context) (err error) {
|
2021-05-26 00:20:31 +00:00
|
|
|
if session.lastPriceUpdatedAt.After(time.Now().Add(-time.Hour)) {
|
2021-01-26 09:23:40 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-01-26 09:21:18 +00:00
|
|
|
balances := session.Account.Balances()
|
|
|
|
|
2021-12-13 23:19:21 +00:00
|
|
|
var symbols []string
|
2021-01-26 09:21:18 +00:00
|
|
|
for _, b := range balances {
|
2021-02-15 13:04:44 +00:00
|
|
|
symbols = append(symbols, b.Currency+"USDT")
|
2021-12-13 23:19:21 +00:00
|
|
|
symbols = append(symbols, "USDT"+b.Currency)
|
2021-02-06 21:11:58 +00:00
|
|
|
}
|
2021-01-26 09:21:18 +00:00
|
|
|
|
2021-02-06 21:11:58 +00:00
|
|
|
tickers, err := session.Exchange.QueryTickers(ctx, symbols...)
|
|
|
|
|
|
|
|
if err != nil || len(tickers) == 0 {
|
|
|
|
return err
|
|
|
|
}
|
2021-01-26 09:21:18 +00:00
|
|
|
|
2021-02-06 21:11:58 +00:00
|
|
|
for k, v := range tickers {
|
|
|
|
session.lastPrices[k] = v.Last
|
2021-01-26 09:21:18 +00:00
|
|
|
}
|
|
|
|
|
2021-01-26 09:23:40 +00:00
|
|
|
session.lastPriceUpdatedAt = time.Now()
|
2021-01-26 09:21:18 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-02-19 02:42:24 +00:00
|
|
|
|
|
|
|
func (session *ExchangeSession) FindPossibleSymbols() (symbols []string, err error) {
|
|
|
|
// If the session is an isolated margin session, there will be only the isolated margin symbol
|
2021-02-22 07:01:05 +00:00
|
|
|
if session.Margin && session.IsolatedMargin {
|
2021-02-19 02:42:24 +00:00
|
|
|
return []string{
|
|
|
|
session.IsolatedMarginSymbol,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var balances = session.Account.Balances()
|
|
|
|
var fiatAssets []string
|
|
|
|
|
2021-06-10 10:51:13 +00:00
|
|
|
for _, currency := range types.FiatCurrencies {
|
2021-02-19 02:42:24 +00:00
|
|
|
if balance, ok := balances[currency]; ok && balance.Total() > 0 {
|
|
|
|
fiatAssets = append(fiatAssets, currency)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var symbolMap = map[string]struct{}{}
|
|
|
|
|
|
|
|
for _, market := range session.Markets() {
|
|
|
|
// ignore the markets that are not fiat currency markets
|
|
|
|
if !util.StringSliceContains(fiatAssets, market.QuoteCurrency) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// ignore the asset that we don't have in the balance sheet
|
|
|
|
balance, hasAsset := balances[market.BaseCurrency]
|
|
|
|
if !hasAsset || balance.Total() == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
symbolMap[market.Symbol] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
for s := range symbolMap {
|
|
|
|
symbols = append(symbols, s)
|
|
|
|
}
|
|
|
|
|
|
|
|
return symbols, nil
|
|
|
|
}
|
2021-06-10 11:05:07 +00:00
|
|
|
|
2021-12-25 15:42:29 +00:00
|
|
|
// 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 (session *ExchangeSession) InitExchange(name string, exchange types.Exchange) error {
|
2021-06-10 11:05:07 +00:00
|
|
|
var err error
|
|
|
|
var exchangeName = session.ExchangeName
|
2021-12-23 16:24:00 +00:00
|
|
|
if exchange == nil {
|
2021-12-26 07:29:42 +00:00
|
|
|
if session.PublicOnly {
|
|
|
|
exchange, err = cmdutil.NewExchangePublic(exchangeName)
|
2021-12-23 16:24:00 +00:00
|
|
|
} else {
|
2021-12-26 07:29:42 +00:00
|
|
|
if session.Key != "" && session.Secret != "" {
|
|
|
|
exchange, err = cmdutil.NewExchangeStandard(exchangeName, session.Key, session.Secret, session.Passphrase, session.SubAccount)
|
|
|
|
} else {
|
|
|
|
exchange, err = cmdutil.NewExchangeWithEnvVarPrefix(exchangeName, session.EnvVarPrefix)
|
|
|
|
}
|
2021-12-23 16:24:00 +00:00
|
|
|
}
|
2021-06-10 11:05:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// configure exchange
|
|
|
|
if session.Margin {
|
|
|
|
marginExchange, ok := exchange.(types.MarginExchange)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("exchange %s does not support margin", exchangeName)
|
|
|
|
}
|
|
|
|
|
|
|
|
if session.IsolatedMargin {
|
|
|
|
marginExchange.UseIsolatedMargin(session.IsolatedMarginSymbol)
|
|
|
|
} else {
|
|
|
|
marginExchange.UseMargin()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-13 15:16:58 +00:00
|
|
|
if session.Futures {
|
|
|
|
futuresExchange, ok := exchange.(types.FuturesExchange)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("exchange %s does not support futures", exchangeName)
|
|
|
|
}
|
|
|
|
|
|
|
|
if session.IsolatedFutures {
|
|
|
|
futuresExchange.UseIsolatedFutures(session.IsolatedFuturesSymbol)
|
|
|
|
} else {
|
|
|
|
futuresExchange.UseFutures()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-10 11:05:07 +00:00
|
|
|
session.Name = name
|
|
|
|
session.Notifiability = Notifiability{
|
|
|
|
SymbolChannelRouter: NewPatternChannelRouter(nil),
|
|
|
|
SessionChannelRouter: NewPatternChannelRouter(nil),
|
|
|
|
ObjectChannelRouter: NewObjectChannelRouter(),
|
|
|
|
}
|
|
|
|
session.Exchange = exchange
|
|
|
|
session.UserDataStream = exchange.NewStream()
|
|
|
|
session.MarketDataStream = exchange.NewStream()
|
|
|
|
session.MarketDataStream.SetPublicOnly()
|
|
|
|
|
|
|
|
// pointer fields
|
|
|
|
session.Subscriptions = make(map[types.Subscription]types.Subscription)
|
|
|
|
session.Account = &types.Account{}
|
|
|
|
session.Trades = make(map[string]*types.TradeSlice)
|
|
|
|
|
|
|
|
session.orderBooks = make(map[string]*types.StreamOrderBook)
|
|
|
|
session.markets = make(map[string]types.Market)
|
|
|
|
session.lastPrices = make(map[string]float64)
|
|
|
|
session.startPrices = make(map[string]float64)
|
|
|
|
session.marketDataStores = make(map[string]*MarketDataStore)
|
2021-12-11 11:16:16 +00:00
|
|
|
session.positions = make(map[string]*types.Position)
|
2021-06-10 11:05:07 +00:00
|
|
|
session.standardIndicatorSets = make(map[string]*StandardIndicatorSet)
|
|
|
|
session.orderStores = make(map[string]*OrderStore)
|
|
|
|
session.OrderExecutor = &ExchangeOrderExecutor{
|
|
|
|
// copy the notification system so that we can route
|
|
|
|
Notifiability: session.Notifiability,
|
|
|
|
Session: session,
|
|
|
|
}
|
|
|
|
|
|
|
|
session.usedSymbols = make(map[string]struct{})
|
|
|
|
session.initializedSymbols = make(map[string]struct{})
|
|
|
|
session.logger = log.WithField("session", name)
|
|
|
|
return nil
|
|
|
|
}
|
2021-12-27 09:16:30 +00:00
|
|
|
|
|
|
|
func (session *ExchangeSession) MarginType() string {
|
|
|
|
margin := "none"
|
|
|
|
if session.Margin {
|
|
|
|
margin = "margin"
|
|
|
|
if session.IsolatedMargin {
|
|
|
|
margin = "isolated"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return margin
|
|
|
|
}
|
|
|
|
|
|
|
|
func (session *ExchangeSession) metricsBalancesUpdater(balances types.BalanceMap) {
|
|
|
|
for currency, balance := range balances {
|
|
|
|
labels := prometheus.Labels{
|
|
|
|
"exchange": session.ExchangeName.String(),
|
|
|
|
"margin": session.MarginType(),
|
|
|
|
"symbol": session.IsolatedMarginSymbol,
|
|
|
|
"currency": currency,
|
|
|
|
}
|
|
|
|
|
|
|
|
metricsTotalBalances.With(labels).Set(balance.Total().Float64())
|
|
|
|
metricsLockedBalances.With(labels).Set(balance.Locked.Float64())
|
|
|
|
metricsAvailableBalances.With(labels).Set(balance.Available.Float64())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (session *ExchangeSession) metricsTradeUpdater(trade types.Trade) {
|
|
|
|
labels := prometheus.Labels{
|
|
|
|
"exchange": session.ExchangeName.String(),
|
|
|
|
"margin": session.MarginType(),
|
|
|
|
"side": trade.Side.String(),
|
|
|
|
"symbol": trade.Symbol,
|
|
|
|
"liquidity": trade.Liquidity(),
|
|
|
|
}
|
|
|
|
metricsTradingVolume.With(labels).Add(trade.Quantity)
|
|
|
|
metricsTradesTotal.With(labels).Inc()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (session *ExchangeSession) bindUserDataStreamMetrics(stream types.Stream) {
|
|
|
|
stream.OnBalanceUpdate(session.metricsBalancesUpdater)
|
2021-12-27 09:27:16 +00:00
|
|
|
stream.OnBalanceSnapshot(session.metricsBalancesUpdater)
|
2021-12-27 09:16:30 +00:00
|
|
|
stream.OnTradeUpdate(session.metricsTradeUpdater)
|
|
|
|
}
|