# Overview

### About DerivaDEX

DerivaDEX is a noncustodial decentralized derivatives exchange focused on providing a high-performance trading experience for perpetual swaps. Utilizing a custom off-chain network for order matching and trade execution, DerivaDEX ensures low latency and a front-running resistant environment. Deposits and withdrawals are managed by secure Ethereum smart contracts, providing full transparency and user custody.

Owned and governed by the DerivaDAO, all key updates and changes to the exchange are determined through decentralized governance, empowering DDX token holders with voting rights.

### Key Features

1. **Highly Liquid Order Book**: A robust central-limit order book facilitates high liquidity and deep trading pairs.
2. **Cross-Margin Leverage**: Offers flexibility in capital usage, tailored to traders’ needs.
3. **High-Performance Matching**: Trusted hardware-enabled nodes ensure off-chain, tamper-resistant execution.
4. **Real-Time Price Feeds**: Secures liquidation processes with a DAO-controlled insurance fund.
5. **Sustainable Liquidity Mining**: Incentivizes long-term liquidity provision by rewarding active participants with increased voting power.

### Availability

<mark style="color:green;">**The mainnet version is currently in a limited-access pilot on Ethereum, and a testnet is accessible on Sepolia at**</mark> [<mark style="color:green;">**testnet.derivadex.io**</mark>](https://testnet.derivadex.io)<mark style="color:green;">**.**</mark>

### Differentiation from Competitors

Unlike decentralized exchanges that rely solely on on-chain matching, DerivaDEX uses a hybrid approach that combines on-chain custody with off-chain performance, allowing for lower latency, deeper liquidity, and more responsive trading.&#x20;

Its governance structure, centered around the DerivaDAO, ensures that users have a direct say in the evolution of the exchange.

Unlike centralized exchanges, DerivaDEX users maintain self-custody of funds.&#x20;


# Getting started

Welcome to DerivaDEX! This is a brief guide to making your first trade on DerivaDEX. DerivaDEX uses a central-limit orderbook and cross-margin collateral, so should feel very familiar to users accustomed to trading on centralized exchanges.

This guide will walk you through setting up your account, depositing funds, and placing your first trade.

### Step 1: Connect your wallet

1. Choose a supported wallet (e.g., MetaMask,).
2. Ensure your wallet is set to the Ethereum Mainnet or Sepolia (for testnet).
3. Click **"Connect Wallet"** on the DerivaDEX platform.

### Step 2: Complete KYC verification

1. Follow the instructions to verify your identity. You will need an ID, proof of residency, and your Ethereum address. Not all jurisdictions are eligible for trading at this time.
2. KYC is mandatory for all traders. For any problems with KYC, please reach out directly to [Blockpass support](https://help.blockpass.org/hc/en-us/requests/new?ticket_form_id=5717485213081).&#x20;

### Step 3: Approve USDC tokens

1. Click **“Approve”** to enable the platform to interact with your USDC.
2. Sign the transaction using your wallet of choice.

{% hint style="info" %}
You will normally only need to do this step the first time you use the exchange. Token approvals are a security feature that ensures the smart contract can interact with only the specified amount of tokens, minimizing risk.
{% endhint %}

### Step 4: Deposit funds

1. Go to **“Deposit”** and select the asset (e.g., USDC).
2. Specify the amount and complete the transaction from your wallet.

![Select "Deposit" to open the deposit form](/files/yCFiDVzDL5CVhiVVeGpA)

### Step 5: Place your first trade

1. Select the trading pair (ETHP, BTCP).
2. Choose your order type (limit, market, etc.).
3. Review and place your trade.

### Managing your positions

When your order fills, which will be immediate if you place a market order, you should see a new open position. The table at the bottom of the interface will display your position under the "Positions" tab, and you can find your trade history under the "Filled Orders" tab.                                                   &#x20;

### Withdrawing collateral

Withdrawals are a two step process. First, a withdrawal request is made to the DerivaDEX operators, and then, after the withdrawal has been included in a checkpoint, the withdrawal can be finalized with a user-initiated on-chain transaction.&#x20;

To make a withdrawal, select "withdraw". Then, input the following information:

* **Withdraw from**: the strategy to withdraw from. At the moment, DerivaDEX only supports the "main" strategy, so you will not need to modify this.
* **Withdraw to**: the Ethereum address to withdraw funds to. This will auto-populate to the connected Ethereum address, and cannot be modified.
* **Collateral type**: the collateral token you intend on withdrawing. DerivaDEX only supports USDC deposits at this time, and consequently, only supports USDC withdrawals, so this will not need to be modified.
* **Amount**: The amount of the collateral token you intend on withdrawing.&#x20;

After entering the information above, you can proceed by clicking "Initiate Withdrawal". Once a new checkpoint has elapsed, you will receive an alert that your withdrawal may be completed by clicking the "Complete Withdrawal" button, triggering an on-chain transfer of the tokens. Because you need a checkpoint to finalize after you have first initiated the withdrawal desire, you can expect withdrawals to take approximately 10 minutes (approximately the length of an epoch).&#x20;

**Alternatively, you can choose to submit a checkpoint yourself.** This process will cost some Ethereum network gas, and will enable you to complete your withdrawal immediately afterwards.&#x20;

### Troubleshooting

* **Problems with KYC:** Reach out directly to Blockpass and open a support ticket: <https://help.blockpass.org/hc/en-us/requests/new?ticket_form_id=5717485213081>
* **Ethereum fees**: Be mindful of Ethereum gas fees for deposits and withdrawals during high network congestion. There are no gas fees for trading.
* **Common Errors**: If you encounter issues connecting your wallet, try refreshing or switching networks.

**Need More Help?**

Visit our [FAQs](/troubleshooting-and-faq/faq).


# Deposits

### Making a USDC collateral deposit

Ensure you have an Ethereum address and USDC to deposit as collateral.&#x20;

For use on the Sepolia testnet, you will need to make sure you are on the Sepolia network and have Sepolia ETH and USDC.&#x20;

{% hint style="info" %}
Have USDC but having trouble making a deposit on testnet? You may have tokens from an outdated deployment. Hop in the Discord and request support.
{% endhint %}

Select "Deposit" in the left side of the UI.&#x20;

![](/files/OYR6QxOVpWfYXRGDJJqM)

When the Deposit pane opens, approve the USDC token if you have not already. Then, select the amount of USDC you would like to deposit as collateral. Please note, there are currently several important limitations

* Traders can only deposit 10,000 USDC. If you deposit more collateral, it will automatically be added to your frozen collateral. You can withdraw it, but it is not available as collateral for trading.&#x20;
* Only USDC is currently supported as collateral.
* There is a deposit minimum of 1,000 USDC.

![](/files/wtdarSVi8xxxZwSKKB5R)

### Making a DDX deposit

Users can also deposit DDX to pay trading fees.&#x20;

Select the "Deposit" button from the top left of the UI.

![](/files/vK7YH5BqKpWSpY9o0TFB)

Next, navigate to the "Deposit DDX" tab in the panel that comes out. Then, "approve token" so that you can deposit DDX.

![](/files/c4Cqeq4QFfQ9HiZo9Lr0)

Finally, enter the amount of DDX that you would like to deposit.&#x20;

![](/files/L2v16dskT87IS7GF7V2Y)

Select "Deposit" and sign the transaction using your wallet. Your DDX will be available on the exchange in 6 confirmations.&#x20;

{% hint style="info" %}
DDX is not used as collateral: DDX can be used on the exchange to pay for trading fees (and receive a discounted rate).&#x20;
{% endhint %}

If you would like to use DDX to pay for trading fees, toggle this option using the UI. You will need to sign this request using your wallet.&#x20;

![](/files/lmXf9hSsxVs3mjPb85Yj)


# Withdrawals

To make a withdrawal, a wallet must be connected, and a user must have collateral or DDX available to withdraw.

### USDC Withdrawals

First, select the "withdraw" button, located on the left side of the interface.&#x20;

![](/files/wTHtBMQx0vM2CgefFRk7)

After doing this, the withdrawal panel will open.&#x20;

![](/files/f2CWGpr3k7NMbbWy5rW9)

Here, you can select:

* which Strategy you want to withdraw collateral from (currently, only one strategy per trader is supported)
* The type of collateral you will withdraw (only USDC is supported currently)
* The amount you want to withdraw. Note: you can only withdraw funds in "free collateral". If you want to withdraw all collateral, you must first close your open positions and orders.&#x20;

{% hint style="info" %}
You cannot withdraw to a different address than the one which you have deposited with.&#x20;
{% endhint %}

After you've made your selections, select "initiate withdrawal". This will freeze your funds from being used as collateral on the exchange. **Please be aware, this will affect your free collateral as well as your liquidation price on any open positions.**&#x20;

**Pending:** "pending" reflects the amount of USDC you have initiated for withdrawal, but is not yet ready to be completed. If you initiate multiple withdrawal requests before the next on-chain checkpoint, the total sum will be reflected in pending.&#x20;

**Allowed:** "allowed" reflects USDC that is now free to be withdrawn completely to your externally owned address (your connected Ethereum address).&#x20;

{% hint style="info" %}
If you deposited more than 10,000 USDC, any excess collateral will \*immediately\* be placed into "allowed" for withdrawal. This collateral can be removed from the exchange, but cannot be used as collateral for trading.
{% endhint %}

In the next checkpoint (approximately \~10 minutes), you will need to click "Complete withrawal".&#x20;

After this, the withdrawn funds will appear in your Ethereum account.&#x20;

### DDX Withdrawals

First, select your trader account on the top right of the UI.&#x20;

![](/files/X6IggZIPJF5SlV5haH2K)

Then, select "Withdraw DDX".

![](/files/9CUoSvulQ6Np9crPM5Bo)

If you have DDX to withdraw, you can select the amount you want to withdraw here. Then, select "initiate withdrawal".&#x20;

Similarly to USDC withdrawals, you will need to wait for \~10 minutes, until a checkpoint has passed, before you can "complete withdrawal".

After you complete withdrawal, the DDX will appear in your Ethereum account.&#x20;


# Perpetual swaps

On DerivaDEX, users are able to trade perpetual swaps with other users on a decentralized platform.&#x20;

1. **Place a Trade**: Select a trading pair. Choose your order type—limit, or market.
2. **Manage Risk**: Monitor your margin fraction to avoid liquidation.
3. **Monitor Funding Rates**: Keep track of the funding rate changes, as these can impact your bottom line and change regularly.

### Perpetual swaps on DerivaDEX

* **No Rollover Costs**: Traders avoid costs associated with rolling contracts as there is no expiration.
* **Real-Time Price Tracking**: Funding rates and advanced price feeds ensure that the swap price closely follows the index price.

### Perpetual swaps vs. other derivatives

1. **No Expiration**: Unlike futures, perpetual swaps have no settlement date, allowing positions to be held indefinitely.
2. **Funding Rates**: Funding rates are periodically paid between long and short positions to anchor the swap price close to the underlying asset price. Traders must monitor these payments as they influence the profitability of holding positions. Funding rates are assessed every 8 hours on DerivaDEX.&#x20;
3. **Efficient Shorting**: Enables traders to profit from downward price movements in a straightforward manner.
4. **No Asset Custody**: Since the underlying asset isn’t traded, there are no custody concerns.

{% hint style="info" %}
For more info, check[ out this article on perpetual swaps](https://medium.com/derivadex/what-are-perpetual-swaps-130236587df2)
{% endhint %}


# Funding rate

**The funding rate is how the price of a perpetual swap is kept close to the price of the underlying asset. It works by sending periodic payments between long and short traders. This is critical: a poorly designed funding rate makes perpetual swaps riskier, more volatile, and costlier.**

For perpetual swap products, the funding rate is levied and updated approximately every 8 hours worth of blocks (\~2400 blocks).  The funding rate interval can be modified via DerivaDAO governance.

**You can view the funding rate at the top of the interface, and you can see your individual funding-rate payments in the "Order History" table at the bottom of the interface.**

### Funding rate calculation

The funding rate is computed in the following manner:

1. Obtain the last 8 hours worth of premium rates, which is actually just the EMA component of the price feed (`premium_rates`). This premium rate essentially tracks the magnitude of the difference between the underlying composite index the perpetual swap is tracking and the DerivaDEX order book itself. Please refer to [Price feed](/platform-features/price-feed) to better understand what this term refers to.
2. Take a simple average of these EMA values. `avg_premium_rate = avg(premium_rates)`
3. Compute the unclamped funding rate. Any `avg_premium_rate` value between the `funding_zero_lower_bound` (-0.0005) and the `funding_zero_upper_bound` (0.0005) will become 0. `unclamped_funding_rate = max(funding_zero_upper_bound, avg_premium_rate) + min(funding_zero_lower_bound, avg_premium_rate)`
4. Compute the clamped funding rate. Any `unclamped_funding_rate` value below the `funding_lower_bound` (-0.005) and the `funding_upper_bound` (0.005) will be capped at either of those respective bounds. `funding_rate = min(funding_upper_bound, max(funding_lower_bound, unclamped_funding_rate))`

### Funding rate distribution

At the boundaries of the funding rate window, users will either be credited or debited the funding fee depending on their open position size. The magnitude of the funding fee for any individual trader can be computed as `funding_rate * position_notional`. When the DerivaDEX perpetual swap is trading above the composite index it's tracking, the funding rate will be positive, meaning long traders will *pay* the funding fee and short traders will *receive* the funding fee, thus bringing the perpetual swap's price down back in line with the underlying. Conversely, when the DerivaDEX pereptual swap is trading below the composite index it's tracking, the funding rate will be negative, meaning long traders will *receive* the funding fee and short traders will *pay* the funding fee, thus taking the perpetual swap's price up back in line with the underlying.

{% hint style="info" %}
**For more information about funding rates,** [**see this in-depth introduction.** ](https://medium.com/derivadex/what-is-the-funding-rate-for-perpetual-swaps-a0335c4228a9)
{% endhint %}


# Strategy

Collateral is always deposited to a specific `strategy`. The default strategy, `main`, will be used for the trading competition (and will be a user's only strategy until multiple strategies are enabled).&#x20;

### Cross-margin

DerivaDEX uses "cross-margined" leverage. This means all funds in a Strategy Value are used as collateral to prevent liquidations. This is in contrast to "isolated margin", where users determine how much collateral to apply to a given position.&#x20;

{% hint style="info" %}
Users who wish to trade with an isolated margin approach can simulate this by creating multiple strategies with their own dedicated collateral.
{% endhint %}

In the future, DerivaDEX can (with a successful governance proposal) offer users the ability to open and manage different strategies, enabling the same trader address (Ethereum address) to have accounts with isolated collateral from one another.  This will allow traders to simulate isolated margin or construct more complex trading strategies.

### Strategy value

This is how much a strategy is worth at any given point in time.&#x20;

The `strategy_value` is calculated using the formula:

```
strategy_value = strategy_collateral + unrealized_pnl
```

Where `strategy_collateral` is the total collateral assigned to the strategy, and `unrealized_pnl` is the profit or loss that has not yet been realized from the open positions within the strategy.

### Available collateral

Available collateral represents the amount of collateral that is not currently tied up in any open positions. It is essentially the collateral available for new trades.&#x20;

### Margin Fraction

Margin Fraction defines the amount of collateral required to open and maintain positions. It ensures the trader has enough funds to cover potential losses and maintain their positions during market fluctuations. It is the strategy's backing collateral, relative to its notional value.

```
margin_fraction = strategy_value / notional_value
```

### Open Margin Fraction (OMF)

Open Margin Fraction represents the percentage of collateral that is currently being utilized for open trades. OMF is calculated as:

`min(total_value, collateral) / total_open_position_notional`

where `total_value` is `collateral + unrealized_pnl`

and `total_open_position_notional` sums all your open positions, as well as **what your open positions would be if all your open orders were to be filled**.&#x20;

If you notice that you are hitting your leverage limit earlier than you expect, please check to ensure you don't have open orders -- *these will affect your OMF.*

### Margin fraction

The margin fraction is a key measure of account health in leveraged trading. It represents the ratio of your account's equity to its total exposure, providing a snapshot of your financial buffer against market fluctuations. To calculate the margin fraction, use the formula:

`1/leverage`

### Leverage

```
leverage = notional_value / strategy_value

# leverage = 1 / margin_fraction
```

### Minimum Margin Requirement (MMR)

The Minimum Margin Requirement is the lowest amount of collateral that a trader must maintain in their account to keep their positions open. If the account balance falls below this threshold, additional collateral must be deposited, or positions will be automatically liquidated to cover the shortfall.


# Fees

### Trading fees

Fees are paid on the notional value of an order. This means that for a taker order of $5000 notional value (`fill_price * fill_amount`), a fee of 0.2% or 10 USD would be applied. Fees are applied to the user's collateral balance (`strategy_collateral`). **At no time do traders pay an Ethereum gas to open or close their trading positions.**

{% hint style="info" %}
DDX Fee discount: \
Users can also pay fees in DDX, the native token of DerivaDEX. **Fees paid in DDX are 1/2 the cost of fees paid in USDC.**
{% endhint %}

### Trading fee rates

| Maker      | Taker                                  |
| ---------- | -------------------------------------- |
| 0% (0 bps) | 0.2% (20 bps) USDC / 0.1% (10 bps) DDX |

### Deposit and withdrawal fees

These fees are paid in Ethereum, often referred to as `gas`.  The exact price will depend on network congestion and user-defined gas limit.&#x20;


# Position management

### Opening a position

To open a position, place a [*market* or *limit* order](/trading/position-management/order-types).&#x20;

If the quantity requested is available at the request price level, the order will be filled and displayed under the "Filled Orders" tab and your updated position will be reflected in the "Positions" tab.&#x20;

If there is a remaining amount, this quantity will be placed as an open order in the order book and show up in the "Open Orders" tab.&#x20;

#### Maker

A *maker* order is one that has added liquidity to the order book upon placement. In other words, when the order was placed, it did not trigger a match, and thus entered the order book waiting to be matched against at some later point in time.

#### Taker

A *taker* order, on the other hand, is one that removes liquidity from the order book upon placement. In other words, when the order was placed, it did trigger a match vs. one or more *maker* orders in the book.

#### Matched trades

Every executed *trade* (commonly referred to as *match* or *fill*) is comprised of exactly one *maker* order and one *taker* order. The *maker* order is the one that was there first, waiting to be matched. The *taker* order is the second one that triggered the match.

* A *maker* order will spend some non-zero time on the order book.
* A *taker* order will never spend any time on the order book.

**Market makers** are traders with strategies that generally place *maker* orders to the book, looking to consistently capture the bid / ask spread. **Market takers** are traders with strategies that generally place *taker* orders, looking to capture directional moves in the market.

#### Maker/Taker Fees

See [Fees](/trading/fees) for trading fee information.&#x20;

### View orders and positions

To view any **open orders**, navigate to the 'Open Orders' tab. Any open orders will be listed.&#x20;

**Open positions** can be found on the 'Positions" tab.

### Cancel an open order

To cancel an open order, guide to the 'Open Orders' tab, under the Orders tab. Here, find the order you wish to cancel. Click the 'X' on the far right hand side of the order. A confirmation message from your wallet will be prompted, and once cancelled, the open order is closed and removed from the order book.&#x20;

### Close or reduce an open position

To reduce and/or close your position, you will need to execute a trade in the opposite direction of your current position.&#x20;

In other words, if you currently have a long position open, you must place a market sell order, or have a limit sell execute at some point after placement.&#x20;

If you currently have a short position open, you must place a market buy order or have a limit buy execute at some point after placement.

{% hint style="info" %}
When using the Open Positions table interface "X" button to close open positions, you will initiate a **market** order, not a **reduce only** order.  If your order fails, this is likely because it would violate a slippage safety or because there is insufficient liquidity to close your order.  When **reduce only** order types are supported, this will be modified.
{% endhint %}


# Order types

There are two ways to buy or sell perpetual swaps on the DerivaDEX exchange. DerivaDEX supports limit and market orders. Understanding these types of transactions will help you be a successful trader.

## Market Orders

{% hint style="info" %}
Use this type of order when you are interested in executing a trade on a given market for a specific quantity irrespective of price. The best available prices will be given to you upon execution, and any unmatched quantity will be canceled.
{% endhint %}

### **Market&#x20;*****Buy*****&#x20;Order**&#x20;

#### buy a specific quantity of perpetual contracts at any price level.

* The matching engine will match this order against existing *ask (sell)* orders in the order book, starting with the most favorable ones (i.e., lowest-priced sell orders).
* Any unmatched amount is cancelled.&#x20;

### **Market&#x20;*****Sell*****&#x20;Order**&#x20;

#### &#x20;sell a specific quantity of perpetual contracts at any price level

* The matching engine will match this order against existing *bid (buy)* orders in the order book, starting with the most favorable ones (i.e., highest-priced buy orders).
* Any unmatched amount is cancelled.

{% content-ref url="/pages/-MZVKrkatjw41q7aiAmx" %}
[Getting started](/introduction/getting-started)
{% endcontent-ref %}

## Limit Orders&#x20;

{% hint style="info" %}
Use this type of order when you are interested in executing a trade on a given market for a specific quantity, with a limit to how unfavorable of a price you are willing to go (i.e., the highest price you are willing to buy for in the case of a *bid (buy)* or the lowest you are willing to sell for in the case of an *ask (sell)*. In the case of a match, the best available prices will be given to you upon execution, and any unmatched quantity will be posted to the order book.
{% endhint %}

### **Limit&#x20;*****Buy*****&#x20;Order**&#x20;

#### buy a specific quantity of perpetual contracts with a ceiling (maximum) price level.

* The matching engine will match this order against any existing *ask (sell)* orders in the order book that are at any price less than or equal to the incoming limit order's price, starting with the most favorable ones (i.e., lowest-priced sell orders).
* Any left-over amount that went unmatched will be posted to the order book as a *bid* at the price level specified in the limit order.

### **Limit&#x20;*****Sell*****&#x20;Order**&#x20;

#### sell a specific quantity of perpetual contracts with a floor (minimum) price level.

* The matching engine will match this order against any existing *bid (buy)* orders in the order book that are at any price greater than or equal to the incoming limit order's price, starting with the most favorable ones (i.e., highest-priced buy orders).
* Any left-over amount that went unmatched will be posted to the order book as an *ask* at the price level specified in the limit order.

{% hint style="danger" %}
**Self Match Prevention**

This safeguard makes it so you cannot trade with yourself. Limit and market orders will be filled as much as they can until they would otherwise inflict a self-match, at which point the remainder of the incoming order will be canceled. The existing order in the book will remain intact.
{% endhint %}

{% content-ref url="/pages/-MZVKrkatjw41q7aiAmx" %}
[Getting started](/introduction/getting-started)
{% endcontent-ref %}


# PNL

PnL on DerivaDEX falls into two categories: **realized** and **unrealized**. PnL is realized when the [PNL Settlement](#pnl-settlement) takes place. Unrealized PnL factors into your [open margin fraction](/trading/strategy)[.](/trading/strategy#open-margin-fraction-omf)

### PnL settlement

DerivaDEX settles all traders' PNLs periodically. Settlement occurs approximately every 8 hours worth of blocks (\~2400 blocks). The settlement frequency can be modified via DerivaDAO governance.

PNL settlement takes place for every open position a trader has with the following two steps:

1. **All unrealized PNL becomes realized PNL**: at all points in time, users have a strategy collateral value, which are tokens they rightfully possess (on the exchange, but noncustodially in their, and only their, possession). Open positions also have an unrealized PNL with respect to the mark price that can be thought of as paper profits or losses. When PNL settlement occurs, this unrealized PNL realizes, thereby crediting/debiting your strategy collateral accordingly. Net-net, in some sense, nothing has really changed as your strategy value is unchanged. Moreover, how the exchange considers your strategy when assessing liquidations is also unchanged since margin fraction looks at your strategy value, which as mentioned, is unchanged.&#x20;
2. **The open position's average entry price resets to the current mark price**: Given that DerivaDEX realizes unrealized PNL relative to a given mark price, in order to ensure that the strategy value proceeds as it would have even if PNL settlement were to not have taken place, the average entry price must now be set to the current mark price.

#### Example

Let's take a look at an example to illustrate. Imagine Alice has deposited 1000 USDC as collateral on DerivaDEX and goes long 5 ETHPERP at a price of 2000 USD. Imagine 8 hours from now, at the time of PNL settlement, the mark price of ETHPERP has risen to 3000 USD.&#x20;

The following two scenarios demonstrate how PNL settlement works - **please take note that scenario 1 is NOT how DerivaDEX handles things. DerivaDEX uses scenario 2. Both are presented, however, to more clearly describe what happens**:

* Scenario 1 (no PNL settlement): Alice has an unrealized PNL of 5000 USD given that she is long 5 ETHPERP contracts and the price has risen by 1000 USD each relative to her average entry price of 2000 USDC. If she were to withdraw, she could withdraw (imagine an unrealistic no-liquidation paradigm for a second where you don't need any collateral to support open positions) a maximum of 1000 USDC since that is her strategy collateral despite her strategy value of 6000 USDC. She could then choose to close her long position to realize the additional 5000 USDC unrealized profit, and then withdraw that amount, reaching the total of 6000 USDC that her strategy was worth.&#x20;
* Scenario 2 (PNL settlement): Once again, Alice has an unrealized PNL of 5000 USD given that she is long 5 ETHPERP contracts and the price has risen by 1000 USD each. This unrealized PNL is realized upon PNL settlement, thus her strategy collateral will now actually be 6000 USDC, matching her strategy value of 6000 USDC (although the unrealized component of this is now 0 USDC since the average entry price was just set to the current mark price of 3000 USD). If she were to withdraw, she could withdraw (imagine an unrealistic no-liquidation paradigm for a second where you don't need any collateral to support open positions) a maximum of 6000 USDC since that is her strategy collateral. She could then choose to close her long position that she still has, but this would actually realize 0 USDC of unrealized PNL. In the end, she was able to withdraw the same amount of collateral as in scenario 1, but this approach is much more desirable for traders and versatile, hence is adopted by DerivaDEX.&#x20;

### Unrealized PnL

Your unrealized PnL is the profit or loss that has accrued to your position either since it was opened, or since the last settlement epoch (whichever occurred more recently).&#x20;

`Unrealized_pnl = position_balance * position_side * (mark_price - position_avg_entry_price)`

`position_side = 1 (long), -1 (short)`

Total Unrealized PnL is the unrealized PnL across all positions.&#x20;

Position balance is the size of your position (i.e., 1 ETHPERP).&#x20;

### Realized PnL

Realized PnL is updated when position are closed or when a settlement epoch occurs.


# Liquidations

A liquidation occurs when the a trader's margin fraction dips below the maintenance margin ratio, indicating that their account is insufficiently collateralized.

Traders will be liquidated when their margin fraction (MF) dips below the maintenance margin ratio (MMR).&#x20;

A strategy's margin fraction and maintenance margin ratio are defined as follows:

```
# strategy_value = strategy_collateral + all_positions(unrealized_pnl)
# notional_value = all_positions(position_size * mark_price)

margin_fraction = strategy_value / notional_value
maintenance_margin_ratio = 0.6 / max_leverage
```

From the equation above, you can see how if the market moves unfavorably against your position, your margin fraction will decrease since your strategy value will decrease due to a more negative unrealized PNL. If this dips below the MMR, you will be liquidated.

Although the technical definition of a liquidation trigger is MF < MMR, you can also think of it as when the mark price crosses the liquidation price based on a trader's position. Things get a little more complicated in a cross-margined paradigm with multiple positions open across markets, however this approximation/estimate can be a good, more intuitive way to think about things. The estimated liquidation price for any given position is as follows:

`estimated_liquidation_price = (collateral - position_size * position_side * avg_entry_px) / (position_size * (mmr - position_side))`

More explanation on how this formula was derived can be found [here](https://medium.com/derivadex/liquidation-and-bankruptcy-prices-under-the-hood-c93167950d6a).

{% hint style="info" %}
A strategy (and all its positions) will be entirely liquidated when the liquidation price is met. Partial liquidations are not currently supported.&#x20;
{% endhint %}

## Liquidation Checklist

If a trader is liquidated, three important things will happen:

1. any remaining collateral will be taken.&#x20;
2. any open orders will be canceled
3. any open positions will be closed, more on this in the next section...

## Liquidation Position Closing

This is a little trickier as there are two paths this can take, the first of which the likelier (and happier) path, and the second of which being the far less likely path. A detailed demonstration of the following materials can be found [here](https://medium.com/derivadex/what-is-an-insurance-fund-49410775d41e).

In either scenario, the exchange will essentially buy liquidated positions from the liquidated trader at their bankruptcy price, and exchanged with open orders on the book until the position has been fully closed. A position's bankruptcy price is the price at which their losses exactly equals the collateral deposited, computed in the following manner: `bankruptcy_price = mark_px - position_side * (total_account_value / position_size)`

In other words, a liquidated long position will be matched with any open bids in the order book, and a liquidated short position will be matched with any open shorts in the order book. The prices at which these positions are offloaded to other traders are called the closing prices.&#x20;

* Happy path: in the scenario where the closing price is more favorable than the bankruptcy price (in the case of a liquidated long, the closing price is higher than the bankruptcy price, and in the case of a liquidated short, the closing price is lower than the bankruptcy price), this positive spread is credited to the insurance fund.&#x20;
* Adverse path: in the scenario where the closing price is less favorable thank the bankruptcy price, the negative spread is debited from the insurance fund. If the insurance fund is insufficiently capitalized to handle this drawdown, it results in an auto-deleveraging (ADL) event. More on this in the next section...

## Auto-Deleveraging (ADL)

Auto-deleveraging is an extremely rare outcome, but final resort, the exchange would take in the event the insurance fund was not sufficiently capitalized to handle a liquidation drawdown. The key premise of auto-deleveraging lies with the invariant that the long and short positions at all times is zero-sum (i.e. there are just as many longs as there are shorts). Thus, for every undercollateralized/liquidated position, there are positions of equal size that are profitable. Auto-deleveraging forcibly closes positions to match the amount being liquidated, closing positions in order of most profitable to least.&#x20;


# Insurance fund

The DerivaDEX Insurance Fund is a reserve designed to protect traders from losses due to unexpected liquidations or extreme market events. It serves as a safeguard to cover negative balances when a trader's position is liquidated, ensuring that other users are not affected (minimizing the occurence of auto de-leveraging, or ADL).&#x20;

The fund is maintained by collecting all USDC trading fees and liquidation penalties, and it is managed through the DerivaDAO governance system.&#x20;

For more information on the insurnance fund, see [this article. ](https://medium.com/derivadex/what-is-an-insurance-fund-49410775d41e)


# Trade mining

Trade mining is a form of liquidity mining that ensures active traders receive DDX so that they can participate in DerivaDAO governance (and receive reduced fees, when paying in DDX). Makers and takers receive proportional shares of a DDX allotment every payment epoch.

As is the case with all parameters on DerivaDEX, trade mining distributions are subject to DerivaDAO governance, but initial parameters likely will be:

* `35,000,000` DDX emitted over a 10-year horizon every trade mining epoch (\~8 hours) =  `~3196` DDX every trade mining epoch
* 80% of this distribution goes to market takers, proportionally divided to them based on their taker volume vs the global taker volume during the trade mining epoch
* 20% of this distribution goes to market makers, proportionally divided to them based on their maker volume vs the global maker volume during the trade mining epoch

All DDX holders are able to vote and delegate voting power. Holders who have above 1% of the circulating supply (either held outright, or via delegation) may make proposals. These numbers are subject to modification via governance proposal.


# Checkpoints

Checkpoints are how the DerivaDEX off-chain operators confirm and verify state and transactions with on-chain data (such as deposit and withdrawal events). You can view the current checkpoint in the stats bar at the top of the interface.

Checkpoints occur roughly every 10 minutes worth of blocks. A checkpoint contains all the exchange state, and is periodically submitted on-chain to Ethereum. \
\
Checkpoints are how DerivaDEX verifies withdrawals, and also enable the application to resume statefully if necessary.&#x20;

### Checkpoint technical note:

A checkpoint is the merkleized state root hash.&#x20;


# Price feed

### Composite index weighting

Perpetual swaps track an underlying composite index, which is a weighted average price of spot prices across a selection of exchange offerings. Exactly which exchanges to use is a parameter that can be be modified from an initial setting via governance.&#x20;

While it is fairly trivial to add more exchanges with custom weightings (which can become necessary as the exchange supports numerous assets), at the moment, the DerivaDEX composite index price is currently constructed in the following manner:

#### Price feed input sources

| Exchange | Weighting |
| -------- | --------- |
| Binance  | 33.33%    |
| Gemini   | 33.33%    |
| Coinbase | 33.33%    |

### Update criterion

The DerivaDEX price feed updates every second, if and only if the price has changed by more than `1 bps` (0.01%). This is similar to the standards of highly performany centralized exchanges.

### Price feed attributes

The price feed emits "Price checkpoint" events that are stored in the system's verifiable state, that contain the following information:

#### Index price

The index price is the weighted average composite price as per the details above.

#### EMA

The EMA (exponential moving average) tracks the spread between the DerivaDEX perpetual swap's price and the underlying index price it is tracking. It is derived in the following manner:

1. Compute the `fair_price` of the DerivaDEX order book, which is the midpoint of the best available bid and ask. `fair_price = avg(best_bid, best_ask)`.
2. Compute the `premium`, which is the difference between the `fair_price` and the composite index price. `premium = fair_price - index_price`.
3. Compute the latest `ema` value of this `premium` using a 30-period EMA multiplier and the last computed `ema`. `ema = (premium - previous_ema) * (2/31) + previous_ema`.

In the case where the DerivaDEX order book is consistently trading above the composite index price, this `ema` will be positive, and if it is trading below the index price, it will be negative. This `ema` field has special significance for computing and distributing [funding rate](/trading/perpetual-swap/funding-rate)-related payments.

if there is an empty order book, the `fair price` is set equal to the `index price`.

### Mark price

The mark price is used to assess liquidations and depict unrealized PNLs for positions. It can be calculated using the `index_price` and `ema` described above: `mark_price = index_price + delta` where delta is the `ema` bounded to 0.5% of the index price.


# Account data

Accounts on Ethereum are pseudonymous, as are trader accounts on DerivaDEX.

Exchange operators do \*not\* have privileged information about trader accounts beyond what is publicly available. However, unlike a centralized exchange, the transaction log is public information in DerivaDEX.&#x20;


# Execution security

DerivaDEX is designed to provide execution security through several mechanisms:&#x20;

**Economic incentives:** operators must post a bond that can be revoked by the DAO for malicious behavior.

**Trusted execution environments:** Each operator runs code that is deployed within a trusted execution environment (TEE). This technology provides assurances to users that the execution code approved by governance has NOT been tampered with.&#x20;

**Checkpointing + auditor:** The DerivaDEX auditor is a pythonic implementation of the exact logic run by the exchange. In the event that the auditor and exchange reach different state root hashes, governance can pursue blacklisting operators and pausing the exchange to investigate.

Together, these attributes should provide traders with a radical level of transparency compared to centralized exchanges. Furthermore, the DerivaDEX governance process ensures that there are public pathways for protocol community to remediate emergent problems.


# API

DerivaDEX has several APIs, all of which are documented more fully at [https://testnet.derivadex.io/api-docs](https://testnet.derivadex.io/api-docs#derivadex-realtime-api)

The current APIs include:

* Public REST API
* Authenticated REST API
* Realtime API
* Auditor


# Contract addresses

### Mainnet Ethereum

| Contract             | Address                                      |   |
| -------------------- | -------------------------------------------- | - |
| DDX token            | `0x3A880652F47bFaa771908C07Dd8673A787dAEd3A` |   |
| USDC token           | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` |   |
| All DerivaDEX facets | `0x6fb8aa6fc6f27e591423009194529ae126660027` |   |

### Sepolia Ethereum

| Contract             | Address                                      |   |
| -------------------- | -------------------------------------------- | - |
| DDX token            | `0x5b1049d81e29bad0ae77392276e030161fc4a4c8` |   |
| USDC token           | `0x9623ea5645d21fb21f94e582c683c011a76bb9d2` |   |
| All DerivaDEX facets | `0x5d1a3b4181d3cad422f404f28e9e972d0ba4dad6` |   |


# FAQ

## What does the funding rate show?

The funding rate displayed in the header bar shows you an estimate of the rate that will be assessed at the end of the payment epoch.

## What is a payment epoch?

Payment epochs occur every 8 hours. This is the interval for funding rate payments, trade mining, and PnL settlements.

## What is a PnL Settlement?

Every 8 hours, open positions are settled vs the mark price.&#x20;

## What is trade mining?

Trade mining is a form of liquidity mining that ensures active traders receive DDX so that they can participate in DerivaDAO governance (and receive reduced fees, when paying in DDX). Makers and takers receive proportional shares of a DDX allotment every payment epoch.

| Amount per payment epoch | Makers | Takers |
| ------------------------ | ------ | ------ |
| 3196.34703196 DDX        | 20%    | 80%    |


# Troubleshooting

This section details some errors you may encounter while using the exchange.

### Account margin fraction too low

If you attempt to place an order and get the message: **"Order not executed. Order would bring account margin fraction too low."** it means that placing this order would bring your open margin fraction (OMF) below your initial margin fraction requirement.&#x20;

To successfully place this order, try closing other open orders or open positions, or depositing more collateral.&#x20;

You can also try creating the desired position via a series of smaller orders.

### Order would incur slippage greater than 2%

If after attempting to place an order you receive the message: **"Order failed: Order would incur slippage greater than 2%."** You've encountered the slippage protection safeguard, which is in place to prevent taker orders from going through that would incur significant slippage.&#x20;

To solve this issue, try creating a limit order for the desired trade within 2% of the current mark price.&#x20;

You can see a full list of safeguards here.

### Order not executed

This order was submitted, but could not be executed when the exchange attempted to process it. **You are not charged trading fees for unsuccessful orders.**

There are a small number of situations where this occurs, and this is always intended to protect traders and the exchange. These scenarios should occur very rarely in a normal trading environment.&#x20;

Here are some of the reasons, and solutions, for orders that are not executed:&#x20;

* **"Self-match" is not permitted:** if your order would have been filled by an order \*you\* placed on the opposite direction, this order will not be executed. You cannot match your own orders. Try cancelling the open order that would have been filled by your attempted order.
* **No orders in the book:** Market orders are only permitted when there are open orders available to fill it. If you placed a market order against an empty or very illiquid book, this order would not be executed. Wait until there is liquidity in the market and try again.
* **Liquidation safeguards**: if you attempted to place an order that had a high probability of liquidating you instantaneously if it were filled, this order will not be executed. Try depositing more collateral, or closing some open orders and positions. You can see a full list of safeguards here.


# DerivaDAO Governance

## Introduction to the DerivaDAO

The DerivaDEX protocol is governed by the DerivaDAO. DAO is shorthand for “decentralized autonomous organization”, a concept often used in decentralized applications to refer to smart-contract based governance, where token holders are able to make proposals regarding changes to a protocol, and vote on them.&#x20;

### Governance structure

#### The DAO and voting power

All DDX token holders participate in governance, with voting power proportional to their token holdings.&#x20;

Governance decisions include:

* Approving protocol updates
* Managing DAO-owned funds
* Appointing Bond Providers and Foundation directors

#### Types of proposals

1. **On-chain Proposals**: Direct changes to protocol code or smart contracts.
2. **Hybrid Proposals**: Combine on-chain changes with off-chain activities.
3. **Off-chain Proposals**: Non-binding, ratified by the DAO.

#### Proposal process

1. **Draft Creation**: Shared on the [Governance Forum](http://forum.derivadex.com).
2. **Security Council Review**: Assesses potential risks.
3. **DIP Submission**: Created and submitted on the [DIPs Repository](https://gitlab.com/derivadex/dips).
4. **Voting**: Open for 3 days; 4% quorum needed.
5. **Execution**: If approved, the proposal is implemented on-chain.

<br>


# DerivaDEX Improvement Proposals (DIPs)

## DerivaDEX Improvement Proposals <a href="#e367" id="e367"></a>

DerivaDEX Improvement Proposals (DIPs) should be very familiar to contributors or participants in the EIP ecosystem. **However, the DIP process has some key differences because DerivaDEX proposals all utilize on-chain execution.**

For an in-depth discussion of the DIP process, please visit the DIP repository: <https://gitlab.com/derivadex/dips>

* Anyone can participate in the DIP process, either via submitting a PR or providing feedback
* DIPs are for proposals that have reached **draft** stage only! Use the governance forum for early-stage idea coordination and development.

Each DIP will consist of two PRs to the DIP repo:\
**Proposal Spec** — A `DIP-n.md`file detailing the proposal. The proposal spec PR will be merged to `master` if and only if an on-chain governance proposal is actually made.\
**Implementation** — The corresponding implementation. The implementation PR will be merged to`master` if and only if the proposal successfully executes on-chain.\
\
Once a proposal has been executed, both PRs will be merged to the DIP repo. If a proposal is in draft, open for voting, queued, failed or cancelled, only the proposal spec PR will be merged.

## Proposal stages <a href="#id-3348" id="id-3348"></a>

**Idea** — An idea that is pre-draft. This is not tracked within the DIP Repository. There is no proposal spec PR nor implementation PR open. These topics belong in the “Ideas” category on the [forum](http://forum.derivadex.com/).

**Draft** — The first formally tracked stage of a DIP in development. At minimum, a proposal spec PR has been opened to garner feedback on the [forum](http://forum.derivadex.com/). An implementation PR at some point will be opened as well to seek additional input from the community.

**Proposed** — An on-chain governance proposal has been made. The proposal spec PR will be merged to `master`. The implementation PR will remain open.

**Succeeded** — The proposal has succeeded on-chain, but has not yet been queued for execution.

**Failed** — The proposal has failed on-chain.

**Queued** — The successful proposal has been queued for execution.

**Cancelled** — The proposal has been cancelled.

**Expired** — The queued proposal has expired prior to execution.

**Executed** — The proposal has successfully executed on-chain.

![](/files/-MhKSbdnxwYodxWrCO-V)


# Voting and Delegation

* All proposals can be voted upon by DDX holders in the governance app: governance.derivadex.com.&#x20;
* Anyone who has participated in insurance mining, and has claimed their DDX, will be able to vote from their connected account.

### Voting process <a href="#e67b" id="e67b"></a>

**Submission:** Proposals must be submitted by an address that holds (and maintains throughout the entire proposal process) `>1%` of the circulating supply. This is intended to cut down on the number of spam proposals and malicious proposals. After the governance cliff is lifted, users can delegate freely, which should enable a wider range of participants to make proposals.

**Voting:** When a proposal is submitted on-chain, there is a 3-day voting period. This voting period may be shorter if `>50%` of the circulating supply votes “FOR” or “AGAINST”, at which point the proposal is immediately Succeeded and Queued, or Fails. A successful proposal requires at minimum a quorum of `>4%` of the circulating supply.

**Queuing and Execution:** The successful proposal is then Queued for 3 days. At the end of the 3-day queue, the proposal can be executed.

### Delegation <a href="#id-34b9" id="id-34b9"></a>

DDX can be delegated via the [governance.derivadex.com](http://governance.derivadex.com/) interface.

* Initially, all Trader wallet DDX is automatically delegated to the user-owned connected account (EOA).
* Now that the governance cliff is lifted via a successful proposal, users are able to withdraw DDX from their Trader wallet to their EOA and then delegate to any desired third party.


