NAV Navbar
javascript shell

Introduction

Welcome to the IDEX v3 API developer documentation. IDEX provides a REST API for public market data, authenticated user data, and trading. IDEX also offers a WebSocket API for real-time access to market and user data.

Changelog

2021-12-01: IDEX v3 mainnet release.

Concepts

Blockchains

IDEX operates on Polygon, supporting MATIC and ERC-20 assets. More blockchain integrations are planned for the future. IDEX provides a uniform API across blockchains, so new integrations take minutes instead of days.

Fund Custody

As the leading high-performance, non-custodial exchange, IDEX does not take custody of funds before making them available to trade. Unlike centralized exchanges, where funds are first deposited to a wallet controlled by the exchange, IDEX relies on a smart contract to hold user funds, track user balances, and settle trades. While the user experience is similar to a centralized exchange – funds must first be deposited to the IDEX smart contract before trading – the resulting security is anything but. IDEX does not control user funds, funds can never change hands without authorization from the user’s wallet, and funds can always be withdrawn from the contract, even in the case that IDEX ceases to operate. Most importantly, these properties are independently verifiable by the community.

Hybrid Liquidity

The launch of IDEX v3 introduces hybrid liquidity, a pioneering technology that seamlessly integrates automated market maker pool liquidity into a feature-rich central limit order book exchange. The IDEX v3 consumer documentation contains an in-depth explanation of hybrid liquidity concepts and operation.

For traders and API integrators, hybrid liquidity is completely seamless. Order placements, cancelations, and executions work as they do in a standard central limit order book exchange. The IDEX v3 matching engine and smart contracts automatically fill orders with the best combination of pool and order book liquidity. IDEX v3 also provides a familiar interface for liquidity providers, with liquidity additions and removals using the standard addLiquidity and removeLiquidity functions common to many open source router contract designs.

Advanced operators looking to maximize the potential of hybrid liquidity may also consider:

Matching Engine

IDEX employs a high-performance central limit order book design that continuously matches user orders on a price-time priority basis. Similar to matching engines employed by traditional, non-crypto exchanges, limit orders are filled at the specified price or better with no risk of order collisions or trade failures. Support for partial fills enables seamless matching against multiple orders. As a result, the user experience is similar to a high-performance, centralized exchange.

Example

  1. User A first places a limit buy order for 1 ETH at 210 USDC
  2. User B then places a limit sell order for 1 ETH at 200 USDC

Assuming no other orders are on the ETH-USDC order book, the matching engine fills user A’s and B’s orders for 1 ETH at 210 USDC. User A’s order was placed first and resting on the books, while User B’s order crossed the spread and was able to be filled at a better price than specified.

Order Types

IDEX’s matching engine supports a wide range of order types.

Market

A market order is an order to buy or sell a quantity of an asset at the prevailing prices. Market orders execute immediately, never rest on an order book, and only take liquidity from an order book. Market orders have no pricing guarantees but quantities may be specified in base or quote terms. For example, a market buy order for ETH-USDC may either specify 10 ETH as the quantity, instructing the matching engine to buy 10 ETH, or 2000 USDC as the quantity, instructing the matching engine to buy 2000 USDC worth of ETH.

Limit

A limit order is an order to buy or sell a quantity of an asset at or better than a specified price. Limit orders require specifying both a quantity in base terms and a price in quote terms. The matching engine only fills limit buy orders up to the specified quantity at or lower than the specified price; it fills limit sell orders up to the specified quantity at or higher than the specified price. Limit orders specified with a price that crosses the spread are immediately matched and take liquidity from an order book. Any portion of a limit order that cannot be matched immediately is added to the order book, subject to time in force rules and the maker trade minimum.

LimitMaker

A limitMaker order is a limit order that can only add liquidity to the order book. If a limitMaker order price crosses the spread and matches with an existing order on the books, the limitMaker order is rejected by the matching engine without generating any fills. LimitMaker orders are sometimes referred to as "post-only" orders in other systems.

StopLoss

A market order that is only processed by the matching engine when the most recent fill in a market crosses the specified stop price. See Stop Mechanics for the specific trigger criteria.

StopLossLimit

A limit order that is only processed by the matching engine when the most recent fill in a market crosses the specified stop price. See Stop Mechanics for the specific trigger criteria.

TakeProfit

A market order that is only processed by the matching engine when the most recent fill in a market crosses the specified stop price. See Stop Mechanics for the specific trigger criteria.

TakeProfitLimit

A limit order that is only processed by the matching engine when the most recent fill in a market crosses the specified stop price. See Stop Mechanics for the specific trigger criteria.

Stop Mechanics

StopLoss and TakeProfit orders are similar, but have opposite stop trigger criteria.

Type Side Trigger Condition
Stop Loss Sell Last fill price <= stop price
Take Profit Sell Last fill price >= stop price
Stop Loss Buy Last fill price >= stop price
Take Profit Buy Last fill price <= stop price

Stop and Take orders do not appear in any public data until the stop is triggered and the order is added to the order book. Importantly, these orders are not guaranteed to execute immediately when the stop is triggered. Like all other orders, they are processed with price-time priority where the time of the order is the stop trigger time. Funds for stopLossLimit or takeProfitLimit orders are held immediately at the time of placement, not when the stop is triggered. Funds for stopLoss and takeProfit orders are never held.

Time In Force

Time in force policies specify the behavior of limit orders upon execution.

Self-Trade Prevention

IDEX’s matching engine includes logic to prevent self-trading. Two orders from the same API user or wallet cannot fill each other and on match are subject to the taker order’s specified self-trade prevention policy.

Order States & Lifecycle

Orders take on various states throughout the order execution lifecycle.

Order state is included in all order endpoint responses. Orders are not guaranteed to enter the open state before reporting as another state. For example, a limit order that is completely filled on execution first reports in the filled state in endpoint responses.

Holds

IDEX reserves funds associated with a limit order while the order is resting on an order book. For limit buy orders, the matching engine holds quantity * price of the wallet’s quote asset balance. For limit sells, the matching engine holds the specified quantity of base asset balance. Canceling an open limit order releases the funds associated with the order. Funds for stopLossLimit or takeProfitLimit orders are held immediately at the time of placement, not when the stop is triggered. No funds are held for market orders regardless of whether a stop is specified.

Fees

IDEX collects several types of fees: maker trade fees, taker trade fees, withdrawal fees, and liquidity addition and removal fees.

Maker & Taker Orders

Trade fees are split into maker and taker fees, assessed when an order execution results in a fill, and split between hybrid liquidity providers and IDEX.

Type Fee
Maker Trade Fee 0.125%
Default Taker Trade Fee 0.125%

For example, for a fill in the ETH-USDC market where the resting maker order is the buyer:

When taker orders execute against hybrid liquidity, liquidity providers collect 0.1% and IDEX collects 0.025% taker trade fees. From a trader's perspective, fees are uniform regardless of liquidity source. Taker trade fee components are included in the API to support synthetic price level calculations for real-time hybrid liquidity order books.

Taker Gas Fee

In addition to trading fees, IDEX collects a fee to offset settlement gas costs from the taker. Fills are settled via Polygon transactions to the IDEX custody smart contracts. IDEX dispatches the settlement transaction and thus pays gas. The gas cost of the fill is computed based on the prevailing gas price and deducted from the amount received by the taker in the fill. Taker gas fees are collected in the asset received by the taker, not always in MATIC.

Withdrawal Gas Fee

IDEX collects fees on withdrawals in order to cover the cost of gas for the resulting MATIC or token transfer. Unlike deposits, withdrawals are initiated through the REST API. IDEX dispatches the resulting Polygon transaction to return funds to the original wallet and thus pays gas. The gas cost of the withdrawal is computed based on the prevailing gas price and deducted from the amount withdrawn to the wallet. Withdrawal gas fees are collected in the withdrawn asset, not always in MATIC.

Liquidity Addition & Removal Gas Fees

IDEX collects fees on liquidity additions and removals in order to cover the cost of gas for the resulting pool state update and MATIC or token transfers. While liquidity changes may be initiated through contract calls or the REST API, IDEX always dispatches liquidity change settlement transactions and thus pays gas. Gas cost is computed based on the prevailing gas price and deducted proportionally from the reserve quantities of the addition or removal.

Minimums

IDEX enforces trade, withdrawal, and liquidity change minimums.

Type Polygon Minimum
Maker Trade Minimum 10 MATIC The minimum size of an order that can be added to an order book. Maker orders are automatically closed when the remaining open quantity falls below the Taker Trade Minimum.
Taker Trade Minimum 1 MATIC The minimum order size that is accepted by the matching engine for execution.
Withdrawal Minimum 0.5 MATIC The minimum value of an asset that can be withdrawn through the withdrawal endpoint.
Liquidity Addition Minimum 0.5 MATIC The minimum value of reserve assets that can be added to a hybrid liquidity pool.
Liquidity Removal Minimum 0.4 MATIC The minimum value of reserve assets that can be removed from a hybrid liquidity pool.

Minimums for tokens are enforced based on the spot price of the token in MATIC at the time of execution.

Resources

Client Libraries & SDKs

IDEX maintains official TypeScript / JavaScript and Python SDKs, supporting REST and WebSocket APIs as well as real-time order books.

IDEX smart contracts, ABIs, documentation and tests are also available.

Bug Bounty

The IDEX v3 API is covered by a bug bounty via Immunefi.

Support

Support is available via the IDEX developers Discord channel or via [email protected].

REST API Interaction

URL & Contract Addresses

Polygon

REST API: https://api-matic.idex.io/
Exchange Contract: 0x3253A7e75539EdaEb1Db608ce6Ef9AA1ac9126B6
Custody Contract: 0x3bcC4EcA0a40358558ca8D1bcd2d1dBdE63eB468

IDEX’s data centers are in the AWS Europe (Ireland) eu-west-1 region.

Requests

All requests and responses use the application/json content type with UTF-8 encoding. GET request parameters must be supplied in the query string, while POST and DELETE request parameters must be supplied as a JSON object in the body.

Successful requests return a 200 HTTP status code, while requests that generate errors return 4xx or 5xx status codes.

Error response body:

{
  "code": "<Machine-readable short code>",
  "message": "<Human-readable error message>"
}
Code Status Description
400 Bad Request Invalid request or format.
401 Unauthorized Invalid authentication credentials.
403 Forbidden No access to the requested resource.
404 Not Found Resource could not be located.
422 Unprocessable Entity The request format is valid but the request did not succeed. For example, 422 is returned if an order is placed with insufficient funds.
500 Internal Server Error Unexpected server error. This code does not necessarily indicate a failure in the call so the resulting state is unknown.

Error responses include a machine-readable error short code and longer human-readable error message in the body. As a result, it is important to configure the requesting http library to provide message bodies for error responses.

Data Types

Times

Time parameters in API requests must be represented in Unix epoch time in either seconds or milliseconds. Times included in API responses are returned in Unix epoch time in milliseconds.

Numbers & Precision

Aside from the Liquidity Endpoints, IDEX normalizes all asset precision to 8 decimals, and price and quantity values in API requests must be fully zero-padded strings. For example:

Price and quantity values included in API responses are returned in the same string format. Normalizing precision eliminates the need for clients to track asset precision and results in more human-readable values. Expressing values in fully zero-padded strings ensures that numeric values are always represented consistently for authentication signature verification.

Price and quantity values in API responses are exact and should not be treated as floating point numbers.

The Liquidity Endpoints use full token precision for quantities, as is the standard for most open-source liquidity pools. Any fields that do not use normalized precision, such as those in the Liquidity Endpoints, are explicitly documented accordingly.

IDs

Resource identifiers are UUIDs. API requests may encode ids with or without hyphens.

Client IDs

Order requests may optionally include a client-specified id. Client ids are not public and are only included in authorized responses. Orders may also be queried by client id. Client ids are scoped to a wallet, meaning different wallets can use the same client id to refer to different orders. Client ids are interpreted as UTF-8 encoded strings with a maximum length of 40 bytes.

Sequence Numbers

IDEX provides two types of sequence numbers to synchronize data between the REST and WebSocket APIs.

Pagination

Pagination is specified by several standard request parameters.

Any combination of start, end, limit and fromId are valid, but certain values take precedence over others. For example, if start and end are specified but not limit, the response will include objects starting at start and ending either at end or at 1,000 objects. Specifying end alone returns 50 objects closest to, but earlier (older) than end. Specifying none of the pagination parameters returns the 50 most recent objects. fromId takes precedence over start.

Response data is returned in ascending time order, with oldest objects first and newest objects last.

Authentication

API Keys

API keys may be generated via the IDEX API keys page and are only valid for requests by the generating API account. They include an accompanying secret value that is used to sign requests to some endpoints. API keys are not chain-specific and work for REST API requests for all supported blockchains.

API keys have three access scopes which are set independently via the API keys page.

Endpoint Security

Endpoints are protected by three security policies.

Request Structure & HMAC Signature

To create the HMAC signature for GET requests, hash the request query string.

const querystring = require("querystring");
const axios = require("axios");
const crypto = require("crypto");
const uuid = require('uuid');

let params = {
  nonce: uuid.v1(),
  wallet: "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
};
// Important: use querystring.stringify for parameters in the query string
let stringifiedParams = querystring.stringify(params);

let signature = crypto.createHmac("sha256", "<API secret>").update(stringifiedParams).digest("hex");

axios.get("https://api-matic.idex.io/v1/fills", {
  params: params,
  headers: {
    "IDEX-API-KEY": "<API key>",
    "IDEX-HMAC-SIGNATURE": signature
  }
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });
$ echo -n "nonce=79ed6fb0-9ee3-11ea-863e-898eb621b577&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d" | openssl sha256 -hmac "<API secret>"
5998679166d343f3940530d8a8a4d2c776d093bcb426e10232987953a6ab4e1c

$ curl "https://api-matic.idex.io/v1/fills?nonce=79ed6fb0-9ee3-11ea-863e-898eb621b577&wallet=0xa71c4aeeaabbbb8d2910f41c2ca3964b81f7310d" \
    -H "IDEX-API-Key: <API key>" \
    -H "IDEX-HMAC-Signature: 5998679166d343f3940530d8a8a4d2c776d093bcb426e10232987953a6ab4e1c"

To create the HMAC signature for POST or DELETE requests, hash the request body.

const axios = require("axios");
const crypto = require("crypto");

let body = {
  "parameters": {
    "nonce": "8fa5dce0-9ee6-11ea-9fa0-bf38ac8631c1",
    "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
    "market": "ETH-USDC",
    "type": "market",
    "side": "buy",
    "quoteOrderQuantity": "1000.00000000"
  },
  "signature": "<Wallet signature>"
};
// Important: use JSON.stringify for parameters in the body
let stringifiedBody = JSON.stringify(body);

let signature = crypto.createHmac("sha256", "<API secret>").update(stringifiedBody).digest("hex");

axios.post("https://api-matic.idex.io/v1/orders", body, {
    headers: {
      "IDEX-API-Key": "<API key>",
      "IDEX-HMAC-Signature": signature,
    }
  })
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });
$ echo -n '{"parameters":{"nonce":"8fa5dce0-9ee6-11ea-9fa0-bf38ac8631c1","wallet":"0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d","market":"ETH-USDC","type":"market","side":"buy","quoteOrderQuantity":"1000.00000000"},"signature":"<Wallet signature>"}' | openssl sha256 -hmac "<API secret>"
ae1e6b454f6aa86bed9f8ef59b635cc948bcd5e5689acbfc1a73cd97ca2dc6c1

$ curl "https://api-matic.idex.io/v1/orders" \
    -X POST
    -H "IDEX-API-Key: <API key>" \
    -H "IDEX-HMAC-Signature: ae1e6b454f6aa86bed9f8ef59b635cc948bcd5e5689acbfc1a73cd97ca2dc6c1" \
    -H "Content-Type: application/json" \
    -d '{"parameters":{"nonce":"8fa5dce0-9ee6-11ea-9fa0-bf38ac8631c1","wallet":"0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d","market":"ETH-USDC","type":"market","side":"buy","quoteOrderQuantity":"1000.00000000"},"signature":"<Wallet signature>"}'

The server-side validation checks the signature on the query string or request body as it is represented in the request.

For endpoints that require or benefit from authentication, the API key and HMAC signature must be included as request headers.

The HMAC signature is computed by signing the payload of the request via HMAC-SHA256. The HMAC signature is computed differently for GET requests, where the payload is in the query string, and POSTs or DELETEs where the payload is in the body.

Wallet Signature

To create the Polygon wallet signature, encode the request parameters according to the relevant Wallet Signature Parameter Hash scheme.

const ethers = require("ethers");

let order = {
  "nonce": "8fa5dce0-9ee6-11ea-9fa0-bf38ac8631c1",
  "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
  "market": "ETH-USDC",
  "type": 0, // enum value for market orders
  "side": 0, // enum value for buy
  "quoteOrderQuantity": "1000.00000000"
}

// Nonce must be a 16-byte array, not string representation
let nonceAsByteArray = ethers.utils.arrayify(`0x${order.nonce.replace(/-/g, '')}`)

let signatureParameters = [
  ["uint8", 4], // The signature hash version is 4 for mainnet
  ["uint128", nonceAsByteArray],
  ["address", order.wallet],
  ["string", order.market],
  ["uint8", order.type],
  ["uint8", order.side],
  ["string", order.quantity ? order.quantity : order.quoteOrderQuantity],
  ["bool", order.quantity ? false : true],
  ["string", order.price || ''],
  ["string", order.stopPrice || ''],
  ["string", order.clientOrderId || ''],
  ["uint8", order.timeInForce || 0],
  ["uint8", order.selfTradePrevention || 0],
  ["uint64", 0]
];

let fields = signatureParameters.map(param => param[0]);
let values = signatureParameters.map(param => param[1]);
let signatureParametersHash = ethers.utils.solidityKeccak256(fields, values);

new ethers.Wallet("<Polygon wallet private key>").signMessage(
    ethers.utils.arrayify(signatureParametersHash),
  )
  .then((polygonWalletSignature) => {
    console.log(polygonWalletSignature);
  });

As a non-custodial exchange, IDEX requires authorization from the funding wallet for placing and canceling orders, withdrawing funds, and adding and removing liquidity. Specifically, all trade endpoint requests must include a Polygon wallet signature, in addition to the standard HMAC signature, to be processable by the exchange.

Polygon wallet signatures, which are identical to Ethereum wallet signtuares, are computed by using the funding wallet keypair to sign a Keccak-256/SHA-3 hash of request parameters. Parameters must be hashed in a specific order with standardized data types for each endpoint, and optional parameters must be handled according to the below documentation. Wallet signatures are included in the body of the request for endpoints that require them.

Associate Wallet Wallet Signature Parameter Hash Structure

Position Data Type Value
0 uint128 Nonce
1 address Signing wallet address

Create Order Wallet Signature Parameter Hash Structure

Position Data Type Value
0 uint8 Signature hash version, should be 4 for mainnet
1 uint128 Nonce
2 address Signing wallet address
3 string Market symbol
4 uint8 Order type enum value
5 uint8 Order side enum value
6 string Order quantity in base or quote terms
7 bool false if order quantity in base terms; true if order quantity in quote terms
8 string Order price or empty string if market order
9 string Order stop price or empty string if not a stop loss or take profit order
10 string Client order id or empty string
11 uint8 Order time in force enum value
12 uint8 Order self-trade prevention enum value
13 uint64 Unused, always should be 0

Cancel Order Wallet Signature Parameter Hash Structure

Position Data Type Value
0 uint128 Nonce
1 address Signing wallet address
2 string Order id, client id, or empty string if market (3) is specified
3 string Market symbol or empty string if id (2) is specified

Withdraw Funds Wallet Signature Parameter Hash Structure

Position Data Type Value
0 uint128 Nonce
1 address Signing wallet address
2 string Asset symbol if the withdrawal is specified by an asset symbol
2 address Token contract address if the withdrawal is specified by token contract address
3 string Withdrawal quantity in exchange precision
4 bool Auto-dispatch setting, always must be true

Add Liquidity Wallet Signature Parameter Hash Structure

Position Data Type Value
0 uint8 Signature hash version, should be 4 for mainnet
1 uint8 Liquidity change type enum value, should always be 0 for additions
2 uint8 Liquidity change origin enum value, should always be 1
3 uint128 Nonce
4 address Signing wallet address
5 address tokenA contract address
6 address tokenB contract address
7 uint256 Maximum amount of tokenA to add in token precision
8 uint256 Maximum amount of tokenB to add in token precision
9 uint256 Minimum amount of tokenA to add in token precision
10 uint256 Minimum amount of tokenB to add in token precision
11 address Wallet address to credit resulting liquidity provider (LP) tokens
12 uint256 Unused for API-initiated liquidity additions, should always be 0

Remove Liquidity Wallet Signature Parameter Hash Structure

Position Data Type Value
0 uint8 Signature hash version, should be 4 for mainnet
1 uint8 Liquidity change type enum value, should always be 1 for removals
2 uint8 Liquidity change origin enum value, should always be 1
3 uint128 Nonce
4 address Signing wallet address
5 address tokenA contract address
6 address tokenB contract address
7 uint256 Quantity of liquidity provider (LP) tokens to burn in token precision
8 uint256 Minimum quantity of tokenA to remove in token precision
9 uint256 Minimum quantity of tokenB to remove in token precision
10 address Wallet address to credit resulting reserve tokens
11 uint256 Unused for API-initiated liquidity removals, should always be 0

Wallet to API Account Association

A wallet must be associated with an API account to request private data from endpoints such as Get Orders or Get Fills. Several actions associate a wallet with an API account.

Under the hood, associating a wallet with an API account requires proving that the requester has access to the wallet's private key. The associating actions all include a wallet signature along with the request, satisfying the association requirement. Calling Associate Wallet is often the first step in requesting data from User Data endpoints.

Nonces

Use a standard UUID library to generate version 1 UUID nonces.

const uuid = require('uuid');

uuid.v1();

User data and trade endpoints requests must include a nonce. IDEX uses version 1 UUID nonces, eliminating the need to coordinate nonce increments between multiple agents operating on a single wallet. Version 1 UUIDs encode a timestamp in addition to other unique information, and thus serve both to prevent replay attacks as well as to enforce request timing. As a result, nonces must be generated at the time of a request. Nonces may be supplied with or without hyphens.

Order Nonce Invalidation

const fs = require("fs");
const ethers = require("ethers");
const uuid = require('uuid');

async function invalidateNonce() {
    const idexAddress = "<IDEX exchange contract address>";
    const txOptions = { gasPrice: ethers.utils.parseUnits("<Gas price in gwei>", "gwei") };

    // Connect a wallet to mainnet
    const provider = new ethers.providers.JsonRpcProvider("<Polygon RPC>");
    const walletWithProvider = new ethers.Wallet("<Polygon wallet private key>", provider);

    // Load contract
    const idexAbi = JSON.parse(fs.readFileSync("idex.abi.json"));
    const idexContract = new ethers.Contract(idexAddress, idexAbi, walletWithProvider);

    const nonce = uuid.v1();
    // Nonce must be a 16-byte array, not string representation
    const nonceAsByteArray = ethers.utils.arrayify(`0x${nonce.replace(/-/g, "")}`);

    console.log("Invalidating order nonce...")
    const invalidateOrderNonceTx = await idexContract.invalidateOrderNonce(nonceAsByteArray, txOptions);
    console.log(`Dispatched invalidate order nonce call ${invalidateOrderNonceTx.hash} awaiting mine...`);
    await invalidateOrderNonceTx.wait();
    console.log("Mined");
}

invalidateNonce();

The IDEX exchange smart contract includes the ability to invalidate old order nonces. In the unlikely event that IDEX's off-chain components are compromised, it is theoretically possible that an attacker could submit a trade against an old, unfilled but canceled order. To limit risk in this scenario, clients may periodically invalidate old order nonces. Order nonce invalidation is a three-step process:

  1. Cancel all open orders.
  2. Call invalidateOrderNonce on the IDEX exchange contract with a freshly generated nonce. A freshly generated nonce invalidates all order nonces generated in the past.
  3. Re-place formerly-open orders with new orders.

Timing

IDEX only accepts recently-generated requests to prevent the inadvertent processing of out-of-date requests, regardless of the source of delay. Request timing is established by the nonce request parameter, which encodes a timestamp. IDEX rejects requests that have a nonce that is more than 60 seconds older or 5 second newer than the IDEX system clock. The Get Time endpoint returns the current IDEX time to synchronize the skew between internal and client clocks.

Rate Limits

IDEX enforces rate limits on all endpoints. Exceeding a rate limit returns a 429 Too Many Requests HTTP status code. Rate limits vary between different types of endpoints, authentication, and the amount of data requested. Some endpoints are available without rate limits via IDEX API Replicators.

Endpoint Type Single Bundled
Public, no API key 5/s 1/s
Public, with API key 10/s 1/s
User Data 10/s 1/s
Trade 10/s n/a

API Replicator

Like all APIs, the IDEX REST API implements rate limits and caching to maintain excellent performance. Some endpoints, such as Get Order Books, do not respond with real-time market data by design. For API consumers that need real-time order book data but do not want to implement the WebSocket API, the IDEX API Replicator program is a unique option, powered by the community, to access real-time market data without rate limits.

Members of the IDEX community operate Replicator nodes that consume the IDEX WebSocket API, maintaining the real-time state of all order books, and make the data available via standard REST requests. As a REST API consumer, accessing data from API Replicators is simple.

API Replicator Faucet: https://sc.idex.io/replicators

Request an active Replicator from the Faucet to use for unlimited requests for real-time order book data.

$ curl "https://sc.idex.io/replicators"
{"url":"http://dusty-newt.replicators.idexstaking.net:8081"}

$ curl "http://dusty-newt.replicators.idexstaking.net:8081/matic/v1/orderbook?market=ETH-USDC&level=2&limit=100"
  1. Request an active Replicator URL from the Replicator Faucet with GET https://sc.idex.io/replicators.
  2. Use the returned URL, including the port, for any requets to the supported Replicator endpoints. Currently only the Get Order Books endpoint is supported, but more endpoints may be added in the future. For replicator requests, the target blockchain of matic, indicating the Polygon network, must be specified in the path. For example, /matic/v1/orderbook?market=ETH-USDC.

Some important considerations:

Public Data Endpoints

Get Ping

Tests connectivity to the REST API.

Request Parameters

$ curl "https://api-matic.idex.io/v1/ping" 

None

Response Object

JSON response

{}

Empty JSON object

Get Time

Returns the current server time.

Request Parameters

$ curl "https://api-matic.idex.io/v1/time" 

None

Response Object

JSON response

{
    "serverTime": 1590408000000
}
Field Type Description
serverTime integer Current server time

Get Exchange

Returns basic information about the exchange.

Request Parameters

$ curl "https://api-matic.idex.io/v1/exchange" 

None

Response Object

JSON response

{
    "timeZone": "UTC",
    "serverTime": 1590408000000,
    "maticDepositContractAddress": "0x...",
    "maticCustodyContractAddress": "0x...",
    "maticUsdPrice": "1.46",
    "gasPrice": 7,
    "volume24hUsd": "10416227.98",
    "totalVolumeUsd": "2921007583.74",
    "totalTrades": 5372019,
    "totalValueLockedUsd": "218462011.50",
    "idexTokenAddress": "0x...",
    "idexUsdPrice": "1.62",
    "idexMarketCapUsd": "954070759.33",
    "makerFeeRate": "0.0010",
    "takerFeeRate": "0.0025",
    "takerIdexFeeRate": "0.0005",
    "takerLiquidityProviderFeeRate": "0.0020",
    "makerTradeMinimum": "10.00000000",
    "takerTradeMinimum": "1.00000000",
    "withdrawalMinimum": "0.50000000",
    "liquidityAdditionMinimum": "0.50000000",
    "liquidityRemovalMinimum": "0.40000000",
    "blockConfirmationDelay": 128
}
Field Type Description
timeZone string Server time zone, always UTC
serverTime integer Current server time
maticDepositContractAddress string Polygon address of the exchange smart contract for deposits
maticCustodyContractAddress string Polygon address of the custody smart contract for certain add and remove liquidity calls
maticUsdPrice string Current price of MATIC in USD
gasPrice integer Current gas price used by the exchange for trade settlement and withdrawal transactions in Gwei
volume24hUsd string Total exchange trading volume for the trailing 24 hours in USD
totalVolumeUsd string Total exchange trading volume for IDEX v3 on Polygon in USD
totalTrades integer Total number of trade executions for IDEX v3 on Polygon
totalValueLockedUsd string Total value locked in IDEX v3 on Polygon in USD
idexTokenAddress string Token contract address for the IDEX token on Polygon
idexUsdPrice string Current price of the IDEX token in USD
idexMarketCapUsd string Market capitalization of the IDEX token in USD
makerFeeRate string Maker trade fee rate
takerFeeRate string Total taker trade fee rate
takerIdexFeeRate string Taker trade fee rate collected by IDEX; used in computing synthetic price levels for real-time order books
takerLiquidityProviderFeeRate string Taker trade fee rate collected by liquidity providers; used in computing synthetic price levels for real-time order books
makerTradeMinimum string Minimum size of an order that can rest on the order book in MATIC, applies to both MATIC and tokens
takerTradeMinimum string Minimum order size that is accepted by the matching engine for execution in MATIC, applies to both MATIC and tokens
withdrawalMinimum string Minimum withdrawal amount in MATIC, applies to both MATIC and tokens
liquidityAdditionMinimum string Minimum liquidity addition amount in MATIC, applies to both MATIC and tokens
liquidityRemovalMinimum string Minimum withdrawal amount in MATIC, applies to both MATIC and tokens
blockConfirmationDelay integer Number of block confirmations for deposits, liquidity additions, and liquidity removals as required by Polygon network constraints

Get Assets

Returns information about assets supported by the exchange. Assets returned by this endpoint may or may not be included in listed markets. For example, a market may have been listed and then subsequently delisted, but the underlying assets are still returned by this endpoint.

Request Parameters

$ curl "https://api-matic.idex.io/v1/assets" 

None

Response Array Objects

JSON response

[
    {
        "name": "Ether",
        "symbol": "ETH",
        "contractAddress": "0x0000000000000000000000000000000000000000",
        "assetDecimals": 18,
        "exchangeDecimals": 8,
        "tokenPrice": "152.67175572"
    },
    {
        "name": "USD Coin",
        "symbol": "USDC",
        "contractAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
        "assetDecimals": 6,
        "exchangeDecimals": 8,
        "tokenPrice": "0.76335877"
    },
    ...
]
Field Type Description
name string Asset name
symbol string Asset symbol
contractAddress string Polygon address of the asset contract
assetDecimals integer Decimal precision of the native asset
exchangeDecimals integer Decimal precision of the asset on the exchange; assets are normalized to 8 decimal precision for trading purposes within IDEX
tokenPrice string Current price of the token in MATIC

Get Markets

Returns information about the currently listed markets.

Request Parameters

$ curl "https://api-matic.idex.io/v1/markets" 
Parameter Type Required Default Description
market string No Target market, all markets are returned if omitted

Response Array Objects

JSON response

[
    {
        "market": "ETH-USDC",
        "type": "hybrid",
        "status": "activeHybrid",
        "baseAsset": "ETH",
        "baseAssetPrecision": 8,
        "quoteAsset": "USDC",
        "quoteAssetPrecision": 8,
        "makerFeeRate": "0.0010",
        "takerFeeRate": "0.0025",
        "takerIdexFeeRate": "0.0005",
        "takerLiquidityProviderFeeRate": "0.0020"
    },
    ...
]
Field Type Description
market string Market symbol
type string Market type, see values
status string Market trading status, see values
baseAsset string Base asset symbol
baseAssetPrecision integer Exchange decimal precision of the base asset, always 8 due to precision normalization
quoteAsset string Quote asset symbol
quoteAssetPrecision integer Exchange decimal precision of the quote asset, always 8 due to precision normalization
makerFeeRate string Maker trade fee rate
takerFeeRate string Total taker trade fee rate
takerIdexFeeRate string Taker trade fee rate collected by IDEX; used in computing synthetic price levels for real-time order books
takerLiquidityProviderFeeRate string Taker trade fee rate collected by liquidity providers; used in computing synthetic price levels for real-time order books

Market Data Endpoints

Get Tickers

Returns market statistics for the trailing 24-hour period.

Request Parameters

$ curl "https://api-matic.idex.io/v1/tickers" 
Parameter Type Required Default Description
market string No Target market, all markets are returned if omitted

Response Array Objects

JSON response

[
    {
        "market": "ETH-USDC",
        "time": 1590408000000,
        "open": "202.11928302",
        "high": "207.58100029",
        "low": "201.85600392",
        "close": "206.00192301",
        "closeQuantity": "9.50000000",
        "baseVolume": "11297.01959248",
        "quoteVolume": "2327207.76033252",
        "percentChange": "1.92",
        "numTrades": 14201,
        "ask": "206.00207150",
        "bid": "206.00084721",
        "sequence": 848728
    },
    ...
]
Field Type Description
market string Market symbol
time integer Timestamp when the statistics were computed, the opening time of the period is 24 hours prior
open string Price of the first trade in the period in quote terms
high string Highest traded price in the period in quote terms
low string Lowest traded price in the period in quote terms
close string Price of the last trade in the period in quote terms
closeQuantity string Quantity of the last trade in the period in base terms
lastFillPrice string Price of the most recent trade in the period in quote terms
baseVolume string Trailing 24-hour trading volume in base terms
quoteVolume string Trailing 24-hour trading volume in quote terms
percentChange string Percentage change from open price to close price
numTrades integer Number of trades in the period
ask string Best ask price on the order book in quote terms
bid string Best bid price on the order book in quote terms
sequence integer Fill sequence number of the last trade in the period

Get Candles

Returns candle (OHLCV) data for a market.

Request Parameters

$ curl "https://api-matic.idex.io/v1/candles?market=ETH-USDC&interval=5m" 
Parameter Type Required Default Description
market string Yes None Target market
interval string Yes None Time period for each data point, see values
start integer No None Timestamp of the earliest (oldest) interval, inclusive
end integer No None Timestamp of the latest (newest) interval, inclusive
limit integer No 50 Maximum number of data points to return, 1-1,000

Response Array Objects

JSON response

[
    {
        "start": 1590393000000,
        "open": "202.11928302",
        "high": "202.98100029",
        "low": "201.85600392",
        "close": "202.50192301",
        "volume": "39.22576247",
        "sequence": 848678
    },
    ...
]
Field Type Description
start integer Timestamp of the start of the interval
open string Price of the first trade in the interval in quote terms
high string Highest traded price in the interval in quote terms
low string Lowest traded price in the interval in quote terms
close string Price of the last trade in the interval in quote terms
volume string Trading volume in the interval in base terms, null for some historical chart data
sequence integer Fill sequence number of the last trade in the interval, null for some historical chart data

Get Trades

Returns trade data for a market. There is also a Get Fills endpoint that returns more detailed private information. In this documentation, "trades" refers to public information about trades, whereas "fills" refers to detailed non-public information about trades resulting from orders placed by the API account.

Request Parameters

$ curl "https://api-matic.idex.io/v1/trades?market=ETH-USDC&start=1590394500000" 
Parameter Type Required Default Description
market string Yes None Target market
start integer No None Timestamp of the earliest (oldest) trade, inclusive
end integer No None Timestamp of the latest (newest) trade, inclusive
limit integer No 50 Maximum number of data points to return, 1-1,000
fromId string No None fillId of the earliest (oldest) trade

Response Array Objects

JSON response

[
    {
        "fillId": "a0b6a470-a6bf-11ea-90a3-8de307b3b6da",
        "price": "202.74900000",
        "quantity": "10.00000000",
        "quoteQuantity": "2027.49000000",
        "time": 1590394500000,
        "makerSide": "sell",
        "type": "hybrid",
        "sequence": 848778
    },
    ...
]
Field Type Description
fillId string Trade identifier
price string Price of the trade in quote terms
quantity string Quantity of the trade in base terms
quoteQuantity string Quantity of the trade in quote terms
time integer Timestamp of the trade
makerSide string Maker side of the trade, buy or sell
type string Trade type, see values
sequence integer Fill sequence number of the trade

Get Order Books

Returns a level-1 or level-2 order book of a market. With the introduction of hybrid liquidity in IDEX v3, Get Order Book responses include synthetic price levels representing liquidity pool liquidity. IDEX hybrid liquidity seamlessly matches orders with the best-priced source of liquidity from both order book orders and pool liquidity. Synthetic price levels, indicated by 0 orders at the price level, are not individual orders; they represent liquidity available from a market's liquidity pool at a limit price.

Request Parameters

The level-1 order book only includes the best bid and ask.

$ curl "https://api-matic.idex.io/v1/orderbook?market=ETH-USDC" 

JSON response

{
    "sequence": 71228121,
    "bids": [
        [ "202.00200000", "13.88204000", 2 ]
    ],
    "asks": [
        [ "202.01000000", "8.11400000", 0 ]
    ],
    "pool": {
        "baseReserveQuantity": "28237.08610815", 
        "quoteReserveQuantity": "5703947.86801900"
    }
}

Price level arrays for both bids and asks take the form of:

[ price, quantity available, number of orders at price level ]

A value of 0 for the number of orders at a price level indicates a synthetic price level where the quantities available are supplied by pool liquidity.

The level-2 order book contains all price levels up to the specified limit.

$ curl "https://api-matic.idex.io/v1/orderbook?market=ETH-USDC&level=2" 

JSON response

{
    "sequence": 71228121,
    "bids": [
        [ "202.00200000", "13.88204000", 2 ],
        [ "202.00100000", "8.11411500", 0 ],
        ...
    ],
    "asks": [
        [ "202.01000000", "8.11400000", 0 ],
        [ "202.01100000", "8.11392000", 0 ],
        ...
    ],
    "pool": {
        "baseReserveQuantity": "28237.08610815", 
        "quoteReserveQuantity": "5703947.86801900"
    }
}
Parameter Type Required Default Description
market string Yes Target market
level integer No 1 Level of order book, 1 or 2
limit integer No 50 Number of bids and asks to return, only applicable to level-2 data, 0 returns the maximum of 500 price levels per side
limitOrderOnly boolean No False true only returns standing limit orders without liquidity pool synthetic price levels, only applicable to level-2 data

Level 1 Response Object

Level-1 order book data is limited to the best bid and ask for a market, including hybrid liquidity synthetic price levels.

Field Type Description
sequence integer Most recent order book update sequence number reflected in the returned snapshot
bids array Single record of the best bid price level on the order book
asks array Single record of the best ask price level on the order book
pool object Reserve quantities of the market's liquidity pool as an object, null if hybrid liquidity is not available or active on the market

Pool Object

Field Type Description
baseReserveQuantity string Base reserve quantity in normalized precision
quoteReserveQuantity string Quote reserve quantity in normalized precision

Level 2 Response Object

Level-2 order book data includes price and quantity information for all price levels in the order book.

Field Type Description
sequence integer Most recent order book update sequence number reflected in the returned snapshot
bids array Bid price levels on the order book, limited by limit
asks array Ask price levels on the order book, limited by limit
pool object Reserve quantities of the market's liquidity pool as an object, null if hybrid liquidity is not available or active on the market

Real-Time Order Book Tracking Algorithm

  1. Connect to the WebSocket API endpoint and subscribe to the L2 Order Book for the target market.
  2. Buffer the incoming order book update subscription messages.
  3. Request a level-2 order book snapshot for the market from the REST API Order Books endpoint with limit set to 0.
  4. If the sequence in the order book snapshot is less than the sequence of the first buffered order book update message, discard the order book snapshot and retry step 3.
  5. Discard all order book update messages with sequence numbers less than or equal to the snapshot sequence number.
  6. Apply the remaining buffered order book update messages and any incoming order book update messages to the order book snapshot.
    1. Order book update messages include the new absolute quantity and number of orders for a price level. Replace the current data for the price level with the update message data.
    2. Remove price levels with a quantity of 0.
    3. Re-synchronize the order book if there are any gaps in the order book update sequence numbers.

Hybrid liquidity poses real time implementation challenges. The above algorithm correctly constructs a real-time order book for limit orders but does not reflect liquidity available from hybrid liquidity pools. The L2 Order Book WebSocket subscription includes real-time updates of pool reserve quantities, which is sufficient to compute the same order book representation as provided by the REST API, but does not push synthetic price levels directly. The IDEX JavaScript and Python SDKs use real-time pool reserve quantity updates to maintain an order book with complete hybrid liquidity. API integrators requiring a real time order book have several options:

IDEX is looking to expand language coverage for its SDKs. Please inquire in the developer Discord to request a particular language or platform.

User Data Endpoints

Get API Account

Returns information about the API account.

Request Parameters

$ curl "https://api-matic.idex.io/v1/user?nonce=90c22250-9ee6-11ea-9b53-65f7087a7a7e" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce

Response Object

JSON response

{
    "depositEnabled": true,
    "orderEnabled": true,
    "cancelEnabled": true,
    "withdrawEnabled": true,
    "totalPortfolioValueUsd": "127182.82",
    "makerFeeRate": "0.0010",
    "takerFeeRate": "0.0025",
    "takerIdexFeeRate": "0.0005",
    "takerLiquidityProviderFeeRate": "0.0020"
}
Field Type Description
depositEnabled boolean Deposits are enabled for the API account
orderEnabled boolean Placing orders is enabled for the API account
cancelEnabled boolean Canceling orders is enabled for the API account
withdrawEnabled boolean Withdrawals are enabled for the API account
totalPortfolioValueUsd string Total value of all holdings deposited on the exchange, for all wallets associated with the API account, in USD
makerFeeRate string User-specific maker trade fee rate
takerFeeRate string User-specific total taker trade fee rate
takerIdexFeeRate string Taker trade fee rate collected by IDEX; used in computing synthetic price levels for real-time order books
takerLiquidityProviderFeeRate string Taker trade fee rate collected by liquidity providers; used in computing synthetic price levels for real-time order books

Associate Wallet

// Example code for creating the required wallet signature. Note the IDEX SDKs
// automatically generate wallet signatures for endpoints that require them.

const ethers = require("ethers");
const uuid = require("uuid");

let data = {
  "nonce": uuid.v1(),
  "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d"
};

// Nonce must be a 16-byte array, not string representation
let nonceAsByteArray = ethers.utils.arrayify(`0x${data.nonce.replace(/-/g, '')}`);

let signatureParameters = [
  ["uint128", nonceAsByteArray],
  ["address", data.wallet]
];

let fields = signatureParameters.map(param => param[0]);
let values = signatureParameters.map(param => param[1]);
let signatureParametersHash = ethers.utils.solidityKeccak256(fields, values);

new ethers.Wallet("<Polygon wallet private key>").signMessage(
    ethers.utils.arrayify(signatureParametersHash),
  )
  .then((polygonWalletSignature) => {
    console.log(polygonWalletSignature);
  });

Associates a wallet with an API account, allowing access to private data such as fills. Associating a wallet with an API account is often the first step in interacting with private read endpoints. A wallet is automatically associated with an API account when creating orders, withdrawing funds, or adding or removing liquidity. Unlocking a wallet in the web client also associates a wallet with an API account.

For further information, see Wallet to API Account Association. Note this endpoint requires Trade endpoint security and must include a wallet signature.

Request Parameters

Sample associate order request payload

{
    "parameters": {
        "nonce": "9436afa0-9ee6-11ea-8a53-71994564322f",
        "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d"
    },
    "signature": "<Wallet signature>"
}
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Target wallet address

Response Object

JSON response

{
    "address": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
    "totalPortfolioValueUsd": "88141.77",
    "time": 1590393600000
}
Field Type Description
address string Polygon address of the wallet
totalPortfolioValueUsd string Total value of all holdings deposited on the exchange for the wallet in USD
time integer Timestamp of association of the wallet with the API account

Get Wallets

Returns information about the wallets associated with the API account.

Request Parameters

$ curl "https://api-matic.idex.io/v1/wallets?nonce=913ad4c0-9ee6-11ea-87e1-b75e864948fa" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce

Response Array Objects

JSON response

[
    {
        "address": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "totalPortfolioValueUsd": "88141.77",
        "time": 1590393600000
    },
    ...
]
Field Type Description
address string Polygon address of the wallet
totalPortfolioValueUsd string Total value of all holdings deposited on the exchange for the wallet in USD
time integer Timestamp of association of the wallet with the API account

Get Balances

Returns asset quantity information held by a wallet on the exchange.

Request Parameters

$ curl "https://api-matic.idex.io/v1/balances?nonce=919c2ea0-9ee6-11ea-8c44-8bbede4f2ec8&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Wallet address
asset array No None Array of asset symbols to query for balance information

Response Array Objects

JSON response

[
    {
        "asset": "USDC",
        "quantity": "38192.94678100",
        "availableForTrade": "26710.66678121",
        "locked": "11482.28000000",
        "usdValue": "38188.22"
    },
    ...
]
Field Type Description
asset string Asset symbol
quantity string Total quantity of the asset held by the wallet on the exchange
availableForTrade string Quantity of the asset available for trading; quantity - locked
locked string Quantity of the asset held in trades on the order book
usdValue string Total value of the asset held by the wallet on the exchange in USD

Orders & Trade Endpoints

Create Order

Create and submit an order to the matching engine.

Request Parameters

Sample market order request payload

{
    "parameters": {
        "nonce": "8fa5dce0-9ee6-11ea-9fa0-bf38ac8631c1",
        "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "market": "ETH-USDC",
        "type": "market",
        "side": "buy",
        "quoteOrderQuantity": "1000.00000000"
      },
    "signature": "<Wallet signature>"
}

Standard order JSON response

{
    "market": "ETH-USDC",
    "orderId": "92782120-a775-11ea-aa55-4da1cc97a06d",
    "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
    "time": 1590394200000,
    "status": "filled",
    "type": "market",
    "side": "buy",
    "originalQuoteQuantity": "1000.00000000",
    "executedQuantity": "4.95044603",
    "cumulativeQuoteQuantity": "1000.00000000",
    "avgExecutionPrice": "202.00200000",
    "fills": [
        {
            "fillId": "974480d0-a776-11ea-895b-bfcbb5bdaa50",
            "price": "202.00150000",
            "quantity": "3.78008801",
            "quoteQuantity": "763.58344815",
            "orderBookQuantity": "3.50000000",
            "orderBookQuoteQuantity": "707.00700000",
            "poolQuantity": "0.28008801",
            "poolQuoteQuantity": "56.57644815",
            "time": 1590394200000,
            "makerSide": "sell",
            "sequence": 981372,
            "fee": "0.00756017",
            "feeAsset": "ETH",
            "liquidity": "taker",
            "type": "hybrid",
            "txId": "0x01d28c33271cf1dd0eb04249617d3092f24bd9bad77ffb57a0316c3ce5425158",
            "txStatus": "mined"
        },
        ...
    ]
}

Sample stopLossLimit order request payload

{
    "parameters": {
        "nonce": "dd2e0930-a777-11ea-b5e9-d9c1e499360f",
        "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "market": "ETH-USDC",
        "type": "stopLossLimit",
        "side": "sell",
        "quantity": "4.95044603",
        "price": "190.00000000",
        "stopPrice": "195.00000000",
        "clientOrderId": "199283"
      },
    "signature": "<Wallet signature>"
}

Standard order JSON response

{
    "market": "ETH-USDC",
    "orderId": "3a9ef9c0-a779-11ea-907d-23e999279287",
    "clientOrderId": "199283",
    "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
    "time": 1590394500000,
    "status": "active",
    "type": "stopLossLimit",
    "side": "sell",
    "originalQuantity": "4.95044603",
    "executedQuantity": "0.00000000",
    "cumulativeQuoteQuantity": "0.00000000",
    "price": "190.00000000",
    "stopPrice": "195.00000000"
}
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Placing wallet address
market string Yes None Target market symbol
type string Yes None Order type, see values
side string Yes None Order side, buy or sell
quantity string No None Order quantity in base terms, exclusive with quoteOrderQuantity
quoteOrderQuantity string No None Order quantity in quote terms, market orders only, exclusive with quantity
price string No None Order price in quote terms, required for all limit orders, omitted for all market orders
stopPrice string No None Stop loss or take profit price, required for stopLoss, stopLossLimit, takeProfit, takeProfitLimit orders, omitted for others
clientOrderId string No None Client-specified order id, maximum of 40 bytes
timeInForce string No gtc Time in force policy, see values, only applies to all limit orders
selfTradePrevention string No dc Self-trade prevention policy, see values, must be cn if fok timeInForce is specified

Response Object

Field Type Optional Description
market string No Market symbol
orderId string No Exchange-assigned order identifier
clientOrderId string Yes Client-specified order identifier
wallet string No Polygon address of placing wallet
time integer No Timestamp of initial order processing by the matching engine
status string No Current order status, see values
errorCode string Yes Error short code explaining failed self-trade prevention condition if present
errorMessage string Yes Error description explaining failed self-trade prevention condition if present
type string No Order type, see values
side string No Order side, buy or sell
originalQuantity string Yes Original quantity specified by the order in base terms, omitted for market orders specified in quote terms
originalQuoteQuantity string Yes Original quantity specified by the order in quote terms, only present for market orders specified in quote terms
executedQuantity string No Quantity that has been executed in base terms
cumulativeQuoteQuantity string Yes Cumulative quantity that has been spent (buy orders) or received (sell orders) in quote terms, omitted if unavailable for historical orders
avgExecutionPrice string Yes Weighted average price of fills associated with the order; only present with fills
price string Yes Original price specified by the order in quote terms, omitted for all market orders
stopPrice string Yes Stop loss or take profit price, only present for stopLoss, stopLossLimit, takeProfit, and takeProfitLimit orders
timeInForce string Yes Time in force policy, see values, only present for limit orders
selfTradePrevention string No Self-trade prevention policy, see values
fills array Yes Array of order fill objects

Order Fill Array Objects

Field Type Optional Description
fillId string No Fill identifier
price string No Price of the fill in quote terms
quantity string No Total quantity of the fill in base terms
quoteQuantity string No Total quantity of the fill in quote terms
orderBookQuantity string Yes Order book-supplied quantity of the fill in base terms, omitted for pool fills
orderBookQuoteQuantity string Yes Order book-supplied quantity of the fill in quote terms, omitted for pool fills
poolQuantity string Yes Liquidity pool-supplied quantity of the fill in base terms, omitted for orderBook fills
poolQuoteQuantity string Yes Liquidity pool-supplied quantity of the fill in quote terms, omitted for orderBook fills
time integer No Timestamp of the fill
makerSide string No Maker side of the fill, buy or sell
sequence integer No Fill sequence number
fee string No Fee amount collected on the fill
feeAsset string No Symbol of asset in which fees collected
gas string Yes Amount collected to cover trade settlement gas costs, only present for taker
liquidity string No Whether the fill is the maker or taker in the trade from the perspective of the requesting API account, maker or taker
type string No Fill type, see values
txId string No Transaction id of the trade settlement transaction or null if not yet assigned
txStatus string No Status of the trade settlement transaction, see values

Test Create Order

Tests order creation and validation without submitting an order to the matching engine. This endpoint is for testing only. Orders submitted to this endpoint are never processed by the matching engine, added to an order book, or generate trades.

Request Parameters

This endpoint uses the same request parameters as Create Order.

Response Object

For successfully validated orders, this endpoint returns an empty JSON object. For orders that result in a validation failure, this endpoint returns a standard error response with code and message fields.

Cancel Order

Cancel a single open order, all open orders for a market, or all open orders placed by a wallet.

Request Parameters

Sample cancel order request payload

{
    "parameters": {
        "nonce": "91f460c0-9ee6-11ea-9026-c1542192a384",
        "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "orderId": "3a9ef9c0-a779-11ea-907d-23e999279287"
    },
    "signature": "<Wallet signature>"
}
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Placing wallet address
orderId string No None Single orderId or clientOrderId to cancel; prefix client-provided ids with client:
market string No None Symbol of the market from which to cancel all open orders for the wallet

Response Array Object

JSON response

[
    {
        "orderId": "3a9ef9c0-a779-11ea-907d-23e999279287"
    },
    ...
]
Field Type Description
orderId string Exchange-assigned order identifier

Order cancelation requests are made on a best-effort basis and are not guaranteed to succeed. There are several scenarios in which cancels can fail.

Get Orders

Returns information about open and past orders.

Request Parameters

$ curl "https://api-matic.idex.io/v1/orders?nonce=924e67a0-9ee6-11ea-816d-3d27597be6b7&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d&market=ETH-USDC" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Placing wallet address
orderId string No None Single orderId or clientOrderId to return; prefix client-provided ids with client:
market string No None Symbol of the market from which to query orders for the wallet, only applies if orderId is absent
closed boolean No false false only returns active orders on the order book; true only returns orders that are no longer on the order book and resulted in at least one fill; only applies if orderId is absent
start integer No None Timestamp of the earliest (oldest) order, inclusive, only applies if orderId is absent
end integer No None Timestamp of the latest (newest) order, inclusive, only applies if orderId is absent
limit integer No 50 Maximum number of data points to return, 1-1,000, only applies if orderId is absent
fromId string No None orderId of the earliest (oldest) order, only applies if orderId is absent

Response

This endpoint responds with either a single standard order response object, or an array of standard order response objects.

Get Fills

Returns information about trades involving orders placed by a wallet. Both this endpoint and the Trades endpoint return trade objects, but this endpoint includes additional private fields in its response. In this documentation, "trades" refers to public information about trades, whereas "fills" refers to detailed non-public information about trades resulting from orders placed by the API account.

Request Parameters

$ curl "https://api-matic.idex.io/v1/fills?nonce=92ba6fe0-9ee6-11ea-8a50-ad909d142fe6&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d&market=ETH-USDC" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Placing wallet address
fillId string No None Single fillId to return
market string No None Symbol of the market from which to query fills for the wallet, only applies if fillId is absent
start integer No None Timestamp of the earliest (oldest) fill, inclusive, only applies if fillId is absent
end integer No None Timestamp of the latest (newest) fill, inclusive, only applies if fillId is absent
limit integer No 50 Maximum number of fills to return, 1-1,000, only applies if fillId is absent
fromId string No None fillId of the earliest (oldest) fill, only applies if fillId is absent

Response Array Objects

JSON response

[
    {
        "fillId": "974480d0-a776-11ea-895b-bfcbb5bdaa50",
        "price": "202.00150000",
        "quantity": "3.78008801",
        "quoteQuantity": "763.58344815",
        "orderBookQuantity": "3.50000000",
        "orderBookQuoteQuantity": "707.00700000",
        "poolQuantity": "0.28008801",
        "poolQuoteQuantity": "56.57644815",
        "time": 1590394200000,
        "makerSide": "sell",
        "sequence": 981372,
        "market": "ETH-USDC",
        "orderId": "92782120-a775-11ea-aa55-4da1cc97a06d",
        "side": "buy",
        "fee": "0.00756017",
        "feeAsset": "ETH",
        "liquidity": "taker",
        "type": "hybrid",
        "txId": "0x01d28c33271cf1dd0eb04249617d3092f24bd9bad77ffb57a0316c3ce5425158",
        "txStatus": "mined"
    },
    ...
]
Field Type Optional Description
fillId string No Fill identifier
price string No Price of the fill in quote terms
quantity string No Quantity of the fill in base terms
quoteQuantity string No Quantity of the fill in quote terms
orderBookQuantity string Yes Order book-supplied quantity of the fill in base terms, omitted for pool fills
orderBookQuoteQuantity string Yes Order book-supplied quantity of the fill in quote terms, omitted for pool fills
poolQuantity string Yes Liquidity pool-supplied quantity of the fill in base terms, omitted for orderBook fills
poolQuoteQuantity string Yes Liquidity pool-supplied quantity of the fill in quote terms, omitted for orderBook fills
time integer No Timestamp of the fill
makerSide string No Maker side of the fill, buy or sell
sequence integer No Fill sequence number
market string No Market symbol
orderId string No Exchange-assigned order identifier
clientOrderId string Yes Client-specified order identifier
side string No Orders side, buy or sell
fee string No Fee amount collected on the fill
feeAsset string No Symbol of asset in which fees collected
gas string Yes Amount collected to cover trade settlement gas costs, only present for taker
liquidity string No Whether the fill is the maker or taker in the trade from the perspective of the requesting API account, maker or taker
type string No Fill type, see values
txId string No Transaction id of the trade settlement transaction or null if not yet assigned
txStatus string No Status of the trade settlement transaction, see values

Deposit Endpoints

Deposit Funds

Funds are deposited on IDEX via calls to the exchange smart contract rather than REST API endpoints. There are slightly different procedures for depositing MATIC and for depositing other ERC-20 tokens.

Exchange Contract (Polygon mainnet): 0x3253A7e75539EdaEb1Db608ce6Ef9AA1ac9126B6

ABIs for interacting with the exchange contracts are available in the official JavaScript SDK repo.

Deposit MATIC

const fs = require("fs");
const ethers = require("ethers");

async function deposit() {
  const idexAddress = "<IDEX exchange contract address>";
  const tokenAddress = "<ERC-20 token contract address>";
  const txOptions = { gasPrice: ethers.utils.parseUnits("<Gas price in gwei>", "gwei") };

  // Connect a wallet to mainnet
  const provider = new ethers.providers.JsonRpcProvider("<Polygon RPC>");
  const walletWithProvider = new ethers.Wallet("<Polygon wallet private key>", provider);

  // Load contracts
  // FaucetToken.abi.json and Exchange.abi.json may be found in the IDEX JavaScript SDK repo:
  // https://github.com/idexio/idex-sdk-js/blob/main/contracts/
  const erc20Abi = JSON.parse(fs.readFileSync("FaucetToken.abi.json"));
  const erc20Contract = new ethers.Contract(tokenAddress, erc20Abi, walletWithProvider);
  const idexAbi = JSON.parse(fs.readFileSync("Exchange.abi.json"));
  const idexContract = new ethers.Contract(idexAddress, idexAbi, walletWithProvider);

  // Deposit ERC-20 token
  const depositAmount = ethers.utils.bigNumberify("10000000000000000000");
  console.log("Depositing Token...")
  const approveTokenTx = await erc20Contract.approve(idexAddress, depositAmount, txOptions);
  console.log(`Dispatched approve ${approveTokenTx.hash} awaiting mine...`);
  await approveTokenTx.wait();
  console.log("Mined");
  const depositTokenTx = await idexContract.depositTokenByAddress(tokenAddress, depositAmount, txOptions);
  console.log(`Dispatched deposit ${depositTokenTx.hash} awaiting mine...`);
  await depositTokenTx.wait();
  console.log("Mined");

  // Deposit MATIC
  txOptions.value = ethers.utils.parseEther("10.0"); // Specify deposit amount as msg.value
  console.log("Depositing MATIC...")
  const depositEthTx = await idexContract.depositEther(txOptions);
  console.log(`Dispatched ${depositEthTx.hash} awaiting mine...`);
  await depositEthTx.wait();
  console.log("Mined");
}

deposit();

Call depositEther on the IDEX exchange contract with the amount to deposit included as the transaction value. Despite running on Polygon, the IDEX v3 exchange contract implements a depositEther function in order to maintain identical ABIs between blockchains.

Deposit Tokens

Depositing ERC-20 token assets requires two function calls.

  1. Call approve on the ERC-20 contract, with the IDEX exchange contract as the spender and the quantity to deposit as the amount.
  2. Call depositTokenByAddress or depositTokenBySymbol on the IDEX exchange contract with the same amount to deposit.

The exchange contract implements two token deposit functions. To specify the token to deposit by its contract address, use depositTokenByAddress. To specify the token to deposit by its symbol, use depositTokenBySymbol.

Details

Get Deposits

Returns information about deposits made by a wallet.

Request Parameters

$ curl "https://api-matic.idex.io/v1/deposits?nonce=931d0240-9ee6-11ea-916a-4520a9090bcd&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d&asset=USDC" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Depositing wallet address
depositId string No None Single depositId to return
asset string No None Asset symbol to query for deposits, only applies if depositId is absent
start integer No None Timestamp of the earliest (oldest) deposit, inclusive, only applies if depositId is absent
end integer No None Timestamp of the latest (newest) deposit, inclusive, only applies if depositId is absent
limit integer No 50 Maximum number of deposits to return, 1-1,000, only applies if depositId is absent
fromId string No None depositId of the earliest (oldest) deposit, only applies if depositId is absent

Response Array Objects

JSON response

[
    {
        "depositId": "57f88930-a6c7-11ea-9d9c-6b2dc98dcc67",
        "asset": "USDC",
        "quantity": "25000.00000000",
        "txId": "0xf3299b8222b2977fabddcf2d06e2da6303d99c976ed371f9749cb61514078a07",
        "txTime": 1590393900000,
        "confirmationTime": 1590394050000
    },
    ...
]
Field Type Description
depositId string Deposit identifier
asset string Symbol of the deposited asset
quantity string Quantity of the deposit
txId string Transaction id of the deposit transaction
txTime integer Timestamp of the deposit transaction
confirmationTime integer Timestamp of crediting the deposited funds on the exchange

Withdrawal Endpoints

Withdraw Funds

Withdraw funds from the exchange. Unlike deposits, withdrawals are initiated via this REST API endpoint. Once the withdrawal is validated, IDEX automatically dispatches the resulting Polygon transaction to return funds to the wallet.

Request Parameters

Sample withdraw request payload

{
    "parameters": {
        "nonce": "93dd1df0-9ee6-11ea-a40b-3148146b6ce3",
        "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "asset": "USDC",
        "quantity": "1000.00000000"
    },
    "signature": "<Wallet signature>"
}
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Depositing wallet address
asset string No None Symbol of asset to withdraw, exclusive with assetContractAddress
assetContractAddress string No None Token contract address of asset to withdraw, exclusive with asset
quantity string Yes None Quantity to withdraw

Response Object

Standard withdrawal JSON response

[
    {
        "withdrawalId": "3ac67790-a77c-11ea-ae39-b3356c7170f3",
        "asset": "USDC",
        "assetContractAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
        "quantity": "25000.00000000",
        "time": 1590394800000,
        "fee": "0.14332956",
        "txId": "0xf215d7a6d20f6dda52cdb3a3332aa5de898dead06f92f4d26523f140ae5dcc5c",
        "txStatus": "mined"
    },
    ...
]
Field Type Description
withdrawalId string Exchange-assigned withdrawal identifier
asset string Symbol of the withdrawn asset
assetContractAddress string Token contract address of withdrawn asset
quantity string Quantity of the withdrawal
time integer Timestamp of withdrawal API request
fee string Amount deducted from withdrawal to cover IDEX-paid gas
txId string Transaction id of the withdrawal transaction or null if not yet assigned
txStatus string Status of the withdrawal transaction, see values

Get Withdrawals

Returns information about withdrawals to a wallet.

Request Parameters

$ curl "https://api-matic.idex.io/v1/withdrawals?nonce=937a1660-9ee6-11ea-b492-c9d43244f49c&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d&asset=USDC" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Withdrawing wallet address
withdrawalId string No None Single withdrawalId to return
asset string No None Asset symbol to query for withdrawals, only applies if withdrawalId is absent, exclusive with assetContractAddress
assetContractAddress string No None Token contract address to query for withdrawals, only applies if withdrawalId is absent, exclusive with asset
start integer No None Timestamp of the earliest (oldest) withdrawal, inclusive, only applies if withdrawalId absent
end integer No None Timestamp of the latest (newest) deposit, inclusive, only applies if withdrawalId is absent
limit integer No 50 Maximum number of deposits to return, 1-1,000, only applies if withdrawalId is absent
fromId string No None withdrawalId of the earliest (oldest) deposit, only applies if withdrawalId is absent

Response

This endpoint responds with either a single standard withdrawal response object, or an array of standard withdrawal response objects.

Exit Wallet

const fs = require("fs");
const ethers = require("ethers");

async function exitWallet() {
  const idexAddress = "<IDEX exchange contract address>";
  const txOptions = { gasPrice: ethers.utils.parseUnits("<Gas price in gwei>", "gwei") };

  // Connect a wallet to mainnet
  const provider = new ethers.providers.JsonRpcProvider("<Polygon RPC>");
  const walletWithProvider = new ethers.Wallet("<Polygon wallet private key>", provider);

  // Load contract
  const idexAbi = JSON.parse(fs.readFileSync("idex.abi.json"));
  const idexContract = new ethers.Contract(idexAddress, idexAbi, walletWithProvider);

  console.log("Exiting wallet...")
  const exitWalletTx = await idexContract.exitWallet(txOptions);
  console.log(`Dispatched exit ${exitWalletTx.hash} awaiting mine...`);
  const withdrawExitTx = await idexContract.withdrawExit("<Token contract address>", txOptions);
  console.log(`Dispatched withdraw ${withdrawExitTx.hash} awaiting mine...`);
  await Promise.all([exitWalletTx.wait(), withdrawExitTx.wait()]);
  console.log("Mined");
}

exitWallet();

While the Withdraw Funds REST API endpoint is the standard way to withdraw funds from the exchange, the exchange smart contract also includes a direct withdrawal mechanism. Funds can always be withdrawn directly from the contract, even if IDEX is offline or otherwise unresponsive.

Exchange Contract (Polygon mainnet): 0x3253A7e75539EdaEb1Db608ce6Ef9AA1ac9126B6

ABIs for interacting with the exchange contracts are available in the official JavaScript SDK repo.

Exit Withdrawals require several smart contract function calls.

  1. Call the exitWallet function on the IDEX exchange contract. All future deposits, trades, and liquidity additions and removals are blocked. Any open orders associated with the wallet are cleared from the order books, and any liquidity provider (LP) tokens held as exchange balances are liquidated.
  2. Wait at least 1 hour for any in-flight settlement transactions to mine.
  3. Call the withdrawExit function with the token contract address of the asset to withdraw. The exchange contract transfers the wallet’s full exchange balance of the specified asset back to the wallet.
  4. Repeat 3 for all wallet assets held on the exchange.

Liquidity Endpoints

Get Liquidity Pools

Returns information about liquidity pools supported by the exchange.

Request Parameters

$ curl "https://api-matic.idex.io/v1/liquidityPools"
Parameter Type Required Default Description
market string No None Target market, exclusive with tokenA and tokenB
tokenA string No None Address of one reserve token, exclusive with market
tokenB string No None Address of one reserve token, exclusive with market

Response Object

JSON response

{
    "tokenA": "0x0000000000000000000000000000000000000000",
    "tokenB": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "reserveA": "28237086108150291001205",
    "reserveB": "5647417229283",
    "liquidityToken": "0x041B70bf48cfF1a7d3E87297D9F13772f11ed764",
    "totalLiquidity": "399332701245168000",
    "reserveUsd": "11294834.44",
    "market": "ETH-USDC"
}
Field Type Description
tokenA string Address of one reserve token
tokenB string Address of one reserve token
reserveA string Quantity of token A held as reserve in token precision, not normalized precision
reserveB string Quantity of token B held as reserve in token precision, not normalized precision
liquidityToken string Address of the liquidity provider (LP) token
totalLiquidity string Total quantity of liquidity provider (LP) tokens minted in token precision, not normalized precision
reserveUsd string Total value of reserves in USD
market string Market symbol of pool’s associated hybrid market

Add Liquidity

Add liquidity to a hybrid liquidity pool from assets held by a wallet on the exchange. Adding liquidity is also supported via a smart contract function call on the IDEX exchange contract.

Request Parameters

Sample add liquidity request payload

{
    "parameters": {
        "nonce": "7e4a6810-15a7-11ec-85d3-a5ac3bcfe3ca",
        "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "tokenA": "0x0000000000000000000000000000000000000000",
        "tokenB": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
        "amountADesired": "2499999996612190000",
        "amountBDesired": "500000000",
        "amountAMin": "2487499996629130000",
        "amountBMin": "497500000",
        "to": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d"
    },
    "signature": "<Wallet signature>"
}
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Adding wallet address
tokenA string Yes None Address of one reserve token
tokenB string Yes None Address of one reserve token
amountADesired string Yes None Maximum amount of token A to add as liquidity in token precision, not normalized precision
amountBDesired string Yes None Maximum amount of token B to add as liquidity in token precision, not normalized precision
amountAMin string Yes None Minimum amount of token A to add as liquidity in token precision, not normalized precision
amountBMin string Yes None Minimum amount of token B to add as liquidity in token precision, not normalized precision
to string Yes None Wallet to credit resulting liquidity provider (LP) tokens; set to the Custody contract address to retain LP tokens as an exchange balance

Response Object

Standard liquidity addition JSON response

{
    "liquidityAdditionId": "f3fd2683-26e6-4475-88b5-3eeb088acd1f",
    "tokenA": "0x0000000000000000000000000000000000000000",
    "tokenB": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "amountA": "2499999996612190000",
    "amountB": "500000000",
    "liquidity": "35355339001212",
    "time": "1631656966432",
    "initiatingTxId": null,
    "feeTokenA": "1260000000000000",
    "feeTokenB": "252000",
    "txId": "0x39518147124286b97f4803171732aaa1bffea15f12b0474e7ab386bf5cdeda56",
    "txStatus": "mined"
}
Field Type Optional Description
liquidityAdditionId string No Exchange-assigned liquidity addition identifier; null if errorCode is present
tokenA string No Address of one added reserve token
tokenB string No Address of one added reserve token
amountA string No Quantity of token A added as liquidity in token precision, not normalized precision; null if errorCode is present
amountB string No Quantity of token B added as liquidity in token precision, not normalized precision; null if errorCode is present
liquidity string No Quantity of liquidity provided (LP) tokens minted in token precision, not normalized precision; null if errorCode is present
time integer No Timestamp of the processing of the liquidity addition; may be delayed from the transaction time of chain-initiated liquidity additions
initiatingTxId string No Transaction id of the on-chain transaction that initiated the liquidity addition; null for API-initiated additions
errorCode string Yes Error short code present on liquidity addition error
errorMessage string Yes Human-readable error message present on liquidity addition error
feeTokenA string No Quantity deducted from the liquidity addition to cover IDEX-paid gas in token precision, not normalized precision; null if errorCode is present
feeTokenB string No Quantity deducted from the liquidity addition to cover IDEX-paid gas in token precision, not normalized precision; null if errorCode is present
txId string No Transaction id of the liquidity addition settlement transaction; null if not yet assigned or errorCode is present
txStatus string No Status of the liquidity addition settlement transaction, see values; null if errorCode is present

Add Liquidity via Smart Contract Function Call

const fs = require("fs");
const ethers = require("ethers");

async function addLiquidity() {
  const idexAddress = "<IDEX exchange contract address>";
  const tokenAAddress = "<ERC-20 token contract address>";
  const tokenBAddress = "<ERC-20 token contract address>";
  const txOptions = { gasPrice: ethers.utils.parseUnits("<Gas price in gwei>", "gwei") };

  // Connect a wallet to mainnet
  const provider = new ethers.providers.JsonRpcProvider("<Polygon RPC>");
  const walletWithProvider = new ethers.Wallet("<Polygon wallet private key>", provider);

  // Load contracts
  const erc20Abi = JSON.parse(fs.readFileSync("erc20.abi.json"));
  const tokenAContract = new ethers.Contract(tokenAAddress, erc20Abi, walletWithProvider);
  const tokenBContract = new ethers.Contract(tokenBAddress, erc20Abi, walletWithProvider);
  const idexAbi = JSON.parse(fs.readFileSync("idex.abi.json"));
  const idexContract = new ethers.Contract(idexAddress, idexAbi, walletWithProvider);

  // Addition request parameters
  const tokenADesired = ethers.utils.bigNumberify("2499999996612190000");
  const tokenBDesired = ethers.utils.bigNumberify("500000000");  
  const tokenAMin = ethers.utils.bigNumberify("2487499996629130000");
  const tokenBMin = ethers.utils.bigNumberify("497500000");
  const toAddress = "<Polygon wallet address>";
  const deadline = Math.floor(Date.now()/1000) + (10 * 60); // 10 minutes

  // Approve ERC-20 tokens
  console.log("Approving Tokens...")
  const approveTokenATx = await tokenAContract.approve(idexAddress, tokenADesired, txOptions);
  console.log(`Dispatched approve ${approveTokenATx.hash} awaiting mine...`);
  const approveTokenBTx = await tokenBContract.approve(idexAddress, tokenBDesired, txOptions);
  console.log(`Dispatched approve ${approveTokenBTx.hash} awaiting mine...`);
  await Promise.all([approveTokenATx.wait(), approveTokenBTx.wait()]);
  console.log("Mined");
  // Add liquidity
  const addLiquidityTx = await idexContract.addLiquidity(
    tokenAAddress, tokenBAddress, tokenADesired, tokenBDesired, tokenAMin, tokenBMin, toAddress, deadline, txOptions
  );
  console.log(`Dispatched add liquidity ${addLiquidityTx.hash} awaiting mine...`);
  await addLiquidityTx.wait();
  console.log("Mined");
}

addLiquidity();

In addition to the REST API endpoint, IDEX v3 supports liquidity additions via smart contract function calls. Liquidity additions made via smart contract function calls are called chain-initiated liquidity additions, as opposed to API-initiated liquidity additions.

Exchange Contract (Polygon mainnet): 0x3253A7e75539EdaEb1Db608ce6Ef9AA1ac9126B6

ABIs for interacting with the exchange contracts are available in the official JavaScript SDK repo.

The exchange contract's addLiquidity and addLiquidityETH functions implement the same interface as most open-source Router contracts. Use addLiquidity when adding liquidity to a market between two ERC-20 tokens, and addLiquidityETH when adding liquidity to a market between an ERC-20 token and MATIC. IDEX v3's liquidity addition smart contract functions differ from most open-source implementations in a few important ways:

Adding liquidity requires two or three function calls.

  1. Call approve on one (in the case of an addition involving MATIC) or both ERC-20 contracts, with the IDEX exchange contract as the spender and the desired quantity as the amount.
  2. Call addLiquidity or addLiquidityETH on the IDEX exchange contract with the desired parameters to initiate the liquidity addition.

Remove Liquidity

Remove liquidity from a hybrid liquidity pool using liquidity provider (LP) tokens held by a wallet on the exchange. Removing liquidity is also supported via a smart contract function call on the IDEX exchange contract.

Request Parameters

Sample remove liquidity request payload

{
    "parameters": {
        "nonce": "7ed43180-15a7-11ec-85d3-a5ac3bcfe3ca",
        "wallet": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "tokenA": "0x0000000000000000000000000000000000000000",
        "tokenB": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
        "liquidity": "35355339001212",
        "amountAMin": "2487499996629130000",
        "amountBMin": "497500000",
        "to": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d"
    },
    "signature": "<Wallet signature>"
}
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Removing wallet address
tokenA string Yes None Address of one reserve token
tokenB string Yes None Address of one reserve token
liquidity string Yes None Quantity of liquidity provider (LP) tokens to burn in token precision, not normalized precision
amountAMin string Yes None Minimum amount of token A to remove as liquidity in token precision, not normalized precision
amountBMin string Yes None Minimum amount of token B to remove as liquidity in token precision, not normalized precision
to string Yes None Wallet to credit resulting reserve tokens; set to the Custody contract address to retain reserve tokens as exchange balances

Response Object

Standard liquidity removal JSON response

{
    "liquidityRemovalId": "e87083db-5f64-4fd8-a1ad-1b57a84840f7",
    "tokenA": "0x0000000000000000000000000000000000000000",
    "tokenB": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "amountA": "2499999996612190000",
    "amountB": "500000000",
    "liquidity": "35355339001212",
    "time": "1631656967341",
    "initiatingTxId": null,
    "feeTokenA": "1207500000000000",
    "feeTokenB": "241500",
    "txId": "0xfe48b79028a61d971672172874304283aaa6780ad38b9dc2d76c28fe7fd03002",
    "txStatus": "mined"
}
Field Type Optional Description
liquidityRemovalId string No Exchange-assigned liquidity removal identifier; null if errorCode is present
tokenA string No Address of one removed reserve token
tokenB string No Address of one removed reserve token
amountA string No Quantity of token A removed from liquidity in token precision, not normalized precision; null if errorCode is present
amountB string No Quantity of token B removed from liquidity in token precision, not normalized precision; null if errorCode is present
liquidity string No Quantity of liquidity provided (LP) tokens burned in token precision, not normalized precision
time integer No Timestamp of the processing of the liquidity removal; may be delayed from the transaction time of chain-initiated liquidity removals
initiatingTxId string No Transaction id of the on-chain transaction that initiated the liquidity removal; null for API-initiated removals
errorCode string Yes Error short code present on liquidity removal error
errorMessage string Yes Human-readable error message present on liquidity removal error
feeTokenA string No Quantity deducted from the liquidity removal to cover IDEX-paid gas in token precision, not normalized precision; null if errorCode is present
feeTokenB string No Quantity deducted from the liquidity removal to cover IDEX-paid gas in token precision, not normalized precision; null if errorCode is present
txId string No Transaction id of the liquidity removal settlement transaction; null if not yet assigned or errorCode is present
txStatus string No Status of the liquidity removal settlement transaction, see values; null if errorCode is present

Remove Liquidity via Smart Contract Function Call

const fs = require("fs");
const ethers = require("ethers");

async function removeLiquidity() {
  const idexAddress = "<IDEX exchange contract address>";
  const tokenAAddress = "<ERC-20 token contract address>";
  const tokenBAddress = "<ERC-20 token contract address>";
  const lpTokenAddress = "<ERC-20 token contract address>";
  const txOptions = { gasPrice: ethers.utils.parseUnits("<Gas price in gwei>", "gwei") };

  // Connect a wallet to mainnet
  const provider = new ethers.providers.JsonRpcProvider("<Polygon RPC>");
  const walletWithProvider = new ethers.Wallet("<Polygon wallet private key>", provider);

  // Load contracts
  const erc20Abi = JSON.parse(fs.readFileSync("erc20.abi.json"));
  const lpTokenContract = new ethers.Contract(lpTokenAddress, erc20Abi, walletWithProvider);
  const idexAbi = JSON.parse(fs.readFileSync("idex.abi.json"));
  const idexContract = new ethers.Contract(idexAddress, idexAbi, walletWithProvider);

  // Removal request parameters
  const liquidity = ethers.utils.bigNumberify("35355339001212");
  const tokenAMin = ethers.utils.bigNumberify("2487499996629130000");
  const tokenBMin = ethers.utils.bigNumberify("497500000");
  const toAddress = "<Polygon wallet address>";
  const deadline = Math.floor(Date.now()/1000) + (10 * 60); // 10 minutes

  // Remove liquidity
  console.log("Approving Tokens...")
  const approveLpTokenTx = await lpTokenContract.approve(idexAddress, liquidity, txOptions);
  console.log(`Dispatched approve ${approveLpTokenTx.hash} awaiting mine...`);
  await approveLpTokenTx.wait();
  console.log("Mined");
  const removeLiquidityTx = await idexContract.removeLiquidity(
    tokenAAddress, tokenBAddress, liquidity, tokenAMin, tokenBMin, toAddress, deadline, txOptions
  );
  console.log(`Dispatched remove liquidity ${removeLiquidityTx.hash} awaiting mine...`);
  await removeLiquidityTx.wait();
  console.log("Mined");
}

removeLiquidity();

In addition to the REST API endpoint, IDEX v3 supports liquidity removals via smart contract function calls. Liquidity removals made via smart contract function calls are called chain-initiated liquidity removals, as opposed to API-initiated liquidity removals.

Exchange Contract (Polygon mainnet): 0x3253A7e75539EdaEb1Db608ce6Ef9AA1ac9126B6

ABIs for interacting with the exchange contracts are available in the official JavaScript SDK repo.

The exchange contract's removeLiquidity and removeLiquidityETH functions implement the same interface as most open-source Router contracts. Use removeLiquidity when removing liquidity from a market between two ERC-20 tokens, and removeLiquidityETH when removing liquidity from a market between an ERC-20 token and MATIC. IDEX v3's liquidity removal smart contract functions differ from most open-source implementations in a few important ways:

Removing liquidity requires two function calls.

  1. Call approve on the LP token ERC-20 contract, with the IDEX exchange contract as the spender and the liquidity quantity as the amount.
  2. Call removeLiquidity or removeLiquidityETH on the IDEX exchange contract with the desired parameters to initiate the liquidity removal.

Get Liquidity Additions

Returns information about liquidity additions from a wallet.

Request Parameters

$ curl "https://api-matic.idex.io/v1/liquidityAdditions?nonce=7fd8d040-15a7-11ec-85d3-a5ac3bcfe3ca&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Wallet address
liquidityAdditionId string No None Single liquidityAdditionId to return; exclusive with initiatingTxId
initiatingTxId string No None Transaction id of the Exchange contract addLiquidity or addLiquidityETH call transaction, only applies to chain-initiated liquidity additions; exclusive with liquidityAdditionId
start integer No None Timestamp of the earliest (oldest) liquidity addition, inclusive, only applies if liquidityAdditionId and initiatingTxId are absent
end integer No None Timestamp of the latest (newest) liquidity addition, inclusive, only applies if liquidityAdditionId and initiatingTxId are absent
limit integer No 50 Maximum number of liquidity additions to return, 1-1,000, only applies if liquidityAdditionId and initiatingTxId are absent
fromId string No None liquidityAdditionId of the earliest (oldest) liquidity addition, only applies if liquidityAdditionId and initiatingTxId are absent

Response

This endpoint responds with either a single standard liquidity addition response object, or an array of standard liquidity addition response objects.

Get Liquidity Removals

Returns information about liquidity removals from a wallet.

Request Parameters

$ curl "https://api-matic.idex.io/v1/liquidityRemovals?nonce=807a4060-15a7-11ec-85d3-a5ac3bcfe3ca&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Wallet address
liquidityRemovalId string No None Single liquidityRemovalId to return; exclusive with initiatingTxId
initiatingTxId string No None Transaction id of the Exchange contract removeLiquidity or removeLiquidityETH call transaction, only applies to chain-initiated liquidity removals; exclusive with liquidityRemovalId
start integer No None Timestamp of the earliest (oldest) liquidity removal, inclusive, only applies if liquidityRemovalId and initiatingTxId are absent
end integer No None Timestamp of the latest (newest) liquidity removal, inclusive, only applies if liquidityRemovalId and initiatingTxId are absent
limit integer No 50 Maximum number of liquidity removals to return, 1-1,000, only applies if liquidityRemovalId and initiatingTxId are absent
fromId string No None liquidityRemovalId of the earliest (oldest) liquidity removal, only applies if liquidityRemovalId and initiatingTxId are absent

Response

This endpoint responds with either a single standard liquidity removal response object, or an array of standard liquidity removal response objects.

WebSocket Authentication Endpoints

Get Authentication Token

Returns a single-use authentication token for access to private subscriptions in the WebSocket API.

Request Parameters

$ curl "https://api-matic.idex.io/v1/wsToken?nonce=9436afa0-9ee6-11ea-8a53-71994564322f&wallet=0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d" \
    -H "IDEX-API-KEY: <API key>" \
    -H "IDEX-HMAC-SIGNATURE: <HMAC signature>"
Parameter Type Required Default Description
nonce string Yes None Request nonce
wallet string Yes None Target wallet address

Response Object

JSON response

{
    "token": "<WebSocket authentication token>"
}
Field Type Description
token string WebSocket subscription authentication token

WebSocket API Interaction

The IDEX WebSocket API provides the most up-to-date public market and authenticated user data. It is the recommended integration point for time-sensitive applications.

URL

Polygon WebSocket API: wss://websocket-matic.idex.io/v1

IDEX’s data centers are in the AWS Europe (Ireland) eu-west-1 region.

Frame Encoding

Frames sent from the server include at least one JSON object with two top-level keys:

The server may send more than one JSON object in a single frame. The data object uses case-sensitive one or two-letter keys that map to equivalent REST API response object fields.

Subscriptions

Subscriptions specify which data is pushed to the client. Clients can subscribe either at connection time, via the supplied path, or by sending subscription message frames once connected.

Path Subscriptions

To subscribe to the tickers subscription for the ETH-USDC via connection path:

$ wscat -c wss://websocket-matic.idex.io/v1/ETH-USDC@tickers

Path subscriptions are a quick and easy way to start receiving push updates. The WebSocket API interprets the URL path supplied at connection time to set an initial subscription.

Path subscription notation: wss://websocket-{blockchain}.idex.io/v1/{market}@{subscription}_{option}

For example, to connect to the WebSocket API and start receiving tickers updates for the ETH-USDC market, connect to wss://websocket-matic.idex.io/v1/ETH-USDC@tickers. For subsciptions that require option parameters, such as candles, use the option notation wss://websocket-matic.idex.io/v1/ETH-USDC@candles_15m.

Only a single, non-authenticated subscription may be included in the path.

Frame Subscriptions

Sample subscribe frame for 1 minute candles for the ETH-USDC market:

{
    "method": "subscribe",
    "subscriptions": [
        {
            "name": "candles",
            "markets": ["ETH-USDC"],
            "interval": "1m"
        }
    ]
}

There is also a shorthand for subscribe frames where markets are specified at the top level, resulting in subscriptions for all listed markets.

{
    "method": "subscribe",
    "markets": ["ETH-USDC", "IDEX-ETH"],
    "subscriptions": [
        "tickers",
        "trades"
    ]
}

Mixing both formats is valid, in which case, the markets defined at the subscription level take precedence.

{
    "method": "subscribe",
    "markets": ["ETH-USDC", "IDEX-ETH"],
    "subscriptions": [
        "tickers",
        "trades",
        {
            "name": "candles",
            "markets": ["ETH-USDC"],
            "interval": "1m"
        }
    ]
}

In the above example, a candles subscription applies only to the ETH-USDC market.

Clients can subscribe, unsubscribe, and list any subscriptions by sending method frames.

Subscribe Request

After connecting, clients can initiate subscriptions by sending a subscribe frame. subscribe frames specify the requested subscriptions, applicable markets, and any subscription-specific options.

Request Frame Fields

Parameter Type Required Default Description
cid string No None Customer-supplied request identifier; this value is included in response frames to the request if specified
method string Yes None Subscription action, subscribe
token string No None Authentication token, only required for Balances and Orders subscriptions
markets array No None Array of market symbols to apply to the specified subscriptions
subscriptions array Yes None Array of subscription objects

Subscription Request Object Fields

Parameter Type Required Default Description
name string Yes None Subscription name
markets array No None Array of market symbols for the subscription, optional if markets is defined at the top level
* Any additional options specific to the subscription

Unsubscribe Request

{
    "method": "unsubscribe",
    "markets": ["IDEX-ETH"],
    "subscriptions": [
        "tickers",
        "trades"
    ]
}

unsubscribe requests follow the same format as subscribe, but with additional flexibility. If the top-level markets parameter is omitted, any listed subscriptions without specified markets are removed from all markets. If the top-level subscriptions field is omitted, the top-level markets are removed from all subscriptions. Listing neither markets nor subscriptions at the top level unsubscribes all.

unsubscribe requests receive the standard frame subscription response.

List Subscriptions Request

Returns the connection’s active subscriptions.

Request Frame Fields

{
    "method": "subscriptions"
}
Parameter Type Required Default Description
cid string No None Customer-supplied request identifier; this value is included in response frames to the request
method string Yes None List subscriptions action, subscriptions

Frame Subscription Response

Standard subscription response frame. The response to subscribe requests includes all active subscriptions.

{
    "type": "subscriptions",
    "subscriptions": [
        {
            "name": "tickers",
            "markets": [ 
              "ETH-USDC",
              "IDEX-ETH"
            ]
        },
        {
            "name": "trades",
            "markets": [ 
              "ETH-USDC",
              "IDEX-ETH"
            ]
        },
        {
            "name": "candles",
            "markets": ["ETH-USDC"],
            "interval": "1m"
        }
    ]
}

All subscribe, unsubscribe, and subscriptions requests return a standard response frame that enumerates active subscriptions.

Response Frame Fields

Field Type Description
cid string Customer-supplied request identifier, only included if specified in the request
type string Frame type, always subscriptions
subscriptions array Array of subscription response objects

Subscription Response Object Fields

Field Type Description
name string Subscription name
markets array Array of market symbols for the subscription
* Any additional options specific to the subscription

Authenticated Subscriptions

{
    "method": "subscribe",
    "token": "<WebSocket authentication token>",
    "subscriptions": ["balances"]
}

User authentication is required for the Balances and Orders subscriptions. Authentication is specified on a per-subscribe basis via a single-use authentication token.

Tokens are generated via the Get Authentication Token endpoint and are valid for 15 minutes, good for a one-time subscription request to an arbitrary number of subscriptions within a single subscribe, and good for the life of the subscription

Connection Maintenance

The WebSocket API includes several mechanisms to reduce stale connections.

Errors

{
    "type": "error",
    "data": {
        "code": "<Error short code>",
        "message": "<Error message>"
    }
}

Errors are only expected in response to invalid client subscription requests. Error frames use type error and include both code, a machine-readable error short code, and message, a longer human-readable error description.

WebSocket Subscriptions

Ping

Tests connectivity to the WebSocket API. All clients are automatically subscribed to Ping on connection.

Message Object

{
    "type": "ping",
    "data": {}
}

Empty JSON object

Tickers

Provides ticker data updates for a market.

Message Object

{
    "type": "tickers",
    "data": {
        "m": "ETH-USDC",
        "t": 1590408000000,
        "o": "202.11928302",
        "h": "207.58100029",
        "l": "201.85600392",
        "c": "206.00192301",
        "Q": "9.50000000",
        "v": "11297.01959248",
        "q": "2327207.76033252",
        "P": "1.92",
        "n": 14201,
        "a": "206.00207150",
        "b": "206.00084721",
        "u": 848728
    }
}
Field Inflated Field Type Description
m market string Market symbol
t time integer Timestamp when the statistics were computed, the opening time of the period is 24 hours prior
o open string Price of the first trade in the period in quote terms
h high string Highest traded price in the period in quote terms
l low string Lowest traded price in the period in quote terms
c close string Price of the last trade in the period in quote terms
Q closeQuantity string Quantity of the last trade in th period in base terms
v baseVolume string Trailing 24-hour trading volume in base terms
q quoteVolume string Trailing 24-hour trading volume in quote terms
P percentChange string Percentage change from open price to close price
n numTrades integer Number of trades in the period
a ask string Best ask price on the order book in quote terms
b bid string Best bid price on the order book in quote terms
u sequence integer Fill sequence number of the last trade in the period

Candles

Provides candle (OHLCV) data updates for a market.

Message Object

{
    "type": "candles",
    "data": {
        "m": "ETH-USDC",
        "t": 1590393183000,
        "i": "5m",
        "s": 1590393000000,
        "e": 1590393300000,
        "o": "202.11928302",
        "h": "202.98100029",
        "l": "201.85600392",
        "c": "202.50192301",
        "v": "39.22576247",
        "n": 103,
        "u": 848678
    }
}
Field Inflated Field Type Description
m market string Market symbol
t time integer Timestamp when the statistics were computed, time is always between the start and end timestamps of the interval
i interval string Interval duration, see Interval Values
s start integer Timestamp of the start of the interval
e end integer Timestamp of the end of the interval
o open string Price of the first trade in the interval in quote terms
h high string Highest traded price in the interval in quote terms
l low string Lowest traded price in the interval in quote terms
c close string Price of the last trade in the interval in quote terms
v volume string Trading volume in the interval in base terms
n numTrades integer Number of trades in the candle
u sequence integer Fill sequence number of the last trade in the interval

Trades

Provides real-time trade data for a market. In this documentation, "trades" refers to public information about trades, whereas "fills" refers to detailed non-public information about trades resulting from orders placed by the API account.

Message Object

{
    "type": "trades",
    "data": {
        "m": "ETH-USDC",
        "i": "a0b6a470-a6bf-11ea-90a3-8de307b3b6da",
        "p": "202.74900000",
        "q": "10.00000000",
        "Q": "2027.49000000",
        "t": 1590394500000,
        "s": "sell",
        "y": "hybrid",
        "u": 848778
    }
}
Field Inflated Field Type Description
m market string Market symbol
i fillId string Trade identifier
p price string Price of the trade in quote terms
q quantity string Quantity of the trade in base terms
Q quoteQuantity string Quantity of the trade in quote terms
t time integer Timestamp of the trade
s makerSide string Maker side of the trade, buy or sell
y type string Trade type, see values
u sequence integer Fill sequence number of the trade

L1 Order Book

Provides real-time level-1 order book data for a market. Level-1 order book data is limited to the best bid and ask for a market, including hybrid liquidity synthetic price levels.

Message Object

{
    "type": "l1orderbook",
    "data": {
        "m": "ETH-USDC",
        "t": 1590393480000,
        "b": "202.00200000",
        "B": "13.88204000",
        "a": "202.01000000",
        "A": "8.11400000",
        "p": {
            "q": "28237.08610815", 
            "Q": "5703947.86801900"
        }
    }
}
Field Inflated Field Type Description
m market string Market symbol
t time integer Timestamp of the order book update
b bidPrice string Best bid price
B bidQuantity string Quantity available at the best bid price
a askPrice string Best ask price
A askQuantity string Quantity available at the best ask price
p pool object Reserve quantities of the market's liquidity pool as an object, null if hybrid liquidity is not available or active on the market

Pool Object

Field Inflated Field Type Description
q baseReserveQuantity string Base reserve quantity in normalized precision
Q quoteReserveQuantity string Quote reserve quantity in normalized precision

L2 Order Book

Provides real-time level-2 order book data for a market. Level-2 order book data includes price and quantity information for all limit order price levels in the order book but does not include hybrid liquidity synthetic price levels. Pool reserve quantity changes are included instead, however, providing the necessary data to compute synthetic price levels in real time by the client.

Message Object

{
    "type": "l2orderbook",
    "data": {
        "m": "ETH-USDC",
        "t": 1590393540000,
        "u": 71228110,
        "b": [["202.00100000", "10.00000000", 1]],
        "a": [],
        "p": {
            "q": "28237.08610815", 
            "Q": "5703947.86801900"
        }
    }
}
Field Inflated Field Type Description
m market string Market symbol
t time integer Timestamp of the order book update
u sequence integer Order book update sequence number of the update
b bids array Array of bid price level updates
a asks array Array of ask price level updates
p pool object Reserve quantities of the market's liquidity pool as an object, null if hybrid liquidity is not available or active on the market

Balances

Provides real-time deposit and withdrawal balance change information for a wallet.

Message Object

{
    "type": "balances",
    "data": {
        "w": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "a": "USDC",
        "q": "38192.94678100",
        "f": "26710.66678121",
        "l": "11482.28000000",
        "d": "38188.22"
    }
}
Field Inflated Field Type Description
w wallet string Target wallet address
a asset string Asset symbol
q quantity string Total quantity of the asset held by the wallet on the exchange
f availableForTrade string Quantity of the asset available for trading; quantity - locked
l locked string Quantity of the asset held in trades on the order book
d usdValue string Total value of the asset held by the wallet on the exchange in USD

Orders

Provides real-time updates on orders issued by a wallet. This subscription includes granular updates for all order-related activity, including placement, cancelation, fills and stop triggers. Detailed order execution information is only available to the placing wallet. In this documentation, "trades" refers to public information about trades, whereas "fills" refers to detailed non-public information about trades resulting from orders placed by the API account.

Message Object

{
    "type": "orders",
    "data": {
        "m": "ETH-USDC",
        "i": "92782120-a775-11ea-aa55-4da1cc97a06d",
        "w": "0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d",
        "t": 1590394200000,
        "T": 1590394200000,
        "x": "fill",
        "X": "filled",
        "u": 71228108,
        "o": "market",
        "S": "buy",
        "Q": "1000.00000000",
        "z": "4.95044603",
        "Z": "1000.00000000",
        "v": "202.00200000",
        "F": [
            {
                "i": "974480d0-a776-11ea-895b-bfcbb5bdaa50",
                "p": "202.00150000",
                "q": "3.78008801",
                "Q": "763.58344815",
                "oq": "3.50000000",
                "oQ": "707.00700000",
                "pq": "0.28008801",
                "pQ": "56.57644815",
                "t": 1590394200000,
                "s": "sell",
                "u": 981372,
                "f": "0.00756017",
                "a": "ETH",
                "l": "taker",
                "y": "hybrid",
                "T": "0x01d28c33271cf1dd0eb04249617d3092f24bd9bad77ffb57a0316c3ce5425158",
                "S": "mined"
            },
            ...
        ]
    }
}
Field Inflated Field Type Optional Description
m market string No Market symbol
i orderId string No Exchange-assigned order identifier
c clientOrderId string Yes Client-specified order identifier
w wallet string No Polygon address of placing wallet
t executionTime integer No Timestamp of the most recent update
T time integer No Timestamp of initial order processing by the matching engine
x update string No Type of order update, see values
X status string No Order status, see values
u sequence integer Yes order book update sequence number, only included if update type triggers an order book update
o type string No Order type, see values
S side string No Order side, buy or sell
q originalQuantity string Yes Original quantity specified by the order in base terms, omitted for market orders specified in quote terms
Q originalQuoteQuantity string Yes Original quantity specified by the order in quote terms, only present for market orders specified in quote terms
z executedQuantity string No Quantity that has been executed in base terms
Z cumulativeQuoteQuantity string Yes Cumulative quantity that has been spent (buy orders) or received (sell orders) in quote terms, omitted if unavailable for historical orders
v avgExecutionPrice string Yes Weighted average price of fills associated with the order; only present with fills
p price string Yes Original price specified by the order in quote terms, omitted for all market orders
P stopPrice string Yes Stop loss or take profit price, only present for stopLoss, stopLossLimit, takeProfit, and takeProfitLimit orders
f timeInForce string Yes Time in force policy, see values, only present for limit orders
V selfTradePrevention string No Self-trade prevention policy, see values
F fills array Yes Array of order fill objects

Fills Array Objects

Field Inflated Field Type Description
i fillId string Fill identifier
p price string Price of the fill in quote terms
q quantity string Quantity of the fill in base terms
Q quoteQuantity string Quantity of the fill in quote terms
oq orderBookQuantity string Optional. Order book-supplied quantity of the fill in base terms, omitted for pool fills
oQ orderBookQuoteQuantity string Optional. Order book-supplied quantity of the fill in quote terms, omitted for pool fills
pq poolQuantity string Optional. Liquidity pool-supplied quantity of the fill in base terms, omitted for orderBook fills
pQ poolQuoteQuantity string Optional. Liquidity pool-supplied quantity of the fill in quote terms, omitted for orderBook fills
t time integer Timestamp of the fill
s makerSide string Maker side of the fill, buy or sell
u sequence integer Fill sequence number
f fee string Fee amount collected on the fill
a feeAsset string Symbol of asset in which fees collected
g gas string Optional. Amount collected to cover trade settlement gas costs, only present for taker
l liquidity string Whether the fill is the maker or taker in the trade from the perspective of the requesting API account, maker or taker
y type string Fill type, see values
T txId string Transaction id of the trade settlement transaction or null if not yet assigned
S txStatus string Status of the trade settlement transaction, see values

Enums & Values

Wallet Signature Hash Enums

Order Type Enum

Value Name
0 Market
1 Limit
2 Limit maker
3 Stop loss
4 Stop loss limit
5 Take profit
6 Take profit limit

Order Side Enum

Value Name
0 Buy
1 Sell

Order Time-In-Force Enum

Value Name
0 Good-til-canceled
1 Good-til-time (unused)
2 Immediate-or-cancel
3 Fill-or-kill

Order Self-Trade Prevention Enum

Value Name
0 Decrement and cancel
1 Cancel oldest
2 Cancel newest
3 Cancel both

Liquidity Change Type Enum

Value Name
0 Addition
1 Removal

Liquidity Change Origin Enum

Value Name
0 On chain
1 Off chain

API Request & Response Values

Market Type Values

Value Description
orderBook Order book settlements only, no hybrid liquidity pool
hybrid Both order book and hybrid liquidity pool settlements

Market Trading Status Values

Value Description
inactive No orders or cancels accepted
cancelsOnly Cancels accepted but not new orders
limitMakerOnly Cancels and limitMaker orders only
active Cancels and all order types accepted
activeHybrid Cancels and all order types accepted with settlement against hybrid liquidity pools

Candle Interval Values

Value Description
1m 1 minute
5m 5 minutes
15m 15 minutes
30m 30 minutes
1h 1 hour
6h 6 hours
1d 1 day

Trade Type Values

Value Description
orderBook Trade settled between order book orders only
pool Trade settled between a liquidity pool and taking order
hybrid Trade settled between a combination of liquidity pool and order book orders

Order Type Values

Value Description
market See order types
limit
limitMaker
stopLoss
stopLossLimit
takeProfit
takeProfitLimit

Order Time In Force Values

Value Description
gtc See time in force policies
ioc
fok

Order Self-Trade Prevention Values

Value Description
dc See self-trade prevention policies
co
cn
cb

Order Status Values

Value Description
active See order states and lifecycle
open
partiallyFilled
filled
canceled
rejected

Order Update Values

Value Description
new An order without a stopPrice has been accepted by the matching engine. new is not sent as a WebSocket state change event if the order matches on initial processing.
activated An order with a stopPrice has accepted into the matching engine and once the stopPrice is triggered, will go through other normal events starting with new.
fill An order has generated a fill, which is sent as a WebSocket event for both maker and taker orders. fill is the first WebSocket state change event sent if an order matches on initial processing. fill is also sent as a WebSocket event when an order is decremented by self-trade prevention.
canceled An order has been canceled. canceled is also sent as a WebSocket event when an order is canceled by self-trade prevention.
expired
  • A fill-or-kill (fok) order has been processed without filling
  • An immediate-or-cancel (ioc) order has been processed and partially filled
  • A market order has been processed and is unfilled or partially filled

Settlement Transaction State Values

Value Description
pending Not yet sent to Polygon or not yet mined.
mined Succesfully mined.
failed Transaction reverted.