bbgo_origin/pkg/bbgo/risk_controls.go

75 lines
2.0 KiB
Go
Raw Permalink Normal View History

package bbgo
import (
"context"
2020-11-10 06:19:33 +00:00
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/types"
)
2020-11-09 06:56:54 +00:00
type SymbolBasedRiskController struct {
BasicRiskController *BasicRiskController `json:"basic,omitempty" yaml:"basic,omitempty"`
}
2020-11-09 06:56:54 +00:00
type RiskControlOrderExecutor struct {
*ExchangeOrderExecutor
// Symbol => Executor config
2020-11-09 06:56:54 +00:00
BySymbol map[string]*SymbolBasedRiskController `json:"bySymbol,omitempty" yaml:"bySymbol,omitempty"`
}
2020-11-09 06:56:54 +00:00
func (e *RiskControlOrderExecutor) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (retOrders types.OrderSlice, err error) {
var symbolOrders = groupSubmitOrdersBySymbol(orders)
for symbol, orders := range symbolOrders {
2020-11-09 06:56:54 +00:00
if controller, ok := e.BySymbol[symbol]; ok && controller != nil {
2020-11-09 08:34:35 +00:00
var riskErrs []error
2020-11-10 06:19:33 +00:00
orders, riskErrs = controller.BasicRiskController.ProcessOrders(e.Session, orders...)
2020-11-09 08:34:35 +00:00
for _, riskErr := range riskErrs {
// use logger from ExchangeOrderExecutor
2020-11-10 06:19:33 +00:00
logrus.Warnf("RISK ERROR: %s", riskErr.Error())
2020-11-09 08:34:35 +00:00
}
2020-11-09 06:56:54 +00:00
}
formattedOrders, err := formatOrders(e.Session, orders)
2020-11-09 08:34:35 +00:00
if err != nil {
return retOrders, err
}
2020-11-09 07:02:12 +00:00
retOrders2, err := e.ExchangeOrderExecutor.SubmitOrders(ctx, formattedOrders...)
2020-11-09 06:56:54 +00:00
if err != nil {
return retOrders, err
}
2020-11-09 06:56:54 +00:00
retOrders = append(retOrders, retOrders2...)
}
2020-11-09 06:56:54 +00:00
return
}
type SessionBasedRiskControl struct {
2020-11-09 06:56:54 +00:00
OrderExecutor *RiskControlOrderExecutor `json:"orderExecutor,omitempty" yaml:"orderExecutor"`
}
func (control *SessionBasedRiskControl) SetBaseOrderExecutor(executor *ExchangeOrderExecutor) {
if control.OrderExecutor == nil {
return
}
control.OrderExecutor.ExchangeOrderExecutor = executor
2020-11-09 06:56:54 +00:00
}
2020-11-09 06:56:54 +00:00
func groupSubmitOrdersBySymbol(orders []types.SubmitOrder) map[string][]types.SubmitOrder {
var symbolOrders = make(map[string][]types.SubmitOrder, len(orders))
for _, order := range orders {
symbolOrders[order.Symbol] = append(symbolOrders[order.Symbol], order)
}
2020-11-09 06:56:54 +00:00
return symbolOrders
}
type RiskControls struct {
SessionBasedRiskControl map[string]*SessionBasedRiskControl `json:"sessionBased,omitempty" yaml:"sessionBased,omitempty"`
}