types: record the position open time

This commit is contained in:
c9s 2022-07-27 19:22:06 +08:00
parent 56bfa22dbe
commit 03541ca746
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 17 additions and 2 deletions

View File

@ -120,6 +120,8 @@ func (p *Position) NewProfit(trade Trade, profit, netProfit fixedpoint.Value) Pr
TradedAt: trade.Time.Time(),
Strategy: p.Strategy,
StrategyInstanceID: p.StrategyInstanceID,
PositionOpenedAt: p.OpenedAt,
}
}
@ -163,7 +165,7 @@ func (p *Position) NewMarketCloseOrder(percentage fixedpoint.Value) *SubmitOrder
}
func (p *Position) IsDust(price fixedpoint.Value) bool {
base := p.GetBase().Abs()
base := p.Base.Abs()
return p.Market.IsDustQuantity(base, price)
}
@ -472,6 +474,12 @@ func (p *Position) AddTrade(td Trade) (profit fixedpoint.Value, netProfit fixedp
}
}
// before adding the quantity, it's already a dust position
// then we should set the openedAt time
if p.IsDust(td.Price) {
p.OpenedAt = td.Time.Time()
}
// here the case is: base == 0 or base > 0
divisor := p.Base.Add(quantity)
p.ApproximateAverageCost = p.ApproximateAverageCost.Mul(p.Base).
@ -481,7 +489,6 @@ func (p *Position) AddTrade(td Trade) (profit fixedpoint.Value, netProfit fixedp
p.AverageCost = p.AverageCost.Mul(p.Base).Add(quoteQuantity).Div(divisor)
p.Base = p.Base.Add(quantity)
p.Quote = p.Quote.Sub(quoteQuantity)
return fixedpoint.Zero, fixedpoint.Zero, false
case SideTypeSell:
@ -508,6 +515,12 @@ func (p *Position) AddTrade(td Trade) (profit fixedpoint.Value, netProfit fixedp
}
}
// before subtracting the quantity, it's already a dust position
// then we should set the openedAt time
if p.IsDust(td.Price) {
p.OpenedAt = td.Time.Time()
}
// handling short position, since Base here is negative we need to reverse the sign
divisor := quantity.Sub(p.Base)
p.ApproximateAverageCost = p.ApproximateAverageCost.Mul(p.Base.Neg()).

View File

@ -56,6 +56,8 @@ type Profit struct {
IsIsolated bool `json:"isIsolated" db:"is_isolated"`
TradedAt time.Time `json:"tradedAt" db:"traded_at"`
PositionOpenedAt time.Time `json:"positionOpenedAt" db:"-"`
// strategy related fields
Strategy string `json:"strategy" db:"strategy"`
StrategyInstanceID string `json:"strategyInstanceID" db:"strategy_instance_id"`