# Introduction

DMEX is a pioneering **decentralized perpetuals exchange** (DEX) for margin trading, established in 2019. We deliver a seamless trading experience that rivals centralized platforms—without ever compromising on decentralization, self-custody, or privacy.

Today, DMEX stands out in the DeFi landscape with features designed for serious traders:

* **Zero gas fees** on trades — keep more of your profits
* **No KYC** required — true anonymity and permissionless access
* **Multi-collateral support** — use BTC, ETH, SOL, XMR, USDT/USDC, BNB, TON, and more as margin
* **Cross-margin positions** — the first DEX to offer this powerful feature, allowing efficient use of collateral across multiple trades
* **High leverage** up to 250x on select pairs — maximize your exposure with control
* **Quanto perpetuals** — trade with stable, predictable payouts in your preferred collateral
* **Demo mode** available — practice risk-free before going live
* **Broad asset coverage** — perpetuals on major cryptos like BTC, ETH, and an ever-growing list including recent additions such as WLD, NEAR, SUI, ARB, TAO, and many others
* **Optimized funding rate system** — earn interest by holding positions when funding works in your favor

Whether you're a professional trader seeking CEX-like performance in a fully on-chain environment or a DeFi user who values privacy and non-custodial control, DMEX combines innovation, reliability, and user-centric design to power your next-level trading strategy.

Trade smarter, trade freer → [dmex.app](https://dmex.app/)


# Changelog

#### 28 January 2026

* [Fees](/trading-fees) reduced for Binary Contracts

#### 25 January 2026

* [Fee schedule ](/trading-fees)updated for Binary Contracts

#### 22 January 2026

* [1-Click trading](/1-click-trading) enabled
* STOP MARKET order type added

#### 20 January 2026

* Launched [Binary Contracts](/binary-contracts)

#### 3 January 2026

* Balance transfers between DMEX accounts are now instant. When you withdraw to another DMEX account's deposit address, the withdrawal will be considered an internal transfer.

#### 19 December 2025

* Post-Only option added to Limit Orders

#### 13 November 2025

* Max leverage for BTC and ETH increased to 250x

#### 26 October 2025

* Liquidation fee removed. During position liquidation, no additional liquidation fee is charged. The position will be closed at the market price with the standard taker fee.

#### 6 August 2025

* Realized profit value in positions now includes Trading Fees and Net Funding

#### 27 July 2025

* Funding system overhaul, now when funding rate is positive, longs pay shorts, when negative, shorts pay longs

#### 26 July 2025

* Trading fees reduced to 0.0125%/0.0250% (maker/taker)
* Liquidation now is an automatica market close with the taker fee applied, remaining collateral remains with the trader&#x20;

#### 10 July 2025

* Significant improvements in funding rates

#### 8 July 2025

* Significant improvements in liquidation prices

#### 1 July 2025

* Trading fees reduced to 0.025%/0.05% (maker/taker)

#### 25 June 2025

* Monero (XMR) added both as tradeable asset and margin currency

#### 15 June 2025

* TRX (Tron) Added as tradeable asset

#### 23 May 2024

* Funding cost is now charged once an hour

#### 26 April 2024

* Liquidations removed. When a position reaches the liquidation price, it is auto market closed, remaining collateral is returned to the user's balance.

#### 24 April 2024

* JUP (JUPITER) added as a tradeable asset

#### 23 April 2024

* TON (TONCOIN) added as a tradeable asset

#### 18 April 2024

* WIF added as a tradeable asset

#### 15 April 2024

* PEPE added as a tradeable asset

#### 9 April 2024

* Added SOL \[SOLANA] as margin currency

#### 20 March 2024

* Added BNB, BUSD, USDC on Binance Smart Chain \[BSC] as margin currencies

#### 18 March 2024

* Added 1 second chart resolution

#### 4 March 2024

* Unrealized profit is now counted towards available cross margin
* USDT TRC20 (TRON) now accepted as margin

#### 20 February 2024

* Added cross margin
* Increased default risk limit to 500k

#### 14 February 2024

* Avalanche AVAX, USDT and USDC added as margin currencies

#### 12 February 2024

* Polygon MATIC, USDT, USDC and WBTC added as margin currencies

#### 9 February 2024

* Ethereum USDT, USDC and WBTC added as margin currencies

#### 29 January 2024

* New frontend interface
* New backend
* 1 confirmation deposits (new bridge)
* faster matching engine
* new demo trading engine
* overall speed improvements
* ux improvements

#### 18 May 2023

* Moved DEMO version to Goerli Testnet

#### 13 July 2022

* General stability improvements
* Improved trade execution time
* Increased general throughput to accommodate for high demand periods

#### 1 February, 2021

* UI freezing bug fix and interface optimizations

#### 25 January, 2021

* Minimum order value reduced to 10 USD

#### 18 January, 2021

* Trade processing moved to xDAI sidechain
* Risk Limits added
* Global MM Multiplier added
* Funding period no longer position entry block dependent

#### 25 March, 2020

* Bitcoin added as Margin Currency through decentralized stack. Details [here](/bitcoin-integration).

#### 20 Feb, 2020

* DMEX Token contract updated
* DMEX Token set as feeAccount in the contract (token is now fully integrated)

#### 13 Feb, 2020&#x20;

Major contracts update with the following changes:

* \[Bug Fix] When trying to open a position using your full balance the order would sometimes not fill and get cancelled
* \[Bug Fix] Allow 1x leverage<br>
* \[New] Allow for flexible leverage levels (eg. 3.5x)
* \[New] Allow for margin update on an open positions (add margin)
* \[New] Allow for token integration into the DMEX contract
* \[New] Withdrawal fee for non-ETH collateral currencies will be paid in collateral currency (not ETH as was the case, where you had to deposit ETH to DMEX in order to withdraw DAI)
* \[New] Funding cost charged every 8 hours (approx.). If you keep the position open for less than 8 hours, no funding cost is paid. If the position is open for 10 hours, only 8 hours of funding cost will be charged.

#### 3 Feb, 2020

* \[Bug Fix] User order indicator not showing up properly in the order book for limit orders

#### 29 Jan, 2020

* \[Bug Fix] Pending deposits/withdrawals getting stuck in the UI

#### 27 Jan, 2020

* Minimum order value based on leverage introduced:

  | Leverage    | Minimum Order Value |
  | ----------- | ------------------- |
  | 100x        | 500 USD             |
  | 50x         | 250 USD             |
  | 25x         | 125 USD             |
  | 10x or less | 100 USD             |

#### 22 Jan, 2020

* DMEX Token now available on Uniswap Exchange:\
  <https://uniswap.exchange/swap/0x45Fcf164BaffBefaeE70a368c96de6f33BDCcab0>

#### 19 Jan, 2020

* DAI returned as margin currency

#### 13 Jan, 2020

* Minimum order value set to 100 USD (this is the price \* amount, not the margin/collateral)
* removed the first step in trading fees (0-150$), 100-500$ remains instead
* brought back perpetual contracts with increased funding rate (use expiring contracts for lower funding rates)
* added 90D expiration term option

#### Dec 29, 2019

* Step-by-step interactive tour for new users added

#### Dec 22, 2019

* Market Order added

#### Nov 29, 2019

* Funding rates reduced&#x20;

#### Nov 11, 2019

* Trading fees updated

#### Nov 8, 2019

* Referral program launched

#### Nov 4, 2019

* **Flexible trading fees**\
  This will allow the offering of trading fee discounts for bigger orders and the ability to charge higher fees for small orders (to better cover the gas fees).

#### Nov 1, 2019

* Token collateral functionality added

#### Oct 24, 2019

* Stop-Limit Orders

#### Oct 15, 2019

* **Perpetual contracts**

  Perpetual (never expiring) contracts are now available on all assets. This means you can open a position and keep it open indefinitely. It will not close until you decide to close it.
* **New Leverage levels: 1x and 2x**

  With 1x leverage you can trade assets as you would on a spot exchange, the only difference being that you can only withdraw ETH, so if you buy BTC or other assets you cannot withdraw them, you can only earn the profit on the position in ETH.

#### Oct 12, 2019

* Deployed an updated contract that solves a minor issue in the logic that prevented expired positions from closing properly.

#### Oct 10, 2019

* **Position expiration bug fix.** We have fixed an annoying bug that would throw an error when closing some expired positions and prevent them from closing.
* **Longer expiration terms for highly leveraged contracts.** Now, up to 30D expirations available on all leverages.
* **Perpetual contracts are now available**. Perpetual contracts are futures contracts without an expiration date. Positions on perpetual contracts do not expire and can only be closed through the order book.
* **Fee Credit implementation is now possible.** The new contracts allow dynamic reduction of trading fees for users with Fee Credit on their account.
* **Funding Cost is no longer reserved in the margin**. Funding costs for the life of the contract will no longer be reserved during position opening. Instead, the liquidation price will be adjusted during the time the position is open to take into account the accumulating funding cost. This allows us to offer long term and perpetual futures contracts for high leverage positions.
* **Taker fee will be charged to close an expired position.** When a position is expiring the trader will be charged the taker fee for the closure of the position to cover the gas and oracle costs.

#### Sep 16, 2019

* **Funding cost bug fixed.** Solved a small bug that deducted the wrong amount of funding cost on position closure.

#### Sep 12, 2019

* Email and Password login added to DMEX (private keys are sent to DMEX encrypted, DMEX cannot read the private keys)

#### Sep 3, 2019

* Profit cap removed. Positions can now make unlimited profit.
* Liquidity pools added


# Oracle

An Oracle is a system that provides information from the real world to the blockchain. In our case the Oracle is used to provide the settlement/liquidation price from a trusted third-party exchange.

DMEX implements a unique approach to trading real-world and crypto assets without the actual underlying asset changing hands. Given the blockchain implementation and the use of a decentralised oracle (CHAINLINK) this trading method actually provides exactly the same trading experience while being more secure than a traditional centralised exchange.

## Settlement and Liquidation Price

When a position expires or reaches the liquidation price, DMEX calls on the Oracle to record the latest [MARK PRICE](/definitions/mark-price) on the blockchain.

{% hint style="info" %}
To see the price source for each asset scroll down to the [ASSETS](/assets/btc) section and select an asset.
{% endhint %}

Only after the latest MARK PRICE is recorded on the DMEX smart contract, the position can be settled or liquidated.

{% hint style="success" %}
The use of an Oracle is crucial to the safety of user funds, because it eliminates the risk of price manipulation on the part of DMEX owners.
{% endhint %}


# Funds Safety

DMEX is built with safety in mind. Every step of the way we made sure that no attack angles exist. All funds are stored safely on the DMEX smart contract. Below is a list of some of the security measures employed:

### Frontend

* [x] Domain SSL long term certificate
* [x] 2FA authentications for datacenter access
* [x] IP-restricted access to the frontend CDN
* [x] Pipeline deployment for the frontend code
* [x] MetaMask and Ledger Nano S integration

### Backend

We do not store any fund related information on the backend. The user owns his/her private keys. Nobody can access the funds without having the private keys.

* [x] IP-restricted access
* [x] Strong Firewall protection

### Smart contracts

* [x] All funds operations require a signature from the owner
* [x] Trading contract cannot be changed in the base contract after deployment&#x20;

### Oracle

* [x] The Oracle contract cannot be changed after deployment (to prevent price feed hacking)
* [x] Escape hatch for stuck contracts (if the oracle doesn't settle the futures contract within 2 hours, all collaterals are released)

{% hint style="info" %}
Join our [Telegram group](https://t.me/dmex_app) and follow our [Twitter](https://twitter.com/DMEX_APP) account to stay up to date with the latest developments and have a way to contact us in case you need any help.
{% endhint %}


# Base Tokens

* TESTNER

0x0000000000000000000000000000000000000003 - DEMO USD

* Bitcoin

0x0000000000000000000000000000000000000002 - BTC<br>

* Ethereum

0x0000000000000000000000000000000000000000 - ETH

0x0000000000000000000000000000000000000001 - DAI

0x0000000000000000000000000000000000000004 - USDT

0x0000000000000000000000000000000000000005 - USDC

0x0000000000000000000000000000000000000006 - WBTC

<br>

* &#x20;POLYGON

0x0000000000000000000000000000000000000007 - MATIC

0x0000000000000000000000000000000000000008 - USDT

0x0000000000000000000000000000000000000009 - USDC

0x0000000000000000000000000000000000000010 - WBTC

<br>

* &#x20;AVAC

0x0000000000000000000000000000000000000011 - AVAX

0x0000000000000000000000000000000000000012 - USDT

0x0000000000000000000000000000000000000013 - USDC

<br>

* OPTIMISM

0x0000000000000000000000000000000000000014 - ETH

0x0000000000000000000000000000000000000015 - USDT

0x0000000000000000000000000000000000000016 - USDC

0x0000000000000000000000000000000000000017 - WBTC

<br>

* ARBITRUM

0x0000000000000000000000000000000000000018 - ETH

0x0000000000000000000000000000000000000019 - USDT

0x0000000000000000000000000000000000000020 - USDC

0x0000000000000000000000000000000000000021 - WBTC

<br>

* BASE

0x0000000000000000000000000000000000000022 - ETH

0x0000000000000000000000000000000000000023 - USDC

<br>

* BNB

0x0000000000000000000000000000000000000025 - BNB

0x0000000000000000000000000000000000000026 - BUSD

0x0000000000000000000000000000000000000027 - USDC

<br>

* SOL

0x0000000000000000000000000000000000000028 - SOL

<br>

* TON

0x0000000000000000000000000000000000000029 - TON

0x0000000000000000000000000000000000000030 - USDT

<br>

* XMR (MONERO)

0x0000000000000000000000000000000000000031 - XMR

<br>

* TRON

0x0000000000000000000000000000000000000024 - USDT

0x0000000000000000000000000000000000000032 - TRX


# Binary Contracts

Binary Contracts offer a distinct trading experience compared to Perpetual Contracts (Perps). Here are the key differences and how they work:

* **Binary Outcome Betting** Traders speculate on a simple yes/no question — for example: “Will Bitcoin’s price be above a specific target price 15 minutes from now?”
* **Pricing Reflects Probability** Contracts are priced in cents (between $0.00 and $1.00), where the price directly represents the market’s current estimated probability of the “Yes” (above target) outcome occurring at expiry.
  * $0.00 = 0% probability
  * $1.00 = 100% probability Example: Buying (going long) at $0.45 means you’re paying 45 cents per share, implying the market assigns a 45% chance of the price being above the target at expiry.
* **Available Expiry Durations** Binary Contracts come with fixed lifetimes: 15 minutes, 1 hour, 4 hours, or 24 hours.
* **Trading Flexibility** You can enter or exit positions at any time before expiry by trading on the order book (buying or selling shares at current market prices). Alternatively, hold until expiry:
  * If the final asset price meets the condition (above target) → contract resolves to **$1.00** per share
  * If not → contract resolves to **$0.00** per share
* **Long and Short Mechanics** You can take either side of the trade:
  * **Long** (buy “Yes” shares): Profit if the outcome occurs
  * **Short** (sell “Yes” shares / buy the opposing side): Profit if the outcome does **not** occur Example: If you short 100 shares at $0.50 and the contract resolves to $0.00 (price below target), your profit is $0.50 × 100 = **$50**.
* **Leverage Available** Like Perps, Binary Contracts support leverage, allowing traders to amplify their exposure (subject to platform risk parameters and margin requirements).

In short, Binary Contracts let you trade directly on short-term price direction probabilities with fixed-expiry binary payoffs, full order-book liquidity for early exits, and the ability to go long or short.


# 1-Click trading

When connecting an external wallet to DMEX, the user must sign every action with the connected wallet (order creation, order cancellation, margin updates, withdrawals). This can become cumbersome when a trader performs multiple actions in a short time or uses DMEX from a mobile device.

To improve the user experience, we have introduced **1-Click trading**. When enabled, the browser generates a fresh wallet and private key, then stores them locally in the user's browser. The generated wallet address (not the private key) is sent to the smart contract and registered as a delegate for the main wallet. This allows the frontend to sign and send requests using the delegate's private key to perform most actions—**except withdrawals**, which still require a signature from the main wallet. The delegate authorization remains valid for 24 hours, after which a new authorization must be issued.

Once 1-Click trading is enabled, the user can perform actions without signing each time in their wallet. To revoke the delegate wallet's authorization, go to the **Wallets** dropdown in the top-right corner and click **"Disable 1-Click trading"** below your wallet address.


# Volume on DMEX

The volume shown on the DMEX chart and in the trade history represents an aggregation of the price source volume and internal DMEX traded volume. The last column in the trade history table shows whether the trade shown was performed on DMEX (internally - "I") or on the price source exchange (externally - "E").

### Overlap volume display

When an external trade is shown in the Trade History it is generated by the one side of the order book overlapping the other side. For example, if a buy trade shows up in the trade list, it means that the buy side of the order book overlapped the sell side of the order book. This is important because it means that if your order was at the bottom of the sell side and the buy side overlapped it, your order would have been filled.

In other words, although not all trades shown in the Trade History and the chart are trades performed on DMEX, if your order would match the price of the trade, the order would have been filled. Therefore, for trading purposes the volume shown on DMEX is indicative of what is happening on the price source exchange and is effective in the sense that the volume is filling orders and triggering stop-losses.

{% hint style="info" %}
The Overlap volume model was developed to create an active trading environment and replicate the price source exchange.&#x20;
{% endhint %}

{% hint style="warning" %}
If you place an order to buy 1 BTC at the price of 7000$ and you see a trade of 6990$ happening, it means your order was filled. It is not possible for the price to go past your order without filling it.
{% endhint %}


# Bitcoin Integration

DMEX has integrated with [Provable.xyz](https://provable.xyz)'s (the same company providing the Oracle services) new service called [pTokens ](https://ptokens.io)that offers a trustless way to move Bitcoin to the Ethereum blockchain and back.

#### How does it work?

***Provable*** is running a TEE (Trusted Execution Environment), or in other words a blackbox machine that is preprogrammed to act in a certain way and has no access to it from external parties. This machine once started generates private keys for two blockchains (Bitcoin and Ethereum), no-one has access to the private keys, just the TEE.

The TEE can be contacted to request a BTC deposit address that would be linked to an Etheruem address. Every time a user sends BTC to the BTC deposit address, the TEE mints an equal amount of pBTC (a ERC777 Ethereum Token which is pegged 1:1 with Bitcoin, 1 pBTC = 1 BTC) and sends the newly minted pBTC tokens to the Ethereum address specified when requesting the BTC address.

At anytime, a user can redeem his/her pBTC into BTC by calling the redeem() method on the pBTC contract.

#### Why this approach is superior to other BTC pegged tokens?

pBTC is a direct representation of Bitcoin on the Ethereum blockchain. Other pegged tokens (such as WBTC) require an exchange to switch between BTC and WBTC which adds fees and spread costs. pBTC on the other hand allows switching from BTC to pBTC and the other way around without any cost and not requiring liquidity. All bitcoins sent to the TEE are converted into the exactly the same amount of pBTC minus the blockchain fees and a small fee taken by ***Provable*** for the service.

#### How is pBTC integrated into DMEX?

DMEX was designed from the get go with user experience in mind, therefore we were not satisfied with simply adding pBTC as a token. That would require users to also have ETH in order to be able to deposit funds into the DMEX contract. We wanted to give our users the ability to use Bitcoin on DMEX without needing to purchase any ETH (users still need an Ethereum account in order to sign orders, but no ETH is required).

In order to provide the best user experience we have adopted the following approach:

1. When a user clicks on the "Deposit" button, while having BTC chosen as the margin currency. The website generates a deposit contract for the user (everything is done in the browser). This contract is specific to the user's wallet, all funds sent to it will be credited to the users' account on DMEX).\
   \
   The deposit contract code is as follows:

```
pragma solidity >0.4.99 <0.6.0;

// https://theethereum.wiki/w/index.php/ERC20_Token_Standard
contract ERC20Interface {
    function approve(address spender, uint tokens) public returns (bool success);
    function balanceOf(address tokenOwner) public view returns (uint balance);
}

contract DMEXBaseInterface {
    function depositTokenForUser(address token, uint128 amount, address user) public;
}

contract DepositToDMEX { 
    address public owner;
    address public dmex_contract;

    event Log(address tokenAddress);

    constructor(address owner_, address dmex_contract_, address token) public {
        owner = owner_;
        dmex_contract = dmex_contract_;
        IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24).setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
        sendTokensToDMEX(token);
    }
    
    function sendTokensToDMEX(address token) public
    {
        uint256 availableBalance = ERC20Interface(token).balanceOf(address(this));
        uint128 shortAvailableBalance = uint128(availableBalance);
        ERC20Interface(token).approve(dmex_contract, availableBalance);
        DMEXBaseInterface(dmex_contract).depositTokenForUser(token, shortAvailableBalance, owner);
    }

    function tokensReceived(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) public
    {
        emit Log(msg.sender);
        sendTokensToDMEX(msg.sender);
    }


}
```

2\. The deposit contract address is used when requesting the BTC address from ***pTokens***. The BTC address received from ***pTokens*** is displayed to the user. All Bitcoins sent to the BTC address will be forwarded in pBTC token form to the user's deposit contract.

3\. When the user wants to withdraw his BTC from DMEX, the redeem function is called from the DMEX contract on the ***pBTC*** contract with the Bitcoin withdrawal address as argument. This redeem() call triggers the TEE to release the specified bitcoin amount to the BTC withdrawal address and burn the associated ***pBTC***.\ <br>

{% hint style="info" %}
This approach allows for users not familiar with Ethereum to use their Bitcoins in a trustless way while using DMEX. All the user needs to do, is send his/her bitcoins to the BTC deposit address and the Bitcoins will appear in the user's account on DMEX.
{% endhint %}

{% hint style="info" %}
The deposit processing time will be equal to:\
\
Bitcoin transaction confirmation (1 confirmation) + Ethereum transaction confirmation (1 confirmation)
{% endhint %}


# xDAI Integration

xDAI is an Ethereum sidechain that operates a POS (Proof-of-Stake) validation mechanism (the new validation mechanism used in Ethereum 2.0). xDAI uses the same wallet system and signatures, meaning that your Ethereum wallet will work with xDAI.

On DMEX xDAI is only used for trade processing. All funds are stored on Ethereum as before.

### Do you need to purchase xDAI to use DMEX?

No. You do not need to do anything, xDAI is integrated as part of the stack and is not affecting the user in any way. You simply deposit to DMEX as before on Ethereum network.

### How does the Ethereum contract communicate with the xDAI contracts?

Ethereum contracts are connected to the xDAI contracts through a decentralized bridge that relays messages between the two chains.

{% hint style="info" %}
More information on the xDAI sidechain can be found [here](https://www.xdaichain.com/).
{% endhint %}


# Withdrawing from Old Contracts

At DMEX we are continually working on improving the exchange and the user experience, therefore, periodically we are updating our contracts to allow this improvements.

When the contracts are updated, the balances will show up as Zero in the exchange header.

In order to withdraw funds form an old contract, please follow the steps below:

1. Go to Menu > Smart Contracts
2. In the first dropdown (Base Contract) select one of the previous contracts (the second one in most cases)
3. Go back to the exchange, you should now see the balance on your old contract.
4. Withdraw funds form the old contract using the standard Withdraw flow.
5. Switch back to the latest contract (using steps 1, 2, 3) and deposit funds to the new contract.

{% hint style="info" %}
If you have open positions on the old contract, you can leave them open. When you decide to close them simply use the close button in the positions list. \
\
Note: When you close a position on the old contract the collateral and profit/loss will be credited to the old contract so it will not show up in the balance of the new contract. Use the steps above to retrieve the unlocked funds from the old contract.
{% endhint %}


# General

### REST API

#### Base URL

`https://back.dmex.app/`

#### Endpoints

**1. Get Candles**

* **Method**: `GET`
* **Path**: `/candles`
* **Query Parameters**:
  * `symbol` (required): Asset symbol (e.g., "btcusd")
  * `interval` (required): Time interval ("1", "5", "15", "60", "240", "1440")
  * `from` (optional): Start timestamp
  * `to` (optional): End timestamp
  * `limit` (optional): Number of candles (default: 500)

**Example Request**:

```
GET /candles?symbol=btcusd&interval=60&limit=100
```

**Response**:

```json
{
  "s": "ok",
  "c": [50000, 50100, 50050],
  "o": [49950, 50000, 50100],
  "h": [50200, 50150, 50200],
  "l": [49900, 49980, 50000],
  "v": [1500, 1200, 800],
  "t": [1640995200, 1640998800, 1641002400]
}
```

**2. Server Ping**

* **Method**: `GET`
* **Path**: `/sPing`

**Response**:

```json
{
  "status": "ok",
  "timestamp": 1640995200000
}
```

**3. Contracts**

* **Method**: `GET`
* **Path**: `/contracts`
* **Description**: Returns all available derivative contracts

**Response**:

```json
[
  {
    "ticker_id": "BTC-USD",
    "base_currency": "BTC",
    "target_currency": "USD",
    "last_price": "50000.00",
    "base_volume": "150.25",
    "target_volume": "7512500.00",
    "bid": "49950.00",
    "ask": "50050.00",
    "high": "51000.00",
    "low": "49000.00",
    "product_type": "Perpetual",
    "open_interest": "1000.50",
    "open_interest_usd": "50025000.00",
    "index_price": "50000.00",
    "index_name": "BTC Index",
    "index_currency": "BTC",
    "start_timestamp": 0,
    "end_timestamp": 0,
    "funding_rate": "0.00010000",
    "next_funding_rate": "0.00010000",
    "next_funding_rate_timestamp": 1641002400,
    "contract_type": "Vanilla",
    "contract_price": "50000.00",
    "contract_price_currency": "USD"
  }
]
```

**4. Orderbook**

* **Method**: `GET`
* **Path**: `/orderbook`
* **Query Parameters**:
  * `ticker_id` (required): Ticker ID (e.g., "BTC-USD")
  * `depth` (optional): Number of orders per side (default: 100, max: 500)

**Example Request**:

```
GET /orderbook?ticker_id=BTC-USD&depth=50
```

**Response**:

```json
{
  "ticker_id": "BTC-USD",
  "timestamp": 1640995200000,
  "bids": [
    ["49950.00", "1.5"],
    ["49900.00", "2.0"]
  ],
  "asks": [
    ["50050.00", "1.2"],
    ["50100.00", "0.8"]
  ]
}
```

***

### WebSocket API

#### Connection

* **URL**: `wss://back.dmex.app/ws`
* **Protocol**: WebSocket
* **Authentication**: Required for most operations

#### Message Format

All WebSocket messages follow this JSON structure:

```json
{
  "type": "message_type",
  "data": {
    // Message-specific data
  }
}
```

#### Client to Server Messages

**1. Authentication**

```json
{
  "type": "auth",
  "data": {
    "user_address": "0x1234567890abcdef...",
  }
}
```

**Response**: User data, balances, positions, orders, etc.

**2. Subscribe to Asset**

```json
{
  "type": "subscribeAsset",
  "data": {
    "asset": "btcusdt"
  }
}
```

**Response**: Asset data, orderbook, trades

**10. Ping**

```
"ping"
```

**Response**: Connection stays alive

#### Server to Client Messages

**1. Asset Data**

```json
{
  "type": "assets",
  "data": [
    {
      "symbol": "btcusd",
      "last_price": "50000.00",
      "mark_price": 50100.00,
      "high": 51000.00,
      "low": 49000.00,
      "volume": 1500.50,
      "change": 2.5,
      "funding_rate": "0.0001",
      "open_interest": 25000000.00,
      "daily_trades": 1250
    }
  ]
}
```

**2. User Parameters**

```json
{
  "type": "params_user",
  "data": {
    "risk_limit": "5000",
    "mm_multiplier": "1.0",
    "fr_multiplier": "1.0",
    "btc_deposit_address": "bc1q...",
    "eth_deposit_address": "0x...",
    "xmr_deposit_address": "4...",
    "tron_deposit_address": "T...",
    "solana_deposit_address": "..."
  }
}
```

**3. Balances**

```json
{
  "type": "balances",
  "data": [
    {
      "currency": "btc",
      "available": "1.5",
      "total": "2.0",
      "reserved": "0.5"
    }
  ]
}
```

**4. Positions**

```json
{
  "type": "positions",
  "data": [
    {
      "symbol": "btcusd",
      "side": "long",
      "size": "1.5",
      "entry_price": "49500.00",
      "mark_price": "50000.00",
      "liquidation_price": "45000.00",
      "unrealized_pnl": "750.00",
      "margin": "5000.00",
      "leverage": "10",
      "margin_type": "isolated"
    }
  ]
}
```

**5. Orders**

```json
{
  "type": "orders",
  "data": [
    {
      "id": "order_hash",
      "symbol": "btcusd",
      "side": "buy",
      "amount": "1.0",
      "price": "49000.00",
      "filled": "0.5",
      "status": "open|filled|cancelled",
      "type": "limit|market",
      "timestamp": 1640995200000
    }
  ]
}
```

**6. Trades**

```json
{
  "type": "trades",
  "data": [
    {
      "symbol": "btcusd",
      "price": "50000.00",
      "amount": "0.5",
      "side": "buy",
      "timestamp": 1640995200000
    }
  ]
}
```

**7. Orderbook**

```json
{
  "type": "orderbook",
  "data": {
    "symbol": "btcusd",
    "bids": [
      ["49950.00", "1.5"],
      ["49900.00", "2.0"]
    ],
    "asks": [
      ["50050.00", "1.2"],
      ["50100.00", "0.8"]
    ]
  }
}
```

**8. Mark Price Updates**

```json
{
  "type": "mark_price",
  "data": {
    "symbol": "btcusd",
    "price": 50125.50,
    "timestamp": 1640995200000
  }
}
```

**9. Funding Rate Updates**

```json
{
  "type": "funding_rate",
  "data": {
    "symbol": "btcusd",
    "funding_rate": "0.0001"
  }
}
```

**10. Error Messages**

```json
{
  "type": "error",
  "data": {
    "message": "Error description"
  }
}
```

**11. Success Messages**

```json
{
  "type": "success",
  "data": {
    "message": "Operation successful"
  }
}
```

***

### Authentication

#### WebSocket Authentication

1. Connect to WebSocket endpoint
2. Send authentication message with user address and unique ID
3. Server validates and responds with user data

#### Message Signing

For sensitive operations (orders, withdrawals, margin updates), messages must be signed:

* **hash**: Keccak256 hash of message data
* **v**: Recovery ID (27 or 28)
* **r**: First 32 bytes of signature
* **s**: Last 32 bytes of signature
* **user**: User's Ethereum address

***

### Rate Limiting

#### Global Limits

* **Global**: 1000 requests per second with burst of 5000
* **Per IP**: 1 request per second with burst of 5

#### Connection Limits

* **Max connections per user**: 5
* **Max total connections**: Configurable via environment

#### Rate Limit Headers

Rate limit information is not exposed in headers but enforced server-side.

***

### Error Handling

#### WebSocket Errors

```json
{
  "type": "error",
  "data": {
    "message": "Error description"
  }
}
```

#### HTTP Errors

* **400 Bad Request**: Invalid parameters
* **404 Not Found**: Endpoint or resource not found
* **429 Too Many Requests**: Rate limit exceeded
* **500 Internal Server Error**: Server error

#### Common Error Messages

* `"Invalid wallet"`: Authentication failed
* `"Too Many Requests"`: Rate limit exceeded
* `"Ticker not found"`: Invalid asset symbol
* `"SERVER MAX ALLOWED CONNECTIONS REACHED"`: Connection limit exceeded
* `"Invalid Signature"`: Message signature validation failed

***

### Data Types

#### Precision

* **Prices**: Stored as big integers with 1e8 precision
* **Amounts**: Stored as big integers with asset-specific precision
* **Funding Rates**: Stored as big integers with 1e16 precision

#### Timestamps

* **WebSocket**: Unix timestamps in milliseconds
* **REST**: Unix timestamps in seconds or milliseconds (endpoint-specific)

#### Asset Symbols

* Format: `{base}usd` (e.g., "btcusd", "ethusd")
* Case-insensitive but returned in lowercase

#### Order Sides

* `"buy"` or `"sell"`

#### Order Types

* `"limit"`: Limit order
* `"market"`: Market order

#### Margin Types

* `"isolated"`: Isolated margin
* `"cross"`: Cross margin

#### Order Status

* `"open"`: Active order
* `"filled"`: Completely filled
* `"cancelled"`: Cancelled order
* `"partially_filled"`: Partially filled


# Base Tokens

### Supported Base Tokens

These are the canonical token addresses used across DMEX for each chain.

#### TESTNET

| Address                                      | Symbol   |
| -------------------------------------------- | -------- |
| `0x0000000000000000000000000000000000000003` | DEMO USD |

#### Ethereum (ETH)

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000000` | ETH    |
| `0x0000000000000000000000000000000000000001` | DAI    |
| `0x0000000000000000000000000000000000000002` | BTC    |
| `0x0000000000000000000000000000000000000004` | USDT   |
| `0x0000000000000000000000000000000000000005` | USDC   |
| `0x0000000000000000000000000000000000000006` | WBTC   |

#### Polygon

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000007` | MATIC  |
| `0x0000000000000000000000000000000000000008` | USDT   |
| `0x0000000000000000000000000000000000000009` | USDC   |
| `0x0000000000000000000000000000000000000010` | WBTC   |

#### Avalanche (AVAX)

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000011` | AVAX   |
| `0x0000000000000000000000000000000000000012` | USDT   |
| `0x0000000000000000000000000000000000000013` | USDC   |

#### Optimism

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000014` | ETH    |
| `0x0000000000000000000000000000000000000015` | USDT   |
| `0x0000000000000000000000000000000000000016` | USDC   |
| `0x0000000000000000000000000000000000000017` | WBTC   |

#### Arbitrum

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000018` | ETH    |
| `0x0000000000000000000000000000000000000019` | USDT   |
| `0x0000000000000000000000000000000000000020` | USDC   |
| `0x0000000000000000000000000000000000000021` | WBTC   |

#### Base

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000022` | ETH    |
| `0x0000000000000000000000000000000000000023` | USDC   |

#### BNB Chain

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000025` | BNB    |
| `0x0000000000000000000000000000000000000026` | BUSD   |
| `0x0000000000000000000000000000000000000027` | USDC   |

#### Solana

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000028` | SOL    |

#### TON

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000029` | TON    |
| `0x0000000000000000000000000000000000000030` | USDT   |

#### Monero (XMR)

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000031` | XMR    |

#### TRON

| Address                                      | Symbol |
| -------------------------------------------- | ------ |
| `0x0000000000000000000000000000000000000024` | USDT   |
| `0x0000000000000000000000000000000000000032` | TRX    |


# REST

### Authentication

All order-related endpoints require a valid signature. The signature is created by signing the order/cancel hash with the user's private key or an authorized delegate wallet.

***

### Orders

#### Get Open Orders

Retrieves all open orders for a user.

**Endpoint:** `GET /api/orders`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/orders?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "hash": "0x...",
      "user_address": "0x...",
      "base_token": "0x...",
      "asset": "btcusd",
      "amount": "1000000000",
      "price": "10000000000000",
      "side": true,
      "nonce": 1234567890,
      "leverage": "1000000000",
      "closing_order": false,
      "remaining_amount": "1000000000",
      "closed": false,
      "stop": false,
      "stop_price": "0",
      "stopped": false,
      "is_market": false,
      "post_only": false,
      "decimals": 2,
      "amount_dec": 4,
      "margin_currency_symbol": "USDC",
      "created_at": "2024-01-15T10:30:00Z"
    }
  ]
}
```

#### Create Order

Creates a new trading order.

**Endpoint:** `POST /api/order`

**Request Body:**

```json
{
  "hash": "0x...",
  "user_address": "0x...",
  "base_token": "0x...",
  "asset": "btcusd",
  "amount": "1000000000",
  "price": "10000000000000",
  "side": true,
  "nonce": 1234567890,
  "leverage": "1000000000",
  "closing_order": false,
  "v": 27,
  "r": "0x...",
  "s": "0x...",
  "remaining_amount": "1000000000",
  "closed": false,
  "stop": false,
  "stop_price": "0",
  "stopped": false,
  "is_market": false,
  "post_only": false,
  "decimals": 2,
  "amount_dec": 4,
  "margin_currency_symbol": "USDC",
  "replace_hash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
```

**Field Descriptions:**

| Field              | Type    | Description                                           |
| ------------------ | ------- | ----------------------------------------------------- |
| `hash`             | string  | Order hash (keccak256 of order parameters)            |
| `user_address`     | string  | User's Ethereum address                               |
| `base_token`       | string  | Margin currency token address                         |
| `asset`            | string  | Trading pair symbol (e.g., "btcusd", "ethusd")        |
| `amount`           | string  | Order amount (as string, scaled by 1e8)               |
| `price`            | string  | Order price (as string, scaled by 1e8)                |
| `side`             | boolean | `true` = buy/long, `false` = sell/short               |
| `nonce`            | integer | Unique nonce for the order                            |
| `leverage`         | string  | Leverage amount (scaled by 1e8), `0` for cross margin |
| `closing_order`    | boolean | `true` if this is a reduce-only order                 |
| `v`, `r`, `s`      | -       | ECDSA signature components                            |
| `remaining_amount` | string  | Remaining unfilled amount                             |
| `stop`             | boolean | `true` if this is a stop order                        |
| `stop_price`       | string  | Trigger price for stop orders                         |
| `is_market`        | boolean | `true` for market orders                              |
| `post_only`        | boolean | `true` to only add liquidity (maker only)             |
| `replace_hash`     | string  | Hash of order to replace (for order amendments)       |

**Success Response (200):**

```json
{
  "success": true,
  "message": "Order created",
  "data": {
    "hash": "0x..."
  }
}
```

**Error Response (400):**

```json
{
  "success": false,
  "error": "Insufficient balance"
}
```

**Possible Errors:**

* `Nonce too large`
* `Invalid order hash - please refresh and try again`
* `Invalid Signature`
* `Delegate expired`
* `Order with this hash already exists`
* `Maximum 100 open orders allowed`
* `Insufficient balance`
* `Leverage too high`
* `Too much leverage`
* `Minimum order value is 10 USD`
* `Maximum order value for this asset is X USD`
* `Min acceptable price is X`
* `Max acceptable price is X`

***

#### Cancel Order

Cancels an existing open order.

**Endpoint:** `POST /api/cancel-order`

**Request Body:**

```json
{
  "order_hash": "0x...",
  "v": 27,
  "r": "0x...",
  "s": "0x..."
}
```

**Field Descriptions:**

| Field         | Type   | Description                       |
| ------------- | ------ | --------------------------------- |
| `order_hash`  | string | Hash of the order to cancel       |
| `v`, `r`, `s` | -      | ECDSA signature of the order hash |

**Success Response (200):**

```json
{
  "success": true,
  "message": "Order cancelled",
  "data": {
    "hash": "0x..."
  }
}
```

**Error Response (400):**

```json
{
  "success": false,
  "error": "Order not found"
}
```

**Possible Errors:**

* `Order not found`
* `Liquidation order cannot be canceled`
* `Invalid Signature`
* `Delegate expired`

***

### Trades

#### Get User Trades

Retrieves trade history for a user (last 100 trades).

**Endpoint:** `GET /api/trades`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/trades?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "hash": "0x...",
      "user": "0x...",
      "asset": "btcusd",
      "base_token": "0x...",
      "amount": "1000000000",
      "price": "10000000000000",
      "side": true,
      "fee": "100000",
      "created_at": "2024-01-15T10:30:00Z"
    }
  ]
}
```

***

### Positions

#### Get Open Positions

Retrieves all open positions for a user.

**Endpoint:** `GET /api/positions/open`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/positions/open?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "tx_hash": "0x...",
      "hash": "0x...",
      "base_token": "0x...",
      "asset": "btcusd",
      "side": true,
      "size": "1000000000",
      "entry_block": "12345678",
      "value": "50000000000",
      "entry_price": "10000000000000",
      "last_price": "10100000000000",
      "mark_price": 0.5,
      "liquidation_price": "9000000000000",
      "margin": "5000000000",
      "unrealized_pnl": "100000000",
      "realized_pnl": "0",
      "funding_rate": "100000",
      "decimals": 2,
      "amount_dec": 4,
      "margin_dec": 6,
      "margin_symbol": "USDC",
      "profit": "0",
      "loss": "0",
      "funding_cost": "0",
      "ur_funding_cost": "0",
      "created_at": "2024-01-15T10:30:00Z",
      "liquidated": false,
      "global_mm": 0.005,
      "is_cross": false,
      "cross_margin": "0"
    }
  ]
}
```

***

#### Get Closed Positions

Retrieves closed positions for a user (last 100).

**Endpoint:** `GET /api/positions/closed`

**Query Parameters:**

| Parameter | Type   | Required | Description             |
| --------- | ------ | -------- | ----------------------- |
| `user`    | string | Yes      | User's Ethereum address |

**Example Request:**

```
GET /api/positions/closed?user=0x1234567890abcdef1234567890abcdef12345678
```

**Success Response (200):**

```json
{
  "success": true,
  "data": [
    {
      "tx_hash": "0x...",
      "hash": "0x...",
      "base_token": "0x...",
      "asset": "btcusd",
      "side": true,
      "liquidated": false,
      "profit": "500000000",
      "loss": "0",
      "funding_cost": "10000000",
      "ur_funding_cost": "0",
      "created_at": "2024-01-15T10:30:00Z",
      "global_mm": 0.005,
      "decimals": 2,
      "amount_dec": 4
    }
  ]
}
```

***

### Binary Contracts

#### Get Settled Binary Contracts

Retrieves historical settled binary contracts for a given underlying asset and contract duration.

**Endpoint:** `GET /settled-binary-contracts`

**Query Parameters:**

| Parameter      | Type    | Required | Description                                          |
| -------------- | ------- | -------- | ---------------------------------------------------- |
| `underlying`   | string  | Yes      | Underlying asset symbol (e.g., "BTCUSDT", "ETHUSDT") |
| `contractLife` | integer | Yes      | Contract duration in minutes (e.g., 15, 60)          |

**Example Request:**

```
GET /settled-binary-contracts?underlying=btcusd&contractLife=15
```

**Success Response (200):**

```json
[
  {
    "symbol": "BTCUSDT-1706356800-105000-15",
    "underlying_symbol": "BTCUSDT",
    "target": 105000.00,
    "final_price": 105234.56,
    "is_above_target": true,
    "started_at": 1706356800,
    "settled_at": 1706357700
  },
  {
    "symbol": "BTCUSDT-1706355900-104500-15",
    "underlying_symbol": "BTCUSDT",
    "target": 104500.00,
    "final_price": 104123.45,
    "is_above_target": false,
    "started_at": 1706355900,
    "settled_at": 1706356800
  }
]
```

**Response Field Descriptions:**

| Field               | Type    | Description                               |
| ------------------- | ------- | ----------------------------------------- |
| `symbol`            | string  | Unique binary contract identifier         |
| `underlying_symbol` | string  | The underlying asset (e.g., "BTCUSD")     |
| `target`            | float   | Strike/target price for the contract      |
| `final_price`       | float   | Settlement price at contract expiry       |
| `is_above_target`   | boolean | `true` if final price was above target    |
| `started_at`        | integer | Contract start time (Unix timestamp)      |
| `settled_at`        | integer | Contract settlement time (Unix timestamp) |

**Error Responses:**

| Status | Message                                  |
| ------ | ---------------------------------------- |
| 400    | Missing required parameter: underlying   |
| 400    | Missing required parameter: contractLife |
| 400    | Invalid contractLife parameter           |
| 500    | Failed to fetch settled contracts        |

***

### Error Handling

All endpoints return errors in a consistent format:

```json
{
  "success": false,
  "error": "Error message describing what went wrong"
}
```

**HTTP Status Codes:**

| Code | Description                                          |
| ---- | ---------------------------------------------------- |
| 200  | Success                                              |
| 400  | Bad Request (validation error, business logic error) |
| 405  | Method Not Allowed                                   |

***

### Notes

* All `*big.Int` values are represented as strings to preserve precision
* Amounts and prices are scaled by `1e8` unless otherwise specified
* Timestamps are in ISO 8601 format (UTC)
* Ethereum addresses and hashes should include the `0x` prefix


# WebSocket


# Create Order

## Create Order API

This guide explains how to programmatically create orders on the DMEX exchange.

### Overview

Orders are created by:

1. Building the order parameters
2. Generating a keccak256 hash of the order
3. Signing the hash with your private key
4. Sending the signed order via WebSocket

### Order Parameters

| Parameter       | Type    | Description                                       |
| --------------- | ------- | ------------------------------------------------- |
| `amount`        | string  | Order size (will be multiplied by 1e8)            |
| `price`         | string  | Order price (will be multiplied by 1e8)           |
| `side`          | boolean | `true` = buy/long, `false` = sell/short           |
| `leverage`      | string  | Leverage multiplier (e.g., "10" for 10x)          |
| `base_token`    | address | The margin token contract address                 |
| `asset`         | string  | Trading pair symbol (e.g., "BTC", "ETH")          |
| `closing_order` | boolean | `true` if this order closes an existing position  |
| `stop`          | boolean | `true` if this is a stop order                    |
| `stop_price`    | string  | Trigger price for stop orders (multiplied by 1e8) |
| `is_market`     | boolean | `true` for market orders                          |
| `post_only`     | boolean | `true` to ensure order is maker only              |
| `replace_hash`  | string  | Hash of order to replace, or zero hash            |

### JavaScript/TypeScript Example

```typescript
import { ethers } from 'ethers';
import Web3 from 'web3';

// Configuration
const WS_ENDPOINT = 'wss://api.dmex.app/ws';
const BASE_TOKEN = '0x...'; // USDC or other margin token address

async function createOrder({
    privateKey,
    asset,
    amount,
    price,
    side,
    leverage,
    closingOrder = false,
    stop = false,
    stopPrice = '0',
    isMarket = false,
    postOnly = false,
    replaceHash = ''
}: {
    privateKey: string;
    asset: string;
    amount: string;
    price: string;
    side: boolean;
    leverage: string;
    closingOrder?: boolean;
    stop?: boolean;
    stopPrice?: string;
    isMarket?: boolean;
    postOnly?: boolean;
    replaceHash?: string;
}) {
    // Initialize web3 for signing
    const web3 = new Web3();
    const account = web3.eth.accounts.privateKeyToAccount(privateKey);
    const userAddress = account.address;

    // Convert to 1e8 precision
    const amountScaled = (Number(amount) * 1e8).toFixed(0);
    const priceScaled = (Number(price) * 1e8).toFixed(0);
    const stopPriceScaled = (Number(stopPrice) * 1e8).toFixed(0);

    // Generate unique nonce
    const nonce = Date.now();

    // Create order hash
    const orderHash = ethers.utils.keccak256(
        ethers.utils.defaultAbiCoder.encode(
            ['string', 'address', 'address', 'uint256', 'uint256', 'bool', 'uint256', 'uint256'],
            [asset, BASE_TOKEN, userAddress, amountScaled, priceScaled, side, nonce, leverage]
        )
    );

    // Sign the hash
    const signedData = web3.eth.accounts.sign(orderHash, privateKey);
    const signature = signedData.signature;

    // Parse signature into v, r, s
    const sig = signature.slice(2);
    const r = `0x${sig.slice(0, 64)}`;
    const s = `0x${sig.slice(64, 128)}`;
    let v = parseInt(`0x${sig.slice(128, 130)}`, 16);
    if (v < 27) v += 27;

    // Format replace_hash
    const formattedReplaceHash = replaceHash === '' 
        ? '0x0000000000000000000000000000000000000000000000000000000000000000'
        : replaceHash;

    // Build order payload
    const order = {
        hash: orderHash,
        user_address: userAddress,
        base_token: BASE_TOKEN,
        asset: asset,
        amount: amountScaled,
        price: priceScaled,
        side: side,
        nonce: nonce,
        leverage: leverage,
        closing_order: closingOrder,
        v: v,
        r: r,
        s: s,
        remaining_amount: amountScaled,
        closed: false,
        stop: stop,
        stop_price: stopPriceScaled,
        stopped: false,
        is_market: isMarket,
        replace_hash: formattedReplaceHash,
        post_only: postOnly
    };

    return order;
}

// Send order via WebSocket
function sendOrder(ws: WebSocket, order: object) {
    const message = JSON.stringify({
        op: 'create_order',
        data: order
    });
    ws.send(message);
}

// Usage Example
async function main() {
    const privateKey = '0x...'; // Your private key
    
    // Create a limit buy order for 0.1 BTC at $50,000 with 10x leverage
    const order = await createOrder({
        privateKey,
        asset: 'BTC',
        amount: '0.1',
        price: '50000',
        side: true,        // true = buy/long
        leverage: '10',
        closingOrder: false,
        isMarket: false,
        postOnly: false
    });

    // Connect to WebSocket and send
    const ws = new WebSocket(WS_ENDPOINT);
    
    ws.onopen = () => {
        console.log('Connected');
        sendOrder(ws, order);
    };

    ws.onmessage = (event) => {
        const response = JSON.parse(event.data);
        console.log('Response:', response);
    };
}
```

### Python Example

```python
import json
import time
import websocket
from web3 import Web3
from eth_abi import encode

# Configuration
WS_ENDPOINT = 'wss://api.dmex.app/ws'
BASE_TOKEN = '0x...'  # USDC or other margin token address

def create_order(
    private_key: str,
    asset: str,
    amount: str,
    price: str,
    side: bool,
    leverage: str,
    closing_order: bool = False,
    stop: bool = False,
    stop_price: str = '0',
    is_market: bool = False,
    post_only: bool = False,
    replace_hash: str = ''
):
    w3 = Web3()
    account = w3.eth.account.from_key(private_key)
    user_address = account.address

    # Convert to 1e8 precision
    amount_scaled = str(int(float(amount) * 1e8))
    price_scaled = str(int(float(price) * 1e8))
    stop_price_scaled = str(int(float(stop_price) * 1e8))

    # Generate unique nonce
    nonce = int(time.time() * 1000)

    # Create order hash
    encoded = encode(
        ['string', 'address', 'address', 'uint256', 'uint256', 'bool', 'uint256', 'uint256'],
        [asset, BASE_TOKEN, user_address, int(amount_scaled), int(price_scaled), side, nonce, int(leverage)]
    )
    order_hash = Web3.keccak(encoded).hex()

    # Sign the hash
    signed = w3.eth.account.sign_message(
        encode_defunct(hexstr=order_hash),
        private_key=private_key
    )
    
    v = signed.v
    r = hex(signed.r)
    s = hex(signed.s)

    # Format replace_hash
    formatted_replace_hash = (
        '0x0000000000000000000000000000000000000000000000000000000000000000'
        if replace_hash == '' else replace_hash
    )

    # Build order payload
    order = {
        'hash': order_hash,
        'user_address': user_address,
        'base_token': BASE_TOKEN,
        'asset': asset,
        'amount': amount_scaled,
        'price': price_scaled,
        'side': side,
        'nonce': nonce,
        'leverage': leverage,
        'closing_order': closing_order,
        'v': v,
        'r': r,
        's': s,
        'remaining_amount': amount_scaled,
        'closed': False,
        'stop': stop,
        'stop_price': stop_price_scaled,
        'stopped': False,
        'is_market': is_market,
        'replace_hash': formatted_replace_hash,
        'post_only': post_only
    }

    return order


def send_order(ws, order):
    message = json.dumps({
        'op': 'create_order',
        'data': order
    })
    ws.send(message)


# Usage Example
if __name__ == '__main__':
    from eth_account.messages import encode_defunct
    
    private_key = '0x...'  # Your private key
    
    # Create a limit buy order for 0.1 BTC at $50,000 with 10x leverage
    order = create_order(
        private_key=private_key,
        asset='BTC',
        amount='0.1',
        price='50000',
        side=True,  # True = buy/long
        leverage='10',
        closing_order=False,
        is_market=False,
        post_only=False
    )

    # Connect and send
    ws = websocket.create_connection(WS_ENDPOINT)
    send_order(ws, order)
    
    response = ws.recv()
    print('Response:', response)
    ws.close()
```

### Order Hash Structure

The order hash is generated using `keccak256` with ABI-encoded parameters:

```
keccak256(abi.encode(
    asset,        // string  - Trading pair symbol
    base_token,   // address - Margin token contract
    user_address, // address - Your wallet address
    amount,       // uint256 - Order size * 1e8
    price,        // uint256 - Order price * 1e8
    side,         // bool    - true=buy, false=sell
    nonce,        // uint256 - Unique timestamp
    leverage      // uint256 - Leverage multiplier
))
```

### Order Types

#### Limit Order

```typescript
{
    is_market: false,
    stop: false,
    post_only: false  // or true for maker-only
}
```

#### Market Order

```typescript
{
    is_market: true,
    stop: false
}
```

#### Stop-Limit Order

```typescript
{
    is_market: false,
    stop: true,
    stop_price: '49000'  // Trigger price
}
```

#### Stop-Market Order

```typescript
{
    is_market: true,
    stop: true,
    stop_price: '49000'
}
```

### Closing Positions

To close an existing position, set `closing_order: true`. The `side` should be opposite to your current position:

* To close a long position: `side: false` (sell)
* To close a short position: `side: true` (buy)

### Replacing Orders

To replace an existing order, pass the hash of the order you want to cancel in `replace_hash`. This atomically cancels the old order and creates the new one.

### Error Handling

Common validation errors:

* **Amount must be greater than zero**
* **Invalid signature** - Ensure the hash is signed correctly
* **Insufficient margin** - Not enough balance for the order
* **Invalid leverage** - Leverage outside allowed range for the asset

### WebSocket Response

Successful order creation returns:

```json
{
    "op": "order_created",
    "data": {
        "hash": "0x...",
        "status": "open"
    }
}
```


# Cancel Order

## Cancel Order API

Cancel an existing open order by signing its hash.

### Overview

Order cancellation requires:

1. The hash of the order you want to cancel
2. Signing the order hash with your private key
3. Sending the signed cancellation via WebSocket

### Cancel Request Parameters

| Parameter    | Type   | Description                     |
| ------------ | ------ | ------------------------------- |
| `order_hash` | string | The hash of the order to cancel |
| `v`          | number | Signature recovery parameter    |
| `r`          | string | Signature r component           |
| `s`          | string | Signature s component           |

### JavaScript/TypeScript Example

```typescript
import Web3 from 'web3';

async function cancelOrder(privateKey: string, orderHash: string) {
    const web3 = new Web3();
    
    // Sign the order hash
    const signedData = web3.eth.accounts.sign(orderHash, privateKey);
    const signature = signedData.signature;

    // Parse signature into v, r, s
    const sig = signature.slice(2);
    const r = `0x${sig.slice(0, 64)}`;
    const s = `0x${sig.slice(64, 128)}`;
    let v = parseInt(`0x${sig.slice(128, 130)}`, 16);
    if (v < 27) v += 27;

    return {
        order_hash: orderHash,
        v: v,
        r: r,
        s: s
    };
}

// Send cancel request via WebSocket
function sendCancelOrder(ws: WebSocket, cancelRequest: object) {
    const message = JSON.stringify({
        op: 'cancel_order',
        data: cancelRequest
    });
    ws.send(message);
}

// Usage Example
async function main() {
    const privateKey = '0x...'; // Your private key
    const orderHash = '0x...';  // Hash of order to cancel
    
    const cancelRequest = await cancelOrder(privateKey, orderHash);

    const ws = new WebSocket('wss://api.dmex.app/ws');
    
    ws.onopen = () => {
        sendCancelOrder(ws, cancelRequest);
    };

    ws.onmessage = (event) => {
        const response = JSON.parse(event.data);
        console.log('Response:', response);
    };
}
```

### Python Example

```python
import json
import websocket
from web3 import Web3
from eth_account.messages import encode_defunct

def cancel_order(private_key: str, order_hash: str):
    w3 = Web3()
    
    # Sign the order hash
    signed = w3.eth.account.sign_message(
        encode_defunct(hexstr=order_hash),
        private_key=private_key
    )
    
    return {
        'order_hash': order_hash,
        'v': signed.v,
        'r': hex(signed.r),
        's': hex(signed.s)
    }


def send_cancel_order(ws, cancel_request):
    message = json.dumps({
        'op': 'cancel_order',
        'data': cancel_request
    })
    ws.send(message)


# Usage Example
if __name__ == '__main__':
    private_key = '0x...'  # Your private key
    order_hash = '0x...'   # Hash of order to cancel
    
    cancel_request = cancel_order(private_key, order_hash)

    ws = websocket.create_connection('wss://api.dmex.app/ws')
    send_cancel_order(ws, cancel_request)
    
    response = ws.recv()
    print('Response:', response)
    ws.close()
```

### Notes

* You can only cancel orders that you created (signature must match the original order creator)
* The order must still be open (not fully filled or already cancelled)
* To cancel and replace an order atomically, use the `replace_hash` parameter when creating a new order instead


# Chart KLines

## Chart WebSocket API

Real-time kline (candlestick) data streaming via WebSocket.

### Connection

```
ws://back.dmex.app/ws/chart
```

### Message Format

All messages use JSON with the following structure:

```json
{
  "type": "message_type",
  "data": { ... }
}
```

### Client → Server Messages

#### Subscribe to Kline Stream

Subscribe to real-time candlestick updates for a symbol/interval pair.

```json
{
  "type": "subscribeKlineStream",
  "data": {
    "symbol": "BTCUSDT",
    "interval": "1m"
  }
}
```

**Parameters:**

* `symbol` - Trading pair (e.g., `BTCUSDT`, `ETHUSDT`)
* `interval` - Candle interval (e.g., `1m`, `5m`, `15m`, `1h`, `4h`, `1d`)

#### Unsubscribe from Kline Stream

```json
{
  "type": "unsubscribeKlineStream",
  "data": {
    "symbol": "BTCUSDT",
    "interval": "1m"
  }
}
```

#### Ping

Keep connection alive with application-level ping.

```json
{
  "type": "ping",
  "data": null
}
```

### Server → Client Messages

#### Subscription Confirmed

Sent after successful subscription.

```json
{
  "type": "subscriptionConfirmed",
  "data": {
    "symbol": "BTCUSDT",
    "interval": "1m"
  }
}
```

#### Kline Stream Update

Real-time candle data pushed to subscribed clients.

```json
{
  "type": "klineStreamUpdate",
  "data": {
    "stream": "btcusdt_1m",
    "data": {
      "k": {
        "t": 1704067200000,
        "o": "42000.00",
        "h": "42150.00",
        "l": "41950.00",
        "c": "42100.00",
        "v": "125.5",
        "x": false
      }
    }
  }
}
```

**Candle fields (`k`):**

| Field | Description                |
| ----- | -------------------------- |
| `t`   | Candle open time (Unix ms) |
| `o`   | Open price                 |
| `h`   | High price                 |
| `l`   | Low price                  |
| `c`   | Close price                |
| `v`   | Volume                     |
| `x`   | Is candle closed           |

#### Pong

Response to client ping.

```json
{
  "type": "pong",
  "data": null
}
```

### Example Usage (JavaScript)

```javascript
const ws = new WebSocket('ws://back.dmex.app/ws/chart');

ws.onopen = () => {
  // Subscribe to BTC 1-minute candles
  ws.send(JSON.stringify({
    type: 'subscribeKlineStream',
    data: { symbol: 'BTCUSDT', interval: '1m' }
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  
  switch (msg.type) {
    case 'subscriptionConfirmed':
      console.log('Subscribed to:', msg.data.symbol, msg.data.interval);
      break;
    case 'klineStreamUpdate':
      const candle = msg.data.data.k;
      console.log('Candle update:', candle);
      break;
    case 'pong':
      console.log('Pong received');
      break;
  }
};

// Keep-alive ping every 30 seconds
setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'ping', data: null }));
  }
}, 30000);
```

### Connection Management

* **Ping/Pong**: Server sends WebSocket ping frames every 54 seconds
* **Read timeout**: 60 seconds (reset on pong)
* **Connection cleanup**: Stale connections removed after 120 seconds of inactivity
* **Throttling**: Updates are throttled to max 1 broadcast per 300ms per symbol to prevent flooding

### Multiple Subscriptions

You can subscribe to multiple symbol/interval pairs on a single connection:

```javascript
// Subscribe to multiple streams
ws.send(JSON.stringify({ type: 'subscribeKlineStream', data: { symbol: 'BTCUSDT', interval: '1m' } }));
ws.send(JSON.stringify({ type: 'subscribeKlineStream', data: { symbol: 'BTCUSDT', interval: '5m' } }));
ws.send(JSON.stringify({ type: 'subscribeKlineStream', data: { symbol: 'ETHUSDT', interval: '1m' } }));
```

### Notes

* Symbol names are case-insensitive (internally converted to lowercase)
* Subscription keys are formatted as `{symbol}_{interval}` (e.g., `btcusdt_1m`)
* The `stream` field in updates matches this subscription key format


# Trading Fees

<table data-header-hidden><thead><tr><th valign="top"></th><th valign="top"></th><th valign="top"></th><th valign="top"></th></tr></thead><tbody><tr><td valign="top"><strong>Tier</strong></td><td valign="top"><strong>Volume</strong></td><td valign="top">Taker</td><td valign="top">Maker</td></tr><tr><td valign="top">0</td><td valign="top">&#x3C;5,000,000</td><td valign="top">0.025%</td><td valign="top">0.012%</td></tr><tr><td valign="top">1</td><td valign="top">>5,000,000</td><td valign="top">0.020%</td><td valign="top">0.010%</td></tr><tr><td valign="top">2</td><td valign="top">>25,000,000</td><td valign="top">0.015%</td><td valign="top">0.005%</td></tr><tr><td valign="top">3</td><td valign="top">>100,000,000</td><td valign="top">0.010%</td><td valign="top">0.000%</td></tr><tr><td valign="top">4</td><td valign="top">>500,000,000</td><td valign="top">0.005%</td><td valign="top">0.000%</td></tr><tr><td valign="top">5</td><td valign="top">>1,000,000,000</td><td valign="top">0.0025%</td><td valign="top">0.000%</td></tr></tbody></table>

\* The maker is the trader that adds order to the order book. When you create a limit order, and it is not instantly executed - you are the maker.

\*\* The taker is the person that takes an order from the order book. When placing a MARKET order or a LIMIT order that executes instantly - you are the taker.

\*\*\* Fee tires are recalculated every hour based on 30 day traded volume.


# Maintenance Margins

| Symbol | Maintenance Margin |
| ------ | ------------------ |
| BTC    | 0.15               |
| ETH    | 0.15               |
| LTC    | 0.3                |
| BCH    | 0.3                |
| ADA    | 0.4                |
| LINK   | 0.4                |
| DOGE   | 0.3                |
| XRP    | 0.3                |
| AVAX   | 0.4                |
| POL    | 0.4                |
| XLM    | 0.4                |
| SOL    | 0.3                |
| UNI    | 0.4                |
| WIF    | 0.4                |
| TON    | 0.4                |
| JUP    | 0.4                |
| TRX    | 0.4                |
| XMR    | 0.4                |
| BNB    | 0.4                |
| SUI    | 0.5                |
| HBAR   | 0.5                |
| CELO   | 0.5                |
| DOT    | 0.5                |
| ONDO   | 0.5                |
| TAO    | 0.5                |
| WLD    | 0.5                |
| NEAR   | 0.5                |
| AAVE   | 0.5                |
| ETC    | 0.5                |
| APT    | 0.5                |
| VET    | 0.5                |
| FIL    | 0.5                |
| ALGO   | 0.5                |
| ENA    | 0.5                |
| FET    | 0.5                |
| CRV    | 0.5                |
| ARB    | 0.5                |
| ATOM   | 0.5                |


# Deposits & Withdrawals

#### ETH/DAI

* Deposit: free
* Withdrawal: gas fee\*&#x20;
* *Minimum Deposit/Withdrawal: no limits*

#### BTC

* Deposit: 0.1% (pBTC fee)
* Withdrawal: gas fee\* + 0.25% (pBTC fee)&#x20;
* Minimum deposit/withdrawal amount is 0.0015 BTC (pBTC)

{% hint style="info" %}
DMEX is not earning on deposit/withdrawal fees
{% endhint %}

\* The gas fee is the fee paid to the miners to record a transaction on the blockchain (also known as *transaction fee*).


# Market

Market Order executes instantly against the best available price in the order book

DMEX is the only margin DEX that allows market orders. In effect, the market order is a Limit Order with a price slightly lower/higher than the best available price in the order book. So the Market Order is just a faster way to create a limit order with the price basically pre-filled.

{% hint style="info" %}
When creating a MARKET order, the DMEX app will create a LIMIT order with the price +/- 1% from the best available price in the order book.
{% endhint %}

{% hint style="danger" %}
MARKET orders will execute instantly and will always pay the taker fee.&#x20;
{% endhint %}

{% hint style="warning" %}
In rare cases, when a violent price move is happening the MARKET order will not execute, and instead will appear as a LIMIT order in the order list. That can happen when the price moves more than 1% while the order is being confirmed. In this case users have the option of cancelling the order and creating a new one, or waiting for the order to execute as a LIMIT order (in that case the user will only pay the maker fee).
{% endhint %}


# Limit

Limit Order is added to the order book and executes when it matches another order.

The LIMIT order requires a price and amount to be selected. If the selected price is better than the price in the order book, the LIMIT order will behave like the MARKET order and execute instantly. Otherwise the order will be added to the order book and will wait until it is matched against another order.

{% hint style="info" %}
If the LIMIT order is created with a price worse than the best available price in the order book, it will execute instantly and the user will pay the taker fee. Otherwise the user will pay the maker fee.
{% endhint %}


# Stop-Limit

Stop Limit is an advanced order type. It is a limit order with an additional trigger (stop) price. This order is hidden from the order book until the market price passes the trigger (stop) price in the order.<br>

{% hint style="success" %}
Use this order type to prevent your position from getting liquidated.
{% endhint %}

{% hint style="danger" %}
DISCLAIMER: The STOP-LIMIT order is stored and triggered from the DMEX server. Opening a STOP-LIMIT order implies trusting that DMEX will trigger the order as expected.
{% endhint %}

{% hint style="info" %}
STOP-LIMIT orders are triggered by the price on DMEX, not the mark price.
{% endhint %}


# Expiration Term

On DMEX each trade is an electronic agreement between two parties, one taking one side of the trade and the other party taking the other side.&#x20;

On DMEX everyone is not trading the same futures contract, the futures contract is unique for each order and can have a predefined term. When creating an order, the user generates a new electronic agreement that can have any expiration term, therefore when opening a position with a 90D expiration term, it will expire in 90 days from order creation (not on quarterly basis).

The expiration term is the number of blocks before the position will be settled using the price from the Oracle.

$$
ExpirationBlock = Current Block + ExpirationSeconds/14
$$

The chosen expiration term is converted to seconds.The seconds are then divided by 14 (the current rate of block generation is 1 block each 14 seconds) and added to the latest block number. This gives us the block number when the position will expire.

{% hint style="info" %}
The actual expiration time may vary since the rate of new blocks can vary in time. However the actual expiration time will be reasonably close to the predicted expiration time.
{% endhint %}


# Leverage

Leverage represents the ratio by which you can increase your purchasing power beyond the initial margin (collateral). A 3x leverage means that you can buy three times more than your collateral. If you put in $100 as collateral, you can purchase $300 worth of futures contracts. With 50x leverage, the maximum purchase value would be $5,000 based on $100 collateral.

{% hint style="danger" %}
Exercise caution when choosing your leverage level. Higher leverage increases the risk of liquidation. Trading with leverage carries significant risks. DMEX is not liable for any losses incurred due to poor trading decisions.
{% endhint %}


# Cross Margin

Cross Margin positions use the full balance as margin and allow the trader to increase the size of the position on the fly allowing for dollar cost averaging. When multiple position openned, the PnL from each position will be counted towards the margin (collateral) of the other cross margin positions (on the same margin currency)

{% hint style="info" %}
When a user has multiple Cross-Margin positions opens and one position reaches its liquidation price, all cross margin positions for the collateral are liquidated (market closed). This is done in order to protect hedged positions so there is no scenario in which one leg of the hedge is liquidated and the other stays open.
{% endhint %}


# Mark Price

Mark Price is the price on the price source. All assets traded on DMEX have a price source defined. For the top assets like Bitcoin and Ethereum, the price source is Bitstamp.net. Therefore in this cases the MARK PRICE is the Bitstamp price.

The MARK PRICE is used to settle and liquidate positions.

{% hint style="success" %}
Positions can only be liquidated if the MARK PRICE reaches the liquidation price. DMEX cannot manipulate the price internally to liquidate your position!
{% endhint %}


# Asset

The Asset in the DMEX smart contract is a fundamental object that defines the asset being traded in the futures contract. \
\
The Asset comprises of the following information:

| Parameter | Type    | Value                                                                                                           |
| --------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| baseToken | address | the token used for margin (0x000... in the ETH case)                                                            |
| priceUrl  | string  | the url where the Oracle will take the settlement price from                                                    |
| pricePath | string  | the JSON parameter inside the priceUrl that represent the last traded price                                     |
| disabled  | bool    | if true, the asset cannot be used in contract creation (when priceUrl no longer valid or decimals have changed) |
| decimals  | uint256 | number of decimals in the price                                                                                 |

Every Asset has a unique hash. That unique hash is used in the “Asset” parameter when creating a new Futures Contract. There can be no two assets with different parameters but the same hash because all parameters are part of the hash, therefore a change in parameters would result in a new unique asset hash.

```javascript
bytes32 futuresAssetHash = keccak256(
    this, 
    baseToken, 
    priceUrl, 
    pricePath, 
    decimals
);
```


# Futures Contract

On [DMEX](https://dmex.app/?utm_source=medium\&utm_medium=story\&utm_campaign=part1), users trade futures contracts. Futures contracts are defined by the following parameters:

| Parameter         | Type    | Description                                                                                                                                                                |
| ----------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| asset             | bytes32 | the hash of the underlying [asset object](/definitions/asset-definitions)                                                                                                  |
| expirationBlock   | uint256 | futures contract expiration block                                                                                                                                          |
| closingPrice      | uint256 | the closing price for the futures contract                                                                                                                                 |
| closed            | bool    | is the futures contract closed? (0 - false, 1 - true)                                                                                                                      |
| broken            | bool    | if someone has forced release of funds after no settlement for two hours, the contract is marked as broken and can no longer close positions, all collaterals are released |
| multiplier        | uint256 | the multiplier price (usually 1/ETHUSD x 1e8)                                                                                                                              |
| fundingRate       | uint256 | funding rate expressed per block \* 1e18                                                                                                                                   |
| closingBlock      | uint256 | the block in which the contract was closed (0 while contract open)                                                                                                         |
| perpetual         | bool    | true if the contract is perpetual                                                                                                                                          |
| maintenanceMargin | uint256 | the maintenance margin coefficient                                                                                                                                         |

The Futures Contract has a unique hash derived from its parameters. There can be no two futures contracts with the same hash and different parameters as all parameters are included in the hash. A change in any parameter will result in a new futures contract hash.

```javascript
bytes32 futuresContractHash = keccak256(
    this, 
    asset, 
    expirationBlock, 
    multiplier, 
    fundingRate, 
    perpetual, 
    maintenanceMargin
);
```

When a user places an order, the order is placed to trade a specific futures contract and the futures contract hash is embedded in the user’s signature. This way the user can be sure that he/she is trading the correct asset/futures contract.


# Position

The position object is the one that holds the information about a position and is crucial in managing reserved funds and profit/loss calculations.

Depending on the parameters of the order (leverage, expiration date) the appropriate futures contract hash is generated by the DMEX Web Application and sent for matching to the DMEX server.

The matching is performed as is usually done on an exchange, buy orders and sell orders are matched against one another and if the price condition matches, a new trade is created. The trade is then sent to the Smart Contract and a position is opened.

A position contains the following parameters:

| Parameter  | Type   | Description                                                      |
| ---------- | ------ | ---------------------------------------------------------------- |
| size       | uint64 | the size of the position in terms of the underlying asset (x1e8) |
| price      | uint64 | the average entry price                                          |
| side       | uint16 | 0 or 1 (1 - long, 0 - short)                                     |
| entryBlock | uint48 | the average entry block for the position                         |
| collateral | uint64 | the amount of collateral (margin) reserved for the position      |

Each position has its unique hash comprised from the user address, futures contract hash and side.

```javascript
function generatePositionHash (address user, bytes32 futuresContractHash, bool side) public view returns (bytes32)
{
    return keccak256(this, user, futuresContractHash, side);
}
```


# TradingView

DMEX uses TradingView technology to display data on charts. TradingView offers a state-of-the-art charting platform and tools for a global community of traders and investors: you can track[ detailed symbol charts](https://www.tradingview.com/symbols/ETHUSD/), look for opportunities in the [live stock screener](https://www.tradingview.com/screener/), check global events and discuss them with fellow traders to always stay on top of where the markets are moving.


# Liquidation Price

The price when the position is liquidated. When a position is liquidated it is automatically market closed and the taker fee is applied.

The liquidation price for a position is calculated based on the entry price and amount of collateral provided. The higher the leverage, the lower the collateral amount, therefore the higher the risk of liquidation.

{% hint style="warning" %}
To prevent your position from getting liquidated ALWAYS USE STOP LOSS orders.
{% endhint %}

Positions can only be liquidated using the Mark Price (the price from the price source).&#x20;

When a position is liquidated, the collateral for the position is not collected, only the taker fee.

### Liquidation Price Formula

$$
LP = NLP ± P \* C
$$

#### Definitions

| LP  | Liquidation Price                                                |
| --- | ---------------------------------------------------------------- |
| NLP | Net Liquidation Price                                            |
| P   | Entry Price                                                      |
| C   | Margin Call Coefficient                                          |
| M   | Margin (Collateral)                                              |
| MOV | Allowed price movement before margin call                        |
| FC  | Funding Cost                                                     |
| S   | Position Size                                                    |
| FB  | Funding Blocks (the number of blocks the position is opened for) |
| FR  | Funding Rate (rate per block)                                    |
| L   | Leverage                                                         |
| MM  | Maintenance Margin                                               |

#### Formulas

| Parameter | Formula            |
| --------- | ------------------ |
| NL        | P ± MOV            |
| MOV       | (M - FC) / S       |
| FC        | S \* P \* FB \* FR |
| C         | MM / L             |
| L         | P \* S / M         |

{% hint style="success" %}
Use Stop-Limit (Stop-Loss) orders to prevent the position from getting liquidated!
{% endhint %}


# Maintenance Margin

This values is used in Margin Call Price calculations

Maintenance Margin Coefficient depends on the asset and leverage traded. The higher the leverage the higher the MM coefficient. This is necessary in order to mitigate the risk of slippage when margin calling a position during a violent price move.

Check the Asset page for the specific values.

{% hint style="info" %}
This value affects only in the margin call price. Make sure to check the estimated margin call price in the order confirmation popup before signing the order.
{% endhint %}


# Risk Limit

The Risk Limit defines how many total open positions a user can have.&#x20;

| Risk Level | Max Open Interest (USD) | MM Multiplier |
| ---------- | ----------------------: | ------------: |
| 1          |                 500 000 |          1.00 |
| 2          |               1 000 000 |          1.05 |
| 3          |               2 500 000 |          1.10 |
| 4          |               5 000 000 |          1.15 |
| 5          |              10 000 000 |          1.20 |
| 6          |              50 000 000 |          1.25 |

MM Multiplier stands for ***Maintenance Margin Multiplier**,* with higher risk levels the MM Multiplier is higher. The MM Multiplier multiplies the Maintenance Margin Coefficient and affects the liquidation price. Read about Maintenance Margin [here](/formulas/maintenance-margin-coefficient).


# Global MM Multiplier

The Global MM Multiplier works the same as the risk-specific MM Multiplier (read more [here](/formulas/risk-limit)) but is set globally and affects all users regardless of the selected risk limit.

```
Final MM Multiplier = Asset_MMC * User_MM_Multiplier * Global_MM_Multiplier
```

Global MM Multiplier, normally at 1.00 (which means it doesn't affect any change) can be increased during times of extreme price volatility in order to reduce the risk to the liquidity pool. The real-time Global MM Multiplier can be viewed in the bottom left corner of the DMEX interface.


# Funding Cost

Funding cost is charged every hour.\
If the funding rate is positive, longs pay shorts. If the funding rate is negative, shorts pay longs.\
When funding is deducted, it is subtracted from the position margin/collateral and balance.\
When funding is added, it is credited to the position margin/collateral and balance.


# USD Conversion

All prices on DMEX are in US Dollars. However, the profits are paid in the collateral currency chosen by the user. Therefore the profits made in USD must be converted to the collateral currency when a position is settled.

To make this work properly, the conversion rate between USD and the collateral currency (eg. ETH/USD) is set up during the order creation.

For example, if you want to open a position using ETH as collateral currency, inside the **Futures Contract** the *multiplier* parameter will be set:&#x20;

$$
Multiplier = 1/ETHUSD \* 100 000 000
$$

When closing the position, the profits made in USD will be converted to ETH by multiplying the profit with the *multiplier*.

Let's say that ETH was worth 125$ when you opened the position. This means that the *multiplier* = 1/125\*100 000 000 = 800 000. If for example you make a 100$ profit on this position, you will be credited 100$ \* 800 000 / 100 000 000 = 0.8 ETH.

{% hint style="warning" %}
The ETH/USD exchange rate remains fixed for the duration of the position. Therefore if the price of ETH fluctuates your profits might vary slightly due to the price volatility of ETH.\
\
If you want to protect from this volatility use a USD pegged stablecoin like DAI as collateral. Because the stablecoin will always equal to 1 USD, there is no volatility risk.
{% endhint %}

{% hint style="info" %}
We use the 100000000 (or 1e8) in the formula because of the particularities of Ethereum smart contract design. Ethereum smart contracts don't support floating numbers, so all formulas are multiplied by a standard number (1e8 or 1e18) before performing divisions. Otherwise the division that results in a fraction would be truncated to the integer value by the Ethereum Virtual Machine.
{% endhint %}


# Overview

This section describes the procedures necessary to perform in order to retrieve your funds in case the DMEX website goes down or is not functioning properly.

{% hint style="warning" %}
Print out or save a PDF copy of the articles in this section so you have the instructions in case the DMEX domain is compromised and you can no longer access this DOCS page
{% endhint %}

All funds, transactions and positions are recorded on the blockchain. The DMEX smart contracts were built with safety in mind, therefore we have implemented several functions that would allow the user to retrieve his/her funds in case of emergency.

Safety of user funds is the cornerstone of the DMEX product, therefore everyone must have full control of their funds whether the website is working or not.


# Withdrawing funds

{% hint style="danger" %}
Only use this method if the DMEX website is down or not functioning properly. Otherwise withdraw your funds through the website.
{% endhint %}

Any user can withdraw his/her funds from the contract at any time, even if the DMEX website is down. To do that the user must follow the following steps:

1. Navigate to the contract explorer: [**https://blockscout.com/poa/xdai/address/0xd840f57b84Eb281fb045FC271c07d37C3cf4E206/read-contract**](https://blockscout.com/poa/xdai/address/0xd840f57b84Eb281fb045FC271c07d37C3cf4E206/read-contract)
2. Go to item number 5 (availableBalanceOf)
3. Enter your wallet address and the token:\
   ETH: **0x0000000000000000000000000000000000000000**\
   BTC: **0x5228a22e72ccC52d415EcFd199F99D0665E7733b**\
   DAI: **0x6B175474E89094C44Da98b954EedeAC495271d0F**
4. Press "Query" to get your available balance and save the amount
5. Navigate to the "Write Contract" tab:\
   [**https://blockscout.com/poa/xdai/address/0xd840f57b84Eb281fb045FC271c07d37C3cf4E206/write-contract**](https://blockscout.com/poa/xdai/address/0xd840f57b84Eb281fb045FC271c07d37C3cf4E206/write-contract)
6. Go to item 27 "withdraw"
7. Enter the token and amount (saved in step 4)
8. Press "Write". Make sure you have MetaMask unlocked with your wallet imported
9. Confirm the transaction in MetaMask and get the transaction hash
10. Navigate to the AMMB Bridge:\
    [**https://alm-xdai.herokuapp.com/**](https://alm-xdai.herokuapp.com/)
11. Paste in the transaction hash from MetaMask
12. Once your transaction is loaded, press "Execute Manually" and confirm in MetaMask.
13. Once the transaction is confirmed you will have the funds in your wallet.


# Force Release Collateral

This is an escape hatch that allows the user to release reserves from an open position in case the futures contract was not settled properly after expiration. We will automatically release the funds for the user if no settlement happens, therefore this method should only be used if DMEX website or backend servers are not working properly.

{% hint style="danger" %}
Only use this function if the DMEX website is down or not functioning properly. Otherwise withdraw your funds through the website.
{% endhint %}

{% hint style="info" %}
You can force release reserves only on futures contracts that have expired and were not settled within 500 blocks (approx. 2 hours)
{% endhint %}

1. Find the DMEX Trading contract  ([click here for instructions](/contracts/finding-the-trading-contract))
2. Open the Trading Contract on Etherscan
3. Go to the **Contract** Tab
4. Go to the **Write Contract** Tab
5. Click on **Connect to Web3** (you will need to have your wallet imported in MetaMask)
6. Scroll down to the ***forceReleaseReserve*** function
7. Enter the **futures contract hash** in the first field
8. Enter the position side in the second field (0 - short, 1 - long)
9. Enter your wallet address in the third field
10. Press **Write** and confirm the transaction in MetaMask&#x20;
11. Wait for the transaction to confirm on the blockchain and you will see the reserved balance become available.

If the DMEX website is down or not functioning properly use [this method](/contracts/withdrawing-funds) to withdraw your funds manually.


# Finding the Base Contract

{% hint style="danger" %}
This guide is necessary only if the DMEX website is unaccessible or not functioning properly. If the website is operational you can find the smart contract address in Menu > Smart Contracts
{% endhint %}

1. Go to [blockscout.com](https://blockscout.com/xdai/mainnet/)
2. Put in your wallet address into the search box
3. In the transaction list find the deposit transaction to the DMEX contract (you will find it easier if you remember the approximate date of your last deposit)
4. Click on the transaction and you will see the contract address in the "To" field.

![](https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxKuth_62wVofkWGRcV%2F-LxL3G1442LhsCrPbxcd%2FScreen%20Shot%202019-12-30%20at%2011.07.49%20AM.png?alt=media\&token=d5699588-f414-412c-9851-5c46196d5e8a)


# Finding the Trading Contract

{% hint style="danger" %}
This guide is necessary only if the DMEX website is unaccessible or not functioning properly. If the website is operational you can find the smart contract address in Menu > Smart Contracts
{% endhint %}

1. Find the DMEX Base Contract ([click here for instructions](/contracts/finding-the-base-contract))
2. Go to the Base Contract on Etherscan and  click the "Contract" tab
3. Select "Read Contract"
4. Scroll down until you find the **firstFuturesContract** variable, this is the Trading Contract address

![](https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxKuth_62wVofkWGRcV%2F-LxL6kv1uDhfaob3dg0P%2FScreen%20Shot%202019-12-30%20at%2011.24.03%20AM.png?alt=media\&token=0c1c3f63-6e18-4aea-9faa-246c8ea73d9c)


# Overview

In this section we give detailed information about each asset traded on DMEX. Below you will find some definitions in order to understand the information better.

The main parameters in an asset are the **Price URL** and the **Price Path**.

When trading BTC (Bitcoin) the [MARK PRICE](/definitions/mark-price) is taken from the Price URL <https://www.bitstamp.net/api/v2/ticker/btcusd/> which returns a JSON string with the latest ticker information for Bitcoin on Bitstamp.

The response looks as follows:

```javascript
{
    "high": "7495.00", 
    "last": "7425.29", // this is the last traded price on Bitstamp
    "timestamp": "1578223348", 
    "bid": "7425.29", 
    "vwap": "7358.33", 
    "volume": "3386.74324367", 
    "low": "7256.03", 
    "ask": "7429.67", 
    "open": "7356.05"
}
```

The last traded price on Bitstamp is represented by the ***last*** JSON parameter. Therefore when the Oracle is requested to provide the MARK PRICE for Bitcoin, it will request the JSON from the **Price URL** and take the value under the "last" parameter (**Price Path**).

Since assets can have different numbers of decimals in the price, the asset also specifies the ***decimals*** value. In this case **2**.


# BTC - Bitcoin

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGbaZBDzp5imyHQMBN%2F-LxGbgljT6-R65X5boRh%2F1.png?alt=media&amp;token=3aec789e-a2dd-4ac8-b4b1-46f84b4e7e0a" alt=""></div>

Bitcoin is a cryptocurrency. It is a decentralized digital currency without a central bank or single administrator that can be sent from user to user on the peer-to-peer bitcoin network without the need for intermediaries.

| Parameter        | Value                                            |
| ---------------- | ------------------------------------------------ |
| Underlying Asset | Bitcoin                                          |
| Project Website  | <https://bitcoin.org/>                           |
| Asset symbol     | BTC                                              |
| Price Source     | Bitstamp                                         |
| Price Url        | <https://www.bitstamp.net/api/v2/ticker/btcusd/> |
| Price Path       | last                                             |
| Max. Leverage    | 100x                                             |

#### Maintenance Margin Coefficients

| Leverage    | Maintenance Margin Coefficient |
| ----------- | ------------------------------ |
| 100x        | 0.45                           |
| 50x         | 0.4                            |
| 25x         | 0.35                           |
| 10x or less | 0.3                            |


# ETH - Ethereum

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGbuow3WZ2_WEMARsZ%2F-LxGc1llDrzbsT-AQr-v%2F1027.png?alt=media&amp;token=9c6f95df-809e-422b-9fe8-6081f8149f27" alt=""></div>

Ethereum is an open source, public, blockchain-based distributed computing platform and operating system featuring smart contract functionality. It supports a modified version of Nakamoto consensus via transaction-based state transitions.

| Parameter                                                   | Value                                            |
| ----------------------------------------------------------- | ------------------------------------------------ |
| Underlying Asset                                            | Ethereum                                         |
| Project Website                                             | <https://ethereum.org/>                          |
| Asset symbol                                                | ETH                                              |
| Price Source                                                | Bitstamp                                         |
| [Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/) | <https://www.bitstamp.net/api/v2/ticker/ethusd/> |
| Price Path                                                  | last                                             |
| Max. Leverage                                               | 50x                                              |

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |


# LTC - Litecoin

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGcMyiPP1XfM8lrieE%2F-LxGcWF2yuiyU3Csmd8g%2F2.png?alt=media&amp;token=6548ff2e-4636-4417-94fe-9d57d7768eb1" alt=""></div>

Litecoin is a peer-to-peer cryptocurrency and open-source software project released under the MIT/X11 license. Creation and transfer of coins is based on an open source cryptographic protocol and is not managed by any central authority. Litecoin was an early bitcoin spinoff or altcoin, starting in October 2011.

| Parameter                                                     | Value                                            |
| ------------------------------------------------------------- | ------------------------------------------------ |
| Underlying Asset                                              | Litecoin                                         |
| Project Website                                               | <https://litecoin.org/>                          |
| Asset symbol                                                  | LTC                                              |
| Price Source                                                  | Bitstamp                                         |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://www.bitstamp.net/api/v2/ticker/ltcusd/> |
| Price Path                                                    | last                                             |
| Max. Leverage                                                 | 50x                                              |

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |

####


# BCH - Bitcoin Cash

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGcp3fxQOAI1W6o7J-%2F-LxGcwKIP194syYnoR-F%2F1831.png?alt=media&amp;token=e07b700a-99d0-40f4-a140-b30e8764c26c" alt=""></div>

Bitcoin Cash is a cryptocurrency that is a fork of Bitcoin. Bitcoin Cash is a spin-off or altcoin that was created in 2017. In 2018 Bitcoin Cash subsequently split into two cryptocurrencies: Bitcoin Cash, and Bitcoin SV. Bitcoin Cash is sometimes also referred to as Bcash.

| Parameter                                                     | Value                                            |
| ------------------------------------------------------------- | ------------------------------------------------ |
| Underlying Asset                                              | Bitcoin Cash                                     |
| Project Website                                               | <https://www.bitcoincash.org/>                   |
| Asset symbol                                                  | BCH                                              |
| Price Source                                                  | Bitstamp                                         |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://www.bitstamp.net/api/v2/ticker/bchusd/> |
| Price Path                                                    | last                                             |
| Max. Leverage                                                 | 50x                                              |

####

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |

####


# ADA - Cardano

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGduVyG25or9FdjDIC%2F-LxGe0fHkIFCCzwVFfGo%2F2010.png?alt=media&amp;token=bf8a12a7-5c64-4a36-9211-6d3694fc8180" alt=""></div>

Cardano (ADA) is a decentralized platform that will allow complex programmable transfers of value in a secure and scalable fashion. It is reportedly the first blockchain platform to evolve out of a scientific philosophy and a research-first driven approach, and one of the first to be built in the Haskell programming language. Cardano is developing a smart contract platform which seeks to deliver more advanced features than any protocol previously developed. The development team consists of a large global collective of expert engineers and researchers. The protocol reportedly features a layered blockchain software stack that is flexible, scalable, and is being developed with the most rigorous academic and commercial software standards in the industry. Cardano will use a democratic governance system that allows the project to evolve over time, and fund itself sustainably through a treasury system.

| Parameter                                                     | Value                                                        |
| ------------------------------------------------------------- | ------------------------------------------------------------ |
| Underlying Asset                                              | Cardano                                                      |
| Project Website                                               | <https://www.cardano.org/>                                   |
| Asset symbol                                                  | ADA                                                          |
| Price Source                                                  | Binance                                                      |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://api.binance.com/api/v3/ticker/price?symbol=ADAUSDT> |
| Price Path                                                    | price                                                        |
| Max. Leverage                                                 | 50x                                                          |

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |


# XLM - Stellar

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGe6noU4hzLhk8qiM2%2F-LxGeG6hbZa9G4k7OXyj%2F512.png?alt=media&amp;token=33060d98-1b8c-4614-a365-83def715d372" alt=""></div>

The Stellar network is an open source, distributed, and community owned network used to facilitate cross-asset transfers of value. Stellar aims to help facilitate cross-asset transfer of value at a fraction of a penny while aiming to be an open financial system that gives people of all income levels access to low-cost financial services. Stellar can handle exchanges between fiat-based currencies and between cryptocurrencies. Stellar.org, the organization that supports Stellar, is centralized like XRP and meant to handle cross platform transactions and micro transactions like XRP. However, unlike Ripple, Stellar.org is non-profit and their platform itself is open source and decentralized. Through the use of its intermediary currency Lumens (XLM), a user can send any currency that they own to anyone else in a different currency.

| Parameter                                                     | Value                                                        |
| ------------------------------------------------------------- | ------------------------------------------------------------ |
| Underlying Asset                                              | Stellar                                                      |
| Project Website                                               | <https://www.stellar.org/>                                   |
| Asset symbol                                                  | XLM                                                          |
| Price Source                                                  | Binance                                                      |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://api.binance.com/api/v3/ticker/price?symbol=XLMUSDT> |
| Price Path                                                    | price                                                        |
| Max. Leverage                                                 | 50x                                                          |

####

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |


# XMR - Monero

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGeM6FD8mvCcdmcaho%2F-LxGeSWCLt4o1S1u8zJQ%2F328.png?alt=media&amp;token=838feda8-64af-4611-a290-80713e6a49a7" alt=""></div>

Monero (XMR) is a private, secure, and untraceable cryptocurrency that was launched April 18th, 2014. With Monero, it is said you are in complete control of your funds and privacy no one else can see anyone else's balances or transactions.

| Parameter                                                     | Value                                                        |
| ------------------------------------------------------------- | ------------------------------------------------------------ |
| Underlying Asset                                              | Monero                                                       |
| Project Website                                               | <https://web.getmonero.org/>                                 |
| Asset symbol                                                  | XMR                                                          |
| Price Source                                                  | Binance                                                      |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://api.binance.com/api/v3/ticker/price?symbol=XMRUSDT> |
| Price Path                                                    | price                                                        |
| Max. Leverage                                                 | 50x                                                          |

####

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |


# LINK - ChainLink

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGeYe7VyUsB3UST1Jf%2F-LxGeggQ9fNAftRrCY7h%2F1975.png?alt=media&amp;token=134c839a-d252-4f74-8969-e363b8834764" alt=""></div>

Chainlink (LINK) is a decentralized oracle service, which aims to connect smart contracts with data from the real world. Since blockchains cannot access data outside their network, oracles are needed to function as data feeds in smart contracts. Oracles provide external data (e.g. temperature, weather) that trigger smart contract executions upon the fulfillment of pre-defined conditions. Participants on the Chainlink network are incentivized (through rewards) to provide smart contracts with access to external data feeds. Should users desire access to off-chain data, they can submit a requesting contract to ChainLink’s network. These contracts will match the requesting contract with the appropriate oracles. The contracts include a reputation contract, an order-matching contract, and an aggregating contract. The aggregating contract gathers data of the selected oracles to find the most accurate result.

| Parameter                                                     | Value                                                         |
| ------------------------------------------------------------- | ------------------------------------------------------------- |
| Underlying Asset                                              | ChainLink                                                     |
| Project Website                                               | <https://chain.link/>                                         |
| Asset symbol                                                  | Link                                                          |
| Price Source                                                  | Binance                                                       |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://api.binance.com/api/v3/ticker/price?symbol=LINKUSDT> |
| Price Path                                                    | price                                                         |
| Max. Leverage                                                 | 50x                                                           |

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |


# ATOM - Cosmos

<div align="left"><img src="https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-LxGg76mR0TCWVR6Roh8%2F-LxGgGlmfVk30H6aQDF-%2F3794.png?alt=media&amp;token=7d69bce1-4028-4368-ae82-35cf4d500cae" alt=""></div>

Cosmos is an ecosystem of blockchains that can scale and interoperate with each other. Before Cosmos, blockchains were siloed and unable to communicate with each other. They were hard to build and could only handle a small amount of transactions per second. Cosmos solves these problems with a new technical vision. In order to understand this vision we need to go back to the fundamentals of blockchain technology.

| Parameter                                                     | Value                                                         |
| ------------------------------------------------------------- | ------------------------------------------------------------- |
| Underlying Asset                                              | Cosmos                                                        |
| Project Website                                               | <https://cosmos.network/>                                     |
| Asset symbol                                                  | ATOM                                                          |
| Price Source                                                  | Binance                                                       |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://api.binance.com/api/v3/ticker/price?symbol=ATOMUSDT> |
| Price Path                                                    | price                                                         |
| Max. Leverage                                                 | 50x                                                           |

####

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 50x        | 0.45                           |
| 25x        | 0.40                           |
| 10x        | 0.35                           |
| 5x or less | 0.30                           |


# DOT - Polkadot

![](https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-MSw6ZUItrZ2v3vkm3Kq%2F-MSw6oreaeM32Hpy6nMY%2F6636.png?alt=media\&token=a32e4d69-1856-43b5-953f-86877c87641b)

Polkadot is an open-source sharding multichain protocol that facilitates the cross-chain transfer of any data or asset types, not just tokens, thereby making a wide range of blockchains interoperable with each other.

This interoperability seeks to establish a fully decentralized and private web, controlled by its users, and simplify the creation of new applications, institutions and services.

The Polkadot protocol connects public and private chains, permissionless networks, oracles and future technologies, allowing these independent blockchains to trustlessly share information and transactions through the Polkadot relay chain (explained further down).

Polkadot’s native DOT token serves three clear purposes: providing network governance and operations, and creating parachains (parallel chains) by bonding.

| Parameter                                                     | Value                                                        |
| ------------------------------------------------------------- | ------------------------------------------------------------ |
| Underlying Asset                                              | Polkadot                                                     |
| Project Website                                               | <https://polkadot.network/>                                  |
| Asset symbol                                                  | DOT                                                          |
| Price Source                                                  | Binance                                                      |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | <https://api.binance.com/api/v3/ticker/price?symbol=DOTUSDT> |
| Price Path                                                    | price                                                        |
| Max. Leverage                                                 | 25x                                                          |

####

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 25x        | 0.45                           |
| 10x        | 0.40                           |
| 5x         | 0.35                           |
| 3x or less | 0.30                           |

####


# UNI - Uniswap

![](https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-MSw6ZUItrZ2v3vkm3Kq%2F-MSw7Ra-ftZagKDMGQqi%2F7083.png?alt=media\&token=70e7a859-1c3e-4bac-b3d1-cf594b437e24)

[Uniswap](https://coinmarketcap.com/exchanges/uniswap-v2/) is a popular decentralized trading protocol, known for its role in facilitating automated trading of decentralized finance ([DeFi](https://coinmarketcap.com/alexandria/article/what-is-decentralized-finance)) tokens.

An example of an automated market maker ([AMM](https://coinmarketcap.com/alexandria/glossary/automated-market-maker-amm)), Uniswap launched in November 2018, but has gained considerable popularity this year thanks to the DeFi phenomenon and associated surge in token trading.

Uniswap aims to keep token trading automated and completely open to anyone who holds tokens, while improving the efficiency of trading versus that on traditional exchanges.

Uniswap creates more efficiency by solving liquidity issues with automated solutions, avoiding the problems which plagued the first decentralized exchanges.

In September 2020, Uniswap went a step further by creating and awarding its own governance token, UNI, to past users of the protocol. This added both profitability potential and the ability for users to shape its future — an attractive aspect of decentralized entities.

| Parameter                                                     | Value                                                                                                                       |
| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Underlying Asset                                              | Uniswap                                                                                                                     |
| Project Website                                               | <https://uniswap.org/blog/uni/>                                                                                             |
| Asset symbol                                                  | UNI                                                                                                                         |
| Price Source                                                  | Binance                                                                                                                     |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | [https://api.binance.com/api/v3/ticker/price?symbol=UNIUSDT](< https://api.binance.com/api/v3/ticker/price?symbol=UNIUSDT>) |
| Price Path                                                    | price                                                                                                                       |
| Max. Leverage                                                 | 25x                                                                                                                         |

####

#### Maintenance Margin Coefficients

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 25x        | 0.45                           |
| 10x        | 0.40                           |
| 5x         | 0.35                           |
| 3x or less | 0.30                           |

####


# ZRX - 0x

![](https://357569466-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lx0bNqIx5ju0NQpuNqM%2F-MSw87maWnLnTlW7UofU%2F-MSw8Okri3a6sqpqPiAb%2F1896.png?alt=media\&token=8fd9896c-49c9-45c9-a322-59daddcd9072)

0x is an infrastructure protocol that allows users to easily trade ERC20 tokens and other assets on the [Ethereum](https://coinmarketcap.com/currencies/ethereum/) blockchain without relying on centralized intermediaries like traditional [cryptocurrency](https://coinmarketcap.com/alexandria/article/what-are-cryptocurrencies) exchanges.

0x achieves this decentralized exchange functionality using a collection of open-source, publicly auditable [smart contracts](https://coinmarketcap.com/alexandria/glossary/smart-contract) that work together to produce a flexible, low-friction trading protocol that developers can easily weave into their products.

The protocol is powered by an ERC20 utility token known as ZRX. Nodes that (also known as relayers) host an off-chain order book and offer user-facing applications that present this information and allow users to make, fill and cancel transactions are paid in ZRX tokens (as trading fees). ZRX can also be used to participate in platform governance, helping holders suggest and vote on changes to the protocol.

In 2019, 0x [announced](https://blog.0xproject.com/0x-roadmap-2019-part-4-proposal-for-stake-based-liquidity-incentive-52c16558df29) an overhaul of the ZRX token, adding extra functionality, allowing ZRX holders to delegate their stake to a market maker to earn passive rewards while retaining their voting capacity.

| Parameter                                                     | Value                                                                                                                       |
| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Underlying Asset                                              | 0x                                                                                                                          |
| Project Website                                               | <https://0x.org/>                                                                                                           |
| Asset symbol                                                  | ZRX                                                                                                                         |
| Price Source                                                  | Binance                                                                                                                     |
| ​[Price Url](https://www.bitstamp.net/api/v2/ticker/ethusd/)​ | [https://api.binance.com/api/v3/ticker/price?symbol=ZRXUSDT](< https://api.binance.com/api/v3/ticker/price?symbol=ZRXUSDT>) |
| Price Path                                                    | price                                                                                                                       |
| Max. Leverage                                                 | 25x                                                                                                                         |

####

#### Maintenance Margin Coefficient

| Leverage   | Maintenance Margin Coefficient |
| ---------- | ------------------------------ |
| 25x        | 0.45                           |
| 10x        | 0.40                           |
| 5x         | 0.35                           |
| 3x or less | 0.30                           |

####


