2020-10-25 16:26:17 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-11-09 08:34:35 +00:00
|
|
|
"fmt"
|
2023-02-23 15:34:26 +00:00
|
|
|
"time"
|
2020-10-25 16:26:17 +00:00
|
|
|
|
2023-02-24 04:50:43 +00:00
|
|
|
"github.com/cenkalti/backoff/v4"
|
2020-10-25 16:26:17 +00:00
|
|
|
"github.com/pkg/errors"
|
2021-02-10 16:21:56 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2022-09-09 10:41:06 +00:00
|
|
|
"go.uber.org/multierr"
|
2020-10-25 16:26:17 +00:00
|
|
|
|
2020-10-26 10:17:18 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2020-10-25 16:26:17 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2023-03-02 09:17:18 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2020-10-25 16:26:17 +00:00
|
|
|
)
|
|
|
|
|
2023-03-02 09:17:18 +00:00
|
|
|
var DefaultSubmitOrderRetryTimeout = 5 * time.Minute
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
if du, ok := util.GetEnvVarDuration("BBGO_SUBMIT_ORDER_RETRY_TIMEOUT"); ok && du > 0 {
|
|
|
|
DefaultSubmitOrderRetryTimeout = du
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-21 05:47:40 +00:00
|
|
|
type OrderExecutor interface {
|
|
|
|
SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error)
|
2022-03-16 10:25:27 +00:00
|
|
|
CancelOrders(ctx context.Context, orders ...types.Order) error
|
2020-12-21 05:47:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type OrderExecutionRouter interface {
|
2021-05-12 10:58:20 +00:00
|
|
|
// SubmitOrdersTo submit order to a specific exchange Session
|
2020-12-21 05:47:40 +00:00
|
|
|
SubmitOrdersTo(ctx context.Context, session string, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error)
|
2022-03-16 10:25:27 +00:00
|
|
|
CancelOrdersTo(ctx context.Context, session string, orders ...types.Order) error
|
2020-12-21 05:47:40 +00:00
|
|
|
}
|
|
|
|
|
2020-10-25 16:26:17 +00:00
|
|
|
type ExchangeOrderExecutionRouter struct {
|
2022-01-10 17:36:19 +00:00
|
|
|
sessions map[string]*ExchangeSession
|
2021-05-12 10:58:20 +00:00
|
|
|
executors map[string]OrderExecutor
|
2020-10-25 16:26:17 +00:00
|
|
|
}
|
|
|
|
|
2020-10-31 11:54:05 +00:00
|
|
|
func (e *ExchangeOrderExecutionRouter) SubmitOrdersTo(ctx context.Context, session string, orders ...types.SubmitOrder) (types.OrderSlice, error) {
|
2022-01-10 17:36:19 +00:00
|
|
|
if executor, ok := e.executors[session]; ok {
|
2021-05-12 10:58:20 +00:00
|
|
|
return executor.SubmitOrders(ctx, orders...)
|
|
|
|
}
|
|
|
|
|
2020-10-25 16:26:17 +00:00
|
|
|
es, ok := e.sessions[session]
|
|
|
|
if !ok {
|
2021-02-10 16:21:56 +00:00
|
|
|
return nil, fmt.Errorf("exchange session %s not found", session)
|
2020-10-25 16:26:17 +00:00
|
|
|
}
|
|
|
|
|
2022-06-18 04:30:42 +00:00
|
|
|
formattedOrders, err := es.FormatOrders(orders)
|
2020-10-26 10:17:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2020-10-25 16:26:17 +00:00
|
|
|
}
|
|
|
|
|
2022-09-09 10:41:06 +00:00
|
|
|
createdOrders, _, err := BatchPlaceOrder(ctx, es.Exchange, formattedOrders...)
|
|
|
|
return createdOrders, err
|
|
|
|
}
|
|
|
|
|
2022-03-16 10:25:27 +00:00
|
|
|
func (e *ExchangeOrderExecutionRouter) CancelOrdersTo(ctx context.Context, session string, orders ...types.Order) error {
|
|
|
|
if executor, ok := e.executors[session]; ok {
|
|
|
|
return executor.CancelOrders(ctx, orders...)
|
|
|
|
}
|
|
|
|
es, ok := e.sessions[session]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("exchange session %s not found", session)
|
|
|
|
}
|
|
|
|
|
|
|
|
return es.Exchange.CancelOrders(ctx, orders...)
|
|
|
|
}
|
|
|
|
|
2020-10-25 16:26:17 +00:00
|
|
|
// ExchangeOrderExecutor is an order executor wrapper for single exchange instance.
|
2020-12-21 05:40:23 +00:00
|
|
|
//go:generate callbackgen -type ExchangeOrderExecutor
|
2020-10-25 16:26:17 +00:00
|
|
|
type ExchangeOrderExecutor struct {
|
2021-05-12 10:58:20 +00:00
|
|
|
// MinQuoteBalance fixedpoint.Value `json:"minQuoteBalance,omitempty" yaml:"minQuoteBalance,omitempty"`
|
|
|
|
|
|
|
|
Session *ExchangeSession `json:"-" yaml:"-"`
|
2020-12-21 05:40:23 +00:00
|
|
|
|
|
|
|
// private trade update callbacks
|
|
|
|
tradeUpdateCallbacks []func(trade types.Trade)
|
|
|
|
|
|
|
|
// private order update callbacks
|
|
|
|
orderUpdateCallbacks []func(order types.Order)
|
2020-10-25 16:26:17 +00:00
|
|
|
}
|
|
|
|
|
2020-10-31 11:54:05 +00:00
|
|
|
func (e *ExchangeOrderExecutor) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (types.OrderSlice, error) {
|
2022-06-18 04:30:42 +00:00
|
|
|
formattedOrders, err := e.Session.FormatOrders(orders)
|
2020-10-26 10:17:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-10-30 21:21:17 +00:00
|
|
|
for _, order := range formattedOrders {
|
2021-02-10 16:21:56 +00:00
|
|
|
log.Infof("submitting order: %s", order.String())
|
2020-10-30 21:21:17 +00:00
|
|
|
}
|
|
|
|
|
2022-09-09 10:41:06 +00:00
|
|
|
createdOrders, _, err := BatchPlaceOrder(ctx, e.Session.Exchange, formattedOrders...)
|
|
|
|
return createdOrders, err
|
2020-10-25 16:26:17 +00:00
|
|
|
}
|
|
|
|
|
2022-03-16 10:25:27 +00:00
|
|
|
func (e *ExchangeOrderExecutor) CancelOrders(ctx context.Context, orders ...types.Order) error {
|
|
|
|
for _, order := range orders {
|
|
|
|
log.Infof("cancelling order: %s", order)
|
|
|
|
}
|
|
|
|
return e.Session.Exchange.CancelOrders(ctx, orders...)
|
|
|
|
}
|
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
type BasicRiskController struct {
|
2021-02-10 16:21:56 +00:00
|
|
|
Logger *log.Logger
|
2020-10-26 10:17:18 +00:00
|
|
|
|
2021-03-01 05:44:58 +00:00
|
|
|
MaxOrderAmount fixedpoint.Value `json:"maxOrderAmount,omitempty" yaml:"maxOrderAmount,omitempty"`
|
|
|
|
MinQuoteBalance fixedpoint.Value `json:"minQuoteBalance,omitempty" yaml:"minQuoteBalance,omitempty"`
|
|
|
|
MaxBaseAssetBalance fixedpoint.Value `json:"maxBaseAssetBalance,omitempty" yaml:"maxBaseAssetBalance,omitempty"`
|
|
|
|
MinBaseAssetBalance fixedpoint.Value `json:"minBaseAssetBalance,omitempty" yaml:"minBaseAssetBalance,omitempty"`
|
2020-10-26 10:17:18 +00:00
|
|
|
}
|
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
// ProcessOrders filters and modifies the submit order objects by:
|
|
|
|
// 1. Increase the quantity by the minimal requirement
|
|
|
|
// 2. Decrease the quantity by risk controls
|
|
|
|
// 3. If the quantity does not meet minimal requirement, we should ignore the submit order.
|
2020-11-09 07:02:12 +00:00
|
|
|
func (c *BasicRiskController) ProcessOrders(session *ExchangeSession, orders ...types.SubmitOrder) (outOrders []types.SubmitOrder, errs []error) {
|
2022-04-23 07:43:11 +00:00
|
|
|
balances := session.GetAccount().Balances()
|
2020-11-09 06:56:54 +00:00
|
|
|
|
2020-11-09 07:29:40 +00:00
|
|
|
addError := func(err error) {
|
|
|
|
errs = append(errs, err)
|
|
|
|
}
|
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
accumulativeQuoteAmount := fixedpoint.Zero
|
|
|
|
accumulativeBaseSellQuantity := fixedpoint.Zero
|
|
|
|
increaseFactor := fixedpoint.NewFromFloat(1.01)
|
|
|
|
|
2020-10-26 10:28:34 +00:00
|
|
|
for _, order := range orders {
|
2020-11-09 06:56:54 +00:00
|
|
|
lastPrice, ok := session.LastPrice(order.Symbol)
|
2020-10-28 08:27:25 +00:00
|
|
|
if !ok {
|
2020-11-09 08:34:35 +00:00
|
|
|
addError(fmt.Errorf("the last price of symbol %q is not found, order: %s", order.Symbol, order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
2020-10-26 10:28:34 +00:00
|
|
|
}
|
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
market, ok := session.Market(order.Symbol)
|
|
|
|
if !ok {
|
2020-11-09 08:34:35 +00:00
|
|
|
addError(fmt.Errorf("the market config of symbol %q is not found, order: %s", order.Symbol, order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
price := order.Price
|
2020-10-26 10:28:34 +00:00
|
|
|
quantity := order.Quantity
|
2020-11-09 06:56:54 +00:00
|
|
|
switch order.Type {
|
|
|
|
case types.OrderTypeMarket:
|
|
|
|
price = lastPrice
|
|
|
|
}
|
2020-10-26 10:28:34 +00:00
|
|
|
|
|
|
|
switch order.Side {
|
|
|
|
case types.SideTypeBuy:
|
2022-02-03 11:19:56 +00:00
|
|
|
minAmount := market.MinAmount.Mul(increaseFactor)
|
2020-11-09 06:56:54 +00:00
|
|
|
// Critical conditions for placing buy orders
|
|
|
|
quoteBalance, ok := balances[market.QuoteCurrency]
|
|
|
|
if !ok {
|
2020-11-09 08:34:35 +00:00
|
|
|
addError(fmt.Errorf("can not place buy order, quote balance %s not found", market.QuoteCurrency))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
if quoteBalance.Available.Compare(c.MinQuoteBalance) < 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(errors.Wrapf(ErrQuoteBalanceLevelTooLow, "can not place buy order, quote balance level is too low: %s < %s, order: %s",
|
2022-02-03 11:19:56 +00:00
|
|
|
types.USD.FormatMoney(quoteBalance.Available),
|
|
|
|
types.USD.FormatMoney(c.MinQuoteBalance), order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
// Increase the quantity if the amount is not enough,
|
|
|
|
// this is the only increase op, later we will decrease the quantity if it meets the criteria
|
2022-02-03 11:19:56 +00:00
|
|
|
quantity = AdjustFloatQuantityByMinAmount(quantity, price, minAmount)
|
2020-11-09 06:56:54 +00:00
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
if c.MaxOrderAmount.Sign() > 0 {
|
|
|
|
quantity = AdjustFloatQuantityByMaxAmount(quantity, price, c.MaxOrderAmount)
|
2020-11-09 06:56:54 +00:00
|
|
|
}
|
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
quoteAssetQuota := fixedpoint.Max(
|
|
|
|
fixedpoint.Zero, quoteBalance.Available.Sub(c.MinQuoteBalance))
|
|
|
|
if quoteAssetQuota.Compare(market.MinAmount) < 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
|
|
|
errors.Wrapf(
|
|
|
|
ErrInsufficientQuoteBalance,
|
2022-02-03 11:19:56 +00:00
|
|
|
"can not place buy order, insufficient quote balance: quota %s < min amount %s, order: %s",
|
|
|
|
quoteAssetQuota.String(), market.MinAmount.String(), order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-05-14 06:52:19 +00:00
|
|
|
quantity = AdjustFloatQuantityByMaxAmount(quantity, price, quoteAssetQuota)
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
// if MaxBaseAssetBalance is enabled, we should check the current base asset balance
|
2022-02-03 11:19:56 +00:00
|
|
|
if baseBalance, hasBaseAsset := balances[market.BaseCurrency]; hasBaseAsset && c.MaxBaseAssetBalance.Sign() > 0 {
|
|
|
|
if baseBalance.Available.Compare(c.MaxBaseAssetBalance) > 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
|
|
|
errors.Wrapf(
|
|
|
|
ErrAssetBalanceLevelTooHigh,
|
2022-02-03 11:19:56 +00:00
|
|
|
"should not place buy order, asset balance level is too high: %s > %s, order: %s",
|
|
|
|
baseBalance.Available.String(),
|
|
|
|
c.MaxBaseAssetBalance.String(),
|
2020-11-09 07:29:40 +00:00
|
|
|
order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
2020-10-26 10:28:34 +00:00
|
|
|
}
|
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
baseAssetQuota := fixedpoint.Max(fixedpoint.Zero, c.MaxBaseAssetBalance.Sub(baseBalance.Available))
|
|
|
|
if quantity.Compare(baseAssetQuota) > 0 {
|
2020-11-09 06:56:54 +00:00
|
|
|
quantity = baseAssetQuota
|
2020-10-26 10:28:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
// if the amount is still too small, we should skip it.
|
2022-02-03 11:19:56 +00:00
|
|
|
notional := quantity.Mul(lastPrice)
|
|
|
|
if notional.Compare(market.MinAmount) < 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
2020-11-09 08:34:35 +00:00
|
|
|
fmt.Errorf(
|
2022-02-03 11:19:56 +00:00
|
|
|
"can not place buy order, quote amount too small: notional %s < min amount %s, order: %s",
|
|
|
|
notional.String(),
|
|
|
|
market.MinAmount.String(),
|
2020-11-09 07:29:40 +00:00
|
|
|
order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
accumulativeQuoteAmount = accumulativeQuoteAmount.Add(notional)
|
2020-11-09 06:56:54 +00:00
|
|
|
|
2020-10-26 10:28:34 +00:00
|
|
|
case types.SideTypeSell:
|
2022-02-15 05:55:19 +00:00
|
|
|
minNotion := market.MinNotional.Mul(increaseFactor)
|
2022-02-03 11:19:56 +00:00
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
// Critical conditions for placing SELL orders
|
|
|
|
baseAssetBalance, ok := balances[market.BaseCurrency]
|
|
|
|
if !ok {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
2020-11-09 08:34:35 +00:00
|
|
|
fmt.Errorf(
|
2020-11-09 07:29:40 +00:00
|
|
|
"can not place sell order, no base asset balance %s, order: %s",
|
|
|
|
market.BaseCurrency,
|
|
|
|
order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
|
|
|
}
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
// if the amount is too small, we should increase it.
|
2022-02-03 11:19:56 +00:00
|
|
|
quantity = AdjustFloatQuantityByMinAmount(quantity, price, minNotion)
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
// we should not SELL too much
|
2022-02-03 11:19:56 +00:00
|
|
|
quantity = fixedpoint.Min(quantity, baseAssetBalance.Available)
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
if c.MinBaseAssetBalance.Sign() > 0 {
|
|
|
|
if baseAssetBalance.Available.Compare(c.MinBaseAssetBalance) < 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
|
|
|
errors.Wrapf(
|
|
|
|
ErrAssetBalanceLevelTooLow,
|
2022-02-03 11:19:56 +00:00
|
|
|
"asset balance level is too low: %s > %s", baseAssetBalance.Available.String(), c.MinBaseAssetBalance.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
2020-10-26 10:28:34 +00:00
|
|
|
}
|
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
quantity = fixedpoint.Min(quantity, baseAssetBalance.Available.Sub(c.MinBaseAssetBalance))
|
|
|
|
if quantity.Compare(market.MinQuantity) < 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
|
|
|
errors.Wrapf(
|
|
|
|
ErrInsufficientAssetBalance,
|
2022-02-03 11:19:56 +00:00
|
|
|
"insufficient asset balance: %s > minimal quantity %s",
|
|
|
|
baseAssetBalance.Available.String(),
|
|
|
|
market.MinQuantity.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
2020-10-26 10:28:34 +00:00
|
|
|
}
|
2020-11-09 06:56:54 +00:00
|
|
|
}
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
if c.MaxOrderAmount.Sign() > 0 {
|
|
|
|
quantity = AdjustFloatQuantityByMaxAmount(quantity, price, c.MaxOrderAmount)
|
2020-11-09 06:56:54 +00:00
|
|
|
}
|
2020-10-26 10:28:34 +00:00
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
notional := quantity.Mul(lastPrice)
|
|
|
|
if notional.Compare(market.MinNotional) < 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
2020-11-09 08:34:35 +00:00
|
|
|
fmt.Errorf(
|
2022-02-03 11:19:56 +00:00
|
|
|
"can not place sell order, notional %s < min notional: %s, order: %s",
|
|
|
|
notional.String(),
|
|
|
|
market.MinNotional.String(),
|
2020-11-09 07:29:40 +00:00
|
|
|
order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
2020-10-26 10:28:34 +00:00
|
|
|
}
|
2020-11-09 06:56:54 +00:00
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
if quantity.Compare(market.MinQuantity) < 0 {
|
2020-11-09 07:29:40 +00:00
|
|
|
addError(
|
2020-11-09 08:34:35 +00:00
|
|
|
fmt.Errorf(
|
2022-02-03 11:19:56 +00:00
|
|
|
"can not place sell order, quantity %s is less than the minimal lot %s, order: %s",
|
|
|
|
quantity.String(),
|
|
|
|
market.MinQuantity.String(),
|
2020-11-09 07:29:40 +00:00
|
|
|
order.String()))
|
2020-11-09 06:56:54 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-02-03 11:19:56 +00:00
|
|
|
accumulativeBaseSellQuantity = accumulativeBaseSellQuantity.Add(quantity)
|
2020-10-26 10:28:34 +00:00
|
|
|
}
|
|
|
|
|
2020-10-26 13:36:47 +00:00
|
|
|
// update quantity and format the order
|
2020-10-26 10:28:34 +00:00
|
|
|
order.Quantity = quantity
|
2020-11-09 06:56:54 +00:00
|
|
|
outOrders = append(outOrders, order)
|
2020-10-26 10:17:18 +00:00
|
|
|
}
|
|
|
|
|
2020-11-09 06:56:54 +00:00
|
|
|
return outOrders, nil
|
|
|
|
}
|
|
|
|
|
2023-02-23 15:17:04 +00:00
|
|
|
// BatchPlaceOrder
|
|
|
|
func BatchPlaceOrder(ctx context.Context, exchange types.Exchange, submitOrders ...types.SubmitOrder) (types.OrderSlice, []int, error) {
|
|
|
|
var createdOrders types.OrderSlice
|
|
|
|
var err error
|
|
|
|
var errIndexes []int
|
|
|
|
for i, submitOrder := range submitOrders {
|
|
|
|
createdOrder, err2 := exchange.SubmitOrder(ctx, submitOrder)
|
|
|
|
if err2 != nil {
|
|
|
|
err = multierr.Append(err, err2)
|
|
|
|
errIndexes = append(errIndexes, i)
|
|
|
|
} else if createdOrder != nil {
|
|
|
|
createdOrder.Tag = submitOrder.Tag
|
|
|
|
createdOrders = append(createdOrders, *createdOrder)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return createdOrders, errIndexes, err
|
|
|
|
}
|
|
|
|
|
2023-02-23 15:34:26 +00:00
|
|
|
type OrderCallback func(order types.Order)
|
|
|
|
|
2023-02-23 15:17:04 +00:00
|
|
|
// BatchRetryPlaceOrder places the orders and retries the failed orders
|
2023-03-02 08:16:14 +00:00
|
|
|
func BatchRetryPlaceOrder(ctx context.Context, exchange types.Exchange, errIdx []int, orderCallback OrderCallback, logger log.FieldLogger, submitOrders ...types.SubmitOrder) (types.OrderSlice, []int, error) {
|
|
|
|
if logger == nil {
|
|
|
|
logger = log.StandardLogger()
|
|
|
|
}
|
|
|
|
|
2023-02-23 15:17:04 +00:00
|
|
|
var createdOrders types.OrderSlice
|
2023-02-24 04:50:43 +00:00
|
|
|
var werr error
|
2023-02-23 15:17:04 +00:00
|
|
|
|
|
|
|
// if the errIdx is nil, then we should iterate all the submit orders
|
2023-03-01 07:29:26 +00:00
|
|
|
// allocate a variable for new error index
|
|
|
|
var errIdxNext []int
|
2023-02-23 15:17:04 +00:00
|
|
|
if len(errIdx) == 0 {
|
|
|
|
for i, submitOrder := range submitOrders {
|
|
|
|
createdOrder, err2 := exchange.SubmitOrder(ctx, submitOrder)
|
|
|
|
if err2 != nil {
|
2023-02-24 04:50:43 +00:00
|
|
|
werr = multierr.Append(werr, err2)
|
2023-03-01 07:29:26 +00:00
|
|
|
errIdxNext = append(errIdxNext, i)
|
2023-02-23 15:17:04 +00:00
|
|
|
} else if createdOrder != nil {
|
|
|
|
// if the order is successfully created, than we should copy the order tag
|
|
|
|
createdOrder.Tag = submitOrder.Tag
|
2023-02-23 15:34:26 +00:00
|
|
|
|
|
|
|
if orderCallback != nil {
|
|
|
|
orderCallback(*createdOrder)
|
|
|
|
}
|
|
|
|
|
2023-02-23 15:17:04 +00:00
|
|
|
createdOrders = append(createdOrders, *createdOrder)
|
|
|
|
}
|
|
|
|
}
|
2023-03-01 07:29:26 +00:00
|
|
|
|
|
|
|
errIdx = errIdxNext
|
2023-02-23 15:17:04 +00:00
|
|
|
}
|
|
|
|
|
2023-03-02 09:17:18 +00:00
|
|
|
timeoutCtx, cancelTimeout := context.WithTimeout(ctx, DefaultSubmitOrderRetryTimeout)
|
2023-03-01 07:29:26 +00:00
|
|
|
defer cancelTimeout()
|
|
|
|
|
2023-02-23 15:17:04 +00:00
|
|
|
// if we got any error, we should re-iterate the errored orders
|
2023-03-01 07:29:26 +00:00
|
|
|
coolDownTime := 200 * time.Millisecond
|
|
|
|
|
|
|
|
// set backoff max retries to 101 because https://ja.wikipedia.org/wiki/101%E5%9B%9E%E7%9B%AE%E3%81%AE%E3%83%97%E3%83%AD%E3%83%9D%E3%83%BC%E3%82%BA
|
|
|
|
backoffMaxRetries := uint64(101)
|
2023-03-01 09:42:01 +00:00
|
|
|
batchRetryOrder:
|
2023-03-01 07:29:26 +00:00
|
|
|
for retryRound := 0; len(errIdx) > 0 && retryRound < 10; retryRound++ {
|
|
|
|
// sleep for 200 millisecond between each retry
|
2023-03-02 08:16:14 +00:00
|
|
|
logger.Warnf("retry round #%d, cooling down for %s", retryRound+1, coolDownTime)
|
2023-03-01 07:29:26 +00:00
|
|
|
time.Sleep(coolDownTime)
|
2023-02-23 15:34:26 +00:00
|
|
|
|
2023-03-01 07:29:26 +00:00
|
|
|
// reset error index since it's a new retry
|
|
|
|
errIdxNext = nil
|
2023-02-23 15:17:04 +00:00
|
|
|
|
|
|
|
// iterate the error index and re-submit the order
|
2023-03-02 08:16:14 +00:00
|
|
|
logger.Warnf("starting retry round #%d...", retryRound+1)
|
2023-03-02 07:41:11 +00:00
|
|
|
for _, idx := range errIdx {
|
2023-02-23 15:17:04 +00:00
|
|
|
submitOrder := submitOrders[idx]
|
2023-02-23 15:34:26 +00:00
|
|
|
|
2023-02-24 04:50:43 +00:00
|
|
|
op := func() error {
|
|
|
|
// can allocate permanent error backoff.Permanent(err) to stop backoff
|
2023-03-01 07:29:26 +00:00
|
|
|
createdOrder, err2 := exchange.SubmitOrder(timeoutCtx, submitOrder)
|
2023-03-02 07:41:11 +00:00
|
|
|
if err2 != nil {
|
2023-03-05 09:23:06 +00:00
|
|
|
logger.WithError(err2).Errorf("submit order error: %s", submitOrder.String())
|
2023-03-02 07:41:11 +00:00
|
|
|
}
|
|
|
|
|
2023-02-24 04:50:43 +00:00
|
|
|
if err2 == nil && createdOrder != nil {
|
2023-03-01 07:29:26 +00:00
|
|
|
// if the order is successfully created, then we should copy the order tag
|
2023-02-24 04:50:43 +00:00
|
|
|
createdOrder.Tag = submitOrder.Tag
|
|
|
|
|
|
|
|
if orderCallback != nil {
|
|
|
|
orderCallback(*createdOrder)
|
|
|
|
}
|
|
|
|
|
|
|
|
createdOrders = append(createdOrders, *createdOrder)
|
2023-02-23 15:34:26 +00:00
|
|
|
}
|
|
|
|
|
2023-02-24 04:50:43 +00:00
|
|
|
return err2
|
|
|
|
}
|
|
|
|
|
2023-03-01 07:29:26 +00:00
|
|
|
var bo backoff.BackOff = backoff.NewExponentialBackOff()
|
|
|
|
bo = backoff.WithMaxRetries(bo, backoffMaxRetries)
|
2023-03-02 08:58:14 +00:00
|
|
|
bo = backoff.WithContext(bo, timeoutCtx)
|
2023-03-01 07:29:26 +00:00
|
|
|
if err2 := backoff.Retry(op, bo); err2 != nil {
|
2023-03-01 09:42:01 +00:00
|
|
|
if err2 == context.Canceled {
|
2023-03-02 08:16:14 +00:00
|
|
|
logger.Warnf("context canceled error, stop retry")
|
2023-03-01 09:42:01 +00:00
|
|
|
break batchRetryOrder
|
|
|
|
}
|
|
|
|
|
2023-02-24 04:50:43 +00:00
|
|
|
werr = multierr.Append(werr, err2)
|
|
|
|
errIdxNext = append(errIdxNext, idx)
|
2023-02-23 15:17:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// update the error index
|
|
|
|
errIdx = errIdxNext
|
2020-11-10 06:19:33 +00:00
|
|
|
}
|
2023-02-23 15:17:04 +00:00
|
|
|
|
2023-03-01 07:29:26 +00:00
|
|
|
return createdOrders, errIdx, werr
|
2020-11-10 06:19:33 +00:00
|
|
|
}
|