2023-06-08 07:54:32 +00:00
|
|
|
package xalign
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2023-06-08 10:05:58 +00:00
|
|
|
"strings"
|
2023-06-13 09:29:19 +00:00
|
|
|
"sync"
|
2023-06-08 07:54:32 +00:00
|
|
|
"time"
|
|
|
|
|
2023-06-21 09:36:09 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2024-10-24 09:50:01 +00:00
|
|
|
"github.com/slack-go/slack"
|
2024-08-01 08:58:07 +00:00
|
|
|
"golang.org/x/time/rate"
|
2023-06-08 07:54:32 +00:00
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
2023-07-04 13:42:24 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/core"
|
2023-06-08 07:54:32 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2024-08-24 04:28:05 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/pricesolver"
|
2023-06-08 07:54:32 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
const ID = "xalign"
|
|
|
|
|
2023-06-21 09:36:09 +00:00
|
|
|
var log = logrus.WithField("strategy", ID)
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
func init() {
|
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
|
|
|
}
|
|
|
|
|
2023-06-21 07:56:59 +00:00
|
|
|
type TimeBalance struct {
|
|
|
|
types.Balance
|
|
|
|
|
|
|
|
Time time.Time
|
|
|
|
}
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
type QuoteCurrencyPreference struct {
|
|
|
|
Buy []string `json:"buy"`
|
|
|
|
Sell []string `json:"sell"`
|
|
|
|
}
|
|
|
|
|
2024-10-24 09:50:01 +00:00
|
|
|
type AmountAlertConfig struct {
|
|
|
|
QuoteCurrency string `json:"quoteCurrency"`
|
|
|
|
Amount fixedpoint.Value `json:"amount"`
|
|
|
|
SlackMentions []string `json:"slackMentions"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type LargeAmountAlert struct {
|
|
|
|
QuoteCurrency string
|
|
|
|
AlertAmount fixedpoint.Value
|
|
|
|
SlackMentions []string
|
|
|
|
|
|
|
|
BaseCurrency string
|
|
|
|
Side types.SideType
|
|
|
|
Price fixedpoint.Value
|
|
|
|
Quantity fixedpoint.Value
|
|
|
|
Amount fixedpoint.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *LargeAmountAlert) SlackAttachment() slack.Attachment {
|
|
|
|
return slack.Attachment{
|
|
|
|
Color: "red",
|
|
|
|
Title: fmt.Sprintf("xalign amount alert - try to align %s with quote %s amount %f > %f",
|
|
|
|
m.BaseCurrency, m.QuoteCurrency, m.Amount.Float64(), m.AlertAmount.Float64()),
|
|
|
|
Text: strings.Join(m.SlackMentions, " "),
|
|
|
|
Fields: []slack.AttachmentField{
|
|
|
|
{
|
|
|
|
Title: "Base Currency",
|
|
|
|
Value: m.BaseCurrency,
|
|
|
|
Short: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Title: "Side",
|
|
|
|
Value: m.Side.String(),
|
|
|
|
Short: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Title: "Price",
|
|
|
|
Value: m.Price.String(),
|
|
|
|
Short: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Title: "Quantity",
|
|
|
|
Value: m.Quantity.String(),
|
|
|
|
Short: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
type Strategy struct {
|
|
|
|
*bbgo.Environment
|
|
|
|
Interval types.Interval `json:"interval"`
|
|
|
|
PreferredSessions []string `json:"sessions"`
|
|
|
|
PreferredQuoteCurrencies *QuoteCurrencyPreference `json:"quoteCurrencies"`
|
|
|
|
ExpectedBalances map[string]fixedpoint.Value `json:"expectedBalances"`
|
|
|
|
UseTakerOrder bool `json:"useTakerOrder"`
|
2023-06-08 15:15:26 +00:00
|
|
|
DryRun bool `json:"dryRun"`
|
2023-06-21 07:59:15 +00:00
|
|
|
BalanceToleranceRange fixedpoint.Value `json:"balanceToleranceRange"`
|
2023-06-21 07:56:59 +00:00
|
|
|
Duration types.Duration `json:"for"`
|
2023-10-27 07:01:41 +00:00
|
|
|
MaxAmounts map[string]fixedpoint.Value `json:"maxAmounts"`
|
2024-10-24 09:50:01 +00:00
|
|
|
LargeAmountAlert *AmountAlertConfig `json:"largeAmountAlert"`
|
2023-06-21 07:56:59 +00:00
|
|
|
|
2024-08-01 08:58:07 +00:00
|
|
|
SlackNotify bool `json:"slackNotify"`
|
|
|
|
SlackNotifyMentions []string `json:"slackNotifyMentions"`
|
|
|
|
SlackNotifyThresholdAmount fixedpoint.Value `json:"slackNotifyThresholdAmount,omitempty"`
|
|
|
|
|
2023-06-21 07:56:59 +00:00
|
|
|
faultBalanceRecords map[string][]TimeBalance
|
2023-06-08 07:54:32 +00:00
|
|
|
|
2024-08-24 04:28:05 +00:00
|
|
|
priceResolver *pricesolver.SimplePriceSolver
|
2024-08-02 07:20:28 +00:00
|
|
|
|
2023-06-13 04:27:38 +00:00
|
|
|
sessions map[string]*bbgo.ExchangeSession
|
2023-06-13 04:22:43 +00:00
|
|
|
orderBooks map[string]*bbgo.ActiveOrderBook
|
2023-06-13 15:23:41 +00:00
|
|
|
|
2023-07-04 13:42:24 +00:00
|
|
|
orderStore *core.OrderStore
|
2024-11-05 07:20:03 +00:00
|
|
|
|
|
|
|
activeTransferNotificationLimiter *rate.Limiter
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) InstanceID() string {
|
2023-06-08 10:05:58 +00:00
|
|
|
var cs []string
|
|
|
|
|
|
|
|
for cur := range s.ExpectedBalances {
|
|
|
|
cs = append(cs, cur)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ID + strings.Join(s.PreferredSessions, "-") + strings.Join(cs, "-")
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
|
|
|
// session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession) {
|
|
|
|
}
|
|
|
|
|
2023-06-21 07:56:59 +00:00
|
|
|
func (s *Strategy) Defaults() error {
|
2023-06-21 07:59:15 +00:00
|
|
|
s.BalanceToleranceRange = fixedpoint.NewFromFloat(0.01)
|
2023-06-21 07:56:59 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-11-05 07:20:03 +00:00
|
|
|
func (s *Strategy) Initialize() error {
|
|
|
|
s.activeTransferNotificationLimiter = rate.NewLimiter(rate.Every(5*time.Minute), 1)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
func (s *Strategy) Validate() error {
|
|
|
|
if s.PreferredQuoteCurrencies == nil {
|
|
|
|
return errors.New("quoteCurrencies is not defined")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-03-15 07:57:17 +00:00
|
|
|
func (s *Strategy) aggregateBalances(
|
|
|
|
ctx context.Context, sessions map[string]*bbgo.ExchangeSession,
|
|
|
|
) (totalBalances types.BalanceMap, sessionBalances map[string]types.BalanceMap) {
|
2023-06-08 07:54:32 +00:00
|
|
|
totalBalances = make(types.BalanceMap)
|
|
|
|
sessionBalances = make(map[string]types.BalanceMap)
|
|
|
|
|
|
|
|
// iterate the sessions and record them
|
|
|
|
for sessionName, session := range sessions {
|
|
|
|
// update the account balances and the margin information
|
|
|
|
if _, err := session.UpdateAccount(ctx); err != nil {
|
|
|
|
log.WithError(err).Errorf("can not update account")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
account := session.GetAccount()
|
|
|
|
balances := account.Balances()
|
|
|
|
|
|
|
|
sessionBalances[sessionName] = balances
|
|
|
|
totalBalances = totalBalances.Add(balances)
|
|
|
|
}
|
|
|
|
|
|
|
|
return totalBalances, sessionBalances
|
|
|
|
}
|
|
|
|
|
2024-08-01 08:58:07 +00:00
|
|
|
func (s *Strategy) detectActiveWithdraw(
|
|
|
|
ctx context.Context,
|
|
|
|
sessions map[string]*bbgo.ExchangeSession,
|
|
|
|
) (*types.Withdraw, error) {
|
2024-07-31 08:51:00 +00:00
|
|
|
var err2 error
|
2024-07-31 07:04:08 +00:00
|
|
|
until := time.Now()
|
|
|
|
since := until.Add(-time.Hour * 24)
|
|
|
|
for _, session := range sessions {
|
2024-07-31 08:51:00 +00:00
|
|
|
transferService, ok := session.Exchange.(types.ExchangeTransferHistoryService)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
2024-07-31 07:04:08 +00:00
|
|
|
|
2024-07-31 08:51:00 +00:00
|
|
|
withdraws, err := transferService.QueryWithdrawHistory(ctx, "", since, until)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("unable to query withdraw history")
|
|
|
|
err2 = err
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, withdraw := range withdraws {
|
2024-08-06 10:08:39 +00:00
|
|
|
log.Infof("checking withdraw status: %s", withdraw.String())
|
2024-07-31 08:51:00 +00:00
|
|
|
switch withdraw.Status {
|
2024-08-05 08:40:10 +00:00
|
|
|
case types.WithdrawStatusSent, types.WithdrawStatusProcessing, types.WithdrawStatusAwaitingApproval:
|
2024-08-01 08:58:07 +00:00
|
|
|
return &withdraw, nil
|
2024-07-31 07:04:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-01 08:58:07 +00:00
|
|
|
return nil, err2
|
2024-07-31 07:04:08 +00:00
|
|
|
}
|
|
|
|
|
2024-10-21 07:58:23 +00:00
|
|
|
func (s *Strategy) detectActiveDeposit(
|
|
|
|
ctx context.Context,
|
|
|
|
sessions map[string]*bbgo.ExchangeSession,
|
|
|
|
) (*types.Deposit, error) {
|
|
|
|
var err2 error
|
|
|
|
until := time.Now()
|
|
|
|
since := until.Add(-time.Hour * 24)
|
|
|
|
for _, session := range sessions {
|
|
|
|
transferService, ok := session.Exchange.(types.ExchangeTransferHistoryService)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
deposits, err := transferService.QueryDepositHistory(ctx, "", since, until)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("unable to query deposit history")
|
|
|
|
err2 = err
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, deposit := range deposits {
|
|
|
|
log.Infof("checking deposit status: %s", deposit.String())
|
|
|
|
switch deposit.Status {
|
|
|
|
case types.DepositPending:
|
|
|
|
return &deposit, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, err2
|
|
|
|
}
|
|
|
|
|
2024-03-15 07:57:17 +00:00
|
|
|
func (s *Strategy) selectSessionForCurrency(
|
|
|
|
ctx context.Context, sessions map[string]*bbgo.ExchangeSession, currency string, changeQuantity fixedpoint.Value,
|
|
|
|
) (*bbgo.ExchangeSession, *types.SubmitOrder) {
|
2024-10-24 09:50:01 +00:00
|
|
|
var taker = s.UseTakerOrder
|
|
|
|
var side types.SideType
|
|
|
|
var quoteCurrencies []string
|
|
|
|
if changeQuantity.Sign() > 0 {
|
|
|
|
quoteCurrencies = s.PreferredQuoteCurrencies.Buy
|
|
|
|
side = types.SideTypeBuy
|
|
|
|
} else {
|
|
|
|
quoteCurrencies = s.PreferredQuoteCurrencies.Sell
|
|
|
|
side = types.SideTypeSell
|
|
|
|
}
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
for _, sessionName := range s.PreferredSessions {
|
|
|
|
session := sessions[sessionName]
|
|
|
|
|
2024-03-18 16:29:45 +00:00
|
|
|
for _, fromQuoteCurrency := range quoteCurrencies {
|
2024-03-15 07:59:43 +00:00
|
|
|
// skip the same currency, because there is no such USDT/USDT market
|
2024-03-18 16:29:45 +00:00
|
|
|
if currency == fromQuoteCurrency {
|
2024-03-15 07:59:43 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-03-18 16:29:45 +00:00
|
|
|
// check both fromQuoteCurrency/currency and currency/fromQuoteCurrency
|
2024-03-19 07:29:18 +00:00
|
|
|
reversed := false
|
2024-03-18 16:29:45 +00:00
|
|
|
baseCurrency := currency
|
|
|
|
quoteCurrency := fromQuoteCurrency
|
2024-03-19 07:29:18 +00:00
|
|
|
symbol := currency + quoteCurrency
|
2023-06-08 07:54:32 +00:00
|
|
|
market, ok := session.Market(symbol)
|
|
|
|
if !ok {
|
2024-03-15 07:57:17 +00:00
|
|
|
// for TWD in USDT/TWD market, buy TWD means sell USDT
|
2024-03-18 16:29:45 +00:00
|
|
|
baseCurrency = fromQuoteCurrency
|
|
|
|
quoteCurrency = currency
|
2024-03-19 07:29:18 +00:00
|
|
|
symbol = baseCurrency + currency
|
2024-03-15 07:57:17 +00:00
|
|
|
market, ok = session.Market(symbol)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// reverse side
|
|
|
|
side = side.Reverse()
|
2024-03-19 07:29:18 +00:00
|
|
|
reversed = true
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ticker, err := session.Exchange.QueryTicker(ctx, symbol)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("unable to query ticker on %s", symbol)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-06-13 05:44:31 +00:00
|
|
|
spread := ticker.Sell.Sub(ticker.Buy)
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
// changeQuantity > 0 = buy
|
|
|
|
// changeQuantity < 0 = sell
|
|
|
|
q := changeQuantity.Abs()
|
|
|
|
|
2023-08-05 08:49:25 +00:00
|
|
|
// a fast filtering
|
2024-03-19 07:29:18 +00:00
|
|
|
if reversed {
|
|
|
|
if q.Compare(market.MinNotional) < 0 {
|
|
|
|
log.Debugf("skip dust notional: %f", q.Float64())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if q.Compare(market.MinQuantity) < 0 {
|
|
|
|
log.Debugf("skip dust quantity: %f", q.Float64())
|
|
|
|
continue
|
|
|
|
}
|
2023-06-13 05:49:22 +00:00
|
|
|
}
|
|
|
|
|
2023-06-13 05:40:39 +00:00
|
|
|
log.Infof("%s changeQuantity: %f ticker: %+v market: %+v", symbol, changeQuantity.Float64(), ticker, market)
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
switch side {
|
|
|
|
|
|
|
|
case types.SideTypeBuy:
|
2023-10-27 07:01:41 +00:00
|
|
|
var price fixedpoint.Value
|
2023-06-08 07:54:32 +00:00
|
|
|
if taker {
|
|
|
|
price = ticker.Sell
|
2023-06-13 05:44:31 +00:00
|
|
|
} else if spread.Compare(market.TickSize) > 0 {
|
|
|
|
price = ticker.Sell.Sub(market.TickSize)
|
2023-06-08 07:54:32 +00:00
|
|
|
} else {
|
|
|
|
price = ticker.Buy
|
|
|
|
}
|
|
|
|
|
2023-08-05 08:49:25 +00:00
|
|
|
quoteBalance, ok := session.Account.Balance(quoteCurrency)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-03-19 07:29:18 +00:00
|
|
|
requiredQuoteAmount := fixedpoint.Zero
|
|
|
|
if reversed {
|
|
|
|
requiredQuoteAmount = q
|
|
|
|
} else {
|
|
|
|
requiredQuoteAmount = q.Mul(price)
|
|
|
|
}
|
|
|
|
|
2023-06-09 03:04:31 +00:00
|
|
|
requiredQuoteAmount = requiredQuoteAmount.Round(market.PricePrecision, fixedpoint.Up)
|
2023-06-13 04:42:07 +00:00
|
|
|
if requiredQuoteAmount.Compare(quoteBalance.Available) > 0 {
|
|
|
|
log.Warnf("required quote amount %f > quote balance %v, skip", requiredQuoteAmount.Float64(), quoteBalance)
|
2023-06-08 07:54:32 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-03-18 16:29:45 +00:00
|
|
|
// for currency = TWD in market USDT/TWD
|
|
|
|
// since the side is reversed, the quote currency is also "TWD" here.
|
|
|
|
//
|
|
|
|
// for currency = BTC in market BTC/USDT and the side is buy
|
|
|
|
// we want to check if the quote currency USDT used up another expected balance.
|
|
|
|
if quoteCurrency != currency {
|
|
|
|
if expectedQuoteBalance, ok := s.ExpectedBalances[quoteCurrency]; ok {
|
|
|
|
rest := quoteBalance.Total().Sub(requiredQuoteAmount)
|
|
|
|
if rest.Compare(expectedQuoteBalance) < 0 {
|
|
|
|
log.Warnf("required quote amount %f will use up the expected balance %f, skip", requiredQuoteAmount.Float64(), expectedQuoteBalance.Float64())
|
|
|
|
continue
|
|
|
|
}
|
2024-03-18 04:47:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-27 07:01:41 +00:00
|
|
|
maxAmount, ok := s.MaxAmounts[market.QuoteCurrency]
|
2024-03-27 08:35:22 +00:00
|
|
|
if ok && requiredQuoteAmount.Compare(maxAmount) > 0 {
|
|
|
|
log.Infof("adjusted required quote ammount %f %s by max amount %f %s", requiredQuoteAmount.Float64(), market.QuoteCurrency, maxAmount.Float64(), market.QuoteCurrency)
|
|
|
|
|
|
|
|
requiredQuoteAmount = maxAmount
|
2023-10-27 07:01:41 +00:00
|
|
|
}
|
|
|
|
|
2023-08-05 08:49:25 +00:00
|
|
|
if quantity, ok := market.GreaterThanMinimalOrderQuantity(side, price, requiredQuoteAmount); ok {
|
|
|
|
return session, &types.SubmitOrder{
|
|
|
|
Symbol: symbol,
|
|
|
|
Side: side,
|
|
|
|
Type: types.OrderTypeLimit,
|
|
|
|
Quantity: quantity,
|
|
|
|
Price: price,
|
|
|
|
Market: market,
|
|
|
|
TimeInForce: types.TimeInForceGTC,
|
|
|
|
}
|
2024-03-27 07:54:52 +00:00
|
|
|
} else {
|
|
|
|
log.Warnf("The amount %f is not greater than the minimal order quantity for %s", requiredQuoteAmount.Float64(), market.Symbol)
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
case types.SideTypeSell:
|
2023-10-27 07:01:41 +00:00
|
|
|
var price fixedpoint.Value
|
2023-06-08 07:54:32 +00:00
|
|
|
if taker {
|
|
|
|
price = ticker.Buy
|
2023-06-13 05:44:31 +00:00
|
|
|
} else if spread.Compare(market.TickSize) > 0 {
|
|
|
|
price = ticker.Buy.Add(market.TickSize)
|
2023-06-08 07:54:32 +00:00
|
|
|
} else {
|
|
|
|
price = ticker.Sell
|
|
|
|
}
|
|
|
|
|
2024-03-19 07:29:18 +00:00
|
|
|
if reversed {
|
|
|
|
q = q.Div(price)
|
|
|
|
}
|
|
|
|
|
2024-03-18 16:29:45 +00:00
|
|
|
baseBalance, ok := session.Account.Balance(baseCurrency)
|
2023-08-05 08:49:25 +00:00
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if q.Compare(baseBalance.Available) > 0 {
|
|
|
|
log.Warnf("required base amount %f < available base balance %v, skip", q.Float64(), baseBalance)
|
|
|
|
continue
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
|
2023-10-27 07:01:41 +00:00
|
|
|
maxAmount, ok := s.MaxAmounts[market.QuoteCurrency]
|
|
|
|
if ok {
|
|
|
|
q = bbgo.AdjustQuantityByMaxAmount(q, price, maxAmount)
|
|
|
|
log.Infof("adjusted quantity %f %s by max amount %f %s", q.Float64(), market.BaseCurrency, maxAmount.Float64(), market.QuoteCurrency)
|
|
|
|
}
|
|
|
|
|
2023-08-05 08:49:25 +00:00
|
|
|
if quantity, ok := market.GreaterThanMinimalOrderQuantity(side, price, q); ok {
|
|
|
|
return session, &types.SubmitOrder{
|
|
|
|
Symbol: symbol,
|
|
|
|
Side: side,
|
|
|
|
Type: types.OrderTypeLimit,
|
|
|
|
Quantity: quantity,
|
|
|
|
Price: price,
|
|
|
|
Market: market,
|
|
|
|
TimeInForce: types.TimeInForceGTC,
|
|
|
|
}
|
2024-03-27 07:54:52 +00:00
|
|
|
} else {
|
|
|
|
log.Warnf("The amount %f is not greater than the minimal order quantity for %s", q.Float64(), market.Symbol)
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession) error {
|
|
|
|
instanceID := s.InstanceID()
|
|
|
|
_ = instanceID
|
|
|
|
|
2023-06-21 07:56:59 +00:00
|
|
|
s.faultBalanceRecords = make(map[string][]TimeBalance)
|
2023-06-13 04:27:38 +00:00
|
|
|
s.sessions = make(map[string]*bbgo.ExchangeSession)
|
2023-06-13 04:22:43 +00:00
|
|
|
s.orderBooks = make(map[string]*bbgo.ActiveOrderBook)
|
2023-06-08 07:54:32 +00:00
|
|
|
|
2023-07-04 13:42:24 +00:00
|
|
|
s.orderStore = core.NewOrderStore("")
|
2023-06-13 15:23:41 +00:00
|
|
|
|
2024-08-02 07:20:28 +00:00
|
|
|
markets := types.MarketMap{}
|
2023-06-08 07:54:32 +00:00
|
|
|
for _, sessionName := range s.PreferredSessions {
|
|
|
|
session, ok := sessions[sessionName]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("incorrect preferred session name: %s is not defined", sessionName)
|
|
|
|
}
|
|
|
|
|
2023-06-13 15:23:41 +00:00
|
|
|
s.orderStore.BindStream(session.UserDataStream)
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
orderBook := bbgo.NewActiveOrderBook("")
|
|
|
|
orderBook.BindStream(session.UserDataStream)
|
2023-06-13 04:22:43 +00:00
|
|
|
s.orderBooks[sessionName] = orderBook
|
2023-06-13 04:27:38 +00:00
|
|
|
|
|
|
|
s.sessions[sessionName] = session
|
2024-08-02 07:20:28 +00:00
|
|
|
|
|
|
|
// session.Market(symbol)
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
|
2024-08-24 04:28:05 +00:00
|
|
|
s.priceResolver = pricesolver.NewSimplePriceResolver(markets)
|
2024-10-24 09:50:01 +00:00
|
|
|
for _, session := range s.sessions {
|
|
|
|
// init the price
|
|
|
|
marketPrices := session.LastPrices()
|
|
|
|
for market, price := range marketPrices {
|
|
|
|
s.priceResolver.Update(market, price)
|
|
|
|
}
|
|
|
|
|
|
|
|
// bind on trade to update price
|
|
|
|
session.UserDataStream.OnTradeUpdate(s.priceResolver.UpdateFromTrade)
|
|
|
|
}
|
2024-08-02 07:20:28 +00:00
|
|
|
|
2023-06-13 09:29:19 +00:00
|
|
|
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
|
|
|
for n, session := range s.sessions {
|
|
|
|
if ob, ok := s.orderBooks[n]; ok {
|
|
|
|
_ = ob.GracefulCancel(ctx, session.Exchange)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
go func() {
|
2023-06-13 04:27:38 +00:00
|
|
|
s.align(ctx, s.sessions)
|
2023-06-08 07:54:32 +00:00
|
|
|
|
2023-06-08 08:00:43 +00:00
|
|
|
ticker := time.NewTicker(s.Interval.Duration())
|
2023-06-08 07:54:32 +00:00
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-ticker.C:
|
2023-06-13 04:27:38 +00:00
|
|
|
s.align(ctx, s.sessions)
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-11-04 08:13:05 +00:00
|
|
|
func (s *Strategy) resetFaultBalanceRecords(currency string) {
|
|
|
|
s.faultBalanceRecords[currency] = nil
|
|
|
|
}
|
|
|
|
|
2023-06-21 07:56:59 +00:00
|
|
|
func (s *Strategy) recordBalance(totalBalances types.BalanceMap) {
|
|
|
|
now := time.Now()
|
|
|
|
for currency, expectedBalance := range s.ExpectedBalances {
|
|
|
|
q := s.calculateRefillQuantity(totalBalances, currency, expectedBalance)
|
|
|
|
rf := q.Div(expectedBalance).Abs().Float64()
|
2023-06-21 07:59:15 +00:00
|
|
|
tr := s.BalanceToleranceRange.Float64()
|
|
|
|
if rf > tr {
|
2023-06-21 07:56:59 +00:00
|
|
|
balance := totalBalances[currency]
|
|
|
|
s.faultBalanceRecords[currency] = append(s.faultBalanceRecords[currency], TimeBalance{
|
|
|
|
Time: now,
|
|
|
|
Balance: balance,
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
// reset counter
|
2024-11-04 08:13:05 +00:00
|
|
|
s.resetFaultBalanceRecords(currency)
|
2023-06-21 07:56:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
func (s *Strategy) align(ctx context.Context, sessions map[string]*bbgo.ExchangeSession) {
|
|
|
|
for sessionName, session := range sessions {
|
2023-06-13 04:22:43 +00:00
|
|
|
ob, ok := s.orderBooks[sessionName]
|
|
|
|
if !ok {
|
|
|
|
log.Errorf("orderbook on session %s not found", sessionName)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if ok {
|
|
|
|
if err := ob.GracefulCancel(ctx, session.Exchange); err != nil {
|
2024-08-01 08:58:07 +00:00
|
|
|
log.WithError(err).Errorf("unable to cancel order")
|
2023-06-13 04:22:43 +00:00
|
|
|
}
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-01 08:58:07 +00:00
|
|
|
pendingWithdraw, err := s.detectActiveWithdraw(ctx, sessions)
|
2024-07-31 08:51:00 +00:00
|
|
|
if err != nil {
|
2024-10-21 07:58:23 +00:00
|
|
|
log.WithError(err).Errorf("unable to check active transfers (withdraw)")
|
2024-08-01 08:58:07 +00:00
|
|
|
} else if pendingWithdraw != nil {
|
2024-11-04 08:13:05 +00:00
|
|
|
log.Warnf("found active transfer (%f %s withdraw), skip balance align check",
|
|
|
|
pendingWithdraw.Amount.Float64(),
|
|
|
|
pendingWithdraw.Asset)
|
|
|
|
|
|
|
|
s.resetFaultBalanceRecords(pendingWithdraw.Asset)
|
2024-08-01 08:58:07 +00:00
|
|
|
|
2024-11-05 07:20:03 +00:00
|
|
|
if s.activeTransferNotificationLimiter.Allow() {
|
2024-11-04 08:13:05 +00:00
|
|
|
bbgo.Notify("Found active %s withdraw, skip balance align",
|
|
|
|
pendingWithdraw.Asset,
|
|
|
|
pendingWithdraw)
|
2024-08-01 08:58:07 +00:00
|
|
|
}
|
2024-11-04 08:13:05 +00:00
|
|
|
|
2024-07-31 08:51:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-10-21 07:58:23 +00:00
|
|
|
pendingDeposit, err := s.detectActiveDeposit(ctx, sessions)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("unable to check active transfers (deposit)")
|
|
|
|
} else if pendingDeposit != nil {
|
2024-11-04 08:13:05 +00:00
|
|
|
log.Warnf("found active transfer (%f %s deposit), skip balance align check",
|
|
|
|
pendingDeposit.Amount.Float64(),
|
|
|
|
pendingDeposit.Asset)
|
|
|
|
|
|
|
|
s.resetFaultBalanceRecords(pendingDeposit.Asset)
|
2024-10-21 07:58:23 +00:00
|
|
|
|
2024-11-05 07:20:03 +00:00
|
|
|
if s.activeTransferNotificationLimiter.Allow() {
|
2024-11-04 08:13:05 +00:00
|
|
|
bbgo.Notify("Found active %s deposit, skip balance align",
|
|
|
|
pendingDeposit.Asset,
|
|
|
|
pendingDeposit)
|
2024-10-21 07:58:23 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-06-21 07:56:59 +00:00
|
|
|
totalBalances, sessionBalances := s.aggregateBalances(ctx, sessions)
|
|
|
|
_ = sessionBalances
|
|
|
|
|
|
|
|
s.recordBalance(totalBalances)
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
for currency, expectedBalance := range s.ExpectedBalances {
|
|
|
|
q := s.calculateRefillQuantity(totalBalances, currency, expectedBalance)
|
|
|
|
|
2023-06-21 07:56:59 +00:00
|
|
|
if s.Duration > 0 {
|
2024-11-04 08:06:17 +00:00
|
|
|
log.Infof("checking %s fault balance records...", currency)
|
2023-06-21 07:56:59 +00:00
|
|
|
if faultBalance, ok := s.faultBalanceRecords[currency]; ok && len(faultBalance) > 0 {
|
|
|
|
if time.Since(faultBalance[0].Time) < s.Duration.Duration() {
|
|
|
|
log.Infof("%s fault record since: %s < persistence period %s", currency, faultBalance[0].Time, s.Duration.Duration())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-12 08:24:18 +00:00
|
|
|
if s.LargeAmountAlert != nil {
|
|
|
|
if price, ok := s.priceResolver.ResolvePrice(currency, s.LargeAmountAlert.QuoteCurrency); ok {
|
|
|
|
quantity := q.Abs()
|
|
|
|
amount := price.Mul(quantity)
|
|
|
|
if amount.Compare(s.LargeAmountAlert.Amount) > 0 {
|
|
|
|
alert := &LargeAmountAlert{
|
|
|
|
QuoteCurrency: s.LargeAmountAlert.QuoteCurrency,
|
|
|
|
AlertAmount: s.LargeAmountAlert.Amount,
|
|
|
|
SlackMentions: s.LargeAmountAlert.SlackMentions,
|
|
|
|
BaseCurrency: currency,
|
|
|
|
Price: price,
|
|
|
|
Quantity: quantity,
|
|
|
|
Amount: amount,
|
|
|
|
}
|
2024-10-24 09:50:01 +00:00
|
|
|
|
2024-11-12 08:24:18 +00:00
|
|
|
if q.Sign() > 0 {
|
|
|
|
alert.Side = types.SideTypeBuy
|
|
|
|
} else {
|
|
|
|
alert.Side = types.SideTypeSell
|
|
|
|
}
|
2024-10-24 09:50:01 +00:00
|
|
|
|
2024-11-12 08:24:18 +00:00
|
|
|
bbgo.Notify(alert)
|
|
|
|
}
|
2024-10-24 09:50:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
selectedSession, submitOrder := s.selectSessionForCurrency(ctx, sessions, currency, q)
|
|
|
|
if selectedSession != nil && submitOrder != nil {
|
2024-11-04 08:06:17 +00:00
|
|
|
log.Infof("placing %s order on %s: %+v", submitOrder.Symbol, selectedSession.Name, submitOrder)
|
2023-06-08 07:54:32 +00:00
|
|
|
|
2024-11-04 08:08:52 +00:00
|
|
|
bbgo.Notify("Aligning %s position on exchange session %s, delta: %f %s, expected balance: %f %s",
|
|
|
|
currency, selectedSession.Name,
|
|
|
|
q.Float64(), currency,
|
|
|
|
expectedBalance.Float64(), currency,
|
|
|
|
submitOrder)
|
2023-06-13 05:47:01 +00:00
|
|
|
|
2023-06-08 15:15:26 +00:00
|
|
|
if s.DryRun {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-06-08 07:54:32 +00:00
|
|
|
createdOrder, err := selectedSession.Exchange.SubmitOrder(ctx, *submitOrder)
|
|
|
|
if err != nil {
|
2024-11-04 08:06:17 +00:00
|
|
|
log.WithError(err).Errorf("can not place order: %+v", submitOrder)
|
2023-06-08 07:54:32 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if createdOrder != nil {
|
2023-06-13 04:24:25 +00:00
|
|
|
if ob, ok := s.orderBooks[selectedSession.Name]; ok {
|
|
|
|
ob.Add(*createdOrder)
|
|
|
|
} else {
|
|
|
|
log.Errorf("orderbook %s not found", selectedSession.Name)
|
|
|
|
}
|
2024-11-04 08:06:17 +00:00
|
|
|
|
2023-06-13 04:22:43 +00:00
|
|
|
s.orderBooks[selectedSession.Name].Add(*createdOrder)
|
2023-06-08 07:54:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-15 07:57:17 +00:00
|
|
|
func (s *Strategy) calculateRefillQuantity(
|
|
|
|
totalBalances types.BalanceMap, currency string, expectedBalance fixedpoint.Value,
|
|
|
|
) fixedpoint.Value {
|
2023-06-08 07:54:32 +00:00
|
|
|
if b, ok := totalBalances[currency]; ok {
|
|
|
|
netBalance := b.Net()
|
|
|
|
return expectedBalance.Sub(netBalance)
|
|
|
|
}
|
|
|
|
return expectedBalance
|
|
|
|
}
|