Skip to content

Matching engine ​

Spot orders are matched by the platform's spot engine (PHP, app/Services/Spot): price, then time priority, one market at a time under a database lock, every step in one transaction. It supports limit, market, stop-limit, OCO and trailing-stop orders, TP/SL on limit and market orders, time in force and post-only. The repository also contains an older optional matching engine written in Rust; the current spot engine does not support it.

Keep the Rust engine switched off

Leave MATCHING_ENGINE_ENABLED=false. If it is switched on, the spot engine refuses new orders on every market the Rust engine would handle ("This market is temporarily unavailable.") and writes a critical entry to storage/logs/laravel-YYYY-MM-DD.log, because the Rust engine still uses the old settlement code (no OCO, time in force, post-only, per-order reserved funds or market protection). The sections below describe the Rust engine for reference only.

Rules of the platform's own matching

Best price first, then the earliest order; the platform's book and the liquidity provider's book act as one book (users' orders win ties); fills at the resting order's price; market order protection; self-trade prevention (the new order's rest is cancelled). See Spot trading → How orders are matched.

15 minutesAdvancedDevOpsVerified against the platform code

When it's used ​

The Rust engine only matches markets that trade inside your exchange:

MarketMatched by
Takes liquidity from a provider (Binance)The platform, against the provider. Never the Rust engine.
Custom-token liquidity botThe platform. Never the Rust engine.
No liquidity provider, MATCHING_ENGINE_ENABLED=trueRefused by the current spot engine (see the warning above)
No liquidity provider, engine offThe platform

Don't turn it on: the platform's spot engine handles markets without a liquidity provider itself.

Settings ​

All in .env (read by config/matching_engine.php):

VariableDefaultMeaning
MATCHING_ENGINE_ENABLEDfalseUse the Rust engine for markets without a liquidity provider
MATCHING_ENGINE_FORCE_LARAVELfalseTemporarily send every market back to the platform's own matching, without changing ENABLED
MATCHING_ENGINE_HOST127.0.0.1Where the engine runs
MATCHING_ENGINE_PORT9000Its TCP port
MATCHING_ENGINE_TIMEOUT5Connection timeout, in seconds
MATCHING_ENGINE_RECONNECT_ATTEMPTS3Reconnection tries
MATCHING_ENGINE_RECONNECT_DELAY100Pause between tries, in milliseconds
MATCHING_ENGINE_PRICE_PRECISION100000000Prices are sent as whole numbers: price × this value (8 decimals)
MATCHING_ENGINE_QUANTITY_PRECISION100000000The same for quantities
MATCHING_ENGINE_SYMBOL_SEPARATOR/Symbol format sent to the engine (BTC/USDT)
MATCHING_ENGINE_DEBUGfalseExtra logging

Don't change the precision on a running engine

The engine stores prices and quantities as whole numbers. Changing the precision values while it holds orders would misread every order in its books. Change them only with empty books, then run a sync.

Build it ​

The engine is in rust-matching-engine/. Install Rust once, then build the release binary:

bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"

cd /var/www/exchange/rust-matching-engine
cargo build --release

The binary is target/release/rust-cex.

Run it ​

Start it from its own folder, because it saves its state in a state/ folder next to where it runs:

bash
cd /var/www/exchange/rust-matching-engine
pm2w start target/release/rust-cex --name matching-engine
pm2w save

When it starts, it prints Listening on 0.0.0.0:9000 and loads any saved order books.

The engine isn't in the list that pm:watcher manages, so PM2 alone keeps it running. PM2 restarts it if it crashes, and pm2w save plus pm2 startup bring it back after a reboot.

Block port 9000 from the internet

The engine listens on all network interfaces on port 9000 and has no password. Anyone who can reach that port could add or cancel orders in its books. Allow it only from the server itself:

bash
sudo ufw deny 9000/tcp

Then switch it on in .env and reload the configuration:

ini
MATCHING_ENGINE_ENABLED=true
bash
php artisan config:clear
php artisan horizon:terminate

Saved state ​

  • Each market's order book is saved to its own file in rust-matching-engine/state/.
  • It saves every 30 seconds and after every 100 operations, and once more when it stops cleanly (Ctrl+C or pm2 stop).
  • On start, it loads every file in state/.

Keeping it in sync with the database ​

The database is the source of truth. If the engine's books are lost (for example, the state/ folder was deleted), it's rebuilt from the open orders in the database:

  • Automatically: the scheduler runs matching-engine:check-sync every 5 minutes. If a market has open orders in the database but none in the engine, it runs a full sync.
  • By hand:
bash
php artisan matching-engine:status                 # can the platform reach the engine?
php artisan matching-engine:sync --dry-run         # show what would be loaded
php artisan matching-engine:sync                   # load all markets
php artisan matching-engine:sync --market=ABC-USDT # one market
php artisan matching-engine:sync --force           # even if the engine already has orders

After a restart

When the platform notices an empty engine book while placing an order, it also queues a sync on the high queue. No Horizon worker listens to that queue, so in practice the 5-minute check-sync task does the repair. Run matching-engine:sync yourself if you can't wait.

Monitoring ​

  • Admin → System Monitor shows the engine as online or offline when it's enabled (and as maintenance when it's off). If System Monitor alerts are on, an offline engine is included in the alert email.
  • pm2w logs matching-engine shows its output, including the auto-save messages.
  • Platform-side errors are logged in storage/logs/laravel-YYYY-MM-DD.log with the prefix [RustMatchingEngine].

Turning it off ​

Set MATCHING_ENGINE_ENABLED=false (or MATCHING_ENGINE_FORCE_LARAVEL=true for a short test), then run php artisan config:clear and php artisan horizon:terminate. New orders are matched by the platform again.

Owner documentation for the CryptoTech exchange platform.