mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-21 22:43:52 +00:00
query market config with cache
This commit is contained in:
parent
180bfff558
commit
40c697275d
52
pkg/bbgo/cache.go
Normal file
52
pkg/bbgo/cache.go
Normal 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
|
||||
}
|
|
@ -2,10 +2,12 @@ package bbgo
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/pkg/errors"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"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) {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(markets) == 0 {
|
||||
return errors.Errorf("market config should not be empty")
|
||||
}
|
||||
|
||||
session.markets = markets
|
||||
session.Account = &types.Account{}
|
||||
session.Stream = session.Exchange.NewStream()
|
||||
|
|
Loading…
Reference in New Issue
Block a user