Skip to content

Commit

Permalink
Short position TPA calculation fix
Browse files Browse the repository at this point in the history
  • Loading branch information
melekhine committed Jun 9, 2019
1 parent 69f92bf commit 00bccf9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
8 changes: 7 additions & 1 deletion analysis.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,16 @@ func (tps TotalProfitAnalysis) Analyze(record *TradingRecord) float64 {
totalProfit := big.NewDecimal(0)
for _, trade := range record.Trades {
if trade.IsClosed() {

costBasis := trade.CostBasis()
exitValue := trade.ExitValue()

totalProfit = totalProfit.Add(exitValue.Sub(costBasis))
if trade.IsLong() {
totalProfit = totalProfit.Add(exitValue.Sub(costBasis))
} else if trade.IsShort() {
totalProfit = totalProfit.Sub(exitValue.Sub(costBasis))
}

}
}

Expand Down
18 changes: 16 additions & 2 deletions analysis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,27 @@ func TestTotalProfitAnalysis(t *testing.T) {
Security: example,
ExecutionTime: time.Now(),
},
{
Side: SELL,
Amount: big.NewDecimal(1),
Price: big.NewDecimal(2),
Security: example,
ExecutionTime: time.Now(),
},
{
Side: BUY,
Amount: big.NewDecimal(1),
Price: big.NewDecimal(1),
Security: example,
ExecutionTime: time.Now(),
},
}

for _, order := range orders {
record.Operate(order)
}

assert.EqualValues(t, 1, tpa.Analyze(record))
assert.EqualValues(t, 2.0, tpa.Analyze(record))

record.Operate(Order{
Side: BUY,
Expand All @@ -60,7 +74,7 @@ func TestTotalProfitAnalysis(t *testing.T) {
ExecutionTime: time.Now(),
})

assert.EqualValues(t, .5, tpa.Analyze(record))
assert.EqualValues(t, 1.5, tpa.Analyze(record))
})
}

Expand Down

0 comments on commit 00bccf9

Please sign in to comment.