2022-06-18 08:31:53 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-09-09 05:57:39 +00:00
|
|
|
"errors"
|
2022-07-04 12:13:54 +00:00
|
|
|
"fmt"
|
2022-06-27 10:17:57 +00:00
|
|
|
"strings"
|
2022-06-18 08:31:53 +00:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2022-09-09 10:41:06 +00:00
|
|
|
"go.uber.org/multierr"
|
2022-06-18 08:31:53 +00:00
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type NotifyFunc func(obj interface{}, args ...interface{})
|
|
|
|
|
|
|
|
// GeneralOrderExecutor implements the general order executor for strategy
|
|
|
|
type GeneralOrderExecutor struct {
|
|
|
|
session *ExchangeSession
|
|
|
|
symbol string
|
|
|
|
strategy string
|
|
|
|
strategyInstanceID string
|
|
|
|
position *types.Position
|
|
|
|
activeMakerOrders *ActiveOrderBook
|
|
|
|
orderStore *OrderStore
|
|
|
|
tradeCollector *TradeCollector
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewGeneralOrderExecutor(session *ExchangeSession, symbol, strategy, strategyInstanceID string, position *types.Position) *GeneralOrderExecutor {
|
|
|
|
// Always update the position fields
|
|
|
|
position.Strategy = strategy
|
|
|
|
position.StrategyInstanceID = strategyInstanceID
|
|
|
|
|
|
|
|
orderStore := NewOrderStore(symbol)
|
|
|
|
return &GeneralOrderExecutor{
|
|
|
|
session: session,
|
|
|
|
symbol: symbol,
|
|
|
|
strategy: strategy,
|
|
|
|
strategyInstanceID: strategyInstanceID,
|
|
|
|
position: position,
|
|
|
|
activeMakerOrders: NewActiveOrderBook(symbol),
|
|
|
|
orderStore: orderStore,
|
|
|
|
tradeCollector: NewTradeCollector(symbol, position, orderStore),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-28 10:34:12 +00:00
|
|
|
func (e *GeneralOrderExecutor) ActiveMakerOrders() *ActiveOrderBook {
|
|
|
|
return e.activeMakerOrders
|
|
|
|
}
|
|
|
|
|
2022-06-18 08:31:53 +00:00
|
|
|
func (e *GeneralOrderExecutor) BindEnvironment(environ *Environment) {
|
|
|
|
e.tradeCollector.OnProfit(func(trade types.Trade, profit *types.Profit) {
|
|
|
|
environ.RecordPosition(e.position, trade, profit)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *GeneralOrderExecutor) BindTradeStats(tradeStats *types.TradeStats) {
|
|
|
|
e.tradeCollector.OnProfit(func(trade types.Trade, profit *types.Profit) {
|
|
|
|
if profit == nil {
|
|
|
|
return
|
|
|
|
}
|
2022-07-05 03:14:50 +00:00
|
|
|
|
|
|
|
tradeStats.Add(profit)
|
2022-06-18 08:31:53 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-06-19 04:29:36 +00:00
|
|
|
func (e *GeneralOrderExecutor) BindProfitStats(profitStats *types.ProfitStats) {
|
2022-06-18 08:31:53 +00:00
|
|
|
e.tradeCollector.OnProfit(func(trade types.Trade, profit *types.Profit) {
|
|
|
|
profitStats.AddTrade(trade)
|
|
|
|
if profit == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
profitStats.AddProfit(*profit)
|
2022-07-08 08:43:32 +00:00
|
|
|
|
|
|
|
Notify(profit)
|
2022-07-01 09:32:40 +00:00
|
|
|
Notify(profitStats)
|
2022-06-18 08:31:53 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-06-19 05:01:22 +00:00
|
|
|
func (e *GeneralOrderExecutor) Bind() {
|
2022-06-18 08:31:53 +00:00
|
|
|
e.activeMakerOrders.BindStream(e.session.UserDataStream)
|
|
|
|
e.orderStore.BindStream(e.session.UserDataStream)
|
|
|
|
|
|
|
|
// trade notify
|
|
|
|
e.tradeCollector.OnTrade(func(trade types.Trade, profit, netProfit fixedpoint.Value) {
|
2022-06-19 05:01:22 +00:00
|
|
|
Notify(trade)
|
2022-06-18 08:31:53 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
e.tradeCollector.OnPositionUpdate(func(position *types.Position) {
|
|
|
|
log.Infof("position changed: %s", position)
|
2022-06-19 05:01:22 +00:00
|
|
|
Notify(position)
|
2022-06-18 08:31:53 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
e.tradeCollector.BindStream(e.session.UserDataStream)
|
|
|
|
}
|
|
|
|
|
2022-06-30 16:57:19 +00:00
|
|
|
// CancelOrders cancels the given order objects directly
|
2022-06-26 08:13:58 +00:00
|
|
|
func (e *GeneralOrderExecutor) CancelOrders(ctx context.Context, orders ...types.Order) error {
|
2022-08-11 05:49:16 +00:00
|
|
|
err := e.session.Exchange.CancelOrders(ctx, orders...)
|
|
|
|
if err != nil { // Retry once
|
|
|
|
err = e.session.Exchange.CancelOrders(ctx, orders...)
|
|
|
|
}
|
|
|
|
return err
|
2022-06-26 08:13:58 +00:00
|
|
|
}
|
|
|
|
|
2022-06-19 07:57:59 +00:00
|
|
|
func (e *GeneralOrderExecutor) SubmitOrders(ctx context.Context, submitOrders ...types.SubmitOrder) (types.OrderSlice, error) {
|
2022-06-18 08:31:53 +00:00
|
|
|
formattedOrders, err := e.session.FormatOrders(submitOrders)
|
|
|
|
if err != nil {
|
2022-06-19 07:57:59 +00:00
|
|
|
return nil, err
|
2022-06-18 08:31:53 +00:00
|
|
|
}
|
|
|
|
|
2022-09-09 10:41:06 +00:00
|
|
|
createdOrders, errIdx, err := BatchPlaceOrder(ctx, e.session.Exchange, formattedOrders...)
|
|
|
|
if len(errIdx) > 0 {
|
|
|
|
createdOrders2, err2 := BatchRetryPlaceOrder(ctx, e.session.Exchange, errIdx, formattedOrders...)
|
|
|
|
if err2 != nil {
|
|
|
|
err = multierr.Append(err, err2)
|
|
|
|
} else {
|
|
|
|
createdOrders = append(createdOrders, createdOrders2...)
|
2022-08-11 05:49:16 +00:00
|
|
|
}
|
2022-06-18 08:31:53 +00:00
|
|
|
}
|
2022-09-09 09:55:51 +00:00
|
|
|
|
2022-06-18 08:31:53 +00:00
|
|
|
e.orderStore.Add(createdOrders...)
|
|
|
|
e.activeMakerOrders.Add(createdOrders...)
|
|
|
|
e.tradeCollector.Process()
|
2022-06-19 07:57:59 +00:00
|
|
|
return createdOrders, err
|
2022-06-18 08:31:53 +00:00
|
|
|
}
|
|
|
|
|
2022-09-09 05:57:39 +00:00
|
|
|
type OpenPositionOptions struct {
|
|
|
|
// Long is for open a long position
|
2022-09-12 15:24:37 +00:00
|
|
|
// Long or Short must be set, avoid loading it from the config file
|
|
|
|
// it should be set from the strategy code
|
|
|
|
Long bool `json:"-" yaml:"-"`
|
2022-09-09 05:57:39 +00:00
|
|
|
|
|
|
|
// Short is for open a short position
|
|
|
|
// Long or Short must be set
|
2022-09-12 15:24:37 +00:00
|
|
|
Short bool `json:"-" yaml:"-"`
|
2022-09-09 05:57:39 +00:00
|
|
|
|
|
|
|
// Leverage is used for leveraged position and account
|
2022-09-12 15:48:40 +00:00
|
|
|
// Leverage is not effected when using non-leverage spot account
|
2022-09-09 09:50:21 +00:00
|
|
|
Leverage fixedpoint.Value `json:"leverage,omitempty"`
|
2022-09-09 05:57:39 +00:00
|
|
|
|
2022-09-12 15:48:40 +00:00
|
|
|
// Quantity will be used first, it will override the leverage if it's given
|
2022-09-09 09:50:21 +00:00
|
|
|
Quantity fixedpoint.Value `json:"quantity,omitempty"`
|
|
|
|
|
|
|
|
// MarketOrder set to true to open a position with a market order
|
2022-09-12 15:48:40 +00:00
|
|
|
// default is MarketOrder = true
|
2022-09-10 18:36:45 +00:00
|
|
|
MarketOrder bool `json:"marketOrder,omitempty"`
|
2022-09-09 05:57:39 +00:00
|
|
|
|
2022-09-09 09:50:21 +00:00
|
|
|
// LimitOrder set to true to open a position with a limit order
|
2022-09-10 18:36:45 +00:00
|
|
|
LimitOrder bool `json:"limitOrder,omitempty"`
|
2022-09-09 09:50:21 +00:00
|
|
|
|
2022-09-12 15:24:37 +00:00
|
|
|
// LimitOrderTakerRatio is used when LimitOrder = true, it adjusts the price of the limit order with a ratio.
|
2022-09-09 09:50:21 +00:00
|
|
|
// So you can ensure that the limit order can be a taker order. Higher the ratio, higher the chance it could be a taker order.
|
2022-09-12 15:48:40 +00:00
|
|
|
//
|
|
|
|
// limitOrderTakerRatio is the price ratio to adjust your limit order as a taker order. e.g., 0.1%
|
|
|
|
// for sell order, 0.1% ratio means your final price = price * (1 - 0.1%)
|
|
|
|
// for buy order, 0.1% ratio means your final price = price * (1 + 0.1%)
|
|
|
|
// this is only enabled when the limitOrder option set to true
|
2022-09-12 15:24:37 +00:00
|
|
|
LimitOrderTakerRatio fixedpoint.Value `json:"limitOrderTakerRatio,omitempty"`
|
|
|
|
|
|
|
|
Price fixedpoint.Value `json:"-" yaml:"-"`
|
|
|
|
Tags []string `json:"-" yaml:"-"`
|
2022-09-09 05:57:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (e *GeneralOrderExecutor) OpenPosition(ctx context.Context, options OpenPositionOptions) error {
|
2022-09-12 15:24:37 +00:00
|
|
|
price := options.Price
|
2022-09-09 05:57:39 +00:00
|
|
|
submitOrder := types.SubmitOrder{
|
|
|
|
Symbol: e.position.Symbol,
|
|
|
|
Type: types.OrderTypeMarket,
|
|
|
|
MarginSideEffect: types.SideEffectTypeMarginBuy,
|
2022-09-10 18:36:45 +00:00
|
|
|
Tag: strings.Join(options.Tags, ","),
|
2022-09-09 05:57:39 +00:00
|
|
|
}
|
|
|
|
|
2022-09-12 15:24:37 +00:00
|
|
|
if !options.LimitOrderTakerRatio.IsZero() {
|
2022-09-09 05:57:39 +00:00
|
|
|
if options.Long {
|
|
|
|
// use higher price to buy (this ensures that our order will be filled)
|
2022-09-12 15:24:37 +00:00
|
|
|
price = price.Mul(one.Add(options.LimitOrderTakerRatio))
|
2022-09-09 05:57:39 +00:00
|
|
|
} else if options.Short {
|
|
|
|
// use lower price to sell (this ensures that our order will be filled)
|
2022-09-12 15:24:37 +00:00
|
|
|
price = price.Mul(one.Sub(options.LimitOrderTakerRatio))
|
2022-09-09 05:57:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if options.MarketOrder {
|
|
|
|
submitOrder.Type = types.OrderTypeMarket
|
|
|
|
} else if options.LimitOrder {
|
|
|
|
submitOrder.Type = types.OrderTypeLimit
|
|
|
|
submitOrder.Price = price
|
|
|
|
}
|
|
|
|
|
|
|
|
quantity := options.Quantity
|
|
|
|
|
|
|
|
if options.Long {
|
|
|
|
if quantity.IsZero() {
|
2022-09-09 09:40:17 +00:00
|
|
|
quoteQuantity, err := CalculateQuoteQuantity(ctx, e.session, e.position.QuoteCurrency, options.Leverage)
|
2022-09-09 05:57:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
quantity = quoteQuantity.Div(price)
|
|
|
|
}
|
|
|
|
|
|
|
|
submitOrder.Side = types.SideTypeBuy
|
|
|
|
submitOrder.Quantity = quantity
|
|
|
|
|
2022-09-10 18:36:45 +00:00
|
|
|
Notify("Opening %s long position with quantity %f at price %f", e.position.Symbol, quantity.Float64(), price.Float64())
|
2022-09-09 05:57:39 +00:00
|
|
|
createdOrder, err2 := e.SubmitOrders(ctx, submitOrder)
|
|
|
|
if err2 != nil {
|
|
|
|
return err2
|
|
|
|
}
|
|
|
|
_ = createdOrder
|
|
|
|
return nil
|
|
|
|
} else if options.Short {
|
|
|
|
if quantity.IsZero() {
|
|
|
|
var err error
|
2022-09-09 09:40:17 +00:00
|
|
|
quantity, err = CalculateBaseQuantity(e.session, e.position.Market, price, quantity, options.Leverage)
|
2022-09-09 05:57:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
submitOrder.Side = types.SideTypeSell
|
|
|
|
submitOrder.Quantity = quantity
|
|
|
|
|
2022-09-10 18:36:45 +00:00
|
|
|
Notify("Opening %s short position with quantity %f at price %f", e.position.Symbol, quantity.Float64(), price.Float64())
|
2022-09-09 05:57:39 +00:00
|
|
|
createdOrder, err2 := e.SubmitOrders(ctx, submitOrder)
|
|
|
|
if err2 != nil {
|
|
|
|
return err2
|
|
|
|
}
|
|
|
|
_ = createdOrder
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return errors.New("options Long or Short must be set")
|
|
|
|
}
|
|
|
|
|
2022-06-30 16:57:19 +00:00
|
|
|
// GracefulCancelActiveOrderBook cancels the orders from the active orderbook.
|
|
|
|
func (e *GeneralOrderExecutor) GracefulCancelActiveOrderBook(ctx context.Context, activeOrders *ActiveOrderBook) error {
|
2022-07-14 03:46:19 +00:00
|
|
|
if activeOrders.NumOfOrders() == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2022-06-30 16:57:19 +00:00
|
|
|
if err := activeOrders.GracefulCancel(ctx, e.session.Exchange); err != nil {
|
2022-08-11 05:49:16 +00:00
|
|
|
// Retry once
|
|
|
|
if err = activeOrders.GracefulCancel(ctx, e.session.Exchange); err != nil {
|
|
|
|
return fmt.Errorf("graceful cancel order error: %w", err)
|
|
|
|
}
|
2022-06-18 08:31:53 +00:00
|
|
|
}
|
|
|
|
|
2022-06-19 05:40:10 +00:00
|
|
|
e.tradeCollector.Process()
|
2022-06-18 08:31:53 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-09-02 10:22:26 +00:00
|
|
|
func (e *GeneralOrderExecutor) GracefulCancelOrder(ctx context.Context, order types.Order) error {
|
2022-09-01 04:09:03 +00:00
|
|
|
if e.activeMakerOrders.NumOfOrders() == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if err := e.activeMakerOrders.Cancel(ctx, e.session.Exchange, order); err != nil {
|
|
|
|
// Retry once
|
|
|
|
if err = e.activeMakerOrders.Cancel(ctx, e.session.Exchange, order); err != nil {
|
|
|
|
return fmt.Errorf("cancel order error: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
e.tradeCollector.Process()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-30 16:57:19 +00:00
|
|
|
// GracefulCancel cancels all active maker orders
|
|
|
|
func (e *GeneralOrderExecutor) GracefulCancel(ctx context.Context) error {
|
|
|
|
return e.GracefulCancelActiveOrderBook(ctx, e.activeMakerOrders)
|
|
|
|
}
|
|
|
|
|
2022-09-10 18:01:48 +00:00
|
|
|
// ClosePosition closes the current position by a percentage.
|
|
|
|
// percentage 0.1 means close 10% position
|
|
|
|
// tag is the order tag you want to attach, you may pass multiple tags, the tags will be combined into one tag string by commas.
|
2022-06-27 10:17:57 +00:00
|
|
|
func (e *GeneralOrderExecutor) ClosePosition(ctx context.Context, percentage fixedpoint.Value, tags ...string) error {
|
2022-06-19 03:20:29 +00:00
|
|
|
submitOrder := e.position.NewMarketCloseOrder(percentage)
|
2022-06-18 08:31:53 +00:00
|
|
|
if submitOrder == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-09-11 09:46:23 +00:00
|
|
|
// check base balance and adjust the close position order
|
2022-09-11 09:49:24 +00:00
|
|
|
if e.position.IsLong() {
|
|
|
|
if baseBalance, ok := e.session.Account.Balance(e.position.Market.BaseCurrency); ok {
|
|
|
|
submitOrder.Quantity = fixedpoint.Min(submitOrder.Quantity, baseBalance.Available)
|
|
|
|
}
|
|
|
|
if submitOrder.Quantity.IsZero() {
|
|
|
|
return fmt.Errorf("insufficient base balance, can not sell: %+v", submitOrder)
|
|
|
|
}
|
2022-09-11 09:46:23 +00:00
|
|
|
}
|
|
|
|
|
2022-09-10 18:33:32 +00:00
|
|
|
tagStr := strings.Join(tags, ",")
|
|
|
|
submitOrder.Tag = tagStr
|
|
|
|
|
|
|
|
Notify("closing %s position %s with tags: %v", e.symbol, percentage.Percentage(), tagStr)
|
2022-09-10 18:36:45 +00:00
|
|
|
|
2022-06-19 07:57:59 +00:00
|
|
|
_, err := e.SubmitOrders(ctx, *submitOrder)
|
|
|
|
return err
|
2022-06-18 08:31:53 +00:00
|
|
|
}
|
2022-06-19 05:40:10 +00:00
|
|
|
|
|
|
|
func (e *GeneralOrderExecutor) TradeCollector() *TradeCollector {
|
|
|
|
return e.tradeCollector
|
|
|
|
}
|
2022-06-26 08:13:58 +00:00
|
|
|
|
|
|
|
func (e *GeneralOrderExecutor) Session() *ExchangeSession {
|
|
|
|
return e.session
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *GeneralOrderExecutor) Position() *types.Position {
|
|
|
|
return e.position
|
|
|
|
}
|