bbgo_origin/pkg/cmd/pnl.go

206 lines
5.1 KiB
Go
Raw Permalink Normal View History

2020-10-10 05:14:06 +00:00
package cmd
import (
"context"
2022-06-08 06:51:31 +00:00
"errors"
2021-03-14 03:04:56 +00:00
"fmt"
2022-06-08 06:59:32 +00:00
"sort"
2020-10-10 05:14:06 +00:00
"strings"
2021-03-14 03:04:56 +00:00
"time"
2020-10-10 05:14:06 +00:00
2021-01-19 18:45:50 +00:00
log "github.com/sirupsen/logrus"
2020-10-10 05:14:06 +00:00
"github.com/spf13/cobra"
"github.com/c9s/bbgo/pkg/accounting/pnl"
"github.com/c9s/bbgo/pkg/bbgo"
2020-10-11 08:46:15 +00:00
"github.com/c9s/bbgo/pkg/service"
"github.com/c9s/bbgo/pkg/types"
2020-10-10 05:14:06 +00:00
)
func init() {
2022-06-22 10:19:11 +00:00
PnLCmd.Flags().StringArray("session", []string{}, "target exchange sessions")
2021-03-14 03:04:56 +00:00
PnLCmd.Flags().String("symbol", "", "trading symbol")
PnLCmd.Flags().Bool("include-transfer", false, "convert transfer records into trades")
2022-06-22 10:24:34 +00:00
PnLCmd.Flags().Bool("sync", false, "sync before loading trades")
2022-06-22 10:19:11 +00:00
PnLCmd.Flags().String("since", "", "query trades from a time point")
PnLCmd.Flags().Uint64("limit", 0, "number of trades")
2020-10-23 06:28:07 +00:00
RootCmd.AddCommand(PnLCmd)
2020-10-10 05:14:06 +00:00
}
2020-10-23 06:28:07 +00:00
var PnLCmd = &cobra.Command{
2020-10-10 05:14:06 +00:00
Use: "pnl",
2022-06-08 06:51:31 +00:00
Short: "Average Cost Based PnL Calculator",
Long: "This command calculates the average cost-based profit from your total trades",
2020-10-10 05:14:06 +00:00
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
2022-06-22 10:19:11 +00:00
sessionNames, err := cmd.Flags().GetStringArray("session")
if err != nil {
return err
}
2022-06-22 10:19:11 +00:00
if len(sessionNames) == 0 {
return errors.New("--session [SESSION] is required")
}
2022-06-22 10:24:34 +00:00
wantSync, err := cmd.Flags().GetBool("sync")
if err != nil {
return err
}
2020-10-10 05:14:06 +00:00
symbol, err := cmd.Flags().GetString("symbol")
if err != nil {
return err
}
2021-03-14 03:04:56 +00:00
if len(symbol) == 0 {
return errors.New("--symbol [SYMBOL] is required")
}
// this is the default since
2021-03-14 03:04:56 +00:00
since := time.Now().AddDate(-1, 0, 0)
sinceOpt, err := cmd.Flags().GetString("since")
if err != nil {
return err
}
if sinceOpt != "" {
lt, err := types.ParseLooseFormatTime(sinceOpt)
if err != nil {
return err
}
since = lt.Time()
}
2021-03-14 03:04:56 +00:00
until := time.Now()
includeTransfer, err := cmd.Flags().GetBool("include-transfer")
if err != nil {
return err
}
2022-06-22 10:19:11 +00:00
limit, err := cmd.Flags().GetUint64("limit")
if err != nil {
return err
}
environ := bbgo.NewEnvironment()
2024-01-24 07:18:31 +00:00
if err := environ.ConfigureDatabase(ctx, userConfig); err != nil {
2022-06-22 10:19:11 +00:00
return err
}
if err := environ.ConfigureExchangeSessions(userConfig); err != nil {
return err
}
for _, sessionName := range sessionNames {
session, ok := environ.Session(sessionName)
2021-03-14 03:04:56 +00:00
if !ok {
2022-06-22 10:19:11 +00:00
return fmt.Errorf("session %s not found", sessionName)
2021-03-14 03:04:56 +00:00
}
2022-06-22 10:24:34 +00:00
if wantSync {
if err := environ.SyncSession(ctx, session, symbol); err != nil {
return err
}
2021-03-14 03:04:56 +00:00
}
2022-06-22 10:19:11 +00:00
if includeTransfer {
exchange := session.Exchange
market, _ := session.Market(symbol)
transferService, ok := exchange.(types.ExchangeTransferService)
if !ok {
return fmt.Errorf("session exchange %s does not implement transfer service", sessionName)
}
deposits, err := transferService.QueryDepositHistory(ctx, market.BaseCurrency, since, until)
if err != nil {
return err
}
_ = deposits
withdrawals, err := transferService.QueryWithdrawHistory(ctx, market.BaseCurrency, since, until)
if err != nil {
return err
}
sort.Slice(withdrawals, func(i, j int) bool {
a := withdrawals[i].ApplyTime.Time()
b := withdrawals[j].ApplyTime.Time()
return a.Before(b)
})
// we need the backtest klines for the daily prices
backtestService := &service.BacktestService{DB: environ.DatabaseService.DB}
if err := backtestService.Sync(ctx, exchange, symbol, types.Interval1d, since, until); err != nil {
return err
}
2021-03-14 03:04:56 +00:00
}
2022-06-22 10:19:11 +00:00
}
2022-06-08 06:59:32 +00:00
2022-06-22 10:19:11 +00:00
if err = environ.Init(ctx); err != nil {
return err
2021-03-14 03:04:56 +00:00
}
2021-02-20 16:58:34 +00:00
2022-06-22 10:19:11 +00:00
session, _ := environ.Session(sessionNames[0])
exchange := session.Exchange
2020-10-10 05:14:06 +00:00
var trades []types.Trade
tradingFeeCurrency := exchange.PlatformFeeCurrency()
2020-10-10 05:14:06 +00:00
if strings.HasPrefix(symbol, tradingFeeCurrency) {
2021-01-19 18:45:50 +00:00
log.Infof("loading all trading fee currency related trades: %s", symbol)
trades, err = environ.TradeService.QueryForTradingFeeCurrency(exchange.Name(), symbol, tradingFeeCurrency)
2020-10-10 05:14:06 +00:00
} else {
trades, err = environ.TradeService.Query(service.QueryTradesOptions{
2022-06-22 10:19:11 +00:00
Symbol: symbol,
Limit: limit,
Sessions: sessionNames,
Since: &since,
2021-01-29 10:48:00 +00:00
})
2020-10-10 05:14:06 +00:00
}
if err != nil {
return err
}
2022-06-08 06:51:31 +00:00
if len(trades) == 0 {
return errors.New("empty trades, you need to run sync command to sync the trades from the exchange first")
2020-10-10 05:14:06 +00:00
}
2022-06-08 06:51:31 +00:00
trades = types.SortTradesAscending(trades)
2020-10-10 05:14:06 +00:00
2022-06-08 06:51:31 +00:00
log.Infof("%d trades loaded", len(trades))
2020-10-10 05:14:06 +00:00
2021-02-06 21:11:58 +00:00
tickers, err := exchange.QueryTickers(ctx, symbol)
if err != nil {
return err
}
2021-02-07 23:02:08 +00:00
currentTick, ok := tickers[symbol]
2021-02-06 21:11:58 +00:00
if !ok {
return errors.New("no ticker data for current price")
}
2022-07-02 09:45:24 +00:00
market, ok := session.Market(symbol)
if !ok {
return fmt.Errorf("market not found: %s, %s", symbol, session.Exchange.Name())
}
2021-02-06 21:11:58 +00:00
currentPrice := currentTick.Last
calculator := &pnl.AverageCostCalculator{
2020-10-10 05:14:06 +00:00
TradingFeeCurrency: tradingFeeCurrency,
2022-07-02 09:45:24 +00:00
Market: market,
2020-10-10 05:14:06 +00:00
}
2020-10-18 03:18:12 +00:00
2020-10-22 07:57:50 +00:00
report := calculator.Calculate(symbol, trades, currentPrice)
2020-10-10 05:14:06 +00:00
report.Print()
2022-06-08 06:59:32 +00:00
log.Warnf("note that if you're using cross-exchange arbitrage, the PnL won't be accurate")
log.Warnf("withdrawal and deposits are not considered in the PnL")
2020-10-10 05:14:06 +00:00
return nil
},
}