bbgo_origin/pkg/report/profit_tracker.go

71 lines
2.0 KiB
Go
Raw Normal View History

2023-06-16 06:56:22 +00:00
package report
import (
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
type ProfitTracker struct {
types.IntervalWindow
ProfitStatsSlice []*types.ProfitStats
CurrentProfitStats **types.ProfitStats
market types.Market
2023-06-16 06:56:22 +00:00
}
// InitOld is for backward capability. ps is the ProfitStats of the strategy, market is the strategy market
func (p *ProfitTracker) InitOld(ps **types.ProfitStats, market types.Market) {
p.market = market
if *ps == nil {
*ps = types.NewProfitStats(p.market)
}
p.CurrentProfitStats = ps
p.ProfitStatsSlice = append(p.ProfitStatsSlice, *ps)
2023-06-16 06:56:22 +00:00
}
// Init initialize the tracker with the given market
func (p *ProfitTracker) Init(market types.Market) {
p.market = market
*p.CurrentProfitStats = types.NewProfitStats(p.market)
p.ProfitStatsSlice = append(p.ProfitStatsSlice, *p.CurrentProfitStats)
2023-06-16 06:56:22 +00:00
}
func (p *ProfitTracker) Bind(tradeCollector *bbgo.TradeCollector, session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, p.market.Symbol, types.SubscribeOptions{Interval: p.Interval})
2023-06-16 06:56:22 +00:00
tradeCollector.OnProfit(func(trade types.Trade, profit *types.Profit) {
p.AddProfit(*profit)
})
tradeCollector.OnTrade(func(trade types.Trade, profit fixedpoint.Value, netProfit fixedpoint.Value) {
2023-06-16 07:06:58 +00:00
p.AddTrade(trade)
2023-06-16 06:56:22 +00:00
})
2023-06-16 07:06:58 +00:00
// Rotate profitStats slice
2023-06-16 06:56:22 +00:00
session.MarketDataStream.OnKLineClosed(types.KLineWith(p.market.Symbol, p.Interval, func(kline types.KLine) {
2023-06-16 07:06:58 +00:00
p.Rotate()
2023-06-16 06:56:22 +00:00
}))
}
// Rotate the tracker to make a new ProfitStats to record the profits
func (p *ProfitTracker) Rotate() {
*p.CurrentProfitStats = types.NewProfitStats(p.market)
p.ProfitStatsSlice = append(p.ProfitStatsSlice, *p.CurrentProfitStats)
2023-06-16 06:56:22 +00:00
// Truncate
if len(p.ProfitStatsSlice) > p.Window {
p.ProfitStatsSlice = p.ProfitStatsSlice[len(p.ProfitStatsSlice)-p.Window:]
2023-06-16 06:56:22 +00:00
}
}
func (p *ProfitTracker) AddProfit(profit types.Profit) {
(*p.CurrentProfitStats).AddProfit(profit)
2023-06-16 06:56:22 +00:00
}
2023-06-16 07:06:58 +00:00
func (p *ProfitTracker) AddTrade(trade types.Trade) {
(*p.CurrentProfitStats).AddTrade(trade)
2023-06-16 07:06:58 +00:00
}