Merge pull request #925 from c9s/feature/open-position

feature: order executor open position method
This commit is contained in:
Yo-An Lin 2022-09-09 17:58:12 +08:00 committed by GitHub
commit e86df62daf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 141 additions and 47 deletions

View File

@ -21,7 +21,7 @@ import (
"github.com/spf13/viper"
"gopkg.in/tucnak/telebot.v2"
exchange2 "github.com/c9s/bbgo/pkg/exchange"
"github.com/c9s/bbgo/pkg/exchange"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/interact"
"github.com/c9s/bbgo/pkg/notifier/slacknotifier"
@ -223,12 +223,12 @@ func (environ *Environment) ConfigureExchangeSessions(userConfig *Config) error
func (environ *Environment) AddExchangesByViperKeys() error {
for _, n := range types.SupportedExchanges {
if viper.IsSet(string(n) + "-api-key") {
exchange, err := exchange2.NewWithEnvVarPrefix(n, "")
ex, err := exchange.NewWithEnvVarPrefix(n, "")
if err != nil {
return err
}
environ.AddExchange(n.String(), exchange)
environ.AddExchange(n.String(), ex)
}
}

1
pkg/bbgo/log.go Normal file
View File

@ -0,0 +1 @@
package bbgo

View File

@ -2,6 +2,7 @@ package bbgo
import (
"context"
"errors"
"fmt"
"strings"
@ -128,6 +129,96 @@ func (e *GeneralOrderExecutor) SubmitOrders(ctx context.Context, submitOrders ..
return createdOrders, err
}
type OpenPositionOptions struct {
// Long is for open a long position
// Long or Short must be set
Long bool
// Short is for open a short position
// Long or Short must be set
Short bool
// Leverage is used for leveraged position and account
Leverage fixedpoint.Value
Quantity fixedpoint.Value
MarketOrder bool
LimitOrder bool
LimitTakerRatio fixedpoint.Value
CurrentPrice fixedpoint.Value
Tag string
}
func (e *GeneralOrderExecutor) OpenPosition(ctx context.Context, options OpenPositionOptions) error {
price := options.CurrentPrice
submitOrder := types.SubmitOrder{
Symbol: e.position.Symbol,
Type: types.OrderTypeMarket,
MarginSideEffect: types.SideEffectTypeMarginBuy,
Tag: options.Tag,
}
if !options.LimitTakerRatio.IsZero() {
if options.Long {
// use higher price to buy (this ensures that our order will be filled)
price = price.Mul(one.Add(options.LimitTakerRatio))
} else if options.Short {
// use lower price to sell (this ensures that our order will be filled)
price = price.Mul(one.Sub(options.LimitTakerRatio))
}
}
if options.MarketOrder {
submitOrder.Type = types.OrderTypeMarket
} else if options.LimitOrder {
submitOrder.Type = types.OrderTypeLimit
submitOrder.Price = price
}
quantity := options.Quantity
if options.Long {
if quantity.IsZero() {
quoteQuantity, err := CalculateQuoteQuantity(ctx, e.session, e.position.QuoteCurrency, options.Leverage)
if err != nil {
return err
}
quantity = quoteQuantity.Div(price)
}
submitOrder.Side = types.SideTypeBuy
submitOrder.Quantity = quantity
createdOrder, err2 := e.SubmitOrders(ctx, submitOrder)
if err2 != nil {
return err2
}
_ = createdOrder
return nil
} else if options.Short {
if quantity.IsZero() {
var err error
quantity, err = CalculateBaseQuantity(e.session, e.position.Market, price, quantity, options.Leverage)
if err != nil {
return err
}
}
submitOrder.Side = types.SideTypeSell
submitOrder.Quantity = quantity
createdOrder, err2 := e.SubmitOrders(ctx, submitOrder)
if err2 != nil {
return err2
}
_ = createdOrder
return nil
}
return errors.New("options Long or Short must be set")
}
// GracefulCancelActiveOrderBook cancels the orders from the active orderbook.
func (e *GeneralOrderExecutor) GracefulCancelActiveOrderBook(ctx context.Context, activeOrders *ActiveOrderBook) error {
if activeOrders.NumOfOrders() == 0 {

View File

@ -1,32 +1,30 @@
package risk
package bbgo
import (
"context"
"fmt"
"time"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/risk"
"github.com/c9s/bbgo/pkg/types"
)
var log = logrus.WithField("risk", "AccountValueCalculator")
var one = fixedpoint.One
var defaultLeverage = fixedpoint.NewFromInt(3)
var maxLeverage = fixedpoint.NewFromInt(10)
type AccountValueCalculator struct {
session *bbgo.ExchangeSession
session *ExchangeSession
quoteCurrency string
prices map[string]fixedpoint.Value
tickers map[string]types.Ticker
updateTime time.Time
}
func NewAccountValueCalculator(session *bbgo.ExchangeSession, quoteCurrency string) *AccountValueCalculator {
func NewAccountValueCalculator(session *ExchangeSession, quoteCurrency string) *AccountValueCalculator {
return &AccountValueCalculator{
session: session,
quoteCurrency: quoteCurrency,
@ -188,10 +186,10 @@ func (c *AccountValueCalculator) MarginLevel(ctx context.Context) (fixedpoint.Va
return marginLevel, nil
}
func CalculateBaseQuantity(session *bbgo.ExchangeSession, market types.Market, price, quantity, leverage fixedpoint.Value) (fixedpoint.Value, error) {
func CalculateBaseQuantity(session *ExchangeSession, market types.Market, price, quantity, leverage fixedpoint.Value) (fixedpoint.Value, error) {
// default leverage guard
if leverage.IsZero() {
leverage = fixedpoint.NewFromInt(3)
leverage = defaultLeverage
}
baseBalance, _ := session.Account.Balance(market.BaseCurrency)
@ -203,7 +201,7 @@ func CalculateBaseQuantity(session *bbgo.ExchangeSession, market types.Market, p
balance, hasBalance := session.Account.Balance(market.BaseCurrency)
if hasBalance {
if quantity.IsZero() {
logrus.Warnf("sell quantity is not set, using all available base balance: %v", balance)
log.Warnf("sell quantity is not set, using all available base balance: %v", balance)
if !balance.Available.IsZero() {
return balance.Available, nil
}
@ -220,7 +218,7 @@ func CalculateBaseQuantity(session *bbgo.ExchangeSession, market types.Market, p
}
// using leverage -- starts from here
logrus.Infof("calculating available leveraged base quantity: base balance = %+v, quote balance = %+v", baseBalance, quoteBalance)
log.Infof("calculating available leveraged base quantity: base balance = %+v, quote balance = %+v", baseBalance, quoteBalance)
// calculate the quantity automatically
if session.Margin || session.IsolatedMargin {
@ -230,22 +228,22 @@ func CalculateBaseQuantity(session *bbgo.ExchangeSession, market types.Market, p
// avoid using all account value since there will be some trade loss for interests and the fee
accountValue = accountValue.Mul(one.Sub(fixedpoint.NewFromFloat(0.01)))
logrus.Infof("calculated account value %f %s", accountValue.Float64(), market.QuoteCurrency)
log.Infof("calculated account value %f %s", accountValue.Float64(), market.QuoteCurrency)
if session.IsolatedMargin {
originLeverage := leverage
leverage = fixedpoint.Min(leverage, maxLeverage)
logrus.Infof("using isolated margin, maxLeverage=10 originalLeverage=%f currentLeverage=%f",
log.Infof("using isolated margin, maxLeverage=10 originalLeverage=%f currentLeverage=%f",
originLeverage.Float64(),
leverage.Float64())
}
// spot margin use the equity value, so we use the total quote balance here
maxPosition := CalculateMaxPosition(price, accountValue, leverage)
maxPosition := risk.CalculateMaxPosition(price, accountValue, leverage)
debt := baseBalance.Debt()
maxQuantity := maxPosition.Sub(debt)
logrus.Infof("margin leverage: calculated maxQuantity=%f maxPosition=%f debt=%f price=%f accountValue=%f %s leverage=%f",
log.Infof("margin leverage: calculated maxQuantity=%f maxPosition=%f debt=%f price=%f accountValue=%f %s leverage=%f",
maxQuantity.Float64(),
maxPosition.Float64(),
debt.Float64(),
@ -259,8 +257,8 @@ func CalculateBaseQuantity(session *bbgo.ExchangeSession, market types.Market, p
if session.Futures || session.IsolatedFutures {
// TODO: get mark price here
maxPositionQuantity := CalculateMaxPosition(price, quoteBalance.Available, leverage)
requiredPositionCost := CalculatePositionCost(price, price, maxPositionQuantity, leverage, types.SideTypeSell)
maxPositionQuantity := risk.CalculateMaxPosition(price, quoteBalance.Available, leverage)
requiredPositionCost := risk.CalculatePositionCost(price, price, maxPositionQuantity, leverage, types.SideTypeSell)
if quoteBalance.Available.Compare(requiredPositionCost) < 0 {
return maxPositionQuantity, fmt.Errorf("available margin %f %s is not enough, can not submit order", quoteBalance.Available.Float64(), market.QuoteCurrency)
}
@ -271,10 +269,10 @@ func CalculateBaseQuantity(session *bbgo.ExchangeSession, market types.Market, p
return quantity, fmt.Errorf("quantity is zero, can not submit sell order, please check your settings")
}
func CalculateQuoteQuantity(session *bbgo.ExchangeSession, ctx context.Context, quoteCurrency string, leverage fixedpoint.Value) (fixedpoint.Value, error) {
func CalculateQuoteQuantity(ctx context.Context, session *ExchangeSession, quoteCurrency string, leverage fixedpoint.Value) (fixedpoint.Value, error) {
// default leverage guard
if leverage.IsZero() {
leverage = fixedpoint.NewFromInt(3)
leverage = defaultLeverage
}
quoteBalance, _ := session.Account.Balance(quoteCurrency)
@ -292,7 +290,8 @@ func CalculateQuoteQuantity(session *bbgo.ExchangeSession, ctx context.Context,
log.WithError(err).Errorf("can not update available quote")
return fixedpoint.Zero, err
}
logrus.Infof("calculating available leveraged quote quantity: account available quote = %+v", availableQuote)
log.Infof("calculating available leveraged quote quantity: account available quote = %+v", availableQuote)
return availableQuote.Mul(leverage), nil
}

View File

@ -1,4 +1,4 @@
package risk
package bbgo
import (
"context"
@ -8,7 +8,6 @@ import (
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/c9s/bbgo/pkg/types/mocks"
@ -40,7 +39,7 @@ func TestAccountValueCalculator_NetValue(t *testing.T) {
"BTCUSDT": newTestTicker(),
}, nil)
session := bbgo.NewExchangeSession("test", mockEx)
session := NewExchangeSession("test", mockEx)
session.Account.UpdateBalances(types.BalanceMap{
"BTC": {
Currency: "BTC",
@ -81,7 +80,7 @@ func TestAccountValueCalculator_NetValue(t *testing.T) {
"BTCUSDT": newTestTicker(),
}, nil)
session := bbgo.NewExchangeSession("test", mockEx)
session := NewExchangeSession("test", mockEx)
session.Account.UpdateBalances(types.BalanceMap{
"BTC": {
Currency: "BTC",
@ -123,7 +122,7 @@ func TestNewAccountValueCalculator_MarginLevel(t *testing.T) {
"BTCUSDT": newTestTicker(),
}, nil)
session := bbgo.NewExchangeSession("test", mockEx)
session := NewExchangeSession("test", mockEx)
session.Account.UpdateBalances(types.BalanceMap{
"BTC": {
Currency: "BTC",

View File

@ -6,7 +6,6 @@ import (
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/indicator"
"github.com/c9s/bbgo/pkg/risk"
"github.com/c9s/bbgo/pkg/types"
)
@ -197,7 +196,7 @@ func (s *BreakLow) Bind(session *bbgo.ExchangeSession, orderExecutor *bbgo.Gener
// graceful cancel all active orders
_ = orderExecutor.GracefulCancel(ctx)
quantity, err := risk.CalculateBaseQuantity(s.session, s.Market, closePrice, s.Quantity, s.Leverage)
quantity, err := bbgo.CalculateBaseQuantity(s.session, s.Market, closePrice, s.Quantity, s.Leverage)
if err != nil {
log.WithError(err).Errorf("quantity calculation error")
}
@ -241,7 +240,7 @@ func (s *BreakLow) pilotQuantityCalculation() {
s.Quantity.Float64(),
s.Leverage.Float64())
quantity, err := risk.CalculateBaseQuantity(s.session, s.Market, s.lastLow, s.Quantity, s.Leverage)
quantity, err := bbgo.CalculateBaseQuantity(s.session, s.Market, s.lastLow, s.Quantity, s.Leverage)
if err != nil {
log.WithError(err).Errorf("quantity calculation error")
}

View File

@ -6,7 +6,6 @@ import (
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/indicator"
"github.com/c9s/bbgo/pkg/risk"
"github.com/c9s/bbgo/pkg/types"
)
@ -199,6 +198,7 @@ func (s *FailedBreakHigh) Bind(session *bbgo.ExchangeSession, orderExecutor *bbg
// stop EMA protection
if s.StopEMA != nil {
if !s.StopEMA.Allowed(closePrice) {
bbgo.Notify("stopEMA protection: close price %f %s", kline.Close.Float64(), s.StopEMA.String())
return
}
}
@ -208,7 +208,7 @@ func (s *FailedBreakHigh) Bind(session *bbgo.ExchangeSession, orderExecutor *bbg
// graceful cancel all active orders
_ = orderExecutor.GracefulCancel(ctx)
quantity, err := risk.CalculateBaseQuantity(s.session, s.Market, closePrice, s.Quantity, s.Leverage)
quantity, err := bbgo.CalculateBaseQuantity(s.session, s.Market, closePrice, s.Quantity, s.Leverage)
if err != nil {
log.WithError(err).Errorf("quantity calculation error")
}
@ -219,8 +219,8 @@ func (s *FailedBreakHigh) Bind(session *bbgo.ExchangeSession, orderExecutor *bbg
}
if s.MarketOrder {
bbgo.Notify("%s price %f failed breaking the previous high %f with ratio %f, submitting market sell to open a short position", symbol, kline.Close.Float64(), previousHigh.Float64(), s.Ratio.Float64())
_, _ = s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
bbgo.Notify("%s price %f failed breaking the previous high %f with ratio %f, submitting market sell %f to open a short position", symbol, kline.Close.Float64(), previousHigh.Float64(), s.Ratio.Float64(), quantity.Float64())
_, err := s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeMarket,
@ -228,12 +228,15 @@ func (s *FailedBreakHigh) Bind(session *bbgo.ExchangeSession, orderExecutor *bbg
MarginSideEffect: types.SideEffectTypeMarginBuy,
Tag: "FailedBreakHighMarket",
})
if err != nil {
bbgo.Notify(err.Error())
}
} else {
sellPrice := previousHigh
bbgo.Notify("%s price %f failed breaking the previous high %f with ratio %f, submitting limit sell @ %f", symbol, kline.Close.Float64(), previousHigh.Float64(), s.Ratio.Float64(), sellPrice.Float64())
_, _ = s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
_, err := s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: kline.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimit,
@ -242,6 +245,10 @@ func (s *FailedBreakHigh) Bind(session *bbgo.ExchangeSession, orderExecutor *bbg
MarginSideEffect: types.SideEffectTypeMarginBuy,
Tag: "FailedBreakHighLimit",
})
if err != nil {
bbgo.Notify(err.Error())
}
}
}))
}
@ -252,7 +259,7 @@ func (s *FailedBreakHigh) pilotQuantityCalculation() {
s.Quantity.Float64(),
s.Leverage.Float64())
quantity, err := risk.CalculateBaseQuantity(s.session, s.Market, s.lastHigh, s.Quantity, s.Leverage)
quantity, err := bbgo.CalculateBaseQuantity(s.session, s.Market, s.lastHigh, s.Quantity, s.Leverage)
if err != nil {
log.WithError(err).Errorf("quantity calculation error")
}

View File

@ -7,7 +7,6 @@ import (
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/indicator"
"github.com/c9s/bbgo/pkg/risk"
"github.com/c9s/bbgo/pkg/types"
)
@ -128,7 +127,7 @@ func (s *ResistanceShort) updateResistanceOrders(closePrice fixedpoint.Value) {
}
func (s *ResistanceShort) placeResistanceOrders(ctx context.Context, resistancePrice fixedpoint.Value) {
totalQuantity, err := risk.CalculateBaseQuantity(s.session, s.Market, resistancePrice, s.Quantity, s.Leverage)
totalQuantity, err := bbgo.CalculateBaseQuantity(s.session, s.Market, resistancePrice, s.Quantity, s.Leverage)
if err != nil {
log.WithError(err).Errorf("quantity calculation error")
}

View File

@ -6,13 +6,12 @@ import (
"os"
"sync"
"github.com/c9s/bbgo/pkg/data/tsv"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/risk"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/data/tsv"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/indicator"
@ -188,7 +187,7 @@ type Strategy struct {
Leverage fixedpoint.Value `json:"leverage"`
// Quantity sets the fixed order qty, takes precedence over Leverage
Quantity fixedpoint.Value `json:"quantity"`
AccountValueCalculator *risk.AccountValueCalculator
AccountValueCalculator *bbgo.AccountValueCalculator
// TakeProfitAtrMultiplier TP according to ATR multiple, 0 to disable this
TakeProfitAtrMultiplier float64 `json:"takeProfitAtrMultiplier"`
@ -404,7 +403,7 @@ func (s *Strategy) calculateQuantity(ctx context.Context, currentPrice fixedpoin
return balance.Available.Mul(fixedpoint.Min(s.Leverage, fixedpoint.One))
} else { // Using leverage or spot buy
quoteQty, err := risk.CalculateQuoteQuantity(s.session, ctx, s.Market.QuoteCurrency, s.Leverage)
quoteQty, err := bbgo.CalculateQuoteQuantity(ctx, s.session, s.Market.QuoteCurrency, s.Leverage)
if err != nil {
log.WithError(err).Errorf("can not update %s quote balance from exchange", s.Symbol)
return fixedpoint.Zero
@ -464,7 +463,7 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.orderExecutor.Bind()
// AccountValueCalculator
s.AccountValueCalculator = risk.NewAccountValueCalculator(s.session, s.Market.QuoteCurrency)
s.AccountValueCalculator = bbgo.NewAccountValueCalculator(s.session, s.Market.QuoteCurrency)
// Accumulated profit report
if bbgo.IsBackTesting {