2024-03-04 12:52:01 +00:00
package dca2
import (
"context"
"time"
2024-04-22 05:46:28 +00:00
"github.com/c9s/bbgo/pkg/bbgo"
2024-03-04 12:52:01 +00:00
"github.com/c9s/bbgo/pkg/exchange/retry"
"github.com/c9s/bbgo/pkg/strategy/common"
"github.com/c9s/bbgo/pkg/util"
)
2024-04-22 05:46:28 +00:00
func ( s * Strategy ) syncPeriodically ( ctx context . Context ) {
s . logger . Info ( "sync periodically" )
// sync persistence
syncPersistenceTicker := time . NewTicker ( 1 * time . Hour )
defer syncPersistenceTicker . Stop ( )
// sync active orders
syncActiveOrdersTicker := time . NewTicker ( util . MillisecondsJitter ( 10 * time . Minute , 5 * 60 * 1000 ) )
defer syncActiveOrdersTicker . Stop ( )
2024-03-04 12:52:01 +00:00
for {
select {
case <- ctx . Done ( ) :
return
2024-04-22 05:46:28 +00:00
case <- syncPersistenceTicker . C :
bbgo . Sync ( ctx , s )
case <- syncActiveOrdersTicker . C :
if err := s . syncActiveOrders ( ctx ) ; err != nil {
s . logger . WithError ( err ) . Warn ( err , "failed to sync active orders" )
2024-03-04 12:52:01 +00:00
}
}
}
}
2024-04-22 05:46:28 +00:00
func ( s * Strategy ) syncActiveOrders ( ctx context . Context ) error {
2024-03-21 08:18:48 +00:00
s . logger . Info ( "recover active orders..." )
2024-03-04 12:52:01 +00:00
openOrders , err := retry . QueryOpenOrdersUntilSuccessfulLite ( ctx , s . ExchangeSession . Exchange , s . Symbol )
if err != nil {
s . logger . WithError ( err ) . Warn ( "failed to query open orders" )
return err
}
2024-03-21 08:18:48 +00:00
activeOrders := s . OrderExecutor . ActiveMakerOrders ( )
2024-03-04 12:52:01 +00:00
// update num of open orders metrics
if metricsNumOfOpenOrders != nil {
metricsNumOfOpenOrders . With ( baseLabels ) . Set ( float64 ( len ( openOrders ) ) )
}
// update num of active orders metrics
if metricsNumOfActiveOrders != nil {
2024-03-21 08:18:48 +00:00
metricsNumOfActiveOrders . With ( baseLabels ) . Set ( float64 ( activeOrders . NumOfOrders ( ) ) )
}
if len ( openOrders ) != activeOrders . NumOfOrders ( ) {
s . logger . Warnf ( "num of open orders (%d) and active orders (%d) is different before active orders recovery, please check it." , len ( openOrders ) , activeOrders . NumOfOrders ( ) )
2024-03-04 12:52:01 +00:00
}
opts := common . SyncActiveOrdersOpts {
2024-04-11 03:40:19 +00:00
Logger : s . logger ,
Exchange : s . ExchangeSession . Exchange ,
2024-04-16 05:37:53 +00:00
OrderQueryService : s . collector . queryService ,
2024-04-11 03:40:19 +00:00
ActiveOrderBook : activeOrders ,
OpenOrders : openOrders ,
2024-03-04 12:52:01 +00:00
}
return common . SyncActiveOrders ( ctx , opts )
}