grid2: add stopLossPrice handler

This commit is contained in:
c9s 2022-12-04 18:01:58 +08:00
parent 5f0c45093c
commit 4f3a160bbf
2 changed files with 26 additions and 2 deletions

View File

@ -65,6 +65,7 @@ type Strategy struct {
BaseInvestment fixedpoint.Value `json:"baseInvestment"` BaseInvestment fixedpoint.Value `json:"baseInvestment"`
TriggerPrice fixedpoint.Value `json:"triggerPrice"` TriggerPrice fixedpoint.Value `json:"triggerPrice"`
StopLossPrice fixedpoint.Value `json:"stopLossPrice"` StopLossPrice fixedpoint.Value `json:"stopLossPrice"`
TakeProfitPrice fixedpoint.Value `json:"takeProfitPrice"` TakeProfitPrice fixedpoint.Value `json:"takeProfitPrice"`
@ -498,6 +499,25 @@ func (s *Strategy) newTriggerPriceHandler(ctx context.Context, session *bbgo.Exc
if err := s.openGrid(ctx, session); err != nil { if err := s.openGrid(ctx, session); err != nil {
s.logger.WithError(err).Errorf("failed to setup grid orders") s.logger.WithError(err).Errorf("failed to setup grid orders")
return
}
})
}
func (s *Strategy) newStopLossPriceHandler(ctx context.Context, session *bbgo.ExchangeSession) types.KLineCallback {
return types.KLineWith(s.Symbol, types.Interval1m, func(k types.KLine) {
if s.StopLossPrice.Compare(k.Low) < 0 {
return
}
if err := s.closeGrid(ctx); err != nil {
s.logger.WithError(err).Errorf("can not close grid")
return
}
if err := s.orderExecutor.ClosePosition(ctx, fixedpoint.One, "grid2:stopLoss"); err != nil {
s.logger.WithError(err).Errorf("can not close position")
return
} }
}) })
} }
@ -772,6 +792,10 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
session.MarketDataStream.OnKLineClosed(s.newTriggerPriceHandler(ctx, session)) session.MarketDataStream.OnKLineClosed(s.newTriggerPriceHandler(ctx, session))
} }
if !s.StopLossPrice.IsZero() {
session.MarketDataStream.OnKLineClosed(s.newStopLossPriceHandler(ctx, session))
}
session.UserDataStream.OnStart(func() { session.UserDataStream.OnStart(func() {
if !s.TriggerPrice.IsZero() { if !s.TriggerPrice.IsZero() {
return return