exits/trailingstop: properly works on both long and short positions

This commit is contained in:
Andy Cheng 2022-08-11 13:36:31 +08:00
parent d31b812471
commit df0e527e1e

View File

@ -90,6 +90,7 @@ func (s *TrailingStop2) checkStopPrice(price fixedpoint.Value, position *types.P
return nil
}
if (position.IsLong() && s.Side == types.SideTypeSell) || (position.IsShort() && s.Side == types.SideTypeBuy) {
if !s.MinProfit.IsZero() {
// check if we have the minimal profit
roi := position.ROI(price)
@ -107,6 +108,7 @@ func (s *TrailingStop2) checkStopPrice(price fixedpoint.Value, position *types.P
s.activated = true
}
}
}
// update the latest high for the sell order, or the latest low for the buy order
if s.latestHigh.IsZero() {
@ -126,23 +128,22 @@ func (s *TrailingStop2) checkStopPrice(price fixedpoint.Value, position *types.P
switch s.Side {
case types.SideTypeBuy:
s.latestHigh = fixedpoint.Min(price, s.latestHigh)
if position.IsShort() {
change := price.Sub(s.latestHigh).Div(s.latestHigh)
if change.Compare(s.CallbackRate) >= 0 {
// submit order
return s.triggerStop(price)
}
}
case types.SideTypeSell:
s.latestHigh = fixedpoint.Max(price, s.latestHigh)
if position.IsLong() {
change := s.latestHigh.Sub(price).Div(price)
if change.Compare(s.CallbackRate) >= 0 {
// submit order
return s.triggerStop(price)
}
}
}
return nil
}