Skip to content

Latest commit

 

History

History
3171 lines (2058 loc) · 168 KB

API.md

File metadata and controls

3171 lines (2058 loc) · 168 KB

API

Table of Contents

Clients

REST Public Client

  import { RestPublicClient } from '@idexio/idex-sdk';

RestPublicClient

Public REST API client

Parameters
Examples
import { v1 as uuidv1 } from 'uuid';
import { RestPublicClient } from '@idexio/idex-sdk';

const publicClient = new RestPublicClient({
  sandbox: true,
  // Optionally provide an API key to increase rate limits
  apiKey: '1f7c4f52-4af7-4e1b-aa94-94fac8d931aa',
});
console.log(await publicClient.getTickers('IDEX-ETH'));
ping

Test connectivity to the REST API

Returns {}

getServerTime

Returns the current server time

Returns Promise<number> Current server time as milliseconds since UNIX epoch

getExchangeInfo

Returns basic information about the exchange.

Returns Promise<RestResponseExchangeInfo>

getAssets

Returns information about assets supported by the exchange

Returns Promise<Array<RestResponseAsset>>

getMarkets

Returns information about the currently listed markets

Parameters

Returns Promise<Array<RestResponseMarket>>

getLiquidityPools

Returns information about liquidity pools supported by the exchange

Parameters

Returns Promise<Array<RestResponseLiquidityPool>>

getTickers

Returns market statistics for the trailing 24-hour period

Parameters
  • market string? Base-quote pair e.g. 'IDEX-ETH', if provided limits ticker data to a single market

Returns Promise<Array<RestResponseTicker>>

getCandles

Returns candle (OHLCV) data for a market

Parameters

Returns Promise<Array<RestResponseCandle>>

getTrades

Returns public trade data for a market

Parameters

Returns Promise<Array<RestResponseTrade>>

getOrderBookLevel1

Get current top bid/ask price levels of order book for a market

Parameters
  • market string Base-quote pair e.g. 'IDEX-ETH'
  • limitOrderOnly (optional, default false)

Returns Promise<RestResponseOrderBookLevel1>

getOrderBookLevel2

Get current order book price levels for a market

Parameters
  • market string Base-quote pair e.g. 'IDEX-ETH'
  • limit number Number of bids and asks to return. Default is 50, 0 returns the entire book (optional, default 50)
  • limitOrderOnly (optional, default false)

Returns Promise<RestResponseOrderBookLevel2>

RestPublicClientOptions

Public REST API client options

Type: Object

Properties

REST Authenticated Client

  import { RestAuthenticatedClient } from '@idexio/idex-sdk';

RestAuthenticatedClient

Authenticated API client

Parameters
Examples
import { v1 as uuidv1 } from 'uuid';
import { RestAuthenticatedClient } from '@idexio/idex-sdk';

const authenticatedClient = new RestAuthenticatedClient({
  // Edit the values before for your environment
  apiKey: '1f7c4f52-4af7-4e1b-aa94-94fac8d931aa',
  apiSecret: 'axuh3ywgg854aq7m73oy6gnnpj5ar9a67szuw5lclbz77zqu0j',
  // Optionally prove a wallet private key to automatically sign requests that need an ECDSA signature
  walletPrivateKey: '0x3141592653589793238462643383279502884197169399375105820974944592'
  sandbox: true,
});
addLiquidity

Add liquidity to a hybrid liquidity pool from assets held by a wallet on the exchange

Parameters

Returns Promise<RestResponseLiquidityAddition>

removeLiquidity

Remove liquidity from a hybrid liquidity pool represented by LP tokens held by a wallet on the exchange

Parameters

Returns Promise<RestResponseLiquidityRemoval>

getLiquidityAddition

Returns information about a single Liquidity Addition from a wallet

Parameters

Returns Promise<RestResponseLiquidityAddition>

getLiquidityAdditions

Returns information about multiple Liquidity Additions from a wallet

Parameters

Returns Promise<Array<RestResponseLiquidityAddition>>

getLiquidityRemoval

Returns information about a single Liquidity Removal from a wallet

Parameters

Returns Promise<RestResponseLiquidityRemoval>

getLiquidityRemovals

Returns information about multiple Liquidity Removals from a wallet

Parameters

Returns Promise<Array<RestResponseLiquidityRemoval>>

getUser

Get account details for the API key’s user

Parameters

Returns Promise<RestResponseUser>

getWallets

Get account details for the API key’s user

Parameters

Returns Promise<Array<RestResponseWallet>>

getBalances

Get asset quantity data (positions) held by a wallet on the exchange

Parameters

Returns Promise<Array<RestResponseBalance>>

associateWallet

Associate a wallet with the authenticated account

Parameters
Examples
const wallet = await authenticatedClient.associateWallet(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

Returns Promise<RestResponseAssociateWallet>

createOrder

Create and submit an order to the matching engine.

Parameters
Examples
const order = await authenticatedClient.createOrder(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
    market: 'IDEX-ETH',
    type: 'limit',
    side: 'sell',
    price: '0.10000000',
    quantity: '1.50000000',
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

Returns Promise<RestResponseOrder>

createTestOrder

Tests order creation and validation without submitting an order to the matching engine

Parameters
Examples
const order = await authenticatedClient.createTestOrder(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
    market: 'IDEX-ETH',
    type: 'limit',
    side: 'sell',
    price: '0.10000000',
    quantity: '1.50000000',
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

Returns Promise<RestResponseOrder>

cancelOrder

Cancel a single order

Parameters
  • cancelOrder RestRequestCancelOrder
  • signer MessageSigner? Required if a private key was not provided in the constructor (optional, default this.signer)
Examples
const responseByOrderId = await authenticatedClient.cancelOrder(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
    orderId: 'f077a010-ce18-11ea-9557-a9d3f954788d',
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

const clientOrderId = '0001_23234_18863_IDEX_ETH';
const responseByClientId = await authenticatedClient.cancelOrder(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
    orderId: `client:${clientOrderId}`,
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

Returns Promise<RestResponseCanceledOrder>

cancelOrders

Cancel multiple orders

Parameters
Examples
const allOrders = authenticatedClient.cancelOrders(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

const ordersForMarket = authenticatedClient.cancelOrders(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
    market: 'IDEX-ETH'
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

Returns Promise<RestResponseCanceledOrder>

getOrder

Get an order

Parameters

Returns Promise<RestResponseOrder>

getOrders

Get multiple orders

Parameters

Returns Promise<Array<RestResponseOrder>>

getFill

Get a fill

Parameters

Returns Promise<RestResponseFill>

getFills

Get multiple fills

Parameters

Returns Promise<Array<RestResponseFill>>

getDeposit

Get a deposit

Parameters

Returns Promise<RestResponseDeposit>

getDeposits

Get multiple deposits

Parameters

Returns Promise<Array<RestResponseDeposit>>

withdraw

Create a new withdrawal

Parameters
Examples
const withdrawal = await authenticatedClient.withdraw(
  {
    nonce: uuidv1(),
    wallet: '0xA71C4aeeAabBBB8D2910F41C2ca3964b81F7310d',
    asset: 'MATIC',
    quantity: '0.04000000',
  },
  idex.signatures.createPrivateKeyMessageSigner(config.walletPrivateKey),
);

Returns Promise<RestResponseWithdrawal>

getWithdrawal

Get a withdrawal

Parameters

Returns Promise<RestResponseWithdrawal>

getWithdrawals

Get multiple withdrawals

Parameters

Returns Promise<Array<RestResponseWithdrawal>>

getWsToken

Obtain a WebSocket API token

Parameters

Returns Promise<string>

RestAuthenticatedClientOptions

Authenticated API client configuration options.

Type: Object

Properties
  • apiKey string Used to authenticate user
  • apiSecret string Used to compute HMAC signature
  • walletPrivateKey string? If provided, used to create ECDSA signatures
  • sandbox boolean? If true, client will point to API sandbox
  • multiverseChain MultiverseChain? Which multiverse chain the client will point to

WebSocketClient

  import { WebSocketClient } from '@idexio/idex-sdk';

WebSocketClient

WebSocket API client

When apiKey and apiSecret are provided, the client will automatically handle WebSocket authentication token generation and refresh. Omit when using only public WebSocket subscriptions.

Parameters
Examples
import * as idex from '@idexio/idex-sdk';

const webSocketClient = new idex.WebSocketClient({
  // Edit the values before for your environment
  apiKey: '1f7c4f52-4af7-4e1b-aa94-94fac8d931aa',
  apiSecret: 'axuh3ywgg854aq7m73oy6gnnpj5ar9a67szuw5lclbz77zqu0j',
  shouldReconnectAutomatically: true,
  sandbox: true,
});

await webSocketClient.connect();
subscribe

Subscribe to a given set of subscriptions, optionally providing a list of top level markets or a cid property.

Parameters

Returns this

subscribeAuthenticated

Strictly typed subscribe which only can be used on authenticated subscriptions.

For this methods you need to pass websocketAuthTokenFetch to the websocket constructor. Library will automatically refresh user's wallet auth tokens for you.

See API specification

Parameters

Returns this

subscribeUnauthenticated

Subscribe which only can be used on non-authenticated subscriptions

Parameters

Returns this

WebSocketClientOptions

WebSocket API client options

Type: Object

Properties
  • apiKey string? Used to authenticate user when automatically refreshing WS token
  • apiSecret string? Used to compute HMAC signature when automatically refreshing WS token receiving push updates. Eg. {market}@{subscription}_{option}
  • shouldReconnectAutomatically boolean? If true, automatically reconnects when connection is closed by the server or network errors
  • connectTimeout number? Timeout (in milliseconds) before failing when trying to connect to the WebSocket. Defaults to 5000.
  • sandbox boolean? If true, client will point to API sandbox
  • multiverseChain MultiverseChain? Which multiverse chain the client will point to

OrderBookRealTimeClient

  import { OrderBookRealTimeClient } from '@idexio/idex-sdk';

OrderBookRealTimeClient

Extends EventEmitter

Orderbook API client

Parameters
Examples
import { OrderBookRealTimeClient } from '@idexio/idex-sdk';

const client = new OrderBookRealTimeClient({
  multiverseChain: 'matic',
  sandbox: false,
});

const markets = ['IDEX-USD'];
client.start(markets);

function handleOrderBook(l2: L2OrderBook) {
  const l2 = await client.getOrderBookLevel2('IDEX-USD', 10);
}

client.on('ready', handleOrderBook);
client.on('l2Changed', handleOrderBook);
start

Loads initial state from REST API and begin listening to orderbook updates.

Parameters

Returns Promise<void>

stop

Stop the order book client, and reset internal state. Call this when you are no longer using the client, to release memory and network resources.

Returns void

setFeesAndMinimumsOverride

Set custom fee rates for synthetic price level calculations. Use this if your wallet has custom fees set.

Parameters

Returns void

getOrderBookL1

Load the current state of the level 1 orderbook for this market.

Parameters

Returns RestResponseOrderBookLevel1

getOrderBookL2

Load the current state of the level 2 orderbook for this market.

Parameters
  • market string
  • limit number Total number of price levels (bids + asks) to return, between 2 and 1000 (optional, default 100)

Returns Promise<RestResponseOrderBookLevel2>

OrderBookRealTimeClientOptions

Orderbook Client Options

Type: Object

Properties
  • apiKey string? Increases rate limits if provided
  • connectTimeout number? Connection timeout for websocket (default 5000)
  • sandbox boolean? If true, client will point to API sandbox
  • multiverseChain MultiverseChain? Which multiverse chain the client will point to

Enums

Sets of named constants used as field types for several requests and responses

CandleInterval

Type: string

1m

Type: string

5m

Type: string

15m

Type: string

30m

Type: string

1h

Type: string

6h

Type: string

1d

Type: string

EthTransactionStatus

Type: string

pending

Either not yet submitted or not yet mined

Type: string

mined

Mined, no need for any block confirmation delay

Type: string

failed

Transaction reverted

Type: string

Liquidity

Type: string

maker

Maker provides liquidity

Type: string

taker

Taker removes liquidity

Type: string

MarketStatus

Type: string

inactive

No orders or cancels accepted

Type: string

cancelsOnly

Cancels accepted but not trades

Type: string

limitMakerOnly

Cancels and limitMaker orders only

Type: string

active

Trades and cancels accepted

Type: string

activeHybrid

Hybrid trades and cancels accepted

Type: string

OrderSelfTradePrevention

Type: string

dc

Decrement And Cancel (DC) - When two orders from the same user cross, the smaller order will be canceled and the larger order size will be decremented by the smaller order size. If the two orders are the same size, both will be canceled.

Type: string

co

Cancel Oldest (CO) - Cancel the older (maker) order in full

Type: string

cn

Cancel Newest (CN) - Cancel the newer, taker order and leave the older, resting order on the order book. This is the only valid option when time-in-force is set to fill or kill

Type: string

cb

Cancel Both (CB) - Cancel both orders

Type: string

OrderSide

Type: string

buy

Type: string

sell

Type: string

OrderStateChange

Type: string

new

An order without a stop has been accepted into the trading engine. Will not be sent as a discrete change event if the order matches on execution.

Type: string

activated

A stop order has accepted into the trading engine, once triggered, will go through other normal events starting with new

Type: string

fill

An order has generated a fill, both on maker and taker sides. Will be the first change event sent if an order matches on execution.

Type: string

canceled

An order is canceled by the user.

Type: string

expired

LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill, GTT orders past time.

Type: string

OrderStatus

Type: string

active

Stop order exists on the order book

Type: string

open

Limit order exists on the order book

Type: string

partiallyFilled

Limit order has completed fills but has remaining open quantity

Type: string

filled

Limit order is completely filled and is no longer on the book; market order was filled

Type: string

canceled

Limit order was canceled prior to execution completion but may be partially filled

Type: string

rejected

Order was rejected by the trading engine

Type: string

expired

GTT limit order expired prior to execution completion but may be partially filled

Type: string

testOnlyAccepted

Order submitted to the test endpoint and accepted by the trading engine, not executed

Type: string

testOnlyRejected

Order submitted to the test endpoint and rejected by validation or the trading engine, not executed

Type: string

OrderTimeInForce

Type: string

gtc

Good until canceled (default)

Type: string

gtt

Good until time

Type: string

ioc

Immediate or cancel

Type: string

fok

Fill or kill

Type: string

OrderType

Type: string

market

Type: string

limit

Type: string

limitMaker

Type: string

stopLoss

Type: string

stopLossLimit

Type: string

takeProfit

Type: string

takeProfitLimit

Type: string

REST Requests

RestRequestCancelOrders

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string
  • orderId string? Single orderId or clientOrderId to cancel; prefix client-provided ids with client:
  • market string? Base-quote pair e.g. 'IDEX-ETH'

RestRequestFindBalances

Type: Object

Properties

RestRequestFindCandles

Type: Object

Properties

  • market string Base-quote pair e.g. 'IDEX-ETH'
  • interval CandleInterval Time interval for data
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000

RestRequestFindDeposit

Type: Object

Properties

RestRequestFindDeposits

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string
  • asset string? Asset by symbol
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? Deposits created at the same timestamp or after fromId

RestRequestFindFill

Type: Object

Properties

RestRequestFindFills

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string Ethereum wallet address
  • market string Base-quote pair e.g. 'IDEX-ETH'
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? Fills created at the same timestamp or after fillId

RestRequestFindMarkets

Type: Object

Properties

  • market string Target market, all markets are returned if omitted

RestRequestFindOrder

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string
  • orderId string Single orderId or clientOrderId to cancel; prefix client-provided ids with client:

RestRequestFindOrders

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string
  • market string? Base-quote pair e.g. 'IDEX-ETH'
  • closed boolean? 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 number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? orderId of the earliest (oldest) order, only applies if orderId is absent

RestRequestFindTrades

Type: Object

Properties

  • market string Base-quote pair e.g. 'IDEX-ETH'
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? Trades created at the same timestamp or after fromId

RestRequestFindWithdrawal

Type: Object

Properties

RestRequestFindWithdrawals

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string
  • asset string? Asset by symbol
  • assetContractAddress string? Asset by contract address
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? Withdrawals created after the fromId

RestRequestOrder

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string
  • market string Base-quote pair e.g. 'IDEX-ETH'
  • type OrderType
  • side OrderSide
  • quantity string? Order quantity in base terms, exclusive with quoteOrderQuantity
  • quoteOrderQuantity string? Order quantity in quote terms, exclusive with quantity
  • price string? Price in quote terms, optional for market orders
  • stopPrice string? Stop loss or take profit price, only if stop or take order
  • clientOrderId string? Client-supplied order id
  • timeInForce OrderTimeInForce? Defaults to good until canceled
  • selfTradePrevention OrderSelfTradePrevention? Defaults to decrease and cancel

RestRequestWithdrawal

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string
  • asset string? Asset by symbol
  • assetContractAddress string? Asset by contract address
  • quantity string Withdrawal amount in asset terms, fees are taken from this value

RestRequestAssociateWallet

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string The wallet to associate with the authenticated account.

wallet

The wallet to associate with the authenticated account.

Type: string

REST Responses

RestResponseAsset

Asset

Type: Object

Properties

RestResponseBalance

Balance

Type: Object

Properties

  • 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 | null) Total value of the asset held by the wallet on the exchange in USD

RestResponseCandle

Candle (OHLCV) data points aggregated by time interval

Type: Object

Properties

  • start number Time of the start of the interval
  • open string Price of the first fill of the interval in quote terms
  • high string Price of the highest fill of the interval in quote terms
  • low string Price of the lowest fill of the interval in quote terms
  • close string Price of the last fill of the interval in quote terms
  • volume string Total volume of the period in base terms
  • sequence number Fill sequence number of the last trade in the interval

RestResponseDeposit

Asset deposits into smart contract

Type: Object

Properties

  • depositId string IDEX-issued deposit identifier
  • asset string Asset by symbol
  • quantity string Deposit amount in asset terms
  • txId string Ethereum transaction hash
  • txTime number Timestamp of the Ethereum deposit transaction
  • confirmationTime number Timestamp of credit on IDEX including block confirmations

RestResponseExchangeInfo

Basic exchange info

Type: Object

Properties

  • timeZone string Server time zone, always UTC
  • serverTime number 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 number 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 number 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
  • withdrawMinimum 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 number Minimum number of block confirmations before on-chain transactions are processed

RestResponseFill

Fill

Type: Object

Properties

  • fillId string Internal ID of fill
  • price string Executed price of fill in quote terms
  • quantity string Executed quantity of fill in base terms
  • quoteQuantity string Executed quantity of fill in quote terms
  • orderBookQuantity string? Quantity of the fill in base terms supplied by order book liquidity, omitted for pool fills
  • orderBookQuoteQuantity string? Quantity of the fill in quote terms supplied by order book liquidity, omitted for pool fills
  • poolQuantity string? Quantity of the fill in base terms supplied by pool liquidity, omitted for orderBook fills
  • poolQuoteQuantity string? Quantity of the fill in quote terms supplied by pool liquidity, omitted for orderBook fills
  • time string Fill timestamp
  • makerSide OrderSide Which side of the order the liquidity maker was on
  • sequence number Last trade sequence number for the market
  • market string Base-quote pair e.g. 'IDEX-ETH'
  • orderId string Internal ID of order
  • clientOrderId string? Client-provided ID of order
  • side OrderSide Orders side, buy or sell
  • fee string Fee amount on fill
  • feeAsset string Which token the fee was taken in
  • gas string Amount collected to cover trade settlement gas costs, only present for taker
  • liquidity Liquidity Whether the fill is the maker or taker in the trade from the perspective of the requesting API account, maker or taker
  • type TradeType Fill type
  • txId (string | null) Ethereum transaction ID, if available
  • txStatus string Ethereum transaction status

RestResponseMarket

Market

Type: Object

Properties

RestResponseOrder

Order

Type: Object

Properties

  • market string Market symbol as base-quote pair e.g. 'IDEX-ETH'
  • orderId string Exchange-assigned order identifier
  • clientOrderId string? Client-specified order identifier
  • wallet string Ethereum address of placing wallet
  • time string Time of initial order processing by the matching engine
  • status OrderStatus Current order status
  • errorCode string? Error short code explaining order error or failed batch cancel
  • errorMessage string? Error description explaining order error or failed batch cancel
  • type OrderType Order type
  • side OrderSide Order side
  • originalQuantity string? Original quantity specified by the order in base terms, omitted for market orders specified in quote terms
  • originalQuoteQuantity string? Original quantity specified by the order in quote terms, only present for market orders specified in quote terms
  • executedQuantity string Quantity that has been executed in base terms
  • cumulativeQuoteQuantity string? Cumulative quantity that has been spent (buy orders) or received (sell orders) in quote terms, omitted if unavailable for historical orders
  • avgExecutionPrice string? Weighted average price of fills associated with the order; only present with fills
  • price string? Original price specified by the order in quote terms, omitted for all market orders
  • stopPrice string? Stop loss or take profit price, only present for stopLoss, stopLossLimit, takeProfit, and takeProfitLimit orders
  • timeInForce OrderTimeInForce? Time in force policy, see values, only present for limit orders
  • selfTradePrevention OrderSelfTradePrevention Self-trade prevention policy, see values
  • fills Array<RestResponseOrderFill>? Array of order fill objects

RestResponseCanceledOrder

Response to "cancel order" requests (single or multiple orders). Includes one { orderId: string } object for each successfully canceled order.

Type: Array<Object>

RestResponseOrderBookLevel1

OrderBookLevel1

Type: Object

Properties

RestResponseOrderBookLevel2

OrderBookLevel2

Type: Object

Properties

RestResponseOrderBookPriceLevel

OrderBookPriceLevel

price and size as decimal strings numorders = # of limit orders at this price level (0 for synthetic levels)

Type: [Price, Size, NumOrders]

RestResponseOrderFill

OrderFill

Type: Object

Properties

  • fillId string Internal ID of fill
  • price string Executed price of fill in quote terms
  • quantity string Executed quantity of fill in base terms
  • quoteQuantity string Executed quantity of trade in quote terms
  • orderBookQuantity string? Quantity of the fill in base terms supplied by order book liquidity, omitted for pool fills
  • orderBookQuoteQuantity string? Quantity of the fill in quote terms supplied by order book liquidity, omitted for pool fills
  • poolQuantity string? Quantity of the fill in base terms supplied by pool liquidity, omitted for orderBook fills
  • poolQuoteQuantity string? Quantity of the fill in quote terms supplied by pool liquidity, omitted for orderBook fills
  • time string Fill timestamp
  • makerSide OrderSide Which side of the order the liquidity maker was on
  • sequence number Last trade sequence number for the market
  • fee string Fee amount on fill
  • feeAsset string Which token the fee was taken in
  • gas string?
  • liquidity Liquidity
  • type TradeType orderBook, pool, or hybrid
  • txId (string | null) Ethereum transaction ID, if available
  • txStatus string Ethereum transaction status

RestResponsePing

Ping

Type: Object

RestResponseTicker

Ticker

Type: Object

Properties

  • market string Base-quote pair e.g. 'IDEX-ETH'
  • time number Time when data was calculated, open and change is assumed to be trailing 24h
  • open (string | null) Price of the first trade for the period in quote terms
  • high (string | null) Highest traded price in the period in quote terms
  • low (string | null) Lowest traded price in the period in quote terms
  • close (string | null) Same as last
  • closeQuantity (string | null) Quantity of the last period in base terms
  • baseVolume string 24h volume in base terms
  • quoteVolume string 24h volume in quote terms
  • percentChange string % change from open to close
  • numTrades number Number of fills for the market in the period
  • ask (string | null) Best ask price on the order book
  • bid (string | null) Best bid price on the order book
  • sequence (number | null) Last trade sequence number for the market

RestResponseTime

Time

Type: Object

Properties

  • time number Current server time

RestResponseTrade

Trade

Type: Object

Properties

  • fillId string Internal ID of fill
  • price string Executed price of trade in quote terms
  • quantity string Executed quantity of trade in base terms
  • quoteQuantity string Executed quantity of trade in quote terms
  • time number Fill timestamp
  • makerSide OrderSide Which side of the order the liquidity maker was on
  • type TradeType orderBook, pool, or hybrid
  • sequence number Last trade sequence number for the market

RestResponseUser

User

Type: Object

Properties

  • depositEnabled boolean Deposits are enabled for the user account
  • orderEnabled boolean Placing orders is enabled for the user account
  • cancelEnabled boolean Cancelling orders is enabled for the user account
  • withdrawEnabled boolean Withdrawals are enabled for the user account
  • totalPortfolioValueUsd string Total value of all holdings deposited on the exchange, for all wallets associated with the user account, in USD
  • makerFeeRate string User-specific maker trade fee rate
  • takerFeeRate string User-specific taker trade fee rate
  • takerIdexFeeRate string User-specific liquidity pool taker IDEX fee rate
  • takerLiquidityProviderFeeRate string User-specific liquidity pool taker LP provider fee rate

RestResponseWallet

Type: Object

Properties

  • address string Ethereum address of the wallet
  • totalPortfolioValueUsd string Total value of all holdings deposited on the exchange for the wallet in USD
  • time number Timestamp of association of the wallet with the user account

RestResponseWebSocketToken

Type: Object

Properties

  • token string WebSocket subscription authentication token

RestResponseWithdrawal

Type: Object

Properties

  • withdrawalId string Exchange-assigned withdrawal identifier
  • asset string? Symbol of the withdrawn asset, exclusive with assetContractAddress
  • assetContractAddress string? Token contract address of withdrawn asset, exclusive with asset
  • quantity string Quantity of the withdrawal
  • time number Timestamp of withdrawal API request
  • fee string Amount deducted from withdrawal to cover IDEX-paid gas
  • txId (string | null) Ethereum transaction ID, if available
  • txStatus string Ethereum transaction status

RestResponseAssociateWallet

Type: Object

Properties

  • address string Ethereum address of the wallet
  • totalPortfolioValueUsd string Total value of all holdings deposited on the exchange for the wallet in USD
  • time number Timestamp of association of the wallet with the user account

WebSocket Subscriptions

AuthTokenWebSocketRequestOrdersSubscription

Type: Object

Properties

  • name "orders" The name of the subscription
  • wallet string Orders subscription with wallet attribute, which is fed to the websocketAuthTokenFetch function when needed to get an updated wsToken.
    Note: This property is not sent over the WebSocket and is exclusive to the idex-sdk.

AuthTokenWebSocketRequestBalancesSubscription

Type: Object

Properties

  • name "balances" The name of the subscription
  • wallet string Balances subscription with wallet attribute, which is fed to the websocketAuthTokenFetch function when needed to get an updated wsToken.
    Note: This property is not sent over the WebSocket and is exclusive to the idex-sdk.

WebSocketRequestTickersSubscription

TickersSubscription

Type: Object

Properties

WebSocketRequestCandlesSubscription

CandlesSubscription

Type: Object

Properties

WebSocketRequestTradesSubscription

TradesSubscription

Type: Object

Properties

WebSocketRequestL1OrderBookSubscription

L1OrderBookSubscription

Type: Object

Properties

WebSocketRequestL2OrderBookSubscription

L2OrderBookSubscription

Type: Object

Properties

WebSocketRequestBalancesSubscription

BalancesSubscription

Type: Object

Properties

WebSocketRequestOrdersSubscription

OrdersSubscription

Type: Object

Properties

WebSocket Responses

WebSocketResponseError

Error Response

Type: Object

Properties

WebSocketResponseSubscriptions

Subscriptions Response

Type: Object

Properties

WebSocketResponseTickerShort

TickerShort

Type: Object

Properties

  • m string (market) Market symbol
  • t number (time) Timestamp when the statistics were computed, the opening time of the period is 24 hours prior
  • o (string | null) (open) Price of the first trade in the period in quote terms
  • h (string | null) (high) Highest traded price in the period in quote terms
  • l (string | null) (low) Lowest traded price in the period in quote terms
  • c (string | null) (close) Price of the last trade in the period in quote terms
  • Q (string | null) (closeQuantity) Quantity of the last trade in th period in base terms
  • v string (baseVolume) Trailing 24-hour trading volume in base terms
  • q string (quoteVolume) Trailing 24-hour trading volume in quote terms
  • P string (percentChange) Percentage change from open price to close price
  • n number (numTrades) Number of trades in the period
  • a (string | null) (ask) Best ask price on the order book in quote terms
  • b (string | null) (bid) Best bid price on the order book in quote terms
  • u (number | null) (sequence) Fill sequence number of the last trade in the period

WebSocketResponseTickerLong

TickerLong

Type: Object

Properties

  • market string Market symbol
  • time number Timestamp when the statistics were computed, the opening time of the period is 24 hours prior
  • open (string | null) Price of the first trade in the period in quote terms
  • high (string | null) Highest traded price in the period in quote terms
  • low (string | null) Lowest traded price in the period in quote terms
  • close (string | null) Price of the last trade in the period in quote terms
  • closeQuantity (string | null) Quantity of the last trade in th period in base 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 number Number of trades in the period
  • ask (string | null) Best ask price on the order book in quote terms
  • bid (string | null) Best bid price on the order book in quote terms
  • sequence (number | null) Fill sequence number of the last trade in the period

WebSocketResponseCandleShort

CandleShort

Type: Object

Properties

  • m string (market) Market symbol
  • t number (time) Timestamp when the statistics were computed, time is always between the start and end timestamps of the interval
  • i string (interval) Interval duration, see Interval Values
  • s number (start) Timestamp of the start of the interval
  • e number (end) Timestamp of the end of the interval
  • o string (open) Price of the first trade in the interval in quote terms
  • h string (high) Highest traded price in the interval in quote terms
  • l string (low) Lowest traded price in the interval in quote terms
  • c string (close) Price of the last trade in the interval in quote terms
  • v string (volume) Trading volume in the interval in base terms
  • n number (numTrades) Number of trades in the candle
  • u number (sequence) Fill sequence number of the last trade in the interval

WebSocketResponseCandleLong

CandleLong

Type: Object

Properties

  • market string Market symbol
  • time number Timestamp when the statistics were computed, time is always between the start and end timestamps of the interval
  • interval string Interval duration, see Interval Values
  • start number Timestamp of the start of the interval
  • end number Timestamp of the end 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
  • numTrades number Number of trades in the candle
  • sequence number Fill sequence number of the last trade in the interval

WebSocketResponseTradeShort

TradeShort

Type: Object

Properties

  • y string (type) orderBook, pool, or hybrid
  • m string (market) Market symbol
  • i string (fillId) Trade identifier
  • p string (price) Price of the trade in quote terms
  • q string (quantity) Quantity of the trade in base terms
  • Q string (quoteQuantity) Quantity of the trade in quote terms
  • t number (time) Timestamp of the trade
  • s string (makerSide) Maker side of the trade, buy or sell
  • u number (sequence) Fill sequence number of the trade

WebSocketResponseTradeLong

TradeLong

Type: Object

Properties

  • market string Market symbol
  • 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 number Timestamp of the trade
  • makerSide string Maker side of the trade, buy or sell
  • sequence number Fill sequence number of the trade

WebSocketResponseL1OrderBookShort

L1OrderBookShort

Type: Object

Properties

  • m string (market) Market symbol
  • t number (time) Timestamp of the order book update
  • b string (bidPrice) Best bid price
  • B string (bidQuantity) Quantity available at the best bid price
  • a string (askPrice) Best ask price
  • A string (askQuantity) Quantity available at the best ask price
  • p (WebSocketResponseLiquidityPoolShort | null) Liquidity pool reserves for this market

WebSocketResponseL1OrderBookLong

L1OrderBookLong

Type: Object

Properties

WebSocketResponseL2OrderBookShort

L2OrderBookShort

Type: Object

Properties

WebSocketResponseL2OrderBookLong

L2OrderBookLong

Type: Object

Properties

WebSocketResponseBalanceShort

BalanceShort

Type: Object

Properties

  • w string (wallet) Target wallet address
  • a string (asset) Asset symbol
  • q string (quantity) Total quantity of the asset held by the wallet on the exchange
  • f string (availableForTrade) Quantity of the asset available for trading; quantity - locked
  • l string (locked) Quantity of the asset held in trades on the order book
  • d string (usdValue) Total value of the asset held by the wallet on the exchange in USD

WebSocketResponseBalanceLong

BalanceLong

Type: Object

Properties

  • wallet string Target wallet address
  • 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

WebSocketResponseOrderShort

OrderShort

Type: Object

Properties

  • m string (market) Market symbol
  • i string (orderId) Exchange-assigned order identifier
  • c string? (clientOrderId) Client-specified order identifier
  • w string (wallet) Ethereum address of placing wallet
  • t string (executionTime) Timestamp of the most recent update
  • T number (time) Timestamp of initial order processing by the matching engine
  • x OrderStateChange (update) Type of order update, see values
  • X OrderStatus (status) Order status, see values
  • u number? (sequence) order book update sequence number, only included if update type triggers an order book update
  • o OrderType (type) Order type, see values
  • S OrderSide (side) Order side, buy or sell
  • q string? (originalQuantity) Original quantity specified by the order in base terms, omitted for market orders specified in quote terms
  • Q string? (originalQuoteQuantity) Original quantity specified by the order in quote terms, only present for market orders specified in quote terms
  • z string (executedQuantity) Quantity that has been executed in base terms
  • Z string? (cumulativeQuoteQuantity) Cumulative quantity that has been spent (buy orders) or received (sell orders) in quote terms, omitted if unavailable for historical orders
  • v string? (avgExecutionPrice) Weighted average price of fills associated with the order; only present with fills
  • p string? (price) Original price specified by the order in quote terms, omitted for all market orders
  • P string? (stopPrice) Stop loss or take profit price, only present for stopLoss, stopLossLimit, takeProfit, and takeProfitLimit orders
  • f OrderTimeInForce? (timeInForce) Time in force policy, see values, only present for limit orders
  • V OrderSelfTradePrevention (selfTradePrevention) Self-trade prevention policy, see values
  • F Array<WebSocketResponseOrderFillShort>? (fills) Array of order fill objects

WebSocketResponseOrderLong

OrderLong

Type: Object

Properties

  • market string Market symbol
  • orderId string Exchange-assigned order identifier
  • clientOrderId string? Client-specified order identifier
  • wallet string Ethereum address of placing wallet
  • executionTime string Timestamp of the most recent update
  • time number Timestamp of initial order processing by the matching engine
  • update string Type of order update, see values
  • status OrderStatus Order status, see values
  • sequence number? order book update sequence number, only included if update type triggers an order book update
  • type OrderType Order type, see values
  • side OrderSide Order side, buy or sell
  • originalQuantity string? Original quantity specified by the order in base terms, omitted for market orders specified in quote terms
  • originalQuoteQuantity string? Original quantity specified by the order in quote terms, only present for market orders specified in quote terms
  • executedQuantity string Quantity that has been executed in base terms
  • cumulativeQuoteQuantity string? Cumulative quantity that has been spent (buy orders) or received (sell orders) in quote terms, omitted if unavailable for historical orders
  • avgExecutionPrice string? Weighted average price of fills associated with the order; only present with fills
  • price string? Original price specified by the order in quote terms, omitted for all market orders
  • stopPrice string? Stop loss or take profit price, only present for stopLoss, stopLossLimit, takeProfit, and takeProfitLimit orders
  • timeInForce OrderTimeInForce? Time in force policy, see values, only present for limit orders
  • selfTradePrevention OrderSelfTradePrevention Self-trade prevention policy, see values
  • fills Array<RestResponseOrderFill>? Array of order fill objects

WebSocketResponseOrderFillShort

OrderFillShort

Type: Object

Properties

  • type TradeType orderBook, pool, or hybrid
  • i string (fillId) Fill identifier
  • p string (price) Price of the fill in quote terms
  • q string (quantity) Quantity of the fill in base terms
  • Q string (quoteQuantity) Quantity of the fill in quote terms
  • oq string? Quantity of the fill in base terms supplied by order book liquidity, omitted for pool fills
  • oQ string? Quantity of the fill in quote terms supplied by order book liquidity, omitted for pool fills
  • pq string? Quantity of the fill in base terms supplied by pool liquidity, omitted for orderBook fills
  • pQ string? Quantity of the fill in quote terms supplied by pool liquidity, omitted for orderBook fills
  • t number (time) Timestamp of the fill
  • s string (makerSide) Maker side of the fill, buy or sell
  • u string (sequence) Fill sequence number
  • f string (fee) Fee amount collected on the fill
  • a string (feeAsset) Symbol of asset in which fees collected
  • g string? (gas) Amount collected to cover trade settlement gas costs, only present for taker
  • l string (liquidity) Whether the fill is the maker or taker in the trade from the perspective of the requesting user account, maker or taker
  • T string (txId) Ethereum ID of the trade settlement transaction
  • S string (txStatus) Status of the trade settlement transaction, see values

Type Guards

Type Guards are mostly useful for TypeScript users and can be used to refine general types when needing to parse or build the required values.

isWebSocketAuthenticatedSubscription

A type guard that checks if a given value is a subscription object which represents an authenticated subscription. These subscriptions require the wallet property (local to idex-sdk only) and require that the WebSocketClient was created with the websocketAuthTokenFetch function provided.

Parameters

  • subscription any

Properties

  • subscription any The subscription to check

Returns any

isWebSocketUnauthenticatedSubscription

A type guard that checks if a given value is a subscription object which represents an unauthenticated subscription.

Parameters

  • subscription any

Properties

  • subscription any The subscription to check

Returns any

isWebSocketCandlesSubscription

A type guard that checks if a given value is a subscription object which represents a candles subscription. This is useful as the candles subscription has the interval property in addition to markets and name.

Parameters

  • subscription any

Properties

  • subscription any The subscription to check

Returns any

isWebSocketLooseSubscription

A type guard which allows using a subscription object in a "loose" manner. This is less "safe" but can often be useful when parsing values where you do not need strict typing. When true, the provided value will be a "partial" shape of that conforms to any/all subscription objects.

This should be used lightly.

Parameters

  • subscription any

Properties

  • subscription any The subscription to check

Returns any

isCandleInterval

A type guard which checks if a string is a valid candle interval.

Parameters

  • value any

Properties

  • value string The subscription to check

Returns any

ECDSA Signatures

MessageSigner

A function that accepts a string and returns a Promise resolving on its ECDSA signature

Type: Function

Misc Types & Utilities

ErrorShortCodes

The possible error short codes when interacting with the IDEX API's.

Type: ("TOKEN_NOT_FOUND" | "ORDER_NOT_FOUND" | "MARKET_NOT_FOUND" | "DEPOSIT_NOT_FOUND" | "WITHDRAWAL_NOT_FOUND" | "FILL_NOT_FOUND" | "USER_NOT_FOUND" | "ENDPOINT_NOT_FOUND" | "EXCEEDED_RATE_LIMIT" | "INSUFFICIENT_FUNDS" | "USER_MIGRATION_REQUIRED" | "WALLET_NOT_ASSOCIATED" | "EMAIL_VERIFICATION_REQUIRED" | "INVALID_WALLET_SIGNATURE" | "INVALID_API_KEY" | "REQUIRED_API_KEY" | "INVALID_HMAC_SIGNATURE" | "REQUIRED_HMAC_SIGNATURE" | "REQUIRED_API_KEY_READ_SCOPE" | "REQUIRED_API_KEY_TRADE_SCOPE" | "REQUIRED_API_KEY_WITHDRAW_SCOPE" | "TRADING_RESTRICTED_FOR_LOCATION" | "EXCEEDED_WITHDRAWAL_LIMIT" | "CANCELS_DISABLED" | "TRADING_DISABLED" | "WITHDRAWALS_DISABLED" | "INTERNAL_SERVER_ERROR" | "BAD_REQUEST" | "SERVICE_UNAVAILABLE" | "INVALID_API_VERSION" | "REQUIRED_PARAMETER" | "INVALID_PARAMETER" | "INVALID_WITHDRAWAL_QUANTITY" | "INVALID_ORDER_QUANTITY" | "INVALID_ORDER_PRICE_CROSSES_SPREAD")

L1Equal

Determine whether two level 1 order books are equal, including pool reserves

Parameters

Returns boolean

L2toL1OrderBook

Derive the level 1 orderbook from a level 2 orderbook

Parameters

Returns L1OrderBook

BestAvailablePriceLevels

Type: Object

Properties

  • baseReceived bigint actual quantity received, in base units at the best available buy price
  • bestAvailableBuyPrice bigint best available price for buy orders of the minimum size
  • bestAvailableSellPrice bigint best available price for sell orders of the minimum size
  • quoteReceived bigint actual quantity received, in quote units at the best available sell price

RestRequestFindLiquidityPools

Type: Object

Properties

  • market string? Target market
  • tokenA string? Address of one reserve token
  • tokenB string? Address of one reserve token

L1OrderBook

Type: Object

Properties

L2LimitOrderBookToHybridOrderBooks

Convert a limit-order orderbook and a liquidity pool to a hybrid order book representation

Parameters

  • orderBook L2OrderBook L2 book, e.g. from GET /v1/orderbook?level=2&limitOrderOnly=true
  • visibleLevels number number of price levels to calculate, default = 10 asks, 10 bids (optional, default 10)
  • visibleSlippage number price slippage per level, in increments of 0.001%, default = 100 (0.1%) (optional, default 100)
  • idexFeeRate bigint trade fee rate charged by IDEX, expressed in pips
  • poolFeeRate bigint pool fee rate chared by liquidity pool, expressed in pips
  • includeMinimumTakerLevels boolean if true, calculate a synthetic price level at twice the minimum trade size
  • minimumTakerInQuote (bigint | null) minimum trade size expressed in pips, or null if none available

Returns {l1: L1OrderBook, l2: L2OrderBook}

calculateGrossBaseQuantity

Helper function to calculate gross base available at a bid price see: {quantitiesAvailableFromPoolAtBidPrice}

Parameters

  • baseAssetQuantity bigint
  • quoteAssetQuantity bigint
  • targetPrice bigint
  • idexFeeRate bigint
  • poolFeeRate bigint

Returns bigint

updateL2Levels

Updates a level 2 orderbook using a partial "diff" received over websockets

Parameters

  • book L2OrderBook
  • updatedLevels L2OrderBook level 2 orderbook containing only limit order price levels that have changed

Returns void orderbook is updated in-place

RestRequestAddLiquidity

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string Ethereum wallet address
  • tokenA string Asset by address
  • tokenB string Asset by address
  • amountADesired string Maximum amount of tokenA to add to the liquidity pool
  • amountBDesired string Maximum amount of tokenB to add to the liquidity pool
  • amountAMin string Minimum amount of tokenA to add to the liquidity pool
  • amountBMin string Minimum amount of tokenB to add to the liquidity pool
  • to string Wallet to credit LP tokens, or the custodian contract address to leave on exchange

L2OrderBook

Type: Object

Properties

WebSocketRequestTokenPriceSubscription

TokenPriceSubscription

Type: Object

Properties

createPrivateKeyMessageSigner

Returns an ethers Wallet signer which takes a message and signs it with the originally provided private key.

Parameters

  • walletPrivateKey string The private key to use when signing any given messages

Examples

const signMessage = createPrivateKeyMessageSigner(myPrivateKey)
const signed = await signMessage(myMessageToSign)

Returns MessageSigner

updateL2Side

Applies a changeset to a single side of the orderbook

Parameters

Returns Array<OrderBookLevelL2>

OrderBookFeesAndMinimums

Type: Object

Properties

  • 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
  • takerTradeMinimum string Minimum order size that is accepted by the matching engine for execution in MATIC, applies to both MATIC and tokensSee RestResponseExchangeInfo

RestRequestRemoveLiquidity

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string Ethereum wallet address
  • tokenA string Asset by address
  • tokenB string Asset by address
  • liquidity string LP tokens to burn
  • amountAMin string Minimum amount of tokenA to add to the liquidity pool
  • amountBMin string Minimum amount of tokenB to add to the liquidity pool
  • to string Wallet to credit LP tokens, or the custodian contract address to leave on exchange

calculateGrossBaseValueOfBuyQuantities

Helper function to convert from quote to base quantities see: {quantitiesAvailableFromPoolAtAskPrice}

Parameters

  • baseAssetQuantity bigint
  • quoteAssetQuantity bigint
  • grossQuoteQuantity bigint

Returns bigint

privateKeySigner

  • See: {createPrivateKeyMessageSigner}

Meta

  • deprecated: use createPrivateKeyMessageSigner directly

OrderBookLevelType

Type: Object

OrderBookLevelL1

Type: Object

Properties

  • price bigint
  • size bigint
  • numOrders number

calculateGrossQuoteQuantity

Helper function to calculate gross quote available at an ask price see: {quantitiesAvailableFromPoolAtAskPrice}

Parameters

  • baseAssetQuantity bigint
  • quoteAssetQuantity bigint
  • targetPrice bigint
  • idexFeeRate bigint
  • poolFeeRate bigint

Returns bigint

RestRequestFindLiquidityAddition

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string Ethereum wallet address
  • liquidityAdditionId string? Single liquidityAdditionId to return; exclusive with initiatingTxId
  • initiatingTxId string? Transaction id of the Exchange contract addLiquidity or addLiquidityETH call transaction, only applies to chain-initiated liquidity additions; exclusive with liquidityAdditionId
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? Liquidity additions created at the same timestamp or after fromId

OrderBookLevelL2

Type: Object

Properties

PoolReserveQuantities

Type: Object

Properties

  • baseReserveQuantity bigint
  • quoteReserveQuantity bigint

RestRequestFindLiquidityRemoval

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string Ethereum wallet address
  • liquidityRemovalId string? Single liquidityRemovalId to return; exclusive with initiatingTxId
  • initiatingTxId string? Transaction id of the Exchange contract removeLiquidity or removeLiquidityETH call transaction, only applies to chain-initiated liquidity removals; exclusive with liquidityRemovalId
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? Liquidity additions created at the same timestamp or after fromId

PriceLevelQuantities

Type: Object

Properties

  • grossBase bigint
  • grossQuote bigint

calculateGrossQuoteValueOfSellQuantities

Helper function to convert from base to quote quantities see: {quantitiesAvailableFromPoolAtBidPrice}

Parameters

  • baseAssetQuantity bigint
  • quoteAssetQuantity bigint
  • grossBaseQuantity bigint

Returns bigint

RestRequestFindLiquidityChanges

Type: Object

Properties

  • nonce string UUIDv1
  • wallet string Ethereum wallet address
  • start number? Starting timestamp (inclusive)
  • end number? Ending timestamp (inclusive)
  • limit number? Max results to return from 1-1000
  • fromId string? Deposits created at the same timestamp or after fromId

MarketType

Type: string

orderBook

Orderbook trades accepted

Type: string

hybrid

Orderbook, pool, and hybrid trades accepted

Type: string

calculateBaseQuantityOut

Given a taker order size expressed in quote, how much base is received from the pool

see: {L1orL2BestAvailablePrices}

Parameters

  • baseAssetQuantity bigint
  • quoteAssetQuantity bigint
  • grossQuoteQuantityIn bigint
  • idexFeeRate bigint
  • poolFeeRate bigint

Returns bigint

LiquidityChangeOrigination

Type: string

OnChain

Initiation on-chain via contract call

Type: string

OffChain

Initiated off-chain via API

Type: string

WebSocketRequestAuthenticatedSubscription

Type: (WebSocketRequestBalancesSubscription | WebSocketRequestOrdersSubscription)

WebSocketRequestUnauthenticatedSubscription

Type: (WebSocketRequestCandlesSubscription | WebSocketRequestL1OrderBookSubscription | WebSocketRequestL2OrderBookSubscription | WebSocketRequestTickersSubscription | WebSocketRequestTradesSubscription)

calculateQuoteQuantityOut

Given a taker order size expressed in base, how much quote is received from the pool

see: {L1orL2BestAvailablePrices}

Parameters

  • baseAssetQuantity bigint
  • quoteAssetQuantity bigint
  • grossBaseQuantityIn bigint
  • idexFeeRate bigint
  • poolFeeRate bigint

Returns bigint

LiquidityChangeType

Type: string

Addition

Adding reserve assets to pool and minting LP tokens

Type: string

Removal

Removing reserve assets from pool and burning LP tokens

Type: string

AuthTokenWebSocketRequestAuthenticatedSubscription

Type: (AuthTokenWebSocketRequestBalancesSubscription | AuthTokenWebSocketRequestOrdersSubscription)

numerator

The result needs to be rounded down to prevent the pool's constant product from decreasing, ie. the second part of the subtraction (the division) needs to be rounded up.

AuthTokenWebSocketRequestSubscription

Type: (AuthTokenWebSocketRequestAuthenticatedSubscription | WebSocketRequestUnauthenticatedSubscription)

MultiverseChain

The available multiverse chains to define when creating a client.

Type: "matic"

WebSocketRequestSubscription

Type: (AuthTokenWebSocketRequestAuthenticatedSubscription | WebSocketRequestUnauthenticatedSubscription)

WebSocketResponseLiquidityPoolShort

LiquidityPoolShort

Type: Object

Properties

  • q string (baseReserveQuantity) quantity of base asset held in the liquidity pool
  • Q string (quoteReserveQuantity) quantity of quote asset held in the liquidity pool

RestResponseLiquidityPool

Liquidity Pool

Type: Object

Properties

  • 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 pips
  • reserveB string Quantity of token B held as reserve in token precision, not pips
  • liquidityToken string Address of the liquidity provider (LP) token
  • totalLiquidity string Total quantity of liquidity provider (LP) tokens minted in token precision, not pips
  • reserveUsd string Total value of reserves in USD
  • market string Market symbol of pool’s associated hybrid market

WebSocketResponseLiquidityPoolLong

LiquidityPoolLong

Type: Object

Properties

  • baseReserveQuantity string quantity of base asset held in the liquidity pool
  • quoteReserveQuantity string quantity of quote asset held in the liquidity pool

WebSocketRequestSubscriptionsByName

Type: Object

Properties

calculateSyntheticPriceLevels

Generates a synthetic orderbook consisting of price levels for pool liquidity only

Parameters

  • baseAssetQuantity bigint pool reserve in base asset, must be at least 1.0 expressed in pips (10^-8)
  • quoteAssetQuantity bigint pool reserve in quote asset, must be at least 1.0 expressed in pips (10^-8)
  • visibleLevels number how many ask and bid price levels to generate (of each)
  • visibleSlippage number how much slippage per price level, in 1/1000th of a percent (100 = 0.1%)
  • idexFeeRate bigint? the idex fee rate to use for calculations (query /v1/exchange for current global setting) (optional, default BigInt(0))
  • poolFeeRate bigint? the liquidity pool fee rate to use for calculations (query /v1/exchange for current global setting) (optional, default BigInt(0))

Returns SyntheticL2OrderBook a level 2 order book with synthetic price levels only

RestResponseLiquidityAddition

LiquidityAddition

Type: Object

Properties

  • liquidityAdditionId string Internal ID of liquidity addition
  • tokenA string Asset symbol
  • tokenB string Asset symbol
  • amountA (string | null) Amount of tokenA added to the liquidity pool
  • amountB (string | null) Amount of tokenB added to the liquidity pool
  • liquidity (string | null) Amount of liquidity provided (LP) tokens minted
  • time number Liquidity addition timestamp
  • initiatingTxId (string | null) On chain initiated transaction ID, if available
  • errorCode string Error short code present on liquidity addition error
  • errorMessage string Human-readable error message present on liquidity addition error
  • feeTokenA (string | null) Amount of tokenA collected as fees
  • feeTokenB (string | null) Amount of tokenB collected as fees
  • txId (string | null) Ethereum transaction ID, if available
  • txStatus (EthTransactionStatus | null) Ethereum transaction status

RestResponseLiquidityPoolReserves

LiquidityPoolReserves

Type: Object

Properties

  • baseReserveQuantity string reserve quantity of base asset in pool
  • quoteReserveQuantity string reserve quantity of quote asset in pool

WebSocketResponseL2OrderBookChange

L2OrderBookChange

Type: [string, string, number]

RestResponseLiquidityRemoval

LiquidityRemoval

Type: Object

Properties

  • liquidityRemovalId string Internal ID of liquidity removal
  • tokenA string Asset symbol
  • tokenB string Asset symbol
  • amountA (string | null) Amount of tokenA added to the liquidity pool
  • amountB (string | null) Amount of tokenB added to the liquidity pool
  • liquidity (string | null) Amount of liquidity provided (LP) tokens minted
  • time number Liquidity addition timestamp
  • initiatingTxId (string | null) On chain initiated transaction ID, if available
  • errorCode string Error short code present on liquidity addition error
  • errorMessage string Human-readable error message present on liquidity addition error
  • feeTokenA (string | null) Amount of tokenA collected as fees
  • feeTokenB (string | null) Amount of tokenB collected as fees
  • txId (string | null) Ethereum transaction ID, if available
  • txStatus (EthTransactionStatus | null) Ethereum transaction status

recalculateHybridLevelAmounts

Recalculate price level quantities for a book previously sorted with {sortAndMergeLevelsUnadjusted}

Parameters

  • orderbook L2OrderBook an unadjusted level 2 order book as returned by {sortAndMergeLevelsUnadjusted}
  • idexFeeRate bigint idex fee rate to use in pool quantity calculations
  • poolFeeRate bigint pool fee rate to use in pool quantity calculations

Returns L2OrderBook the recalculated level 2 order book

WebSocketRequestUnsubscribe

UnsubscribeRequest

Type: Object

Properties

  • method string 'unsubscribe'
  • cid string? client-supplied request id
  • markets Array<string>? array of market symbols
  • subscriptions Array<(WebSocketRequestUnsubscribeSubscription | WebSocketRequestUnsubscribeShortNames)>? array of subscription objects

WebSocketRequestSubscriptions

SubscriptionsRequest

Type: Object

Properties

  • method string 'subscriptions'
  • cid string? customer-supplied request id

WebSocketRequest

Type: (WebSocketRequestSubscribeStrict | WebSocketRequestSubscriptions | WebSocketRequestUnsubscribe)

WebSocketRequest

Type: (WebSocketRequestSubscribe | WebSocketRequestSubscriptions | WebSocketRequestUnsubscribe)

TradeType

Type: string

orderBook

Type: string

pool

Type: string

hybrid

Type: string

sortAndMergeLevelsUnadjusted

Combines limit orders and synthetic price levels into an intermediate sorted state IMPORTANT: this function does not update price level quantities after merging

Parameters

Returns Array<OrderBookLevelL2> a level 2 order book with synthetic price levels only

quantitiesAvailableFromPoolAtAskPrice

Helper function to calculate the asset quantities available at a given price level (pool liquidity only)

Parameters

  • baseAssetQuantity bigint pool reserve in base asset, must be at least 1.0 expressed in pips (10^-8)
  • quoteAssetQuantity bigint pool reserve in quote asset, must be at least 1.0 expressed in pips (10^-8)
  • askPrice bigint the ask price level to calculate quantities for
  • idexFeeRate bigint? the idex fee rate to use for calculations (query /v1/exchange for current global setting)
  • poolFeeRate bigint? the liquidity pool fee rate to use for calculations (query /v1/exchange for current global setting)

Returns PriceLevelQuantities a level 2 order book with synthetic price levels only

WebSocketResponseTokenPriceShort

TokenPriceShort

Type: Object

Properties

  • t string (token) Token symbol
  • p string (price) Current price of token relative to the native asset

WebSocketResponseTokenPriceLong

TokenPriceLong

Type: Object

Properties

  • token string Token symbol
  • price string Current price of token relative to the native asset

WebSocketResponseSubscriptionMessageShort

Short-hand response payloads

Type: ({type: "tickers", data: WebSocketResponseTickerShort} | {type: "trades", data: WebSocketResponseTradeShort} | {type: "candles", data: WebSocketResponseCandleShort} | {type: "l1orderbook", data: WebSocketResponseL1OrderBookShort} | {type: "l2orderbook", data: WebSocketResponseL2OrderBookShort} | {type: "balances", data: WebSocketResponseBalanceShort} | {type: "orders", data: WebSocketResponseOrderShort} | {type: "tokenprice", data: WebSocketResponseTokenPriceShort})

WebSocketResponseSubscriptionMessageLong

Transformer (long-form) response payloads

Type: ({type: "tickers", data: WebSocketResponseTickerLong} | {type: "trades", data: WebSocketResponseTradeLong} | {type: "candles", data: WebSocketResponseCandleLong} | {type: "l1orderbook", data: WebSocketResponseL1OrderBookLong} | {type: "l2orderbook", data: WebSocketResponseL2OrderBookLong} | {type: "balances", data: WebSocketResponseBalanceLong} | {type: "orders", data: WebSocketResponseOrderLong} | {type: "tokenprice", data: WebSocketResponseTokenPriceLong})

quantitiesAvailableFromPoolAtBidPrice

Helper function to calculate the asset quantities available at a given price level (pool liquidity only)

Parameters

  • baseAssetQuantity bigint pool reserve in base asset, must be at least 1.0 expressed in pips (10^-8)
  • quoteAssetQuantity bigint pool reserve in quote asset, must be at least 1.0 expressed in pips (10^-8)
  • bidPrice bigint the bid price level to calculate quantities for
  • idexFeeRate bigint? the idex fee rate to use for calculations (query /v1/exchange for current global setting)
  • poolFeeRate bigint? the liquidity pool fee rate to use for calculations (query /v1/exchange for current global setting)

Returns PriceLevelQuantities a level 2 order book with synthetic price levels only

L1orL2BestAvailablePrices

Given a minimum taker order size, calculate the best achievable price level using pool liquidity only

Parameters

  • pool PoolReserveQuantities pool reserve quantities for the orderbook in question
  • idexFeeRate bigint the idex fee rate to use for pool calculations
  • poolFeeRate bigint the pool fee rate to use for pool calculations
  • takerMinimumInBase bigint the minimum taker order size, expressed in base asset units
  • takerMinimumInQuote bigint the minimum taker order size, expressed in quote asset units

Returns PriceLevelQuantities a level 2 order book with synthetic price levels only

L1L2OrderBooksWithMinimumTaker

Modifies an existing level 2 order book to include better price levels at the desired taker order size, if available from pool reserves

Parameters

  • l2 L2OrderBook
  • idexFeeRate bigint the idex fee rate to use for pool calculations
  • poolFeeRate bigint the pool fee rate to use for pool calculations
  • takerMinimumInQuote bigint the minimum taker order size, expressed in quote asset units
  • pool PoolReserveQuantities pool reserve quantities for the orderbook in question

Returns {l1: L1OrderBook, l2: L2OrderBook}

validateSyntheticPriceLevelInputs

Validates assumptions for reserve quantities and pricing required for quantity calculations

Parameters

  • baseAssetQuantity bigint pool reserve in base asset, must be at least 1.0 expressed in pips (10^-8)
  • quoteAssetQuantity bigint pool reserve in quote asset, must be at least 1.0 expressed in pips (10^-8)
  • targetPrice bigint price expressed in pips, must be 0 < price < 2^64-1 and on the correct side of the spread
  • isBuy boolean if true, the price is targeting buy orders (bids), otherwise sell orders (asks)

Returns void validation always succeeds or throws