Repository navigation
Description
Expected Behavior
For a coin-margined (inverse) crypto future, adding to a position at a different price should give an average entry price that keeps the position's profit right, which for inverse contracts is the harmonic mean of the fill prices weighted by quantity (Binance COIN-M: average entry price = total quantity / Σ(quantity / fill price)).
Example, Binance BTCUSD (USD 100 per contract), zero fees: buy 100 at 40,000, buy 100 at 50,000, sell 200 at 45,000. The realized profit is
100 × 100 × (1/40000 − 1/45000) + 100 × 100 × (1/50000 − 1/45000) ≈ +0.0055556 BTC.
Actual Behavior
SecurityPortfolioModel.ProcessFill (Common/Securities/SecurityPortfolioModel.cs, the averageHoldingsPrice updates for adding to a long or short) averages fill prices arithmetically for every security type. For the example the average entry price is 45,000, so closing at 45,000 credits 0 BTC and books 0 profit instead of +0.0055556 BTC. Unrealized profit of such a position is off by the same amount.
This is independent of the profit sign fixed for #9940: with the correct sign, the average is still wrong.
Reproducing the Problem
In Tests/Common/Securities/CryptoFuture/CryptoFutureMarginModelTests.cs, with its GetAlgorithm() and SetPrice() helpers:
var algo = GetAlgorithm();
var cf = algo.AddCryptoFuture("BTCUSD");
cf.BaseCurrency.SetAmount(1);
cf.FeeModel = new ConstantFeeModel(0);
SetPrice(cf, 40000);
algo.Portfolio.ProcessFills(new List<OrderEvent> { new OrderEvent(1, cf.Symbol, algo.UtcTime, OrderStatus.Filled, OrderDirection.Buy, 40000, 100, OrderFee.Zero) });
SetPrice(cf, 50000);
algo.Portfolio.ProcessFills(new List<OrderEvent> { new OrderEvent(2, cf.Symbol, algo.UtcTime, OrderStatus.Filled, OrderDirection.Buy, 50000, 100, OrderFee.Zero) });
SetPrice(cf, 45000);
var before = cf.BaseCurrency.Amount;
algo.Portfolio.ProcessFills(new List<OrderEvent> { new OrderEvent(3, cf.Symbol, algo.UtcTime, OrderStatus.Filled, OrderDirection.Sell, 45000, -200, OrderFee.Zero) });
// BTC change: 0, expected ≈ 0.0055556What a fix must achieve
Average entry price of coin-margined crypto futures (outside dYdX, matching CryptoFutureHolding.GetQuantityValue) follows the inverse-contract convention when a position is increased, so realized and unrealized profit match contracts × contract size × (1/entry − 1/exit) per fill. Linear contracts and other security types stay as they are. A suggestion, whoever fixes it picks the approach: let the holding compute the new average, as #10133 lets it compute profit.
System Information
Current master.
Activity