Files
mika@stocksharp.com 536abc52b0 Refuse a market order that has no market, and say so
A market order names no price, so only the book can give it one. Sent against a
side holding nothing - an empty book, or a book quoting only the order's own
side - it produced an Active row and then a Done row with the balance still
equal to the volume and no error at all, which reads exactly like an order that
filled as far as it asked to. A strategy could not tell that it had not traded,
let alone why.

The refusal was already written, and switched off: the check that an order with
no price cannot be paid for sits behind an early return taken when money is not
being checked, and money is not checked by default. Whether a market exists is
not a question about money.

Two neighbours stay as they are, and are now pinned: an order the book fills
only part of did find a market, so it ends Done with what it bought; a limit
order carries its own price and rests in an empty book.

Gone with it: a setting naming this behaviour that nothing ever read, and a
variable in the matcher that computed whether anything traded and did nothing
with the answer.
2026-09-19 23:49:12 +03:00

252 lines
7.1 KiB
C#

namespace StockSharp.MatchingEngine;
/// <summary>
/// Order matcher implementation.
/// </summary>
public class OrderMatcher : IOrderMatcher
{
/// <inheritdoc />
public MatchResult Match(EmulatorOrder order, IOrderBook book, MatchingSettings settings)
{
if (order is null)
throw new ArgumentNullException(nameof(order));
if (book is null)
throw new ArgumentNullException(nameof(book));
if (settings is null)
throw new ArgumentNullException(nameof(settings));
// Post-only check: reject if would cross
if (order.PostOnly && WouldCross(order, book))
{
return new MatchResult
{
Order = order,
IsRejected = true,
RejectionReason = "Post-only order would cross the book",
FinalState = OrderStates.Done,
RemainingVolume = order.Balance,
ShouldPlaceInBook = false,
};
}
// A market order names no price, so only the book can give it one: nothing quoted on the side
// it takes from means there is no market for it, and a plain Done would be indistinguishable
// from an order filled as far as it asked.
if (order.OrderType == OrderTypes.Market && GetMarketPrice(order.Side, book) is null)
{
return new MatchResult
{
Order = order,
IsRejected = true,
RejectionReason = $"No market for the {order.Side} market order: the {order.Side.Invert()} side of the book is empty.",
FinalState = OrderStates.Done,
RemainingVolume = order.Balance,
ShouldPlaceInBook = false,
};
}
// Fill-or-kill is a property of the order, not of the price it names, so a market order
// carrying it is killed whole exactly as a limit one is.
if (order.TimeInForce == TimeInForce.MatchOrCancel)
return MatchFOK(order, book, settings);
var trades = new List<MatchTrade>();
var matchedOrders = new List<EmulatorOrder>();
// Market orders
if (order.OrderType == OrderTypes.Market)
{
return MatchMarketOrder(order, book, settings, trades, matchedOrders);
}
// Limit orders
return MatchLimitOrder(order, book, settings, trades, matchedOrders);
}
private static MatchResult MatchMarketOrder(
EmulatorOrder order,
IOrderBook book,
MatchingSettings settings,
List<MatchTrade> trades,
List<EmulatorOrder> matchedOrders)
{
var oppositeSide = order.Side.Invert();
var remaining = order.Balance;
// Consume from opposite side at any price
foreach (var (price, volume, fills) in ((OrderBook)book).ConsumeVolume(oppositeSide, null, remaining))
{
var consumed = volume.Min(remaining);
trades.Add(new MatchTrade(price, consumed, order.Side, fills));
matchedOrders.AddRange(fills.Where(f => f.Order.IsUserOrder).Select(f => f.Order));
remaining -= consumed;
if (remaining <= 0)
break;
}
return new MatchResult
{
Order = order,
Trades = trades,
MatchedOrders = matchedOrders,
RemainingVolume = remaining,
ShouldPlaceInBook = false, // Market orders never go to book
FinalState = OrderStates.Done,
};
}
private static MatchResult MatchLimitOrder(
EmulatorOrder order,
IOrderBook book,
MatchingSettings settings,
List<MatchTrade> trades,
List<EmulatorOrder> matchedOrders)
{
var oppositeSide = order.Side.Invert();
var remaining = order.Balance;
var limitPrice = order.Price;
// Get matchable volume
foreach (var (price, volume, fills) in ((OrderBook)book).ConsumeVolume(oppositeSide, limitPrice, remaining))
{
var consumed = volume.Min(remaining);
// Use order price for candle-based matching
var tradePrice = settings.UseOrderPriceForLimitTrades ? limitPrice : price;
trades.Add(new MatchTrade(tradePrice, consumed, order.Side, fills));
matchedOrders.AddRange(fills.Where(f => f.Order.IsUserOrder).Select(f => f.Order));
remaining -= consumed;
if (remaining <= 0)
break;
}
var isFullyMatched = remaining <= 0;
// Determine final state based on TimeInForce
var shouldPlaceInBook = false;
var finalState = OrderStates.Active;
switch (order.TimeInForce)
{
case TimeInForce.PutInQueue:
case null:
// Place remaining in book
shouldPlaceInBook = remaining > 0;
finalState = isFullyMatched ? OrderStates.Done : OrderStates.Active;
break;
case TimeInForce.MatchOrCancel: // FOK
finalState = OrderStates.Done;
break;
case TimeInForce.CancelBalance: // IOC
// Execute what we can, cancel the rest
finalState = OrderStates.Done;
break;
}
return new MatchResult
{
Order = order,
Trades = trades,
MatchedOrders = matchedOrders,
RemainingVolume = remaining,
ShouldPlaceInBook = shouldPlaceInBook,
FinalState = finalState,
};
}
private static MatchResult MatchFOK(EmulatorOrder order, IOrderBook book, MatchingSettings settings)
{
var oppositeSide = order.Side.Invert();
// A market order names no price, so no level in the book is out of its reach.
var limitPrice = order.OrderType == OrderTypes.Market ? null : (decimal?)order.Price;
// Check if we can fill entire order without actually consuming
var availableVolume = 0m;
foreach (var level in book.GetLevels(oppositeSide))
{
// Check price
if (limitPrice is decimal limit)
{
if (order.Side == Sides.Buy && level.Price > limit)
break;
if (order.Side == Sides.Sell && level.Price < limit)
break;
}
availableVolume += level.Volume;
if (availableVolume >= order.Balance)
break;
}
if (availableVolume < order.Balance)
{
// Cannot fill entirely - reject (but order is "done" with full balance remaining)
return new MatchResult
{
Order = order,
Trades = [],
MatchedOrders = [],
RemainingVolume = order.Balance,
ShouldPlaceInBook = false,
FinalState = OrderStates.Done,
};
}
// Can fill - do actual matching
var trades = new List<MatchTrade>();
var matchedOrders = new List<EmulatorOrder>();
var remaining = order.Balance;
foreach (var (price, volume, fills) in ((OrderBook)book).ConsumeVolume(oppositeSide, limitPrice, remaining))
{
var consumed = volume.Min(remaining);
var tradePrice = settings.UseOrderPriceForLimitTrades && limitPrice is decimal orderPrice ? orderPrice : price;
trades.Add(new MatchTrade(tradePrice, consumed, order.Side, fills));
matchedOrders.AddRange(fills.Where(f => f.Order.IsUserOrder).Select(f => f.Order));
remaining -= consumed;
if (remaining <= 0)
break;
}
return new MatchResult
{
Order = order,
Trades = trades,
MatchedOrders = matchedOrders,
RemainingVolume = 0,
ShouldPlaceInBook = false,
FinalState = OrderStates.Done,
};
}
/// <inheritdoc />
public bool WouldCross(EmulatorOrder order, IOrderBook book)
{
if (order.OrderType == OrderTypes.Market)
return true;
var oppositeBest = order.Side == Sides.Buy ? book.BestAsk : book.BestBid;
if (oppositeBest is null)
return false;
if (order.Side == Sides.Buy)
return order.Price >= oppositeBest.Value.price;
else
return order.Price <= oppositeBest.Value.price;
}
/// <inheritdoc />
public decimal? GetMarketPrice(Sides side, IOrderBook book)
{
// For buy orders, get best ask; for sell orders, get best bid
var oppositeBest = side == Sides.Buy ? book.BestAsk : book.BestBid;
return oppositeBest?.price;
}
}