qbtrade/pkg/risk/riskcontrol/order_price_risk.go

36 lines
1.1 KiB
Go
Raw Normal View History

2024-06-27 14:42:38 +00:00
package riskcontrol
import (
"git.qtrade.icu/lychiyu/qbtrade/pkg/fixedpoint"
indicatorv2 "git.qtrade.icu/lychiyu/qbtrade/pkg/indicator/v2"
"git.qtrade.icu/lychiyu/qbtrade/pkg/types"
log "github.com/sirupsen/logrus"
)
type OrderPriceRiskControl struct {
referencePrice *indicatorv2.EWMAStream
lossThreshold fixedpoint.Value
}
func NewOrderPriceRiskControl(referencePrice *indicatorv2.EWMAStream, threshold fixedpoint.Value) *OrderPriceRiskControl {
return &OrderPriceRiskControl{
referencePrice: referencePrice,
lossThreshold: threshold,
}
}
func (r *OrderPriceRiskControl) IsSafe(side types.SideType, price fixedpoint.Value, quantity fixedpoint.Value) bool {
refPrice := fixedpoint.NewFromFloat(r.referencePrice.Last(0))
// calculate profit
var profit fixedpoint.Value
if side == types.SideTypeBuy {
profit = refPrice.Sub(price).Mul(quantity)
} else if side == types.SideTypeSell {
profit = price.Sub(refPrice).Mul(quantity)
} else {
log.Warnf("OrderPriceRiskControl: unsupported side type: %s", side)
return false
}
return profit.Compare(r.lossThreshold) > 0
}