2022-05-10 09:11:24 +00:00
package pivotshort
2022-05-09 21:11:22 +00:00
import (
"context"
"fmt"
2022-05-19 01:48:36 +00:00
2022-06-04 17:09:31 +00:00
"github.com/sirupsen/logrus"
2022-05-09 21:11:22 +00:00
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
2022-05-13 10:05:25 +00:00
"github.com/c9s/bbgo/pkg/indicator"
2022-05-09 21:11:22 +00:00
"github.com/c9s/bbgo/pkg/types"
)
2022-05-10 09:11:24 +00:00
const ID = "pivotshort"
2022-05-09 21:11:22 +00:00
var log = logrus . WithField ( "strategy" , ID )
func init ( ) {
bbgo . RegisterStrategy ( ID , & Strategy { } )
}
type IntervalWindowSetting struct {
types . IntervalWindow
}
2022-06-03 08:38:06 +00:00
type Entry struct {
2022-06-03 15:23:26 +00:00
Immediate bool ` json:"immediate" `
2022-06-03 08:38:06 +00:00
CatBounceRatio fixedpoint . Value ` json:"catBounceRatio" `
Quantity fixedpoint . Value ` json:"quantity" `
2022-06-05 04:37:35 +00:00
NumLayers int ` json:"numLayers" `
2022-06-03 08:38:06 +00:00
MarginSideEffect types . MarginOrderSideEffectType ` json:"marginOrderSideEffect" `
}
type Exit struct {
TakeProfitPercentage fixedpoint . Value ` json:"takeProfitPercentage" `
StopLossPercentage fixedpoint . Value ` json:"stopLossPercentage" `
2022-06-03 15:28:48 +00:00
ShadowTPRatio fixedpoint . Value ` json:"shadowTakeProfitRatio" `
2022-06-03 08:38:06 +00:00
MarginSideEffect types . MarginOrderSideEffectType ` json:"marginOrderSideEffect" `
}
2022-05-09 21:11:22 +00:00
type Strategy struct {
2022-05-12 11:27:57 +00:00
* bbgo . Graceful
* bbgo . Notifiability
* bbgo . Persistence
2022-06-02 13:34:26 +00:00
Environment * bbgo . Environment
Symbol string ` json:"symbol" `
Market types . Market
Interval types . Interval ` json:"interval" `
TotalQuantity fixedpoint . Value ` json:"totalQuantity" `
2022-05-12 11:27:57 +00:00
// persistence fields
Position * types . Position ` json:"position,omitempty" persistence:"position" `
ProfitStats * types . ProfitStats ` json:"profitStats,omitempty" persistence:"profit_stats" `
2022-05-09 21:11:22 +00:00
2022-06-03 08:38:06 +00:00
PivotLength int ` json:"pivotLength" `
2022-06-03 18:17:58 +00:00
LastLow fixedpoint . Value
2022-06-03 08:38:06 +00:00
Entry Entry
Exit Exit
2022-05-09 21:11:22 +00:00
2022-06-05 21:43:38 +00:00
activeMakerOrders * bbgo . ActiveOrderBook
2022-05-09 21:11:22 +00:00
orderStore * bbgo . OrderStore
tradeCollector * bbgo . TradeCollector
session * bbgo . ExchangeSession
2022-06-05 04:56:40 +00:00
pivot * indicator . Pivot
pivotLowPrices [ ] fixedpoint . Value
2022-05-12 11:27:57 +00:00
// StrategyController
bbgo . StrategyController
2022-05-09 21:11:22 +00:00
}
func ( s * Strategy ) ID ( ) string {
return ID
}
func ( s * Strategy ) Subscribe ( session * bbgo . ExchangeSession ) {
log . Infof ( "subscribe %s" , s . Symbol )
2022-05-19 01:48:36 +00:00
session . Subscribe ( types . KLineChannel , s . Symbol , types . SubscribeOptions { Interval : s . Interval } )
2022-06-04 17:09:31 +00:00
// session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1d})
2022-05-09 21:11:22 +00:00
}
2022-06-05 04:47:15 +00:00
func ( s * Strategy ) placeMarketSell ( ctx context . Context , orderExecutor bbgo . OrderExecutor ) {
quantity := s . Entry . Quantity
if quantity . IsZero ( ) {
if balance , ok := s . session . Account . Balance ( s . Market . BaseCurrency ) ; ok {
2022-06-05 04:58:12 +00:00
s . Notify ( "sell quantity is not set, submitting sell with all base balance: %s" , balance . Available . String ( ) )
2022-06-05 04:47:15 +00:00
quantity = balance . Available
}
}
2022-06-05 04:58:12 +00:00
if quantity . IsZero ( ) {
log . Errorf ( "quantity is zero, can not submit sell order, please check settings" )
return
}
2022-06-05 04:47:15 +00:00
sideEffect := s . Entry . MarginSideEffect
if len ( sideEffect ) == 0 {
sideEffect = types . SideEffectTypeMarginBuy
}
submitOrder := types . SubmitOrder {
Symbol : s . Symbol ,
Side : types . SideTypeSell ,
Type : types . OrderTypeMarket ,
Quantity : quantity ,
MarginSideEffect : sideEffect ,
}
s . submitOrders ( ctx , orderExecutor , submitOrder )
}
2022-06-03 18:17:58 +00:00
func ( s * Strategy ) placeOrder ( ctx context . Context , lastLow fixedpoint . Value , limitPrice fixedpoint . Value , currentPrice fixedpoint . Value , qty fixedpoint . Value , orderExecutor bbgo . OrderExecutor ) {
2022-05-11 12:55:11 +00:00
submitOrder := types . SubmitOrder {
Symbol : s . Symbol ,
Side : types . SideTypeSell ,
Type : types . OrderTypeLimit ,
2022-06-03 15:23:26 +00:00
Price : limitPrice ,
2022-05-11 12:55:11 +00:00
Quantity : qty ,
}
2022-06-03 18:17:58 +00:00
if ! lastLow . IsZero ( ) && s . Entry . Immediate && lastLow . Compare ( currentPrice ) <= 0 {
2022-06-03 15:23:26 +00:00
submitOrder . Type = types . OrderTypeMarket
}
2022-06-02 13:34:26 +00:00
if s . session . Margin {
2022-06-03 08:38:06 +00:00
submitOrder . MarginSideEffect = s . Entry . MarginSideEffect
2022-06-02 13:34:26 +00:00
}
2022-06-05 04:47:15 +00:00
s . submitOrders ( ctx , orderExecutor , submitOrder )
}
func ( s * Strategy ) submitOrders ( ctx context . Context , orderExecutor bbgo . OrderExecutor , submitOrders ... types . SubmitOrder ) {
createdOrders , err := orderExecutor . SubmitOrders ( ctx , submitOrders ... )
2022-05-11 12:55:11 +00:00
if err != nil {
log . WithError ( err ) . Errorf ( "can not place orders" )
}
2022-06-05 04:47:15 +00:00
2022-05-11 12:55:11 +00:00
s . orderStore . Add ( createdOrders ... )
s . activeMakerOrders . Add ( createdOrders ... )
2022-06-05 04:40:08 +00:00
s . tradeCollector . Process ( )
2022-05-11 12:55:11 +00:00
}
2022-05-09 21:11:22 +00:00
func ( s * Strategy ) ClosePosition ( ctx context . Context , percentage fixedpoint . Value ) error {
base := s . Position . GetBase ( )
if base . IsZero ( ) {
return fmt . Errorf ( "no opened %s position" , s . Position . Symbol )
}
// make it negative
quantity := base . Mul ( percentage ) . Abs ( )
side := types . SideTypeBuy
if base . Sign ( ) > 0 {
side = types . SideTypeSell
}
if quantity . Compare ( s . Market . MinQuantity ) < 0 {
return fmt . Errorf ( "order quantity %v is too small, less than %v" , quantity , s . Market . MinQuantity )
}
submitOrder := types . SubmitOrder {
Symbol : s . Symbol ,
Side : side ,
Type : types . OrderTypeMarket ,
2022-05-12 11:27:57 +00:00
Quantity : quantity ,
2022-05-09 21:11:22 +00:00
Market : s . Market ,
}
2022-06-02 13:42:05 +00:00
if s . session . Margin {
2022-06-03 08:38:06 +00:00
submitOrder . MarginSideEffect = s . Exit . MarginSideEffect
2022-06-02 13:42:05 +00:00
}
2022-05-09 21:11:22 +00:00
2022-06-04 17:09:31 +00:00
// s.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder)
2022-05-09 21:11:22 +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 ... )
2022-06-05 04:51:45 +00:00
s . tradeCollector . Process ( )
2022-05-09 21:11:22 +00:00
return err
}
2022-05-12 11:27:57 +00:00
func ( s * Strategy ) InstanceID ( ) string {
return fmt . Sprintf ( "%s:%s" , ID , s . Symbol )
}
2022-05-09 21:11:22 +00:00
2022-06-03 08:38:06 +00:00
// check if position can be close or not
func canClosePosition ( position * types . Position , signal fixedpoint . Value , price fixedpoint . Value ) bool {
return ! signal . IsZero ( ) && position . IsShort ( ) && ! position . IsDust ( price )
}
2022-06-05 05:04:48 +00:00
// findHigherPivotLow checks the pivot low prices and return the low that is higher than the current price
func ( s * Strategy ) findHigherPivotLow ( price fixedpoint . Value ) ( fixedpoint . Value , bool ) {
2022-06-05 04:56:40 +00:00
for l := len ( s . pivotLowPrices ) - 1 ; l > 0 ; l -- {
if s . pivotLowPrices [ l ] . Compare ( price ) > 0 {
2022-06-05 05:04:48 +00:00
return s . pivotLowPrices [ l ] , true
2022-06-03 08:38:06 +00:00
}
}
2022-06-05 05:04:48 +00:00
return price , false
2022-06-03 08:38:06 +00:00
}
2022-06-05 04:40:41 +00:00
func ( s * Strategy ) placeBounceSellOrders ( ctx context . Context , lastLow fixedpoint . Value , limitPrice fixedpoint . Value , currentPrice fixedpoint . Value , orderExecutor bbgo . OrderExecutor ) {
2022-06-03 18:17:58 +00:00
futuresMode := s . session . Futures || s . session . IsolatedFutures
2022-06-05 04:40:08 +00:00
numLayers := fixedpoint . NewFromInt ( int64 ( s . Entry . NumLayers ) )
d := s . Entry . CatBounceRatio . Div ( numLayers )
2022-06-03 18:17:58 +00:00
q := s . Entry . Quantity
if ! s . TotalQuantity . IsZero ( ) {
2022-06-05 04:40:08 +00:00
q = s . TotalQuantity . Div ( numLayers )
2022-06-03 18:17:58 +00:00
}
2022-06-05 04:40:08 +00:00
for i := 0 ; i < s . Entry . NumLayers ; i ++ {
2022-06-03 18:17:58 +00:00
balances := s . session . GetAccount ( ) . Balances ( )
quoteBalance , _ := balances [ s . Market . QuoteCurrency ]
baseBalance , _ := balances [ s . Market . BaseCurrency ]
p := limitPrice . Mul ( fixedpoint . One . Add ( s . Entry . CatBounceRatio . Sub ( fixedpoint . NewFromFloat ( d . Float64 ( ) * float64 ( i ) ) ) ) )
if futuresMode {
2022-06-04 17:09:31 +00:00
// log.Infof("futures mode on")
2022-06-03 18:17:58 +00:00
if q . Mul ( p ) . Compare ( quoteBalance . Available ) <= 0 {
s . placeOrder ( ctx , lastLow , p , currentPrice , q , orderExecutor )
}
} else if s . Environment . IsBackTesting ( ) {
2022-06-04 17:09:31 +00:00
// log.Infof("spot backtest mode on")
2022-06-03 18:17:58 +00:00
if q . Compare ( baseBalance . Available ) <= 0 {
s . placeOrder ( ctx , lastLow , p , currentPrice , q , orderExecutor )
}
} else {
2022-06-04 17:09:31 +00:00
// log.Infof("spot mode on")
2022-06-03 18:17:58 +00:00
if q . Compare ( baseBalance . Available ) <= 0 {
s . placeOrder ( ctx , lastLow , p , currentPrice , q , orderExecutor )
}
}
}
}
2022-05-09 21:11:22 +00:00
func ( s * Strategy ) Run ( ctx context . Context , orderExecutor bbgo . OrderExecutor , session * bbgo . ExchangeSession ) error {
// initial required information
s . session = session
2022-06-05 22:57:25 +00:00
s . activeMakerOrders = bbgo . NewActiveOrderBook ( s . Symbol )
2022-05-09 21:11:22 +00:00
s . activeMakerOrders . BindStream ( session . UserDataStream )
s . orderStore = bbgo . NewOrderStore ( s . Symbol )
s . orderStore . BindStream ( session . UserDataStream )
if s . Position == nil {
s . Position = types . NewPositionFromMarket ( s . Market )
}
2022-06-04 17:48:56 +00:00
if s . ProfitStats == nil {
s . ProfitStats = types . NewProfitStats ( s . Market )
}
2022-05-12 11:27:57 +00:00
instanceID := s . InstanceID ( )
// Always update the position fields
s . Position . Strategy = ID
s . Position . StrategyInstanceID = instanceID
2022-05-09 21:11:22 +00:00
s . tradeCollector = bbgo . NewTradeCollector ( s . Symbol , s . Position , s . orderStore )
2022-05-12 11:27:57 +00:00
s . tradeCollector . OnTrade ( func ( trade types . Trade , profit , netProfit fixedpoint . Value ) {
s . Notifiability . Notify ( trade )
s . ProfitStats . AddTrade ( trade )
if profit . Compare ( fixedpoint . Zero ) == 0 {
s . Environment . RecordPosition ( s . Position , trade , nil )
} else {
log . Infof ( "%s generated profit: %v" , s . Symbol , profit )
p := s . Position . NewProfit ( trade , profit , netProfit )
p . Strategy = ID
p . StrategyInstanceID = instanceID
s . Notify ( & p )
s . ProfitStats . AddProfit ( p )
s . Notify ( & s . ProfitStats )
s . Environment . RecordPosition ( s . Position , trade , & p )
}
} )
s . tradeCollector . OnPositionUpdate ( func ( position * types . Position ) {
log . Infof ( "position changed: %s" , s . Position )
s . Notify ( s . Position )
} )
2022-05-09 21:11:22 +00:00
s . tradeCollector . BindStream ( session . UserDataStream )
2022-05-11 12:55:11 +00:00
iw := types . IntervalWindow { Window : s . PivotLength , Interval : s . Interval }
2022-05-09 21:11:22 +00:00
st , _ := session . MarketDataStore ( s . Symbol )
2022-05-13 10:05:25 +00:00
s . pivot = & indicator . Pivot { IntervalWindow : iw }
2022-05-09 21:11:22 +00:00
s . pivot . Bind ( st )
2022-06-03 18:17:58 +00:00
s . LastLow = fixedpoint . Zero
2022-05-09 21:11:22 +00:00
session . UserDataStream . OnStart ( func ( ) {
2022-06-03 18:17:58 +00:00
if price , ok := session . LastPrice ( s . Symbol ) ; ok {
2022-06-05 05:04:48 +00:00
if limitPrice , ok := s . findHigherPivotLow ( price ) ; ok {
log . Infof ( "%s placing limit sell start from %f adds up to %f percent with %d layers of orders" , s . Symbol , limitPrice . Float64 ( ) , s . Entry . CatBounceRatio . Mul ( fixedpoint . NewFromInt ( 100 ) ) . Float64 ( ) , s . Entry . NumLayers )
s . placeBounceSellOrders ( ctx , s . LastLow , limitPrice , price , orderExecutor )
}
2022-06-03 18:17:58 +00:00
}
2022-05-09 21:11:22 +00:00
} )
2022-06-05 04:48:54 +00:00
session . MarketDataStream . OnKLine ( func ( kline types . KLine ) {
// TODO: handle stop loss here, faster than closed kline
2022-06-05 05:09:32 +00:00
_ , found := s . findHigherPivotLow ( kline . Close )
2022-06-05 05:14:07 +00:00
if ! found && s . Entry . Immediate && ( s . Position . IsClosed ( ) || s . Position . IsDust ( kline . Close ) ) {
2022-06-05 04:55:36 +00:00
s . Notify ( "price breaks the previous low, submitting market sell to open a short position" )
s . placeMarketSell ( ctx , orderExecutor )
}
2022-06-05 04:48:54 +00:00
} )
2022-05-09 21:11:22 +00:00
session . MarketDataStream . OnKLineClosed ( func ( kline types . KLine ) {
if kline . Symbol != s . Symbol || kline . Interval != s . Interval {
return
}
2022-06-02 13:34:26 +00:00
2022-05-09 21:11:22 +00:00
if s . pivot . LastLow ( ) > 0. {
2022-06-03 08:38:06 +00:00
log . Infof ( "pivot low signal detected: %f %s" , s . pivot . LastLow ( ) , kline . EndTime . Time ( ) )
2022-06-03 18:17:58 +00:00
s . LastLow = fixedpoint . NewFromFloat ( s . pivot . LastLow ( ) )
2022-05-09 21:11:22 +00:00
} else {
2022-06-03 18:17:58 +00:00
if canClosePosition ( s . Position , s . LastLow , kline . Close ) {
2022-05-11 12:55:11 +00:00
R := kline . Close . Div ( s . Position . AverageCost )
2022-06-03 08:38:06 +00:00
if R . Compare ( fixedpoint . One . Add ( s . Exit . StopLossPercentage ) ) > 0 {
2022-05-11 12:55:11 +00:00
// SL
2022-06-05 04:51:45 +00:00
s . Notify ( "%s SL triggered" , s . Symbol )
2022-05-11 12:55:11 +00:00
s . ClosePosition ( ctx , fixedpoint . One )
s . tradeCollector . Process ( )
2022-06-03 08:38:06 +00:00
} else if R . Compare ( fixedpoint . One . Sub ( s . Exit . TakeProfitPercentage ) ) < 0 {
2022-05-11 12:55:11 +00:00
// TP
2022-06-05 04:51:45 +00:00
s . Notify ( "%s TP triggered" , s . Symbol )
2022-05-11 12:55:11 +00:00
s . ClosePosition ( ctx , fixedpoint . One )
2022-06-03 08:38:06 +00:00
} else if kline . GetLowerShadowHeight ( ) . Div ( kline . Close ) . Compare ( s . Exit . ShadowTPRatio ) > 0 {
2022-05-11 12:55:11 +00:00
// shadow TP
2022-06-05 04:51:45 +00:00
s . Notify ( "%s shadow TP triggered" , s . Symbol )
2022-05-09 21:11:22 +00:00
s . ClosePosition ( ctx , fixedpoint . One )
}
}
2022-06-03 18:17:58 +00:00
s . LastLow = fixedpoint . Zero
2022-05-09 21:11:22 +00:00
}
2022-05-11 12:55:11 +00:00
2022-06-03 18:17:58 +00:00
if ! s . LastLow . IsZero ( ) {
2022-05-11 12:55:11 +00:00
2022-06-05 04:56:40 +00:00
s . pivotLowPrices = append ( s . pivotLowPrices , s . LastLow )
2022-06-02 13:34:26 +00:00
if err := s . activeMakerOrders . GracefulCancel ( ctx , s . session . Exchange ) ; err != nil {
log . WithError ( err ) . Errorf ( "graceful cancel order error" )
}
2022-06-05 05:04:48 +00:00
if limitPrice , ok := s . findHigherPivotLow ( kline . Close ) ; ok {
log . Infof ( "%s place limit sell start from %f adds up to %f percent with %d layers of orders" , s . Symbol , limitPrice . Float64 ( ) , s . Entry . CatBounceRatio . Mul ( fixedpoint . NewFromInt ( 100 ) ) . Float64 ( ) , s . Entry . NumLayers )
s . placeBounceSellOrders ( ctx , s . LastLow , limitPrice , kline . Close , orderExecutor )
}
2022-05-09 21:11:22 +00:00
}
} )
return nil
}