From e28921879d0d78285d10db08d18aa62697c91bb3 Mon Sep 17 00:00:00 2001 From: c9s Date: Wed, 7 Sep 2022 14:02:57 +0800 Subject: [PATCH] types: implement stats update method for live trading --- pkg/types/trade_stats.go | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/pkg/types/trade_stats.go b/pkg/types/trade_stats.go index 671f1939d..6e923c85b 100644 --- a/pkg/types/trade_stats.go +++ b/pkg/types/trade_stats.go @@ -3,6 +3,7 @@ package types import ( "encoding/json" "math" + "sort" "strconv" "time" @@ -258,6 +259,52 @@ func (s *TradeStats) Add(profit *Profit) { } } +func grossLossReducer(prev, curr fixedpoint.Value) fixedpoint.Value { + if curr.Sign() < 0 { + return prev.Add(curr) + } + + return prev +} + +func grossProfitReducer(prev, curr fixedpoint.Value) fixedpoint.Value { + if curr.Sign() > 0 { + return prev.Add(curr) + } + + return prev +} + +// update the trade stats fields from the orderProfits +func (s *TradeStats) update() { + var profitsByOrder []fixedpoint.Value + var netProfitsByOrder []fixedpoint.Value + for _, profits := range s.orderProfits { + var sumProfit = fixedpoint.Zero + var sumNetProfit = fixedpoint.Zero + for _, p := range profits { + sumProfit = sumProfit.Add(p.Profit) + sumNetProfit = sumNetProfit.Add(p.NetProfit) + } + + profitsByOrder = append(profitsByOrder, sumProfit) + netProfitsByOrder = append(netProfitsByOrder, sumNetProfit) + } + + s.TotalNetProfit = fixedpoint.Reduce(profitsByOrder, fixedpoint.SumReducer) + s.GrossProfit = fixedpoint.Reduce(profitsByOrder, grossProfitReducer) + s.GrossLoss = fixedpoint.Reduce(profitsByOrder, grossLossReducer) + + sort.Sort(fixedpoint.Descending(profitsByOrder)) + sort.Sort(fixedpoint.Descending(netProfitsByOrder)) + + s.LargestProfitTrade = profitsByOrder[0] + s.LargestLossTrade = profitsByOrder[len(profitsByOrder)-1] + if s.LargestLossTrade.Sign() > 0 { + s.LargestLossTrade = fixedpoint.Zero + } +} + func (s *TradeStats) add(pnl fixedpoint.Value) { if pnl.Sign() > 0 { s.NumOfProfitTrade++