mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-04 00:21:31 +00:00
A venue tells an account what it holds: money, positions, their entry prices and what each position has gained or lost. The emulator reported only the account total, and only when an order changed something - and in a backtest even that never arrived. A position adapter recounting positions from trades answered the portfolio lookup itself, so the emulator had no portfolio subscription and every report it made about the account was dropped. A strategy that manages a basket by the floating profit of its positions could not work in a backtest. - The matching engine reports a position with its floating profit, marked at the price it could be closed at, with every fill and again whenever the market moves that price. The market emulator of a backtest reports it with every fill and revalues open positions before each bar it hands over, so a subscriber acting on a bar reads the positions that bar produced, without a report for every price in between. - Positions are no longer recounted around the emulator, and the portfolio lookup reaches it. An account the emulator opens starts with the money of the portfolio it stands for instead of zero. - An order a subscriber sends in reaction to a message runs before the rest of that message's batch is delivered, so the account reports the batch still holds about an account the order changed are dropped instead of arriving after the newer ones. Reporting the positions on every bar sends portfolio names and security ids through lookups that compared them by the invariant culture, which on .NET runs through ICU: hashing a portfolio name and checking whether a security is the all-securities placeholder took more time than the rest of handling a position report. They are identifiers and now ignore case ordinally, so names that differ by a character the culture skips, such as a soft hyphen, are no longer taken for the same name. This covers the emulator's portfolios, the in-memory position storage, the portfolio-to-adapter map, the optimizer's portfolio copies, Security.ToSecurityId and IsAllSecurity. A backtest now raises PortfolioReceived as live trading does.
529 lines
16 KiB
C#
529 lines
16 KiB
C#
namespace StockSharp.MatchingEngine;
|
|
|
|
/// <summary>
|
|
/// Emulated portfolio implementation that tracks positions and money in-memory.
|
|
/// </summary>
|
|
public class EmulatedPortfolio
|
|
{
|
|
private readonly Dictionary<SecurityId, PositionInfo> _positions = [];
|
|
private decimal _beginMoney;
|
|
private decimal _realizedPnL;
|
|
private decimal _totalBlockedMoney;
|
|
private decimal _commission;
|
|
private readonly IMarkPrices _markPrices;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance.
|
|
/// </summary>
|
|
/// <param name="name">Portfolio name.</param>
|
|
/// <param name="markPrices">Where the prices to revalue open positions come from.</param>
|
|
public EmulatedPortfolio(string name, IMarkPrices markPrices)
|
|
{
|
|
Name = name ?? throw new ArgumentNullException(nameof(name));
|
|
_markPrices = markPrices ?? throw new ArgumentNullException(nameof(markPrices));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Portfolio name.
|
|
/// </summary>
|
|
public string Name { get; }
|
|
|
|
/// <summary>
|
|
/// Initial money amount.
|
|
/// </summary>
|
|
public decimal BeginMoney => _beginMoney;
|
|
|
|
/// <summary>
|
|
/// Current money (begin + PnL).
|
|
/// </summary>
|
|
public decimal CurrentMoney => _beginMoney + TotalPnL;
|
|
|
|
/// <summary>
|
|
/// Available money (current - blocked).
|
|
/// </summary>
|
|
public decimal AvailableMoney => CurrentMoney - _totalBlockedMoney;
|
|
|
|
/// <summary>
|
|
/// Total realized PnL.
|
|
/// </summary>
|
|
public decimal RealizedPnL => _realizedPnL;
|
|
|
|
/// <summary>
|
|
/// Total PnL (realized - commission).
|
|
/// </summary>
|
|
public decimal TotalPnL => _realizedPnL - _commission + UnrealizedPnL;
|
|
|
|
/// <summary>
|
|
/// What the open positions have gained or lost since they were taken, at the prices they could be
|
|
/// closed at now. A position the market has not priced counts for nothing.
|
|
/// </summary>
|
|
public decimal UnrealizedPnL
|
|
{
|
|
get
|
|
{
|
|
var total = 0m;
|
|
|
|
foreach (var pos in _positions.Values)
|
|
total += GetUnrealizedPnL(pos) ?? 0m;
|
|
|
|
return total;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Blocked money for pending orders.
|
|
/// </summary>
|
|
public decimal BlockedMoney => _totalBlockedMoney;
|
|
|
|
/// <summary>
|
|
/// Total commission paid.
|
|
/// </summary>
|
|
public decimal Commission => _commission;
|
|
|
|
/// <summary>
|
|
/// Changes whenever an order, a fill or the opening state changes the account, so a report on it can be told
|
|
/// from a newer one.
|
|
/// </summary>
|
|
public long Version { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Margin call level threshold. When margin level falls to this value, a warning is triggered.
|
|
/// </summary>
|
|
public decimal MarginCallLevel { get; set; } = 0.5m;
|
|
|
|
/// <summary>
|
|
/// Stop-out level threshold. When margin level falls to this value, positions are liquidated.
|
|
/// </summary>
|
|
public decimal StopOutLevel { get; set; } = 0.2m;
|
|
|
|
/// <summary>
|
|
/// Enable automatic position liquidation on stop-out.
|
|
/// </summary>
|
|
public bool EnableStopOut { get; set; }
|
|
|
|
/// <summary>
|
|
/// Set initial money.
|
|
/// </summary>
|
|
/// <param name="money">Money amount.</param>
|
|
public void SetMoney(decimal money)
|
|
{
|
|
_beginMoney = money;
|
|
Version++;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Set initial position.
|
|
/// </summary>
|
|
/// <param name="securityId">Security ID.</param>
|
|
/// <param name="volume">Position volume.</param>
|
|
/// <param name="avgPrice">Average entry price.</param>
|
|
public void SetPosition(SecurityId securityId, decimal volume, decimal avgPrice = 0)
|
|
{
|
|
var pos = GetOrCreatePosition(securityId);
|
|
pos.BeginValue = volume;
|
|
pos.Diff = 0;
|
|
pos.AveragePrice = avgPrice;
|
|
Version++;
|
|
}
|
|
|
|
private PositionInfo GetOrCreatePosition(SecurityId securityId)
|
|
{
|
|
if (!_positions.TryGetValue(securityId, out var pos))
|
|
{
|
|
pos = new PositionInfo(securityId);
|
|
_positions[securityId] = pos;
|
|
}
|
|
return pos;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get position for security.
|
|
/// </summary>
|
|
/// <param name="securityId">Security ID.</param>
|
|
/// <returns>Position info or null.</returns>
|
|
public PositionInfo GetPosition(SecurityId securityId)
|
|
{
|
|
return _positions.TryGetValue(securityId, out var pos) ? pos : null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Process a trade execution.
|
|
/// </summary>
|
|
/// <param name="securityId">Security ID.</param>
|
|
/// <param name="side">Trade side.</param>
|
|
/// <param name="price">Trade price.</param>
|
|
/// <param name="volume">Trade volume.</param>
|
|
/// <param name="commission">Commission amount.</param>
|
|
/// <param name="marginPrice">Price at which the filled order reserved funds.</param>
|
|
/// <returns>Trade processing result.</returns>
|
|
public TradeProcessingResult ProcessTrade(SecurityId securityId, Sides side, decimal price, decimal volume, decimal? commission = null, decimal? marginPrice = null)
|
|
{
|
|
var pos = GetOrCreatePosition(securityId);
|
|
Version++;
|
|
|
|
// Update commission
|
|
if (commission.HasValue)
|
|
_commission += commission.Value;
|
|
|
|
// Calculate position change
|
|
var positionDelta = side == Sides.Buy ? volume : -volume;
|
|
var prevPos = pos.CurrentValue;
|
|
var prevAvgPrice = pos.AveragePrice;
|
|
|
|
pos.Diff += positionDelta;
|
|
|
|
var currPos = pos.CurrentValue;
|
|
var tradeRealizedPnL = 0m;
|
|
|
|
// Calculate AveragePrice and RealizedPnL
|
|
if (currPos == 0)
|
|
{
|
|
// Position closed completely
|
|
if (prevPos != 0)
|
|
{
|
|
// Realized PnL = (exit price - entry price) * volume * direction
|
|
tradeRealizedPnL = (price - prevAvgPrice) * prevPos.Abs() * Math.Sign(prevPos);
|
|
_realizedPnL += tradeRealizedPnL;
|
|
}
|
|
pos.AveragePrice = 0;
|
|
}
|
|
else if (prevPos == 0)
|
|
{
|
|
// New position opened
|
|
pos.AveragePrice = price;
|
|
}
|
|
else if (Math.Sign(prevPos) == Math.Sign(currPos))
|
|
{
|
|
// Position increased or partially closed
|
|
if (currPos.Abs() > prevPos.Abs())
|
|
{
|
|
// Position increased - recalculate average price
|
|
pos.AveragePrice = (prevAvgPrice * prevPos.Abs() + price * volume) / currPos.Abs();
|
|
}
|
|
else
|
|
{
|
|
// Position partially closed - realize PnL for closed portion
|
|
var closedVolume = prevPos.Abs() - currPos.Abs();
|
|
tradeRealizedPnL = (price - prevAvgPrice) * closedVolume * Math.Sign(prevPos);
|
|
_realizedPnL += tradeRealizedPnL;
|
|
// Average price remains the same for remaining position
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Position flipped (was long, now short or vice versa)
|
|
// First close old position completely
|
|
tradeRealizedPnL = (price - prevAvgPrice) * prevPos.Abs() * Math.Sign(prevPos);
|
|
_realizedPnL += tradeRealizedPnL;
|
|
// Then open new position at current price
|
|
pos.AveragePrice = price;
|
|
}
|
|
|
|
// A fill releases the reservation made by that order. Its execution price can be better than
|
|
// its limit, so using the trade price would leave part of the reservation behind.
|
|
var heldVolume = side == Sides.Buy ? pos.TotalBidsVolume : pos.TotalAsksVolume;
|
|
var releasedVolume = volume.Min(heldVolume.Max(0m));
|
|
var heldValue = side == Sides.Buy ? pos.TotalBidsValue : pos.TotalAsksValue;
|
|
// Older callers do not identify the order whose fill they report. Preserve their aggregate
|
|
// behaviour by releasing the average reservation; engine callers pass the exact order price.
|
|
var releasePrice = marginPrice ?? (heldVolume > 0 ? heldValue / heldVolume : price);
|
|
var releasedValue = (releasedVolume * releasePrice).Min(heldValue.Max(0m));
|
|
|
|
if (side == Sides.Buy)
|
|
{
|
|
pos.TotalBidsVolume -= releasedVolume;
|
|
pos.TotalBidsValue -= releasedValue;
|
|
}
|
|
else
|
|
{
|
|
pos.TotalAsksVolume -= releasedVolume;
|
|
pos.TotalAsksValue -= releasedValue;
|
|
}
|
|
|
|
UpdateBlockedMoney();
|
|
|
|
return new TradeProcessingResult(tradeRealizedPnL, positionDelta, pos);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Process order registration (block funds).
|
|
/// </summary>
|
|
/// <param name="securityId">Security ID.</param>
|
|
/// <param name="side">Order side.</param>
|
|
/// <param name="volume">Order volume.</param>
|
|
/// <param name="price">Order price for margin calculation.</param>
|
|
public void ProcessOrderRegistration(SecurityId securityId, Sides side, decimal volume, decimal price)
|
|
{
|
|
var pos = GetOrCreatePosition(securityId);
|
|
var value = volume * price;
|
|
|
|
if (side == Sides.Buy)
|
|
{
|
|
pos.TotalBidsVolume += volume;
|
|
pos.TotalBidsValue += value;
|
|
}
|
|
else
|
|
{
|
|
pos.TotalAsksVolume += volume;
|
|
pos.TotalAsksValue += value;
|
|
}
|
|
|
|
UpdateBlockedMoney();
|
|
Version++;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Process order cancellation (unblock funds).
|
|
/// </summary>
|
|
/// <param name="securityId">Security ID.</param>
|
|
/// <param name="side">Order side.</param>
|
|
/// <param name="volume">Cancelled volume.</param>
|
|
/// <param name="price">Price used for margin calculation.</param>
|
|
public void ProcessOrderCancellation(SecurityId securityId, Sides side, decimal volume, decimal price = 0)
|
|
{
|
|
var pos = GetOrCreatePosition(securityId);
|
|
var value = volume * price;
|
|
|
|
if (side == Sides.Buy)
|
|
{
|
|
pos.TotalBidsVolume -= volume;
|
|
pos.TotalBidsValue -= value;
|
|
}
|
|
else
|
|
{
|
|
pos.TotalAsksVolume -= volume;
|
|
pos.TotalAsksValue -= value;
|
|
}
|
|
|
|
UpdateBlockedMoney();
|
|
Version++;
|
|
}
|
|
|
|
private void UpdateBlockedMoney()
|
|
{
|
|
_totalBlockedMoney = 0;
|
|
foreach (var pos in _positions.Values)
|
|
{
|
|
// TotalPrice logic:
|
|
// - If no position: blocked = buys + sells
|
|
// - If long position: blocked = max(position + buys, sells)
|
|
// - If short position: blocked = max(position + sells, buys)
|
|
var positionValue = pos.CurrentValue.Abs() * pos.AveragePrice;
|
|
var buyOrderValue = pos.TotalBidsValue;
|
|
var sellOrderValue = pos.TotalAsksValue;
|
|
|
|
decimal blocked;
|
|
if (positionValue == 0)
|
|
{
|
|
blocked = buyOrderValue + sellOrderValue;
|
|
}
|
|
else if (pos.CurrentValue > 0)
|
|
{
|
|
// Long position: max(position + buys, sells)
|
|
blocked = (positionValue + buyOrderValue).Max(sellOrderValue);
|
|
}
|
|
else
|
|
{
|
|
// Short position: max(position + sells, buys)
|
|
blocked = (positionValue + sellOrderValue).Max(buyOrderValue);
|
|
}
|
|
|
|
_totalBlockedMoney += blocked;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get all positions.
|
|
/// </summary>
|
|
/// <returns>Enumeration of positions.</returns>
|
|
public IEnumerable<(SecurityId securityId, decimal volume, decimal avgPrice)> GetPositions()
|
|
{
|
|
return _positions.Select(kvp => (kvp.Key, kvp.Value.CurrentValue, kvp.Value.AveragePrice));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get all position info objects.
|
|
/// </summary>
|
|
public IEnumerable<PositionInfo> GetAllPositions() => _positions.Values;
|
|
|
|
/// <summary>
|
|
/// What one position has gained or lost since it was taken, at the price it could be closed at now.
|
|
/// </summary>
|
|
/// <param name="securityId">Security ID.</param>
|
|
/// <returns>The floating profit, zero for a flat position, or <see langword="null"/> when the market has not priced an open one.</returns>
|
|
public decimal? GetUnrealizedPnL(SecurityId securityId)
|
|
=> _positions.TryGetValue(securityId, out var pos) ? GetUnrealizedPnL(pos) : 0m;
|
|
|
|
/// <summary>
|
|
/// What one position has gained or lost since it was taken, at the price it could be closed at now.
|
|
/// </summary>
|
|
/// <param name="position">A position of this portfolio.</param>
|
|
/// <returns>The floating profit, zero for a flat position, or <see langword="null"/> when the market has not priced an open one.</returns>
|
|
public decimal? GetUnrealizedPnL(PositionInfo position)
|
|
{
|
|
if (position is null)
|
|
throw new ArgumentNullException(nameof(position));
|
|
|
|
var volume = position.CurrentValue;
|
|
|
|
if (volume == 0)
|
|
return 0m;
|
|
|
|
// A long is closed by selling into the bid, a short by buying from the ask.
|
|
var price = _markPrices.TryGetClosePrice(position.SecurityId, volume > 0 ? Sides.Sell : Sides.Buy);
|
|
|
|
return price is null ? null : (price.Value - position.AveragePrice) * volume;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Calculate unrealized PnL across all positions.
|
|
/// </summary>
|
|
/// <param name="getCurrentPrice">Function to get current market price for a security. Returns null if price unavailable.</param>
|
|
/// <returns>Total unrealized PnL.</returns>
|
|
public decimal CalculateUnrealizedPnL(Func<SecurityId, decimal?> getCurrentPrice)
|
|
{
|
|
if (getCurrentPrice is null)
|
|
throw new ArgumentNullException(nameof(getCurrentPrice));
|
|
|
|
var total = 0m;
|
|
|
|
foreach (var pos in _positions.Values)
|
|
{
|
|
if (pos.CurrentValue == 0)
|
|
continue;
|
|
|
|
var price = getCurrentPrice(pos.SecurityId);
|
|
if (price is null)
|
|
continue;
|
|
|
|
total += (price.Value - pos.AveragePrice) * pos.CurrentValue;
|
|
}
|
|
|
|
return total;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Clear all state (used by Reset).
|
|
/// </summary>
|
|
internal void Clear()
|
|
{
|
|
_positions.Clear();
|
|
_beginMoney = 0;
|
|
_realizedPnL = 0;
|
|
_totalBlockedMoney = 0;
|
|
_commission = 0;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Portfolio manager that creates emulated portfolios in-memory.
|
|
/// </summary>
|
|
public class EmulatedPortfolioManager : IMarkPrices
|
|
{
|
|
// One account, one balance: the name is compared the way the rest of the engine compares it,
|
|
// or an order spelling it differently opens a second, empty portfolio next to the funded one.
|
|
private readonly Dictionary<string, EmulatedPortfolio> _portfolios = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
/// <summary>
|
|
/// Margin controller for order validation.
|
|
/// </summary>
|
|
public IMarginController MarginController { get; set; }
|
|
|
|
/// <summary>
|
|
/// Where the prices to revalue open positions come from. Until the engine supplies them every
|
|
/// position is worth what it cost.
|
|
/// </summary>
|
|
public IMarkPrices MarkPrices { get; set; }
|
|
|
|
/// <summary>
|
|
/// The money an account holds when it is opened, by the account's name, or <see langword="null"/> for an account
|
|
/// that opens empty.
|
|
/// </summary>
|
|
public Func<string, decimal?> InitialMoney { get; set; }
|
|
|
|
decimal? IMarkPrices.TryGetClosePrice(SecurityId securityId, Sides closeSide)
|
|
=> MarkPrices?.TryGetClosePrice(securityId, closeSide);
|
|
|
|
/// <summary>
|
|
/// Get or create a portfolio by name.
|
|
/// </summary>
|
|
/// <param name="name">Portfolio name.</param>
|
|
/// <returns>Portfolio instance.</returns>
|
|
public EmulatedPortfolio GetPortfolio(string name)
|
|
{
|
|
if (!_portfolios.TryGetValue(name, out var portfolio))
|
|
{
|
|
portfolio = new EmulatedPortfolio(name, this);
|
|
|
|
if (InitialMoney?.Invoke(name) is decimal money)
|
|
portfolio.SetMoney(money);
|
|
|
|
_portfolios[name] = portfolio;
|
|
}
|
|
return portfolio;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Look an account up without opening one, unlike <see cref="GetPortfolio"/>, which creates the
|
|
/// account when the name is unknown.
|
|
/// </summary>
|
|
/// <param name="name">Portfolio name.</param>
|
|
/// <param name="portfolio">The account, or <see langword="null"/> when no account carries that name.</param>
|
|
/// <returns><see langword="true"/> when the account exists.</returns>
|
|
public virtual bool TryGetPortfolio(string name, out EmulatedPortfolio portfolio)
|
|
=> _portfolios.TryGetValue(name, out portfolio);
|
|
|
|
/// <summary>
|
|
/// Check if portfolio exists.
|
|
/// </summary>
|
|
/// <param name="name">Portfolio name.</param>
|
|
/// <returns>True if exists.</returns>
|
|
public bool HasPortfolio(string name)
|
|
{
|
|
return _portfolios.ContainsKey(name);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get all portfolios.
|
|
/// </summary>
|
|
public IEnumerable<EmulatedPortfolio> GetAllPortfolios()
|
|
{
|
|
return _portfolios.Values;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validate that portfolio has sufficient funds for order registration.
|
|
/// </summary>
|
|
/// <param name="portfolioName">Portfolio name.</param>
|
|
/// <param name="securityId">Security ID (for per-position leverage).</param>
|
|
/// <param name="price">Order price.</param>
|
|
/// <param name="volume">Order volume.</param>
|
|
/// <returns>Error if insufficient funds, null otherwise.</returns>
|
|
public InvalidOperationException ValidateFunds(string portfolioName, SecurityId securityId, decimal price, decimal volume)
|
|
{
|
|
if (!HasPortfolio(portfolioName))
|
|
return null;
|
|
|
|
var portfolio = GetPortfolio(portfolioName);
|
|
var position = portfolio.GetPosition(securityId);
|
|
|
|
if (MarginController is not null)
|
|
return MarginController.ValidateOrder(portfolio, price, volume, position);
|
|
|
|
var needMoney = price * volume;
|
|
|
|
if (portfolio.AvailableMoney < needMoney)
|
|
return new InvalidOperationException($"Insufficient funds: need {needMoney}, available {portfolio.AvailableMoney}");
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Clear all portfolio state.
|
|
/// </summary>
|
|
public void Clear()
|
|
{
|
|
_portfolios.Clear();
|
|
}
|
|
}
|