bbgo_origin/pkg/bbgo/exit_roi_stop_loss.go

56 lines
1.5 KiB
Go
Raw Permalink Normal View History

package bbgo
import (
"context"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
type RoiStopLoss struct {
2022-07-01 07:30:06 +00:00
Symbol string
Percentage fixedpoint.Value `json:"percentage"`
session *ExchangeSession
orderExecutor *GeneralOrderExecutor
}
2022-07-01 07:30:06 +00:00
func (s *RoiStopLoss) Subscribe(session *ExchangeSession) {
// use 1m kline to handle roi stop
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1m})
}
func (s *RoiStopLoss) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor) {
s.session = session
s.orderExecutor = orderExecutor
position := orderExecutor.Position()
2022-07-01 07:30:06 +00:00
session.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, types.Interval1m, func(kline types.KLine) {
s.checkStopPrice(kline.Close, position)
2022-07-01 07:30:06 +00:00
}))
if !IsBackTesting {
session.MarketDataStream.OnMarketTrade(func(trade types.Trade) {
if trade.Symbol != position.Symbol {
return
}
s.checkStopPrice(trade.Price, position)
})
}
}
func (s *RoiStopLoss) checkStopPrice(closePrice fixedpoint.Value, position *types.Position) {
if position.IsClosed() || position.IsDust(closePrice) {
return
}
roi := position.ROI(closePrice)
if roi.Compare(s.Percentage.Neg()) < 0 {
// stop loss
Notify("[RoiStopLoss] %s stop loss triggered by ROI %s/%s, price: %f", position.Symbol, roi.Percentage(), s.Percentage.Neg().Percentage(), closePrice.Float64())
2022-06-27 10:17:57 +00:00
_ = s.orderExecutor.ClosePosition(context.Background(), fixedpoint.One, "roiStopLoss")
return
}
}