bbgo_origin/pkg/cmd/orders.go

371 lines
9.4 KiB
Go
Raw Normal View History

2021-03-07 04:47:11 +00:00
package cmd
import (
"context"
"fmt"
2021-03-19 02:06:42 +00:00
"os"
"os/signal"
"strings"
2021-05-14 03:53:07 +00:00
"syscall"
2021-03-23 14:25:21 +00:00
"time"
2021-03-07 04:47:11 +00:00
2021-03-13 01:51:31 +00:00
"github.com/google/uuid"
2021-05-14 03:53:07 +00:00
"github.com/pkg/errors"
2021-03-07 04:47:11 +00:00
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/c9s/bbgo/pkg/fixedpoint"
2021-03-19 02:06:42 +00:00
"github.com/c9s/bbgo/pkg/bbgo"
2021-03-13 01:51:31 +00:00
"github.com/c9s/bbgo/pkg/exchange/ftx"
2021-03-07 04:47:11 +00:00
"github.com/c9s/bbgo/pkg/types"
2021-03-13 01:51:31 +00:00
"github.com/c9s/bbgo/pkg/util"
2021-03-07 04:47:11 +00:00
)
2021-05-27 19:05:59 +00:00
// go run ./cmd/bbgo list-orders [open|closed] --session=ftx --symbol=BTCUSDT
2021-03-13 02:12:20 +00:00
var listOrdersCmd = &cobra.Command{
2021-05-27 19:05:59 +00:00
Use: "list-orders [status]",
2021-03-07 04:47:11 +00:00
Args: cobra.OnlyValidArgs,
// default is open which means we query open orders if you haven't provided args.
ValidArgs: []string{"", "open", "closed"},
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
2021-03-23 14:25:21 +00:00
configFile, err := cmd.Flags().GetString("config")
2021-03-07 04:47:11 +00:00
if err != nil {
2021-03-23 14:25:21 +00:00
return err
}
if len(configFile) == 0 {
return fmt.Errorf("--config option is required")
}
// if config file exists, use the config loaded from the config file.
// otherwise, use a empty config object
var userConfig *bbgo.Config
if _, err := os.Stat(configFile); err == nil {
// load successfully
userConfig, err = bbgo.Load(configFile, false)
if err != nil {
return err
}
} else if os.IsNotExist(err) {
// config file doesn't exist
userConfig = &bbgo.Config{}
} else {
// other error
return err
2021-03-07 04:47:11 +00:00
}
2021-03-23 14:25:21 +00:00
environ := bbgo.NewEnvironment()
if err := environ.ConfigureExchangeSessions(userConfig); err != nil {
return err
}
sessionName, err := cmd.Flags().GetString("session")
2021-03-07 04:47:11 +00:00
if err != nil {
return err
}
2021-03-23 14:25:21 +00:00
session, ok := environ.Session(sessionName)
if !ok {
return fmt.Errorf("session %s not found", sessionName)
}
2021-03-07 04:47:11 +00:00
symbol, err := cmd.Flags().GetString("symbol")
if err != nil {
return fmt.Errorf("can't get the symbol from flags: %w", err)
}
if symbol == "" {
return fmt.Errorf("symbol is not found")
}
status := "open"
if len(args) != 0 {
status = args[0]
}
var os []types.Order
switch status {
case "open":
2021-03-23 14:25:21 +00:00
os, err = session.Exchange.QueryOpenOrders(ctx, symbol)
2021-03-07 04:47:11 +00:00
if err != nil {
return err
}
case "closed":
tradeHistoryService, ok := session.Exchange.(types.ExchangeTradeHistoryService)
if !ok {
// skip exchanges that does not support trading history services
log.Warnf("exchange %s does not implement ExchangeTradeHistoryService, skip syncing closed orders (listOrdersCmd)", session.Exchange.Name())
return nil
}
os, err = tradeHistoryService.QueryClosedOrders(ctx, symbol, time.Now().Add(-3*24*time.Hour), time.Now(), 0)
2021-03-23 14:25:21 +00:00
if err != nil {
return err
}
2021-03-07 04:47:11 +00:00
default:
return fmt.Errorf("invalid status %s", status)
}
log.Infof("%s ORDERS FROM %s SESSION", strings.ToUpper(status), session.Name)
2021-03-13 01:51:31 +00:00
for _, o := range os {
log.Infof("%+v", o)
2021-03-13 01:51:31 +00:00
}
return nil
},
}
2021-05-14 03:53:07 +00:00
var executeOrderCmd = &cobra.Command{
Use: "execute-order",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
2021-05-14 03:53:07 +00:00
if userConfig == nil {
return errors.New("config file is required")
}
2021-05-14 03:53:07 +00:00
sessionName, err := cmd.Flags().GetString("session")
if err != nil {
return err
}
2021-05-14 03:53:07 +00:00
symbol, err := cmd.Flags().GetString("symbol")
if err != nil {
return fmt.Errorf("can not get the symbol from flags: %w", err)
}
2021-05-14 03:53:07 +00:00
if symbol == "" {
return fmt.Errorf("symbol not found")
}
2021-05-14 03:53:07 +00:00
sideS, err := cmd.Flags().GetString("side")
if err != nil {
return fmt.Errorf("can't get side: %w", err)
}
2021-03-19 02:06:42 +00:00
2021-05-14 03:53:07 +00:00
side, err := types.StrToSideType(sideS)
2021-03-13 01:51:31 +00:00
if err != nil {
2021-03-19 02:06:42 +00:00
return err
2021-03-13 01:51:31 +00:00
}
2021-03-19 02:06:42 +00:00
2021-05-14 03:53:07 +00:00
targetQuantityS, err := cmd.Flags().GetString("target-quantity")
if err != nil {
return err
2021-03-19 02:06:42 +00:00
}
if len(targetQuantityS) == 0 {
return errors.New("--target-quantity can not be empty")
}
2021-03-19 02:06:42 +00:00
2021-05-14 03:53:07 +00:00
targetQuantity, err := fixedpoint.NewFromString(targetQuantityS)
if err != nil {
2021-03-19 02:06:42 +00:00
return err
}
2021-05-14 03:53:07 +00:00
sliceQuantityS, err := cmd.Flags().GetString("slice-quantity")
if err != nil {
2021-03-19 02:06:42 +00:00
return err
}
if len(sliceQuantityS) == 0 {
return errors.New("--slice-quantity can not be empty")
}
2021-03-19 02:06:42 +00:00
2021-05-14 03:53:07 +00:00
sliceQuantity, err := fixedpoint.NewFromString(sliceQuantityS)
2021-03-13 01:51:31 +00:00
if err != nil {
return err
}
2021-03-19 02:06:42 +00:00
2021-05-14 07:35:11 +00:00
numOfPriceTicks, err := cmd.Flags().GetInt("price-ticks")
if err != nil {
return err
}
stopPriceS, err := cmd.Flags().GetString("stop-price")
if err != nil {
return err
}
stopPrice, err := fixedpoint.NewFromString(stopPriceS)
if err != nil {
return err
}
2021-05-15 01:29:44 +00:00
updateInterval, err := cmd.Flags().GetDuration("update-interval")
if err != nil {
return err
}
2021-05-15 01:46:07 +00:00
deadlineDuration, err := cmd.Flags().GetDuration("deadline")
if err != nil {
return err
}
var deadlineTime time.Time
if deadlineDuration > 0 {
deadlineTime = time.Now().Add(deadlineDuration)
}
2021-05-14 03:53:07 +00:00
environ := bbgo.NewEnvironment()
if err := environ.ConfigureExchangeSessions(userConfig); err != nil {
return err
}
if err := environ.Init(ctx); err != nil {
return err
}
2021-03-19 02:06:42 +00:00
session, ok := environ.Session(sessionName)
if !ok {
return fmt.Errorf("session %s not found", sessionName)
}
executionCtx, cancelExecution := context.WithCancel(ctx)
defer cancelExecution()
2021-05-14 03:53:07 +00:00
2021-05-14 07:35:11 +00:00
execution := &bbgo.TwapExecution{
Session: session,
Symbol: symbol,
Side: side,
TargetQuantity: targetQuantity,
SliceQuantity: sliceQuantity,
StopPrice: stopPrice,
NumOfTicks: numOfPriceTicks,
2021-05-15 01:29:44 +00:00
UpdateInterval: updateInterval,
2021-05-15 01:46:07 +00:00
DeadlineTime: deadlineTime,
2021-05-14 07:35:11 +00:00
}
if err := execution.Run(executionCtx); err != nil {
2021-05-14 03:53:07 +00:00
return err
}
var sigC = make(chan os.Signal, 1)
signal.Notify(sigC, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigC)
select {
case sig := <-sigC:
log.Warnf("signal %v", sig)
log.Infof("shutting down order executor...")
shutdownCtx, cancelShutdown := context.WithDeadline(ctx, time.Now().Add(10*time.Second))
execution.Shutdown(shutdownCtx)
cancelShutdown()
2021-05-14 03:53:07 +00:00
case <-execution.Done():
log.Infof("the order execution is completed")
case <-ctx.Done():
}
2021-05-14 03:53:07 +00:00
return nil
},
}
2021-12-25 16:27:52 +00:00
// go run ./cmd/bbgo submit-order --session=ftx --symbol=BTCUSDT --side=buy --price=18000 --quantity=0.001
2021-05-14 03:53:07 +00:00
var submitOrderCmd = &cobra.Command{
2021-12-25 16:27:52 +00:00
Use: "submit-order --session SESSION --symbol SYMBOL --side SIDE --quantity QUANTITY [--price PRICE]",
2021-05-14 03:53:07 +00:00
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
if userConfig == nil {
return errors.New("config file is required")
}
sessionName, err := cmd.Flags().GetString("session")
if err != nil {
return err
}
2021-03-13 01:51:31 +00:00
symbol, err := cmd.Flags().GetString("symbol")
if err != nil {
return fmt.Errorf("can't get the symbol from flags: %w", err)
}
if symbol == "" {
return fmt.Errorf("symbol is not found")
}
side, err := cmd.Flags().GetString("side")
if err != nil {
return fmt.Errorf("can't get side: %w", err)
}
2021-04-28 11:48:17 +00:00
2021-03-13 01:51:31 +00:00
price, err := cmd.Flags().GetString("price")
if err != nil {
return fmt.Errorf("can't get price: %w", err)
}
2021-04-28 11:48:17 +00:00
2021-03-13 01:51:31 +00:00
quantity, err := cmd.Flags().GetString("quantity")
if err != nil {
return fmt.Errorf("can't get quantity: %w", err)
}
2021-05-14 03:53:07 +00:00
environ := bbgo.NewEnvironment()
if err := environ.ConfigureExchangeSessions(userConfig); err != nil {
return err
}
if err := environ.Init(ctx); err != nil {
return err
}
session, ok := environ.Session(sessionName)
if !ok {
return fmt.Errorf("session %s not found", sessionName)
}
2021-05-27 19:05:59 +00:00
market, ok := session.Market(symbol)
if !ok {
return fmt.Errorf("market definition %s not found", symbol)
}
2021-03-13 01:51:31 +00:00
so := types.SubmitOrder{
2021-04-28 11:48:17 +00:00
ClientOrderID: uuid.New().String(),
Symbol: symbol,
Side: types.SideType(ftx.TrimUpperString(side)),
Type: types.OrderTypeLimit,
Quantity: util.MustParseFloat(quantity),
QuantityString: quantity,
Price: util.MustParseFloat(price),
PriceString: price,
2021-05-27 19:05:59 +00:00
Market: market,
2021-04-28 11:48:17 +00:00
TimeInForce: "GTC",
2021-03-13 01:51:31 +00:00
}
2021-05-27 19:05:59 +00:00
2021-03-19 02:06:42 +00:00
co, err := session.Exchange.SubmitOrders(ctx, so)
2021-03-13 01:51:31 +00:00
if err != nil {
return err
}
log.Infof("submitted order: %+v\ncreated order: %+v", so, co[0])
2021-03-07 04:47:11 +00:00
return nil
},
}
func init() {
2021-03-13 02:12:20 +00:00
listOrdersCmd.Flags().String("session", "", "the exchange session name for sync")
listOrdersCmd.Flags().String("symbol", "", "the trading pair, like btcusdt")
2021-03-07 04:47:11 +00:00
submitOrderCmd.Flags().String("session", "", "the exchange session name for sync")
submitOrderCmd.Flags().String("symbol", "", "the trading pair, like btcusdt")
submitOrderCmd.Flags().String("side", "", "the trading side: buy or sell")
submitOrderCmd.Flags().String("price", "", "the trading price")
submitOrderCmd.Flags().String("quantity", "", "the trading quantity")
2021-03-13 01:51:31 +00:00
2021-05-14 03:53:07 +00:00
executeOrderCmd.Flags().String("session", "", "the exchange session name for sync")
executeOrderCmd.Flags().String("symbol", "", "the trading pair, like btcusdt")
executeOrderCmd.Flags().String("side", "", "the trading side: buy or sell")
executeOrderCmd.Flags().String("target-quantity", "", "target quantity")
executeOrderCmd.Flags().String("slice-quantity", "", "slice quantity")
executeOrderCmd.Flags().String("stop-price", "0", "stop price")
2021-05-15 01:29:44 +00:00
executeOrderCmd.Flags().Duration("update-interval", time.Second*10, "order update time")
2021-05-15 01:46:07 +00:00
executeOrderCmd.Flags().Duration("deadline", 0, "deadline of the order execution")
2021-05-14 07:35:11 +00:00
executeOrderCmd.Flags().Int("price-ticks", 0, "the number of price tick for the jump spread, default to 0")
2021-05-14 03:53:07 +00:00
2021-03-13 02:12:20 +00:00
RootCmd.AddCommand(listOrdersCmd)
RootCmd.AddCommand(submitOrderCmd)
2021-05-14 03:53:07 +00:00
RootCmd.AddCommand(executeOrderCmd)
2021-03-07 04:47:11 +00:00
}