2022-01-08 17:20:47 +00:00
|
|
|
package bollmaker
|
2021-10-07 08:39:20 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2022-01-09 14:32:23 +00:00
|
|
|
"math"
|
2021-10-07 08:39:20 +00:00
|
|
|
"sync"
|
|
|
|
|
2022-01-06 16:10:40 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/indicator"
|
2022-05-05 06:39:29 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2022-01-06 16:10:40 +00:00
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
2022-01-27 10:51:51 +00:00
|
|
|
// TODO:
|
|
|
|
// 1) add option for placing orders only when in neutral band
|
|
|
|
// 2) add option for only placing buy orders when price is below the SMA line
|
|
|
|
|
2022-01-08 17:20:47 +00:00
|
|
|
const ID = "bollmaker"
|
2021-10-07 08:39:20 +00:00
|
|
|
|
|
|
|
const stateKey = "state-v1"
|
|
|
|
|
|
|
|
var defaultFeeRate = fixedpoint.NewFromFloat(0.001)
|
2022-02-07 03:40:30 +00:00
|
|
|
var notionModifier = fixedpoint.NewFromFloat(1.1)
|
|
|
|
var two = fixedpoint.NewFromInt(2)
|
2021-10-07 08:39:20 +00:00
|
|
|
|
|
|
|
var log = logrus.WithField("strategy", ID)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
|
|
|
}
|
|
|
|
|
2022-05-05 06:39:29 +00:00
|
|
|
// Deprecated: State is deprecated, please use the persistence tag
|
2021-10-07 08:39:20 +00:00
|
|
|
type State struct {
|
2022-05-05 06:39:29 +00:00
|
|
|
// Deprecated: Position is deprecated, please define the Position field in the strategy struct directly.
|
|
|
|
Position *types.Position `json:"position,omitempty"`
|
|
|
|
|
|
|
|
// Deprecated: ProfitStats is deprecated, please define the ProfitStats field in the strategy struct directly.
|
2022-03-04 08:39:48 +00:00
|
|
|
ProfitStats types.ProfitStats `json:"profitStats,omitempty"`
|
2021-10-07 08:39:20 +00:00
|
|
|
}
|
|
|
|
|
2021-10-17 16:42:01 +00:00
|
|
|
type BollingerSetting struct {
|
|
|
|
types.IntervalWindow
|
|
|
|
BandWidth float64 `json:"bandWidth"`
|
|
|
|
}
|
|
|
|
|
2022-05-27 08:24:50 +00:00
|
|
|
type DynamicSpreadSettings struct {
|
|
|
|
Enabled bool `json:"enabled"`
|
|
|
|
|
|
|
|
// Window is the window of the SMAs of spreads
|
|
|
|
Window int `json:"window"`
|
|
|
|
|
|
|
|
// AskSpreadScale is used to define the ask spread range with the given percentage.
|
|
|
|
AskSpreadScale *bbgo.PercentageScale `json:"askSpreadScale"`
|
|
|
|
|
|
|
|
// BidSpreadScale is used to define the bid spread range with the given percentage.
|
|
|
|
BidSpreadScale *bbgo.PercentageScale `json:"bidSpreadScale"`
|
|
|
|
|
|
|
|
DynamicAskSpread *indicator.SMA
|
|
|
|
DynamicBidSpread *indicator.SMA
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update dynamic spreads
|
|
|
|
func (ds *DynamicSpreadSettings) Update(kline types.KLine) {
|
|
|
|
if !ds.Enabled {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ampl := (kline.GetHigh().Float64() - kline.GetLow().Float64()) / kline.GetOpen().Float64()
|
|
|
|
|
|
|
|
switch kline.Direction() {
|
|
|
|
case types.DirectionUp:
|
|
|
|
ds.DynamicAskSpread.Update(ampl)
|
|
|
|
ds.DynamicBidSpread.Update(0)
|
|
|
|
case types.DirectionDown:
|
|
|
|
ds.DynamicBidSpread.Update(ampl)
|
|
|
|
ds.DynamicAskSpread.Update(0)
|
|
|
|
default:
|
|
|
|
ds.DynamicAskSpread.Update(0)
|
|
|
|
ds.DynamicBidSpread.Update(0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAskSpread returns current ask spread
|
|
|
|
func (ds *DynamicSpreadSettings) GetAskSpread() (askSpread float64, err error) {
|
|
|
|
if !ds.Enabled {
|
|
|
|
return 0, errors.New("dynamic spread is not enabled")
|
|
|
|
}
|
|
|
|
|
|
|
|
if ds.AskSpreadScale != nil && ds.DynamicAskSpread.Length() >= ds.Window {
|
|
|
|
askSpread, err = ds.AskSpreadScale.Scale(ds.DynamicAskSpread.Last())
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("can not calculate dynamicAskSpread")
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return askSpread, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0, errors.New("incomplete dynamic spread settings or not enough data yet")
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetBidSpread returns current dynamic bid spread
|
|
|
|
func (ds *DynamicSpreadSettings) GetBidSpread() (bidSpread float64, err error) {
|
|
|
|
if !ds.Enabled {
|
|
|
|
return 0, errors.New("dynamic spread is not enabled")
|
|
|
|
}
|
|
|
|
|
|
|
|
if ds.BidSpreadScale != nil && ds.DynamicBidSpread.Length() >= ds.Window {
|
|
|
|
bidSpread, err = ds.BidSpreadScale.Scale(ds.DynamicBidSpread.Last())
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("can not calculate dynamicBidSpread")
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bidSpread, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0, errors.New("incomplete dynamic spread settings or not enough data yet")
|
|
|
|
}
|
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
type Strategy struct {
|
|
|
|
*bbgo.Graceful
|
|
|
|
*bbgo.Notifiability
|
|
|
|
*bbgo.Persistence
|
|
|
|
|
2022-03-11 09:00:09 +00:00
|
|
|
Environment *bbgo.Environment
|
2021-10-17 16:42:01 +00:00
|
|
|
StandardIndicatorSet *bbgo.StandardIndicatorSet
|
2022-03-11 09:00:09 +00:00
|
|
|
Market types.Market
|
2021-10-17 16:42:01 +00:00
|
|
|
|
2022-01-09 14:43:49 +00:00
|
|
|
// Symbol is the market symbol you want to trade
|
2022-01-14 18:52:46 +00:00
|
|
|
Symbol string `json:"symbol"`
|
2022-01-09 14:43:49 +00:00
|
|
|
|
|
|
|
// Interval is how long do you want to update your order price and quantity
|
2022-01-14 18:52:46 +00:00
|
|
|
Interval types.Interval `json:"interval"`
|
2022-01-09 14:43:49 +00:00
|
|
|
|
2022-01-30 16:44:04 +00:00
|
|
|
bbgo.QuantityOrAmount
|
2022-01-09 14:43:49 +00:00
|
|
|
|
|
|
|
// Spread is the price spread from the middle price.
|
|
|
|
// For ask orders, the ask price is ((bestAsk + bestBid) / 2 * (1.0 + spread))
|
|
|
|
// For bid orders, the bid price is ((bestAsk + bestBid) / 2 * (1.0 - spread))
|
|
|
|
// Spread can be set by percentage or floating number. e.g., 0.1% or 0.001
|
2022-01-14 18:52:46 +00:00
|
|
|
Spread fixedpoint.Value `json:"spread"`
|
2022-01-09 14:43:49 +00:00
|
|
|
|
2022-01-30 17:08:33 +00:00
|
|
|
// BidSpread overrides the spread setting, this spread will be used for the buy order
|
|
|
|
BidSpread fixedpoint.Value `json:"bidSpread,omitempty"`
|
|
|
|
|
|
|
|
// AskSpread overrides the spread setting, this spread will be used for the sell order
|
|
|
|
AskSpread fixedpoint.Value `json:"askSpread,omitempty"`
|
|
|
|
|
2022-05-27 08:24:50 +00:00
|
|
|
// DynamicSpread enables the automatic adjustment to bid and ask spread.
|
|
|
|
DynamicSpread DynamicSpreadSettings `json:"dynamicSpread,omitempty"`
|
2022-05-13 09:58:46 +00:00
|
|
|
|
2022-01-09 14:43:49 +00:00
|
|
|
// MinProfitSpread is the minimal order price spread from the current average cost.
|
|
|
|
// For long position, you will only place sell order above the price (= average cost * (1 + minProfitSpread))
|
|
|
|
// For short position, you will only place buy order below the price (= average cost * (1 - minProfitSpread))
|
2022-01-08 18:24:10 +00:00
|
|
|
MinProfitSpread fixedpoint.Value `json:"minProfitSpread"`
|
2022-01-09 14:43:49 +00:00
|
|
|
|
|
|
|
// UseTickerPrice use the ticker api to get the mid price instead of the closed kline price.
|
|
|
|
// The back-test engine is kline-based, so the ticker price api is not supported.
|
|
|
|
// Turn this on if you want to do real trading.
|
2022-01-14 18:52:46 +00:00
|
|
|
UseTickerPrice bool `json:"useTickerPrice"`
|
2022-01-08 18:24:10 +00:00
|
|
|
|
|
|
|
// MaxExposurePosition is the maximum position you can hold
|
|
|
|
// +10 means you can hold 10 ETH long position by maximum
|
|
|
|
// -10 means you can hold -10 ETH short position by maximum
|
2022-01-07 18:18:44 +00:00
|
|
|
MaxExposurePosition fixedpoint.Value `json:"maxExposurePosition"`
|
2021-10-07 08:39:20 +00:00
|
|
|
|
2022-01-26 18:04:57 +00:00
|
|
|
// DynamicExposurePositionScale is used to define the exposure position range with the given percentage
|
|
|
|
// when DynamicExposurePositionScale is set,
|
2022-01-26 17:40:54 +00:00
|
|
|
// your MaxExposurePosition will be calculated dynamically according to the bollinger band you set.
|
2022-01-26 18:04:57 +00:00
|
|
|
DynamicExposurePositionScale *bbgo.PercentageScale `json:"dynamicExposurePositionScale"`
|
2022-01-26 17:40:54 +00:00
|
|
|
|
2022-01-26 17:10:39 +00:00
|
|
|
// Long means your position will be long position
|
|
|
|
// Currently not used yet
|
|
|
|
Long *bool `json:"long,omitempty"`
|
|
|
|
|
|
|
|
// Short means your position will be long position
|
|
|
|
// Currently not used yet
|
|
|
|
Short *bool `json:"short,omitempty"`
|
|
|
|
|
2022-01-08 18:24:10 +00:00
|
|
|
// DisableShort means you can don't want short position during the market making
|
2022-01-09 14:43:49 +00:00
|
|
|
// Set to true if you want to hold more spot during market making.
|
2022-01-08 18:24:10 +00:00
|
|
|
DisableShort bool `json:"disableShort"`
|
|
|
|
|
2022-01-31 17:40:51 +00:00
|
|
|
// BuyBelowNeutralSMA if true, the market maker will only place buy order when the current price is below the neutral band SMA.
|
|
|
|
BuyBelowNeutralSMA bool `json:"buyBelowNeutralSMA"`
|
|
|
|
|
2022-01-09 14:32:23 +00:00
|
|
|
// NeutralBollinger is the smaller range of the bollinger band
|
|
|
|
// If price is in this band, it usually means the price is oscillating.
|
2022-01-26 17:10:39 +00:00
|
|
|
// If price goes out of this band, we tend to not place sell orders or buy orders
|
2021-10-17 16:42:01 +00:00
|
|
|
NeutralBollinger *BollingerSetting `json:"neutralBollinger"`
|
|
|
|
|
2022-01-26 17:10:39 +00:00
|
|
|
// DefaultBollinger is the wide range of the bollinger band
|
|
|
|
// for controlling your exposure position
|
|
|
|
DefaultBollinger *BollingerSetting `json:"defaultBollinger"`
|
|
|
|
|
2022-01-09 14:32:23 +00:00
|
|
|
// DowntrendSkew is the order quantity skew for normal downtrend band.
|
|
|
|
// The price is still in the default bollinger band.
|
|
|
|
// greater than 1.0 means when placing buy order, place sell order with less quantity
|
|
|
|
// less than 1.0 means when placing sell order, place buy order with less quantity
|
|
|
|
DowntrendSkew fixedpoint.Value `json:"downtrendSkew"`
|
|
|
|
|
|
|
|
// UptrendSkew is the order quantity skew for normal uptrend band.
|
|
|
|
// The price is still in the default bollinger band.
|
|
|
|
// greater than 1.0 means when placing buy order, place sell order with less quantity
|
|
|
|
// less than 1.0 means when placing sell order, place buy order with less quantity
|
2022-01-14 18:52:46 +00:00
|
|
|
UptrendSkew fixedpoint.Value `json:"uptrendSkew"`
|
2022-01-09 14:32:23 +00:00
|
|
|
|
2022-01-27 17:29:12 +00:00
|
|
|
// TradeInBand
|
|
|
|
// When this is on, places orders only when the current price is in the bollinger band.
|
|
|
|
TradeInBand bool `json:"tradeInBand"`
|
|
|
|
|
2022-01-15 20:06:19 +00:00
|
|
|
// ShadowProtection is used to avoid placing bid order when price goes down strongly (without shadow)
|
2022-01-15 20:40:50 +00:00
|
|
|
ShadowProtection bool `json:"shadowProtection"`
|
2022-01-15 20:06:19 +00:00
|
|
|
ShadowProtectionRatio fixedpoint.Value `json:"shadowProtectionRatio"`
|
|
|
|
|
2022-01-30 17:27:47 +00:00
|
|
|
bbgo.SmartStops
|
2022-01-28 18:22:20 +00:00
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
session *bbgo.ExchangeSession
|
2022-03-11 09:00:09 +00:00
|
|
|
book *types.StreamOrderBook
|
2021-10-07 08:39:20 +00:00
|
|
|
|
|
|
|
state *State
|
|
|
|
|
2022-05-05 06:39:29 +00:00
|
|
|
// persistence fields
|
2022-05-30 07:20:07 +00:00
|
|
|
Position *types.PositionStack `json:"position,omitempty" persistence:"position"`
|
|
|
|
ProfitStats *types.ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
|
|
|
|
|
|
|
|
PushThreshold fixedpoint.Value `json:"pushThreshold,omitempty"`
|
|
|
|
PopThreshold fixedpoint.Value `json:"popThreshold,omitempty"`
|
2022-05-05 01:54:50 +00:00
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
activeMakerOrders *bbgo.LocalActiveOrderBook
|
|
|
|
orderStore *bbgo.OrderStore
|
|
|
|
tradeCollector *bbgo.TradeCollector
|
|
|
|
|
|
|
|
groupID uint32
|
|
|
|
|
|
|
|
stopC chan struct{}
|
2021-10-17 16:42:01 +00:00
|
|
|
|
|
|
|
// defaultBoll is the BOLLINGER indicator we used for predicting the price.
|
|
|
|
defaultBoll *indicator.BOLL
|
2022-01-08 17:57:51 +00:00
|
|
|
|
|
|
|
// neutralBoll is the neutral price section
|
2021-10-17 16:42:01 +00:00
|
|
|
neutralBoll *indicator.BOLL
|
2022-04-15 07:38:40 +00:00
|
|
|
|
|
|
|
// StrategyController
|
2022-05-06 08:52:00 +00:00
|
|
|
bbgo.StrategyController
|
2021-10-07 08:39:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
2022-05-05 06:39:29 +00:00
|
|
|
func (s *Strategy) InstanceID() string {
|
|
|
|
return fmt.Sprintf("%s:%s", ID, s.Symbol)
|
|
|
|
}
|
|
|
|
|
2022-01-29 09:44:42 +00:00
|
|
|
func (s *Strategy) Initialize() error {
|
2022-01-30 17:07:00 +00:00
|
|
|
return s.SmartStops.InitializeStopControllers(s.Symbol)
|
2022-01-28 18:22:20 +00:00
|
|
|
}
|
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
|
2022-05-19 01:48:36 +00:00
|
|
|
Interval: s.Interval,
|
2021-10-07 08:39:20 +00:00
|
|
|
})
|
2022-01-07 18:18:44 +00:00
|
|
|
|
|
|
|
if s.DefaultBollinger != nil && s.DefaultBollinger.Interval != "" {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
|
2022-05-19 01:48:36 +00:00
|
|
|
Interval: s.DefaultBollinger.Interval,
|
2022-01-07 18:18:44 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.NeutralBollinger != nil && s.NeutralBollinger.Interval != "" {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
|
2022-05-19 01:48:36 +00:00
|
|
|
Interval: s.NeutralBollinger.Interval,
|
2022-01-07 18:18:44 +00:00
|
|
|
})
|
|
|
|
}
|
2022-01-28 18:22:20 +00:00
|
|
|
|
2022-01-30 17:07:00 +00:00
|
|
|
s.SmartStops.Subscribe(session)
|
2021-10-07 08:39:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Validate() error {
|
|
|
|
if len(s.Symbol) == 0 {
|
|
|
|
return errors.New("symbol is required")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-30 07:20:07 +00:00
|
|
|
func (s *Strategy) CurrentPosition() *types.PositionStack {
|
2022-05-05 01:54:50 +00:00
|
|
|
return s.Position
|
2022-01-14 18:52:46 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error {
|
2022-05-05 01:54:50 +00:00
|
|
|
base := s.Position.GetBase()
|
2022-02-07 03:40:30 +00:00
|
|
|
if base.IsZero() {
|
2022-05-05 01:54:50 +00:00
|
|
|
return fmt.Errorf("no opened %s position", s.Position.Symbol)
|
2022-01-14 18:52:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// make it negative
|
2022-02-07 03:40:30 +00:00
|
|
|
quantity := base.Mul(percentage).Abs()
|
2022-01-14 18:52:46 +00:00
|
|
|
side := types.SideTypeBuy
|
2022-02-07 03:40:30 +00:00
|
|
|
if base.Sign() > 0 {
|
2022-01-14 18:52:46 +00:00
|
|
|
side = types.SideTypeSell
|
|
|
|
}
|
|
|
|
|
2022-03-05 04:40:56 +00:00
|
|
|
if quantity.Compare(s.Market.MinQuantity) < 0 {
|
|
|
|
return fmt.Errorf("order quantity %v is too small, less than %v", quantity, s.Market.MinQuantity)
|
2022-01-14 18:52:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
submitOrder := types.SubmitOrder{
|
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: side,
|
|
|
|
Type: types.OrderTypeMarket,
|
2022-02-07 03:40:30 +00:00
|
|
|
Quantity: quantity,
|
2022-03-05 04:40:56 +00:00
|
|
|
Market: s.Market,
|
2022-01-14 18:52:46 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
s.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder)
|
2022-01-14 18:52:46 +00:00
|
|
|
|
|
|
|
createdOrders, err := s.session.Exchange.SubmitOrders(ctx, submitOrder)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("can not place position close order")
|
|
|
|
}
|
|
|
|
|
|
|
|
s.orderStore.Add(createdOrders...)
|
|
|
|
s.activeMakerOrders.Add(createdOrders...)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-05 06:47:06 +00:00
|
|
|
// Deprecated: LoadState method is migrated to the persistence struct tag.
|
2021-10-07 08:39:20 +00:00
|
|
|
func (s *Strategy) LoadState() error {
|
|
|
|
var state State
|
|
|
|
|
|
|
|
// load position
|
2022-05-05 06:39:29 +00:00
|
|
|
if err := s.Persistence.Load(&state, ID, s.Symbol, stateKey); err == nil {
|
2021-10-07 08:39:20 +00:00
|
|
|
s.state = &state
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-01-26 18:22:26 +00:00
|
|
|
func (s *Strategy) getCurrentAllowedExposurePosition(bandPercentage float64) (fixedpoint.Value, error) {
|
|
|
|
if s.DynamicExposurePositionScale != nil {
|
|
|
|
v, err := s.DynamicExposurePositionScale.Scale(bandPercentage)
|
|
|
|
if err != nil {
|
2022-02-07 03:40:30 +00:00
|
|
|
return fixedpoint.Zero, err
|
2022-01-26 18:22:26 +00:00
|
|
|
}
|
|
|
|
return fixedpoint.NewFromFloat(v), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return s.MaxExposurePosition, nil
|
|
|
|
}
|
|
|
|
|
2022-01-15 20:06:19 +00:00
|
|
|
func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExecutor, midPrice fixedpoint.Value, kline *types.KLine) {
|
2022-01-30 17:11:30 +00:00
|
|
|
bidSpread := s.Spread
|
2022-02-07 03:40:30 +00:00
|
|
|
if s.BidSpread.Sign() > 0 {
|
2022-01-30 17:11:30 +00:00
|
|
|
bidSpread = s.BidSpread
|
|
|
|
}
|
|
|
|
|
|
|
|
askSpread := s.Spread
|
2022-02-07 03:40:30 +00:00
|
|
|
if s.AskSpread.Sign() > 0 {
|
2022-01-30 17:11:30 +00:00
|
|
|
askSpread = s.AskSpread
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
askPrice := midPrice.Mul(fixedpoint.One.Add(askSpread))
|
|
|
|
bidPrice := midPrice.Mul(fixedpoint.One.Sub(bidSpread))
|
2022-05-05 01:54:50 +00:00
|
|
|
base := s.Position.GetBase()
|
2022-04-23 07:43:11 +00:00
|
|
|
balances := s.session.GetAccount().Balances()
|
2021-10-07 08:39:20 +00:00
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
log.Infof("mid price:%v spread: %s ask:%v bid: %v position: %s",
|
|
|
|
midPrice,
|
2021-10-17 16:42:01 +00:00
|
|
|
s.Spread.Percentage(),
|
2022-02-07 03:40:30 +00:00
|
|
|
askPrice,
|
|
|
|
bidPrice,
|
2022-05-05 01:54:50 +00:00
|
|
|
s.Position,
|
2021-10-17 16:42:01 +00:00
|
|
|
)
|
|
|
|
|
2022-01-30 17:27:47 +00:00
|
|
|
sellQuantity := s.QuantityOrAmount.CalculateQuantity(askPrice)
|
|
|
|
buyQuantity := s.QuantityOrAmount.CalculateQuantity(bidPrice)
|
2022-01-26 17:10:39 +00:00
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
sellOrder := types.SubmitOrder{
|
2022-04-15 07:38:40 +00:00
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: types.SideTypeSell,
|
|
|
|
Type: types.OrderTypeLimitMaker,
|
|
|
|
Quantity: sellQuantity,
|
|
|
|
Price: askPrice,
|
|
|
|
Market: s.Market,
|
|
|
|
GroupID: s.groupID,
|
2021-10-07 08:39:20 +00:00
|
|
|
}
|
|
|
|
buyOrder := types.SubmitOrder{
|
2022-04-15 07:38:40 +00:00
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: types.SideTypeBuy,
|
|
|
|
Type: types.OrderTypeLimitMaker,
|
|
|
|
Quantity: buyQuantity,
|
|
|
|
Price: bidPrice,
|
|
|
|
Market: s.Market,
|
|
|
|
GroupID: s.groupID,
|
2021-10-07 08:39:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var submitOrders []types.SubmitOrder
|
|
|
|
|
2022-03-05 04:40:56 +00:00
|
|
|
baseBalance, hasBaseBalance := balances[s.Market.BaseCurrency]
|
|
|
|
quoteBalance, hasQuoteBalance := balances[s.Market.QuoteCurrency]
|
2022-01-08 17:57:51 +00:00
|
|
|
|
2022-01-26 18:22:26 +00:00
|
|
|
downBand := s.defaultBoll.LastDownBand()
|
|
|
|
upBand := s.defaultBoll.LastUpBand()
|
|
|
|
sma := s.defaultBoll.LastSMA()
|
|
|
|
log.Infof("bollinger band: up %f sma %f down %f", upBand, sma, downBand)
|
2022-01-15 20:40:50 +00:00
|
|
|
|
2022-01-26 18:22:26 +00:00
|
|
|
bandPercentage := calculateBandPercentage(upBand, downBand, sma, midPrice.Float64())
|
2022-02-07 03:40:30 +00:00
|
|
|
log.Infof("mid price band percentage: %v", bandPercentage)
|
2022-01-26 18:25:23 +00:00
|
|
|
|
2022-01-26 18:22:26 +00:00
|
|
|
maxExposurePosition, err := s.getCurrentAllowedExposurePosition(bandPercentage)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("can not calculate CurrentAllowedExposurePosition")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
log.Infof("calculated max exposure position: %v", maxExposurePosition)
|
2022-01-26 18:25:23 +00:00
|
|
|
|
2022-01-31 17:40:51 +00:00
|
|
|
canSell := true
|
|
|
|
canBuy := true
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if maxExposurePosition.Sign() > 0 && base.Compare(maxExposurePosition) > 0 {
|
2022-01-31 17:40:51 +00:00
|
|
|
canBuy = false
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if maxExposurePosition.Sign() > 0 {
|
|
|
|
if s.Long != nil && *s.Long && base.Sign() < 0 {
|
2022-01-31 17:40:51 +00:00
|
|
|
canSell = false
|
2022-02-07 03:40:30 +00:00
|
|
|
} else if base.Compare(maxExposurePosition.Neg()) < 0 {
|
2022-01-31 17:40:51 +00:00
|
|
|
canSell = false
|
|
|
|
}
|
|
|
|
}
|
2022-01-26 18:22:26 +00:00
|
|
|
|
|
|
|
if s.ShadowProtection && kline != nil {
|
2022-01-15 20:40:50 +00:00
|
|
|
switch kline.Direction() {
|
|
|
|
case types.DirectionDown:
|
|
|
|
shadowHeight := kline.GetLowerShadowHeight()
|
|
|
|
shadowRatio := kline.GetLowerShadowRatio()
|
2022-02-07 03:40:30 +00:00
|
|
|
if shadowHeight.IsZero() && shadowRatio.Compare(s.ShadowProtectionRatio) < 0 {
|
|
|
|
log.Infof("%s shadow protection enabled, lower shadow ratio %v < %v", s.Symbol, shadowRatio, s.ShadowProtectionRatio)
|
2022-01-15 20:40:50 +00:00
|
|
|
canBuy = false
|
|
|
|
}
|
|
|
|
case types.DirectionUp:
|
|
|
|
shadowHeight := kline.GetUpperShadowHeight()
|
|
|
|
shadowRatio := kline.GetUpperShadowRatio()
|
2022-02-07 03:40:30 +00:00
|
|
|
if shadowHeight.IsZero() || shadowRatio.Compare(s.ShadowProtectionRatio) < 0 {
|
|
|
|
log.Infof("%s shadow protection enabled, upper shadow ratio %v < %v", s.Symbol, shadowRatio, s.ShadowProtectionRatio)
|
2022-01-15 20:40:50 +00:00
|
|
|
canSell = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-27 10:51:51 +00:00
|
|
|
// Apply quantity skew
|
|
|
|
// CASE #1:
|
|
|
|
// WHEN: price is in the neutral bollginer band (window 1) == neutral
|
|
|
|
// THEN: we don't apply skew
|
|
|
|
// CASE #2:
|
|
|
|
// WHEN: price is in the upper band (window 2 > price > window 1) == upTrend
|
|
|
|
// THEN: we apply upTrend skew
|
|
|
|
// CASE #3:
|
|
|
|
// WHEN: price is in the lower band (window 2 < price < window 1) == downTrend
|
|
|
|
// THEN: we apply downTrend skew
|
|
|
|
// CASE #4:
|
|
|
|
// WHEN: price breaks the lower band (price < window 2) == strongDownTrend
|
|
|
|
// THEN: we apply strongDownTrend skew
|
|
|
|
// CASE #5:
|
|
|
|
// WHEN: price breaks the upper band (price > window 2) == strongUpTrend
|
|
|
|
// THEN: we apply strongUpTrend skew
|
2022-01-27 17:29:12 +00:00
|
|
|
if s.TradeInBand {
|
|
|
|
if !inBetween(midPrice.Float64(), s.neutralBoll.LastDownBand(), s.neutralBoll.LastUpBand()) {
|
|
|
|
log.Infof("tradeInBand is set, skip placing orders when the price is outside of the band")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-27 10:51:51 +00:00
|
|
|
trend := s.detectPriceTrend(s.neutralBoll, midPrice.Float64())
|
|
|
|
switch trend {
|
|
|
|
case NeutralTrend:
|
|
|
|
// do nothing
|
|
|
|
|
|
|
|
case UpTrend:
|
2022-02-07 03:40:30 +00:00
|
|
|
skew := s.UptrendSkew
|
2022-03-05 04:40:56 +00:00
|
|
|
buyOrder.Quantity = fixedpoint.Max(s.Market.MinQuantity, sellOrder.Quantity.Mul(skew))
|
2022-01-27 10:51:51 +00:00
|
|
|
|
|
|
|
case DownTrend:
|
2022-02-07 03:40:30 +00:00
|
|
|
skew := s.DowntrendSkew
|
|
|
|
ratio := fixedpoint.One.Div(skew)
|
2022-03-05 04:40:56 +00:00
|
|
|
sellOrder.Quantity = fixedpoint.Max(s.Market.MinQuantity, buyOrder.Quantity.Mul(ratio))
|
2022-01-27 10:51:51 +00:00
|
|
|
|
2022-01-09 14:32:23 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if !hasQuoteBalance || buyOrder.Quantity.Mul(buyOrder.Price).Compare(quoteBalance.Available) > 0 {
|
2022-01-29 17:21:36 +00:00
|
|
|
canBuy = false
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if !hasBaseBalance || sellOrder.Quantity.Compare(baseBalance.Available) > 0 {
|
2022-01-29 17:21:36 +00:00
|
|
|
canSell = false
|
|
|
|
}
|
|
|
|
|
2022-05-05 01:54:50 +00:00
|
|
|
if midPrice.Compare(s.Position.AverageCost.Mul(fixedpoint.One.Add(s.MinProfitSpread))) < 0 {
|
2022-01-31 17:40:51 +00:00
|
|
|
canSell = false
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if s.Long != nil && *s.Long && base.Sub(sellOrder.Quantity).Sign() < 0 {
|
2022-01-31 17:40:51 +00:00
|
|
|
canSell = false
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.BuyBelowNeutralSMA && midPrice.Float64() > s.neutralBoll.LastSMA() {
|
|
|
|
canBuy = false
|
|
|
|
}
|
|
|
|
|
|
|
|
if canSell {
|
|
|
|
submitOrders = append(submitOrders, sellOrder)
|
2022-01-09 14:32:23 +00:00
|
|
|
}
|
2022-01-15 20:40:50 +00:00
|
|
|
if canBuy {
|
|
|
|
submitOrders = append(submitOrders, buyOrder)
|
2022-01-09 14:32:23 +00:00
|
|
|
}
|
2022-01-15 17:15:34 +00:00
|
|
|
|
2022-01-15 20:40:50 +00:00
|
|
|
// condition for lower the average cost
|
|
|
|
/*
|
2022-05-05 01:54:50 +00:00
|
|
|
if midPrice < s.Position.AverageCost.MulFloat64(1.0-s.MinProfitSpread.Float64()) && canBuy {
|
2022-01-15 20:06:19 +00:00
|
|
|
submitOrders = append(submitOrders, buyOrder)
|
|
|
|
}
|
2022-01-15 20:40:50 +00:00
|
|
|
*/
|
2021-10-07 08:39:20 +00:00
|
|
|
|
2022-01-08 18:35:12 +00:00
|
|
|
if len(submitOrders) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-15 20:06:19 +00:00
|
|
|
for i := range submitOrders {
|
|
|
|
submitOrders[i] = s.adjustOrderQuantity(submitOrders[i])
|
|
|
|
}
|
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrders...)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("can not place ping pong orders")
|
|
|
|
}
|
|
|
|
s.orderStore.Add(createdOrders...)
|
|
|
|
s.activeMakerOrders.Add(createdOrders...)
|
|
|
|
}
|
|
|
|
|
2022-01-27 10:51:51 +00:00
|
|
|
type PriceTrend string
|
|
|
|
|
|
|
|
const (
|
|
|
|
NeutralTrend PriceTrend = "neutral"
|
|
|
|
UpTrend PriceTrend = "upTrend"
|
|
|
|
DownTrend PriceTrend = "downTrend"
|
|
|
|
UnknownTrend PriceTrend = "unknown"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Strategy) detectPriceTrend(inc *indicator.BOLL, price float64) PriceTrend {
|
|
|
|
if inBetween(price, inc.LastDownBand(), inc.LastUpBand()) {
|
|
|
|
return NeutralTrend
|
|
|
|
}
|
|
|
|
|
|
|
|
if price < inc.LastDownBand() {
|
|
|
|
return DownTrend
|
|
|
|
}
|
|
|
|
|
|
|
|
if price > inc.LastUpBand() {
|
|
|
|
return UpTrend
|
|
|
|
}
|
|
|
|
|
|
|
|
return UnknownTrend
|
|
|
|
}
|
|
|
|
|
2022-01-15 17:15:34 +00:00
|
|
|
func (s *Strategy) adjustOrderQuantity(submitOrder types.SubmitOrder) types.SubmitOrder {
|
2022-03-05 04:40:56 +00:00
|
|
|
if submitOrder.Quantity.Mul(submitOrder.Price).Compare(s.Market.MinNotional) < 0 {
|
|
|
|
submitOrder.Quantity = bbgo.AdjustFloatQuantityByMinAmount(submitOrder.Quantity, submitOrder.Price, s.Market.MinNotional.Mul(notionModifier))
|
2022-01-15 17:15:34 +00:00
|
|
|
}
|
|
|
|
|
2022-03-05 04:40:56 +00:00
|
|
|
if submitOrder.Quantity.Compare(s.Market.MinQuantity) < 0 {
|
|
|
|
submitOrder.Quantity = fixedpoint.Max(submitOrder.Quantity, s.Market.MinQuantity)
|
2022-01-15 17:15:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return submitOrder
|
|
|
|
}
|
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
2022-04-15 07:38:40 +00:00
|
|
|
// StrategyController
|
2022-05-06 08:52:00 +00:00
|
|
|
s.Status = types.StrategyStatusRunning
|
|
|
|
|
2022-05-13 09:58:46 +00:00
|
|
|
// Setup dynamic spread
|
2022-05-27 08:24:50 +00:00
|
|
|
if s.DynamicSpread.Enabled {
|
|
|
|
s.DynamicSpread.DynamicBidSpread = &indicator.SMA{IntervalWindow: types.IntervalWindow{s.Interval, s.DynamicSpread.Window}}
|
|
|
|
s.DynamicSpread.DynamicAskSpread = &indicator.SMA{IntervalWindow: types.IntervalWindow{s.Interval, s.DynamicSpread.Window}}
|
2022-05-13 09:58:46 +00:00
|
|
|
}
|
|
|
|
|
2022-05-06 08:52:00 +00:00
|
|
|
s.OnSuspend(func() {
|
|
|
|
s.Status = types.StrategyStatusStopped
|
|
|
|
|
|
|
|
// Cancel all order
|
|
|
|
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
|
|
|
|
log.WithError(err).Errorf("graceful cancel order error")
|
|
|
|
s.Notify("graceful cancel order error")
|
|
|
|
} else {
|
|
|
|
s.Notify("All orders are cancelled.")
|
|
|
|
}
|
|
|
|
|
|
|
|
s.tradeCollector.Process()
|
|
|
|
|
|
|
|
_ = s.Persistence.Sync(s)
|
|
|
|
})
|
|
|
|
|
|
|
|
s.OnEmergencyStop(func() {
|
|
|
|
// Close 100% position
|
|
|
|
percentage := fixedpoint.NewFromFloat(1.0)
|
|
|
|
_ = s.ClosePosition(ctx, percentage)
|
|
|
|
})
|
2022-04-15 07:38:40 +00:00
|
|
|
|
2022-01-31 17:40:51 +00:00
|
|
|
if s.DisableShort {
|
|
|
|
s.Long = &[]bool{true}[0]
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if s.MinProfitSpread.IsZero() {
|
2022-01-07 18:18:44 +00:00
|
|
|
s.MinProfitSpread = fixedpoint.NewFromFloat(0.001)
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if s.UptrendSkew.IsZero() {
|
2022-01-09 14:37:27 +00:00
|
|
|
s.UptrendSkew = fixedpoint.NewFromFloat(1.0 / 1.2)
|
2022-01-09 14:32:23 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if s.DowntrendSkew.IsZero() {
|
2022-01-09 14:37:27 +00:00
|
|
|
s.DowntrendSkew = fixedpoint.NewFromFloat(1.2)
|
2022-01-09 14:32:23 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if s.ShadowProtectionRatio.IsZero() {
|
2022-01-15 20:40:50 +00:00
|
|
|
s.ShadowProtectionRatio = fixedpoint.NewFromFloat(0.01)
|
2022-01-15 20:06:19 +00:00
|
|
|
}
|
|
|
|
|
2022-01-09 14:32:23 +00:00
|
|
|
// initial required information
|
|
|
|
s.session = session
|
2022-05-13 14:20:23 +00:00
|
|
|
|
2021-10-17 16:42:01 +00:00
|
|
|
s.neutralBoll = s.StandardIndicatorSet.BOLL(s.NeutralBollinger.IntervalWindow, s.NeutralBollinger.BandWidth)
|
2022-01-08 17:57:51 +00:00
|
|
|
s.defaultBoll = s.StandardIndicatorSet.BOLL(s.DefaultBollinger.IntervalWindow, s.DefaultBollinger.BandWidth)
|
2021-10-17 16:42:01 +00:00
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
// calculate group id for orders
|
2022-05-05 04:53:48 +00:00
|
|
|
instanceID := s.InstanceID()
|
2022-05-05 06:39:29 +00:00
|
|
|
s.groupID = util.FNV32(instanceID)
|
2021-10-07 08:39:20 +00:00
|
|
|
|
|
|
|
// restore state
|
|
|
|
if err := s.LoadState(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-05 01:54:50 +00:00
|
|
|
// If position is nil, we need to allocate a new position for calculation
|
|
|
|
if s.Position == nil {
|
|
|
|
// fallback to the legacy position struct in the state
|
2022-05-05 06:39:29 +00:00
|
|
|
if s.state != nil && s.state.Position != nil {
|
2022-05-30 07:20:07 +00:00
|
|
|
s.Position.Position = s.state.Position
|
2022-05-05 01:54:50 +00:00
|
|
|
} else {
|
2022-05-30 07:20:07 +00:00
|
|
|
s.Position = types.NewPositionStackFromMarket(s.Market)
|
2022-05-05 01:54:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-13 14:20:23 +00:00
|
|
|
if s.session.MakerFeeRate.Sign() > 0 || s.session.TakerFeeRate.Sign() > 0 {
|
|
|
|
s.Position.SetExchangeFeeRate(s.session.ExchangeName, types.ExchangeFee{
|
|
|
|
MakerFeeRate: s.session.MakerFeeRate,
|
|
|
|
TakerFeeRate: s.session.TakerFeeRate,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-05-05 06:39:29 +00:00
|
|
|
if s.ProfitStats == nil {
|
|
|
|
if s.state != nil {
|
2022-05-05 06:41:11 +00:00
|
|
|
// copy profit stats
|
2022-05-05 06:39:29 +00:00
|
|
|
p2 := s.state.ProfitStats
|
|
|
|
s.ProfitStats = &p2
|
|
|
|
} else {
|
2022-05-05 06:48:50 +00:00
|
|
|
s.ProfitStats = types.NewProfitStats(s.Market)
|
2022-05-05 06:39:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-05 01:54:50 +00:00
|
|
|
// Always update the position fields
|
|
|
|
s.Position.Strategy = ID
|
|
|
|
s.Position.StrategyInstanceID = instanceID
|
2022-03-11 13:15:57 +00:00
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
s.stopC = make(chan struct{})
|
|
|
|
|
2022-01-06 16:10:40 +00:00
|
|
|
s.activeMakerOrders = bbgo.NewLocalActiveOrderBook(s.Symbol)
|
2021-10-07 08:39:20 +00:00
|
|
|
s.activeMakerOrders.BindStream(session.UserDataStream)
|
|
|
|
|
|
|
|
s.orderStore = bbgo.NewOrderStore(s.Symbol)
|
|
|
|
s.orderStore.BindStream(session.UserDataStream)
|
|
|
|
|
2022-05-05 01:54:50 +00:00
|
|
|
s.tradeCollector = bbgo.NewTradeCollector(s.Symbol, s.Position, s.orderStore)
|
2021-10-17 14:23:34 +00:00
|
|
|
|
2022-03-11 13:27:45 +00:00
|
|
|
s.tradeCollector.OnTrade(func(trade types.Trade, profit, netProfit fixedpoint.Value) {
|
2022-04-15 07:38:40 +00:00
|
|
|
// StrategyController
|
2022-05-06 08:52:00 +00:00
|
|
|
if s.Status != types.StrategyStatusRunning {
|
2022-04-15 07:38:40 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
s.Notifiability.Notify(trade)
|
2022-05-05 06:39:29 +00:00
|
|
|
s.ProfitStats.AddTrade(trade)
|
2022-03-11 13:27:45 +00:00
|
|
|
|
|
|
|
if profit.Compare(fixedpoint.Zero) == 0 {
|
2022-05-30 07:20:07 +00:00
|
|
|
s.Environment.RecordPosition(s.Position.Position, trade, nil)
|
2022-03-11 13:27:45 +00:00
|
|
|
} else {
|
|
|
|
log.Infof("%s generated profit: %v", s.Symbol, profit)
|
2022-05-05 01:54:50 +00:00
|
|
|
p := s.Position.NewProfit(trade, profit, netProfit)
|
2022-03-11 13:27:45 +00:00
|
|
|
p.Strategy = ID
|
|
|
|
p.StrategyInstanceID = instanceID
|
|
|
|
s.Notify(&p)
|
|
|
|
|
2022-05-05 06:39:29 +00:00
|
|
|
s.ProfitStats.AddProfit(p)
|
|
|
|
s.Notify(&s.ProfitStats)
|
2022-03-11 15:38:37 +00:00
|
|
|
|
2022-05-30 07:20:07 +00:00
|
|
|
s.Environment.RecordPosition(s.Position.Position, trade, &p)
|
2022-03-11 13:27:45 +00:00
|
|
|
}
|
2021-10-07 08:39:20 +00:00
|
|
|
})
|
2021-10-17 14:23:34 +00:00
|
|
|
|
2022-05-30 07:20:07 +00:00
|
|
|
s.tradeCollector.OnPositionUpdate(func(position types.PositionInterface) {
|
2022-05-05 01:54:50 +00:00
|
|
|
log.Infof("position changed: %s", s.Position)
|
|
|
|
s.Notify(s.Position)
|
2021-10-07 08:39:20 +00:00
|
|
|
})
|
2021-10-08 05:23:38 +00:00
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
s.tradeCollector.BindStream(session.UserDataStream)
|
2021-10-17 14:23:34 +00:00
|
|
|
|
2022-01-30 17:07:00 +00:00
|
|
|
s.SmartStops.RunStopControllers(ctx, session, s.tradeCollector)
|
2022-01-29 09:44:42 +00:00
|
|
|
|
2022-05-09 11:42:39 +00:00
|
|
|
if s.Environment.IsBackTesting() {
|
|
|
|
log.Warn("turning of useTickerPrice option in the back-testing environment...")
|
|
|
|
s.UseTickerPrice = false
|
|
|
|
}
|
|
|
|
|
2021-10-07 08:39:20 +00:00
|
|
|
session.UserDataStream.OnStart(func() {
|
2022-01-07 18:18:44 +00:00
|
|
|
if s.UseTickerPrice {
|
|
|
|
ticker, err := s.session.Exchange.QueryTicker(ctx, s.Symbol)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
midPrice := ticker.Buy.Add(ticker.Sell).Div(two)
|
2022-01-15 20:06:19 +00:00
|
|
|
s.placeOrders(ctx, orderExecutor, midPrice, nil)
|
2022-01-07 18:18:44 +00:00
|
|
|
} else {
|
|
|
|
if price, ok := session.LastPrice(s.Symbol); ok {
|
2022-02-07 03:40:30 +00:00
|
|
|
s.placeOrders(ctx, orderExecutor, price, nil)
|
2022-01-07 18:18:44 +00:00
|
|
|
}
|
|
|
|
}
|
2021-10-07 08:39:20 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2022-04-15 07:38:40 +00:00
|
|
|
// StrategyController
|
2022-05-06 08:52:00 +00:00
|
|
|
if s.Status != types.StrategyStatusRunning {
|
2022-04-15 07:38:40 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-29 17:40:33 +00:00
|
|
|
if kline.Symbol != s.Symbol || kline.Interval != s.Interval {
|
2022-01-07 18:18:44 +00:00
|
|
|
return
|
|
|
|
}
|
2021-10-07 08:39:20 +00:00
|
|
|
|
2022-05-23 03:37:57 +00:00
|
|
|
// Update spreads with dynamic spread
|
2022-05-27 08:24:50 +00:00
|
|
|
if s.DynamicSpread.Enabled {
|
|
|
|
s.DynamicSpread.Update(kline)
|
|
|
|
dynamicBidSpread, err := s.DynamicSpread.GetBidSpread()
|
2022-05-23 03:37:57 +00:00
|
|
|
if err == nil && dynamicBidSpread > 0 {
|
|
|
|
s.BidSpread = fixedpoint.NewFromFloat(dynamicBidSpread)
|
|
|
|
log.Infof("new bid spread: %v", s.BidSpread.Percentage())
|
|
|
|
}
|
2022-05-27 08:24:50 +00:00
|
|
|
dynamicAskSpread, err := s.DynamicSpread.GetAskSpread()
|
2022-05-23 03:37:57 +00:00
|
|
|
if err == nil && dynamicAskSpread > 0 {
|
|
|
|
s.AskSpread = fixedpoint.NewFromFloat(dynamicAskSpread)
|
|
|
|
log.Infof("new ask spread: %v", s.AskSpread.Percentage())
|
|
|
|
}
|
2022-05-13 09:58:46 +00:00
|
|
|
}
|
|
|
|
|
2022-01-07 18:18:44 +00:00
|
|
|
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
|
|
|
|
log.WithError(err).Errorf("graceful cancel order error")
|
|
|
|
}
|
2022-05-30 07:20:07 +00:00
|
|
|
//log.Error(len(s.Position.Stack), s.Position.AverageCost, kline.Close)
|
2021-10-17 16:42:01 +00:00
|
|
|
|
2022-05-30 07:20:07 +00:00
|
|
|
if s.Position.Position.AverageCost.Div(kline.Close).Compare(fixedpoint.One.Add(s.PushThreshold)) > 0 {
|
|
|
|
log.Errorf("push")
|
|
|
|
log.Error(s.Position)
|
|
|
|
s.Position = s.Position.Push(types.NewPositionFromMarket(s.Market))
|
|
|
|
}
|
|
|
|
// &&
|
|
|
|
if len(s.Position.Stack) > 1 && s.Position.Stack[len(s.Position.Stack)-2].AverageCost.Compare(kline.Close) < 0 && s.Market.IsDustQuantity(s.Position.Position.GetBase(), kline.Close) {
|
|
|
|
log.Errorf("pop")
|
|
|
|
log.Error(s.Position)
|
|
|
|
s.Position = s.Position.Pop()
|
|
|
|
}
|
|
|
|
//if s.Position.AverageCost.Div(kline.Close).Compare(fixedpoint.One.Sub(s.PopThreshold)) < 0 && && !s.Position.AverageCost.IsZero() {
|
|
|
|
// //log.Error(len(s.Position.Stack), s.Position.AverageCost, kline.Close)
|
|
|
|
// log.Errorf("pop")
|
|
|
|
// s.ClosePosition(ctx, fixedpoint.One)
|
|
|
|
// s.Position = s.Position.Pop()
|
|
|
|
//}
|
2022-01-29 17:40:33 +00:00
|
|
|
// check if there is a canceled order had partially filled.
|
2021-10-17 16:42:01 +00:00
|
|
|
s.tradeCollector.Process()
|
2022-01-07 18:18:44 +00:00
|
|
|
|
|
|
|
if s.UseTickerPrice {
|
|
|
|
ticker, err := s.session.Exchange.QueryTicker(ctx, s.Symbol)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
midPrice := ticker.Buy.Add(ticker.Sell).Div(two)
|
|
|
|
log.Infof("using ticker price: bid %v / ask %v, mid price %v", ticker.Buy, ticker.Sell, midPrice)
|
2022-01-15 20:06:19 +00:00
|
|
|
s.placeOrders(ctx, orderExecutor, midPrice, &kline)
|
2022-01-07 18:18:44 +00:00
|
|
|
} else {
|
2022-02-07 03:40:30 +00:00
|
|
|
s.placeOrders(ctx, orderExecutor, kline.Close, &kline)
|
2022-01-07 18:18:44 +00:00
|
|
|
}
|
2021-10-07 08:39:20 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
// s.book = types.NewStreamBook(s.Symbol)
|
2021-10-08 05:23:38 +00:00
|
|
|
// s.book.BindStreamForBackground(session.MarketDataStream)
|
2021-10-07 08:39:20 +00:00
|
|
|
|
|
|
|
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
|
|
|
close(s.stopC)
|
|
|
|
|
2022-01-07 18:18:44 +00:00
|
|
|
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
|
|
|
|
log.WithError(err).Errorf("graceful cancel order error")
|
|
|
|
}
|
2021-10-07 08:39:20 +00:00
|
|
|
|
2022-01-15 17:27:28 +00:00
|
|
|
s.tradeCollector.Process()
|
2021-10-07 08:39:20 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2022-01-26 18:22:26 +00:00
|
|
|
|
|
|
|
func calculateBandPercentage(up, down, sma, midPrice float64) float64 {
|
|
|
|
if midPrice < sma {
|
|
|
|
// should be negative percentage
|
|
|
|
return (midPrice - sma) / math.Abs(sma-down)
|
|
|
|
} else if midPrice > sma {
|
|
|
|
// should be positive percentage
|
2022-02-15 05:55:19 +00:00
|
|
|
return (midPrice - sma) / math.Abs(up-sma)
|
2022-01-26 18:22:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0.0
|
|
|
|
}
|
2022-01-27 10:51:51 +00:00
|
|
|
|
|
|
|
func inBetween(x, a, b float64) bool {
|
|
|
|
return a < x && x < b
|
|
|
|
}
|