query market config with cache

This commit is contained in:
c9s 2020-10-20 12:11:44 +08:00
parent 180bfff558
commit 40c697275d
2 changed files with 63 additions and 1 deletions

52
pkg/bbgo/cache.go Normal file
View File

@ -0,0 +1,52 @@
package bbgo
import (
"encoding/json"
"io/ioutil"
"os"
"path"
"reflect"
"github.com/pkg/errors"
)
func WithCache(file string, obj interface{}, do func() (interface{}, error)) error {
cacheDir := CacheDir()
cacheFile := path.Join(cacheDir, file)
if _, err := os.Stat(cacheFile); os.IsNotExist(err) {
data, err := do()
if err != nil {
return err
}
out, err := json.Marshal(data)
if err != nil {
return err
}
if err := ioutil.WriteFile(cacheFile, out, 0666); err != nil {
return err
}
rv := reflect.ValueOf(obj).Elem()
if !rv.CanSet() {
return errors.New("can not set cache object value")
}
rv.Set(reflect.ValueOf(data))
} else {
data, err := ioutil.ReadFile(cacheFile)
if err != nil {
return err
}
if err := json.Unmarshal(data, obj); err != nil {
return err
}
}
return nil
}

View File

@ -2,10 +2,12 @@ package bbgo
import ( import (
"context" "context"
"fmt"
"strings" "strings"
"time" "time"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -59,11 +61,19 @@ func (environ *Environment) AddExchange(name string, exchange types.Exchange) (s
func (environ *Environment) Init(ctx context.Context) (err error) { func (environ *Environment) Init(ctx context.Context) (err error) {
for _, session := range environ.sessions { for _, session := range environ.sessions {
markets, err := session.Exchange.QueryMarkets(ctx) var markets types.MarketMap
err = WithCache(fmt.Sprintf("%s-markets.json", session.Exchange.Name()), &markets, func() (interface{}, error) {
return session.Exchange.QueryMarkets(ctx)
})
if err != nil { if err != nil {
return err return err
} }
if len(markets) == 0 {
return errors.Errorf("market config should not be empty")
}
session.markets = markets session.markets = markets
session.Account = &types.Account{} session.Account = &types.Account{}
session.Stream = session.Exchange.NewStream() session.Stream = session.Exchange.NewStream()