Skip to content

Commit

Permalink
bind market data store and query avg price before we start
Browse files Browse the repository at this point in the history
  • Loading branch information
c9s committed Oct 12, 2020
1 parent bace7ac commit 6398f04
Show file tree
Hide file tree
Showing 12 changed files with 324 additions and 225 deletions.
84 changes: 84 additions & 0 deletions cmd/buyandhold/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package buyandhold

import (
"context"
"fmt"
"syscall"

"github.com/jmoiron/sqlx"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/c9s/bbgo/cmd/cmdutil"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/strategy/buyandhold"
"github.com/c9s/bbgo/pkg/types"
)

func init() {
rootCmd.Flags().String("exchange", "", "target exchange")
rootCmd.Flags().String("symbol", "", "trading symbol")
}

func connectMysql() (*sqlx.DB, error) {
mysqlURL := viper.GetString("mysql-url")
mysqlURL = fmt.Sprintf("%s?parseTime=true", mysqlURL)
return sqlx.Connect("mysql", mysqlURL)
}

var rootCmd = &cobra.Command{
Use: "buyandhold",
Short: "buy and hold",
Long: "hold trader",

// SilenceUsage is an option to silence usage when an error occurs.
SilenceUsage: true,

RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

exchangeNameStr, err := cmd.Flags().GetString("exchange")
if err != nil {
return err
}

exchangeName, err := types.ValidExchangeName(exchangeNameStr)
if err != nil {
return err
}

symbol, err := cmd.Flags().GetString("symbol")
if err != nil {
return err
}

exchange, err := cmdutil.NewExchange(exchangeName)
if err != nil {
return err
}

db, err := cmdutil.ConnectMySQL()
if err != nil {
return err
}

sessionID := "main"
environ := bbgo.NewEnvironment(db)
environ.AddExchange(sessionID, exchange).Subscribe(types.KLineChannel, symbol, types.SubscribeOptions{})

trader := bbgo.NewTrader(environ)
trader.AttachStrategy(sessionID, buyandhold.New(symbol))
trader.Run(ctx)

cmdutil.WaitForSignal(ctx, syscall.SIGINT, syscall.SIGTERM)
return nil
},
}

func main() {
if err := rootCmd.Execute(); err != nil {
log.WithError(err).Fatalf("cannot execute command")
}
}
14 changes: 14 additions & 0 deletions cmd/cmdutil/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package cmdutil

import (
"fmt"

"github.com/jmoiron/sqlx"
"github.com/spf13/viper"
)

func ConnectMySQL() (*sqlx.DB, error) {
mysqlURL := viper.GetString("mysql-url")
mysqlURL = fmt.Sprintf("%s?parseTime=true", mysqlURL)
return sqlx.Connect("mysql", mysqlURL)
}
36 changes: 36 additions & 0 deletions cmd/cmdutil/exchange.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package cmdutil

import (
"github.com/pkg/errors"
"github.com/spf13/viper"

"github.com/c9s/bbgo/pkg/exchange/binance"
"github.com/c9s/bbgo/pkg/exchange/max"
"github.com/c9s/bbgo/pkg/types"
)

func NewExchange(n types.ExchangeName) (types.Exchange, error) {
switch n {

case types.ExchangeBinance:
key := viper.GetString("binance-api-key")
secret := viper.GetString("binance-api-secret")
if len(key) == 0 || len(secret) == 0 {
return nil, errors.New("empty key or secret")
}

return binance.New(key, secret), nil

case types.ExchangeMax:
key := viper.GetString("max-api-key")
secret := viper.GetString("max-api-secret")
if len(key) == 0 || len(secret) == 0 {
return nil, errors.New("empty key or secret")
}

return max.New(key, secret), nil

}

return nil, nil
}
37 changes: 6 additions & 31 deletions cmd/pnl.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,15 @@ package cmd

import (
"context"
"fmt"
"strings"
"time"

"github.com/jmoiron/sqlx"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/c9s/bbgo/cmd/cmdutil"
"github.com/c9s/bbgo/pkg/accounting"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/exchange/binance"
"github.com/c9s/bbgo/pkg/exchange/max"
"github.com/c9s/bbgo/pkg/service"
"github.com/c9s/bbgo/pkg/types"
)
Expand All @@ -26,30 +22,6 @@ func init() {
RootCmd.AddCommand(pnlCmd)
}

func connectMysql() (*sqlx.DB, error) {
mysqlURL := viper.GetString("mysql-url")
mysqlURL = fmt.Sprintf("%s?parseTime=true", mysqlURL)
return sqlx.Connect("mysql", mysqlURL)
}

func newExchange(n types.ExchangeName) types.Exchange {
switch n {

case types.ExchangeBinance:
key := viper.GetString("binance-api-key")
secret := viper.GetString("binance-api-secret")
return binance.New(key, secret)

case types.ExchangeMax:
key := viper.GetString("max-api-key")
secret := viper.GetString("max-api-secret")
return max.New(key, secret)

}

return nil
}

var pnlCmd = &cobra.Command{
Use: "pnl",
Short: "pnl calculator",
Expand All @@ -72,9 +44,12 @@ var pnlCmd = &cobra.Command{
return err
}

exchange := newExchange(exchangeName)
exchange, err := cmdutil.NewExchange(exchangeName)
if err != nil {
return err
}

db, err := connectMysql()
db, err := cmdutil.ConnectMySQL()
if err != nil {
return err
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/transfers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"

"github.com/c9s/bbgo/cmd/cmdutil"
"github.com/c9s/bbgo/pkg/types"
)

Expand Down Expand Up @@ -83,7 +84,7 @@ var transferHistoryCmd = &cobra.Command{
}
}

exchange := newExchange(exchangeName)
exchange, _ := cmdutil.NewExchange(exchangeName)

var records timeSlice

Expand Down
24 changes: 15 additions & 9 deletions pkg/bbgo/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,37 @@ import (
)

type Account struct {
mu sync.Mutex
sync.Mutex

Balances map[string]types.Balance
}

// TODO: rewrite this as NewAccount(map balances)
func LoadAccount(ctx context.Context, exchange types.Exchange) (*Account, error) {
balances, err := exchange.QueryAccountBalances(ctx)
return &Account{
Balances: balances,
}, err
}

func (a *Account) BindPrivateStream(stream types.Stream) {
stream.OnBalanceSnapshot(func(snapshot map[string]types.Balance) {
a.mu.Lock()
defer a.mu.Unlock()
func (a *Account) handleBalanceUpdates(balances map[string]types.Balance) {
a.Lock()
defer a.Unlock()

for _, balance := range snapshot {
a.Balances[balance.Currency] = balance
}
})
for _, balance := range balances {
a.Balances[balance.Currency] = balance
}
}

func (a *Account) BindStream(stream types.Stream) {
stream.OnBalanceUpdate(a.handleBalanceUpdates)
stream.OnBalanceSnapshot(a.handleBalanceUpdates)
}

func (a *Account) Print() {
a.Lock()
defer a.Unlock()

for _, balance := range a.Balances {
if util.NotZero(balance.Available) {
log.Infof("[trader] balance %s %f", balance.Currency, balance.Available)
Expand Down
2 changes: 1 addition & 1 deletion pkg/bbgo/kline_regression.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (trader *BackTestTrader) SubmitOrder(cxt context.Context, order *types.Subm
trader.pendingOrders = append(trader.pendingOrders, order)
}

func (trader *BackTestTrader) RunStrategy(ctx context.Context, strategy MarketStrategy) (chan struct{}, error) {
func (trader *BackTestTrader) RunStrategy(ctx context.Context, strategy SingleExchangeStrategy) (chan struct{}, error) {
logrus.Infof("[regression] number of kline data: %d", len(trader.SourceKLines))

done := make(chan struct{})
Expand Down
6 changes: 3 additions & 3 deletions pkg/bbgo/order_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ package bbgo

import (
"context"
"fmt"
"math"

"github.com/pkg/errors"

"github.com/c9s/bbgo/pkg/types"
"github.com/c9s/bbgo/pkg/util"
)

var (
Expand Down Expand Up @@ -41,6 +38,7 @@ type OrderProcessor struct {
}

func (p *OrderProcessor) Submit(ctx context.Context, order *types.SubmitOrder) error {
/*
tradingCtx := p.Trader.Context
currentPrice := tradingCtx.CurrentPrice
market := order.Market
Expand Down Expand Up @@ -126,6 +124,8 @@ func (p *OrderProcessor) Submit(ctx context.Context, order *types.SubmitOrder) e
order.Quantity = quantity
order.QuantityString = market.FormatVolume(quantity)
*/

return p.Exchange.SubmitOrder(ctx, order)
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/bbgo/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func NewMarketDataStore() *MarketDataStore {
}
}

func (store *MarketDataStore) BindPrivateStream(stream types.Stream) {
func (store *MarketDataStore) BindStream(stream types.Stream) {
stream.OnKLineClosed(store.handleKLineClosed)
}

Expand Down
6 changes: 3 additions & 3 deletions pkg/bbgo/strategy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"fmt"
"os"
"testing"
time "time"
"time"

"github.com/DATA-DOG/go-sqlmock"
"github.com/jmoiron/sqlx"
Expand All @@ -14,7 +14,6 @@ import (
"github.com/c9s/bbgo/pkg/exchange/binance"
"github.com/c9s/bbgo/pkg/service"
"github.com/c9s/bbgo/pkg/types"

)

func TestTradeService(t *testing.T) {
Expand Down Expand Up @@ -59,10 +58,11 @@ func TestEnvironment_Connect(t *testing.T) {

environment := NewEnvironment(xdb)
environment.AddExchange("binance", exchange).
Subscribe(types.KLineChannel,"BTCUSDT", types.SubscribeOptions{ })
Subscribe(types.KLineChannel,"BTCUSDT", types.SubscribeOptions{})

err = environment.Connect(ctx)
assert.NoError(t, err)

time.Sleep(5 * time.Second)
}

Loading

0 comments on commit 6398f04

Please sign in to comment.