From 617f5119fd4ff6b80fa0bd892fbdb133245ea39c Mon Sep 17 00:00:00 2001 From: c9s Date: Wed, 20 Jan 2021 16:14:02 +0800 Subject: [PATCH] test trade profit calculation --- pkg/bbgo/position.go | 2 +- pkg/bbgo/position_test.go | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/pkg/bbgo/position.go b/pkg/bbgo/position.go index fc17b4533..960d31a48 100644 --- a/pkg/bbgo/position.go +++ b/pkg/bbgo/position.go @@ -34,7 +34,7 @@ func (p *Position) AddTrade(t types.Trade) (fixedpoint.Value, bool) { p.Base -= quantity p.Quote += fixedpoint.NewFromFloat(t.QuoteQuantity) - return price - p.AverageCost, true + return (price - p.AverageCost).Mul(quantity), true } return 0, false diff --git a/pkg/bbgo/position_test.go b/pkg/bbgo/position_test.go index 6f8101cc8..336c3e8f9 100644 --- a/pkg/bbgo/position_test.go +++ b/pkg/bbgo/position_test.go @@ -30,7 +30,17 @@ func TestPosition(t *testing.T) { pos.AddTrade(trade) } + expectedAverageCost := (1000.0*0.01 + 2000.0*0.03) / 0.04 assert.Equal(t, fixedpoint.NewFromFloat(-70.0), pos.Quote) assert.Equal(t, fixedpoint.NewFromFloat(0.04), pos.Base) - assert.Equal(t, fixedpoint.NewFromFloat((1000.0*0.01+2000.0*0.03)/0.04), pos.AverageCost) + assert.Equal(t, fixedpoint.NewFromFloat(expectedAverageCost), pos.AverageCost) + + amount, profit := pos.AddTrade(types.Trade{ + Side: types.SideTypeSell, + Price: 3000.0, + Quantity: 0.01, + QuoteQuantity: 3000.0 * 0.01, + }) + assert.True(t, profit) + assert.Equal(t, fixedpoint.NewFromFloat((3000.0-expectedAverageCost)*0.01), amount) }