Files
StockSharp/MatchingEngine/StopOrderManager.cs
T
mika@stocksharp.com 4e757fd8b9 Make a trailing stop answer a price the same way however it got there
A registered stop carried no watermark, so its first price became one: a sell at 95 with an offset
of 5 seeing 98 moved its stop to 93. The same stop reloaded after a restart took the watermark its
level implies and refused that price. The watermark is taken at registration now, where every path
goes through; an offset-only stop has no level to imply one and still takes the first price.

The three formulas sit together instead of one being inlined in the manager: the level from the
watermark, the watermark back from the level, and the watermark a stop starts from - which the
server asks for too, when it writes a stop down. With them the reachability rule: a sell trailing by
100 percent or more has a stop of zero or below that no price reaches, and it is refused.

A trailing stop registered at a level the market has already passed now triggers at once, as a plain
stop registered the same way does.
2026-08-17 21:57:23 +03:00

189 lines
4.8 KiB
C#

namespace StockSharp.MatchingEngine;
/// <summary>
/// Stop order manager implementation.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public class StopOrderManager : IStopOrderManager
{
private readonly Dictionary<long, StopOrderInfo> _stopOrders = [];
private readonly Dictionary<SecurityId, List<long>> _bySecurityId = [];
private readonly Lock _sync = new();
/// <inheritdoc />
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);
}
}
/// <inheritdoc />
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;
}
}
/// <inheritdoc />
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;
}
}
/// <inheritdoc />
public IReadOnlyList<StopOrderTrigger> CheckPrice(SecurityId securityId, decimal price, DateTime time)
{
using (_sync.EnterScope())
{
if (!_bySecurityId.TryGetValue(securityId, out var list) || list.Count == 0)
return [];
List<StopOrderTrigger> 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<StopOrderTrigger>)[];
}
}
/// <inheritdoc />
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;
}
private 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()
{
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,
};
}
}