Merge pull request #756 from c9s/improve/persistence-api

refactor: clean up rsmaker, xbalance, dca, pivotshort strategies
This commit is contained in:
Yo-An Lin 2022-06-22 16:37:47 +08:00 committed by GitHub
commit 7737083d7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 178 additions and 722 deletions

View File

@ -91,14 +91,18 @@ func (p *Persistence) Sync(obj interface{}) error {
} }
// Sync syncs the object properties into the persistence layer // Sync syncs the object properties into the persistence layer
func Sync(obj interface{}) error { func Sync(obj interface{}) {
id := callID(obj) id := callID(obj)
if len(id) == 0 { if len(id) == 0 {
return nil log.Warnf("InstanceID() is not provided, can not sync persistence")
return
} }
ps := PersistenceServiceFacade.Get() ps := PersistenceServiceFacade.Get()
return storePersistenceFields(obj, id, ps) err := storePersistenceFields(obj, id, ps)
if err != nil {
log.WithError(err).Errorf("persistence sync failed")
}
} }
func loadPersistenceFields(obj interface{}, id string, persistence service.PersistenceService) error { func loadPersistenceFields(obj interface{}, id string, persistence service.PersistenceService) error {

View File

@ -12,6 +12,15 @@ import (
"github.com/c9s/bbgo/pkg/types" "github.com/c9s/bbgo/pkg/types"
) )
type TestStructWithoutInstanceID struct {
Symbol string
}
func (s *TestStructWithoutInstanceID) ID() string {
return "test-struct-no-instance-id"
}
type TestStruct struct { type TestStruct struct {
*Environment *Environment
*Graceful *Graceful
@ -48,8 +57,16 @@ func preparePersistentServices() []service.PersistenceService {
} }
func Test_callID(t *testing.T) { func Test_callID(t *testing.T) {
id := callID(&TestStruct{}) t.Run("default", func(t *testing.T) {
assert.NotEmpty(t, id) id := callID(&TestStruct{})
assert.NotEmpty(t, id)
assert.Equal(t, "test-struct", id)
})
t.Run("fallback", func(t *testing.T) {
id := callID(&TestStructWithoutInstanceID{Symbol: "BTCUSDT"})
assert.Equal(t, "test-struct-no-instance-id:BTCUSDT", id)
})
} }
func Test_loadPersistenceFields(t *testing.T) { func Test_loadPersistenceFields(t *testing.T) {

View File

@ -18,7 +18,17 @@ func callID(obj interface{}) string {
ret := m.Call(nil) ret := m.Call(nil)
return ret[0].String() return ret[0].String()
} }
return ""
if symbol, ok := isSymbolBasedStrategy(sv); ok {
m := sv.MethodByName("ID")
ret := m.Call(nil)
return ret[0].String() + ":" + symbol
}
// fallback to just ID
m := sv.MethodByName("ID")
ret := m.Call(nil)
return ret[0].String() + ":"
} }
func isSymbolBasedStrategy(rs reflect.Value) (string, bool) { func isSymbolBasedStrategy(rs reflect.Value) (string, bool) {

View File

@ -158,8 +158,6 @@ type Strategy struct {
groupID uint32 groupID uint32
stopC chan struct{}
// defaultBoll is the BOLLINGER indicator we used for predicting the price. // defaultBoll is the BOLLINGER indicator we used for predicting the price.
defaultBoll *indicator.BOLL defaultBoll *indicator.BOLL
@ -215,34 +213,7 @@ func (s *Strategy) CurrentPosition() *types.Position {
} }
func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error { func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error {
base := s.Position.GetBase() return s.orderExecutor.ClosePosition(ctx, percentage)
if base.IsZero() {
return fmt.Errorf("no opened %s position", s.Position.Symbol)
}
// make it negative
quantity := base.Mul(percentage).Abs()
side := types.SideTypeBuy
if base.Sign() > 0 {
side = types.SideTypeSell
}
if quantity.Compare(s.Market.MinQuantity) < 0 {
return fmt.Errorf("order quantity %v is too small, less than %v", quantity, s.Market.MinQuantity)
}
submitOrder := types.SubmitOrder{
Symbol: s.Symbol,
Side: side,
Type: types.OrderTypeMarket,
Quantity: quantity,
Market: s.Market,
}
bbgo.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder)
_, err := s.orderExecutor.SubmitOrders(ctx, submitOrder)
return err
} }
// Deprecated: LoadState method is migrated to the persistence struct tag. // Deprecated: LoadState method is migrated to the persistence struct tag.
@ -494,7 +465,7 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.OnSuspend(func() { s.OnSuspend(func() {
s.Status = types.StrategyStatusStopped s.Status = types.StrategyStatusStopped
_ = s.orderExecutor.GracefulCancel(ctx) _ = s.orderExecutor.GracefulCancel(ctx)
_ = s.Persistence.Sync(s) bbgo.Sync(s)
}) })
s.OnEmergencyStop(func() { s.OnEmergencyStop(func() {
@ -574,18 +545,13 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.orderExecutor.BindProfitStats(s.ProfitStats) s.orderExecutor.BindProfitStats(s.ProfitStats)
s.orderExecutor.Bind() s.orderExecutor.Bind()
s.stopC = make(chan struct{})
// TODO: migrate persistance to singleton
s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) { s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
if err := s.Persistence.Sync(s); err != nil { bbgo.Sync(s)
log.WithError(err).Errorf("can not sync state to persistence")
}
}) })
s.SmartStops.RunStopControllers(ctx, session, s.orderExecutor.TradeCollector()) s.SmartStops.RunStopControllers(ctx, session, s.orderExecutor.TradeCollector())
if s.Environment.IsBackTesting() { if bbgo.IsBackTesting {
log.Warn("turning of useTickerPrice option in the back-testing environment...") log.Warn("turning of useTickerPrice option in the back-testing environment...")
s.UseTickerPrice = false s.UseTickerPrice = false
} }
@ -652,7 +618,6 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) { s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done() defer wg.Done()
close(s.stopC)
_ = s.orderExecutor.GracefulCancel(ctx) _ = s.orderExecutor.GracefulCancel(ctx)
}) })

View File

@ -48,7 +48,6 @@ func (b BudgetPeriod) Duration() time.Duration {
// Strategy is the Dollar-Cost-Average strategy // Strategy is the Dollar-Cost-Average strategy
type Strategy struct { type Strategy struct {
*bbgo.Graceful *bbgo.Graceful
*bbgo.Persistence
Environment *bbgo.Environment Environment *bbgo.Environment
Symbol string `json:"symbol"` Symbol string `json:"symbol"`
@ -71,11 +70,8 @@ type Strategy struct {
BudgetQuota fixedpoint.Value `persistence:"budget_quota"` BudgetQuota fixedpoint.Value `persistence:"budget_quota"`
BudgetPeriodStartTime time.Time `persistence:"budget_period_start_time"` BudgetPeriodStartTime time.Time `persistence:"budget_period_start_time"`
activeMakerOrders *bbgo.ActiveOrderBook session *bbgo.ExchangeSession
orderStore *bbgo.OrderStore orderExecutor *bbgo.GeneralOrderExecutor
tradeCollector *bbgo.TradeCollector
session *bbgo.ExchangeSession
bbgo.StrategyController bbgo.StrategyController
} }
@ -88,73 +84,18 @@ func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.InvestmentInterval}) session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.InvestmentInterval})
} }
func (s *Strategy) submitOrders(ctx context.Context, orderExecutor bbgo.OrderExecutor, submitOrders ...types.SubmitOrder) {
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrders...)
if err != nil {
log.WithError(err).Errorf("can not place orders")
}
s.orderStore.Add(createdOrders...)
s.activeMakerOrders.Add(createdOrders...)
s.tradeCollector.Process()
}
func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error { func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error {
base := s.Position.GetBase() return s.orderExecutor.ClosePosition(ctx, percentage)
if base.IsZero() {
return fmt.Errorf("no opened %s position", s.Position.Symbol)
}
// make it negative
quantity := base.Mul(percentage).Abs()
side := types.SideTypeBuy
if base.Sign() > 0 {
side = types.SideTypeSell
}
if quantity.Compare(s.Market.MinQuantity) < 0 {
return fmt.Errorf("order quantity %v is too small, less than %v", quantity, s.Market.MinQuantity)
}
submitOrder := types.SubmitOrder{
Symbol: s.Symbol,
Side: side,
Type: types.OrderTypeMarket,
Quantity: quantity,
Market: s.Market,
}
// s.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder)
createdOrders, err := s.session.Exchange.SubmitOrders(ctx, submitOrder)
if err != nil {
log.WithError(err).Errorf("can not place position close order")
}
s.orderStore.Add(createdOrders...)
s.activeMakerOrders.Add(createdOrders...)
s.tradeCollector.Process()
return err
} }
func (s *Strategy) InstanceID() string { func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol) return fmt.Sprintf("%s:%s", ID, s.Symbol)
} }
// check if position can be close or not func (s *Strategy) Run(ctx context.Context, session *bbgo.ExchangeSession) error {
func canClosePosition(position *types.Position, signal fixedpoint.Value, price fixedpoint.Value) bool { if s.BudgetQuota.IsZero() {
return !signal.IsZero() && position.IsShort() && !position.IsDust(price) s.BudgetQuota = s.Budget
} }
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
// initial required information
s.session = session
s.activeMakerOrders = bbgo.NewActiveOrderBook(s.Symbol)
s.activeMakerOrders.BindStream(session.UserDataStream)
s.orderStore = bbgo.NewOrderStore(s.Symbol)
s.orderStore.BindStream(session.UserDataStream)
if s.Position == nil { if s.Position == nil {
s.Position = types.NewPositionFromMarket(s.Market) s.Position = types.NewPositionFromMarket(s.Market)
@ -165,50 +106,18 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
} }
instanceID := s.InstanceID() instanceID := s.InstanceID()
s.session = session
if s.BudgetQuota.IsZero() { s.orderExecutor = bbgo.NewGeneralOrderExecutor(session, s.Symbol, ID, instanceID, s.Position)
s.BudgetQuota = s.Budget s.orderExecutor.BindEnvironment(s.Environment)
} s.orderExecutor.BindProfitStats(s.ProfitStats)
s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
bbgo.Sync(s)
})
s.orderExecutor.Bind()
numOfInvestmentPerPeriod := fixedpoint.NewFromFloat(float64(s.BudgetPeriod.Duration()) / float64(s.InvestmentInterval.Duration())) numOfInvestmentPerPeriod := fixedpoint.NewFromFloat(float64(s.BudgetPeriod.Duration()) / float64(s.InvestmentInterval.Duration()))
s.budgetPerInvestment = s.Budget.Div(numOfInvestmentPerPeriod) s.budgetPerInvestment = s.Budget.Div(numOfInvestmentPerPeriod)
// Always update the position fields
s.Position.Strategy = ID
s.Position.StrategyInstanceID = instanceID
s.tradeCollector = bbgo.NewTradeCollector(s.Symbol, s.Position, s.orderStore)
s.tradeCollector.OnTrade(func(trade types.Trade, profit, netProfit fixedpoint.Value) {
bbgo.Notify(trade)
s.ProfitStats.AddTrade(trade)
if profit.Compare(fixedpoint.Zero) == 0 {
s.Environment.RecordPosition(s.Position, trade, nil)
} else {
log.Infof("%s generated profit: %v", s.Symbol, profit)
p := s.Position.NewProfit(trade, profit, netProfit)
p.Strategy = ID
p.StrategyInstanceID = instanceID
bbgo.Notify(&p)
s.ProfitStats.AddProfit(p)
bbgo.Notify(&s.ProfitStats)
s.Environment.RecordPosition(s.Position, trade, &p)
}
})
s.tradeCollector.OnTrade(func(trade types.Trade, profit fixedpoint.Value, netProfit fixedpoint.Value) {
s.BudgetQuota = s.BudgetQuota.Sub(trade.QuoteQuantity)
})
s.tradeCollector.OnPositionUpdate(func(position *types.Position) {
log.Infof("position changed: %s", s.Position)
bbgo.Notify(s.Position)
})
s.tradeCollector.BindStream(session.UserDataStream)
session.UserDataStream.OnStart(func() {}) session.UserDataStream.OnStart(func() {})
session.MarketDataStream.OnKLine(func(kline types.KLine) {}) session.MarketDataStream.OnKLine(func(kline types.KLine) {})
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) { session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
@ -234,13 +143,16 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
price := kline.Close price := kline.Close
quantity := s.budgetPerInvestment.Div(price) quantity := s.budgetPerInvestment.Div(price)
s.submitOrders(ctx, orderExecutor, types.SubmitOrder{ _, err := s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: s.Symbol, Symbol: s.Symbol,
Side: types.SideTypeBuy, Side: types.SideTypeBuy,
Type: types.OrderTypeMarket, Type: types.OrderTypeMarket,
Quantity: quantity, Quantity: quantity,
Market: s.Market, Market: s.Market,
}) })
if err != nil {
log.WithError(err).Errorf("submit order failed")
}
}) })
return nil return nil

View File

@ -51,8 +51,6 @@ type Strategy struct {
KLineEndTime types.Time KLineEndTime types.Time
*bbgo.Environment *bbgo.Environment
*bbgo.Notifiability
*bbgo.Persistence
*bbgo.Graceful *bbgo.Graceful
bbgo.StrategyController bbgo.StrategyController

View File

@ -78,7 +78,6 @@ type Exit struct {
type Strategy struct { type Strategy struct {
*bbgo.Graceful *bbgo.Graceful
*bbgo.Persistence
Environment *bbgo.Environment Environment *bbgo.Environment
Symbol string `json:"symbol"` Symbol string `json:"symbol"`
@ -163,35 +162,16 @@ func (s *Strategy) placeMarketSell(ctx context.Context, quantity fixedpoint.Valu
}) })
} }
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
}
func (s *Strategy) CurrentPosition() *types.Position { func (s *Strategy) CurrentPosition() *types.Position {
return s.Position return s.Position
} }
func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error { func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error {
// Cancel active orders return s.orderExecutor.ClosePosition(ctx, percentage)
_ = s.orderExecutor.GracefulCancel(ctx)
submitOrder := s.Position.NewMarketCloseOrder(percentage) // types.SubmitOrder{
if submitOrder == nil {
return nil
}
if s.session.Margin {
submitOrder.MarginSideEffect = s.Exit.MarginSideEffect
}
bbgo.Notify("Closing %s position by %f", s.Symbol, percentage.Float64())
log.Infof("Closing %s position by %f", s.Symbol, percentage.Float64())
_, err := s.orderExecutor.SubmitOrders(ctx, *submitOrder)
if err != nil {
bbgo.Notify("close %s position error", s.Symbol)
log.WithError(err).Errorf("close %s position error", s.Symbol)
}
return err
}
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
} }
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error { func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
@ -205,7 +185,6 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.ProfitStats = types.NewProfitStats(s.Market) s.ProfitStats = types.NewProfitStats(s.Market)
} }
// trade stats
if s.TradeStats == nil { if s.TradeStats == nil {
s.TradeStats = &types.TradeStats{} s.TradeStats = &types.TradeStats{}
} }
@ -231,6 +210,9 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.orderExecutor.BindEnvironment(s.Environment) s.orderExecutor.BindEnvironment(s.Environment)
s.orderExecutor.BindProfitStats(s.ProfitStats) s.orderExecutor.BindProfitStats(s.ProfitStats)
s.orderExecutor.BindTradeStats(s.TradeStats) s.orderExecutor.BindTradeStats(s.TradeStats)
s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
bbgo.Sync(s)
})
s.orderExecutor.Bind() s.orderExecutor.Bind()
store, _ := session.MarketDataStore(s.Symbol) store, _ := session.MarketDataStore(s.Symbol)

View File

@ -4,32 +4,23 @@ import (
"context" "context"
"fmt" "fmt"
"math" "math"
"time"
"github.com/c9s/bbgo/pkg/indicator" "github.com/c9s/bbgo/pkg/indicator"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/service"
"github.com/c9s/bbgo/pkg/types"
"github.com/muesli/clusters" "github.com/muesli/clusters"
"github.com/muesli/kmeans" "github.com/muesli/kmeans"
)
// TODO: "github.com/c9s/bbgo/pkg/bbgo"
// 1) add option for placing orders only when in neutral band "github.com/c9s/bbgo/pkg/fixedpoint"
// 2) add option for only placing buy orders when price is below the SMA line "github.com/c9s/bbgo/pkg/types"
)
const ID = "rsmaker" const ID = "rsmaker"
const stateKey = "state-v1"
var defaultFeeRate = fixedpoint.NewFromFloat(0.001)
var notionModifier = fixedpoint.NewFromFloat(1.1) var notionModifier = fixedpoint.NewFromFloat(1.1)
var two = fixedpoint.NewFromInt(2)
var log = logrus.WithField("strategy", ID) var log = logrus.WithField("strategy", ID)
@ -37,20 +28,9 @@ func init() {
bbgo.RegisterStrategy(ID, &Strategy{}) bbgo.RegisterStrategy(ID, &Strategy{})
} }
type State struct {
Position *types.Position `json:"position,omitempty"`
ProfitStats types.ProfitStats `json:"profitStats,omitempty"`
}
type BollingerSetting struct {
types.IntervalWindow
BandWidth float64 `json:"bandWidth"`
}
type Strategy struct { type Strategy struct {
*bbgo.Graceful *bbgo.Graceful
*bbgo.Notifiability *bbgo.Notifiability
*bbgo.Persistence
Environment *bbgo.Environment Environment *bbgo.Environment
StandardIndicatorSet *bbgo.StandardIndicatorSet StandardIndicatorSet *bbgo.StandardIndicatorSet
@ -114,11 +94,11 @@ type Strategy struct {
// NeutralBollinger is the smaller range of the bollinger band // NeutralBollinger is the smaller range of the bollinger band
// If price is in this band, it usually means the price is oscillating. // If price is in this band, it usually means the price is oscillating.
// If price goes out of this band, we tend to not place sell orders or buy orders // If price goes out of this band, we tend to not place sell orders or buy orders
NeutralBollinger *BollingerSetting `json:"neutralBollinger"` NeutralBollinger *types.BollingerSetting `json:"neutralBollinger"`
// DefaultBollinger is the wide range of the bollinger band // DefaultBollinger is the wide range of the bollinger band
// for controlling your exposure position // for controlling your exposure position
DefaultBollinger *BollingerSetting `json:"defaultBollinger"` DefaultBollinger *types.BollingerSetting `json:"defaultBollinger"`
// DowntrendSkew is the order quantity skew for normal downtrend band. // DowntrendSkew is the order quantity skew for normal downtrend band.
// The price is still in the default bollinger band. // The price is still in the default bollinger band.
@ -140,21 +120,18 @@ type Strategy struct {
ShadowProtection bool `json:"shadowProtection"` ShadowProtection bool `json:"shadowProtection"`
ShadowProtectionRatio fixedpoint.Value `json:"shadowProtectionRatio"` ShadowProtectionRatio fixedpoint.Value `json:"shadowProtectionRatio"`
Position *types.Position `persistence:"position"`
ProfitStats *types.ProfitStats `persistence:"profit_stats"`
TradeStats *types.TradeStats `persistence:"trade_stats"`
bbgo.SmartStops bbgo.SmartStops
session *bbgo.ExchangeSession session *bbgo.ExchangeSession
book *types.StreamOrderBook orderExecutor *bbgo.GeneralOrderExecutor
book *types.StreamOrderBook
state *State
activeMakerOrders *bbgo.ActiveOrderBook
orderStore *bbgo.OrderStore
tradeCollector *bbgo.TradeCollector
groupID uint32 groupID uint32
stopC chan struct{}
// defaultBoll is the BOLLINGER indicator we used for predicting the price. // defaultBoll is the BOLLINGER indicator we used for predicting the price.
defaultBoll *indicator.BOLL defaultBoll *indicator.BOLL
@ -177,24 +154,7 @@ func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{ session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
Interval: s.Interval, Interval: s.Interval,
}) })
// s.SmartStops.Subscribe(session)
//session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
// Interval: types.Interval12h.String(),
//})
//if s.DefaultBollinger != nil && s.DefaultBollinger.Interval != "" {
// session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
// Interval: string(s.DefaultBollinger.Interval),
// })
//}
//
//if s.NeutralBollinger != nil && s.NeutralBollinger.Interval != "" {
// session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
// Interval: string(s.NeutralBollinger.Interval),
// })
//}
//s.SmartStops.Subscribe(session)
} }
func (s *Strategy) Validate() error { func (s *Strategy) Validate() error {
@ -206,50 +166,14 @@ func (s *Strategy) Validate() error {
} }
func (s *Strategy) CurrentPosition() *types.Position { func (s *Strategy) CurrentPosition() *types.Position {
return s.state.Position return s.Position
} }
func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error { func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error {
base := s.state.Position.GetBase() return s.orderExecutor.ClosePosition(ctx, percentage)
if base.IsZero() {
return fmt.Errorf("no opened %s position", s.state.Position.Symbol)
}
// make it negative
quantity := base.Mul(percentage).Abs()
side := types.SideTypeBuy
if base.Sign() > 0 {
side = types.SideTypeSell
}
if quantity.Compare(s.Market.MinQuantity) < 0 {
return fmt.Errorf("order quantity %v is too small, less than %v", quantity, s.Market.MinQuantity)
}
submitOrder := types.SubmitOrder{
Symbol: s.Symbol,
Side: side,
Type: types.OrderTypeMarket,
Quantity: quantity,
Market: s.Market,
}
s.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder)
createdOrders, err := s.session.Exchange.SubmitOrders(ctx, submitOrder)
if err != nil {
log.WithError(err).Errorf("can not place position close order")
}
s.orderStore.Add(createdOrders...)
s.activeMakerOrders.Add(createdOrders...)
s.tradeCollector.Process()
return err
} }
// StrategyController // StrategyController
func (s *Strategy) GetStatus() types.StrategyStatus { func (s *Strategy) GetStatus() types.StrategyStatus {
return s.status return s.status
} }
@ -257,23 +181,11 @@ func (s *Strategy) GetStatus() types.StrategyStatus {
func (s *Strategy) Suspend(ctx context.Context) error { func (s *Strategy) Suspend(ctx context.Context) error {
s.status = types.StrategyStatusStopped s.status = types.StrategyStatusStopped
// Cancel all order if err := s.orderExecutor.GracefulCancel(ctx); err != nil {
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
log.WithError(err).Errorf("graceful cancel order error") log.WithError(err).Errorf("graceful cancel order error")
s.Notify("graceful cancel order error")
} else {
s.Notify("All orders cancelled.")
}
s.tradeCollector.Process()
// Save state
if err := s.SaveState(); err != nil {
log.WithError(err).Errorf("can not save state: %+v", s.state)
} else {
log.Infof("%s position is saved.", s.Symbol)
} }
bbgo.Sync(s)
return nil return nil
} }
@ -283,57 +195,6 @@ func (s *Strategy) Resume(ctx context.Context) error {
return nil return nil
} }
//func (s *Strategy) EmergencyStop(ctx context.Context) error {
// // Close 100% position
// percentage, _ := fixedpoint.NewFromString("100%")
// err := s.ClosePosition(ctx, percentage)
//
// // Suspend strategy
// _ = s.Suspend(ctx)
//
// return err
//}
func (s *Strategy) SaveState() error {
if err := s.Persistence.Save(s.state, ID, s.Symbol, stateKey); err != nil {
return err
}
log.Infof("state is saved => %+v", s.state)
return nil
}
func (s *Strategy) LoadState() error {
var state State
// load position
if err := s.Persistence.Load(&state, ID, s.Symbol, stateKey); err != nil {
if err != service.ErrPersistenceNotExists {
return err
}
s.state = &State{}
} else {
s.state = &state
log.Infof("state is restored: %+v", s.state)
}
// if position is nil, we need to allocate a new position for calculation
if s.state.Position == nil {
s.state.Position = types.NewPositionFromMarket(s.Market)
}
// init profit states
s.state.ProfitStats.Symbol = s.Market.Symbol
s.state.ProfitStats.BaseCurrency = s.Market.BaseCurrency
s.state.ProfitStats.QuoteCurrency = s.Market.QuoteCurrency
if s.state.ProfitStats.AccumulatedSince == 0 {
s.state.ProfitStats.AccumulatedSince = time.Now().Unix()
}
return nil
}
func (s *Strategy) getCurrentAllowedExposurePosition(bandPercentage float64) (fixedpoint.Value, error) { func (s *Strategy) getCurrentAllowedExposurePosition(bandPercentage float64) (fixedpoint.Value, error) {
if s.DynamicExposurePositionScale != nil { if s.DynamicExposurePositionScale != nil {
v, err := s.DynamicExposurePositionScale.Scale(bandPercentage) v, err := s.DynamicExposurePositionScale.Scale(bandPercentage)
@ -346,16 +207,7 @@ func (s *Strategy) getCurrentAllowedExposurePosition(bandPercentage float64) (fi
return s.MaxExposurePosition, nil return s.MaxExposurePosition, nil
} }
func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExecutor, midPrice fixedpoint.Value, klines []*types.KLine) { func (s *Strategy) placeOrders(ctx context.Context, midPrice fixedpoint.Value, klines []*types.KLine) {
//bidSpread := s.Spread
//if s.BidSpread.Sign() > 0 {
// bidSpread = s.BidSpread
//}
//
//askSpread := s.Spread
//if s.AskSpread.Sign() > 0 {
// askSpread = s.AskSpread
//}
// preprocessing // preprocessing
max := 0. max := 0.
min := 100000. min := 100000.
@ -373,21 +225,21 @@ func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExec
} }
mv = mv / 50 mv = mv / 50
//logrus.Info(max, min) // logrus.Info(max, min)
// set up a random two-dimensional data set (float64 values between 0.0 and 1.0) // set up a random two-dimensional data set (float64 values between 0.0 and 1.0)
var d clusters.Observations var d clusters.Observations
for x := 0; x < 50; x++ { for x := 0; x < 50; x++ {
//if klines[x].High.Float64() < max || klines[x].Low.Float64() > min { // if klines[x].High.Float64() < max || klines[x].Low.Float64() > min {
if klines[x].Volume.Float64() > mv*0.3 { if klines[x].Volume.Float64() > mv*0.3 {
d = append(d, clusters.Coordinates{ d = append(d, clusters.Coordinates{
klines[x].High.Float64(), klines[x].High.Float64(),
klines[x].Low.Float64(), klines[x].Low.Float64(),
//klines[x].Open.Float64(), // klines[x].Open.Float64(),
//klines[x].Close.Float64(), // klines[x].Close.Float64(),
//klines[x].Volume.Float64(), // klines[x].Volume.Float64(),
}) })
} }
//} // }
} }
log.Info(len(d)) log.Info(len(d))
@ -396,16 +248,16 @@ func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExec
km := kmeans.New() km := kmeans.New()
clusters, err := km.Partition(d, 3) clusters, err := km.Partition(d, 3)
//for _, c := range clusters { // for _, c := range clusters {
//fmt.Printf("Centered at x: %.2f y: %.2f\n", c.Center[0], c.Center[1]) // fmt.Printf("Centered at x: %.2f y: %.2f\n", c.Center[0], c.Center[1])
//fmt.Printf("Matching data points: %+v\n\n", c.Observations) // fmt.Printf("Matching data points: %+v\n\n", c.Observations)
//} // }
// clustered virtual kline_1's mid price // clustered virtual kline_1's mid price
//vk1mp := fixedpoint.NewFromFloat((clusters[0].Center[0] + clusters[0].Center[1]) / 2.) // vk1mp := fixedpoint.NewFromFloat((clusters[0].Center[0] + clusters[0].Center[1]) / 2.)
// clustered virtual kline_2's mid price // clustered virtual kline_2's mid price
//vk2mp := fixedpoint.NewFromFloat((clusters[1].Center[0] + clusters[1].Center[1]) / 2.) // vk2mp := fixedpoint.NewFromFloat((clusters[1].Center[0] + clusters[1].Center[1]) / 2.)
// clustered virtual kline_3's mid price // clustered virtual kline_3's mid price
//vk3mp := fixedpoint.NewFromFloat((clusters[2].Center[0] + clusters[2].Center[1]) / 2.) // vk3mp := fixedpoint.NewFromFloat((clusters[2].Center[0] + clusters[2].Center[1]) / 2.)
// clustered virtual kline_1's high price // clustered virtual kline_1's high price
vk1hp := fixedpoint.NewFromFloat(clusters[0].Center[0]) vk1hp := fixedpoint.NewFromFloat(clusters[0].Center[0])
@ -421,50 +273,43 @@ func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExec
// clustered virtual kline_3's low price // clustered virtual kline_3's low price
vk3lp := fixedpoint.NewFromFloat(clusters[2].Center[1]) vk3lp := fixedpoint.NewFromFloat(clusters[2].Center[1])
askPrice := fixedpoint.NewFromFloat(math.Max(math.Max(vk1hp.Float64(), vk2hp.Float64()), vk3hp.Float64())) //fixedpoint.NewFromFloat(math.Max(math.Max(vk1mp.Float64(), vk2mp.Float64()), vk3mp.Float64())) askPrice := fixedpoint.NewFromFloat(math.Max(math.Max(vk1hp.Float64(), vk2hp.Float64()), vk3hp.Float64())) // fixedpoint.NewFromFloat(math.Max(math.Max(vk1mp.Float64(), vk2mp.Float64()), vk3mp.Float64()))
bidPrice := fixedpoint.NewFromFloat(math.Min(math.Min(vk1lp.Float64(), vk2lp.Float64()), vk3lp.Float64())) //fixedpoint.NewFromFloat(math.Min(math.Min(vk1mp.Float64(), vk2mp.Float64()), vk3mp.Float64())) bidPrice := fixedpoint.NewFromFloat(math.Min(math.Min(vk1lp.Float64(), vk2lp.Float64()), vk3lp.Float64())) // fixedpoint.NewFromFloat(math.Min(math.Min(vk1mp.Float64(), vk2mp.Float64()), vk3mp.Float64()))
//if vk1mp.Compare(vk2mp) > 0 { // if vk1mp.Compare(vk2mp) > 0 {
// askPrice = vk1mp //.Mul(fixedpoint.NewFromFloat(1.001)) // askPrice = vk1mp //.Mul(fixedpoint.NewFromFloat(1.001))
// bidPrice = vk2mp //.Mul(fixedpoint.NewFromFloat(0.999)) // bidPrice = vk2mp //.Mul(fixedpoint.NewFromFloat(0.999))
//} else if vk1mp.Compare(vk2mp) < 0 { // } else if vk1mp.Compare(vk2mp) < 0 {
// askPrice = vk2mp //.Mul(fixedpoint.NewFromFloat(1.001)) // askPrice = vk2mp //.Mul(fixedpoint.NewFromFloat(1.001))
// bidPrice = vk1mp //.Mul(fixedpoint.NewFromFloat(0.999)) // bidPrice = vk1mp //.Mul(fixedpoint.NewFromFloat(0.999))
//} // }
//midPrice.Mul(fixedpoint.One.Add(askSpread)) // midPrice.Mul(fixedpoint.One.Add(askSpread))
//midPrice.Mul(fixedpoint.One.Sub(bidSpread)) // midPrice.Mul(fixedpoint.One.Sub(bidSpread))
base := s.state.Position.GetBase() base := s.Position.GetBase()
//balances := s.session.GetAccount().Balances() // balances := s.session.GetAccount().Balances()
//log.Infof("mid price:%v spread: %s ask:%v bid: %v position: %s",
// midPrice,
// s.Spread.Percentage(),
// askPrice,
// bidPrice,
// s.state.Position,
//)
canSell := true canSell := true
canBuy := true canBuy := true
//predMidPrice := (askPrice + bidPrice) / 2. // predMidPrice := (askPrice + bidPrice) / 2.
//if midPrice.Float64() > predMidPrice.Float64() { // if midPrice.Float64() > predMidPrice.Float64() {
// bidPrice = predMidPrice.Mul(fixedpoint.NewFromFloat(0.999)) // bidPrice = predMidPrice.Mul(fixedpoint.NewFromFloat(0.999))
//} // }
// //
//if midPrice.Float64() < predMidPrice.Float64() { // if midPrice.Float64() < predMidPrice.Float64() {
// askPrice = predMidPrice.Mul(fixedpoint.NewFromFloat(1.001)) // askPrice = predMidPrice.Mul(fixedpoint.NewFromFloat(1.001))
//} // }
// //
//if midPrice.Float64() > askPrice.Float64() { // if midPrice.Float64() > askPrice.Float64() {
// canBuy = false // canBuy = false
// askPrice = midPrice.Mul(fixedpoint.NewFromFloat(1.001)) // askPrice = midPrice.Mul(fixedpoint.NewFromFloat(1.001))
//} // }
// //
//if midPrice.Float64() < bidPrice.Float64() { // if midPrice.Float64() < bidPrice.Float64() {
// canSell = false // canSell = false
// bidPrice = midPrice.Mul(fixedpoint.NewFromFloat(0.999)) // bidPrice = midPrice.Mul(fixedpoint.NewFromFloat(0.999))
//} // }
sellQuantity := s.QuantityOrAmount.CalculateQuantity(askPrice) sellQuantity := s.QuantityOrAmount.CalculateQuantity(askPrice)
buyQuantity := s.QuantityOrAmount.CalculateQuantity(bidPrice) buyQuantity := s.QuantityOrAmount.CalculateQuantity(bidPrice)
@ -491,8 +336,8 @@ func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExec
var submitBuyOrders []types.SubmitOrder var submitBuyOrders []types.SubmitOrder
var submitSellOrders []types.SubmitOrder var submitSellOrders []types.SubmitOrder
//baseBalance, hasBaseBalance := balances[s.Market.BaseCurrency] // baseBalance, hasBaseBalance := balances[s.Market.BaseCurrency]
//quoteBalance, hasQuoteBalance := balances[s.Market.QuoteCurrency] // quoteBalance, hasQuoteBalance := balances[s.Market.QuoteCurrency]
downBand := s.defaultBoll.LastDownBand() downBand := s.defaultBoll.LastDownBand()
upBand := s.defaultBoll.LastUpBand() upBand := s.defaultBoll.LastUpBand()
@ -522,106 +367,13 @@ func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExec
} }
} }
//if s.ShadowProtection && kline != nil {
// switch kline.Direction() {
// case types.DirectionDown:
// shadowHeight := kline.GetLowerShadowHeight()
// shadowRatio := kline.GetLowerShadowRatio()
// if shadowHeight.IsZero() && shadowRatio.Compare(s.ShadowProtectionRatio) < 0 {
// log.Infof("%s shadow protection enabled, lower shadow ratio %v < %v", s.Symbol, shadowRatio, s.ShadowProtectionRatio)
// canBuy = false
// }
// case types.DirectionUp:
// shadowHeight := kline.GetUpperShadowHeight()
// shadowRatio := kline.GetUpperShadowRatio()
// if shadowHeight.IsZero() || shadowRatio.Compare(s.ShadowProtectionRatio) < 0 {
// log.Infof("%s shadow protection enabled, upper shadow ratio %v < %v", s.Symbol, shadowRatio, s.ShadowProtectionRatio)
// canSell = false
// }
// }
//}
// Apply quantity skew
// CASE #1:
// WHEN: price is in the neutral bollginer band (window 1) == neutral
// THEN: we don't apply skew
// CASE #2:
// WHEN: price is in the upper band (window 2 > price > window 1) == upTrend
// THEN: we apply upTrend skew
// CASE #3:
// WHEN: price is in the lower band (window 2 < price < window 1) == downTrend
// THEN: we apply downTrend skew
// CASE #4:
// WHEN: price breaks the lower band (price < window 2) == strongDownTrend
// THEN: we apply strongDownTrend skew
// CASE #5:
// WHEN: price breaks the upper band (price > window 2) == strongUpTrend
// THEN: we apply strongUpTrend skew
//if s.TradeInBand {
// if !inBetween(midPrice.Float64(), s.neutralBoll.LastDownBand(), s.neutralBoll.LastUpBand()) {
// log.Infof("tradeInBand is set, skip placing orders when the price is outside of the band")
// return
// }
//}
//revmacd := s.detectPriceTrend(s.neutralBoll, midPrice.Float64())
//switch revmacd {
//case NeutralTrend:
// // do nothing
//
//case UpTrend:
// skew := s.UptrendSkew
// buyOrder.Quantity = fixedpoint.Max(s.Market.MinQuantity, sellOrder.Quantity.Mul(skew))
//
//case DownTrend:
// skew := s.DowntrendSkew
// ratio := fixedpoint.One.Div(skew)
// sellOrder.Quantity = fixedpoint.Max(s.Market.MinQuantity, buyOrder.Quantity.Mul(ratio))
//
//}
//if !hasQuoteBalance || buyOrder.Quantity.Mul(buyOrder.Price).Compare(quoteBalance.Available) > 0 {
// canBuy = false
//}
//
//if !hasBaseBalance || sellOrder.Quantity.Compare(baseBalance.Available) > 0 {
// canSell = false
//}
//if midPrice.Compare(s.state.Position.AverageCost.Mul(fixedpoint.One.Add(s.MinProfitSpread))) < 0 {
// canSell = false
//}
//if s.Long != nil && *s.Long && base.Sub(sellOrder.Quantity).Sign() < 0 {
// canSell = false
//}
//
//if s.BuyBelowNeutralSMA && midPrice.Float64() > s.neutralBoll.LastSMA() {
// canBuy = false
//}
if canSell { if canSell {
submitSellOrders = append(submitSellOrders, sellOrder) submitSellOrders = append(submitSellOrders, sellOrder)
//sellOrder = s.adjustOrderPrice(sellOrder, false)
//submitSellOrders = append(submitSellOrders, sellOrder)
//sellOrder = s.adjustOrderPrice(sellOrder, false)
//submitSellOrders = append(submitSellOrders, sellOrder)
} }
if canBuy { if canBuy {
submitBuyOrders = append(submitBuyOrders, buyOrder) submitBuyOrders = append(submitBuyOrders, buyOrder)
//buyOrder = s.adjustOrderPrice(buyOrder, true)
//submitBuyOrders = append(submitBuyOrders, buyOrder)
//buyOrder = s.adjustOrderPrice(buyOrder, true)
//submitBuyOrders = append(submitBuyOrders, buyOrder)
} }
// condition for lower the average cost
/*
if midPrice < s.state.Position.AverageCost.MulFloat64(1.0-s.MinProfitSpread.Float64()) && canBuy {
submitOrders = append(submitOrders, buyOrder)
}
*/
for i := range submitBuyOrders { for i := range submitBuyOrders {
submitBuyOrders[i] = s.adjustOrderQuantity(submitBuyOrders[i]) submitBuyOrders[i] = s.adjustOrderQuantity(submitBuyOrders[i])
} }
@ -630,44 +382,12 @@ func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExec
submitSellOrders[i] = s.adjustOrderQuantity(submitSellOrders[i]) submitSellOrders[i] = s.adjustOrderQuantity(submitSellOrders[i])
} }
createdBuyOrders, err := orderExecutor.SubmitOrders(ctx, submitBuyOrders...) if _, err := s.orderExecutor.SubmitOrders(ctx, submitBuyOrders...); err != nil {
if err != nil { log.WithError(err).Errorf("can not place orders")
log.WithError(err).Errorf("can not place ping pong orders")
} }
s.orderStore.Add(createdBuyOrders...) if _, err := s.orderExecutor.SubmitOrders(ctx, submitSellOrders...); err != nil {
s.activeMakerOrders.Add(createdBuyOrders...) log.WithError(err).Errorf("can not place orders")
createdSellOrders, err := orderExecutor.SubmitOrders(ctx, submitSellOrders...)
if err != nil {
log.WithError(err).Errorf("can not place ping pong orders")
} }
s.orderStore.Add(createdSellOrders...)
s.activeMakerOrders.Add(createdSellOrders...)
}
type PriceTrend string
const (
NeutralTrend PriceTrend = "neutral"
UpTrend PriceTrend = "upTrend"
DownTrend PriceTrend = "downTrend"
UnknownTrend PriceTrend = "unknown"
)
func (s *Strategy) detectPriceTrend(inc *indicator.BOLL, price float64) PriceTrend {
if inBetween(price, inc.LastDownBand(), inc.LastUpBand()) {
return NeutralTrend
}
if price < inc.LastDownBand() {
return DownTrend
}
if price > inc.LastUpBand() {
return UpTrend
}
return UnknownTrend
} }
func (s *Strategy) adjustOrderQuantity(submitOrder types.SubmitOrder) types.SubmitOrder { func (s *Strategy) adjustOrderQuantity(submitOrder types.SubmitOrder) types.SubmitOrder {
@ -682,187 +402,66 @@ func (s *Strategy) adjustOrderQuantity(submitOrder types.SubmitOrder) types.Subm
return submitOrder return submitOrder
} }
func (s *Strategy) adjustOrderPrice(submitOrder types.SubmitOrder, side bool) types.SubmitOrder { func (s *Strategy) Run(ctx context.Context, session *bbgo.ExchangeSession) error {
instanceID := fmt.Sprintf("%s-%s", ID, s.Symbol)
if side {
submitOrder.Price = submitOrder.Price.Mul(fixedpoint.NewFromFloat(0.995))
} else {
submitOrder.Price = submitOrder.Price.Mul(fixedpoint.NewFromFloat(1.005))
}
return submitOrder
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
// StrategyController
s.status = types.StrategyStatusRunning s.status = types.StrategyStatusRunning
//if s.DisableShort { if s.Position == nil {
// s.Long = &[]bool{true}[0] s.Position = types.NewPositionFromMarket(s.Market)
//} }
//
//if s.MinProfitSpread.IsZero() { if s.ProfitStats == nil {
// s.MinProfitSpread = fixedpoint.NewFromFloat(0.001) s.ProfitStats = types.NewProfitStats(s.Market)
//} }
//
//if s.UptrendSkew.IsZero() { if s.TradeStats == nil {
// s.UptrendSkew = fixedpoint.NewFromFloat(1.0 / 1.2) s.TradeStats = &types.TradeStats{}
//} }
//
//if s.DowntrendSkew.IsZero() {
// s.DowntrendSkew = fixedpoint.NewFromFloat(1.2)
//}
//
//if s.ShadowProtectionRatio.IsZero() {
// s.ShadowProtectionRatio = fixedpoint.NewFromFloat(0.01)
//}
// initial required information // initial required information
s.session = session s.session = session
s.orderExecutor = bbgo.NewGeneralOrderExecutor(session, s.Symbol, ID, instanceID, s.Position)
s.orderExecutor.BindEnvironment(s.Environment)
s.orderExecutor.BindProfitStats(s.ProfitStats)
s.orderExecutor.BindTradeStats(s.TradeStats)
s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
bbgo.Sync(s)
})
s.orderExecutor.Bind()
s.neutralBoll = s.StandardIndicatorSet.BOLL(s.NeutralBollinger.IntervalWindow, s.NeutralBollinger.BandWidth) s.neutralBoll = s.StandardIndicatorSet.BOLL(s.NeutralBollinger.IntervalWindow, s.NeutralBollinger.BandWidth)
s.defaultBoll = s.StandardIndicatorSet.BOLL(s.DefaultBollinger.IntervalWindow, s.DefaultBollinger.BandWidth) s.defaultBoll = s.StandardIndicatorSet.BOLL(s.DefaultBollinger.IntervalWindow, s.DefaultBollinger.BandWidth)
// calculate group id for orders // s.SmartStops.RunStopControllers(ctx, session, s.tradeCollector)
instanceID := fmt.Sprintf("%s-%s", ID, s.Symbol)
//s.groupID = max.GenerateGroupID(instanceID)
log.Infof("using group id %d from fnv(%s)", s.groupID, instanceID)
// restore state
if err := s.LoadState(); err != nil {
return err
}
s.state.Position.Strategy = ID
s.state.Position.StrategyInstanceID = instanceID
//s.stopC = make(chan struct{})
s.activeMakerOrders = bbgo.NewActiveOrderBook(s.Symbol)
s.activeMakerOrders.BindStream(session.UserDataStream)
s.orderStore = bbgo.NewOrderStore(s.Symbol)
s.orderStore.BindStream(session.UserDataStream)
s.tradeCollector = bbgo.NewTradeCollector(s.Symbol, s.state.Position, s.orderStore)
//s.tradeCollector.OnTrade(func(trade types.Trade, profit, netProfit fixedpoint.Value) {
// // StrategyController
// if s.status != types.StrategyStatusRunning {
// return
// }
//
// s.Notifiability.Notify(trade)
// s.state.ProfitStats.AddTrade(trade)
//
// if profit.Compare(fixedpoint.Zero) == 0 {
// s.Environment.RecordPosition(s.state.Position, trade, nil)
// } else {
// log.Infof("%s generated profit: %v", s.Symbol, profit)
// p := s.state.Position.NewProfit(trade, profit, netProfit)
// p.Strategy = ID
// p.StrategyInstanceID = instanceID
// s.Notify(&p)
//
// s.state.ProfitStats.AddProfit(p)
// s.Notify(&s.state.ProfitStats)
//
// s.Environment.RecordPosition(s.state.Position, trade, &p)
// }
//})
//
//s.tradeCollector.OnPositionUpdate(func(position *types.Position) {
// log.Infof("position changed: %s", s.state.Position)
// s.Notify(s.state.Position)
//})
s.tradeCollector.BindStream(session.UserDataStream)
//s.SmartStops.RunStopControllers(ctx, session, s.tradeCollector)
//session.UserDataStream.OnStart(func() {
//if s.UseTickerPrice {
// ticker, err := s.session.Exchange.QueryTicker(ctx, s.Symbol)
// if err != nil {
// return
// }
//
// midPrice := ticker.Buy.Add(ticker.Sell).Div(two)
// s.placeOrders(ctx, orderExecutor, midPrice, nil)
//} else {
// if price, ok := session.LastPrice(s.Symbol); ok {
// s.placeOrders(ctx, orderExecutor, price, nil)
// }
//}
//})
var klines []*types.KLine var klines []*types.KLine
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) { session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
// StrategyController // StrategyController
if s.status != types.StrategyStatusRunning { if s.status != types.StrategyStatusRunning {
return return
} }
//if kline.Symbol != s.Symbol || kline.Interval != s.Interval { // if kline.Symbol != s.Symbol || kline.Interval != s.Interval {
// return // return
//} // }
if kline.Interval == s.Interval { if kline.Interval == s.Interval {
klines = append(klines, &kline) klines = append(klines, &kline)
} }
if len(klines) > 50 { if len(klines) > 50 {
//if s.UseTickerPrice {
// ticker, err := s.session.Exchange.QueryTicker(ctx, s.Symbol)
// if err != nil {
// return
// }
//
// midPrice := ticker.Buy.Add(ticker.Sell).Div(two)
// log.Infof("using ticker price: bid %v / ask %v, mid price %v", ticker.Buy, ticker.Sell, midPrice)
// s.placeOrders(ctx, orderExecutor, midPrice, klines[len(klines)-100:])
// s.tradeCollector.Process()
//}
//else {
if kline.Interval == s.Interval { if kline.Interval == s.Interval {
if err := s.orderExecutor.GracefulCancel(ctx); err != nil {
//if s.state.Position.AverageCost.Div(kline.Close).Float64() < 0.999 {
// s.ClosePosition(ctx, fixedpoint.One)
// s.tradeCollector.Process()
//}
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
log.WithError(err).Errorf("graceful cancel order error") log.WithError(err).Errorf("graceful cancel order error")
} }
// check if there is a canceled order had partially filled. s.placeOrders(ctx, kline.Close, klines[len(klines)-50:])
s.tradeCollector.Process()
s.placeOrders(ctx, orderExecutor, kline.Close, klines[len(klines)-50:])
s.tradeCollector.Process()
} }
//}
} }
}) })
// s.book = types.NewStreamBook(s.Symbol)
// s.book.BindStreamForBackground(session.MarketDataStream)
//s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
// //defer wg.Done()
// //close(s.stopC)
//
// if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
// log.WithError(err).Errorf("graceful cancel order error")
// }
//
// s.tradeCollector.Process()
//
// if err := s.SaveState(); err != nil {
// log.WithError(err).Errorf("can not save state: %+v", s.state)
// }
//})
return nil return nil
} }

View File

@ -3,9 +3,10 @@ package supertrend
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/c9s/bbgo/pkg/util"
"sync" "sync"
"github.com/c9s/bbgo/pkg/util"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -256,9 +257,7 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
// Sync position to redis on trade // Sync position to redis on trade
s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) { s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
if err := s.Persistence.Sync(s); err != nil { bbgo.Sync(s)
log.WithError(err).Errorf("can not sync state to persistence")
}
}) })
s.stopC = make(chan struct{}) s.stopC = make(chan struct{})

View File

@ -15,8 +15,6 @@ import (
const ID = "support" const ID = "support"
const stateKey = "state-v1"
var log = logrus.WithField("strategy", ID) var log = logrus.WithField("strategy", ID)
var zeroiw = types.IntervalWindow{} var zeroiw = types.IntervalWindow{}
@ -352,7 +350,7 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.OnSuspend(func() { s.OnSuspend(func() {
// Cancel all order // Cancel all order
_ = s.orderExecutor.GracefulCancel(ctx) _ = s.orderExecutor.GracefulCancel(ctx)
_ = s.Persistence.Sync(s) bbgo.Sync(s)
}) })
s.OnEmergencyStop(func() { s.OnEmergencyStop(func() {

View File

@ -13,7 +13,6 @@ import (
"github.com/c9s/bbgo/pkg/bbgo" "github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint" "github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/service"
"github.com/c9s/bbgo/pkg/types" "github.com/c9s/bbgo/pkg/types"
"github.com/c9s/bbgo/pkg/util" "github.com/c9s/bbgo/pkg/util"
) )
@ -137,7 +136,6 @@ func (a *Address) UnmarshalJSON(body []byte) error {
type Strategy struct { type Strategy struct {
*bbgo.Graceful *bbgo.Graceful
*bbgo.Persistence
Interval types.Duration `json:"interval"` Interval types.Duration `json:"interval"`
@ -158,7 +156,7 @@ type Strategy struct {
Verbose bool `json:"verbose"` Verbose bool `json:"verbose"`
state *State State *State `persistence:"state"`
} }
func (s *Strategy) ID() string { func (s *Strategy) ID() string {
@ -235,23 +233,23 @@ func (s *Strategy) checkBalance(ctx context.Context, sessions map[string]*bbgo.E
requiredAmount = requiredAmount.Add(toAddress.ForeignFee) requiredAmount = requiredAmount.Add(toAddress.ForeignFee)
} }
if s.state != nil { if s.State != nil {
if s.MaxDailyNumberOfTransfer > 0 { if s.MaxDailyNumberOfTransfer > 0 {
if s.state.DailyNumberOfTransfers >= s.MaxDailyNumberOfTransfer { if s.State.DailyNumberOfTransfers >= s.MaxDailyNumberOfTransfer {
bbgo.Notify("⚠️ Exceeded %s max daily number of transfers %d (current %d), skipping transfer...", bbgo.Notify("⚠️ Exceeded %s max daily number of transfers %d (current %d), skipping transfer...",
s.Asset, s.Asset,
s.MaxDailyNumberOfTransfer, s.MaxDailyNumberOfTransfer,
s.state.DailyNumberOfTransfers) s.State.DailyNumberOfTransfers)
return return
} }
} }
if s.MaxDailyAmountOfTransfer.Sign() > 0 { if s.MaxDailyAmountOfTransfer.Sign() > 0 {
if s.state.DailyAmountOfTransfers.Compare(s.MaxDailyAmountOfTransfer) >= 0 { if s.State.DailyAmountOfTransfers.Compare(s.MaxDailyAmountOfTransfer) >= 0 {
bbgo.Notify("⚠️ Exceeded %s max daily amount of transfers %v (current %v), skipping transfer...", bbgo.Notify("⚠️ Exceeded %s max daily amount of transfers %v (current %v), skipping transfer...",
s.Asset, s.Asset,
s.MaxDailyAmountOfTransfer, s.MaxDailyAmountOfTransfer,
s.state.DailyAmountOfTransfers) s.State.DailyAmountOfTransfers)
return return
} }
} }
@ -275,14 +273,14 @@ func (s *Strategy) checkBalance(ctx context.Context, sessions map[string]*bbgo.E
bbgo.Notify("%s withdrawal request sent", s.Asset) bbgo.Notify("%s withdrawal request sent", s.Asset)
if s.state != nil { if s.State != nil {
if s.state.IsOver24Hours() { if s.State.IsOver24Hours() {
s.state.Reset() s.State.Reset()
} }
s.state.DailyNumberOfTransfers += 1 s.State.DailyNumberOfTransfers += 1
s.state.DailyAmountOfTransfers = s.state.DailyAmountOfTransfers.Add(requiredAmount) s.State.DailyAmountOfTransfers = s.State.DailyAmountOfTransfers.Add(requiredAmount)
s.SaveState() bbgo.Sync(s)
} }
} }
@ -327,15 +325,6 @@ func (s *Strategy) findLowBalanceLevelSession(sessions map[string]*bbgo.Exchange
return nil, balance, nil return nil, balance, nil
} }
func (s *Strategy) SaveState() {
if err := s.Persistence.Save(s.state, ID, s.Asset, stateKey); err != nil {
log.WithError(err).Errorf("can not save state: %+v", s.state)
} else {
log.Infof("%s %s state is saved: %+v", ID, s.Asset, s.state)
bbgo.Notify("%s %s state is saved", ID, s.Asset, s.state)
}
}
func (s *Strategy) newDefaultState() *State { func (s *Strategy) newDefaultState() *State {
return &State{ return &State{
Asset: s.Asset, Asset: s.Asset,
@ -344,42 +333,17 @@ func (s *Strategy) newDefaultState() *State {
} }
} }
func (s *Strategy) LoadState() error {
var state State
if err := s.Persistence.Load(&state, ID, s.Asset, stateKey); err != nil {
if err != service.ErrPersistenceNotExists {
return err
}
s.state = s.newDefaultState()
s.state.Reset()
} else {
// we loaded it successfully
s.state = &state
// update Asset name for legacy caches
s.state.Asset = s.Asset
log.Infof("%s %s state is restored: %+v", ID, s.Asset, s.state)
bbgo.Notify("%s %s state is restored", ID, s.Asset, s.state)
}
return nil
}
func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession) error { func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession) error {
if s.Interval == 0 { if s.Interval == 0 {
return errors.New("interval can not be zero") return errors.New("interval can not be zero")
} }
if err := s.LoadState(); err != nil { if s.State == nil {
return err s.State = s.newDefaultState()
} }
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) { s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done() defer wg.Done()
s.SaveState()
}) })
if s.CheckOnStart { if s.CheckOnStart {

8
pkg/types/bollinger.go Normal file
View File

@ -0,0 +1,8 @@
package types
// BollingerSetting contains the bollinger indicator setting propers
// Interval, Window and BandWidth
type BollingerSetting struct {
IntervalWindow
BandWidth float64 `json:"bandWidth"`
}