A Decentralized Matching Engine is one in which orders are matched by a distributed set of network participants. On Hubble Exchange, these network participants are the app-chain's validators.
A matching engine is a key component of a financial exchange that matches buy orders with sell orders. It is critical for facilitating trades and maintaining an orderly market.
In a traditional, centralized exchange (like the NYSE or NASDAQ), the matching engine is a centralized system. It pairs up buy orders (from those who want to buy a particular asset) with sell orders (from those who want to sell the asset). It does this based on certain criteria such as the price and the quantity of the asset in the order, as well as the timing of the order.
Now, in the context of Hubble Exchange, the matching engine works similarly but in a decentralized manner.
In the past, exchanges haven't delivered decentralized matching engines. It's not feasible to create one using smart contracts. Substantial gas costs are associated with iterating over stored orders & checking various conditions. This process, executed upon every order placed, quickly becomes unscalable.
The solution: a customized app-chain.
On Hubble Exchange, the Decentralized Matching Engine is embedded within the block-building process of the app-chain.
When users place orders, their validity is confirmed and they are stored (indexed) locally in the validator node, which also maintains all the information about open positions, margins, pending funding, and margin ratios.
When a validator is randomly selected to produce the next block, that's when the magic happens. A function (essentially a chunk of code) called "buildBlock", responsible for the block building process of the chain, executes several important steps:
First, it fetches active markets and open orders.
Then, it evaluates open positions for potential liquidations and executes them if necessary.
Next, the matching engine is run, finding pairs of buyers and sellers to complete trades.
The final step: all of these operations are relayed as local transactions, before the usual transaction bundling process resumes.
By embedding the Matching Engine within the block-building process, we've achieved a major feat - a truly decentralized order matching engine.