namespace StockSharp.MatchingEngine;
///
/// Stop order manager implementation.
///
///
/// Thread-safe. The server drives a single instance concurrently — Register / Cancel / Replace run
/// on the order-command path while CheckPrice runs on the feeder tick pump — so every operation is
/// serialized under one lock. Without it a register racing a check corrupts the per-security index
/// (lost stops / index-out-of-range) and two concurrent checks double-trigger the same stop.
///
public class StopOrderManager : IStopOrderManager
{
private readonly Dictionary _stopOrders = [];
private readonly Dictionary> _bySecurityId = [];
private readonly Lock _sync = new();
///
public void Register(StopOrderInfo info)
{
if (info is null)
throw new ArgumentNullException(nameof(info));
using (_sync.EnterScope())
{
if (info.IsTrailing && info.BestSeenPrice is null)
info.BestSeenPrice = TrailingStopPriceCalculator.InitialWatermark(
info.StopPrice, info.TrailingOffset, info.IsTrailingOffsetPercent, info.Side);
_stopOrders[info.TransactionId] = info;
if (!_bySecurityId.TryGetValue(info.SecurityId, out var list))
_bySecurityId[info.SecurityId] = list = [];
list.Add(info.TransactionId);
}
}
///
public bool Cancel(long transactionId, out StopOrderInfo info)
{
using (_sync.EnterScope())
{
if (!_stopOrders.TryGetValue(transactionId, out info))
return false;
_stopOrders.Remove(transactionId);
if (_bySecurityId.TryGetValue(info.SecurityId, out var list))
{
list.Remove(transactionId);
if (list.Count == 0)
_bySecurityId.Remove(info.SecurityId);
}
return true;
}
}
///
public bool Replace(long origTransactionId, StopOrderInfo newInfo)
{
// The lock is reentrant: hold it across Cancel + Register so the replace is atomic against a
// concurrent CheckPrice (no window where the old stop is gone but the new one is not yet in).
using (_sync.EnterScope())
{
if (!Cancel(origTransactionId, out _))
return false;
Register(newInfo);
return true;
}
}
///
public IReadOnlyList CheckPrice(SecurityId securityId, decimal price, DateTime time)
{
using (_sync.EnterScope())
{
if (!_bySecurityId.TryGetValue(securityId, out var list) || list.Count == 0)
return [];
List triggered = null;
for (var i = list.Count - 1; i >= 0; i--)
{
var transId = list[i];
if (!_stopOrders.TryGetValue(transId, out var info))
{
list.RemoveAt(i);
continue;
}
if (info.IsTrailing)
UpdateTrailing(info, price);
if (!IsTriggered(info, price))
continue;
triggered ??= [];
triggered.Add(new(info, price, CreateResultingOrder(info, time)));
_stopOrders.Remove(transId);
list.RemoveAt(i);
}
if (list.Count == 0)
_bySecurityId.Remove(securityId);
return triggered ?? (IReadOnlyList)[];
}
}
///
public IReadOnlyList GetStopIds(SecurityId securityId)
{
using (_sync.EnterScope())
{
if (!_bySecurityId.TryGetValue(securityId, out var list))
return [];
// Copied out, because the caller reads it after the lock while CheckPrice moves the live
// list. An id CheckPrice has not pruned yet names a stop that is already gone.
return [.. list.Where(_stopOrders.ContainsKey)];
}
}
///
public void Clear()
{
using (_sync.EnterScope())
{
_stopOrders.Clear();
_bySecurityId.Clear();
}
}
private static void UpdateTrailing(StopOrderInfo info, decimal price)
{
if (info.Side == Sides.Sell)
{
// Trailing sell: track max price
if (info.BestSeenPrice is null || price > info.BestSeenPrice)
{
info.BestSeenPrice = price;
info.StopPrice = TrailingStopPriceCalculator.CalculateStopPrice(
price, info.TrailingOffset, info.IsTrailingOffsetPercent, info.Side);
}
}
else
{
// Trailing buy: track min price
if (info.BestSeenPrice is null || price < info.BestSeenPrice)
{
info.BestSeenPrice = price;
info.StopPrice = TrailingStopPriceCalculator.CalculateStopPrice(
price, info.TrailingOffset, info.IsTrailingOffsetPercent, info.Side);
}
}
}
private static bool IsTriggered(StopOrderInfo info, decimal price)
{
if (info.InvertTrigger)
{
// TakeProfit: sell triggers when price rises, buy triggers when price falls
return info.Side == Sides.Sell
? price >= info.StopPrice
: price <= info.StopPrice;
}
// StopLoss: buy stop triggers when price rises, sell stop triggers when price falls
return info.Side == Sides.Buy
? price >= info.StopPrice
: price <= info.StopPrice;
}
///
/// Builds the order a stop places when it fires: a limit order at the price its condition asks
/// for, resolving a percentage against the level it fired at, or a market order when it names no
/// price at all.
///
/// The stop that fired.
/// When it fired.
/// The order to place.
public static OrderRegisterMessage CreateResultingOrder(StopOrderInfo info, DateTime time)
{
decimal limit = 0;
if (info.LimitPrice is decimal lp)
{
limit = info.IsLimitPricePercent
? info.StopPrice * (info.Side == Sides.Buy ? 1 + lp / 100m : 1 - lp / 100m)
: lp;
}
return new()
{
// The derived order continues the stop's own transaction: that is the only id the caller
// issued, so it is the only id its executions can be attributed to.
TransactionId = info.TransactionId,
SecurityId = info.SecurityId,
Side = info.Side,
Volume = info.Volume,
PortfolioName = info.PortfolioName,
OrderType = info.LimitPrice is not null ? OrderTypes.Limit : OrderTypes.Market,
Price = limit,
LocalTime = time,
};
}
}