2020-10-29 11:47:53 +00:00
|
|
|
package grid
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-12-31 05:54:32 +00:00
|
|
|
"fmt"
|
2021-12-05 17:34:08 +00:00
|
|
|
"sync"
|
|
|
|
|
2021-03-16 10:39:18 +00:00
|
|
|
"github.com/pkg/errors"
|
2020-10-29 13:10:13 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2021-02-16 08:30:01 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/service"
|
2020-10-29 11:47:53 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2022-05-05 06:39:29 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2020-10-29 11:47:53 +00:00
|
|
|
)
|
|
|
|
|
2021-02-03 01:08:05 +00:00
|
|
|
const ID = "grid"
|
|
|
|
|
|
|
|
var log = logrus.WithField("strategy", ID)
|
2020-10-29 13:10:13 +00:00
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
var NotionalModifier = fixedpoint.NewFromFloat(1.0001)
|
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
func init() {
|
|
|
|
// Register the pointer of the strategy struct,
|
|
|
|
// so that bbgo knows what struct to be used to unmarshal the configs (YAML or JSON)
|
|
|
|
// Note: built-in strategies need to imported manually in the bbgo cmd package.
|
2021-02-03 01:08:05 +00:00
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
2020-10-29 11:47:53 +00:00
|
|
|
}
|
|
|
|
|
2021-03-17 17:14:56 +00:00
|
|
|
// State is the grid snapshot
|
|
|
|
type State struct {
|
2021-03-16 10:39:18 +00:00
|
|
|
Orders []types.SubmitOrder `json:"orders,omitempty"`
|
|
|
|
FilledBuyGrids map[fixedpoint.Value]struct{} `json:"filledBuyGrids"`
|
|
|
|
FilledSellGrids map[fixedpoint.Value]struct{} `json:"filledSellGrids"`
|
2021-12-11 11:16:16 +00:00
|
|
|
Position *types.Position `json:"position,omitempty"`
|
2021-03-18 09:20:21 +00:00
|
|
|
|
2021-03-20 15:05:11 +00:00
|
|
|
AccumulativeArbitrageProfit fixedpoint.Value `json:"accumulativeArbitrageProfit"`
|
2021-03-18 09:20:21 +00:00
|
|
|
|
|
|
|
// any created orders for tracking trades
|
|
|
|
// [source Order ID] -> arbitrage order
|
|
|
|
ArbitrageOrders map[uint64]types.Order `json:"arbitrageOrders"`
|
2021-11-04 16:22:44 +00:00
|
|
|
|
2022-03-04 08:39:48 +00:00
|
|
|
ProfitStats types.ProfitStats `json:"profitStats,omitempty"`
|
2021-03-16 10:39:18 +00:00
|
|
|
}
|
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
type Strategy struct {
|
|
|
|
// The notification system will be injected into the strategy automatically.
|
|
|
|
// This field will be injected automatically since it's a single exchange strategy.
|
2021-02-02 18:26:41 +00:00
|
|
|
*bbgo.Notifiability `json:"-" yaml:"-"`
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
*bbgo.Graceful `json:"-" yaml:"-"`
|
2020-11-12 06:50:08 +00:00
|
|
|
|
2021-03-16 10:39:18 +00:00
|
|
|
*bbgo.Persistence
|
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
// OrderExecutor is an interface for submitting order.
|
|
|
|
// This field will be injected automatically since it's a single exchange strategy.
|
2021-02-02 18:26:41 +00:00
|
|
|
bbgo.OrderExecutor `json:"-" yaml:"-"`
|
2020-12-17 07:52:53 +00:00
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
// Market stores the configuration of the market, for example, VolumePrecision, PricePrecision, MinLotSize... etc
|
|
|
|
// This field will be injected automatically since we defined the Symbol field.
|
2021-02-02 18:26:41 +00:00
|
|
|
types.Market `json:"-" yaml:"-"`
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2021-02-16 08:30:01 +00:00
|
|
|
TradeService *service.TradeService `json:"-" yaml:"-"`
|
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
// These fields will be filled from the config file (it translates YAML to JSON)
|
2021-02-02 18:26:41 +00:00
|
|
|
Symbol string `json:"symbol" yaml:"symbol"`
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
// ProfitSpread is the fixed profit spread you want to submit the sell order
|
2021-02-02 18:26:41 +00:00
|
|
|
ProfitSpread fixedpoint.Value `json:"profitSpread" yaml:"profitSpread"`
|
2020-11-05 07:04:56 +00:00
|
|
|
|
2020-11-02 14:14:01 +00:00
|
|
|
// GridNum is the grid number, how many orders you want to post on the orderbook.
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
GridNum int64 `json:"gridNumber" yaml:"gridNumber"`
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
UpperPrice fixedpoint.Value `json:"upperPrice" yaml:"upperPrice"`
|
2020-11-10 11:06:20 +00:00
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
LowerPrice fixedpoint.Value `json:"lowerPrice" yaml:"lowerPrice"`
|
2020-11-10 11:06:20 +00:00
|
|
|
|
2020-11-11 09:55:16 +00:00
|
|
|
// Quantity is the quantity you want to submit for each order.
|
2021-03-15 18:18:17 +00:00
|
|
|
Quantity fixedpoint.Value `json:"quantity,omitempty"`
|
|
|
|
|
2021-05-09 18:52:41 +00:00
|
|
|
// QuantityScale helps user to define the quantity by price scale or volume scale
|
|
|
|
QuantityScale *bbgo.PriceVolumeScale `json:"quantityScale,omitempty"`
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2021-02-02 18:26:41 +00:00
|
|
|
// FixedAmount is used for fixed amount (dynamic quantity) if you don't want to use fixed quantity.
|
|
|
|
FixedAmount fixedpoint.Value `json:"amount,omitempty" yaml:"amount"`
|
2021-01-06 05:31:17 +00:00
|
|
|
|
2021-03-15 18:18:17 +00:00
|
|
|
// Side is the initial maker orders side. defaults to "both"
|
|
|
|
Side types.SideType `json:"side" yaml:"side"`
|
|
|
|
|
|
|
|
// CatchUp let the maker grid catch up with the price change.
|
|
|
|
CatchUp bool `json:"catchUp" yaml:"catchUp"`
|
|
|
|
|
2021-01-06 05:31:17 +00:00
|
|
|
// Long means you want to hold more base asset than the quote asset.
|
2021-02-02 18:26:41 +00:00
|
|
|
Long bool `json:"long,omitempty" yaml:"long,omitempty"`
|
|
|
|
|
2021-03-17 17:14:56 +00:00
|
|
|
state *State
|
2021-03-15 18:18:17 +00:00
|
|
|
|
|
|
|
// orderStore is used to store all the created orders, so that we can filter the trades.
|
2021-02-02 18:26:41 +00:00
|
|
|
orderStore *bbgo.OrderStore
|
2020-12-31 05:54:32 +00:00
|
|
|
|
2020-11-02 14:14:01 +00:00
|
|
|
// activeOrders is the locally maintained active order book of the maker orders.
|
2020-11-05 06:27:22 +00:00
|
|
|
activeOrders *bbgo.LocalActiveOrderBook
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2021-11-04 16:30:04 +00:00
|
|
|
tradeCollector *bbgo.TradeCollector
|
|
|
|
|
2021-03-15 18:18:17 +00:00
|
|
|
// groupID is the group ID used for the strategy instance for canceling orders
|
2021-03-22 09:27:07 +00:00
|
|
|
groupID uint32
|
2020-10-29 11:47:53 +00:00
|
|
|
}
|
|
|
|
|
2021-02-03 01:08:05 +00:00
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
2021-04-02 02:27:20 +00:00
|
|
|
func (s *Strategy) Validate() error {
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.UpperPrice.IsZero() {
|
2021-04-02 02:27:20 +00:00
|
|
|
return errors.New("upperPrice can not be zero, you forgot to set?")
|
|
|
|
}
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.LowerPrice.IsZero() {
|
2021-04-02 02:27:20 +00:00
|
|
|
return errors.New("lowerPrice can not be zero, you forgot to set?")
|
|
|
|
}
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.UpperPrice.Compare(s.LowerPrice) <= 0 {
|
|
|
|
return fmt.Errorf("upperPrice (%s) should not be less than or equal to lowerPrice (%s)", s.UpperPrice.String(), s.LowerPrice.String())
|
2021-04-02 02:27:20 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.ProfitSpread.Sign() <= 0 {
|
2021-04-02 02:27:20 +00:00
|
|
|
// If profitSpread is empty or its value is negative
|
|
|
|
return fmt.Errorf("profit spread should bigger than 0")
|
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.Quantity.IsZero() && s.QuantityScale == nil && s.FixedAmount.IsZero() {
|
2021-12-07 07:37:18 +00:00
|
|
|
return fmt.Errorf("amount, quantity or scaleQuantity can not be zero")
|
2021-04-02 02:27:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-07 03:37:24 +00:00
|
|
|
func (s *Strategy) generateGridSellOrders(session *bbgo.ExchangeSession) ([]types.SubmitOrder, error) {
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
currentPrice, ok := session.LastPrice(s.Symbol)
|
2021-02-07 03:37:24 +00:00
|
|
|
if !ok {
|
2021-05-07 16:59:30 +00:00
|
|
|
return nil, fmt.Errorf("can not generate sell orders, %s last price not found", s.Symbol)
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if currentPrice.Compare(s.UpperPrice) > 0 {
|
|
|
|
return nil, fmt.Errorf("can not generate sell orders, the current price %s is higher than upper price %s", currentPrice.String(), s.UpperPrice.String())
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
priceRange := s.UpperPrice.Sub(s.LowerPrice)
|
2021-02-07 03:37:24 +00:00
|
|
|
numGrids := fixedpoint.NewFromInt(s.GridNum)
|
|
|
|
gridSpread := priceRange.Div(numGrids)
|
2021-03-17 16:46:25 +00:00
|
|
|
|
2022-02-15 09:59:10 +00:00
|
|
|
if gridSpread.IsZero() {
|
|
|
|
return nil, fmt.Errorf(
|
|
|
|
"either numGrids(%v) is too big or priceRange(%v) is too small, "+
|
|
|
|
"the differences of grid prices become zero", numGrids, priceRange)
|
|
|
|
}
|
|
|
|
|
2021-03-17 16:46:25 +00:00
|
|
|
// find the nearest grid price from the current price
|
|
|
|
startPrice := fixedpoint.Max(
|
|
|
|
s.LowerPrice,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
s.UpperPrice.Sub(
|
|
|
|
s.UpperPrice.Sub(currentPrice).Div(gridSpread).Trunc().Mul(gridSpread)))
|
2021-02-07 03:37:24 +00:00
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if startPrice.Compare(s.UpperPrice) > 0 {
|
2022-02-15 09:59:10 +00:00
|
|
|
return nil, fmt.Errorf("current price %v exceeded the upper price boundary %v",
|
|
|
|
currentPrice,
|
|
|
|
s.UpperPrice)
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
2020-12-29 10:18:32 +00:00
|
|
|
|
2022-04-23 07:43:11 +00:00
|
|
|
balances := session.GetAccount().Balances()
|
2021-02-07 03:37:24 +00:00
|
|
|
baseBalance, ok := balances[s.Market.BaseCurrency]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("base balance %s not found", s.Market.BaseCurrency)
|
|
|
|
}
|
2020-10-29 11:47:53 +00:00
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if baseBalance.Available.IsZero() {
|
|
|
|
return nil, fmt.Errorf("base balance %s is zero: %s",
|
|
|
|
s.Market.BaseCurrency, baseBalance.String())
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Infof("placing grid sell orders from %s ~ %s, grid spread %s",
|
|
|
|
startPrice.String(),
|
|
|
|
s.UpperPrice.String(),
|
|
|
|
gridSpread.String())
|
2021-02-07 03:37:24 +00:00
|
|
|
|
|
|
|
var orders []types.SubmitOrder
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
for price := startPrice; price.Compare(s.UpperPrice) <= 0; price = price.Add(gridSpread) {
|
2021-02-28 03:57:25 +00:00
|
|
|
var quantity fixedpoint.Value
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.Quantity.Sign() > 0 {
|
2021-02-28 03:57:25 +00:00
|
|
|
quantity = s.Quantity
|
2021-05-09 18:52:41 +00:00
|
|
|
} else if s.QuantityScale != nil {
|
|
|
|
qf, err := s.QuantityScale.Scale(price.Float64(), 0)
|
2021-02-28 03:57:25 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
quantity = fixedpoint.NewFromFloat(qf)
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
} else if s.FixedAmount.Sign() > 0 {
|
2021-02-07 03:37:24 +00:00
|
|
|
quantity = s.FixedAmount.Div(price)
|
|
|
|
}
|
|
|
|
|
|
|
|
// quoteQuantity := price.Mul(quantity)
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if baseBalance.Available.Compare(quantity) < 0 {
|
|
|
|
return orders, fmt.Errorf("base balance %s %s is not enough, stop generating sell orders",
|
2021-02-28 03:57:25 +00:00
|
|
|
baseBalance.Currency,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
baseBalance.Available.String())
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
2021-03-17 17:14:56 +00:00
|
|
|
if _, filled := s.state.FilledSellGrids[price]; filled {
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Debugf("sell grid at price %s is already filled, skipping", price.String())
|
2021-03-15 18:18:17 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-07 03:37:24 +00:00
|
|
|
orders = append(orders, types.SubmitOrder{
|
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: types.SideTypeSell,
|
|
|
|
Type: types.OrderTypeLimit,
|
|
|
|
Market: s.Market,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
Quantity: quantity,
|
|
|
|
Price: price.Add(s.ProfitSpread),
|
2022-02-18 05:52:13 +00:00
|
|
|
TimeInForce: types.TimeInForceGTC,
|
2021-02-07 03:37:24 +00:00
|
|
|
GroupID: s.groupID,
|
|
|
|
})
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
baseBalance.Available = baseBalance.Available.Sub(quantity)
|
2021-03-15 18:18:17 +00:00
|
|
|
|
2021-03-17 17:14:56 +00:00
|
|
|
s.state.FilledSellGrids[price] = struct{}{}
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return orders, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) generateGridBuyOrders(session *bbgo.ExchangeSession) ([]types.SubmitOrder, error) {
|
2021-03-15 18:18:17 +00:00
|
|
|
// session.Exchange.QueryTicker()
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
currentPrice, ok := session.LastPrice(s.Symbol)
|
2020-11-10 11:06:20 +00:00
|
|
|
if !ok {
|
2021-02-07 03:37:24 +00:00
|
|
|
return nil, fmt.Errorf("%s last price not found, skipping", s.Symbol)
|
2020-10-31 12:36:58 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if currentPrice.Compare(s.LowerPrice) < 0 {
|
2022-02-15 09:59:10 +00:00
|
|
|
return nil, fmt.Errorf("current price %v is lower than the lower price %v",
|
|
|
|
currentPrice, s.LowerPrice)
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
2020-10-29 11:47:53 +00:00
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
priceRange := s.UpperPrice.Sub(s.LowerPrice)
|
2021-02-07 03:37:24 +00:00
|
|
|
numGrids := fixedpoint.NewFromInt(s.GridNum)
|
|
|
|
gridSpread := priceRange.Div(numGrids)
|
2021-03-17 16:46:25 +00:00
|
|
|
|
2022-02-15 09:59:10 +00:00
|
|
|
if gridSpread.IsZero() {
|
|
|
|
return nil, fmt.Errorf(
|
|
|
|
"either numGrids(%v) is too big or priceRange(%v) is too small, "+
|
|
|
|
"the differences of grid prices become zero", numGrids, priceRange)
|
|
|
|
}
|
|
|
|
|
2021-03-17 16:46:25 +00:00
|
|
|
// Find the nearest grid price for placing buy orders:
|
|
|
|
// buyRange = currentPrice - lowerPrice
|
|
|
|
// numOfBuyGrids = Floor(buyRange / gridSpread)
|
|
|
|
// startPrice = lowerPrice + numOfBuyGrids * gridSpread
|
|
|
|
// priceOfBuyOrder1 = startPrice
|
|
|
|
// priceOfBuyOrder2 = startPrice - gridSpread
|
|
|
|
// priceOfBuyOrder3 = startPrice - gridSpread * 2
|
|
|
|
startPrice := fixedpoint.Min(
|
|
|
|
s.UpperPrice,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
s.LowerPrice.Add(
|
|
|
|
currentPrice.Sub(s.LowerPrice).Div(gridSpread).Trunc().Mul(gridSpread)))
|
2020-12-29 10:18:32 +00:00
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if startPrice.Compare(s.LowerPrice) < 0 {
|
2022-02-15 09:59:10 +00:00
|
|
|
return nil, fmt.Errorf("current price %v exceeded the lower price boundary %v",
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
currentPrice,
|
|
|
|
s.UpperPrice)
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
2022-04-23 07:43:11 +00:00
|
|
|
balances := session.GetAccount().Balances()
|
2021-02-07 03:37:24 +00:00
|
|
|
balance, ok := balances[s.Market.QuoteCurrency]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("quote balance %s not found", s.Market.QuoteCurrency)
|
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if balance.Available.IsZero() {
|
|
|
|
return nil, fmt.Errorf("quote balance %s is zero: %v", s.Market.QuoteCurrency, balance)
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Infof("placing grid buy orders from %v to %v, grid spread %v",
|
|
|
|
startPrice,
|
|
|
|
s.LowerPrice,
|
|
|
|
gridSpread)
|
2021-02-07 03:37:24 +00:00
|
|
|
|
|
|
|
var orders []types.SubmitOrder
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
for price := startPrice; s.LowerPrice.Compare(price) <= 0; price = price.Sub(gridSpread) {
|
2021-02-28 03:57:25 +00:00
|
|
|
var quantity fixedpoint.Value
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.Quantity.Sign() > 0 {
|
2021-02-28 03:57:25 +00:00
|
|
|
quantity = s.Quantity
|
2021-05-09 18:52:41 +00:00
|
|
|
} else if s.QuantityScale != nil {
|
|
|
|
qf, err := s.QuantityScale.Scale(price.Float64(), 0)
|
2021-02-28 03:57:25 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
quantity = fixedpoint.NewFromFloat(qf)
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
} else if s.FixedAmount.Sign() > 0 {
|
2021-02-07 03:37:24 +00:00
|
|
|
quantity = s.FixedAmount.Div(price)
|
|
|
|
}
|
|
|
|
|
|
|
|
quoteQuantity := price.Mul(quantity)
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if balance.Available.Compare(quoteQuantity) < 0 {
|
|
|
|
return orders, fmt.Errorf("quote balance %s %v is not enough for %v, stop generating buy orders",
|
2021-02-28 03:57:25 +00:00
|
|
|
balance.Currency,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
balance.Available,
|
|
|
|
quoteQuantity)
|
2020-11-10 11:06:20 +00:00
|
|
|
}
|
2021-02-07 03:37:24 +00:00
|
|
|
|
2021-03-17 17:14:56 +00:00
|
|
|
if _, filled := s.state.FilledBuyGrids[price]; filled {
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Debugf("buy grid at price %v is already filled, skipping", price)
|
2021-03-15 18:18:17 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-02-07 03:37:24 +00:00
|
|
|
orders = append(orders, types.SubmitOrder{
|
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: types.SideTypeBuy,
|
|
|
|
Type: types.OrderTypeLimit,
|
|
|
|
Market: s.Market,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
Quantity: quantity,
|
|
|
|
Price: price,
|
2022-02-18 05:52:13 +00:00
|
|
|
TimeInForce: types.TimeInForceGTC,
|
2021-02-07 03:37:24 +00:00
|
|
|
GroupID: s.groupID,
|
|
|
|
})
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
balance.Available = balance.Available.Sub(quoteQuantity)
|
2021-03-15 18:18:17 +00:00
|
|
|
|
2021-03-17 17:14:56 +00:00
|
|
|
s.state.FilledBuyGrids[price] = struct{}{}
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return orders, nil
|
|
|
|
}
|
|
|
|
|
2021-03-15 18:18:17 +00:00
|
|
|
func (s *Strategy) placeGridSellOrders(orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
|
|
|
orderForms, err := s.generateGridSellOrders(session)
|
|
|
|
|
2021-05-06 18:14:35 +00:00
|
|
|
if len(orderForms) == 0 {
|
2021-05-07 17:00:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-06 18:14:35 +00:00
|
|
|
return errors.New("none of sell order is generated")
|
2020-10-29 11:47:53 +00:00
|
|
|
}
|
|
|
|
|
2021-05-06 18:14:35 +00:00
|
|
|
log.Infof("submitting %d sell orders...", len(orderForms))
|
|
|
|
createdOrders, err := orderExecutor.SubmitOrders(context.Background(), orderForms...)
|
|
|
|
s.activeOrders.Add(createdOrders...)
|
|
|
|
return err
|
2021-03-15 18:18:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) placeGridBuyOrders(orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
|
|
|
orderForms, err := s.generateGridBuyOrders(session)
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2021-05-06 18:14:35 +00:00
|
|
|
if len(orderForms) == 0 {
|
2021-05-07 17:00:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-06 18:14:35 +00:00
|
|
|
return errors.New("none of buy order is generated")
|
2021-03-15 18:18:17 +00:00
|
|
|
}
|
|
|
|
|
2021-05-06 18:14:35 +00:00
|
|
|
log.Infof("submitting %d buy orders...", len(orderForms))
|
|
|
|
createdOrders, err := orderExecutor.SubmitOrders(context.Background(), orderForms...)
|
|
|
|
s.activeOrders.Add(createdOrders...)
|
|
|
|
|
|
|
|
return err
|
2021-03-15 18:18:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) placeGridOrders(orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
|
2021-03-17 17:14:56 +00:00
|
|
|
log.Infof("placing grid orders on side %s...", s.Side)
|
2021-03-15 18:18:17 +00:00
|
|
|
|
|
|
|
switch s.Side {
|
|
|
|
|
|
|
|
case types.SideTypeBuy:
|
|
|
|
if err := s.placeGridBuyOrders(orderExecutor, session); err != nil {
|
|
|
|
log.Warn(err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
case types.SideTypeSell:
|
|
|
|
if err := s.placeGridSellOrders(orderExecutor, session); err != nil {
|
|
|
|
log.Warn(err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
case types.SideTypeBoth:
|
|
|
|
if err := s.placeGridSellOrders(orderExecutor, session); err != nil {
|
|
|
|
log.Warn(err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.placeGridBuyOrders(orderExecutor, session); err != nil {
|
|
|
|
log.Warn(err.Error())
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
2021-05-06 18:14:35 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
log.Errorf("invalid side %s", s.Side)
|
2021-02-07 03:37:24 +00:00
|
|
|
}
|
2020-10-29 11:47:53 +00:00
|
|
|
}
|
|
|
|
|
2021-03-18 09:20:21 +00:00
|
|
|
func (s *Strategy) handleFilledOrder(filledOrder types.Order) {
|
|
|
|
// generate arbitrage order
|
|
|
|
var side = filledOrder.Side.Reverse()
|
|
|
|
var price = filledOrder.Price
|
|
|
|
var quantity = filledOrder.Quantity
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
var amount = filledOrder.Price.Mul(filledOrder.Quantity)
|
2020-12-31 06:29:23 +00:00
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
switch side {
|
|
|
|
case types.SideTypeSell:
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
price = price.Add(s.ProfitSpread)
|
2020-11-10 11:06:20 +00:00
|
|
|
case types.SideTypeBuy:
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
price = price.Sub(s.ProfitSpread)
|
2020-11-05 07:04:56 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.FixedAmount.Sign() > 0 {
|
|
|
|
quantity = s.FixedAmount.Div(price)
|
2021-01-06 05:31:17 +00:00
|
|
|
} else if s.Long {
|
|
|
|
// long = use the same amount to buy more quantity back
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
quantity = amount.Div(price)
|
|
|
|
amount = quantity.Mul(price)
|
2021-11-04 04:38:41 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if quantity.Compare(s.Market.MinQuantity) < 0 {
|
2021-11-04 04:38:41 +00:00
|
|
|
quantity = s.Market.MinQuantity
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
amount = quantity.Mul(price)
|
2021-11-04 04:38:41 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if amount.Compare(s.Market.MinNotional) <= 0 {
|
|
|
|
quantity = bbgo.AdjustFloatQuantityByMinAmount(
|
|
|
|
quantity, price, s.Market.MinNotional.Mul(NotionalModifier))
|
2021-11-04 04:38:41 +00:00
|
|
|
|
|
|
|
// update amount
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
amount = quantity.Mul(price)
|
2020-12-31 05:54:32 +00:00
|
|
|
}
|
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
submitOrder := types.SubmitOrder{
|
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: side,
|
|
|
|
Type: types.OrderTypeLimit,
|
2020-12-31 05:54:32 +00:00
|
|
|
Quantity: quantity,
|
2020-11-10 11:06:20 +00:00
|
|
|
Price: price,
|
2022-02-18 05:52:13 +00:00
|
|
|
TimeInForce: types.TimeInForceGTC,
|
2021-02-07 03:37:24 +00:00
|
|
|
GroupID: s.groupID,
|
2020-10-29 11:47:53 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Infof("submitting arbitrage order: %v against filled order %v", submitOrder, filledOrder)
|
2020-11-05 07:04:56 +00:00
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
createdOrders, err := s.OrderExecutor.SubmitOrders(context.Background(), submitOrder)
|
2020-11-10 06:18:54 +00:00
|
|
|
|
2021-03-18 09:20:21 +00:00
|
|
|
// create one-way link from the newly created orders
|
|
|
|
for _, o := range createdOrders {
|
|
|
|
s.state.ArbitrageOrders[o.OrderID] = filledOrder
|
|
|
|
}
|
|
|
|
|
2020-12-17 08:22:43 +00:00
|
|
|
s.orderStore.Add(createdOrders...)
|
2020-11-10 11:06:20 +00:00
|
|
|
s.activeOrders.Add(createdOrders...)
|
2021-03-18 09:20:21 +00:00
|
|
|
|
2021-04-15 04:08:52 +00:00
|
|
|
if err != nil {
|
2021-11-04 15:22:01 +00:00
|
|
|
log.WithError(err).Errorf("can not place orders: %+v", submitOrder)
|
2021-04-15 04:08:52 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-03-18 09:20:21 +00:00
|
|
|
// calculate arbitrage profit
|
2021-03-18 09:48:05 +00:00
|
|
|
// TODO: apply fee rate here
|
2021-03-18 09:20:21 +00:00
|
|
|
if s.Long {
|
|
|
|
switch filledOrder.Side {
|
|
|
|
case types.SideTypeSell:
|
|
|
|
if buyOrder, ok := s.state.ArbitrageOrders[filledOrder.OrderID]; ok {
|
|
|
|
// use base asset quantity here
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
baseProfit := buyOrder.Quantity.Sub(filledOrder.Quantity)
|
|
|
|
s.state.AccumulativeArbitrageProfit = s.state.AccumulativeArbitrageProfit.
|
|
|
|
Add(baseProfit)
|
|
|
|
s.Notify("%s grid arbitrage profit %v %s, accumulative arbitrage profit %v %s",
|
2021-11-04 05:08:38 +00:00
|
|
|
s.Symbol,
|
2021-03-20 15:05:11 +00:00
|
|
|
baseProfit, s.Market.BaseCurrency,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
s.state.AccumulativeArbitrageProfit, s.Market.BaseCurrency,
|
2021-03-20 15:05:11 +00:00
|
|
|
)
|
2021-03-18 09:20:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
case types.SideTypeBuy:
|
|
|
|
if sellOrder, ok := s.state.ArbitrageOrders[filledOrder.OrderID]; ok {
|
|
|
|
// use base asset quantity here
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
baseProfit := filledOrder.Quantity.Sub(sellOrder.Quantity)
|
|
|
|
s.state.AccumulativeArbitrageProfit = s.state.AccumulativeArbitrageProfit.Add(baseProfit)
|
|
|
|
s.Notify("%s grid arbitrage profit %v %s, accumulative arbitrage profit %v %s",
|
2021-11-04 05:08:38 +00:00
|
|
|
s.Symbol,
|
2021-03-20 15:05:11 +00:00
|
|
|
baseProfit, s.Market.BaseCurrency,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
s.state.AccumulativeArbitrageProfit, s.Market.BaseCurrency,
|
2021-03-20 15:05:11 +00:00
|
|
|
)
|
2021-03-18 09:20:21 +00:00
|
|
|
}
|
|
|
|
}
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
} else if !s.Long && s.Quantity.Sign() > 0 {
|
2021-03-18 09:20:21 +00:00
|
|
|
switch filledOrder.Side {
|
|
|
|
case types.SideTypeSell:
|
|
|
|
if buyOrder, ok := s.state.ArbitrageOrders[filledOrder.OrderID]; ok {
|
|
|
|
// use base asset quantity here
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
quoteProfit := filledOrder.Quantity.Mul(filledOrder.Price).Sub(
|
|
|
|
buyOrder.Quantity.Mul(buyOrder.Price))
|
|
|
|
s.state.AccumulativeArbitrageProfit = s.state.AccumulativeArbitrageProfit.Add(quoteProfit)
|
|
|
|
s.Notify("%s grid arbitrage profit %v %s, accumulative arbitrage profit %v %s",
|
2021-11-04 05:08:38 +00:00
|
|
|
s.Symbol,
|
2021-03-20 15:05:11 +00:00
|
|
|
quoteProfit, s.Market.QuoteCurrency,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
s.state.AccumulativeArbitrageProfit, s.Market.QuoteCurrency,
|
2021-03-20 15:05:11 +00:00
|
|
|
)
|
2021-03-18 09:20:21 +00:00
|
|
|
}
|
|
|
|
case types.SideTypeBuy:
|
|
|
|
if sellOrder, ok := s.state.ArbitrageOrders[filledOrder.OrderID]; ok {
|
|
|
|
// use base asset quantity here
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
quoteProfit := sellOrder.Quantity.Mul(sellOrder.Price).
|
|
|
|
Sub(filledOrder.Quantity.Mul(filledOrder.Price))
|
|
|
|
s.state.AccumulativeArbitrageProfit = s.state.AccumulativeArbitrageProfit.Add(quoteProfit)
|
|
|
|
s.Notify("%s grid arbitrage profit %v %s, accumulative arbitrage profit %v %s", s.Symbol,
|
2021-03-20 15:05:11 +00:00
|
|
|
quoteProfit, s.Market.QuoteCurrency,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
s.state.AccumulativeArbitrageProfit, s.Market.QuoteCurrency,
|
2021-03-20 15:05:11 +00:00
|
|
|
)
|
2021-03-18 09:20:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-10-29 11:47:53 +00:00
|
|
|
}
|
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
|
|
|
|
}
|
|
|
|
|
2021-11-04 16:22:44 +00:00
|
|
|
func (s *Strategy) LoadState() error {
|
|
|
|
instanceID := s.InstanceID()
|
2021-03-20 15:07:01 +00:00
|
|
|
|
2021-11-04 16:22:44 +00:00
|
|
|
var state State
|
2021-03-16 10:39:18 +00:00
|
|
|
if s.Persistence != nil {
|
2021-03-20 15:07:01 +00:00
|
|
|
if err := s.Persistence.Load(&state, ID, instanceID); err != nil {
|
2021-03-16 10:39:18 +00:00
|
|
|
if err != service.ErrPersistenceNotExists {
|
2021-03-17 17:14:56 +00:00
|
|
|
return errors.Wrapf(err, "state load error")
|
2021-03-16 10:39:18 +00:00
|
|
|
}
|
2021-11-04 16:22:44 +00:00
|
|
|
|
|
|
|
s.state = &State{
|
|
|
|
FilledBuyGrids: make(map[fixedpoint.Value]struct{}),
|
|
|
|
FilledSellGrids: make(map[fixedpoint.Value]struct{}),
|
|
|
|
ArbitrageOrders: make(map[uint64]types.Order),
|
2021-12-11 11:16:16 +00:00
|
|
|
Position: types.NewPositionFromMarket(s.Market),
|
2021-11-04 16:22:44 +00:00
|
|
|
}
|
2021-03-16 10:39:18 +00:00
|
|
|
} else {
|
2021-03-17 17:14:56 +00:00
|
|
|
s.state = &state
|
2021-03-16 10:39:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-04 16:22:44 +00:00
|
|
|
// init profit stats
|
|
|
|
s.state.ProfitStats.Init(s.Market)
|
|
|
|
|
2021-11-04 17:04:04 +00:00
|
|
|
// field guards
|
2021-11-04 16:22:44 +00:00
|
|
|
if s.state.ArbitrageOrders == nil {
|
|
|
|
s.state.ArbitrageOrders = make(map[uint64]types.Order)
|
|
|
|
}
|
2021-11-04 17:04:04 +00:00
|
|
|
if s.state.FilledBuyGrids == nil {
|
|
|
|
s.state.FilledBuyGrids = make(map[fixedpoint.Value]struct{})
|
|
|
|
}
|
|
|
|
if s.state.FilledSellGrids == nil {
|
|
|
|
s.state.FilledSellGrids = make(map[fixedpoint.Value]struct{})
|
|
|
|
}
|
2021-11-04 16:22:44 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2021-03-15 18:18:17 +00:00
|
|
|
|
2021-11-04 16:22:44 +00:00
|
|
|
func (s *Strategy) SaveState() error {
|
|
|
|
if s.Persistence != nil {
|
|
|
|
log.Infof("backing up grid state...")
|
|
|
|
|
|
|
|
instanceID := s.InstanceID()
|
|
|
|
submitOrders := s.activeOrders.Backup()
|
|
|
|
s.state.Orders = submitOrders
|
|
|
|
|
|
|
|
if err := s.Persistence.Save(s.state, ID, instanceID); err != nil {
|
|
|
|
return err
|
2021-03-17 17:14:56 +00:00
|
|
|
}
|
2021-02-16 08:30:01 +00:00
|
|
|
}
|
2021-11-04 16:22:44 +00:00
|
|
|
return nil
|
|
|
|
}
|
2021-02-16 08:30:01 +00:00
|
|
|
|
2021-11-04 17:04:04 +00:00
|
|
|
// InstanceID returns the instance identifier from the current grid configuration parameters
|
2021-11-04 16:22:44 +00:00
|
|
|
func (s *Strategy) InstanceID() string {
|
2022-02-02 11:37:18 +00:00
|
|
|
return fmt.Sprintf("%s-%s-%d-%d-%d", ID, s.Symbol, s.GridNum, s.UpperPrice.Int(), s.LowerPrice.Int())
|
2021-11-04 16:22:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
|
|
|
// do some basic validation
|
|
|
|
if s.GridNum == 0 {
|
|
|
|
s.GridNum = 10
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Side == "" {
|
|
|
|
s.Side = types.SideTypeBoth
|
|
|
|
}
|
|
|
|
|
|
|
|
instanceID := s.InstanceID()
|
2022-05-05 06:39:29 +00:00
|
|
|
s.groupID = util.FNV32(instanceID)
|
2021-11-04 16:22:44 +00:00
|
|
|
log.Infof("using group id %d from fnv(%s)", s.groupID, instanceID)
|
|
|
|
|
|
|
|
if err := s.LoadState(); err != nil {
|
2021-11-04 16:30:04 +00:00
|
|
|
return err
|
2021-03-18 09:20:21 +00:00
|
|
|
}
|
|
|
|
|
2021-11-04 05:08:38 +00:00
|
|
|
s.Notify("grid %s position", s.Symbol, s.state.Position)
|
2021-03-15 18:18:17 +00:00
|
|
|
|
2021-01-21 06:51:37 +00:00
|
|
|
s.orderStore = bbgo.NewOrderStore(s.Symbol)
|
2021-05-27 06:45:06 +00:00
|
|
|
s.orderStore.BindStream(session.UserDataStream)
|
2020-10-29 11:47:53 +00:00
|
|
|
|
2020-10-29 13:10:13 +00:00
|
|
|
// we don't persist orders so that we can not clear the previous orders for now. just need time to support this.
|
2022-01-06 16:10:40 +00:00
|
|
|
s.activeOrders = bbgo.NewLocalActiveOrderBook(s.Symbol)
|
2021-03-18 09:20:21 +00:00
|
|
|
s.activeOrders.OnFilled(s.handleFilledOrder)
|
2021-05-27 06:45:06 +00:00
|
|
|
s.activeOrders.BindStream(session.UserDataStream)
|
2020-10-29 13:10:13 +00:00
|
|
|
|
2021-11-04 16:30:04 +00:00
|
|
|
s.tradeCollector = bbgo.NewTradeCollector(s.Symbol, s.state.Position, s.orderStore)
|
2021-11-04 17:05:43 +00:00
|
|
|
|
2022-03-11 13:27:45 +00:00
|
|
|
s.tradeCollector.OnTrade(func(trade types.Trade, profit, netProfit fixedpoint.Value) {
|
2021-11-04 16:30:04 +00:00
|
|
|
s.Notifiability.Notify(trade)
|
|
|
|
s.state.ProfitStats.AddTrade(trade)
|
|
|
|
})
|
2021-11-04 17:05:43 +00:00
|
|
|
|
2021-12-05 17:34:08 +00:00
|
|
|
/*
|
2021-12-11 11:16:16 +00:00
|
|
|
if s.TradeService != nil {
|
|
|
|
s.tradeCollector.OnTrade(func(trade types.Trade) {
|
|
|
|
if err := s.TradeService.Mark(ctx, trade.ID, ID); err != nil {
|
|
|
|
log.WithError(err).Error("trade mark error")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2021-12-05 17:34:08 +00:00
|
|
|
*/
|
2021-11-04 17:05:43 +00:00
|
|
|
|
2022-05-30 10:16:20 +00:00
|
|
|
s.tradeCollector.OnPositionUpdate(func(position types.AnyPosition) {
|
2021-11-04 16:30:04 +00:00
|
|
|
s.Notifiability.Notify(position)
|
|
|
|
})
|
|
|
|
s.tradeCollector.BindStream(session.UserDataStream)
|
|
|
|
|
2020-11-12 06:50:08 +00:00
|
|
|
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
|
2020-11-12 06:59:47 +00:00
|
|
|
defer wg.Done()
|
|
|
|
|
2021-11-04 16:22:44 +00:00
|
|
|
if err := s.SaveState(); err != nil {
|
|
|
|
log.WithError(err).Errorf("can not save state: %+v", s.state)
|
|
|
|
} else {
|
|
|
|
s.Notify("%s: %s grid is saved", ID, s.Symbol)
|
2021-03-16 10:39:18 +00:00
|
|
|
}
|
|
|
|
|
2021-11-04 16:22:44 +00:00
|
|
|
// now we can cancel the open orders
|
2020-11-12 06:50:08 +00:00
|
|
|
log.Infof("canceling active orders...")
|
2022-01-19 10:26:57 +00:00
|
|
|
if err := session.Exchange.CancelOrders(context.Background(), s.activeOrders.Orders()...); err != nil {
|
2020-11-12 06:50:08 +00:00
|
|
|
log.WithError(err).Errorf("cancel order error")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnStart(func() {
|
2021-11-04 16:22:44 +00:00
|
|
|
// if we have orders in the state data, we can restore them
|
|
|
|
if len(s.state.Orders) > 0 {
|
2021-11-04 17:04:04 +00:00
|
|
|
s.Notifiability.Notify("restoring %s %d grid orders...", s.Symbol, len(s.state.Orders))
|
|
|
|
|
2021-03-17 17:14:56 +00:00
|
|
|
createdOrders, err := orderExecutor.SubmitOrders(ctx, s.state.Orders...)
|
2021-03-16 10:39:18 +00:00
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("active orders restore error")
|
|
|
|
}
|
|
|
|
s.activeOrders.Add(createdOrders...)
|
|
|
|
s.orderStore.Add(createdOrders...)
|
|
|
|
} else {
|
2021-11-04 16:22:44 +00:00
|
|
|
// or place new orders
|
2021-03-16 10:39:18 +00:00
|
|
|
s.placeGridOrders(orderExecutor, session)
|
|
|
|
}
|
2020-11-05 07:04:56 +00:00
|
|
|
})
|
|
|
|
|
2021-05-06 18:14:35 +00:00
|
|
|
if s.CatchUp {
|
2021-05-27 19:13:50 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2021-05-06 18:14:35 +00:00
|
|
|
log.Infof("catchUp mode is enabled, updating grid orders...")
|
|
|
|
// update grid
|
|
|
|
s.placeGridOrders(orderExecutor, session)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-10-29 11:47:53 +00:00
|
|
|
return nil
|
|
|
|
}
|