data Package
The data package provides functionality for data processing and management.
The important concepts of this package are as follows:
- Provider: A candlestick data provider, which can contain multiple Feeders with the same start and end times.
- Feeder: Corresponds to a data source for a specific instrument and can include data for multiple timeframes.
- Spider: Real-time monitoring of multiple exchange data, storing it in a database, and notifying subscribers via TCP.
- Miner: Each exchange + market pair corresponds to one Miner.
- KLineWatcher: A client used to communicate with the Spider.
Provider and Feeder
Both backtesting and live trading require subscribing to candlestick data, and multiple strategies may run simultaneously, each subscribing to multiple timeframes. Therefore, the IProvider
interface is introduced to support both backtesting (HistProvider
) and live trading (LiveProvider
).
candlestick data for a single instrument may be used by multiple strategies simultaneously. To avoid redundant data fetching by each strategy, the IKlineFeeder
interface is introduced to support backtesting (DBKlineFeeder
) and live trading (KlineFeeder
+ KLineWatcher
).
Each KlineFeeder
corresponds to one instrument and can include data for multiple timeframes. For example, the instrument BTC/USDT might be used by multiple strategies, subscribing to the 5m, 1h, and 1d timeframes. To avoid redundant data reading, only the smallest timeframe (in this case, 5m) will fetch the candlestick data; larger timeframe data will be aggregated from the smallest timeframe.
Suitable Scenarios for Provider and Feeder
Fetching data for multiple instruments and timeframes with consistent start and end times. For example, during backtesting or live trading, a set of strategies is run over a specific period, involving multiple instruments and different timeframes. It is recommended to use Provider
+ Feeder
in such cases. If data needs to be fetched for different time periods separately, multiple Provider
+ Feeder
instances should be initialized.
Unsuitable Scenarios for Provider and Feeder
Fetching data for different timeframes with inconsistent start and end times. For example, if you want to fetch the last 1,000 candlesticks for both 1m and 1h timeframes for BTC/USDT for backtesting or other tasks, forcing the use of Feeder
would result in the 1m timeframe fetching 60 * 1,000 candlesticks. In such cases, it is better to directly call orm.GetOHLCV
to fetch data for each timeframe separately or initialize Feeder
twice to fetch the data separately.
Important Structures
Feeder
Each Feeder corresponds to a trading pair and can contain multiple time dimensions.
Public fields:
ExSymbol *orm.ExSymbol
- Exchange trading pair informationStates []*PairTFCache
- Cache states for each time dimensionWaitBar *banexg.Kline
- candlestick data waiting to be processedCallBack FnPairKline
- candlestick data callback functionOnEnvEnd FuncEnvEnd
- Environment end callback function (requires position closing when futures main contract switches or stock has ex-rights)isWarmUp bool
- Whether currently in warm-up state
IKlineFeeder
candlestick data feeder interface.
Public methods:
getSymbol() string
- Get trading pair namegetWaitBar() *banexg.Kline
- Get waiting candlesticksetWaitBar(bar *banexg.Kline)
- Set waiting candlestickSubTfs(timeFrames []string, delOther bool) []string
- Subscribe to specified time periodsWarmTfs(curMS int64, tfNums map[string]int, pBar *utils.PrgBar) (int64, *errs.Error)
- Warm up time periodsonNewBars(barTfMSecs int64, bars []*banexg.Kline) (bool, *errs.Error)
- Process new candlestick datagetStates() []*PairTFCache
- Get cache states
KlineFeeder
Each Feeder corresponds to a trading pair and can contain multiple time dimensions. Used in live trading.
Public fields:
Feeder
- Inherits from FeederPreFire float64
- Ratio for triggering bar earlyshowLog bool
- Whether to display logs
IHistKlineFeeder
Historical candlestick data feeder interface, inherits from IKlineFeeder.
Additional public methods:
getNextMS() int64
- Get end timestamp of next barDownIfNeed(sess *orm.Queries, exchange banexg.BanExchange, pBar *utils.PrgBar) *errs.Error
- Download candlesticks for entire rangeSetSeek(since int64)
- Set reading positionGetBar() *banexg.Kline
- Get current candlestickRunBar(bar *banexg.Kline) *errs.Error
- Run callback function for candlestickCallNext()
- Move pointer to next candlestick
HistKLineFeeder
Historical data feeder, base class for file feeder and database feeder.
Public fields:
KlineFeeder
- Inherits from KlineFeederTimeRange *config.TimeTuple
- Time rangeTradeTimes [][2]int64
- Trading times
DBKlineFeeder
Database candlestick feeder for backtesting.
Public fields:
HistKLineFeeder
- Inherits from HistKLineFeederoffsetMS int64
- Offset timestamp
IProvider
Data provider interface.
Public methods:
LoopMain() *errs.Error
- Main loopSubWarmPairs(items map[string]map[string]int, delOther bool) *errs.Error
- Subscribe and warm up trading pairsUnSubPairs(pairs ...string) *errs.Error
- Unsubscribe trading pairsSetDirty()
- Set dirty flag
Provider
Data provider base class.
Public fields:
holders map[string]T
- Map of held FeedersnewFeeder func(pair string, tfs []string) (T, *errs.Error)
- Function to create new FeederdirtyVers chan int
- Dirty version channelshowLog bool
- Whether to display logs
HistProvider
Historical data provider.
Public fields:
Provider[IHistKlineFeeder]
- Inherits from ProviderpBar *utils.StagedPrg
- Progress bar
LiveProvider
Real-time data provider.
Public fields:
Provider[IKlineFeeder]
- Inherits from Provider*KLineWatcher
- candlestick watcher
NotifyKLines
candlestick notification message.
Public fields:
TFSecs int
- Time period (seconds)Interval int
- Update interval (seconds)Arr []*banexg.Kline
- candlestick array
KLineMsg
candlestick message.
Public fields:
ExgName string
- Exchange nameMarket string
- Market typePair string
- Trading pairTFSecs int
- Time period (seconds)Interval int
- Update interval (seconds)Arr []*banexg.Kline
- candlestick array
SaveKline
Task for saving candlesticks.
Public fields:
Sid int32
- Trading pair IDTimeFrame string
- Time periodArr []*banexg.Kline
- candlestick arraySkipFirst bool
- Whether to skip firstMsgAction string
- Message action
FetchJob
candlestick fetching task.
Public fields:
PairTFCache
- candlestick cachePair string
- Trading pairCheckSecs int
- Check interval (seconds)Since int64
- Start timestampNextRun int64
- Next run timestamp
Miner
Data miner.
Public fields:
ExgName string
- Exchange nameMarket string
- Market typeFetchs map[string]*FetchJob
- Map of fetch tasksKlineReady bool
- Whether candlestick is readyKlinePairs map[string]bool
- Map of candlestick trading pairsTradeReady bool
- Whether trade is readyTradePairs map[string]bool
- Map of trade trading pairsBookReady bool
- Whether order book is readyBookPairs map[string]bool
- Map of order book trading pairsIsWatchPrice bool
- Whether to monitor price
LiveSpider
Real-time data spider.
Public fields:
*utils.ServerIO
- Server IOminers map[string]*Miner
- Map of miners
SubKLineState
candlestick subscription state.
Public fields:
Sid int32
- Trading pair IDNextNotify float64
- Next notification timePrevBar *banexg.Kline
- Previous candlestick
KLineWatcher
candlestick watcher.
Public fields:
*utils.ClientIO
- Client IOjobs map[string]*PairTFCache
- Map of jobsOnKLineMsg func(msg *KLineMsg)
- Callback for receiving candlestick messageOnTrade func(exgName, market string, trade *banexg.Trade)
- Callback for receiving trade
WatchJob
Watch task.
Public fields:
Symbol string
- Trading pairTimeFrame string
- Time periodSince int64
- Start timestamp
candlestick Data Related
NewKlineFeeder
Create a new candlestick data feeder for handling real-time candlestick data.
Parameters:
exs *orm.ExSymbol
- Exchange trading pair informationcallBack FnPairKline
- candlestick data callback functionshowLog bool
- Whether to display logs
Returns:
*KlineFeeder
- candlestick feeder instance*errs.Error
- Error information
NewDBKlineFeeder
Create a new database candlestick feeder for reading historical candlestick data from database.
Parameters:
exs *orm.ExSymbol
- Exchange trading pair informationcallBack FnPairKline
- candlestick data callback functionshowLog bool
- Whether to display logs
Returns:
*DBKlineFeeder
- Database candlestick feeder instance*errs.Error
- Error information
NewHistProvider
Create a new historical data provider for managing historical candlestick data retrieval and processing.
Parameters:
callBack FnPairKline
- candlestick data callback functionenvEnd FuncEnvEnd
- Environment end callback functionshowLog bool
- Whether to display logspBar *utils.StagedPrg
- Progress bar object
Returns:
*HistProvider
- Historical data provider instance
RunHistFeeders
Run historical candlestick feeder collection for batch processing of historical data.
Parameters:
makeFeeders func() []IHistKlineFeeder
- Function to create feeder listversions chan int
- Version control channelpBar *utils.PrgBar
- Progress bar object
Returns:
*errs.Error
- Error information
SortFeeders
Sort or insert candlestick feeders.
Parameters:
holds []IHistKlineFeeder
- Existing feeder listhold IHistKlineFeeder
- Feeder to processinsert bool
- Whether it's an insert operation
Returns:
[]IHistKlineFeeder
- Processed feeder list
NewLiveProvider
Create a new real-time data provider for handling real-time candlestick data.
Parameters:
callBack FnPairKline
- candlestick data callback functionenvEnd FuncEnvEnd
- Environment end callback function
Returns:
*LiveProvider
- Real-time data provider instance*errs.Error
- Error information
Data Tools Related
FindPathNames
Find all files with specified suffix in the given path.
Parameters:
inPath string
- Input pathsuffix string
- File suffix
Returns:
[]string
- List of file paths*errs.Error
- Error information
ReadZipCSVs
Read CSV files from ZIP archive.
Parameters:
inPath string
- ZIP file pathpBar *utils.PrgBar
- Progress bar objecthandle FuncReadZipItem
- Callback function for processing each CSV filearg interface{}
- Arguments passed to callback function
Returns:
*errs.Error
- Error information
RunSpider
Run data spider service.
Parameters:
addr string
- Service listening address
Returns:
*errs.Error
- Error information
NewKlineWatcher
Create a new candlestick data monitor.
Parameters:
addr string
- Connection address
Returns:
*KLineWatcher
- candlestick monitor instance*errs.Error
- Error information
RunFormatTick
Run Tick data formatting tool.
Parameters:
args *config.CmdArgs
- Command line arguments
Returns:
*errs.Error
- Error information
Build1mWithTicks
Build 1-minute candlesticks using Tick data.
Parameters:
args *config.CmdArgs
- Command line arguments
Returns:
*errs.Error
- Error information
CalcFilePerfs
Calculate file performance metrics.
Parameters:
args *config.CmdArgs
- Command line arguments
Returns:
*errs.Error
- Error information