mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-22 06:53:52 +00:00
Merge pull request #1198 from andycheng123/feature/profit-tracker
FEATURE: add ProfitStatsTracker
This commit is contained in:
commit
e37edb3056
|
@ -175,3 +175,12 @@ exchangeStrategies:
|
||||||
# roiStopLoss is the stop loss percentage of the position ROI (currently the price change)
|
# roiStopLoss is the stop loss percentage of the position ROI (currently the price change)
|
||||||
- roiStopLoss:
|
- roiStopLoss:
|
||||||
percentage: 30%
|
percentage: 30%
|
||||||
|
|
||||||
|
profitStatsTracker:
|
||||||
|
interval: 1d
|
||||||
|
window: 30
|
||||||
|
accumulatedProfitReport:
|
||||||
|
profitMAWindow: 60
|
||||||
|
shortTermProfitWindow: 14
|
||||||
|
tsvReportPath: res.tsv
|
||||||
|
trackParameters: false
|
||||||
|
|
|
@ -112,3 +112,12 @@ exchangeStrategies:
|
||||||
# If true, looking for lower lows in long position and higher highs in short position. If false, looking for
|
# If true, looking for lower lows in long position and higher highs in short position. If false, looking for
|
||||||
# higher highs in long position and lower lows in short position
|
# higher highs in long position and lower lows in short position
|
||||||
oppositeDirectionAsPosition: false
|
oppositeDirectionAsPosition: false
|
||||||
|
|
||||||
|
profitStatsTracker:
|
||||||
|
interval: 1d
|
||||||
|
window: 30
|
||||||
|
accumulatedProfitReport:
|
||||||
|
profitMAWindow: 60
|
||||||
|
shortTermProfitWindow: 14
|
||||||
|
tsvReportPath: res.tsv
|
||||||
|
trackParameters: false
|
||||||
|
|
|
@ -2,196 +2,173 @@ package report
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/c9s/bbgo/pkg/bbgo"
|
|
||||||
"github.com/c9s/bbgo/pkg/data/tsv"
|
"github.com/c9s/bbgo/pkg/data/tsv"
|
||||||
"github.com/c9s/bbgo/pkg/datatype/floats"
|
"github.com/c9s/bbgo/pkg/datatype/floats"
|
||||||
"github.com/c9s/bbgo/pkg/fixedpoint"
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
||||||
"github.com/c9s/bbgo/pkg/indicator"
|
indicatorv2 "github.com/c9s/bbgo/pkg/indicator/v2"
|
||||||
"github.com/c9s/bbgo/pkg/types"
|
"github.com/c9s/bbgo/pkg/types"
|
||||||
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AccumulatedProfitReport For accumulated profit report output
|
// AccumulatedProfitReport For accumulated profit report output
|
||||||
type AccumulatedProfitReport struct {
|
type AccumulatedProfitReport struct {
|
||||||
// AccumulatedProfitMAWindow Accumulated profit SMA window, in number of trades
|
// ProfitMAWindow Accumulated profit SMA window
|
||||||
AccumulatedProfitMAWindow int `json:"accumulatedProfitMAWindow"`
|
ProfitMAWindow int `json:"profitMAWindow"`
|
||||||
|
|
||||||
// IntervalWindow interval window, in days
|
// ShortTermProfitWindow The window to sum up the short-term profit
|
||||||
IntervalWindow int `json:"intervalWindow"`
|
ShortTermProfitWindow int `json:"shortTermProfitWindow"`
|
||||||
|
|
||||||
// NumberOfInterval How many intervals to output to TSV
|
|
||||||
NumberOfInterval int `json:"NumberOfInterval"`
|
|
||||||
|
|
||||||
// TsvReportPath The path to output report to
|
// TsvReportPath The path to output report to
|
||||||
TsvReportPath string `json:"tsvReportPath"`
|
TsvReportPath string `json:"tsvReportPath"`
|
||||||
|
|
||||||
// AccumulatedDailyProfitWindow The window to sum up the daily profit, in days
|
symbol string
|
||||||
AccumulatedDailyProfitWindow int `json:"accumulatedDailyProfitWindow"`
|
|
||||||
|
|
||||||
Symbol string
|
types.IntervalWindow
|
||||||
|
|
||||||
// Accumulated profit
|
// Accumulated profit
|
||||||
accumulatedProfit fixedpoint.Value
|
accumulatedProfit fixedpoint.Value
|
||||||
accumulatedProfitPerDay floats.Slice
|
accumulatedProfitPerInterval *types.Float64Series
|
||||||
previousAccumulatedProfit fixedpoint.Value
|
|
||||||
|
|
||||||
// Accumulated profit MA
|
// Accumulated profit MA
|
||||||
accumulatedProfitMA *indicator.SMA
|
profitMA *indicatorv2.SMAStream
|
||||||
accumulatedProfitMAPerDay floats.Slice
|
profitMAPerInterval floats.Slice
|
||||||
|
|
||||||
// Daily profit
|
// Profit of each interval
|
||||||
dailyProfit floats.Slice
|
ProfitPerInterval floats.Slice
|
||||||
|
|
||||||
// Accumulated fee
|
// Accumulated fee
|
||||||
accumulatedFee fixedpoint.Value
|
accumulatedFee fixedpoint.Value
|
||||||
accumulatedFeePerDay floats.Slice
|
accumulatedFeePerInterval floats.Slice
|
||||||
|
|
||||||
// Win ratio
|
// Win ratio
|
||||||
winRatioPerDay floats.Slice
|
winRatioPerInterval floats.Slice
|
||||||
|
|
||||||
// Profit factor
|
// Profit factor
|
||||||
profitFactorPerDay floats.Slice
|
profitFactorPerInterval floats.Slice
|
||||||
|
|
||||||
// Trade number
|
// Trade number
|
||||||
dailyTrades floats.Slice
|
accumulatedTrades int
|
||||||
accumulatedTrades int
|
accumulatedTradesPerInterval floats.Slice
|
||||||
previousAccumulatedTrades int
|
|
||||||
|
|
||||||
// Extra values
|
// Extra values
|
||||||
extraValues [][2]string
|
strategyParameters [][2]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *AccumulatedProfitReport) Initialize(Symbol string, session *bbgo.ExchangeSession, orderExecutor *bbgo.GeneralOrderExecutor, TradeStats *types.TradeStats) {
|
func (r *AccumulatedProfitReport) Initialize(symbol string, interval types.Interval, window int) {
|
||||||
r.Symbol = Symbol
|
r.symbol = symbol
|
||||||
|
r.Interval = interval
|
||||||
|
r.Window = window
|
||||||
|
|
||||||
if r.AccumulatedProfitMAWindow <= 0 {
|
if r.ProfitMAWindow <= 0 {
|
||||||
r.AccumulatedProfitMAWindow = 60
|
r.ProfitMAWindow = 60
|
||||||
}
|
}
|
||||||
if r.IntervalWindow <= 0 {
|
|
||||||
r.IntervalWindow = 7
|
if r.Window <= 0 {
|
||||||
|
r.Window = 7
|
||||||
}
|
}
|
||||||
if r.AccumulatedDailyProfitWindow <= 0 {
|
|
||||||
r.AccumulatedDailyProfitWindow = 7
|
if r.ShortTermProfitWindow <= 0 {
|
||||||
|
r.ShortTermProfitWindow = 7
|
||||||
}
|
}
|
||||||
if r.NumberOfInterval <= 0 {
|
|
||||||
r.NumberOfInterval = 1
|
|
||||||
}
|
|
||||||
r.accumulatedProfitMA = &indicator.SMA{IntervalWindow: types.IntervalWindow{Interval: types.Interval1d, Window: r.AccumulatedProfitMAWindow}}
|
|
||||||
|
|
||||||
session.Subscribe(types.KLineChannel, r.Symbol, types.SubscribeOptions{Interval: types.Interval1d})
|
r.accumulatedProfitPerInterval = types.NewFloat64Series()
|
||||||
|
r.profitMA = indicatorv2.SMA(r.accumulatedProfitPerInterval, r.ProfitMAWindow)
|
||||||
// Record profit
|
|
||||||
orderExecutor.TradeCollector().OnProfit(func(trade types.Trade, profit *types.Profit) {
|
|
||||||
if profit == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
r.RecordProfit(profit.Profit)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Record trade
|
|
||||||
orderExecutor.TradeCollector().OnTrade(func(trade types.Trade, profit fixedpoint.Value, netProfit fixedpoint.Value) {
|
|
||||||
r.RecordTrade(trade.Fee)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Record daily status
|
|
||||||
session.MarketDataStream.OnKLineClosed(types.KLineWith(r.Symbol, types.Interval1d, func(kline types.KLine) {
|
|
||||||
r.DailyUpdate(TradeStats)
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *AccumulatedProfitReport) AddExtraValue(valueAndTitle [2]string) {
|
func (r *AccumulatedProfitReport) AddStrategyParameter(title string, value string) {
|
||||||
r.extraValues = append(r.extraValues, valueAndTitle)
|
r.strategyParameters = append(r.strategyParameters, [2]string{title, value})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *AccumulatedProfitReport) RecordProfit(profit fixedpoint.Value) {
|
func (r *AccumulatedProfitReport) AddTrade(trade types.Trade) {
|
||||||
r.accumulatedProfit = r.accumulatedProfit.Add(profit)
|
r.accumulatedFee = r.accumulatedFee.Add(trade.Fee)
|
||||||
}
|
|
||||||
|
|
||||||
func (r *AccumulatedProfitReport) RecordTrade(fee fixedpoint.Value) {
|
|
||||||
r.accumulatedFee = r.accumulatedFee.Add(fee)
|
|
||||||
r.accumulatedTrades += 1
|
r.accumulatedTrades += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *AccumulatedProfitReport) DailyUpdate(tradeStats *types.TradeStats) {
|
func (r *AccumulatedProfitReport) Rotate(ps *types.ProfitStats, ts *types.TradeStats) {
|
||||||
// Daily profit
|
|
||||||
r.dailyProfit.Update(r.accumulatedProfit.Sub(r.previousAccumulatedProfit).Float64())
|
|
||||||
r.previousAccumulatedProfit = r.accumulatedProfit
|
|
||||||
|
|
||||||
// Accumulated profit
|
// Accumulated profit
|
||||||
r.accumulatedProfitPerDay.Update(r.accumulatedProfit.Float64())
|
r.accumulatedProfit = r.accumulatedProfit.Add(ps.AccumulatedNetProfit)
|
||||||
|
r.accumulatedProfitPerInterval.PushAndEmit(r.accumulatedProfit.Float64())
|
||||||
|
|
||||||
// Accumulated profit MA
|
// Profit of each interval
|
||||||
r.accumulatedProfitMA.Update(r.accumulatedProfit.Float64())
|
r.ProfitPerInterval.Update(ps.AccumulatedNetProfit.Float64())
|
||||||
r.accumulatedProfitMAPerDay.Update(r.accumulatedProfitMA.Last(0))
|
|
||||||
|
// Profit MA
|
||||||
|
r.profitMAPerInterval.Update(r.profitMA.Last(0))
|
||||||
|
|
||||||
// Accumulated Fee
|
// Accumulated Fee
|
||||||
r.accumulatedFeePerDay.Update(r.accumulatedFee.Float64())
|
r.accumulatedFeePerInterval.Update(r.accumulatedFee.Float64())
|
||||||
|
|
||||||
|
// Trades
|
||||||
|
r.accumulatedTradesPerInterval.Update(float64(r.accumulatedTrades))
|
||||||
|
|
||||||
// Win ratio
|
// Win ratio
|
||||||
r.winRatioPerDay.Update(tradeStats.WinningRatio.Float64())
|
r.winRatioPerInterval.Update(ts.WinningRatio.Float64())
|
||||||
|
|
||||||
// Profit factor
|
// Profit factor
|
||||||
r.profitFactorPerDay.Update(tradeStats.ProfitFactor.Float64())
|
r.profitFactorPerInterval.Update(ts.ProfitFactor.Float64())
|
||||||
|
}
|
||||||
|
|
||||||
// Daily trades
|
// CsvHeader returns a header slice
|
||||||
r.dailyTrades.Update(float64(r.accumulatedTrades - r.previousAccumulatedTrades))
|
func (r *AccumulatedProfitReport) CsvHeader() []string {
|
||||||
r.previousAccumulatedTrades = r.accumulatedTrades
|
titles := []string{
|
||||||
|
"#",
|
||||||
|
"Symbol",
|
||||||
|
"Total Net Profit",
|
||||||
|
fmt.Sprintf("Total Net Profit %sMA%d", r.Interval, r.ProfitMAWindow),
|
||||||
|
fmt.Sprintf("%s%d Net Profit", r.Interval, r.ShortTermProfitWindow),
|
||||||
|
"accumulatedFee",
|
||||||
|
"winRatio",
|
||||||
|
"profitFactor",
|
||||||
|
fmt.Sprintf("%s%d Trades", r.Interval, r.Window),
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < len(r.strategyParameters); i++ {
|
||||||
|
titles = append(titles, r.strategyParameters[i][0])
|
||||||
|
}
|
||||||
|
|
||||||
|
return titles
|
||||||
|
}
|
||||||
|
|
||||||
|
// CsvRecords returns a data slice
|
||||||
|
func (r *AccumulatedProfitReport) CsvRecords() [][]string {
|
||||||
|
var data [][]string
|
||||||
|
|
||||||
|
for i := 0; i <= r.Window-1; i++ {
|
||||||
|
values := []string{
|
||||||
|
strconv.Itoa(i + 1),
|
||||||
|
r.symbol,
|
||||||
|
strconv.FormatFloat(r.accumulatedProfitPerInterval.Last(i), 'f', 4, 64),
|
||||||
|
strconv.FormatFloat(r.profitMAPerInterval.Last(i), 'f', 4, 64),
|
||||||
|
strconv.FormatFloat(r.accumulatedProfitPerInterval.Last(i)-r.accumulatedProfitPerInterval.Last(i+r.ShortTermProfitWindow), 'f', 4, 64),
|
||||||
|
strconv.FormatFloat(r.accumulatedFeePerInterval.Last(i), 'f', 4, 64),
|
||||||
|
strconv.FormatFloat(r.winRatioPerInterval.Last(i), 'f', 4, 64),
|
||||||
|
strconv.FormatFloat(r.profitFactorPerInterval.Last(i), 'f', 4, 64),
|
||||||
|
strconv.FormatFloat(r.accumulatedTradesPerInterval.Last(i), 'f', 4, 64),
|
||||||
|
}
|
||||||
|
for j := 0; j < len(r.strategyParameters); j++ {
|
||||||
|
values = append(values, r.strategyParameters[j][1])
|
||||||
|
}
|
||||||
|
|
||||||
|
data = append(data, values)
|
||||||
|
}
|
||||||
|
|
||||||
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output Accumulated profit report to a TSV file
|
// Output Accumulated profit report to a TSV file
|
||||||
func (r *AccumulatedProfitReport) Output(symbol string) {
|
func (r *AccumulatedProfitReport) Output() {
|
||||||
if r.TsvReportPath != "" {
|
if r.TsvReportPath != "" {
|
||||||
|
// Open specified file for appending
|
||||||
tsvwiter, err := tsv.AppendWriterFile(r.TsvReportPath)
|
tsvwiter, err := tsv.AppendWriterFile(r.TsvReportPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
defer tsvwiter.Close()
|
defer tsvwiter.Close()
|
||||||
// Output title row
|
|
||||||
titles := []string{
|
|
||||||
"#",
|
|
||||||
"Symbol",
|
|
||||||
"accumulatedProfit",
|
|
||||||
"accumulatedProfitMA",
|
|
||||||
fmt.Sprintf("%dd profit", r.AccumulatedDailyProfitWindow),
|
|
||||||
"accumulatedFee",
|
|
||||||
"accumulatedNetProfit",
|
|
||||||
"winRatio",
|
|
||||||
"profitFactor",
|
|
||||||
"60D trades",
|
|
||||||
}
|
|
||||||
for i := 0; i < len(r.extraValues); i++ {
|
|
||||||
titles = append(titles, r.extraValues[i][0])
|
|
||||||
}
|
|
||||||
_ = tsvwiter.Write(titles)
|
|
||||||
|
|
||||||
// Output data row
|
// Column Title
|
||||||
for i := 0; i <= r.NumberOfInterval-1; i++ {
|
_ = tsvwiter.Write(r.CsvHeader())
|
||||||
accumulatedProfit := r.accumulatedProfitPerDay.Index(r.IntervalWindow * i)
|
|
||||||
accumulatedProfitStr := fmt.Sprintf("%f", accumulatedProfit)
|
// Output data rows
|
||||||
accumulatedProfitMA := r.accumulatedProfitMAPerDay.Index(r.IntervalWindow * i)
|
_ = tsvwiter.WriteAll(r.CsvRecords())
|
||||||
accumulatedProfitMAStr := fmt.Sprintf("%f", accumulatedProfitMA)
|
|
||||||
intervalAccumulatedProfit := r.dailyProfit.Tail(r.AccumulatedDailyProfitWindow+r.IntervalWindow*i).Sum() - r.dailyProfit.Tail(r.IntervalWindow*i).Sum()
|
|
||||||
intervalAccumulatedProfitStr := fmt.Sprintf("%f", intervalAccumulatedProfit)
|
|
||||||
accumulatedFee := fmt.Sprintf("%f", r.accumulatedFeePerDay.Index(r.IntervalWindow*i))
|
|
||||||
accumulatedNetProfit := fmt.Sprintf("%f", accumulatedProfit-r.accumulatedFeePerDay.Index(r.IntervalWindow*i))
|
|
||||||
winRatio := fmt.Sprintf("%f", r.winRatioPerDay.Index(r.IntervalWindow*i))
|
|
||||||
profitFactor := fmt.Sprintf("%f", r.profitFactorPerDay.Index(r.IntervalWindow*i))
|
|
||||||
trades := r.dailyTrades.Tail(60+r.IntervalWindow*i).Sum() - r.dailyTrades.Tail(r.IntervalWindow*i).Sum()
|
|
||||||
tradesStr := fmt.Sprintf("%f", trades)
|
|
||||||
values := []string{
|
|
||||||
fmt.Sprintf("%d", i+1),
|
|
||||||
symbol, accumulatedProfitStr,
|
|
||||||
accumulatedProfitMAStr,
|
|
||||||
intervalAccumulatedProfitStr,
|
|
||||||
accumulatedFee,
|
|
||||||
accumulatedNetProfit,
|
|
||||||
winRatio, profitFactor,
|
|
||||||
tradesStr,
|
|
||||||
}
|
|
||||||
for j := 0; j < len(r.extraValues); j++ {
|
|
||||||
values = append(values, r.extraValues[j][1])
|
|
||||||
}
|
|
||||||
_ = tsvwiter.Write(values)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
96
pkg/report/profit_stats_tracker.go
Normal file
96
pkg/report/profit_stats_tracker.go
Normal file
|
@ -0,0 +1,96 @@
|
||||||
|
package report
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/c9s/bbgo/pkg/bbgo"
|
||||||
|
"github.com/c9s/bbgo/pkg/core"
|
||||||
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
||||||
|
"github.com/c9s/bbgo/pkg/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ProfitStatsTracker struct {
|
||||||
|
types.IntervalWindow
|
||||||
|
|
||||||
|
// Accumulated profit report
|
||||||
|
AccumulatedProfitReport *AccumulatedProfitReport `json:"accumulatedProfitReport"`
|
||||||
|
|
||||||
|
Market types.Market
|
||||||
|
|
||||||
|
ProfitStatsSlice []*types.ProfitStats
|
||||||
|
CurrentProfitStats **types.ProfitStats
|
||||||
|
|
||||||
|
tradeStats *types.TradeStats
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ProfitStatsTracker) Subscribe(session *bbgo.ExchangeSession, symbol string) {
|
||||||
|
session.Subscribe(types.KLineChannel, symbol, types.SubscribeOptions{Interval: p.Interval})
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitLegacy is for backward capability. ps is the ProfitStats of the strategy, Market is the strategy Market
|
||||||
|
func (p *ProfitStatsTracker) InitLegacy(market types.Market, ps **types.ProfitStats, ts *types.TradeStats) {
|
||||||
|
p.Market = market
|
||||||
|
|
||||||
|
if *ps == nil {
|
||||||
|
*ps = types.NewProfitStats(p.Market)
|
||||||
|
}
|
||||||
|
|
||||||
|
p.tradeStats = ts
|
||||||
|
|
||||||
|
p.CurrentProfitStats = ps
|
||||||
|
p.ProfitStatsSlice = append(p.ProfitStatsSlice, *ps)
|
||||||
|
|
||||||
|
if p.AccumulatedProfitReport != nil {
|
||||||
|
p.AccumulatedProfitReport.Initialize(p.Market.Symbol, p.Interval, p.Window)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init initialize the tracker with the given Market
|
||||||
|
func (p *ProfitStatsTracker) Init(market types.Market, ts *types.TradeStats) {
|
||||||
|
ps := types.NewProfitStats(p.Market)
|
||||||
|
p.InitLegacy(market, &ps, ts)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ProfitStatsTracker) Bind(session *bbgo.ExchangeSession, tradeCollector *core.TradeCollector) {
|
||||||
|
tradeCollector.OnProfit(func(trade types.Trade, profit *types.Profit) {
|
||||||
|
if profit == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
p.AddProfit(*profit)
|
||||||
|
})
|
||||||
|
|
||||||
|
tradeCollector.OnTrade(func(trade types.Trade, profit fixedpoint.Value, netProfit fixedpoint.Value) {
|
||||||
|
p.AddTrade(trade)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Rotate profitStats slice
|
||||||
|
session.MarketDataStream.OnKLineClosed(types.KLineWith(p.Market.Symbol, p.Interval, func(kline types.KLine) {
|
||||||
|
p.Rotate()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotate the tracker to make a new ProfitStats to record the profits
|
||||||
|
func (p *ProfitStatsTracker) Rotate() {
|
||||||
|
// Update report
|
||||||
|
if p.AccumulatedProfitReport != nil {
|
||||||
|
p.AccumulatedProfitReport.Rotate(*p.CurrentProfitStats, p.tradeStats)
|
||||||
|
}
|
||||||
|
|
||||||
|
*p.CurrentProfitStats = types.NewProfitStats(p.Market)
|
||||||
|
p.ProfitStatsSlice = append(p.ProfitStatsSlice, *p.CurrentProfitStats)
|
||||||
|
// Truncate
|
||||||
|
if len(p.ProfitStatsSlice) > p.Window {
|
||||||
|
p.ProfitStatsSlice = p.ProfitStatsSlice[len(p.ProfitStatsSlice)-p.Window:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ProfitStatsTracker) AddProfit(profit types.Profit) {
|
||||||
|
(*p.CurrentProfitStats).AddProfit(profit)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *ProfitStatsTracker) AddTrade(trade types.Trade) {
|
||||||
|
(*p.CurrentProfitStats).AddTrade(trade)
|
||||||
|
|
||||||
|
if p.AccumulatedProfitReport != nil {
|
||||||
|
p.AccumulatedProfitReport.AddTrade(trade)
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,6 +3,9 @@ package linregmaker
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/c9s/bbgo/pkg/report"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/c9s/bbgo/pkg/risk/dynamicrisk"
|
"github.com/c9s/bbgo/pkg/risk/dynamicrisk"
|
||||||
|
@ -135,6 +138,10 @@ type Strategy struct {
|
||||||
ProfitStats *types.ProfitStats `persistence:"profit_stats"`
|
ProfitStats *types.ProfitStats `persistence:"profit_stats"`
|
||||||
TradeStats *types.TradeStats `persistence:"trade_stats"`
|
TradeStats *types.TradeStats `persistence:"trade_stats"`
|
||||||
|
|
||||||
|
// ProfitStatsTracker tracks profit related status and generates report
|
||||||
|
ProfitStatsTracker *report.ProfitStatsTracker `json:"profitStatsTracker"`
|
||||||
|
TrackParameters bool `json:"trackParameters"`
|
||||||
|
|
||||||
Environment *bbgo.Environment
|
Environment *bbgo.Environment
|
||||||
StandardIndicatorSet *bbgo.StandardIndicatorSet
|
StandardIndicatorSet *bbgo.StandardIndicatorSet
|
||||||
Market types.Market
|
Market types.Market
|
||||||
|
@ -242,6 +249,11 @@ func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
||||||
if len(s.DynamicQuantityDecrease) > 0 {
|
if len(s.DynamicQuantityDecrease) > 0 {
|
||||||
s.DynamicQuantityDecrease.Initialize(s.Symbol, session)
|
s.DynamicQuantityDecrease.Initialize(s.Symbol, session)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Profit tracker
|
||||||
|
if s.ProfitStatsTracker != nil {
|
||||||
|
s.ProfitStatsTracker.Subscribe(session, s.Symbol)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Strategy) CurrentPosition() *types.Position {
|
func (s *Strategy) CurrentPosition() *types.Position {
|
||||||
|
@ -664,6 +676,28 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
|
||||||
})
|
})
|
||||||
s.ExitMethods.Bind(session, s.orderExecutor)
|
s.ExitMethods.Bind(session, s.orderExecutor)
|
||||||
|
|
||||||
|
// Setup profit tracker
|
||||||
|
if s.ProfitStatsTracker != nil {
|
||||||
|
if s.ProfitStatsTracker.CurrentProfitStats == nil {
|
||||||
|
s.ProfitStatsTracker.InitLegacy(s.Market, &s.ProfitStats, s.TradeStats)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add strategy parameters to report
|
||||||
|
if s.TrackParameters && s.ProfitStatsTracker.AccumulatedProfitReport != nil {
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("ReverseEMAWindow", strconv.Itoa(s.ReverseEMA.Window))
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("FastLinRegWindow", strconv.Itoa(s.FastLinReg.Window))
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("FastLinRegInterval", s.FastLinReg.Interval.String())
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("SlowLinRegWindow", strconv.Itoa(s.SlowLinReg.Window))
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("SlowLinRegInterval", s.SlowLinReg.Interval.String())
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("FasterDecreaseRatio", strconv.FormatFloat(s.FasterDecreaseRatio.Float64(), 'f', 4, 64))
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("NeutralBollingerWindow", strconv.Itoa(s.NeutralBollinger.Window))
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("NeutralBollingerBandWidth", strconv.FormatFloat(s.NeutralBollinger.BandWidth, 'f', 4, 64))
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("Spread", strconv.FormatFloat(s.Spread.Float64(), 'f', 4, 64))
|
||||||
|
}
|
||||||
|
|
||||||
|
s.ProfitStatsTracker.Bind(s.session, s.orderExecutor.TradeCollector())
|
||||||
|
}
|
||||||
|
|
||||||
// Indicators initialized by StandardIndicatorSet must be initialized in Run()
|
// Indicators initialized by StandardIndicatorSet must be initialized in Run()
|
||||||
// Initialize ReverseEMA
|
// Initialize ReverseEMA
|
||||||
s.ReverseEMA = s.StandardIndicatorSet.EWMA(s.ReverseEMA.IntervalWindow)
|
s.ReverseEMA = s.StandardIndicatorSet.EWMA(s.ReverseEMA.IntervalWindow)
|
||||||
|
@ -812,7 +846,15 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
|
||||||
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
|
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
|
||||||
|
// Output profit report
|
||||||
|
if s.ProfitStatsTracker != nil {
|
||||||
|
if s.ProfitStatsTracker.AccumulatedProfitReport != nil {
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.Output()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
_ = s.orderExecutor.GracefulCancel(ctx)
|
_ = s.orderExecutor.GracefulCancel(ctx)
|
||||||
|
_, _ = fmt.Fprintln(os.Stderr, s.TradeStats.String())
|
||||||
})
|
})
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
|
@ -39,6 +39,10 @@ type Strategy struct {
|
||||||
ProfitStats *types.ProfitStats `persistence:"profit_stats"`
|
ProfitStats *types.ProfitStats `persistence:"profit_stats"`
|
||||||
TradeStats *types.TradeStats `persistence:"trade_stats"`
|
TradeStats *types.TradeStats `persistence:"trade_stats"`
|
||||||
|
|
||||||
|
// ProfitStatsTracker tracks profit related status and generates report
|
||||||
|
ProfitStatsTracker *report.ProfitStatsTracker `json:"profitStatsTracker"`
|
||||||
|
TrackParameters bool `json:"trackParameters"`
|
||||||
|
|
||||||
// Symbol is the market symbol you want to trade
|
// Symbol is the market symbol you want to trade
|
||||||
Symbol string `json:"symbol"`
|
Symbol string `json:"symbol"`
|
||||||
|
|
||||||
|
@ -101,9 +105,6 @@ type Strategy struct {
|
||||||
|
|
||||||
// StrategyController
|
// StrategyController
|
||||||
bbgo.StrategyController
|
bbgo.StrategyController
|
||||||
|
|
||||||
// Accumulated profit report
|
|
||||||
AccumulatedProfitReport *report.AccumulatedProfitReport `json:"accumulatedProfitReport"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Strategy) ID() string {
|
func (s *Strategy) ID() string {
|
||||||
|
@ -131,6 +132,11 @@ func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
||||||
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.LinearRegression.Interval})
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.LinearRegression.Interval})
|
||||||
|
|
||||||
s.ExitMethods.SetAndSubscribe(session, s)
|
s.ExitMethods.SetAndSubscribe(session, s)
|
||||||
|
|
||||||
|
// Profit tracker
|
||||||
|
if s.ProfitStatsTracker != nil {
|
||||||
|
s.ProfitStatsTracker.Subscribe(session, s.Symbol)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Position control
|
// Position control
|
||||||
|
@ -351,28 +357,31 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
|
||||||
s.orderExecutor.BindTradeStats(s.TradeStats)
|
s.orderExecutor.BindTradeStats(s.TradeStats)
|
||||||
s.orderExecutor.Bind()
|
s.orderExecutor.Bind()
|
||||||
|
|
||||||
// AccountValueCalculator
|
// Setup profit tracker
|
||||||
s.AccountValueCalculator = bbgo.NewAccountValueCalculator(s.session, s.Market.QuoteCurrency)
|
if s.ProfitStatsTracker != nil {
|
||||||
|
if s.ProfitStatsTracker.CurrentProfitStats == nil {
|
||||||
// Accumulated profit report
|
s.ProfitStatsTracker.InitLegacy(s.Market, &s.ProfitStats, s.TradeStats)
|
||||||
if bbgo.IsBackTesting {
|
|
||||||
if s.AccumulatedProfitReport == nil {
|
|
||||||
s.AccumulatedProfitReport = &report.AccumulatedProfitReport{}
|
|
||||||
}
|
}
|
||||||
s.AccumulatedProfitReport.Initialize(s.Symbol, session, s.orderExecutor, s.TradeStats)
|
|
||||||
|
|
||||||
// Add strategy parameters to report
|
// Add strategy parameters to report
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"window", fmt.Sprintf("%d", s.Window)})
|
if s.TrackParameters && s.ProfitStatsTracker.AccumulatedProfitReport != nil {
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"multiplier", fmt.Sprintf("%f", s.SupertrendMultiplier)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("window", fmt.Sprintf("%d", s.Window))
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"fastDEMA", fmt.Sprintf("%d", s.FastDEMAWindow)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("multiplier", fmt.Sprintf("%f", s.SupertrendMultiplier))
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"slowDEMA", fmt.Sprintf("%d", s.SlowDEMAWindow)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("fastDEMA", fmt.Sprintf("%d", s.FastDEMAWindow))
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"takeProfitAtrMultiplier", fmt.Sprintf("%f", s.TakeProfitAtrMultiplier)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("slowDEMA", fmt.Sprintf("%d", s.SlowDEMAWindow))
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"stopLossByTriggeringK", fmt.Sprintf("%t", s.StopLossByTriggeringK)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("takeProfitAtrMultiplier", fmt.Sprintf("%f", s.TakeProfitAtrMultiplier))
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"stopByReversedSupertrend", fmt.Sprintf("%t", s.StopByReversedSupertrend)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("stopLossByTriggeringK", fmt.Sprintf("%t", s.StopLossByTriggeringK))
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"stopByReversedDema", fmt.Sprintf("%t", s.StopByReversedDema)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("stopByReversedSupertrend", fmt.Sprintf("%t", s.StopByReversedSupertrend))
|
||||||
s.AccumulatedProfitReport.AddExtraValue([2]string{"stopByReversedLinGre", fmt.Sprintf("%t", s.StopByReversedLinGre)})
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("stopByReversedDema", fmt.Sprintf("%t", s.StopByReversedDema))
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.AddStrategyParameter("stopByReversedLinGre", fmt.Sprintf("%t", s.StopByReversedLinGre))
|
||||||
|
}
|
||||||
|
|
||||||
|
s.ProfitStatsTracker.Bind(s.session, s.orderExecutor.TradeCollector())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AccountValueCalculator
|
||||||
|
s.AccountValueCalculator = bbgo.NewAccountValueCalculator(s.session, s.Market.QuoteCurrency)
|
||||||
|
|
||||||
// For drawing
|
// For drawing
|
||||||
profitSlice := floats.Slice{1., 1.}
|
profitSlice := floats.Slice{1., 1.}
|
||||||
price, _ := session.LastPrice(s.Symbol)
|
price, _ := session.LastPrice(s.Symbol)
|
||||||
|
@ -520,10 +529,14 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
|
||||||
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
|
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
|
|
||||||
if bbgo.IsBackTesting {
|
// Output profit report
|
||||||
// Output accumulated profit report
|
if s.ProfitStatsTracker != nil {
|
||||||
defer s.AccumulatedProfitReport.Output(s.Symbol)
|
if s.ProfitStatsTracker.AccumulatedProfitReport != nil {
|
||||||
|
s.ProfitStatsTracker.AccumulatedProfitReport.Output()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if bbgo.IsBackTesting {
|
||||||
// Draw graph
|
// Draw graph
|
||||||
if s.DrawGraph {
|
if s.DrawGraph {
|
||||||
if err := s.Draw(&profitSlice, &cumProfitSlice); err != nil {
|
if err := s.Draw(&profitSlice, &cumProfitSlice); err != nil {
|
||||||
|
|
|
@ -164,6 +164,9 @@ type ProfitStats struct {
|
||||||
TodayGrossProfit fixedpoint.Value `json:"todayGrossProfit,omitempty"`
|
TodayGrossProfit fixedpoint.Value `json:"todayGrossProfit,omitempty"`
|
||||||
TodayGrossLoss fixedpoint.Value `json:"todayGrossLoss,omitempty"`
|
TodayGrossLoss fixedpoint.Value `json:"todayGrossLoss,omitempty"`
|
||||||
TodaySince int64 `json:"todaySince,omitempty"`
|
TodaySince int64 `json:"todaySince,omitempty"`
|
||||||
|
|
||||||
|
//StartTime time.Time
|
||||||
|
//EndTime time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProfitStats(market Market) *ProfitStats {
|
func NewProfitStats(market Market) *ProfitStats {
|
||||||
|
@ -182,6 +185,8 @@ func NewProfitStats(market Market) *ProfitStats {
|
||||||
TodayGrossProfit: fixedpoint.Zero,
|
TodayGrossProfit: fixedpoint.Zero,
|
||||||
TodayGrossLoss: fixedpoint.Zero,
|
TodayGrossLoss: fixedpoint.Zero,
|
||||||
TodaySince: 0,
|
TodaySince: 0,
|
||||||
|
//StartTime: time.Now().UTC(),
|
||||||
|
//EndTime: time.Now().UTC(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -223,6 +228,8 @@ func (s *ProfitStats) AddProfit(profit Profit) {
|
||||||
s.AccumulatedGrossLoss = s.AccumulatedGrossLoss.Add(profit.Profit)
|
s.AccumulatedGrossLoss = s.AccumulatedGrossLoss.Add(profit.Profit)
|
||||||
s.TodayGrossLoss = s.TodayGrossLoss.Add(profit.Profit)
|
s.TodayGrossLoss = s.TodayGrossLoss.Add(profit.Profit)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//s.EndTime = profit.TradedAt.UTC()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ProfitStats) AddTrade(trade Trade) {
|
func (s *ProfitStats) AddTrade(trade Trade) {
|
||||||
|
|
Loading…
Reference in New Issue
Block a user