Markont

Markont is an esoteric programming language created by Tanner Swett in 2013 while up late at night.

Syntax
::= ( "BUY" | "SELL" ) number symbol ( "MARKET" | "LIMIT" number )

"symbol" is any non-empty sequence of uppercase letters, and "number" is any non-negative integer.

Semantics
An order consists of a position, which is either BUY or SELL; a symbol; the disposition, which is either MARKET or LIMIT; and, if the disposition is LIMIT, a price. The state of a Markont interpreter consists of the order book, which is a multiset of orders, and, for each symbol, the last trade price of that symbol, which is initially zero.

Two orders cross if one of them is a BUY order and the other is a SELL order; the orders have the same symbol; and either one of the orders is a MARKET order, or the price of the BUY order is greater than or equal to the price of the SELL order.

When an instruction is executed, the specified number of copies of the order are placed. When an order A is placed, if it crosses another order B, then both orders A and B are deleted, and the last trade price of the corresponding symbol is set to the price of order B. (If order B is a MARKET order, the program halts.) If order A crosses multiple orders, then B is the one with the highest price (if A is a SELL order) or the one with the lowest price (if A is a BUY order); if any of the orders which A crosses is a MARKET order, the program halts.

A "when" block is active if the last trade price of the specified symbol compares with the given number in the specified manner. Execution proceeds by choosing an arbitrary active "when" block and executing every instruction within it, in order. This is repeated until there are no active "when" blocks.

Example
when ( A < 3 ) { BUY 3 A LIMIT 3 BUY 1 A LIMIT 4 BUY 4 A LIMIT 5 BUY 1 A LIMIT 6 BUY 5 A LIMIT 7 SELL 1 A MARKET } when ( A > 6 ) { SELL 2 A LIMIT 7 SELL 7 A LIMIT 6 SELL 1 A LIMIT 5 SELL 8 A LIMIT 4 SELL 2 A LIMIT 3 BUY 1 A MARKET }

In the above program, the first "when" block executes once, then the second "when" block executes once, then execution halts. The resulting last trade price of A is 4, and the order book consists of the following orders: BUY 1 A LIMIT 3, SELL 3 A LIMIT 4, SELL 4 A LIMIT 6.