2022-06-15 17:46:33 +00:00
|
|
|
package marketcap
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
2022-09-13 18:42:36 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/datasource/coinmarketcap"
|
2022-08-25 09:31:42 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/datatype/floats"
|
2022-06-15 17:46:33 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
const ID = "marketcap"
|
|
|
|
|
|
|
|
var log = logrus.WithField("strategy", ID)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
|
|
|
}
|
|
|
|
|
|
|
|
type Strategy struct {
|
2022-09-13 18:47:12 +00:00
|
|
|
datasource *coinmarketcap.DataSource
|
2022-06-15 17:46:33 +00:00
|
|
|
|
2022-09-16 20:04:07 +00:00
|
|
|
// interval to rebalance the portfolio
|
2022-06-15 17:46:33 +00:00
|
|
|
Interval types.Interval `json:"interval"`
|
|
|
|
BaseCurrency string `json:"baseCurrency"`
|
|
|
|
BaseWeight fixedpoint.Value `json:"baseWeight"`
|
|
|
|
TargetCurrencies []string `json:"targetCurrencies"`
|
|
|
|
Threshold fixedpoint.Value `json:"threshold"`
|
|
|
|
DryRun bool `json:"dryRun"`
|
|
|
|
// max amount to buy or sell per order
|
|
|
|
MaxAmount fixedpoint.Value `json:"maxAmount"`
|
2022-09-16 20:04:07 +00:00
|
|
|
// interval to query marketcap data from coinmarketcap
|
|
|
|
QueryInterval types.Interval `json:"queryInterval"`
|
2022-06-15 17:46:33 +00:00
|
|
|
|
2022-09-16 20:04:07 +00:00
|
|
|
subscribeSymbol string
|
2022-06-15 17:46:33 +00:00
|
|
|
activeOrderBook *bbgo.ActiveOrderBook
|
2022-09-16 20:04:07 +00:00
|
|
|
targetWeights types.ValueMap
|
2022-06-15 17:46:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Initialize() error {
|
2022-09-13 18:42:36 +00:00
|
|
|
apiKey := os.Getenv("COINMARKETCAP_API_KEY")
|
2022-09-13 18:47:12 +00:00
|
|
|
s.datasource = coinmarketcap.New(apiKey)
|
2022-09-16 20:04:07 +00:00
|
|
|
|
|
|
|
// select one symbol to subscribe
|
|
|
|
s.subscribeSymbol = s.TargetCurrencies[0] + s.BaseCurrency
|
|
|
|
|
|
|
|
s.activeOrderBook = bbgo.NewActiveOrderBook("")
|
|
|
|
s.targetWeights = types.ValueMap{}
|
2022-06-15 17:46:33 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Validate() error {
|
|
|
|
if len(s.TargetCurrencies) == 0 {
|
|
|
|
return fmt.Errorf("taretCurrencies should not be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, c := range s.TargetCurrencies {
|
|
|
|
if c == s.BaseCurrency {
|
|
|
|
return fmt.Errorf("targetCurrencies contain baseCurrency")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Threshold.Sign() < 0 {
|
|
|
|
return fmt.Errorf("threshold should not less than 0")
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.MaxAmount.Sign() < 0 {
|
|
|
|
return fmt.Errorf("maxAmount shoud not less than 0")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
2022-09-16 20:04:07 +00:00
|
|
|
symbol := s.TargetCurrencies[0] + s.BaseCurrency
|
|
|
|
session.Subscribe(types.KLineChannel, symbol, types.SubscribeOptions{Interval: s.Interval})
|
|
|
|
session.Subscribe(types.KLineChannel, symbol, types.SubscribeOptions{Interval: s.QueryInterval})
|
2022-06-15 17:46:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
|
|
|
s.activeOrderBook.BindStream(session.UserDataStream)
|
|
|
|
|
2022-09-16 20:04:07 +00:00
|
|
|
s.updateTargetWeights(ctx)
|
2022-06-15 17:46:33 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2022-09-16 20:04:07 +00:00
|
|
|
if kline.Interval == s.QueryInterval {
|
|
|
|
s.updateTargetWeights(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
if kline.Interval == s.Interval {
|
|
|
|
s.rebalance(ctx, orderExecutor, session)
|
|
|
|
}
|
2022-06-15 17:46:33 +00:00
|
|
|
})
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
|
|
|
|
if err := orderExecutor.CancelOrders(ctx, s.activeOrderBook.Orders()...); err != nil {
|
|
|
|
log.WithError(err).Error("failed to cancel orders")
|
|
|
|
}
|
|
|
|
|
|
|
|
submitOrders := s.generateSubmitOrders(ctx, session)
|
|
|
|
for _, submitOrder := range submitOrders {
|
|
|
|
log.Infof("generated submit order: %s", submitOrder.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.DryRun {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrders...)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("failed to submit orders")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
s.activeOrderBook.Add(createdOrders...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) generateSubmitOrders(ctx context.Context, session *bbgo.ExchangeSession) (submitOrders []types.SubmitOrder) {
|
|
|
|
prices := s.prices(ctx, session)
|
|
|
|
marketValues := prices.Mul(s.quantities(session))
|
|
|
|
currentWeights := marketValues.Normalize()
|
|
|
|
|
2022-09-16 20:04:07 +00:00
|
|
|
for currency, targetWeight := range s.targetWeights {
|
2022-09-13 15:35:29 +00:00
|
|
|
if currency == s.BaseCurrency {
|
|
|
|
continue
|
|
|
|
}
|
2022-06-15 17:46:33 +00:00
|
|
|
symbol := currency + s.BaseCurrency
|
|
|
|
currentWeight := currentWeights[currency]
|
|
|
|
currentPrice := prices[currency]
|
|
|
|
|
|
|
|
log.Infof("%s price: %v, current weight: %v, target weight: %v",
|
|
|
|
symbol,
|
|
|
|
currentPrice,
|
|
|
|
currentWeight,
|
|
|
|
targetWeight)
|
|
|
|
|
|
|
|
// calculate the difference between current weight and target weight
|
|
|
|
// if the difference is less than threshold, then we will not create the order
|
|
|
|
weightDifference := targetWeight.Sub(currentWeight)
|
|
|
|
if weightDifference.Abs().Compare(s.Threshold) < 0 {
|
|
|
|
log.Infof("%s weight distance |%v - %v| = |%v| less than the threshold: %v",
|
|
|
|
symbol,
|
|
|
|
currentWeight,
|
|
|
|
targetWeight,
|
|
|
|
weightDifference,
|
|
|
|
s.Threshold)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
quantity := weightDifference.Mul(marketValues.Sum()).Div(currentPrice)
|
|
|
|
|
|
|
|
side := types.SideTypeBuy
|
|
|
|
if quantity.Sign() < 0 {
|
|
|
|
side = types.SideTypeSell
|
|
|
|
quantity = quantity.Abs()
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.MaxAmount.Sign() > 0 {
|
|
|
|
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, currentPrice, s.MaxAmount)
|
|
|
|
log.Infof("adjust the quantity %v (%s %s @ %v) by max amount %v",
|
|
|
|
quantity,
|
|
|
|
symbol,
|
|
|
|
side.String(),
|
|
|
|
currentPrice,
|
|
|
|
s.MaxAmount)
|
|
|
|
}
|
|
|
|
|
|
|
|
order := types.SubmitOrder{
|
|
|
|
Symbol: symbol,
|
|
|
|
Side: side,
|
|
|
|
Type: types.OrderTypeLimit,
|
|
|
|
Quantity: quantity,
|
|
|
|
Price: currentPrice,
|
|
|
|
}
|
|
|
|
|
|
|
|
submitOrders = append(submitOrders, order)
|
|
|
|
}
|
|
|
|
return submitOrders
|
|
|
|
}
|
|
|
|
|
2022-09-16 20:04:07 +00:00
|
|
|
func (s *Strategy) updateTargetWeights(ctx context.Context) {
|
2022-08-25 09:31:42 +00:00
|
|
|
m := floats.Map{}
|
2022-06-15 17:46:33 +00:00
|
|
|
|
2022-09-13 18:42:36 +00:00
|
|
|
// get marketcap from coinmarketcap
|
|
|
|
// set higher query limit to avoid target currency not in the list
|
2022-09-13 18:47:12 +00:00
|
|
|
marketcaps, err := s.datasource.QueryMarketCapInUSD(ctx, 100)
|
2022-09-13 18:42:36 +00:00
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("failed to query market cap")
|
|
|
|
}
|
|
|
|
|
2022-06-15 17:46:33 +00:00
|
|
|
for _, currency := range s.TargetCurrencies {
|
2022-09-13 18:42:36 +00:00
|
|
|
m[currency] = marketcaps[currency]
|
2022-06-15 17:46:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// normalize
|
|
|
|
m = m.Normalize()
|
|
|
|
|
|
|
|
// rescale by 1 - baseWeight
|
|
|
|
m = m.MulScalar(1.0 - s.BaseWeight.Float64())
|
|
|
|
|
|
|
|
// append base weight
|
|
|
|
m[s.BaseCurrency] = s.BaseWeight.Float64()
|
|
|
|
|
2022-06-16 08:30:55 +00:00
|
|
|
// convert to types.ValueMap
|
2022-06-15 17:46:33 +00:00
|
|
|
for currency, weight := range m {
|
2022-09-16 20:04:07 +00:00
|
|
|
s.targetWeights[currency] = fixedpoint.NewFromFloat(weight)
|
2022-06-15 17:46:33 +00:00
|
|
|
}
|
|
|
|
|
2022-09-16 20:04:07 +00:00
|
|
|
log.Infof("target weights: %v", s.targetWeights)
|
2022-06-15 17:46:33 +00:00
|
|
|
}
|
|
|
|
|
2022-06-16 08:30:55 +00:00
|
|
|
func (s *Strategy) prices(ctx context.Context, session *bbgo.ExchangeSession) types.ValueMap {
|
2022-06-15 17:46:33 +00:00
|
|
|
tickers, err := session.Exchange.QueryTickers(ctx, s.symbols()...)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("failed to query tickers")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-16 08:30:55 +00:00
|
|
|
prices := types.ValueMap{}
|
2022-06-15 17:46:33 +00:00
|
|
|
for _, currency := range s.TargetCurrencies {
|
|
|
|
prices[currency] = tickers[currency+s.BaseCurrency].Last
|
|
|
|
}
|
|
|
|
|
|
|
|
// append base currency price
|
|
|
|
prices[s.BaseCurrency] = fixedpoint.One
|
|
|
|
|
|
|
|
return prices
|
|
|
|
}
|
|
|
|
|
2022-06-16 08:30:55 +00:00
|
|
|
func (s *Strategy) quantities(session *bbgo.ExchangeSession) types.ValueMap {
|
2022-06-15 17:46:33 +00:00
|
|
|
balances := session.Account.Balances()
|
|
|
|
|
2022-06-16 08:30:55 +00:00
|
|
|
quantities := types.ValueMap{}
|
2022-06-15 17:46:33 +00:00
|
|
|
for _, currency := range s.currencies() {
|
|
|
|
quantities[currency] = balances[currency].Total()
|
|
|
|
}
|
|
|
|
|
|
|
|
return quantities
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) symbols() (symbols []string) {
|
|
|
|
for _, currency := range s.TargetCurrencies {
|
|
|
|
symbols = append(symbols, currency+s.BaseCurrency)
|
|
|
|
}
|
|
|
|
return symbols
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) currencies() (currencies []string) {
|
|
|
|
currencies = append(currencies, s.TargetCurrencies...)
|
|
|
|
currencies = append(currencies, s.BaseCurrency)
|
|
|
|
return currencies
|
|
|
|
}
|