bbgo_origin/pkg/bbgo/order_execution.go

316 lines
10 KiB
Go
Raw Normal View History

package bbgo
import (
"context"
2020-11-09 08:34:35 +00:00
"fmt"
"github.com/pkg/errors"
2021-02-10 16:21:56 +00:00
log "github.com/sirupsen/logrus"
2020-10-26 10:17:18 +00:00
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
type OrderExecutor interface {
SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error)
CancelOrders(ctx context.Context, orders ...types.Order) error
}
type OrderExecutionRouter interface {
// SubmitOrdersTo submit order to a specific exchange Session
SubmitOrdersTo(ctx context.Context, session string, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error)
CancelOrdersTo(ctx context.Context, session string, orders ...types.Order) error
}
type ExchangeOrderExecutionRouter struct {
2022-01-10 17:36:19 +00:00
sessions map[string]*ExchangeSession
executors map[string]OrderExecutor
}
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 {
return executor.SubmitOrders(ctx, orders...)
}
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)
}
formattedOrders, err := es.FormatOrders(orders)
2020-10-26 10:17:18 +00:00
if err != nil {
return nil, err
}
return es.Exchange.SubmitOrders(ctx, formattedOrders...)
}
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...)
}
// ExchangeOrderExecutor is an order executor wrapper for single exchange instance.
//go:generate callbackgen -type ExchangeOrderExecutor
type ExchangeOrderExecutor struct {
// MinQuoteBalance fixedpoint.Value `json:"minQuoteBalance,omitempty" yaml:"minQuoteBalance,omitempty"`
Notifiability `json:"-" yaml:"-"`
Session *ExchangeSession `json:"-" yaml:"-"`
// private trade update callbacks
tradeUpdateCallbacks []func(trade types.Trade)
// private order update callbacks
orderUpdateCallbacks []func(order types.Order)
}
2020-10-30 21:21:17 +00:00
func (e *ExchangeOrderExecutor) notifySubmitOrders(orders ...types.SubmitOrder) {
for _, order := range orders {
// pass submit order as an interface object.
channel, ok := e.RouteObject(&order)
if ok {
NotifyTo(channel, ":memo: Submitting %s %s %s order with quantity: %f @ %f, order: %v", order.Symbol, order.Type, order.Side, order.Quantity.Float64(), order.Price.Float64(), &order)
2020-10-30 21:21:17 +00:00
} else {
Notify(":memo: Submitting %s %s %s order with quantity: %f @ %f, order: %v", order.Symbol, order.Type, order.Side, order.Quantity.Float64(), order.Price.Float64(), &order)
2020-10-30 21:21:17 +00:00
}
}
}
func (e *ExchangeOrderExecutor) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (types.OrderSlice, error) {
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 {
// pass submit order as an interface object.
channel, ok := e.RouteObject(&order)
if ok {
NotifyTo(channel, ":memo: Submitting %s %s %s order with quantity: %f, order: %v", order.Symbol, order.Type, order.Side, order.Quantity.Float64(), &order)
2020-10-30 21:21:17 +00:00
} else {
Notify(":memo: Submitting %s %s %s order with quantity: %f: %v", order.Symbol, order.Type, order.Side, order.Quantity.Float64(), &order)
2020-10-30 21:21:17 +00:00
}
2020-12-29 10:32:51 +00:00
2021-02-10 16:21:56 +00:00
log.Infof("submitting order: %s", order.String())
2020-10-30 21:21:17 +00:00
}
e.notifySubmitOrders(formattedOrders...)
2020-10-26 10:17:18 +00:00
return e.Session.Exchange.SubmitOrders(ctx, formattedOrders...)
}
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
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) {
balances := session.GetAccount().Balances()
2020-11-09 06:56:54 +00:00
addError := func(err error) {
errs = append(errs, err)
}
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)
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:
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
if quoteBalance.Available.Compare(c.MinQuoteBalance) < 0 {
addError(errors.Wrapf(ErrQuoteBalanceLevelTooLow, "can not place buy order, quote balance level is too low: %s < %s, order: %s",
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
quantity = AdjustFloatQuantityByMinAmount(quantity, price, minAmount)
2020-11-09 06:56:54 +00:00
if c.MaxOrderAmount.Sign() > 0 {
quantity = AdjustFloatQuantityByMaxAmount(quantity, price, c.MaxOrderAmount)
2020-11-09 06:56:54 +00:00
}
quoteAssetQuota := fixedpoint.Max(
fixedpoint.Zero, quoteBalance.Available.Sub(c.MinQuoteBalance))
if quoteAssetQuota.Compare(market.MinAmount) < 0 {
addError(
errors.Wrapf(
ErrInsufficientQuoteBalance,
"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
}
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
if baseBalance, hasBaseAsset := balances[market.BaseCurrency]; hasBaseAsset && c.MaxBaseAssetBalance.Sign() > 0 {
if baseBalance.Available.Compare(c.MaxBaseAssetBalance) > 0 {
addError(
errors.Wrapf(
ErrAssetBalanceLevelTooHigh,
"should not place buy order, asset balance level is too high: %s > %s, order: %s",
baseBalance.Available.String(),
c.MaxBaseAssetBalance.String(),
order.String()))
2020-11-09 06:56:54 +00:00
continue
2020-10-26 10:28:34 +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.
notional := quantity.Mul(lastPrice)
if notional.Compare(market.MinAmount) < 0 {
addError(
2020-11-09 08:34:35 +00:00
fmt.Errorf(
"can not place buy order, quote amount too small: notional %s < min amount %s, order: %s",
notional.String(),
market.MinAmount.String(),
order.String()))
2020-11-09 06:56:54 +00:00
continue
}
accumulativeQuoteAmount = accumulativeQuoteAmount.Add(notional)
2020-11-09 06:56:54 +00:00
2020-10-26 10:28:34 +00:00
case types.SideTypeSell:
minNotion := market.MinNotional.Mul(increaseFactor)
2020-11-09 06:56:54 +00:00
// Critical conditions for placing SELL orders
baseAssetBalance, ok := balances[market.BaseCurrency]
if !ok {
addError(
2020-11-09 08:34:35 +00:00
fmt.Errorf(
"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.
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
quantity = fixedpoint.Min(quantity, baseAssetBalance.Available)
2020-10-26 10:28:34 +00:00
if c.MinBaseAssetBalance.Sign() > 0 {
if baseAssetBalance.Available.Compare(c.MinBaseAssetBalance) < 0 {
addError(
errors.Wrapf(
ErrAssetBalanceLevelTooLow,
"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
}
quantity = fixedpoint.Min(quantity, baseAssetBalance.Available.Sub(c.MinBaseAssetBalance))
if quantity.Compare(market.MinQuantity) < 0 {
addError(
errors.Wrapf(
ErrInsufficientAssetBalance,
"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
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
notional := quantity.Mul(lastPrice)
if notional.Compare(market.MinNotional) < 0 {
addError(
2020-11-09 08:34:35 +00:00
fmt.Errorf(
"can not place sell order, notional %s < min notional: %s, order: %s",
notional.String(),
market.MinNotional.String(),
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 quantity.Compare(market.MinQuantity) < 0 {
addError(
2020-11-09 08:34:35 +00:00
fmt.Errorf(
"can not place sell order, quantity %s is less than the minimal lot %s, order: %s",
quantity.String(),
market.MinQuantity.String(),
order.String()))
2020-11-09 06:56:54 +00:00
continue
}
accumulativeBaseSellQuantity = accumulativeBaseSellQuantity.Add(quantity)
2020-10-26 10:28:34 +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
}
2020-11-10 06:19:33 +00:00
func max(a, b int64) int64 {
if a > b {
return a
}
return b
}