Skip to content

Commit 614209e

Browse files
committed
strategy:irr fix kline time syncing
1 parent 612261c commit 614209e

File tree

1 file changed

+32
-72
lines changed

1 file changed

+32
-72
lines changed

pkg/strategy/irr/strategy.go

+32-72
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"os"
77
"sync"
8+
"sync/atomic"
89
"time"
910

1011
"github.com/c9s/bbgo/pkg/bbgo"
@@ -14,7 +15,6 @@ import (
1415
"github.com/c9s/bbgo/pkg/indicator"
1516
"github.com/c9s/bbgo/pkg/types"
1617
"github.com/sirupsen/logrus"
17-
"go.uber.org/atomic"
1818
)
1919

2020
const ID = "irr"
@@ -58,26 +58,15 @@ type Strategy struct {
5858
Nrr *NRR
5959
Ma *indicator.SMA
6060
// realtime book ticker to submit order
61-
obBuyPrice *atomic.Float64
62-
obSellPrice *atomic.Float64
63-
// for posting LO
64-
canBuy bool
65-
canSell bool
61+
obBuyPrice uint64
62+
obSellPrice uint64
6663
// for getting close price
67-
currentTradePrice *atomic.Float64
68-
tradePriceSeries *types.Queue
64+
currentTradePrice uint64
6965
// for negative return rate
7066
openPrice float64
7167
closePrice float64
72-
rtNr *types.Queue
73-
// for moving average reversion
74-
rtMaFast *types.Queue
75-
rtMaSlow *types.Queue
76-
rtMr *types.Queue
7768

78-
// for final alpha (Nr+Mr)/2
79-
rtWeight *types.Queue
80-
stopC chan struct{}
69+
stopC chan struct{}
8170

8271
// StrategyController
8372
bbgo.StrategyController
@@ -346,14 +335,6 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
346335
s.highestPrice = 0
347336
s.lowestPrice = s.sellPrice
348337
}
349-
350-
if trade.Side == types.SideTypeBuy {
351-
s.canSell = true
352-
s.canBuy = false
353-
} else if trade.Side == types.SideTypeSell {
354-
s.canBuy = true
355-
s.canSell = false
356-
}
357338
})
358339

359340
s.InitDrawCommands(&profitSlice, &cumProfitSlice, &cumProfitDollarSlice)
@@ -364,36 +345,9 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
364345
s.orderExecutor.Bind()
365346
s.activeOrders = bbgo.NewActiveOrderBook(s.Symbol)
366347

367-
//back-test only, because 1s delayed a lot
368-
//kLineStore, _ := s.session.MarketDataStore(s.Symbol)
369-
//s.Nrr = &NRR{IntervalWindow: types.IntervalWindow{Window: 2, Interval: s.Interval}, RankingWindow: s.Window}
370-
//s.Nrr.BindK(s.session.MarketDataStream, s.Symbol, s.Interval)
371-
//if klines, ok := kLineStore.KLinesOfInterval(s.Nrr.Interval); ok {
372-
// s.Nrr.LoadK((*klines)[0:])
373-
//}
374-
//s.Ma = &indicator.SMA{IntervalWindow: types.IntervalWindow{Window: s.Window, Interval: s.Interval}}
375-
//s.Ma.BindK(s.session.MarketDataStream, s.Symbol, s.Interval)
376-
//if klines, ok := kLineStore.KLinesOfInterval(s.Ma.Interval); ok {
377-
// s.Ma.LoadK((*klines)[0:])
378-
//}
379-
380-
s.rtNr = types.NewQueue(s.Window)
381-
382-
s.rtMaFast = types.NewQueue(1)
383-
s.rtMaSlow = types.NewQueue(5)
384-
s.rtMr = types.NewQueue(s.Window)
385-
386-
s.rtWeight = types.NewQueue(s.Window)
387-
388-
s.currentTradePrice = atomic.NewFloat64(0.)
389-
s.tradePriceSeries = types.NewQueue(2)
390-
391-
// adverse selection based on order flow dynamics
392-
s.canBuy = true
393-
s.canSell = true
394-
395-
s.closePrice = 0. // atomic.NewFloat64(0)
396-
s.openPrice = 0. //atomic.NewFloat64(0)
348+
atomic.SwapUint64(&s.currentTradePrice, 0.)
349+
s.closePrice = 0.
350+
s.openPrice = 0.
397351
klinDirections := types.NewQueue(100)
398352
started := false
399353
boxOpenPrice := 0.
@@ -404,40 +358,43 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
404358

405359
s.session.MarketDataStream.OnBookTickerUpdate(func(bt types.BookTicker) {
406360
// quote order book price
407-
s.obBuyPrice = atomic.NewFloat64(bt.Buy.Float64())
408-
s.obSellPrice = atomic.NewFloat64(bt.Sell.Float64())
361+
newBid := uint64(bt.Buy.Float64())
362+
newAsk := uint64(bt.Sell.Float64())
363+
atomic.SwapUint64(&s.obBuyPrice, newBid)
364+
atomic.SwapUint64(&s.obSellPrice, newAsk)
409365
})
410366

411367
s.session.MarketDataStream.OnAggTrade(func(trade types.Trade) {
412-
s.currentTradePrice = atomic.NewFloat64(trade.Price.Float64())
368+
tradePrice := uint64(trade.Price.Float64())
369+
atomic.SwapUint64(&s.currentTradePrice, tradePrice)
413370
})
414371

372+
closeTime := <-time.After(time.Duration(s.Interval-int(time.Now().UnixMilli())%s.Interval) * time.Millisecond)
373+
log.Infof("kline close timing synced @ %s", closeTime.Format("2006-01-02 15:04:05.000000"))
415374
go func() {
416-
time.Sleep(time.Duration(s.Interval-int(time.Now().UnixMilli())%s.Interval) * time.Millisecond)
417-
418375
intervalCloseTicker := time.NewTicker(time.Duration(s.Interval) * time.Millisecond)
419376
defer intervalCloseTicker.Stop()
420-
421377
for {
422378
select {
423379
case <-intervalCloseTicker.C:
380+
log.Infof("kline close time @ %s", time.Now().Format("2006-01-02 15:04:05.000000"))
424381

425382
s.orderExecutor.CancelNoWait(context.Background())
426383

427-
if s.currentTradePrice.Load() > 0 {
428-
s.closePrice = s.currentTradePrice.Load()
429-
log.Infof("Close Price: %f", s.closePrice)
384+
if s.currentTradePrice > 0 {
385+
s.closePrice = float64(s.currentTradePrice)
386+
log.Infof("Close Price: %f", float64(s.closePrice))
430387
if s.closePrice > 0 && s.openPrice > 0 {
431388
direction := s.closePrice - s.openPrice
432-
klinDirections.Update(direction)
389+
klinDirections.Update(float64(direction))
433390
regimeShift := klinDirections.Index(0)*klinDirections.Index(1) < 0
434391
if regimeShift && !started {
435-
boxOpenPrice = s.openPrice
392+
boxOpenPrice = float64(s.openPrice)
436393
started = true
437394
boxCounter = 0
438395
log.Infof("box started at price: %f", boxOpenPrice)
439396
} else if regimeShift && started {
440-
boxClosePrice = s.openPrice
397+
boxClosePrice = float64(s.openPrice)
441398
started = false
442399
log.Infof("box ended at price: %f with time length: %d", boxClosePrice, boxCounter)
443400
// box ending, should re-balance position
@@ -451,7 +408,7 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
451408
Side: types.SideTypeSell,
452409
Quantity: s.Quantity,
453410
Type: types.OrderTypeLimitMaker,
454-
Price: fixedpoint.NewFromFloat(s.obSellPrice.Load()),
411+
Price: fixedpoint.NewFromFloat(float64(s.obSellPrice)),
455412
Tag: "irr re-balance: sell",
456413
})
457414
if err != nil {
@@ -463,7 +420,7 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
463420
Side: types.SideTypeBuy,
464421
Quantity: s.Quantity,
465422
Type: types.OrderTypeLimitMaker,
466-
Price: fixedpoint.NewFromFloat(s.obBuyPrice.Load()),
423+
Price: fixedpoint.NewFromFloat(float64(s.obBuyPrice)),
467424
Tag: "irr re-balance: buy",
468425
})
469426
if err != nil {
@@ -484,18 +441,22 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
484441
return
485442
}
486443
}
444+
487445
}()
488446

447+
openTime := <-time.After(time.Duration(s.Interval-int(time.Now().UnixMilli())%s.Interval) * time.Millisecond)
448+
log.Infof("kline open timing synced @ %s", openTime.Format("2006-01-02 15:04:05.000000"))
489449
go func() {
490-
time.Sleep(time.Duration(s.Interval-int(time.Now().UnixMilli())%s.Interval) * time.Millisecond)
491450
intervalOpenTicker := time.NewTicker(time.Duration(s.Interval) * time.Millisecond)
492451
defer intervalOpenTicker.Stop()
493452
for {
494453
select {
495454
case <-intervalOpenTicker.C:
496455
time.Sleep(time.Duration(s.Interval/10) * time.Millisecond)
497-
if s.currentTradePrice.Load() > 0 && s.closePrice > 0 {
498-
s.openPrice = s.currentTradePrice.Load()
456+
log.Infof("kline open time @ %s", time.Now().Format("2006-01-02 15:04:05.000000"))
457+
458+
if s.currentTradePrice > 0 && s.closePrice > 0 {
459+
s.openPrice = float64(s.currentTradePrice)
499460
log.Infof("Open Price: %f", s.openPrice)
500461
}
501462
case <-s.stopC:
@@ -527,7 +488,6 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
527488
_, _ = fmt.Fprintln(os.Stderr, s.TradeStats.String())
528489
_ = s.orderExecutor.GracefulCancel(ctx)
529490
})
530-
531491
return nil
532492
}
533493

0 commit comments

Comments
 (0)