add api .UnrealizedProfit and .IsDust method on Position

This commit is contained in:
c9s 2022-06-02 18:05:35 +08:00
parent 6a25f30b39
commit 5277098f70
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 27 additions and 0 deletions

View File

@ -346,6 +346,10 @@ func (s *Strategy) placeOrders(ctx context.Context, orderExecutor bbgo.OrderExec
log.Infof("calculated %s max exposure position: %v", s.Symbol, maxExposurePosition)
if !s.Position.IsClosed() && !s.Position.IsDust(midPrice) {
log.Infof("current %s unrealized profit: %f %s", s.Symbol, s.Position.UnrealizedProfit(midPrice).Float64(), s.Market.QuoteCurrency)
}
canSell := true
canBuy := true

View File

@ -144,6 +144,13 @@ func (p *Position) NewClosePositionOrder(percentage fixedpoint.Value) *SubmitOrd
}
}
func (p *Position) IsDust(price fixedpoint.Value) bool {
base := p.GetBase()
return p.Market.IsDustQuantity(base, price)
}
// GetBase locks the mutex and return the base quantity
// The base quantity can be negative
func (p *Position) GetBase() (base fixedpoint.Value) {
p.Lock()
base = p.Base
@ -151,6 +158,18 @@ func (p *Position) GetBase() (base fixedpoint.Value) {
return base
}
func (p *Position) UnrealizedProfit(price fixedpoint.Value) fixedpoint.Value {
base := p.GetBase()
if p.IsLong() {
return price.Sub(p.AverageCost).Mul(base)
} else if p.IsShort() {
return p.AverageCost.Sub(price).Mul(base)
}
return fixedpoint.Zero
}
type FuturesPosition struct {
Symbol string `json:"symbol"`
BaseCurrency string `json:"baseCurrency"`
@ -229,6 +248,10 @@ func (p *Position) IsLong() bool {
return p.Base.Sign() > 0
}
func (p *Position) IsClosed() bool {
return p.Base.Sign() == 0
}
func (p *Position) Type() PositionType {
if p.Base.Sign() > 0 {
return PositionLong