types: add ROI method on position

Signed-off-by: c9s <yoanlin93@gmail.com>
This commit is contained in:
c9s 2022-06-26 13:11:19 +08:00
parent 4e670c67a8
commit 25fb684fd1
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 28 additions and 3 deletions

View File

@ -122,6 +122,15 @@ func (p *Position) NewProfit(trade Trade, profit, netProfit fixedpoint.Value) Pr
} }
} }
// ROI -- Return on investment (ROI) is a performance measure used to evaluate the efficiency or profitability of an investment
// or compare the efficiency of a number of different investments.
// ROI tries to directly measure the amount of return on a particular investment, relative to the investment's cost.
func (p *Position) ROI(price fixedpoint.Value) fixedpoint.Value {
unrealizedProfit := p.UnrealizedProfit(price)
cost := p.AverageCost.Mul(p.Base.Abs())
return unrealizedProfit.Div(cost)
}
func (p *Position) NewMarketCloseOrder(percentage fixedpoint.Value) *SubmitOrder { func (p *Position) NewMarketCloseOrder(percentage fixedpoint.Value) *SubmitOrder {
base := p.GetBase() base := p.GetBase()
@ -166,12 +175,12 @@ func (p *Position) GetBase() (base fixedpoint.Value) {
} }
func (p *Position) UnrealizedProfit(price fixedpoint.Value) fixedpoint.Value { func (p *Position) UnrealizedProfit(price fixedpoint.Value) fixedpoint.Value {
base := p.GetBase() quantity := p.GetBase().Abs()
if p.IsLong() { if p.IsLong() {
return price.Sub(p.AverageCost).Mul(base) return price.Sub(p.AverageCost).Mul(quantity)
} else if p.IsShort() { } else if p.IsShort() {
return p.AverageCost.Sub(price).Mul(base) return p.AverageCost.Sub(price).Mul(quantity)
} }
return fixedpoint.Zero return fixedpoint.Zero

View File

@ -10,6 +10,22 @@ import (
const Delta = 1e-9 const Delta = 1e-9
func TestPosition_ROI(t *testing.T) {
pos := &Position{
Symbol: "BTCUSDT",
BaseCurrency: "BTC",
QuoteCurrency: "USDT",
Base: fixedpoint.NewFromFloat(10.0),
AverageCost: fixedpoint.NewFromFloat(8000.0),
Quote: fixedpoint.NewFromFloat(-8000.0 * 10.0),
}
currentPrice := fixedpoint.NewFromFloat(10000.0)
roi := pos.ROI(currentPrice)
assert.Equal(t, "0.25", roi.String())
assert.Equal(t, "25%", roi.Percentage())
}
func TestPosition_ExchangeFeeRate_Short(t *testing.T) { func TestPosition_ExchangeFeeRate_Short(t *testing.T) {
pos := &Position{ pos := &Position{
Symbol: "BTCUSDT", Symbol: "BTCUSDT",