Matching Engine – Market Orders (Reference Price Rule)

In the previous post I implemented the “best limit” crossing rule, matching incoming limit orders against outstanding market orders. In this post I am going to complete the logic related to market orders matching by implementing the last use case – matching market orders to opposite side market orders. To do this we will introduce and explain a notion of reference price. The complete source code for this and other posts in the series is available from my GitHub repo:

Crossing Market Order with Opposite Side Outstanding Market Orders

Consider when a market order matches with another market order in the opposite order book. At what price should the resulting trade occur? There are two possibilites here:

  • the opposite order book with the resting market order also contains one or more outstanding limit orders – in this case the opposite book has a “best limit” price we discussed in the previous post and this price becomes the price for the trade
  • the opposte order book does not have outstanding limit orders, so the “best limit” price is not defined. In this case the trade occurs at the “reference price”. Most often reference price is the last traded price for a security. An exchange sets the reference price at the opening, perphaps to the closing price from the last session, or the result of the opening auction session.

Lets capture the first rule (best limit price is available) using Cucumber:

And the tests necessary for the second rule (when reference price is used):

To make the tests pass lets add the logic to the MatchingEngine class:

Here is some explanation for the new code we added:

  • Lines 4 to 10 – adding additional interface to set and check a reference price
  • Lines 39 to 45 – matching logic when both incoming and opposite orders are market; if best limit is available in the opposite book the trade is made using this price; if best limit is not available, reference price is consulted to generate the trade
  • And, finally, the line 17: every time a trade occurs the reference price is updated to this “last traded price”. I have added the following tests to capture this behavior:

All tests are green! This completes our implementation for the two most fundamental order types: limit and market. In the next post I will add support for another type – pegged orders. Previous posts in this series:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: