2022-06-28 17:58:15 +00:00
|
|
|
package bbgo
|
2022-06-26 08:31:48 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type LowerShadowTakeProfit struct {
|
2022-06-30 07:13:42 +00:00
|
|
|
// inherit from the strategy
|
|
|
|
types.IntervalWindow
|
2022-06-26 08:31:48 +00:00
|
|
|
|
2022-06-30 07:13:42 +00:00
|
|
|
// inherit from the strategy
|
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
|
|
|
|
Ratio fixedpoint.Value `json:"ratio"`
|
2022-06-28 17:58:15 +00:00
|
|
|
session *ExchangeSession
|
|
|
|
orderExecutor *GeneralOrderExecutor
|
2022-06-26 08:31:48 +00:00
|
|
|
}
|
|
|
|
|
2022-06-30 07:13:42 +00:00
|
|
|
func (s *LowerShadowTakeProfit) Subscribe(session *ExchangeSession) {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
|
|
|
|
}
|
|
|
|
|
2022-06-28 17:58:15 +00:00
|
|
|
func (s *LowerShadowTakeProfit) Bind(session *ExchangeSession, orderExecutor *GeneralOrderExecutor) {
|
2022-06-26 08:31:48 +00:00
|
|
|
s.session = session
|
|
|
|
s.orderExecutor = orderExecutor
|
|
|
|
|
2022-07-26 10:35:50 +00:00
|
|
|
stdIndicatorSet := session.StandardIndicatorSet(s.Symbol)
|
2022-06-30 09:42:23 +00:00
|
|
|
ewma := stdIndicatorSet.EWMA(s.IntervalWindow)
|
|
|
|
|
2022-06-26 08:31:48 +00:00
|
|
|
position := orderExecutor.Position()
|
2022-07-05 04:14:53 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, s.Interval, func(kline types.KLine) {
|
2022-06-26 08:31:48 +00:00
|
|
|
closePrice := kline.Close
|
2023-11-29 10:26:01 +00:00
|
|
|
if position.IsClosed() || position.IsDust(closePrice) || position.IsClosing() {
|
2022-06-26 08:31:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
roi := position.ROI(closePrice)
|
|
|
|
if roi.Sign() < 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Ratio.IsZero() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-06-30 09:42:23 +00:00
|
|
|
// skip close price higher than the ewma
|
2023-05-31 11:35:44 +00:00
|
|
|
if closePrice.Float64() > ewma.Last(0) {
|
2022-06-30 09:42:23 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-06-26 08:31:48 +00:00
|
|
|
if kline.GetLowerShadowHeight().Div(kline.Close).Compare(s.Ratio) > 0 {
|
2022-06-28 17:58:15 +00:00
|
|
|
Notify("%s TakeProfit triggered by shadow ratio %f, price = %f",
|
2022-06-26 08:31:48 +00:00
|
|
|
position.Symbol,
|
|
|
|
kline.GetLowerShadowRatio().Float64(),
|
|
|
|
kline.Close.Float64(),
|
|
|
|
kline)
|
|
|
|
|
|
|
|
_ = orderExecutor.ClosePosition(context.Background(), fixedpoint.One)
|
|
|
|
return
|
|
|
|
}
|
2022-07-05 04:14:53 +00:00
|
|
|
}))
|
2022-06-26 08:31:48 +00:00
|
|
|
}
|