2022-06-28 17:58:15 +00:00
|
|
|
package bbgo
|
2022-06-26 08:13:58 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2022-09-14 05:09:58 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
2022-06-26 08:13:58 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
2022-06-28 17:58:15 +00:00
|
|
|
// RoiTakeProfit force takes the profit by the given ROI percentage.
|
2022-06-26 08:13:58 +00:00
|
|
|
type RoiTakeProfit struct {
|
2022-07-19 03:00:45 +00:00
|
|
|
Symbol string `json:"symbol"`
|
2022-06-26 08:13:58 +00:00
|
|
|
Percentage fixedpoint.Value `json:"percentage"`
|
|
|
|
|
2022-09-14 05:09:58 +00:00
|
|
|
// Partial is a percentage of the position to be closed
|
|
|
|
// 50% means you will close halt the position
|
|
|
|
Partial fixedpoint.Value `json:"partial,omitempty"`
|
|
|
|
|
2022-06-28 17:58:15 +00:00
|
|
|
session *ExchangeSession
|
|
|
|
orderExecutor *GeneralOrderExecutor
|
2022-06-26 08:13:58 +00:00
|
|
|
}
|
|
|
|
|
2022-07-19 03:00:45 +00:00
|
|
|
func (s *RoiTakeProfit) Subscribe(session *ExchangeSession) {
|
|
|
|
// use 1m kline to handle roi stop
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1m})
|
|
|
|
}
|
|
|
|
|
2022-06-28 17:58:15 +00:00
|
|
|
func (s *RoiTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor) {
|
2022-06-26 08:13:58 +00:00
|
|
|
s.session = session
|
|
|
|
s.orderExecutor = orderExecutor
|
|
|
|
|
|
|
|
position := orderExecutor.Position()
|
2022-08-10 15:45:21 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, types.Interval1m, func(kline types.KLine) {
|
2022-06-26 08:13:58 +00:00
|
|
|
closePrice := kline.Close
|
|
|
|
if position.IsClosed() || position.IsDust(closePrice) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
roi := position.ROI(closePrice)
|
2022-09-14 05:09:58 +00:00
|
|
|
if roi.Compare(s.Percentage) < 0 {
|
2022-06-26 08:13:58 +00:00
|
|
|
return
|
|
|
|
}
|
2022-09-14 05:09:58 +00:00
|
|
|
|
|
|
|
// default to close the whole position
|
|
|
|
percent := one
|
|
|
|
if !s.Partial.IsZero() {
|
|
|
|
percent = s.Partial
|
|
|
|
}
|
|
|
|
|
|
|
|
// stop loss
|
|
|
|
Notify("[RoiTakeProfit] %s take profit is triggered by ROI %s/%s, price: %f, closing: %s",
|
|
|
|
position.Symbol,
|
|
|
|
roi.Percentage(),
|
|
|
|
s.Percentage.Percentage(),
|
|
|
|
kline.Close.Float64(),
|
|
|
|
percent.Percentage())
|
|
|
|
|
|
|
|
if err := orderExecutor.ClosePosition(context.Background(), percent, "roiTakeProfit"); err != nil {
|
|
|
|
log.WithError(err).Error("failed to close position")
|
|
|
|
}
|
2022-08-10 15:45:21 +00:00
|
|
|
}))
|
2022-06-26 08:13:58 +00:00
|
|
|
}
|