mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-04 08:32:23 +00:00
The manager already indexes its stops by security for CheckPrice, but the interface offered no way to read that index, so every caller that needs to walk the stops of one instrument had to keep a second index of its own over the very same objects. GetStopIds hands out the transaction ids resting on a security, copied out under the same lock every other operation runs under and filtered to the stops that are still registered, since CheckPrice prunes its per-security list lazily.
214 lines
5.8 KiB
C#
214 lines
5.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 IReadOnlyList<long> 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)];
|
|
}
|
|
}
|
|
|
|
/// <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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
/// <param name="info">The stop that fired.</param>
|
|
/// <param name="time">When it fired.</param>
|
|
/// <returns>The order to place.</returns>
|
|
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,
|
|
};
|
|
}
|
|
}
|