bbgo_origin/pkg/bbgo/config.go

711 lines
20 KiB
Go
Raw Normal View History

2020-10-26 13:45:02 +00:00
package bbgo
import (
2021-02-03 01:58:31 +00:00
"bytes"
2020-10-26 13:45:02 +00:00
"encoding/json"
2020-11-09 08:34:35 +00:00
"fmt"
"os"
2020-10-26 13:45:02 +00:00
"reflect"
2021-01-21 04:06:03 +00:00
"runtime"
2022-05-17 10:10:37 +00:00
"strings"
2020-10-26 13:45:02 +00:00
"github.com/pkg/errors"
"gopkg.in/yaml.v3"
2020-12-31 09:07:12 +00:00
"github.com/c9s/bbgo/pkg/datatype"
2022-06-29 10:51:22 +00:00
"github.com/c9s/bbgo/pkg/dynamic"
"github.com/c9s/bbgo/pkg/fixedpoint"
2021-02-20 17:01:39 +00:00
"github.com/c9s/bbgo/pkg/service"
2020-11-06 19:18:05 +00:00
"github.com/c9s/bbgo/pkg/types"
2020-10-26 13:45:02 +00:00
)
// DefaultFeeRate set the fee rate for most cases
// BINANCE uses 0.1% for both maker and taker
//
// for BNB holders, it's 0.075% for both maker and taker
//
// MAX uses 0.050% for maker and 0.15% for taker
var DefaultFeeRate = fixedpoint.NewFromFloat(0.075 * 0.01)
2020-10-26 13:45:02 +00:00
type PnLReporterConfig struct {
2020-12-31 09:07:12 +00:00
AverageCostBySymbols datatype.StringSlice `json:"averageCostBySymbols" yaml:"averageCostBySymbols"`
Of datatype.StringSlice `json:"of" yaml:"of"`
When datatype.StringSlice `json:"when" yaml:"when"`
2020-10-26 13:45:02 +00:00
}
2021-02-02 18:26:41 +00:00
// ExchangeStrategyMount wraps the SingleExchangeStrategy with the ExchangeSession name for mounting
2020-10-26 13:45:02 +00:00
type ExchangeStrategyMount struct {
2021-02-02 18:26:41 +00:00
// Mounts contains the ExchangeSession name to mount
Mounts []string `json:"mounts"`
2020-10-26 13:45:02 +00:00
// Strategy is the strategy we loaded from config
Strategy SingleExchangeStrategy `json:"strategy"`
}
func (m *ExchangeStrategyMount) Map() (map[string]interface{}, error) {
strategyID := m.Strategy.ID()
var params map[string]interface{}
out, err := json.Marshal(m.Strategy)
if err != nil {
return nil, err
}
if err := json.Unmarshal(out, &params); err != nil {
return nil, err
}
return map[string]interface{}{
"on": m.Mounts,
strategyID: params,
}, nil
2020-10-26 13:45:02 +00:00
}
2020-10-27 00:48:47 +00:00
type SlackNotification struct {
DefaultChannel string `json:"defaultChannel,omitempty" yaml:"defaultChannel,omitempty"`
ErrorChannel string `json:"errorChannel,omitempty" yaml:"errorChannel,omitempty"`
QueueSize int `json:"queueSize,omitempty" yaml:"queueSize,omitempty"`
EnableInteraction bool `json:"enableInteraction,omitempty" yaml:"enableInteraction,omitempty"`
2020-10-27 00:48:47 +00:00
}
2021-02-21 08:52:47 +00:00
type SlackNotificationRouting struct {
Trade string `json:"trade,omitempty" yaml:"trade,omitempty"`
Order string `json:"order,omitempty" yaml:"order,omitempty"`
2020-10-27 00:48:47 +00:00
SubmitOrder string `json:"submitOrder,omitempty" yaml:"submitOrder,omitempty"`
PnL string `json:"pnL,omitempty" yaml:"pnL,omitempty"`
2020-10-27 00:48:47 +00:00
}
2021-10-15 08:10:09 +00:00
type TelegramNotification struct {
Broadcast bool `json:"broadcast" yaml:"broadcast"`
}
2022-09-19 11:25:18 +00:00
type NotificationSwitches struct {
Trade bool `json:"trade" yaml:"trade"`
Position bool `json:"position" yaml:"position"`
OrderUpdate bool `json:"orderUpdate" yaml:"orderUpdate"`
SubmitOrder bool `json:"submitOrder" yaml:"submitOrder"`
}
2020-10-30 21:21:17 +00:00
type NotificationConfig struct {
2022-09-19 11:22:08 +00:00
Slack *SlackNotification `json:"slack,omitempty" yaml:"slack,omitempty"`
2021-10-15 08:10:09 +00:00
Telegram *TelegramNotification `json:"telegram,omitempty" yaml:"telegram,omitempty"`
2022-09-19 11:25:18 +00:00
Switches *NotificationSwitches `json:"switches" yaml:"switches"`
2020-10-27 00:48:47 +00:00
}
2023-02-22 07:18:48 +00:00
type LoggingConfig struct {
2023-09-26 08:45:00 +00:00
Trade bool `json:"trade,omitempty"`
Order bool `json:"order,omitempty"`
2023-10-02 09:35:10 +00:00
Balance bool `json:"balance,omitempty"`
2023-09-26 08:45:00 +00:00
FilledOrderOnly bool `json:"filledOrder,omitempty"`
Fields map[string]interface{} `json:"fields,omitempty"`
2023-02-22 07:18:48 +00:00
}
2020-10-26 13:45:02 +00:00
type Session struct {
Name string `json:"name,omitempty" yaml:"name,omitempty"`
ExchangeName string `json:"exchange" yaml:"exchange"`
EnvVarPrefix string `json:"envVarPrefix" yaml:"envVarPrefix"`
2021-02-02 18:26:41 +00:00
Key string `json:"key,omitempty" yaml:"key,omitempty"`
Secret string `json:"secret,omitempty" yaml:"secret,omitempty"`
2021-01-09 03:27:14 +00:00
PublicOnly bool `json:"publicOnly,omitempty" yaml:"publicOnly"`
Margin bool `json:"margin,omitempty" yaml:"margin,omitempty"`
2021-01-09 03:27:14 +00:00
IsolatedMargin bool `json:"isolatedMargin,omitempty" yaml:"isolatedMargin,omitempty"`
2021-01-09 03:12:48 +00:00
IsolatedMarginSymbol string `json:"isolatedMarginSymbol,omitempty" yaml:"isolatedMarginSymbol,omitempty"`
2020-10-26 13:45:02 +00:00
}
2022-09-01 11:17:41 +00:00
//go:generate go run github.com/dmarkham/enumer -type=BacktestFeeMode -transform=snake -trimprefix BacktestFeeMode -yaml -json
type BacktestFeeMode int
2022-09-01 05:18:09 +00:00
const (
// BackTestFeeModeQuoteFee is designed for clean position but which also counts the fee in the quote balance.
// buy order = quote currency fee
// sell order = quote currency fee
2022-09-01 11:17:41 +00:00
BacktestFeeModeQuote BacktestFeeMode = iota // quote
2022-09-01 05:18:09 +00:00
// BackTestFeeModeNativeFee is the default crypto exchange fee mode.
// buy order = base currency fee
// sell order = quote currency fee
2022-09-01 11:17:41 +00:00
BacktestFeeModeNative // BackTestFeeMode = "native"
2022-09-01 05:18:09 +00:00
// BackTestFeeModeFeeToken is the mode which calculates fee from the outside of the balances.
// the fee will not be included in the balances nor the profit.
2022-09-01 11:17:41 +00:00
BacktestFeeModeToken // BackTestFeeMode = "token"
2022-09-01 05:18:09 +00:00
)
2022-09-01 11:17:41 +00:00
type Backtest struct {
StartTime types.LooseFormatTime `json:"startTime,omitempty" yaml:"startTime,omitempty"`
EndTime *types.LooseFormatTime `json:"endTime,omitempty" yaml:"endTime,omitempty"`
2020-11-10 11:06:20 +00:00
// RecordTrades is an option, if set to true, back-testing should record the trades into database
2022-05-10 10:27:23 +00:00
RecordTrades bool `json:"recordTrades,omitempty" yaml:"recordTrades,omitempty"`
2022-05-17 10:45:06 +00:00
// Deprecated:
// Account is deprecated, use Accounts instead
2022-05-17 10:45:06 +00:00
Account map[string]BacktestAccount `json:"account" yaml:"account"`
2022-09-01 11:17:41 +00:00
FeeMode BacktestFeeMode `json:"feeMode" yaml:"feeMode"`
2022-09-01 05:18:09 +00:00
2022-05-10 10:27:23 +00:00
Accounts map[string]BacktestAccount `json:"accounts" yaml:"accounts"`
Symbols []string `json:"symbols" yaml:"symbols"`
Sessions []string `json:"sessions" yaml:"sessions"`
// sync 1 second interval KLines
SyncSecKLines bool `json:"syncSecKLines,omitempty" yaml:"syncSecKLines,omitempty"`
2022-05-10 10:27:23 +00:00
}
2022-09-01 11:17:41 +00:00
func (b *Backtest) GetAccount(n string) BacktestAccount {
2022-05-10 10:27:23 +00:00
accountConfig, ok := b.Accounts[n]
if ok {
return accountConfig
}
2022-05-17 10:45:06 +00:00
accountConfig, ok = b.Account[n]
if ok {
return accountConfig
}
return DefaultBacktestAccount
2020-11-10 11:06:20 +00:00
}
type BacktestAccount struct {
MakerFeeRate fixedpoint.Value `json:"makerFeeRate,omitempty" yaml:"makerFeeRate,omitempty"`
TakerFeeRate fixedpoint.Value `json:"takerFeeRate,omitempty" yaml:"takerFeeRate,omitempty"`
Balances BacktestAccountBalanceMap `json:"balances" yaml:"balances"`
}
2022-05-17 10:45:06 +00:00
var DefaultBacktestAccount = BacktestAccount{
MakerFeeRate: fixedpoint.MustNewFromString("0.050%"),
TakerFeeRate: fixedpoint.MustNewFromString("0.075%"),
Balances: BacktestAccountBalanceMap{
"USDT": fixedpoint.NewFromFloat(10000),
},
}
type BA BacktestAccount
2021-12-05 04:23:27 +00:00
func (b *BacktestAccount) UnmarshalYAML(value *yaml.Node) error {
bb := &BA{MakerFeeRate: DefaultFeeRate, TakerFeeRate: DefaultFeeRate}
if err := value.Decode(bb); err != nil {
return err
}
*b = BacktestAccount(*bb)
return nil
}
func (b *BacktestAccount) UnmarshalJSON(input []byte) error {
bb := &BA{MakerFeeRate: DefaultFeeRate, TakerFeeRate: DefaultFeeRate}
if err := json.Unmarshal(input, bb); err != nil {
return err
}
*b = BacktestAccount(*bb)
return nil
}
type BacktestAccountBalanceMap map[string]fixedpoint.Value
2020-11-06 19:18:05 +00:00
func (m BacktestAccountBalanceMap) BalanceMap() types.BalanceMap {
balances := make(types.BalanceMap)
for currency, value := range m {
balances[currency] = types.Balance{
Currency: currency,
2020-11-10 06:19:33 +00:00
Available: value,
Locked: fixedpoint.Zero,
2020-11-06 19:18:05 +00:00
}
}
return balances
}
2020-12-06 10:58:05 +00:00
type PersistenceConfig struct {
2021-02-20 17:01:39 +00:00
Redis *service.RedisPersistenceConfig `json:"redis,omitempty" yaml:"redis,omitempty"`
Json *service.JsonPersistenceConfig `json:"json,omitempty" yaml:"json,omitempty"`
2020-12-06 10:58:05 +00:00
}
2021-01-21 04:06:03 +00:00
type BuildTargetConfig struct {
Name string `json:"name" yaml:"name"`
Arch string `json:"arch" yaml:"arch"`
OS string `json:"os" yaml:"os"`
2021-02-03 01:34:53 +00:00
LDFlags datatype.StringSlice `json:"ldflags,omitempty" yaml:"ldflags,omitempty"`
GCFlags datatype.StringSlice `json:"gcflags,omitempty" yaml:"gcflags,omitempty"`
Imports []string `json:"imports,omitempty" yaml:"imports,omitempty"`
2021-01-21 04:06:03 +00:00
}
type BuildConfig struct {
2021-02-03 01:34:53 +00:00
BuildDir string `json:"buildDir,omitempty" yaml:"buildDir,omitempty"`
Imports []string `json:"imports,omitempty" yaml:"imports,omitempty"`
Targets []BuildTargetConfig `json:"targets,omitempty" yaml:"targets,omitempty"`
2021-01-21 04:06:03 +00:00
}
func GetNativeBuildTargetConfig() BuildTargetConfig {
return BuildTargetConfig{
Name: "bbgow",
Arch: runtime.GOARCH,
2021-01-22 17:03:56 +00:00
OS: runtime.GOOS,
2021-01-21 04:06:03 +00:00
}
}
type SyncSymbol struct {
Symbol string `json:"symbol" yaml:"symbol"`
Session string `json:"session" yaml:"session"`
}
func (ss *SyncSymbol) UnmarshalYAML(unmarshal func(a interface{}) error) (err error) {
var s string
if err = unmarshal(&s); err == nil {
aa := strings.SplitN(s, ":", 2)
if len(aa) > 1 {
ss.Session = aa[0]
ss.Symbol = aa[1]
} else {
ss.Symbol = aa[0]
}
return nil
}
type localSyncSymbol SyncSymbol
var ssNew localSyncSymbol
if err = unmarshal(&ssNew); err == nil {
*ss = SyncSymbol(ssNew)
return nil
}
return err
}
func categorizeSyncSymbol(slice []SyncSymbol) (map[string][]string, []string) {
var rest []string
var m = make(map[string][]string)
for _, ss := range slice {
if len(ss.Session) > 0 {
m[ss.Session] = append(m[ss.Session], ss.Symbol)
} else {
rest = append(rest, ss.Symbol)
}
}
return m, rest
}
2022-01-24 16:06:25 +00:00
type SyncConfig struct {
// Sessions to sync, if ignored, all defined sessions will sync
Sessions []string `json:"sessions,omitempty" yaml:"sessions,omitempty"`
2022-06-14 05:32:13 +00:00
// Symbols is the list of session:symbol pair to sync, if ignored, symbols wlll be discovered by your existing crypto balances
// Valid formats are: {session}:{symbol}, {symbol} or in YAML object form {symbol: "BTCUSDT", session:"max" }
Symbols []SyncSymbol `json:"symbols,omitempty" yaml:"symbols,omitempty"`
2022-01-24 16:06:25 +00:00
2022-06-01 07:51:45 +00:00
// DepositHistory is for syncing deposit history
2022-04-25 09:18:42 +00:00
DepositHistory bool `json:"depositHistory" yaml:"depositHistory"`
2022-06-01 07:51:45 +00:00
// WithdrawHistory is for syncing withdraw history
2022-04-25 09:18:42 +00:00
WithdrawHistory bool `json:"withdrawHistory" yaml:"withdrawHistory"`
2022-06-01 07:51:45 +00:00
// RewardHistory is for syncing reward history
2022-04-25 09:18:42 +00:00
RewardHistory bool `json:"rewardHistory" yaml:"rewardHistory"`
2022-06-01 07:51:45 +00:00
// MarginHistory is for syncing margin related history: loans, repays, interests and liquidations
MarginHistory bool `json:"marginHistory" yaml:"marginHistory"`
MarginAssets []string `json:"marginAssets" yaml:"marginAssets"`
2022-01-24 16:06:25 +00:00
// Since is the date where you want to start syncing data
Since *types.LooseFormatTime `json:"since,omitempty"`
2022-01-27 01:34:04 +00:00
// UserDataStream is for real-time sync with websocket user data stream
UserDataStream *struct {
2022-01-27 01:34:04 +00:00
Trades bool `json:"trades,omitempty" yaml:"trades,omitempty"`
FilledOrders bool `json:"filledOrders,omitempty" yaml:"filledOrders,omitempty"`
} `json:"userDataStream,omitempty" yaml:"userDataStream,omitempty"`
2022-01-24 16:06:25 +00:00
}
type GoogleSpreadSheetServiceConfig struct {
JsonTokenFile string `json:"jsonTokenFile" yaml:"jsonTokenFile"`
SpreadSheetID string `json:"spreadSheetId" yaml:"spreadSheetId"`
}
type ServiceConfig struct {
GoogleSpreadSheetService *GoogleSpreadSheetServiceConfig `json:"googleSpreadSheet" yaml:"googleSpreadSheet"`
}
2024-01-24 07:18:31 +00:00
type DatabaseConfig struct {
2024-01-26 08:39:05 +00:00
Driver string `json:"driver" yaml:"driver"`
DSN string `json:"dsn" yaml:"dsn"`
2024-01-24 07:18:31 +00:00
2024-01-26 08:39:05 +00:00
ExtraMigrationPackages []string `json:"extraMigrationPackages" yaml:"extraMigrationPackages"`
2024-01-24 07:18:31 +00:00
}
type EnvironmentConfig struct {
DisableDefaultKLineSubscription bool `json:"disableDefaultKLineSubscription"`
DisableHistoryKLinePreload bool `json:"disableHistoryKLinePreload"`
// DisableStartUpBalanceQuery disables the balance query in the startup process
// which initializes the session.Account with the QueryAccount method.
DisableStartupBalanceQuery bool `json:"disableStartupBalanceQuery"`
DisableSessionTradeBuffer bool `json:"disableSessionTradeBuffer"`
2023-12-26 02:53:18 +00:00
DisableMarketDataStore bool `json:"disableMarketDataStore"`
MaxSessionTradeBufferSize int `json:"maxSessionTradeBufferSize"`
2024-06-19 06:18:21 +00:00
SyncBufferPeriod *types.Duration `json:"syncBufferPeriod"`
}
2020-10-26 13:45:02 +00:00
type Config struct {
2021-02-02 18:26:41 +00:00
Build *BuildConfig `json:"build,omitempty" yaml:"build,omitempty"`
2021-01-21 04:06:03 +00:00
// Imports is deprecated
// Deprecated: use BuildConfig instead
2021-02-02 18:26:41 +00:00
Imports []string `json:"imports,omitempty" yaml:"imports,omitempty"`
2020-10-26 13:45:02 +00:00
2022-09-01 11:17:41 +00:00
Backtest *Backtest `json:"backtest,omitempty" yaml:"backtest,omitempty"`
2022-01-24 16:06:25 +00:00
Sync *SyncConfig `json:"sync,omitempty" yaml:"sync,omitempty"`
2020-10-30 21:21:17 +00:00
Notifications *NotificationConfig `json:"notifications,omitempty" yaml:"notifications,omitempty"`
2020-10-27 00:48:47 +00:00
2020-12-06 10:58:05 +00:00
Persistence *PersistenceConfig `json:"persistence,omitempty" yaml:"persistence,omitempty"`
Service *ServiceConfig `json:"services,omitempty" yaml:"services,omitempty"`
2024-01-24 07:18:31 +00:00
DatabaseConfig *DatabaseConfig `json:"database,omitempty" yaml:"database,omitempty"`
Environment *EnvironmentConfig `json:"environment,omitempty" yaml:"environment,omitempty"`
2021-02-02 09:26:35 +00:00
Sessions map[string]*ExchangeSession `json:"sessions,omitempty" yaml:"sessions,omitempty"`
2020-10-26 13:45:02 +00:00
RiskControls *RiskControls `json:"riskControls,omitempty" yaml:"riskControls,omitempty"`
2023-02-22 07:18:48 +00:00
Logging *LoggingConfig `json:"logging,omitempty"`
2021-02-03 01:08:05 +00:00
ExchangeStrategies []ExchangeStrategyMount `json:"-" yaml:"-"`
CrossExchangeStrategies []CrossExchangeStrategy `json:"-" yaml:"-"`
2020-10-26 13:45:02 +00:00
PnLReporters []PnLReporterConfig `json:"reportPnL,omitempty" yaml:"reportPnL,omitempty"`
}
2021-02-03 01:08:05 +00:00
func (c *Config) Map() (map[string]interface{}, error) {
text, err := json.Marshal(c)
if err != nil {
return nil, err
}
var data map[string]interface{}
err = json.Unmarshal(text, &data)
if err != nil {
return nil, err
}
// convert strategy config back to the DSL format
2021-02-03 01:34:53 +00:00
var exchangeStrategies []map[string]interface{}
for _, m := range c.ExchangeStrategies {
params, err := m.Map()
2021-02-03 01:34:53 +00:00
if err != nil {
return nil, err
}
exchangeStrategies = append(exchangeStrategies, params)
2021-02-03 01:08:05 +00:00
}
2021-02-03 01:58:31 +00:00
if len(exchangeStrategies) > 0 {
data["exchangeStrategies"] = exchangeStrategies
}
var crossExchangeStrategies []map[string]interface{}
for _, st := range c.CrossExchangeStrategies {
strategyID := st.ID()
var params Stash
out, err := json.Marshal(st)
if err != nil {
return nil, err
}
if err := json.Unmarshal(out, &params); err != nil {
return nil, err
}
crossExchangeStrategies = append(crossExchangeStrategies, map[string]interface{}{
strategyID: params,
})
}
if len(crossExchangeStrategies) > 0 {
data["crossExchangeStrategies"] = crossExchangeStrategies
}
2021-02-03 01:08:05 +00:00
return data, err
}
2021-02-03 01:58:31 +00:00
func (c *Config) YAML() ([]byte, error) {
m, err := c.Map()
if err != nil {
return nil, err
}
var buf bytes.Buffer
var enc = yaml.NewEncoder(&buf)
enc.SetIndent(2)
err = enc.Encode(m)
return buf.Bytes(), err
}
2022-05-17 10:10:37 +00:00
func (c *Config) GetSignature() string {
var s string
var ps []string
// for single exchange strategy
if len(c.ExchangeStrategies) == 1 && len(c.CrossExchangeStrategies) == 0 {
mount := c.ExchangeStrategies[0].Mounts[0]
ps = append(ps, mount)
strategy := c.ExchangeStrategies[0].Strategy
id := strategy.ID()
ps = append(ps, id)
2022-06-29 10:51:22 +00:00
if symbol, ok := dynamic.LookupSymbolField(reflect.ValueOf(strategy)); ok {
2022-05-17 10:10:37 +00:00
ps = append(ps, symbol)
}
}
startTime := c.Backtest.StartTime.Time()
ps = append(ps, startTime.Format("2006-01-02"))
if c.Backtest.EndTime != nil {
endTime := c.Backtest.EndTime.Time()
ps = append(ps, endTime.Format("2006-01-02"))
}
s = strings.Join(ps, "_")
return s
}
2020-10-26 13:45:02 +00:00
type Stash map[string]interface{}
func loadStash(config []byte) (Stash, error) {
stash := make(Stash)
if err := yaml.Unmarshal(config, stash); err != nil {
return nil, err
}
return stash, nil
}
2020-12-06 03:40:22 +00:00
func LoadBuildConfig(configFile string) (*Config, error) {
2020-11-15 05:23:26 +00:00
var config Config
content, err := os.ReadFile(configFile)
2020-11-15 05:23:26 +00:00
if err != nil {
return nil, err
}
if err := yaml.Unmarshal(content, &config); err != nil {
return nil, err
}
2021-01-21 04:06:03 +00:00
// for backward compatible
if config.Build == nil {
if len(config.Imports) > 0 {
config.Build = &BuildConfig{
BuildDir: "build",
Imports: config.Imports,
Targets: []BuildTargetConfig{
{Name: "bbgow-amd64-darwin", Arch: "amd64", OS: "darwin"},
{Name: "bbgow-amd64-linux", Arch: "amd64", OS: "linux"},
},
}
2021-01-21 04:06:03 +00:00
}
}
2020-11-15 05:23:26 +00:00
return &config, nil
}
2021-01-22 16:50:23 +00:00
// Load parses the config
2020-12-29 08:00:03 +00:00
func Load(configFile string, loadStrategies bool) (*Config, error) {
2020-10-26 13:45:02 +00:00
var config Config
content, err := os.ReadFile(configFile)
2020-10-26 13:45:02 +00:00
if err != nil {
return nil, err
}
if err := yaml.Unmarshal(content, &config); err != nil {
return nil, err
}
2021-01-22 17:03:56 +00:00
// for backward compatible
if config.Build == nil {
2021-01-22 17:06:56 +00:00
config.Build = &BuildConfig{
BuildDir: "build",
Imports: config.Imports,
Targets: []BuildTargetConfig{
{Name: "bbgow-amd64-darwin", Arch: "amd64", OS: "darwin"},
{Name: "bbgow-amd64-linux", Arch: "amd64", OS: "linux"},
},
2021-01-22 17:03:56 +00:00
}
}
2020-10-26 13:45:02 +00:00
stash, err := loadStash(content)
if err != nil {
return nil, err
}
2020-12-29 08:00:03 +00:00
if loadStrategies {
if err := loadExchangeStrategies(&config, stash); err != nil {
return nil, err
}
2020-10-26 13:45:02 +00:00
2020-12-29 08:00:03 +00:00
if err := loadCrossExchangeStrategies(&config, stash); err != nil {
return nil, err
}
2020-10-26 13:45:02 +00:00
}
return &config, nil
}
func loadCrossExchangeStrategies(config *Config, stash Stash) (err error) {
exchangeStrategiesConf, ok := stash["crossExchangeStrategies"]
if !ok {
return nil
}
if len(LoadedCrossExchangeStrategies) == 0 {
return errors.New("no cross exchange strategy is registered")
}
configList, ok := exchangeStrategiesConf.([]interface{})
if !ok {
return errors.New("expecting list in crossExchangeStrategies")
}
for _, entry := range configList {
configStash, ok := entry.(Stash)
if !ok {
2020-11-09 08:34:35 +00:00
return fmt.Errorf("strategy config should be a map, given: %T %+v", entry, entry)
2020-10-26 13:45:02 +00:00
}
for id, conf := range configStash {
// look up the real struct type
if st, ok := LoadedCrossExchangeStrategies[id]; ok {
2020-10-26 13:45:02 +00:00
val, err := reUnmarshal(conf, st)
if err != nil {
return err
}
config.CrossExchangeStrategies = append(config.CrossExchangeStrategies, val.(CrossExchangeStrategy))
}
}
}
return nil
}
2021-02-02 18:26:41 +00:00
func NewStrategyFromMap(id string, conf interface{}) (SingleExchangeStrategy, error) {
if st, ok := LoadedExchangeStrategies[id]; ok {
val, err := reUnmarshal(conf, st)
if err != nil {
return nil, err
}
return val.(SingleExchangeStrategy), nil
}
return nil, fmt.Errorf("strategy %s not found", id)
}
2020-10-26 13:45:02 +00:00
func loadExchangeStrategies(config *Config, stash Stash) (err error) {
exchangeStrategiesConf, ok := stash["exchangeStrategies"]
if !ok {
exchangeStrategiesConf, ok = stash["strategies"]
if !ok {
return nil
}
2020-10-26 13:45:02 +00:00
}
if len(LoadedExchangeStrategies) == 0 {
return errors.New("no exchange strategy is registered")
}
configList, ok := exchangeStrategiesConf.([]interface{})
if !ok {
return errors.New("expecting list in exchangeStrategies")
}
for _, entry := range configList {
configStash, ok := entry.(Stash)
if !ok {
2020-11-09 08:34:35 +00:00
return fmt.Errorf("strategy config should be a map, given: %T %+v", entry, entry)
2020-10-26 13:45:02 +00:00
}
var mounts []string
if val, ok := configStash["on"]; ok {
2021-02-03 01:58:31 +00:00
switch tv := val.(type) {
case []string:
mounts = append(mounts, tv...)
case string:
mounts = append(mounts, tv)
case []interface{}:
for _, f := range tv {
s, ok := f.(string)
if !ok {
return fmt.Errorf("%+v (%T) is not a string", f, f)
}
mounts = append(mounts, s)
}
default:
return fmt.Errorf("unexpected mount type: %T value: %+v", val, val)
2020-10-26 13:45:02 +00:00
}
}
for id, conf := range configStash {
2021-02-02 18:26:41 +00:00
2020-10-26 13:45:02 +00:00
// look up the real struct type
2021-02-02 18:26:41 +00:00
if _, ok := LoadedExchangeStrategies[id]; ok {
st, err := NewStrategyFromMap(id, conf)
2020-10-26 13:45:02 +00:00
if err != nil {
return err
}
config.ExchangeStrategies = append(config.ExchangeStrategies, ExchangeStrategyMount{
Mounts: mounts,
2021-02-02 18:26:41 +00:00
Strategy: st,
2020-10-26 13:45:02 +00:00
})
2021-12-13 23:15:18 +00:00
} else if id != "on" && id != "off" {
2022-01-24 16:06:25 +00:00
// Show error when we didn't find the Strategy
2021-12-13 23:15:18 +00:00
return fmt.Errorf("strategy %s in config not found", id)
2020-10-26 13:45:02 +00:00
}
}
}
return nil
}
func reUnmarshal(conf interface{}, tpe interface{}) (interface{}, error) {
// get the type "*Strategy"
rt := reflect.TypeOf(tpe)
// allocate new object from the given type
val := reflect.New(rt)
// now we have &(*Strategy) -> **Strategy
valRef := val.Interface()
plain, err := json.Marshal(conf)
if err != nil {
return nil, err
}
if err := json.Unmarshal(plain, valRef); err != nil {
return nil, errors.Wrapf(err, "json parsing error, given payload: %s", plain)
}
return val.Elem().Interface(), nil
}