> For the complete documentation index, see [llms.txt](https://docs.bbx.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bbx.com/business/on-chain-perpetual-trading/trading-mechanism.md).

# Trading Mechanism

1. **System Architecture Overview**

The perpetual trading system consists of four core components: Order Matching, Price Mechanism, Position Lifecycle Management, and PnL Calculation.

2. **Order Matching**

BBX uses a centralized order matching engine with a price-time priority rule:

* Price Priority: Higher buy prices and lower sell prices receive higher priority.
* Time Priority: At the same price level, orders placed earlier are matched first.
* Trades execute at the maker price; fees are determined by whether the order is a maker or taker.
* When a limit order is partially filled, the remaining portion retains its original timestamp in the order book.
* The matching engine operates independently of the mark price and risk assessment systems, ensuring that liquidation logic is not affected by short-term liquidity conditions.

3. **Index Price**

The BBX Index Price is independently constructed by BBX. It aggregates real-time trading data from leading global spot exchanges to compute the fair market value of an underlying asset, serving as the core benchmark for mark price calculations. For details, see '3.2.3 BBX Index Price.'

4. **Mark Price**

The mark price is the fair value of a perpetual contract, used for all risk-related calculations (unrealized PnL, margin adequacy checks, forced liquidation, ADL) — not the last traded price. It is designed to track the underlying spot market while resisting short-term volatility, low-liquidity trades, and price manipulation.

Formula: Mark Price = Median (Price 1, Price 2, Contract Price)

**Price 1**

Price 1 represents an index-based forecast that accounts for the time remaining until the next funding event.

Price 1 = Index Price × (1 + Funding Rate × (Time to Next Funding Settlement ÷ Funding Interval))

This component reflects the expected convergence of the perpetual contract price toward the spot price over the funding period.

**Price 2**

Price 2 incorporates the latest basis between the perpetual contract and the index price.

Price 2 = Index Price + Moving Average Basis × (1 + Funding Rate)

**Contract Price**

The contract price refers to the most recent transaction price of the perpetual contract in the order book.

**Moving Average**

The moving average measures the average deviation between the perpetual market and the underlying index.

Calculation: Moving Average Basis = Moving average of ((Best Bid + Best Ask) ÷ 2 − Index Price)

The basis is sampled using a rolling 30-minute window to smooth out short-term fluctuations.

**Median Selection Mechanism**

After calculating Price 1, Price 2, and the Contract Price, the system selects the median value as the final mark price. This median-based approach ensures that extreme outliers — whether from sudden trades or anomalous reference prices — do not have a disproportionate impact on liquidation or margin outcomes.

**Deviation Protection**

If the deviation between the index price and the calculated mark price exceeds a predefined threshold (e.g., greater than 1%), additional safeguards are applied. In this case:

* The mark price may be directly anchored to Price 2.
* This prevents excessive divergence under anomalous market conditions.

**Fallback Protection Mechanism**

In rare circumstances where a stable and reliable index price is unavailable (e.g., during exchange outages or severe data distortion), BBX will activate the Last Traded Price protection mechanism. Under this mechanism:

* The mark price temporarily references the most recent contract transaction price.
* A bounded adjustment range is applied to prevent abrupt changes.
* Risk calculations can continue without interruption.

Once reliable index data is restored, the system automatically resumes standard mark price calculation.

**Mark Price and Unrealized PnL**

A trader may observe positive or negative unrealized PnL immediately after order execution. This is because the actual execution price may differ slightly from the mark price. This is normal and does not represent an immediate loss. Traders should focus on the liquidation price and margin ratio rather than short-term unrealized PnL fluctuations.

5. **Position Lifecycle**

In perpetual trading, a position represents a trader's directional exposure to an underlying asset. The position lifecycle describes how a position is created, adjusted, and ultimately closed over time.

**Position Creation**

A position is formed when a trader executes a trade in the perpetual contract market.

* Buying a perpetual contract establishes a long position.
* Selling a perpetual contract establishes a short position.

Once the trade is executed, the following are established: position direction (long or short), position size, and entry price. The position takes effect immediately upon execution.

**Position Adjustment**

After a position is opened, its size and average entry price may change as a result of subsequent trades. Position adjustments include:

* Increasing position size by executing trades in the same direction as the existing position.
* Reducing position size by executing a reverse trade to partially close the position.
* Reversing the position direction by fully closing the existing position and opening a new one in the opposite direction.

Each adjustment updates the position size, average entry price, and realized PnL accordingly.

**Unrealized PnL**

As market prices change, an open position continuously generates unrealized PnL.

* Unrealized PnL reflects the difference between the position's entry price and the current mark price.
* Unrealized PnL fluctuates with market movements.
* Unrealized PnL is only settled after the position is reduced or closed.

Unrealized PnL plays a crucial role in margin assessment and liquidation risk evaluation.

**Realized PnL**

Realized PnL is generated when a position is partially or fully closed. Realized PnL arises when:

* A portion of the position is closed through a reverse trade.
* The trader voluntarily closes the position.
* The position is closed through liquidation.

Once realized, the PnL is settled into the trader's account balance and no longer fluctuates with market prices.

**Position Closure**

A position can be closed in one of the following ways:

* Voluntary Closure: The trader submits a trade to fully offset the position.
* Forced Closure (Liquidation): The position is automatically closed when margin no longer meets requirements.

In both cases, the position size is reduced to zero, and all remaining unrealized PnL is converted to realized PnL.

**Relationship with Risk Management**

Throughout the position lifecycle, the platform's risk management system continuously monitors positions.

* Position size affects leverage ratio and risk exposure.
* Unrealized PnL affects available margin.
* Market price movements affect liquidation risk.

The position lifecycle in perpetual trading describes the entire process from opening, through adjustment, to final closure. BBX ensures accurate accounting and consistent risk assessment throughout the entire perpetual position lifecycle by tracking position status, entry price, and PnL in real time.

6. **PnL Calculation**

Profit and Loss (PnL) measures the financial result of a user's trading activity. PnL is divided into unrealized PnL and realized PnL, each playing different roles in position tracking and risk management.

* Unrealized PnL: Continuously updated based on average entry price, position size, direction, and current mark price. Used for margin ratio calculations and liquidation checks.
* Realized PnL: Generated through partial or full position closure or funding payments, and immediately settled to the account balance.
* Partial Closure: Only the PnL for the closed quantity is realized; the average entry price of the remaining position is unchanged.

Average Entry Price Formula: Average Entry Price = Total Position Value ÷ Total Contract Quantity

PnL values directly impact margin utilization, liquidation prices, and risk exposure. Traders should closely monitor unrealized PnL, margin ratio, and liquidation thresholds — especially during periods of high market volatility.
