> For the complete documentation index, see [llms.txt](https://fermi-dex.gitbook.io/fermi-dex-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://fermi-dex.gitbook.io/fermi-dex-docs/technical-overview/architecture/matching-logic.md).

# Matching Logic

Crossing the spread

{% hint style="info" %}
Fermi DEX optimistically matches orders on a **Price-Time priority basis**; the orders are later finalised atomically, using Just-in-time liquidity.
{% endhint %}

Fermi DEX optimistically matches orders on a **Price-Time priority basis**; the orders are later finalised atomically, using Just-in-time liquidity.

## How orders are Matched on Fermi

Our internal accounting model adapts the serum/openbook dex model, to make it compatible with just-in-time liquidity. We briefly describe some important accounts below.\
\
Firstly, the open-orders struct stores user specific information:

1. How much of the base and quote currency that user has ~~in open orders or~~ settleable
2. A list of open orders for that user on that market.
3. Market: holds metadata about the market (e.g. important constants like tick size and references to the other accounts below)
4. Base Currency Vault: an SPL token account that holds base currency balances
5. Quote Currency Vault: an SPL tokena account that holds quote currency balances<br>

{% hint style="info" %}
Crucially, on Fermi DEX, there is no concept of "locked liquidity", unlike OpenBook. All liquidity on Fermi is free to be withdrawn at any time, or used to open multiple orders. Trade finalisation happens atomically, and this ensures that users always have access to their assets.
{% endhint %}

**Other important accounts:**

* Orderbook: There’s one account for bids and another for asks. **For JIT purposes**, we ensure every order is pushed to the orderbook (instead of just the unfilled quantity)
* Event Queue: reports the list of outputs from order matching: trades. Also logs the outputs of **FinaliseMatch** - to ensure no double spending occurs.

## Event Flags

Events are emitted when matching occurs.

If you have a flag state of 9, that would correspond to the binary representation `0b1001`, which means that the `Fill` and `Maker` flags are both set. If you have a flag state of 18, that would correspond to the binary representation `0b10010`, which means that the `Bid` and `ReleaseFunds` flags are both set.
