bbgo_origin/pkg/core/converter.go

86 lines
2.0 KiB
Go
Raw Normal View History

2024-08-08 09:00:45 +00:00
package core
2024-08-12 07:56:24 +00:00
import (
"errors"
"github.com/c9s/bbgo/pkg/types"
)
2024-08-08 09:00:45 +00:00
type Converter interface {
OrderConverter
TradeConverter
Initialize() error
2024-08-08 09:00:45 +00:00
}
// OrderConverter converts the order to another order
type OrderConverter interface {
ConvertOrder(order types.Order) (types.Order, error)
}
// TradeConverter converts the trade to another trade
type TradeConverter interface {
ConvertTrade(trade types.Trade) (types.Trade, error)
}
2024-08-08 09:18:17 +00:00
type OrderConvertFunc func(order types.Order) (types.Order, error)
type TradeConvertFunc func(trade types.Trade) (types.Trade, error)
type DynamicConverter struct {
orderConverter OrderConvertFunc
tradeConverter TradeConvertFunc
}
func NewDynamicConverter(orderConverter OrderConvertFunc, tradeConverter TradeConvertFunc) *DynamicConverter {
return &DynamicConverter{orderConverter: orderConverter, tradeConverter: tradeConverter}
}
func (c *DynamicConverter) Initialize() error {
return nil
}
2024-08-08 09:18:17 +00:00
func (c *DynamicConverter) ConvertOrder(order types.Order) (types.Order, error) {
return c.orderConverter(order)
}
func (c *DynamicConverter) ConvertTrade(trade types.Trade) (types.Trade, error) {
return c.tradeConverter(trade)
}
2024-08-08 09:00:45 +00:00
// SymbolConverter converts the symbol to another symbol
type SymbolConverter struct {
2024-08-08 09:18:17 +00:00
FromSymbol string `json:"from"`
ToSymbol string `json:"to"`
2024-08-08 09:00:45 +00:00
}
func NewSymbolConverter(fromSymbol, toSymbol string) *SymbolConverter {
2024-08-08 09:18:17 +00:00
return &SymbolConverter{FromSymbol: fromSymbol, ToSymbol: toSymbol}
2024-08-08 09:00:45 +00:00
}
func (c *SymbolConverter) Initialize() error {
2024-08-12 07:56:24 +00:00
if c.ToSymbol == "" {
return errors.New("toSymbol can not be empty")
}
if c.FromSymbol == "" {
return errors.New("fromSymbol can not be empty")
}
return nil
}
2024-08-08 09:00:45 +00:00
func (c *SymbolConverter) ConvertOrder(order types.Order) (types.Order, error) {
2024-08-08 09:18:17 +00:00
if order.Symbol == c.FromSymbol {
order.Symbol = c.ToSymbol
2024-08-08 09:00:45 +00:00
}
return order, nil
}
func (c *SymbolConverter) ConvertTrade(trade types.Trade) (types.Trade, error) {
2024-08-08 09:18:17 +00:00
if trade.Symbol == c.FromSymbol {
trade.Symbol = c.ToSymbol
2024-08-08 09:00:45 +00:00
}
return trade, nil
}