You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.2 KiB
85 lines
2.2 KiB
package trading |
|
|
|
import ( |
|
"fmt" |
|
"sig-pub/api/pb" |
|
"sig-pub/pkg/indicator" |
|
"sig-pub/pkg/strategy" |
|
"sig-pub/pkg/types" |
|
"sig-pub/pkg/types/series" |
|
"sig-pub/pkg/zlog" |
|
) |
|
|
|
type IOffsetStrategyContext interface { |
|
strategy.ISigStrategyContext |
|
SetOffset(offset int16) |
|
} |
|
|
|
type StrategyContext struct { |
|
IOffsetStrategyContext |
|
|
|
indicatorContext *IndicatorContext |
|
indicatorsReg *indicator.IndicatorRegistry |
|
signal []pb.Side // 0.sell,1.buy |
|
signalTimes []int64 |
|
wins []bool |
|
} |
|
|
|
func NewStrategyContext(klineSeries *KlineSeries, indicatorsReg *indicator.IndicatorRegistry) *StrategyContext { |
|
return &StrategyContext{ |
|
indicatorContext: NewIndicatorContext(klineSeries), |
|
indicatorsReg: indicatorsReg, |
|
} |
|
} |
|
|
|
func (c *StrategyContext) SetOffset(offset int16) { |
|
c.indicatorContext.SetOffset(offset) |
|
} |
|
|
|
func (c *StrategyContext) Get(offset int16) (kline types.Kline) { |
|
return c.indicatorContext.Get(offset) |
|
} |
|
|
|
func (c *StrategyContext) Series(offset, count int16) (klines series.Klines) { |
|
return c.indicatorContext.Series(offset, count) |
|
} |
|
|
|
// Buy 发出多信号 |
|
func (c *StrategyContext) Buy() { |
|
zlog.Infof("signal buy: %d", c.Get(0).Ts) |
|
|
|
c.signal = append(c.signal, pb.Side_BUY) |
|
c.signalTimes = append(c.signalTimes, c.Get(0).Ts) |
|
win := false |
|
signalPrice := c.Get(0).Close |
|
if c.indicatorContext.offset > 0 { |
|
c.indicatorContext.AddOffset(-1) |
|
win = c.Get(0).Close.Cmp(signalPrice) > 0 |
|
c.indicatorContext.AddOffset(1) |
|
} |
|
c.wins = append(c.wins, win) |
|
} |
|
|
|
// Sell 发出空信号 |
|
func (c *StrategyContext) Sell() { |
|
zlog.Infof("signal sell: %d", c.Get(0).Ts) |
|
c.signal = append(c.signal, pb.Side_SELL) |
|
c.signalTimes = append(c.signalTimes, c.Get(0).Ts) |
|
win := false |
|
signalPrice := c.Get(0).Close |
|
if c.indicatorContext.offset > 0 { |
|
c.indicatorContext.AddOffset(-1) |
|
win = c.Get(0).Close.Cmp(signalPrice) < 0 |
|
c.indicatorContext.AddOffset(1) |
|
} |
|
c.wins = append(c.wins, win) |
|
} |
|
|
|
// 获取窗口类型指标 |
|
func (c *StrategyContext) IndicatorW(name string, window int16) (s indicator.IIndicatorSeries) { |
|
indicator, ok := c.indicatorsReg.IndicatorW(name) |
|
if !ok { |
|
panic(fmt.Errorf("indicatorW %s not exists", name)) |
|
} |
|
return NewWindowIndicatorSeries(window, indicator, c.indicatorContext) |
|
}
|
|
|