Order interceptors
An order interceptor is a pre-trade check of your own: the platform asks it about every trading operation before the operation reaches the broker, and the interceptor allows it or rejects it with a reason the trader sees. It is the extension for risk-management and discipline products: a daily loss limit, a maximum order or position size, a maximum number of trades, trading hours, a cool-down after losses, a news window, or a call to the server of a firm that checks its traders.
- The platform keeps one instance of an enabled interceptor for the whole session, whatever panels, charts or workspaces are open; it is not attached to a panel or an instrument.
- It sees the orders of every trading path of the platform: the chart, Smart DOM, the heatmap, the tables of orders and positions, hotkeys, chart indicators and strategies, ATM strategies, copy trading and AI agents through ATAS Connect, on live, simulated and Market Replay accounts.
- Several interceptors form a chain in the order the trader sets; the first rejection ends it.
- An interceptor decides; it cannot change an operation, place orders of its own or delay the platform beyond its timeout.
The trader manages the interceptors in the Order interceptors window of the classic ATAS and of ATAS X: a list in the order of the chain, where each row has the state of the interceptor, a switch, buttons to move it up and down, its timeout, what happens when it cannot answer (On failure: Reject or Allow), its settings and a restart button.
Important
A newly installed interceptor is switched off. The platform shows a notification and the interceptor does nothing until the trader enables it in the list. Installing or updating a DLL never changes whether the trader can trade.
What you build
A public class derived from OrderInterceptor (namespace ATAS.Indicators.Trading)
with a public parameterless constructor, marked with
[OrderInterceptor(id)]: the stable interceptor id (see
The interceptor id) and, optionally, DisplayName, the name in the list and in the rejection
the trader sees. OnCheckAsync is the only required
override:
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using ATAS.Indicators.Trading;
namespace ATAS.Docs.Samples.Trading;
[OrderInterceptor("mycompany.max-order-size", DisplayName = "Max order size")]
public sealed class MaxOrderSizeInterceptor : OrderInterceptor
{
[Display(Name = "Max order size, lots", Order = 10)]
public decimal MaxQuantity { get; set; } = 5;
protected override ValueTask<OrderCheckResult> OnCheckAsync(TradeOperation operation, CancellationToken token)
{
// Order is the order being placed, or for a modify the requested terms; null for a cancel. A reversal (sell 50
// against a long of 1) is not "increasing" but opens a position of its own: it is limited too.
var tooLarge = operation.Kind is TradeOperationKind.PlaceOrder or TradeOperationKind.ModifyOrder
&& (operation.IsPositionIncreasing || operation.IsPositionFlipping)
&& operation.Order is { } order
&& order.Quantity > MaxQuantity;
return ValueTask.FromResult(tooLarge
? OrderCheckResult.Reject($"At most {MaxQuantity:0.########} lots per order.")
: OrderCheckResult.Allow);
}
}
| Method | Called |
|---|---|
| constructor | when the trader enables the interceptor, at the start of the platform for an enabled one, and for every restart; the saved settings are applied right after it |
OnInitialize() |
once per instance, after the settings were restored; Context is available from here on. Throw to refuse the settings |
OnSettingsChanged() |
after OnInitialize, and after the trader changed the settings |
OnCheckAsync(operation, token) |
for every operation the interceptor may reject; returns the decision |
OnOperationObserved(operation) |
for an operation it may not reject (a close, Go flat, a protective order), after it was sent |
OnOperationCompleted(outcome) |
once for every operation this instance allowed: what happened to it |
OnDispose() |
once, when the platform stops using the instance |
OnDispose is called exactly once for every instance whose constructor completed, after its last running call
returned; no other method is called afterwards, and an exception thrown there is logged and ignored. The platform
stops an instance when the trader switches the interceptor off, after failures, when its library is reloaded, when
the tariff or the licence no longer allow it, and when the platform exits. Keep the constructor cheap and free of side
effects: to show the default settings of an interceptor that has never run, the settings window creates a temporary
instance that is never initialized and is disposed at once, so OnDispose must not rely on Context or on anything
OnInitialize built. OnDispose also runs while the platform exits, which waits for it only a few seconds: release
your own resources there and do not wait for the UI thread or a dispatcher.
What is checked and what is only reported
Every operation reaches the interceptor as a TradeOperation.
IsRejectable says which of the two calls gets it:
OnCheckAsync only gets the operations it may reject, OnOperationObserved the others.
| Operation | Kind |
Rejectable |
|---|---|---|
| A new order of any type, both orders of an OCO pair; a reverse is one market order of twice the position | PlaceOrder |
yes |
| A change of a working order: price, trigger price, quantity — also when the trader drags the stop or the target of a built-in ATM strategy | ModifyOrder |
yes |
| A cancel by the trader, a table command or third-party code; "cancel all" is one operation per order | CancelOrder |
yes |
A change of the stop-loss, take-profit or breakeven of a position's protective strategy (SetStopLoss, SetTakeProfit, SetBreakeven of an indicator, the chart's position line, Smart DOM, the heatmap, the breakeven button) |
ChangeProtection |
yes |
| The orders of a third-party ATM strategy, of a chart strategy or of an indicator | PlaceOrder, ModifyOrder, CancelOrder |
yes |
| Close position, close all, Go flat | ClosePosition, ClosePositions, GoFlat |
no: reported |
| An order sent as a close (a partial close from a table, the hedged close of copy trading) | PlaceOrder |
no: reported, while it reduces the position |
| The stop and target a built-in ATM strategy places after a fill, and the cancel and new order it makes to carry out an allowed change | PlaceOrder, CancelOrder |
no: reported, while it reduces the position |
| What the platform does to complete an operation already decided (the cancel of the other order of an OCO pair, the clean-up of a closed position), and the cancels of the Risk Manager and of a Smart DOM being closed | — | not passed at all |
Closing always works. A trader must always be able to get out: a close, close all and Go flat are never asked
about and never wait for an interceptor. They are reported to OnOperationObserved after they were sent, and they
withdraw the account's operations that are still being checked (those end as Withdrawn).
Every exemption holds only while the order reduces the position. Before an order that would be reported is sent, the platform checks against its own position of the account that the order neither increases the position nor turns it to the other side. A "close" or a protective order that would open or flip a position is checked like any new order. So the best a disguised operation can do is reduce the exposure.
IsPositionIncreasing and
IsPositionFlipping tell the same for the operations
you check: for a PlaceOrder, and for a ModifyOrder by its new terms, whether filling the order would make the
position larger or turn it. A rule that must never stand in the way of an exit allows everything else, as the sample
below does. Treat a Kind you do not know (a later version of the platform may add one) as some other operation, not
as an error.
Requests to built-in ATM strategies
The built-in protective strategies (stop-loss, take-profit, breakeven) keep their own orders; what a person or an extension asks of them is checked before the strategy acts:
- dragging the stop or the target of such a strategy, or changing its quantity, is a
ModifyOrderof that order with the actor of the trader (Chart,SmartDom, ...); cancelling it is aCancelOrder; SetStopLoss,SetTakeProfitandSetBreakevenare aChangeProtectionwith Protection: the kind and the new value as ProtectionChange describes it.
When the interceptors allow the request, the strategy carries it out: its resulting cancel and new order are only reported. When the position or the strategy changed while the request was being checked (the position was closed, the strategy stopped), the request is withdrawn. The commands of the strategy panel (Retry, Reset orders) and editing the strategy's settings are not trading operations and are not checked.
Who performs an operation
Actor is who performs this operation,
CreatedBy who created the order it is about (for a modify or
a cancel they may differ: the trader cancels an order a strategy placed). CreatedBy is for information only.
TradeActor |
Who |
|---|---|
Chart, SmartDom, Heatmap, OrdersTable, PositionsTable, AccountsTable |
the trader, in that panel. A buy or sell from a hotkey of a panel is reported as the panel |
Hotkey |
the trader, with a global command (close all, cancel all, flatten) |
IndicatorApi |
a chart indicator or chart strategy through its trading manager; which one is not known |
AtmStrategy |
an ATM strategy that is not one of the built-in protective strategies |
AtmProtective |
a built-in protective strategy placing or replacing the protection of a position |
Agent |
an AI agent through ATAS Connect |
CopyTrading |
copy trading, following another account |
RiskManager, PlatformCleanup, Platform |
the platform itself |
Unknown |
the platform could not tell; such an operation is checked like any other |
Treat a value you do not know like Unknown.
Operations decided together
Some operations are one decision over several orders. They share a BatchId, are all checked before any of them is sent, and if one is rejected none is sent:
- the two orders of an OCO pair placed by a panel or by an agent;
- an order on a group account: one operation per account of the group, with the real account in
Account, its quantity, and the group in GroupAccountId. A change or a cancel of a group order, and a request to the ATM strategy of a group, are decided per account the same way.
Your interceptor is asked about each operation of the unit in turn, then the next interceptor of the chain. An
operation you allowed in a unit that a later check rejects gets OnOperationCompleted with RejectedLater.
Orders of an SDK strategy that only share an OCO group name are checked one by one, and so are the orders an active
ATM strategy places for a position: its stop and its target reach the broker one after the other. An OCO pair on a
group account is one unit per account of the group: one account's pair can be sent while another account's is
rejected.
The check
OnCheckAsync runs on a thread-pool thread, never on the thread of a window or of a data feed. Return
OrderCheckResult:
OrderCheckResult.Allow: the operation goes on to the next interceptor, then to the broker;OrderCheckResult.Reject(reason): the operation is not sent, and the trader sees "Rejected by <DisplayName>: <reason>". Give a reason the trader understands ("Daily loss limit of 500 USD reached"); an empty one becomes a generic text, a longer one than 500 characters is cut. Anullresult is a failure of the interceptor (below).
A rejected operation ends like one the broker rejected: a new order becomes Failed and the panels and the
strategy's OnOrderRegisterFailed get the reason; a rejected modify leaves the working order as it was
(OnOrderModifyFailed); a rejected cancel leaves the order working (OnOrderCancelFailed). Identical rejection
notifications are shown once within a few seconds, so a strategy that retries every half second does not flood the
screen; the log keeps every one with the operation id, the actor, the interceptor and the time it took.
The platform takes a copy of the order's terms when the check starts. Right before it sends the operation it checks
again, without waiting for anything, that the world has not moved meanwhile: the Risk Manager has not blocked the
account, the connection is up, the order is unchanged and still working, no close or Go flat withdrew it, and the
instances that allowed it are still the running ones. If not, the operation is not sent, and you get
OnOperationCompleted with RejectedLater or Withdrawn.
Timeout and the chain
Each interceptor has a timeout, set by the trader in the list: 1000 ms by default, from 100 ms to 10 s. It covers
the wait in the interceptor's queue and the call. When it is over, token is cancelled, the operation is decided by
the failure policy and a late answer is ignored. The whole chain has 10 s for one operation (or one unit),
whatever the timeouts add up to: when it runs out, the operation is not sent ("the order interceptors did not answer
in time"). An operation that is still being checked after 1 s is written to the log with the interceptor that holds
it.
Keep the check short. A rule that asks a server should use the token and keep the timeout in mind: while the check runs, the trader's order waits.
When an interceptor cannot answer
An exception in any method, and a check that runs out of its timeout, is a strike. Five strikes within 60 s stop
the instance: the platform stops calling it, ignores its late answers, calls OnDispose once its running call has
returned (code that is running cannot be interrupted), and starts a new instance after 5 s, then after 30 s, then
after 2 minutes; after that the trader restarts it from the list. An instance that ran for 10 minutes before it failed
starts the pauses from the first one again. More than 1000 calls waiting in the queue also stop the instance: calls
are never dropped silently.
While an enabled interceptor cannot answer — its instance is starting or stopped, its check failed or timed out, its settings could not be restored — the trader's On failure setting decides:
- Reject (the default): every operation the interceptor would check is rejected ("Rejected by <name>: the interceptor cannot check operations now: ..."). For a risk rule a false rejection is cheaper than a false pass;
- Allow: operations pass without it.
At the start of the platform an enabled interceptor is in the chain as starting before the first connection can trade, so with Reject nothing is sent until it has started. If its library is still missing 30 s after the custom libraries were loaded (at most 2 minutes after the start when no custom library loads at all), it counts as removed.
Some states are not failures: the interceptor is simply not active and operations pass. The list shows the reason, and the trader gets a notification once:
- the trader switched it off;
- its library is removed;
- the tariff does not include order interceptors, or the account has no licence for its
[FeatureId](see Installing and selling). A tariff change or an expired licence must not stop all trading.
The mailbox and OnOperationCompleted
The platform never calls one instance concurrently. Checks, reports, completions and settings changes are queued in one mailbox per instance and delivered one at a time, in the order they happened, on a thread-pool thread. Your fields need no locks, and you see the operations in the order they were decided.
OnOperationCompleted(outcome) is called exactly once for every operation this instance allowed, with
Kind:
OperationOutcomeKind |
What happened |
|---|---|
Sent |
the operation was sent and the broker took it: a new order is working or done, a modify or cancel was accepted by the connection. A new order the broker did not answer within 60 s is reported Sent too, although it may not be among the working orders yet |
RejectedLater |
not sent: an interceptor later in the chain, the other order of its unit, or the platform's own final checks rejected it |
BrokerFailed |
sent, and the broker rejected it |
Withdrawn |
not sent: a close or Go flat withdrew it, or the order changed or ended while it was being checked |
So an interceptor that reserves something when it allows an operation — lots, a trade of the daily count, money —
releases it here. The sample below reserves the lots of an order it allows in OnCheckAsync:
if (MaxOpenQuantity > 0 && added > 0)
{
var open = GetOpenQuantity(operation, order.Direction);
if (open + added > MaxOpenQuantity)
return OrderCheckResult.Reject($"At most {MaxOpenQuantity:0.########} open lots of {order.SecurityId}: {open:0.########} are open or working already.");
_reserved[operation.OperationId] = (account, order.SecurityId, order.Direction, added, Environment.TickCount64);
}
and releases them whatever the outcome, because a sent order is counted from then on as a working order of the account:
protected override void OnOperationCompleted(OperationOutcome outcome)
{
// Exactly once for every operation this interceptor allowed: sent (the order works at the broker and is counted
// as a working order from now on), rejected by a later interceptor, failed at the broker, or withdrawn.
_reserved.Remove(outcome.OperationId);
}
Two exceptions:
- only an answer given within the timeout counts as allowing: a check that answers after its token was cancelled gets no completion. A check that computes its answer without waiting can still miss the timeout (the thread can be held up), so give a reservation a lifetime, as the sample does, instead of relying on its release alone;
- completions are not delivered to an instance that has been stopped or disposed meanwhile. Release what is still
reserved in
OnDispose; a new instance starts from the state of the accounts.
Treat an outcome you do not know as "not sent".
The context and the snapshots
Everything an interceptor gets is a snapshot: OrderSnapshot,
PositionSnapshot, AccountSnapshot and
TradeSnapshot, copied by the platform. Changing the order later does not change the
snapshot, and nothing an interceptor does with it reaches the order or the next interceptor. The operation carries
the account, the instrument, the order (for a modify the requested terms in Order and the working order in
WorkingOrder), the position of the account in the instrument when the operation was built, and two times:
TimeUtc, the wall clock, and
MarketTimeUtc, the replay time on a Market Replay
account; use the market time for rules about trading hours.
Context (IOrderInterceptorContext), available from OnInitialize on, reads the
current state at call time and returns snapshots too:
| Member | Returns |
|---|---|
GetAccounts() |
the accounts of the connected connections |
GetPositions(accountId) |
the open positions of an account (a flat position is not in the list) |
GetActiveOrders(accountId) |
the working orders of an account |
GetTrades(accountId, fromUtc) |
the fills of an account since a moment, oldest first, as far as the connection reported them in this session |
Log(message) |
writes a line to the platform log under the interceptor's name |
DisplayName |
the name the platform shows for the interceptor |
There are no push events: an interceptor learns about fills and positions from the operations it sees and from
Context when it is called.
Important
PnL is the connection's value. RealizedPnL of an account and of a position is copied as the connection reports
it: the period it covers (the trading day, the session, the whole history of the account) and whether commissions
are in it depend on the broker, and a fill (TradeSnapshot) has no profit or loss of its own. So a daily-loss rule
stores the value at the start of its own day and compares with that, and a losing-trade rule watches the position's
RealizedPnL drop between two operations — as the sample does.
Settings
Public properties with a getter and a setter are the interceptor's settings (Settings):
use [Display] for names, groups and order, [Browsable(false)] to hide one. They are global for the platform, not
part of a workspace, and shown by the Settings button of the list.
- Edited detached. The settings window works on a copy of the saved values, built from the type's properties
without calling your instance, so a check that takes a while never freezes the window. Apply queues the new
values to the mailbox: they are set on the instance between two calls and
OnSettingsChangedfollows. Settings your instance refuses (a setter throws) restart it with the last valid ones. - Restored strictly. A saved value that cannot be restored is an error, not a default: an interceptor whose limit could not be read must not start with no limit. The instance is not started, the list shows the reason, and the failure policy applies until the trader saves the settings again. The platform keeps the last settings your interceptor accepted.
- Refusing the settings. Throw from the setter of a property to refuse a value (a negative limit, a time zone that
does not exist): it is refused alike when the saved settings are restored and when the trader applies new ones,
and the trader sees the message. Throw from
OnInitializeto refuse a combination of values: the instance does not start and the failure policy applies until the settings change. An exception inOnSettingsChangedis only a strike. - Settings must be of concrete serializable types (numbers, strings,
bool, enums,TimeSpan, lists of them).
The interceptor id
The argument of [OrderInterceptor] is the interceptor id. The platform saves the trader's choice — enabled, the
place in the chain, the timeout, the failure policy, the settings — under this id, not under the class name. The rules
are those of the other kinds: the form <vendor>.<name> in lowercase letters, digits and dashes
(mycompany.risk-limits); the vendor atas is reserved; never change the id of a released interceptor, renaming the
class or the namespace is safe; two interceptors cannot share an id. Problems found while loading are written to the
platform log, and the interceptor is not listed:
| Code | Reason |
|---|---|
INTERCEPTOR_001 |
the id is not of the form <vendor>.<name> in lowercase |
INTERCEPTOR_002 |
the vendor atas is reserved |
INTERCEPTOR_003 |
another interceptor already uses the id |
INTERCEPTOR_004 |
the type is not public, is abstract or generic, or has no public parameterless constructor |
An agent connected through ATAS Connect reads the same in the tool extensions_get_state, which also lists the
interceptors with their state. No agent tool enables, disables, reorders or configures an interceptor.
Installing and selling
The DLL goes into the Extensions or Indicators folder, like a chart indicator, and is reloaded the same way
(Project setup); one DLL may contain
interceptors next to indicators, columns and modules. A new interceptor appears in the list, switched off.
Reloading while trading. When a new build of the DLL is loaded, the running instance keeps answering until the
new one has finished OnInitialize; then the platform switches to the new instance and disposes the old one, so a
reload leaves no gap in the checks. If the DLL is removed for good, the interceptor becomes not available
(operations pass) and keeps its place and settings in the list; it comes back with them when the DLL is installed
again.
To sell an interceptor, mark its class with [FeatureId] (Distribution): on an
account without the feature the interceptor is listed as not available and is not created. Order interceptors can
also be restricted by the tariff (Tariff restrictions); then every interceptor is not available until
the restriction is lifted, and a running one is stopped (it gets OnDispose). Both are read on every check, so losing
them takes effect at the next operation; a sign-in, also with another account, is followed at once, and an
interceptor that becomes allowed again comes back within 30 s.
What an interceptor cannot guarantee
An interceptor is a discipline and risk tool, not a guarantee against the trader.
- It runs inside the platform, in the trader's process, with full trust and the trader's rights. The checks are not a sandbox: other code in the process (another DLL) can reach a connection directly.
- The trader can switch it off, set its failure policy to Allow, or delete its DLL; until the trader enables it, a new interceptor does nothing.
- Orders placed outside this platform — the broker's web terminal, another application on the same account — never reach it.
- Closes and Go flat cannot be rejected, and the platform's protective orders only pass while they reduce the position.
What the platform does guarantee is that every documented trading path of the platform passes the chain. Rules that must hold against the trader — the rules of a prop-firm challenge, compliance limits of a firm — must also be enforced on the side of the broker or of a server.
Example: risk limits
The trader's limits in one interceptor: the size of an order, the open lots per instrument (working orders
included), the realized loss of the day, the trading hours and a cool-down after a series of losing trades. Only what
can make a position larger is limited: exits, cancels and stop changes always pass. Every value the rules need comes
from the operation and from Context; the plain fields need no locks because the platform calls the instance one
call at a time.
- The day is measured from the account's
RealizedPnLat the first operation the interceptor sees that day, in the time zone of the trading hours. - Losing trades are drops of the position's
RealizedPnLbetween two operations on the instrument; a rise ends the series. Several trades between two operations count as one. - Open lots are reserved when an order is allowed and released in
OnOperationCompleted: two orders checked one right after the other cannot both take the last free lots, and an order a later interceptor rejected frees its lots at once.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ATAS.DataFeedsCore;
using ATAS.Indicators.Trading;
namespace ATAS.Docs.Samples.Trading;
/// <summary>
/// Risk limits of a trader: the size of an order, the open lots per instrument, the realized loss of the day, the
/// trading hours and a cool-down after a series of losing trades. Only what can make a position larger is rejected:
/// exits, cancels and stop changes always pass.
/// </summary>
[OrderInterceptor("mycompany.risk-limits", DisplayName = "Risk limits")]
public sealed class RiskLimitsInterceptor : OrderInterceptor
{
// The platform calls one instance one call at a time, so plain dictionaries need no locks.
// The account's RealizedPnL at the start of the interceptor's own day, per account.
private readonly Dictionary<string, (DateTime Day, decimal StartValue)> _dayStart = new();
// The last RealizedPnL seen per account and instrument: a drop between two operations is a losing trade.
private readonly Dictionary<(string Account, string Security), decimal> _lastRealized = new();
private readonly Dictionary<string, int> _lossesInARow = new();
private readonly Dictionary<string, DateTime> _coolDownUntil = new();
// Lots allowed but not working yet, per operation: two orders checked one after the other cannot both take the
// last free lots. Released when the platform reports what happened to the operation, and dropped after
// ReservationLifetime in any case (see Prune).
private readonly Dictionary<long, (string Account, string Security, OrderDirections Direction, decimal Quantity, long ReservedAt)> _reserved = new();
// Longer than the 60 s after which the platform reports an order the broker did not answer.
private static readonly TimeSpan ReservationLifetime = TimeSpan.FromMinutes(2);
private string _timeZoneId = "America/New_York";
private TimeZoneInfo _timeZone = TimeZoneInfo.Utc;
private decimal _maxOrderQuantity = 5;
private decimal _maxOpenQuantity = 10;
private decimal _maxDailyLoss = 500;
private int _lossesBeforeCoolDown = 3;
private int _coolDownMinutes = 15;
// A setter that throws refuses the value: the settings window shows the error and the instance keeps (or restarts
// with) the last valid settings, so a mistyped limit never becomes "no limit".
[Display(Name = "Max order size, lots (0: no limit)", GroupName = "Size", Order = 10)]
public decimal MaxOrderQuantity { get => _maxOrderQuantity; set => _maxOrderQuantity = NotNegative(value); }
[Display(Name = "Max open lots per instrument, working orders included (0: no limit)", GroupName = "Size", Order = 20)]
public decimal MaxOpenQuantity { get => _maxOpenQuantity; set => _maxOpenQuantity = NotNegative(value); }
[Display(Name = "Max realized loss of the day, account currency (0: no limit)", GroupName = "Loss", Order = 30)]
public decimal MaxDailyLoss { get => _maxDailyLoss; set => _maxDailyLoss = NotNegative(value); }
[Display(Name = "Losing trades in a row before a cool-down (0: never)", GroupName = "Loss", Order = 40)]
public int LossesBeforeCoolDown { get => _lossesBeforeCoolDown; set => _lossesBeforeCoolDown = (int)NotNegative(value); }
[Display(Name = "Cool-down, minutes", GroupName = "Loss", Order = 50)]
public int CoolDownMinutes { get => _coolDownMinutes; set => _coolDownMinutes = (int)NotNegative(value); }
[Display(Name = "Time zone of the trading hours and of the day (e.g. America/New_York)", GroupName = "Hours", Order = 60)]
public string TimeZoneId
{
get => _timeZoneId;
set
{
_timeZone = TryFindTimeZone(value, out var zone) ? zone : throw new ArgumentException($"Unknown time zone '{value}'.", nameof(value));
_timeZoneId = value;
}
}
[Display(Name = "Trading starts", GroupName = "Hours", Order = 70)]
public TimeSpan TradingStart { get; set; } = new(9, 30, 0);
[Display(Name = "Trading ends", GroupName = "Hours", Order = 80)]
public TimeSpan TradingEnd { get; set; } = new(16, 0, 0);
protected override void OnInitialize()
{
// The default zone was never set through the setter (saved settings were). Throwing refuses the settings: the
// interceptor does not start and the trader sees the message; with the default failure policy the orders are
// rejected until the settings are fixed.
TimeZoneId = _timeZoneId;
}
protected override void OnDispose()
{
// Completions of operations still in flight are not delivered to a disposed instance; a new instance starts
// from the state of the accounts, so there is nothing to hand over. The temporary instance of the settings
// window is disposed without OnInitialize: nothing here may rely on Context or on what OnInitialize built.
_reserved.Clear();
}
protected override ValueTask<OrderCheckResult> OnCheckAsync(TradeOperation operation, CancellationToken token)
{
// The answer is computed at once, without waiting for anything. An answer that still comes after the timeout is
// ignored and never reported in OnOperationCompleted: its reservation expires (Prune).
Prune();
Track(operation);
return ValueTask.FromResult(Check(operation));
}
protected override void OnOperationObserved(TradeOperation operation)
{
// Closes, Go flat and protective orders cannot be rejected; they still show the account's state.
Track(operation);
}
protected override void OnOperationCompleted(OperationOutcome outcome)
{
// Exactly once for every operation this interceptor allowed: sent (the order works at the broker and is counted
// as a working order from now on), rejected by a later interceptor, failed at the broker, or withdrawn.
_reserved.Remove(outcome.OperationId);
}
private OrderCheckResult Check(TradeOperation operation)
{
// Only an order that can make the position larger is limited: never stand in the way of an exit.
// Unknown operation kinds of a later platform version are allowed.
if (operation.Kind is not (TradeOperationKind.PlaceOrder or TradeOperationKind.ModifyOrder)
|| operation.Order is not { } order
|| !(operation.IsPositionIncreasing || operation.IsPositionFlipping))
{
return OrderCheckResult.Allow;
}
var account = operation.Account.AccountId;
var time = GetMarketTime(operation);
if (!IsTradingTime(TimeZoneInfo.ConvertTimeFromUtc(time, _timeZone).TimeOfDay))
return OrderCheckResult.Reject($"Outside the trading hours {TradingStart:hh\\:mm}-{TradingEnd:hh\\:mm} ({_timeZone.Id}).");
var dailyLoss = _dayStart.TryGetValue(account, out var start) ? Math.Max(0m, start.StartValue - operation.Account.RealizedPnL) : 0m;
if (MaxDailyLoss > 0 && dailyLoss >= MaxDailyLoss)
return OrderCheckResult.Reject($"Daily loss limit of {MaxDailyLoss:0.##} reached (lost {dailyLoss:0.##} today).");
if (_coolDownUntil.TryGetValue(account, out var until) && time < until)
return OrderCheckResult.Reject($"Cool-down after {LossesBeforeCoolDown} losing trades until {TimeZoneInfo.ConvertTimeFromUtc(until, _timeZone):HH:mm}.");
if (MaxOrderQuantity > 0 && order.Quantity > MaxOrderQuantity)
return OrderCheckResult.Reject($"At most {MaxOrderQuantity:0.########} lots per order.");
// A modify adds only what it raises the working order by: the working order is counted already.
var added = operation.Kind == TradeOperationKind.ModifyOrder
? Math.Max(0, order.Quantity - (operation.WorkingOrder?.Quantity ?? 0))
: order.Quantity;
if (MaxOpenQuantity > 0 && added > 0)
{
var open = GetOpenQuantity(operation, order.Direction);
if (open + added > MaxOpenQuantity)
return OrderCheckResult.Reject($"At most {MaxOpenQuantity:0.########} open lots of {order.SecurityId}: {open:0.########} are open or working already.");
_reserved[operation.OperationId] = (account, order.SecurityId, order.Direction, added, Environment.TickCount64);
}
return OrderCheckResult.Allow;
}
private bool IsTradingTime(TimeSpan timeOfDay)
{
// A start after the end is a session over midnight.
return TradingStart <= TradingEnd
? timeOfDay >= TradingStart && timeOfDay < TradingEnd
: timeOfDay >= TradingStart || timeOfDay < TradingEnd;
}
private decimal GetOpenQuantity(TradeOperation operation, OrderDirections direction)
{
var security = operation.Order!.SecurityId;
var sign = direction == OrderDirections.Buy ? 1 : -1;
// The lots on the side of the order: the position if it is on that side, the working orders of that side,
// and what this interceptor allowed and has not heard back about yet. The position is read now, not taken from
// the operation: the operation may have waited for other interceptors while an earlier order filled.
// An order the broker took is counted as working and, until its report arrives, as reserved too: for that
// moment the rule errs on the side of rejecting.
var position = 0m;
foreach (var current in Context.GetPositions(operation.Account.AccountId))
{
if (current.SecurityId == security)
position = current.Volume;
}
var open = Math.Max(0, position * sign);
foreach (var working in Context.GetActiveOrders(operation.Account.AccountId))
{
if (working.SecurityId == security && working.Direction == direction)
open += working.Unfilled;
}
foreach (var reserved in _reserved.Values)
{
if (reserved.Account == operation.Account.AccountId && reserved.Security == security && reserved.Direction == direction)
open += reserved.Quantity;
}
return open;
}
/// <summary>
/// Follows the account through every operation the interceptor sees: the start of the day and the losing trades.
/// There are no fill or PnL events: what an interceptor knows of an account is what its operations carry and what
/// <c>Context</c> returns at call time.
/// </summary>
private void Track(TradeOperation operation)
{
var account = operation.Account.AccountId;
var time = GetMarketTime(operation);
var day = TimeZoneInfo.ConvertTimeFromUtc(time, _timeZone).Date;
// RealizedPnL is the connection's value: the period it covers and whether commissions are in it depend on the
// broker. So the loss of "our" day is the drop from the value of the first operation seen that day, and the
// series of losing trades starts again with the day (a connection may reset the values overnight).
if (!_dayStart.TryGetValue(account, out var start) || start.Day != day)
{
_dayStart[account] = (day, operation.Account.RealizedPnL);
_lossesInARow.Remove(account);
foreach (var stale in _lastRealized.Keys.Where(k => k.Account == account).ToList())
_lastRealized.Remove(stale);
}
if (operation.Position is not { } position || LossesBeforeCoolDown <= 0)
return;
var key = (account, position.SecurityId);
// A trade is seen when an operation shows its result: several losing trades between two operations on the
// instrument count as one. A connection that keeps no position object reports the instrument flat with a
// RealizedPnL of 0, so a change to or from 0 there says nothing about a trade; a rule that matters should count
// the account's trades (Context.GetTrades) instead.
if (_lastRealized.TryGetValue(key, out var last) && position.RealizedPnL != last)
{
if (position.RealizedPnL < last)
{
var losses = _lossesInARow.GetValueOrDefault(account) + 1;
if (losses >= LossesBeforeCoolDown)
{
_coolDownUntil[account] = time.AddMinutes(CoolDownMinutes);
losses = 0;
}
_lossesInARow[account] = losses;
}
else
{
_lossesInARow[account] = 0;
}
}
_lastRealized[key] = position.RealizedPnL;
}
private void Prune()
{
var now = Environment.TickCount64;
List<long>? expired = null;
foreach (var (operationId, reserved) in _reserved)
{
if (TimeSpan.FromMilliseconds(now - reserved.ReservedAt) > ReservationLifetime)
(expired ??= new List<long>()).Add(operationId);
}
if (expired == null)
return;
foreach (var operationId in expired)
_reserved.Remove(operationId);
}
private static decimal NotNegative(decimal value)
{
return value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value), value, "A limit cannot be negative.");
}
private static DateTime GetMarketTime(TradeOperation operation)
{
// The replay time on a Market Replay account, so the rules work in a replay as they do live.
return DateTime.SpecifyKind(operation.MarketTimeUtc, DateTimeKind.Utc);
}
private static bool TryFindTimeZone(string id, out TimeZoneInfo zone)
{
// IANA ids (America/New_York) work on Windows and macOS alike.
try
{
zone = TimeZoneInfo.FindSystemTimeZoneById(id);
return true;
}
catch (Exception e) when (e is TimeZoneNotFoundException or InvalidTimeZoneException or ArgumentException)
{
zone = TimeZoneInfo.Utc;
return false;
}
}
}
The default trading hours are those of the New York stock exchange; set the time zone and the hours of your market in the settings. This sample runs in the platform's own tests in the real interceptor host.
Limitations of this version
- No interactive checks: an interceptor cannot ask the trader to confirm an order or to give the reason of an entry.
- No push events (
OnOrderChanged,OnMyTrade,OnPositionChanged): rules read the state when they are called. - No completed trades with their profit or loss and no normalized daily realized PnL: the platform has no per-connector PnL model.
- The calling indicator or chart strategy is not named: its operations carry the actor
IndicatorApi. - A buy or sell from a panel's hotkey is reported as the panel, not as
Hotkey. - No locked configuration a firm could impose on its traders.
- The panels do not show that an order is being checked; an operation held longer than 1 s is written to the log.
Related articles
- Call model: the calls of all the extension kinds side by side.
- Chart strategies: orders: how a strategy sees a rejected order.
- Tariff restrictions and Distribution.