Pre-Trade Risk Gateway
Prerequisites: Order Gateway and Risk Checks, Trade Lifecycle Overview
Build the firm's order gateway, which every AAPL strategy order passes through before it reaches the exchange. It runs the article's pre-trade risk checks in a fixed order, then forwards the order or rejects it with the name of the first check it failed.
What to implement
process_commands(max_order_qty, collar_ticks, position_limit, bucket_capacity, refill_interval, commands)returns the printed lines in command order.- The five integers are the gateway's limits, loaded once on the cold path.
- Each command is one line that starts with a timestamp
t, an integer number of microseconds since midnight. Timestamps never decrease from one command to the next. - Prices are integer ticks and quantities are positive integers. Symbols are short uppercase names such as
AAPL. Order ids are unique acrossNEWcommands. - On stdin, the first five lines are the limits in the order of the parameters above. The sixth is the number of commands, and each remaining line is one command.
- There are three parts, each adding a check on top of the previous ones. One solution must pass all eleven tests.
| Command | Meaning | Prints |
|---|---|---|
t REF symbol price | Set symbol's reference price | nothing |
t NEW id symbol side price qty | An order to check; side is B (buy) or S (sell) | ACCEPT id or REJECT id REASON |
t FILL id qty | qty of accepted order id executed at the exchange (Part 2) | nothing |
t CANCEL id | Cancel whatever is still open on order id (Part 2) | nothing |
t POS symbol | Report the symbol's risk state (Part 2) | POS symbol position open_buy open_sell |
The four checks
The gateway runs the checks in this order and stops at the first one that fails. That check's code is the REASON. An order that passes all four is accepted.
| Order | Check | Rejects the order when | Reason |
|---|---|---|---|
| 1 | Max order size | qty > max_order_qty | SIZE |
| 2 | Price collar | the price is more than collar_ticks ticks from the symbol's reference price | COLLAR |
| 3 | Position limit | the worst-case position after this order would pass position_limit (Part 2) | POSITION |
| 4 | Throttle | the token bucket is empty (Part 3) | THROTTLE |
Part 1: Size and collar
REFsets or replaces a symbol's reference price. Each symbol has its own.- A
NEWorder is rejected withSIZEwhenqty > max_order_qty. - Otherwise it is rejected with
COLLARwhenabs(price - ref) > collar_ticks, whererefis the symbol's current reference price. - Both limits are inclusive: a quantity equal to
max_order_qtypasses, and so does a price exactlycollar_ticksaway. - An order that fails both checks reports
SIZE, because size is checked first.
Limits and guarantees
- Every
NEWnames a symbol that has already received aREF. There are at most 105 commands. - Timestamps lie between 0 and 86,400,000,000, one day in microseconds, which is too large for a 32-bit
int. With many orders open, positions and open quantities can also pass 231. - Store timestamps, positions, open quantities, and
position_limitin 64-bit integers (std::int64_t). - Prices, quantities, ids,
max_order_qty, andbucket_capacityare between 1 and 109. collar_ticksis between 0 and 109, andrefill_intervalis between 1 and 86,400,000,000.
Tests 1–3 cover this part. They use only REF and NEW, and their position limit and bucket are large enough that checks 3 and 4 never reject.
Part 2: Position limits with open orders
The position check must hold even if every accepted order fills. Each symbol tracks three numbers:
position: the net filled quantity. Buys add to it and sells subtract, so a short position is negative.open_buy: the total unfilled quantity of accepted buy orders that are still open.open_sell: the same for sells.
The check
- A buy of
qtyis rejected withPOSITIONwhenposition + open_buy + qty > position_limit. If all open buys and this one filled, the position would be longer than the limit. - A sell is rejected when
position - open_sell - qty < -position_limit, the same test on the short side. - Open buys and open sells do not offset each other, because either side can fill without the other.
- A rejected order never counts as open.
FILL and CANCEL
FILL id qtyreports thatqtyof accepted orderidexecuted. The order's open quantity drops byqty, and the position moves byqty, up for a buy and down for a sell.- Every
FILLnames an accepted order that is still open, and itsqtyis at most that order's open quantity. CANCEL idremoves whatever is still open on orderid, so that quantity no longer counts as open.- A cancel of an unknown id, a rejected order, a completely filled order, or an already cancelled order changes nothing.
- Neither command prints anything, and neither passes through the checks.
Output of POS symbol:
POS symbol position open_buy open_sell
- A symbol with no accepted orders prints zeros.
Tests 4–6 and 11 cover this part. Their bucket never runs out of tokens.
Part 3: The token-bucket throttle
The last check limits how fast orders leave the gateway, using a token bucket: a counter of permits that holds at most bucket_capacity tokens.
Refill
- The bucket starts full at time 0.
- A new token arrives at every positive multiple of
refill_interval(atrefill_interval,2 * refill_interval, and so on), whether or not an order is waiting. - A token that arrives when the bucket already holds
bucket_capacitytokens is discarded. - A token that arrives at time
tis available to an order with timestampt.
Spending
- An order that passes the first three checks is accepted if the bucket holds at least one token, and the accepted order removes one token.
- If the bucket is empty, the order is rejected with
THROTTLE. - Only accepted orders take a token. An order rejected by any check, the throttle included, leaves the bucket unchanged: it never leaves the gateway, so it does not count toward the exchange's message rate.
REF,FILL,CANCEL, andPOSnever touch the bucket.
Every quantity in the bucket is an integer, so no floating-point rate is needed.
Tests 7–10 cover this part.
1000 100 1000000000 1000 1 9 0 REF AAPL 19011 0 REF MSFT 41250 1 NEW 1 AAPL B 19200 5000 2 NEW 2 MSFT S 41250 300 3 NEW 3 AAPL B 19200 300 4 REF AAPL 19150 5 NEW 4 AAPL B 19200 300 6 NEW 5 MSFT B 19200 300 7 NEW 6 AAPL S 19011 300
REJECT 1 SIZE ACCEPT 2 REJECT 3 COLLAR ACCEPT 4 REJECT 5 COLLAR REJECT 6 COLLAR
The first five lines are the limits: at most 1000 per order, at most 100 ticks from the reference, and a position limit and bucket large enough not to matter here.
Order 1 fails both the size check (5000 > 1000) and the collar (19200 is 189 ticks above 19011). Size is checked first, so it reports SIZE. Order 3 has an acceptable size but the same distant price, so it reports COLLAR.
After REF AAPL 19150 moves the reference, 19200 is only 50 ticks away and order 4 passes. Order 5 is collared against MSFT's own reference of 41250, and order 6 sells at 19011, which is now 139 ticks below the new AAPL reference.