simplify the calculator api

This commit is contained in:
c9s 2020-10-16 10:19:53 +08:00
parent a6b99f6828
commit 63ea81b648
2 changed files with 5 additions and 17 deletions

View File

@ -115,9 +115,8 @@ var pnlCmd = &cobra.Command{
Symbol: symbol, Symbol: symbol,
StartTime: startTime, StartTime: startTime,
CurrentPrice: currentPrice, CurrentPrice: currentPrice,
Trades: trades,
} }
report := calculator.Calculate() report := calculator.Calculate(trades)
report.Print() report.Print()
return nil return nil
}, },

View File

@ -13,22 +13,11 @@ import (
type AverageCostCalculator struct { type AverageCostCalculator struct {
Symbol string Symbol string
StartTime time.Time StartTime time.Time
CurrentPrice float64
Trades []types.Trade
TradingFeeCurrency string TradingFeeCurrency string
} }
func (c *AverageCostCalculator) AddTrade(trade types.Trade) { func (c *AverageCostCalculator) Calculate(trades []types.Trade, currentPrice float64) *accounting.ProfitAndLossReport {
c.Trades = append(c.Trades, trade)
}
func (c *AverageCostCalculator) SetCurrentPrice(price float64) {
c.CurrentPrice = price
}
func (c *AverageCostCalculator) Calculate() *accounting.ProfitAndLossReport {
// copy trades, so that we can truncate it. // copy trades, so that we can truncate it.
var trades = c.Trades
var bidVolume = 0.0 var bidVolume = 0.0
var bidAmount = 0.0 var bidAmount = 0.0
@ -95,14 +84,14 @@ func (c *AverageCostCalculator) Calculate() *accounting.ProfitAndLossReport {
stock := bidVolume - askVolume stock := bidVolume - askVolume
if stock > 0 { if stock > 0 {
stockFee := c.CurrentPrice * stock * feeRate stockFee := currentPrice * stock * feeRate
unrealizedProfit += (c.CurrentPrice-averageCost)*stock - stockFee unrealizedProfit += (currentPrice-averageCost)*stock - stockFee
} }
return &accounting.ProfitAndLossReport{ return &accounting.ProfitAndLossReport{
Symbol: c.Symbol, Symbol: c.Symbol,
StartTime: c.StartTime, StartTime: c.StartTime,
CurrentPrice: c.CurrentPrice, CurrentPrice: currentPrice,
NumTrades: len(trades), NumTrades: len(trades),
BidVolume: bidVolume, BidVolume: bidVolume,