NAV Navbar
  • ABOUT xChange API
  • DEVELOPMENT GUIDE
  • RATE LIMITING
  • CHANGELOG
  • BEST PRACTICES
  • REST API Reference
  • Market data
  • Authentication
  • Authentication HS256
  • Trading
  • Trading history
  • Account management
  • Sub-accounts
  • Buy crypto
  • Socket API Reference
  • Socket Market Data
  • Socket Session Authentication
  • Socket Trading
  • Socket Account Management
  • Errors
  • Guide & Code Samples
  • ABOUT xChange API

    xChange REST & Streaming API version 2.0 provides programmatic access to xChange’s next generation trading engine.

    We strongly recommend that our new customers use API version 3.0 to get the best trading experience. We also recommend that our current traders switch to the newest version 3.0.

    API version 3.0 documentation available on API v3.

    By using the xChange API you confirm that you have read and accepted the API License Agreement.

    DEVELOPMENT GUIDE

    API Explorer

    You can explore the API using SwaggerUI including methods requiring authorization.

    API URLs

    REST https://api.x-changex.com/api/2
    Streaming Market Data wss://api.x-changex.com/api/2/ws/public
    Streaming Trading wss://api.x-changex.com/api/2/ws/trading
    Streaming Account wss://api.x-changex.com/api/2/ws/account

    DateTime Format

    All timestamps are returned in ISO 8601 format (UTC).
    Example: "2017-04-03T10:20:49.315Z"

    Number Format

    All finance data, e.g. price, quantity, fee, etc., should be arbitrary precision numbers and have a string representation.
    Example: "10.2000058"

    Pagination

    Parameters:

    Parameter Description
    limit Number of results per call
    Accepted range: 0 - 1000
    Default value: 100
    offset Number of results offset
    Default value: 0
    sort Sort direction
    Accepted values: ASC (ascending order), DESC (descending order)
    Default value: DESC
    by Defines filter type
    Accepted values: id, timestamp
    from Interval initial value (optional parameter)
    If filter by timestamp is used, then parameter type is datetime, otherwise object id
    till Interval end value (optional parameter)
    If filter by timestamp is used, then parameter type is datetime, otherwise object id

    RATE LIMITING

    The following Rate Limits are applied:

    Significantly exceeding the Rate Limits can lead to suspension.

    CHANGELOG

    02.11.2023

    Added support of multichain that allows specifying a combination of a currency and a base blockchain:

    06.07.2020

    New account streaming endpoint /api/2/ws/account

    06.07.2020

    BEST PRACTICES

    The xChange API development team strives to bring the best trading experience to API users. This manual contains a set of best practices for using the API as efficiently as possible.

    HTTP Persistent Connection

    The underlying TCP connection is kept active for multiple requests/responses. Subsequent requests will result in reduced latency as the TCP handshaking process is no longer required.

    If you use the HTTP 1.0 client, please ensure it supports the Keep-Alive directive and submit the ''Connection: Keep-Alive'' header with your request.

    Keep-Alive is a part of the HTTP 1.1 protocol and enabled by default on compliant clients. However, you will have to ensure your implementation does not set other values as the connection header.

    Retrieving and updating account state

    Use the Streaming API for real-time updates of your orders, trades and any transaction changes.

    REST API Reference

    HTTP Status codes

    Error response

    All error responses have error code and human readable message fields. Some errors contain an additional description field.

    Example of error response:

    {
      "error": {
        "code": 20001,
        "message": "Insufficient funds",
        "description": "Check that the funds are sufficient, given commissions"
      }
    }
    

    Market data

    Currencies

    Get a list of all currencies or specified currencies

    curl "https://api.x-changex.com/api/2/public/currency"  
    

    The above command returns JSON structured like this:

    [
       {
          "id": "BTC",
          "fullName": "Bitcoin",
          "crypto": true,
          "payinEnabled": true,
          "payinPaymentId": false,
          "payinConfirmations": 2,
          "payoutEnabled": true,
          "payoutIsPaymentId": false,
          "transferEnabled": true,
          "delisted": false,
          "payoutFee": "0.00958",
          "payoutMinimalAmount": "0.00958",
          "precisionPayout": 10,
          "precisionTransfer": 10
       },
       {
          "id": "ETH",
          "fullName": "Ethereum",
          "crypto": true,
          "payinEnabled": true,
          "payinPaymentId": false,
          "payinConfirmations": 2,
          "payoutEnabled": true,
          "payoutIsPaymentId": false,
          "transferEnabled": true,
          "delisted": false,
          "payoutFee": "0.001",
          "payoutMinimalAmount": "0.00958",
          "precisionPayout": 20,
          "precisionTransfer": 15,
          "lowProcessingTime": "3.518",
          "highProcessingTime": "2411.963",
          "avgProcessingTime": "247.1108947"
       }
    ]
    

    GET /api/2/public/currency

    Return the actual list of available currencies, tokens, etc.

    You can optionally use comma-separated list of currencies. If it is not provided, null or empty, the request returns all currencies.

    Requires no API key Access Rights.

    Parameter:

    Name Type Description
    currencies String Comma-separated list of currency codes. Optional parameter

    Responses:

    Name Type Description
    id String Currency identifier (code), for example, ''BTC''
    Note: description will simply use currency in the future.
    fullName String Currency full name, for example, ''Bitcoin''
    crypto Boolean Determines whether currency belongs to blockchain
    payinEnabled Boolean Determines whether it is allowed to generate addresses for a deposit
    payinPaymentId Boolean Determines whether it is required to provide additional information other than the address for deposit
    payinConfirmations Number Count of blocks confirmations, which are needed for deposit
    payoutEnabled Boolean Determines whether withdraw is allowed
    payoutIsPaymentId Boolean Determines whether providing of additional information for withdraw is allowed
    transferEnabled Boolean Determines whether transfer between trading account and bank account is allowed (may be disabled on maintenance)
    delisted Boolean true if currency is delisted (deposit and trading are stopped)
    payoutFee Number Default withdraw fee
    payoutMinimalAmount Number Minimum withdraw amount
    precisionPayout Number Currency precision for payout (number of digits after the decimal point)
    precisionTransfer Number Currency precision for transfer (number of digits after the decimal point)
    lowProcessingTime Number The lowest processing time in seconds for payout operation. Optional parameter
    highProcessingTime Number The highest processing time in seconds for payout operation. Optional parameter
    avgProcessingTime Number The average processing time in seconds for payout operation. Optional parameter

    Get a certain currency

    curl "https://api.x-changex.com/api/2/public/currency/ETH"  
    

    The above command returns JSON structured like this:

    {
      "id": "ETH",
      "fullName": "Ethereum",
      "crypto": true,
      "payinEnabled": true,
      "payinPaymentId": false,
      "payinConfirmations": 20,
      "payoutEnabled": true,
      "payoutIsPaymentId": false,
      "transferEnabled": true,
      "delisted": false,
      "payoutFee": "0.042800000000",
      "payoutMinimalAmount": "0.00958",
      "precisionPayout": 10,
      "precisionTransfer": 10,
      "lowProcessingTime": "3.518",
      "highProcessingTime": "2411.963",
      "avgProcessingTime": "247.1108947"
    }
    

    GET /api/2/public/currency/{currency}

    Returns the data for a certain currency.

    Requires no API key Access Rights.

    Responses:

    Name Type Description
    id String Currency identifier (code), for example, ''BTC''
    Note: description will simply use currency in the future.
    fullName String Currency full name, for example, ''Bitcoin''
    crypto Boolean Determines whether currency belongs to blockchain
    payinEnabled Boolean Determines whether it is allowed to generate addresses for a deposit
    payinPaymentId Boolean Determines whether it is required to provide additional information other than the address for deposit
    payinConfirmations Number Count of blocks confirmations, which are needed for deposit
    payoutEnabled Boolean Determines whether withdraw is allowed
    payoutIsPaymentId Boolean Determines whether providing of additional information for withdraw is allowed
    transferEnabled Boolean Determines whether transfer between trading account and bank account is allowed (may be disabled on maintenance)
    delisted Boolean true if currency is delisted (deposit and trading are stopped)
    payoutFee Number Default withdraw fee
    payoutMinimalAmount Number Minimum withdraw amount
    precisionPayout Number Currency precision for payout (number of digits after the decimal point)
    precisionTransfer Number Currency precision for transfer (number of digits after the decimal point)
    lowProcessingTime Number The lowest processing time in seconds for payout operation. Optional parameter
    highProcessingTime Number The highest processing time in seconds for payout operation. Optional parameter
    avgProcessingTime Number The average processing time in seconds for payout operation. Optional parameter

    Symbols

    Get a list of all symbols or specified symbols

    curl "https://api.x-changex.com/api/2/public/symbol"  
    

    The above command returns JSON structured like this:

    [      
      {
        "id": "ETHBTC",
        "baseCurrency": "ETH",
        "quoteCurrency": "BTC",
        "quantityIncrement": "0.001",
        "tickSize": "0.000001",
        "takeLiquidityRate": "0.001",
        "provideLiquidityRate": "-0.0001",
        "feeCurrency": "BTC",
        "marginTrading": true,
        "maxInitialLeverage": "10.00"
      }
    ]
    

    GET /api/2/public/symbol

    Return the actual list of currency symbols (currency pairs) traded on exchange. The first listed currency of a symbol is called the base currency, and the second currency is called the quote currency. The currency pair indicates how much of the quote currency is needed to purchase one unit of the base currency. Read more

    You can optionally use comma-separated list of symbols. If it is not provided, null or empty, the request returns all symbols.

    Requires no API key Access Rights.

    Parameter:

    Name Type Description
    symbols String Comma-separated list of symbol codes. Optional parameter

    Responses:

    Name Type Description
    id String Symbol (currency pair) identifier, for example, ''ETHBTC''
    Note: description will simply use symbol in the future.
    baseCurrency String Name (code) of base currency, for example, ''ETH''
    quoteCurrency String Name of quote currency
    quantityIncrement Number Symbol quantity should be divided by this value with no remainder
    tickSize Number Symbol price should be divided by this value with no remainder
    takeLiquidityRate Number Default fee rate
    provideLiquidityRate Number Default fee rate for market making trades
    feeCurrency String Value of charged fee
    marginTrading Boolean Is margin trading available. Optional parameter
    maxInitialLeverage Number Maximum leverage that user can use for margin trading. Optional parameter

    Get a certain symbol

    curl "https://api.x-changex.com/api/2/public/symbol/ETHBTC"  
    

    The above command returns JSON structured like this:

    {
      "id": "ETHBTC",
      "baseCurrency": "ETH",
      "quoteCurrency": "BTC",
      "quantityIncrement": "0.0001",
      "tickSize": "0.000001",
      "takeLiquidityRate": "0.002",
      "provideLiquidityRate": "0.001",
      "feeCurrency": "BTC",
      "marginTrading": true,
      "maxInitialLeverage": "10.00"
    }
    

    GET /api/2/public/symbol/{symbol}

    Returns the data for a certain symbol.

    Requires no API key Access Rights.

    Responses:

    Name Type Description
    id String Symbol (currency pair) identifier, for example, ''ETHBTC''
    Note: description will simply use symbol in the future.
    baseCurrency String Name (code) of base currency, for example, ''ETH''
    quoteCurrency String Name of quote currency
    quantityIncrement Number Symbol quantity should be divided by this value with no remainder
    tickSize Number Symbol price should be divided by this value with no remainder
    takeLiquidityRate Number Default fee rate
    provideLiquidityRate Number Default fee rate for market making trades
    feeCurrency String Value of charged fee
    marginTrading Boolean Is margin trading available. Optional parameter
    maxInitialLeverage Number Maximum leverage that user can use for margin trading. Optional parameter

    Tickers

    Get tickers for all symbols or for specified symbols

    curl "https://api.x-changex.com/api/2/public/ticker"  
    

    The above command returns JSON structured like this:

    [
      {
        "ask": "0.050043",
        "bid": "0.050042",
        "last": "0.050042",
        "open": "0.047800",
        "low": "0.047052",
        "high": "0.051679",
        "volume": "36456.720",
        "volumeQuote": "1782.625000",
        "timestamp": "2017-05-12T14:57:19.999Z",
        "symbol": "ETHBTC"
     }
    ]
    

    GET /api/2/public/ticker

    Returns ticker information.

    You can optionally use comma-separated list of symbols. If it is not provided, null or empty, the request returns tickers for all symbols.

    Requires no API key Access Rights.

    Parameter:

    Name Type Description
    symbols String Comma-separated list of symbol codes. Optional parameter

    Responses:

    Name Type Description
    ask Number or null Best ask price. Can return 'null' if no data
    bid Number or null Best bid price. Can return 'null' if no data
    last Number or null Last trade price. Can return 'null' if no data
    open Number or null Last trade price 24 hours ago. Can return 'null' if no data
    low Number Lowest trade price within 24 hours
    high Number Highest trade price within 24 hours
    volume Number Total trading amount within 24 hours in base currency
    volumeQuote Number Total trading amount within 24 hours in quote currency
    timestamp Datetime Last update or refresh ticker timestamp
    symbol String Symbol name

    Get ticker for a certain symbol

    curl "https://api.x-changex.com/api/2/public/ticker/ETHBTC"  
    

    The above command returns JSON structured like this:

    {
      "symbol": "ETHBTC",
      "ask": "0.020572",
      "bid": "0.020566",
      "last": "0.020574",
      "open": "0.020913",
      "low": "0.020388",
      "high": "0.021084",
      "volume": "138444.3666",
      "volumeQuote": "2853.6874972480",
      "timestamp": "2020-04-02T17:52:36.731Z"
    }
    

    GET /api/2/public/ticker/{symbol}

    Returns the ticker for a certain symbol.

    Requires no API key Access Rights.

    Responses:

    Name Type Description
    ask Number or null Best ask price. Can return 'null' if no data
    bid Number or null Best bid price. Can return 'null' if no data
    last Number or null Last trade price. Can return 'null' if no data
    open Number or null Last trade price 24 hours ago. Can return 'null' if no data
    low Number Lowest trade price within 24 hours
    high Number Highest trade price within 24 hours
    volume Number Total trading amount within 24 hours in base currency
    volumeQuote Number Total trading amount within 24 hours in quote currency
    timestamp Datetime Last update or refresh ticker timestamp
    symbol String Symbol name

    Trades

    Get trades for all symbols or for specified symbols

    curl "https://api.x-changex.com/api/2/public/trades"  
    

    The above command returns JSON structured like this:

    {
       "BTCUSD":[
          {
             "id":782135488,
             "price":"9793.94",
             "quantity":"0.21469",
             "side":"sell",
             "timestamp":"2020-02-24T12:54:41.972Z"
          }
       ],
       "ETHBTC":[
          {
             "id":782135414,
             "price":"0.027668",
             "quantity":"0.069",
             "side":"buy",
             "timestamp":"2020-02-24T12:54:32.843Z"
          }
       ]
    }
    

    GET /api/2/public/trades

    Returns trades information for a symbol with a symbol Id.

    You can optionally use comma-separated list of symbols. If it is not provided, null or empty, the request returns trades for all symbols.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    sort String Sort direction
    Accepted values: ASC, DESC
    Default value: DESC
    from Datetime or Number Interval initial value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value
    till Datetime or Number Interval end value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value
    limit Number Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000
    symbols String Comma-separated list of symbol codes. Optional parameter

    Responses:

    Name Type Description
    id Number Trade identifier
    price Number Trade price
    quantity Number Trade quantity
    side String Trade side
    Accepted values: sell or buy
    timestamp Datetime Trade timestamp

    Get trades for a certain symbol

    curl "https://api.x-changex.com/api/2/public/trades/ETHBTC?sort=DESC"  
    

    The above command returns JSON structured like this:

    [
      {
        "id": 9533117,
        "price": "0.046001",
        "quantity": "0.220",
        "side": "sell",
        "timestamp": "2017-04-14T12:18:40.426Z"
      },
      {
        "id": 9533116,
        "price": "0.046002",
        "quantity": "0.022",
        "side": "buy",
        "timestamp": "2017-04-14T11:56:37.027Z"
      }
    ]
    

    GET /api/2/public/trades/{symbol}

    Returns trades information for a symbol with a symbol Id.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    sort String Sort direction
    Accepted values: ASC, DESC
    Default value: DESC
    by String Defines filter type
    Accepted values: id, timestamp
    Default value: timestamp
    from Datetime or Number Interval initial value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value
    till Datetime or Number Interval end value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value
    limit Number Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000

    Responses:

    Name Type Description
    id Number Trade identifier
    price Number Trade price
    quantity Number Trade quantity
    side String Trade side
    Accepted values: sell or buy
    timestamp Datetime Trade timestamp

    Order Book

    Get Order Book for all symbols or for specified symbols

    curl "https://api.x-changex.com/api/2/public/orderbook"  
    

    The above command returns JSON structured like this:

    {
      "BTCUSD": {
        "symbol": "BTCUSD",
        "ask": [
          {
            "price": "9777.51",
            "size": "4.50579"
          },
          {
            "price": "9777.52",
            "size": "5.79832"
          }
        ],
        "bid": [
          {
            "price": "9777.5",
            "size": "0.00002"
          },
          {
            "price": "9776.26",
            "size": "0.0001"
          }
        ],
        "timestamp": "2020-02-11T11:18:03.857366871Z"
      },
      "ETHBTC": {
        "symbol": "ETHBTC",
        "ask": [
          {
            "price": "0.022626",
            "size": "0.0057"
          },
          {
            "price": "0.022628",
            "size": "1.4259"
          }
        ],
        "bid": [
          {
            "price": "0.022624",
            "size": "0.5748"
          },
          {
            "price": "0.022623",
            "size": "26.5"
          }
        ],
        "timestamp": "2020-02-11T11:18:03.790858502Z"
      }
    }
    

    GET /api/2/public/orderbook

    An Order Book is an electronic list of buy and sell orders for a specific symbol, structured by price level.

    You can optionally use comma-separated list of symbols. If it is not provided, null or empty, the request returns an Order Book for all symbols.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    limit Number Limit of Order Book levels
    Default value: 100
    Set 0 to view full list of Order Book levels.
    symbols String Comma-separated list of symbol codes. Optional parameter

    Responses:

    Name Type Description
    ask Array Ask side array of levels
    bid Array Bid side array of levels
    size Number Total volume of orders with the specified price
    price Number Price level

    Get Order Book for a certain symbol

    curl "https://api.x-changex.com/api/2/public/orderbook/ETHBTC?volume=0.5"  
    

    The above command returns JSON structured like this:

    {
      "ask": [
        {
          "price": "9779.68",
          "size": "2.497"
        }
      ],
      "bid": [
        {
          "price": "9779.67",
          "size": "0.03719"
        },
        {
          "price": "9779.29",
          "size": "0.171"
        },
        {
          "price": "9779.27",
          "size": "0.171"
        },
        {
          "price": "9779.21",
          "size": "0.171"
        }
      ],
      "timestamp": "2020-02-11T11:30:38.597950917Z",
      "askAveragePrice": "9779.68",
      "bidAveragePrice": "9779.29"
    }
    

    GET /api/2/public/orderbook/{symbol}

    The request returns an Order Book for a certain symbol.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    limit Number Limit of Order Book levels
    Default value: 100
    Set 0 to view full list of Order Book levels.
    volume Number Desired volume for market depth search

    Please note that if the Volume is specified, the Limit will be ignored, askAveragePrice and bidAveragePrice are returned in response.

    Responses:

    Name Type Description
    ask Array Ask side array of levels
    bid Array Bid side array of levels
    size Number Total volume of orders with the specified price
    price Number Price level
    askAveragePrice Number Average aggregated price for the ask side orders
    bidAveragePrice Number Average aggregated price for the bid side orders

    Candles

    Get candles for all symbols or for specified symbols

    curl "https://api.x-changex.com/api/2/public/candles"  
    

    The above command returns JSON structured like this:

    {
       "BTCUSD":[
          {
             "timestamp":"2013-12-27T08:23:00.000Z",
             "open":"777",
             "close":"777",
             "min":"777",
             "max":"777",
             "volume":"0.1",
             "volumeQuote":"77.7"
          }
       ],
       "ETHBTC":[
          {
             "timestamp":"2015-08-20T19:01:00.000Z",
             "open":"0.006",
             "close":"0.006",
             "min":"0.006",
             "max":"0.006",
             "volume":"0.003",
             "volumeQuote":"0.000018"
          }
       ]
    }
    

    GET /api/2/public/candles

    Candles are used for the representation of a specific symbol as an OHLC chart.

    You can optionally use comma-separated list of symbols. If it is not provided, null or empty, the request returns candles for all symbols.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    period String Accepted values: M1 (one minute), M3, M5, M15, M30, H1 (one hour), H4, D1 (one day), D7, 1M (one month)
    Default value: M30 (30 minutes)
    sort String Sort direction
    Accepted values: ASC, DESC
    Default value: ASC
    from Datetime Interval initial value (optional parameter)
    till Datetime Interval end value (optional parameter)
    limit Number Limit of candles
    Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000
    symbols String Comma-separated list of symbol codes. Optional parameter

    Responses:

    Name Type Description
    timestamp Datetime Candle timestamp
    open Number Open price
    close Number Closing price
    min Number Lowest price for the period
    max Number Highest price for the period
    volume Number Volume in base currency
    volumeQuote Number Volume in quote currency

    Get candles for a certain symbol

    curl "https://api.x-changex.com/api/2/public/candles/ETHBTC"  
    

    The above command returns JSON structured like this:

    [
      {
        "timestamp": "2017-10-20T20:00:00.000Z",
        "open": "0.050459",
        "close": "0.050087",
        "min": "0.050000",
        "max": "0.050511",
        "volume": "1326.628",
        "volumeQuote": "66.555987736"
      },
      {
        "timestamp": "2017-10-20T20:30:00.000Z",
        "open": "0.050108",
        "close": "0.050139",
        "min": "0.050068",
        "max": "0.050223",
        "volume": "87.515",
        "volumeQuote": "4.386062831"
      }
    ]
    

    GET /api/2/public/candles/{symbol}

    The request returns candles for a certain symbol.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    period String Accepted values: M1 (one minute), M3, M5, M15, M30, H1 (one hour), H4, D1 (one day), D7, 1M (one month)
    Default value: M30 (30 minutes)
    sort String Sort direction
    Accepted values: ASC, DESC
    Default value: ASC
    from Datetime Interval initial value (optional parameter)
    till Datetime Interval end value (optional parameter)
    limit Number Limit of candles
    Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000

    Responses:

    Name Type Description
    timestamp Datetime Candle timestamp
    open Number Open price
    close Number Closing price
    min Number Lowest price for the period
    max Number Highest price for the period
    volume Number Volume in base currency
    volumeQuote Number Volume in quote currency

    Authentication

    curl -u "publicKey:secretKey" https://api.x-changex.com/api/2/trading/balance
    
    import requests
    session = requests.session()
    session.auth = ("publicKey", "secretKey")
    
    
    const fetch = require('node-fetch');
    
    const credentials = Buffer.from('publicKey' + ':' + 'secretKey').toString('base64');
    
    fetch('https://api.x-changex.com/api/2/trading/balance', {
        method: 'GET',
        headers: {
            'Authorization': 'Basic ' + credentials
        }
    });
    
    

    Public market data are available without authentication. Authentication is required for other requests.

    You should create API keys on the API Settings page. You can create multiple API keys with different access rights for your applications.

    Use Basic Authentication to access the REST API.

    Authentication HS256

    import requests
    from requests.auth import AuthBase
    from urllib.parse import urlparse
    from base64 import b64encode
    import hmac
    import hashlib
    import time
    
    
    class HS256(AuthBase):
        def __init__(self, username, password):
            self.username = username
            self.password = password
    
        def __call__(self, r):
            url = urlparse(r.url)
            timestamp = str(int(time.time()))
            msg = r.method + timestamp + url.path
            if url.query != "":
                msg += "?" + url.query
            if r.body:
                msg += r.body
    
            signature = hmac.new(self.password.encode(), msg.encode(), hashlib.sha256).hexdigest()
            authstr = "HS256 " + b64encode(
                        b':'.join((self.username.encode(), timestamp.encode(), signature.encode()))).decode().strip()
    
            r.headers['Authorization'] = authstr
            return r
    
    session = requests.session()
    session.auth = HS256("publicKey", "secretKey")
    
    balance = session.get("https://api.x-changex.com/api/2/trading/balance").json()
    # or without session
    balance = requests.get("https://api.x-changex.com/api/2/trading/balance", auth=HS256("publicKey", "secretKey")).json()
    

    The alternative authentication method is the HMAC signature.

    You should set header Authorization with publicKey and signature base64 encoded:

    1. Create hmac signature with secretKey as a key and sign request "method+timestamp+url+body"
    2. Like as basic authorization add header "Authorization: HS256 " + base64(publicKey+":"+timestamp+":"+signature hex encoded)

    Trading

    Trading Balance

    curl -X GET -u "publicKey:secretKey" \
         "https://api.x-changex.com/api/2/trading/balance"
    
    import requests
    session = requests.session()
    session.auth = ("publicKey", "secretKey")
    b = session.get('https://api.x-changex.com/api/2/trading/balance').json()
    print(b)
    

    The above command returns JSON structured like this:

        [
          {
            "currency": "ETH",
            "available": "10.000000000",
            "reserved": "0.560000000"
          },
          {
            "currency": "BTC",
            "available": "0.010205869",
            "reserved": "0"
          }
        ]
    

    GET /api/2/trading/balance

    Returns the user's trading balance.

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Responses:

    Name Type Description
    currency String Currency code
    available Number Amount available for trading or transfer to main account
    reserved Number Amount reserved for active orders or incomplete transfers to main account

    Order model

    Order model consists of:

    Name Type Description
    id Number Order unique identifier as assigned by exchange
    clientOrderId String Order unique identifier as assigned by trader. Uniqueness must be guaranteed within a single trading day, including all active orders.
    symbol String Trading symbol name
    side String Trade side
    Accepted values: sell or buy
    status String Order state
    Accepted values: new, suspended, partiallyFilled, filled, canceled, expired
    type String Accepted values: limit, market, stopLimit, stopMarket
    timeInForce String Time in Force is a special instruction used when placing a trade to indicate how long an order will remain active before it is executed or expired.
    GTC - ''Good-Till-Cancelled'' order won't be closed until it is filled.
    IOC - ''Immediate-Or-Cancel'' order must be executed immediately. Any part of an IOC order that cannot be filled immediately will be cancelled.
    FOK - ''Fill-Or-Kill'' is a type of ''Time in Force'' designation used in securities trading that instructs a brokerage to execute a transaction immediately and completely or not execute it at all.
    Day - keeps the order active until the end of the trading day (UTC).
    GTD - ''Good-Till-Date''. The date is specified in expireTime.
    quantity Number Order quantity
    price Number Order price
    avgPrice Number Average execution price, only for history orders
    cumQuantity Number Cumulative executed quantity
    createdAt Datetime Order creation date
    updatedAt Datetime Date of order's last update
    stopPrice Number Required for stop-limit and stop-market orders
    postOnly Boolean A post-only order is an order that does not remove liquidity. If your post-only order causes a match with a pre-existing order as a taker, then the order will be cancelled.
    expireTime Datetime Date of order expiration for timeInForce = GTD
    tradesReport Array of trades Optional list of trades
    {
      "id": 828680665,
      "clientOrderId": "f4307c6e507e49019907c917b6d7a084",
      "symbol": "ETHBTC",
      "side": "sell",
      "status": "partiallyFilled",
      "type": "limit",
      "timeInForce": "GTC",
      "quantity": "13.942",
      "price": "0.011384",
      "cumQuantity": "5.240",
      "createdAt": "2017-01-16T14:18:47.321Z",
      "updatedAt": "2017-01-19T15:23:54.876Z",
      "postOnly": false
    }
    

    Get active orders

    curl -X GET -u "publicKey:secretKey" \
         "https://api.x-changex.com/api/2/order"
    
    import requests
    session = requests.session()
    session.auth = ("publicKey", "secretKey")
    b = session.get('https://api.x-changex.com/api/2/order').json()
    print(b)
    

    The above command returns JSON structured like this:

    [
      {
        "id": 840450210,
        "clientOrderId": "c1837634ef81472a9cd13c81e7b91401",
        "symbol": "ETHBTC",
        "side": "buy",
        "status": "partiallyFilled",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "0.020",
        "price": "0.046001",
        "cumQuantity": "0.005",
        "postOnly": false,
        "createdAt": "2017-05-12T17:17:57.437Z",
        "updatedAt": "2017-05-12T17:18:08.610Z"
      }
    ]
    

    GET /api/2/order

    Return array of active orders.

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Parameters:

    Name Type Description
    symbol String Optional parameter to filter active orders by symbol

    Response: Array of orders

    Get active order by clientOrderId

    curl -X GET -u "publicKey:secretKey" \
         "https://api.x-changex.com/api/2/order/c1837634ef81472a9cd13c81e7b91401"
    
    import requests
    session = requests.session()
    session.auth = ("publicKey", "secretKey")
    b = session.get('https://api.x-changex.com/api/2/order/c1837634ef81472a9cd13c81e7b91401').json()
    print(b)
    

    The above command returns JSON structured like this:

    {
        "id": 840450210,
        "clientOrderId": "c1837634ef81472a9cd13c81e7b91401",
        "symbol": "ETHBTC",
        "side": "buy",
        "status": "partiallyFilled",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "0.020",
        "price": "0.046001",
        "cumQuantity": "0.005",
        "postOnly": false,
        "createdAt": "2017-05-12T17:17:57.437Z",
        "updatedAt": "2017-05-12T17:18:08.610Z"
    }
    

    GET /api/2/order/{clientOrderId}

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Parameters:

    Name Type Description
    wait Number Time in milliseconds (optional parameter)
    Max value: 60000
    Default value: none
    While using long polling request: if order is filled, cancelled or expired order info will be returned instantly. For other order statuses, actual order info will be returned after specified wait time.

    Response: order

    Create new order

    curl -X PUT -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/order/d8574207d9e3b16a4a5511753eeef175" \
        -d 'symbol=ETHBTC&side=sell&quantity=0.063&price=0.046016'
    
        import requests
        session = requests.session()
        session.auth = ("publicKey", "secretKey")
        orderData = {'symbol':'ethbtc', 'side': 'sell', 'quantity': '0.063', 'price': '0.046016' }
        r = session.post('https://api.x-changex.com/api/2/order', data = orderData)        
        print(r.json())
    
    

    The above command returns JSON structured like this:

        {
            "id": 0,
            "clientOrderId": "d8574207d9e3b16a4a5511753eeef175",
            "symbol": "ETHBTC",
            "side": "sell",
            "status": "new",
            "type": "limit",
            "timeInForce": "GTC",
            "quantity": "0.063",
            "price": "0.046016",
            "cumQuantity": "0.000",
            "postOnly": false,
            "createdAt": "2017-05-15T17:01:05.092Z",
            "updatedAt": "2017-05-15T17:01:05.092Z"
        }
    

    Error response example:

    {
      "error": {
        "code": 20001,
        "message": "Insufficient funds",
        "description": "Check that the funds are sufficient, given commissions"
      }
    }
    

    POST /api/2/order
    PUT /api/2/order/{clientOrderId}

    Requires the "Place/cancel orders" API key Access Right.

    Price accuracy and quantity

    Symbol config contains the tickSize parameter which means that price should be divided by tickSize with no remainder.
    quantity should be divided by quantityIncrement with no remainder.
    By default, if strictValidate is not enabled, the Server rounds half down the price and quantity for tickSize and quantityIncrement.

    Example of ETHBTC: tickSize = '0.000001', then price '0.046016' is valid, '0.0460165' is invalid.

    Fees

    Charged fee is determined in symbol's feeCurrency. Maker-taker fees offer a transaction rebate provideLiquidityRate to those who provide liquidity (the market maker), while charging customers who take that liquidity takeLiquidityRate.

    To create buy orders, you must have sufficient balance including fees.
    Available balance > price * quantity * (1 + takeLiquidityRate)

    Order result status

    For orders with timeInForce = IOC or FOK, the REST API returns final order state: filled or expired.

    If order can be instantly executed, then the REST API returns a status of filled or partiallyFilled in the order's info.

    Parameters:

    Name Type Description
    clientOrderId String Optional parameter.
    If it is skipped, it will be generated by the Server. Uniqueness must be guaranteed within a single trading day, including all active orders.
    symbol String Trading symbol
    side String Trade side
    Accepted values: sell or buy
    type String Optional parameter
    Accepted values: limit, market, stopLimit, stopMarket
    Default value: limit
    timeInForce String Optional parameter
    Accepted values: GTC, IOC, FOK, Day, GTD
    Default value: GTC
    quantity Number Order quantity
    price Number Order price. Required for limit order types
    stopPrice Number Required for stop-limit and stop-market orders
    expireTime Datetime Required for orders with timeInForce = GTD
    strictValidate Boolean Price and quantity will be checked for incrementation within the symbol’s tick size and quantity step. See the symbol's tickSize and quantityIncrement.
    postOnly Boolean If your post-only order causes a match with a pre-existing order as a taker, then the order will be cancelled.
    takeLiquidityMarkup Number Optional liquidity taker fee, a fraction of order volume, such as 0.001 (for 0.1% fee)
    provideLiquidityMarkup Number Optional liquidity provider fee, a fraction of order volume, such as 0.001 (for 0.1% fee)

    Response: order

    Cancel orders

    DELETE /api/2/order

    Cancel all active orders, or all active orders for a specified symbol.

    Requires the "Place/cancel orders" API key Access Right.

    Parameters:

    Name Type Description
    symbol String Optional parameter to filter active orders by symbol

    Response: Array of orders

    Cancel order by clientOrderId

    curl -X DELETE -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/order/d8574207d9e3b16a4a5511753eeef175"    
    

    The above command returns JSON structured like this:

    {
      "id": 0,
      "clientOrderId": "d8574207d9e3b16a4a5511753eeef175",
      "symbol": "ETHBTC",
      "side": "sell",
      "status": "canceled",
      "type": "limit",
      "timeInForce": "GTC",
      "quantity": "0.000",
      "price": "0.046016",
      "cumQuantity": "0.000",
      "postOnly": false,
      "createdAt": "2017-05-15T17:01:05.092Z",
      "updatedAt": "2017-05-15T18:08:57.226Z"
    }
    

    Example of Order not found error response:

    {
      "error": {
        "code": 20002,
        "message": "Order not found",
        "description": ""
      }
    }
    

    DELETE /api/2/order/{clientOrderId}

    Requires the "Place/cancel orders" API key Access Right.

    Response: order

    Get trading commission

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/trading/fee/ETHBTC"    
    

    The above command returns JSON structured like this:

    {
      "takeLiquidityRate": "0.001",
      "provideLiquidityRate": "-0.0001"
    }
    

    GET /api/2/trading/fee/{symbol}

    Get personal trading commission rate.

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Trading history

    Orders history

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/history/order?symbol=ETHBTC"    
    
    [
      {
        "id": 828680665,
        "clientOrderId": "f4307c6e507e49019907c917b6d7a084",
        "symbol": "ETHBTC",
        "side": "sell",
        "status": "partiallyFilled",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "13.942",
        "price": "0.011384",
        "avgPrice": "0.055487",
        "cumQuantity": "5.240",
        "createdAt": "2017-01-16T14:18:47.321Z",
        "updatedAt": "2017-01-19T15:23:54.876Z"
      },
      {
        "id": 828680667,
        "clientOrderId": "f4307c6e507e49019907c917b6d7a084",
        "symbol": "ETHBTC",
        "side": "sell",
        "status": "partiallyFilled",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "13.942",
        "price": "0.011384",
        "avgPrice": "0.045000",
        "cumQuantity": "5.240",
        "createdAt": "2017-01-16T14:18:50.321Z",
        "updatedAt": "2017-01-19T15:23:56.876Z"
      }
    ]
    

    GET /api/2/history/order

    All orders older than 24 hours without trades are deleted.

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Parameters:

    Name Type Description
    symbol String Optional parameter to filter orders by symbol.
    clientOrderId String If set, other parameters will be ignored, including limit and offset.
    from Datetime Interval initial value (optional parameter)
    till Datetime Interval end value (optional parameter)
    limit Number Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000

    Response: Array of orders

    Trades history

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/history/trades?symbol=ETHBTC"    
    
    [
      {
        "id": 9535486,
        "orderId": 816088377,
        "clientOrderId": "f8dbaab336d44d5ba3ff578098a68454",
        "symbol": "ETHBTC",
        "side": "sell",
        "quantity": "0.061",
        "price": "0.045487",
        "fee": "0.000002775",
        "timestamp": "2017-05-17T12:32:57.848Z"
      },
      {
        "id": 9535437,
        "orderId": 816088021,
        "clientOrderId": "27b9bfc068b44194b1f453c7af511ed6",
        "symbol": "ETHBTC",
        "side": "buy",
        "quantity": "0.038",
        "price": "0.046000",
        "fee": "-0.000000174",
        "timestamp": "2017-05-17T12:30:57.848Z"
      }
    ]
    

    GET /api/2/history/trades

    Get the user's trading history.

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Parameters:

    Name Type Description
    symbol String Optional parameter to filter active orders by symbol
    sort String Sort direction
    Accepted values: DESC, ASC
    Default value: DESC
    by String Defines filter type
    Accepted values: timestamp, id. Default value: id
    from Datetime or Number Interval initial value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value.
    till Datetime or Number Interval end value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value.
    limit Number Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000
    margin String Filtering of margin orders
    Accepted values: include, only, 'ignore'
    Default value: include

    Responses:

    Name Type Description
    id Number Trade unique identifier as assigned by exchange
    orderId Number Order unique identifier as assigned by exchange
    clientOrderId String Order unique identifier as assigned by trader
    symbol String Trading symbol
    side String Trade side
    Accepted values: sell or buy
    quantity Number Trade quantity
    price Number Trade price
    fee Number Trade commission
    Can be negative (''rebate'' - reward paid to a trader). See fee currency in the symbol config.
    liquidation Boolean Optional parameter. Liquidation trade flag for margin trades
    timestamp Datetime Trade timestamp
    taker Boolean Instantly filled order flag

    Trades by order

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/history/order/816088021/trades"    
    
    [
      {
        "id": 828680665,
        "orderId": 816088021,
        "clientOrderId": "f4307c6e507e49019907c917b6d7a084",
        "symbol": "ETHBTC",
        "side": "sell",
        "status": "partiallyFilled",
        "type": "limit",
        "timeInForce": "GTC",
        "price": "0.011384",
        "quantity": "13.942",
        "postOnly": false,
        "cumQuantity": "5.240",
        "createdAt": "2017-01-16T14:18:47.321Z",
        "updatedAt": "2017-01-19T15:23:54.876Z"
      }
    ]
    
    

    GET /api/2/history/order/{orderId}/trades

    Returns the user's trading order with a specified orderId.

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Parameters:

    Name Type Description
    orderId Number Order id

    orderId is required in cause of clientOrderId can be non-unique during long period.

    Responses:

    Name Type Description
    id Number Trade unique identifier as assigned by exchange
    orderId Number Order unique identifier as assigned by exchange
    clientOrderId String Order unique identifier as assigned by trader
    symbol String Trading symbol
    side String Trade side
    Accepted values: sell or buy
    quantity Number Trade quantity
    price Number Trade price
    fee Number Trade commission
    Can be negative (''rebate'' - reward paid to a trader). See fee currency in the symbol config.
    liquidation Boolean Optional parameter. Liquidation trade flag for margin trades
    timestamp Datetime Trade timestamp
    taker Boolean Instantly filled order flag

    Account management

    Account balance

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/balance"    
    
    [
      {
        "currency": "BTC",
        "available": "0.0504600",
        "reserved": "0.0000000"
      },
      {
        "currency": "ETH",
        "available": "30.8504600",
        "reserved": "0.0000000"
      }
    ]
    

    GET /api/2/account/balance

    Returns the user's account balance.

    Requires the "Payment information" API key Access Right.

    Responses:

    Name Type Description
    currency String Currency code
    available Number Amount available for withdraw or transfer to trading account
    reserved Number Amount reserved for incomplete transactions

    Deposit crypto address

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/address/NXT"    
    
    {
      "address": "NXT-G22U-BYF7-H8D9-3J27W",
      "publicKey": "f79779a3a0c7acc75a62afe8125de53106c6a19c1ebdf92a3598676e58773df0"
    }
    

    GET /api/2/account/crypto/address/{currency} - Get current address

    Requires the "Payment information" API key Access Right.

    POST /api/2/account/crypto/address/{currency} - Create new address

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    networkCode String Optional parameter
    Network code

    Responses:

    Name Type Description
    address String Address for deposit
    paymentId String Optional parameter
    If this parameter is set, it is required for deposit.
    publicKey String Optional parameter
    If this parameter is set, it is required for deposit.
    networkCode String Optional parameter
    Network code

    Last 10 deposit crypto address

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/addresses/NXT"    
    
    [
      {
        "address": "NXT-G22U-BYF7-H8D9-3J27W",
        "publicKey": "f79779a3a0c7acc75a62afe8125de53106c6a19c1ebdf92a3598676e58773df0"
      }
    ]
    

    GET /api/2/account/crypto/addresses/{currency} - Get last 10 deposit addresses for currency

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    networkCode String Optional parameter
    Network code

    Responses:

    Name Type Description
    address String Address for deposit
    paymentId String Optional
    If this field is presented, it is required for deposit.
    publicKey String Optional
    If this field is presented, it is required for deposit.
    networkCode String Optional parameter
    Network code

    Last 10 used crypto address

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/used-addresses/NXT"
    
    [
      {
        "address": "NXT-G22U-BYF7-H8D9-3J27W",
        "paymentId": "f79779a3a0c7acc75a62afe8125de53106c6a19c1ebdf92a3598676e58773df0"
      }
    ]
    

    GET /api/2/account/crypto/used-addresses/{currency} - Get last 10 unique addresses used for withdraw by currency

    Note: used long ago addresses may be omitted, even if they are among last 10 unique addresses

    Requires the "Payment information" API key Access Right.

    Name Type Description
    networkCode String Optional parameter
    Network code

    Responses:

    Name Type Description
    address String Address identifier
    paymentId String Optional parameter

    Withdraw crypto

    curl -X POST -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/withdraw" \
        -d 'currency=BTC&amount=0.001&address=example_address&autoCommit=false'
    
    {
      "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
    }
    

    POST /api/2/account/crypto/withdraw

    Requires the "Withdraw cryptocurrencies" API key Access Right.

    Parameters:

    Name Type Description
    currency String Currency code
    networkCode String Optional parameter
    Network code.
    amount Number The amount that will be sent to the specified address
    address String Address identifier
    paymentId String Optional parameter
    includeFee Boolean Default value: false
    If true is set, then total spent value will include fees.
    autoCommit Boolean Default value: true
    If false is set, then you should commit or rollback transaction in an hour. Used in two phase commit schema.
    publicComment String Optional parameter. Maximum length is 255

    Responses:

    Name Type Description
    id String Transaction unique identifier as assigned by exchange

    Transfer convert between currencies

    curl -X POST -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/transfer-convert" \
        -d 'fromCurrency=USDT20&toCurrency=usd&amount=0.001'
    
    {
      "result": ["d2ce578f-647d-4fa0-b1aa-4a27e5ee597b", "d2ce57hf-6g7d-4ka0-b8aa-4a27e5ee5i7b"]
    }
    

    POST /api/2/account/crypto/transfer-convert

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    fromCurrency String Currency code
    toCurrency String Currency code
    amount Number The amount that will be sent to the specified address

    Responses:

    Name Type Description
    result Array Transaction unique identifiers as assigned by exchange

    Withdraw crypto commit or rollback

    curl -X PUT -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/withdraw/d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
    
    {
      "result": true
    }
    

    PUT /api/2/account/crypto/withdraw/{id} - Commit

    DELETE /api/2/account/crypto/withdraw/{id} - Rollback

    Requires the "Withdraw cryptocurrencies" API key Access Right.

    Both methods are idempotent

    Responses:

    Name Type Description
    result Boolean True, if request is completed

    Estimate withdraw fee

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/estimate-withdraw?currency=BTC&amount=0.01"
    
    {
      "fee": "0.0008"
    }
    

    GET /api/2/account/crypto/estimate-withdraw

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    currency String Currency code
    networkCode String Optional parameter
    Network code
    amount Number Expected withdraw amount

    Responses:

    Name Type Description
    fee Number Fee rate.

    Estimate withdraw fee levels

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/estimate-withdraw-levels?currency=BTC&amount=0.01"
    
    [
      {
        "feeLevelId": 1,
        "comment": "",
        "fee": "0.0002",
        "isDefault": true
      }
    ]
    

    GET /api/2/account/crypto/estimate-withdraw-levels

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    currency String Currency code
    amount Number Expected withdraw amount

    Responses:

    Name Type Description
    feeLevelId Number Fee level identifier.
    comment String Text comment.
    fee String Fee rate.
    isDefault Boolean Flag indicating whether a fee level is default fee level.

    Check if crypto address belongs to current account

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/crypto/is-mine/1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2"
    
    {
      "result": true
    }
    

    GET /api/2/account/crypto/is-mine/{address}

    Requires the "Payment information" API key Access Right.

    Responses:

    Name Type Description
    result Boolean True, if address belongs to current account

    Transfer money between trading account and bank account

    curl -X POST -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/transfer" \
        -d "currency=eth&amount=0.01&type=bankToExchange"
    
    {
      "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
    }
    

    POST /api/2/account/transfer

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    currency String Currency code
    amount Number The amount that will be transferred between balances
    type String Accepted values: bankToExchange, exchangeToBank

    Responses:

    Name Type Description
    id String Transaction unique identifier as assigned by exchange

    Transfer money to another user by email or username

    curl -X POST -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/transfer/internal" \
        -d "by=email&identifier=user@example.com&currency=BTC&amount=0.001"
    
    {
      "result": "fd3088da-31a6-428a-b9b6-c482673ff0f2"
    }
    

    POST /api/2/account/transfer/internal

    Requires the "Withdraw cryptocurrencies" API key Access Right.

    Parameters:

    Name Type Description
    currency String Currency code
    amount Number The amount that will be transferred
    by String Accepted values: email, username
    identifier String Identifier value. Either email or username

    Responses:

    Name Type Description
    result String Transaction unique identifier as assigned by exchange

    Get transactions history

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/account/transactions?currency=ETH&sort=DESC"
    
    [
      {
        "id": "6a2fb54d-7466-490c-b3a6-95d8c882f7f7",
        "index": 20400458,
        "currency": "ETH",
        "amount": "38.616700000000000000000000",
        "fee": "0.000880000000000000000000",
        "address": "0xfaEF4bE10dDF50B68c220c9ab19381e20B8EEB2B",        
        "hash": "eece4c17994798939cea9f6a72ee12faa55a7ce44860cfb95c7ed71c89522fe8",
        "status": "pending",
        "type": "payout",
        "createdAt": "2017-05-18T18:05:36.957Z",
        "updatedAt": "2017-05-18T19:21:05.370Z"
      }
    ]
    

    GET /api/2/account/transactions

    GET /api/2/account/transactions/{id} - get transaction by transaction id

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    currency String Currency code
    sort String Sort direction
    Accepted values: DESC, ASC
    Default value: DESC
    by String Defines filter type
    Accepted values: timestamp or index
    Default value timestamp
    from Datetime or Number Interval initial value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value.
    till Datetime or Number Interval end value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value.
    limit Number Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000
    showSenders Boolean Default value: false
    Show senders addresses for payins

    Responses:

    Name Type Description
    id String Transaction unique identifier as assigned by exchange
    index Number Internal index value that represents when the entry was updated
    currency String Currency code
    amount Number Amount of traded currency
    fee Number Payment commission value
    address String Address identifier
    paymentId String Optional parameter
    hash String Transaction hash
    status String Accepted values: created, pending, failed, success
    type String Accepted values: payout (crypto withdraw transaction), payin (crypto deposit transaction), deposit, withdraw, bankToExchange, exchangeToBank
    subType String Optional parameter
    Currently accepted values: swap (swap between currencies), offchain (offchain transaction). Warning: possible subTypes list may be extended in future
    senders Array of String senders for this payin transaction
    shown only for payins and showSenders = true
    offchainId Array of String Transaction id of external system
    confirmations Number Optional parameter
    Current count of confirmations for transaction in network
    publicComment String Optional parameter
    errorCode String Possible payout error reason: INVALID_ADDRESS, INVALID_PAYMENT_ID, BAD_PRECISION
    createdAt Datetime Transaction creation date
    updatedAt Datetime Date of transactions last update
    commitRisk Commit Risk Optional. Deposit risk score info.

    Commit Risk model consists of:

    Name Type Description
    score Number Risk score that decreases non-linearly when the transaction gains confirmations.
    Scores from 0 to 50 imply the transaction may be considered committed (but it is not guaranteed) or it may take at least half an hour otherwise.
    Possible values: 0100
    rbf Boolean Flag indicating whether the transaction did not gain a sufficient number of confirmations and may be replaced by another one for an additional fee.
    This value indicates the transaction is complete and do not affect the score.
    false value along with a score above 50 gives a good chance that the transaction is irreversible.
    lowFee Boolean Flag indicating whether the actual network fee is lower than the estimated one.
    This value indicates the difference between the estimated fee and the actual paid fee and do not affect the score.

    Sub-accounts

    Get sub-accounts list

    curl -X GET -u "publicKey:secretKey" "https://api.x-changex.com/api/2/sub-acc"
    

    The above command returns JSON structured like this:

    {
      "result": [
        {"id": 7988900, "email": "user+1@example.com", "status": "active"},
        {"id": 7988906, "email": "user+2@example.com", "status": "active"},
        {"id": 7988909, "email": "user+3@example.com", "status": "disable"},
        {"id": 7988918, "email": "user+4@example.com", "status": "disable"},
        {"id": 7988921, "email": "user+5@example.com", "status": "disable"},
        {"id": 7989017, "email": "user+6@example.com", "status": "new"},
        {"id": 8001467, "email": "user+8@example.com", "status": "new"}
      ]
    }
    

    Error response example:

    Failed authorization:

    {
      "error": {
        "code": 1002,
        "message": "Authorization is required or has been failed"
      }
    }
    

    Empty sub-account's list:

    {
      "result": []
    }
    

    GET /api/2/sub-acc

    Returns list of sub-accounts per a super account.

    Requires no API key Access Rights.

    Responses:

    Name Type Description
    id Number Unique identifier of a sub-account.
    email String Email address of a sub-account.
    status String User status of a sub-account. Accepted values: new, active, disable.

    Freeze sub-account

    curl -X POST -u "publicKey:secretKey" "https://api.x-changex.com/api/2/sub-acc/freeze" \
        -d "ids=7988909"
    

    The above command returns JSON structured like this:

    {
      "result": true
    }
    

    Error response example:

    Sub-accounts are already frozen or disabled:

    {
        "error": {
            "code": 21004,
            "message": "Sub account is already frozen or disabled"
        }
    }
    

    POST /api/2/sub-acc/freeze

    Freezes sub-accounts listed. It implies that the Sub-accounts frozen wouldn't be able to:

    For any sub-account listed, all orders will be canceled and all funds will be transferred form the Trading balance.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    ids Array Sub-accounts' userIds separated by commas (,). Those could be obtained by GET /api/2/sub-acc request.

    Responses:

    Name Type Description
    result Boolean Value indicating, whether sub-accounts were successfully frozen.

    Activate sub-account

    curl -X POST -u "publicKey:secretKey" "https://api.x-changex.com/api/2/sub-acc/activate" \
        -d 'ids=7988909,7988918'
    

    The above command returns JSON structured like this:

    {
      "result": true
    }
    

    Error response example:

    Sub-accounts are disabled, and their functionality can't be restored through activation:

    {
      "result": false
    }
    

    Failed authorization:

    {
      "error": {
        "code": 1002,
        "message": "Authorization is required or has been failed"
      }
    }
    

    Wrong input data format:

    {
      "error": {
        "code": 10001,
        "message": "Validation error",
        "description": "Param 'ids' required"
      }
    }
    

    Sub-accounts listed don't exist:

    {
      "error": {
        "code": 500,
        "message": "Internal Server Error",
        "description": "Cannot find sub account 7988920"
      }
    }
    
    

    POST /api/2/sub-acc/activate

    Activates sub-accounts listed. It would make sub-accounts active after being frozen.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    ids Array Sub-accounts' userIds separated by commas (,). Those could be obtained by GET /api/2/sub-acc request.

    Responses:

    Name Type Description
    result Boolean Value indicating, whether sub-accounts were successfully activated.

    Transfer funds

    curl -X POST -u "publicKey:secretKey" "https://api.x-changex.com/api/2/sub-acc/transfer" \
        -d "subAccountId=7988900&amount=1&currency=BTC&type=deposit"
    

    The above command returns JSON structured like this:

    {
      "result": "ae37e806-0191-45fc-8c49-18137274772c"
    }
    
    

    Error response example:

    Insufficient permissions:

    {
      "error": {
        "code": 1003,
        "message": "Action is forbidden for this API key"
      }
    }
    
    

    Sub-account is frozen or disabled:

    {
      "error": {
        "code": 500,
        "message": "Internal Server Error",
        "description": "Bad Request"
      }
    }
    

    Insufficient funds:

    {
      "error": {
        "code": 20001,
        "message": "Internal Server Error",
        "description": "Bad Request"
      }
    }
    

    POST /api/2/sub-acc/transfer

    Transfers funds from the master account to sub-account or from sub-account to the master account.

    Requires the "Withdraw cryptocurrencies" API key Access Right.

    Parameters:

    Name Type Description
    subAccountId Number Identifier of a sub-account to deposit/withdraw funds.
    amount Number Amount of funds to transferred.
    currency String Name (code) of base currency, for example, "BTC".
    type String Type of transaction. Accepted values: deposit, withdraw.

    Responses:

    Name Type Description
    result String Identifier of the transaction resulting.

    Get withdrawal settings

    curl -X GET -u "publicKey:secretKey" "https://api.x-changex.com/api/2/sub-acc/acl?subAccountIds=7988906"
    

    The above command returns JSON structured like this:

    {
        "result": [
          {
            "subAccountId": 7988906,
            "isPayoutEnabled": true,
            "description": ""
          }
        ]
    }
    

    Error response example:

    Insufficient permissions:

    {
      "error": {
        "code": 1003,
        "message": "Action is forbidden for this API key"
      }
    }
    
    

    Sub-account is frozen or disabled:

    {
      "result": []
    }
    
    

    GET /api/2/sub-acc/acl

    Returns a list of withdrawal settings for sub-accounts listed.

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    subAccountIds Array Sub-accounts' userIds separated by commas (,). Those could be obtained by GET /api/2/sub-acc request.

    Responses:

    Name Type Description
    subAccountId Number Unique identifier of a sub-account.
    isPayoutEnabled Boolean Value indicating, whether withdrawals are enabled (true) or not (false).
    description String Textual description. Normally left empty.

    Change withdrawal settings

    curl -X PUT -u "publicKey:secretKey" "https://api.x-changex.com/api/2/sub-acc/acl/7988900"
        -d "isPayoutEnabled=false&description=spam"
    

    The above command returns JSON structured like this:

    {
      "result": [
        {
          "id": 7988900,
          "isPayoutEnabled": true,
          "description": "spam"
        }
      ]
    }
    

    Error response example:

    Sub-account is frozen or disabled:

    {
      "error": {
        "code": 10021,
        "message": "user disabled"
      }
    }
    
    

    Insufficient permissions:

    {
      "error": {
        "code": 1003,
        "message": "Action is forbidden for this API key"
      }
    }
    
    

    PUT /api/2/sub-acc/acl/{subAccountUserId}

    Disables or enables withdrawals for a sub-account.

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type. Description
    isPayoutEnabled Boolean Value indicating the desired state of withdrawals.
    description String Textual description.

    Responses:

    Name Type Description
    subAccountId Number Unique identifier of a sub-account.
    isPayoutEnabled Boolean Value indicating, whether withdrawals are enabled (true) or not (false). It must be equal to the value in a request.
    description String Textual description. It duplicates the value in a request.

    Get sub-account balance

    curl -X GET -u "publicKey:secretKey" "https://api.x-changex.com/api/2/sub-acc/balance/7988900"
    

    The above command returns JSON structured like this:

    {
      "result": {
        "main": [
          {
            "currency": "1ST",
            "available": "0.0",
            "reserved": "0.0"
          }
        ],
        "trading": [
          {
            "currency": "1ST",
            "available": "0",
            "reserved": "0"
          }
        ]
      }
    }
    
    

    Error response example:

    Insufficient permissions:

    {
      "error": {
        "code": 1003,
        "message": "Action is forbidden for this API key"
      }
    }
    

    GET /api/2/sub-acc/balance/{subAccountUserID}

    Returns balance values by sub-account ID specified. Report will include main account and Trading balances for each currency. It is functional with no regard to the state of a sub-account.

    Requires the "Payment information" API key Access Right.

    Get sub-account crypto address

    curl -X GET -u "publicKey:secretKey" \
        "https://api.x-changex.com/api/2/sub-acc/deposit-address/7988900/NXT"
    

    The above command returns JSON structured like this:

    {
        "result": {
            "address": "NXT-G22U-BYF7-H8D9-3J27W",
            "publicKey": "f79779a3a0c7acc75a62afe8125de53106c6a19c1ebdf92a3598676e58773df0"
        }
    }
    

    GET /api/2/sub-acc/deposit-address/{subAccountUserId}/{currency}

    Returns sub-account crypto address for currency.

    Requires no API key Access Rights.

    Parameters:

    Name Type Description
    networkCode String Optional parameter
    Network code

    Responses:

    Name Type Description
    address String Address for deposit
    paymentId String Optional parameter
    If this parameter is set, it is required for deposit.
    publicKey String Optional parameter
    If this parameter is set, it is required for deposit.
    networkCode String Optional parameter
    Network code

    Errors

    Error code HTTP Status Code Message Note
    10021 400 user disabled Sub-account is frozen or disabled
    500 500 Internal Server Error Cannot find sub account subAccountId

    Following errors are conventional:

    Error code HTTP Status Code Message Note
    10001 400 Validation error Param 'ids' required.
    1003 403 Action is forbidden for this API key Check Access Rights for API key.
    20001 400 Insufficient funds Insufficient funds for creating order or any account operation
    1002 401 Authorization failed
    504 504 Gateway Timeout Check the result of your request later
    503 503 Service Unavailable Try it again later
    1001 401 Authorization required
    2001 400 Symbol not found
    2002 400 Currency not found
    600 400 Action is not allowed

    Buy crypto

    You can purchase cryptocurrency on our platform. The current section requests allow receiving the list of providers, available for buying crypto, and information about them. You can receive rates and orders, and create orders using these API methods as well.

    Get providers information

    curl -X GET -u "publicKey:secretKey" "https://api.x-changex.com/api/2/buy-crypto/provider"
    

    The above command returns JSON structured like this:

    [
      {
        "providerID": 2,
        "providerName": "moonpay",
        "methods": [
          {
            "id": 0,
            "name": "credit_debit_card",
            "description": "",
            "logoURL": "https://example.com/logo.png",
            "status": "ACTIVE",
            "type": "credit_debit_card",
            "supportedSource": [
              {
                "code": "USD",
                "displayName": "USD"
              }
            ],
            "supportedTarget": [
              {
                "code": "ETH",
                "displayName": "ETH"
              }
            ],
            "transactionLimits": [
              {
                "currencyCode": "USD",
                "targetCode": "ETH",
                "sourceMin": "0",
                "sourceMax": "124"
              }
            ]
          }
        ]
      }
    ]
    

    GET /api/2/buy-crypto/provider

    This method provides the providers' information (transaction limits, available currencies, payment methods).

    Requires the "Payment information" API key Access Right.

    Name Type Description
    providerId Number Provider ID. Optional.
    source String The source (fiat) currency code. Optional.
    target String The target (crypto) currency code. Optional.

    Responses:

    Name Type Description
    providerID Number Provider ID
    providerName String Provider name
    methods Array Payment methods list
    methods[0].id Number Payment method ID
    methods[0].name String Payment method name
    methods[0].description String Payment method text description
    methods[0].logoURL String Payment method logo URL
    methods[0].status String Payment method status (ACTIVE)
    methods[0].type String Payment method type
    methods[0].supportedSource Array The source currencies, supported by the payment method
    methods[0].supportedSource[0].code String The source currency code
    methods[0].supportedSource[0].displayName String The source currency display name
    methods[0].supportedSource[0].networkCode String Network code. Optional.
    methods[0].supportedTarget Array The target currencies, supported by the payment method
    methods[0].supportedTarget[0].code String The target currency code
    methods[0].supportedTarget[0].displayName String The target currency displayed name
    methods[0].supportedTarget[0].networkCode String Network code. Optional.
    methods[0].transactionLimits Array Payment method limits
    methods[0].transactionLimits[0].currencyCode String Transaction source currency code
    methods[0].transactionLimits[0].targetCode String Transaction target currency amount
    methods[0].transactionLimits[0].sourceMin String Minimum source currency amount
    methods[0].transactionLimits[0].sourceMax String Maximum source currency amount
    methods[0].transactionLimits[0].networkCode String Network code. Optional.

    Get rates per payment method

    curl -X GET -u "publicKey:secretKey" "https://api.x-changex.com/api/2/buy-crypto/provider/1/rate"
    

    The above command returns JSON structured like this:

    {
      "spotPrice": "10268.74",
      "prices": [
        {
          "paymentMethodId": 6025,
          "type": "credit_debit_card",
          "targetCode": "BTC",
          "targetAmount": "1",
          "sourceCode": "USD",
          "sourceAmount": "10472.06"
        }
      ]
    }
    

    GET /api/2/buy-crypto/provider/{providerID}/rate

    This method provides the rates information per payment method.

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    providerID Number Provider ID path param
    source String Source currency code. Required.
    target String Target currency code. Required.
    sourceAmount String Amount in the source currency. Optional.
    targetAmount String Amount in the target currency. Optional.
    paymentMethodId String Payment method ID. Optional.

    Responses:

    Name Type Description
    spotPrice String The spot price
    prices Array Prices list
    prices[0].paymentMethodId String Payment method ID
    prices[0].type String Payment method type
    prices[0].targetCode String Target currency code
    prices[0].sourceCode String Source currency code
    prices[0].targetAmount String Amount in the the target currency
    prices[0].sourceAmount String Amount in the source currency

    Get order list

    curl -X GET -u "publicKey:secretKey" "https://api.x-changex.com/api/2/buy-crypto/provider/1/order"
    

    The above command returns JSON structured like this:

    [
      {
        "id": 79,
        "providerId": 1,
        "orderType": "buy",
        "sourceCode": "BTC",
        "targetCode": "GBP",
        "walletAddress": "2N2gCeg7C1zKvZpFkdNNEnRFux9VSttzSVx",
        "checkoutURL": "",
        "status": "expired",
        "createdAt": "2020-10-07T10:04:40Z"
      }
    ]
    

    GET /api/2/buy-crypto/provider/{providerID}/order

    Returns the list of buying cryptocurrency orders.

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    providerID Number Provider ID path param
    from Number Unix timestamp, filter by order creation date. Required.
    till Number Unix timestamp, filter by order creation date. Required.
    limit Number Limit. Optional.
    offset Number Offset. Optional.
    sourceCode String Source currency code. Optional.
    targetCode String Target currency code. Optional.
    walletAddress String Filter by wallet address. Optional.
    targetNetworkCode String Network code. Optional.

    Responses:

    Name Type Description
    id String Order ID
    providerId Number Provider ID
    orderType String Provider order type (buy)
    sourceCode String Source currency code
    targetCode String Target currency code
    walletAddress String The user will receive cryptocurrency from the crypto provider to this address. This address is generated and provided to the crypto provider by the exchange (by us).
    checkoutURL String Checkout URL
    status String Provider order status (initial, in_progress, completed, failed, expired)
    createdAt String Order creation date and time

    Create order

    curl -X POST -u "publicKey:secretKey" "https://api.x-changex.com/api/2/buy-crypto/provider/1/order"
      -H "Content-Type: application/json"
      -d "{\"target\":\"BTC\",\"source\":\"EUR\",\"sourceAmount\":\"20\",\"paymentMethodId\": 6037}"
    

    The above command returns JSON structured like this:

    {
      "id": 79,
      "providerId": 1,
      "orderType": "buy",
      "sourceCode": "BTC",
      "targetCode": "GBP",
      "walletAddress": "2N2gCeg7C1zKvZpFkdNNEnRFux9VSttzSVx",
      "checkoutURL": "",
      "status": "expired",
      "createdAt": "2020-10-07T10:04:40Z"
    }
    

    POST /api/2/buy-crypto/provider/{providerID}/order

    This method allows to create an order. The checkoutURL will lead to a provider's widget page.

    Requires the "Payment information" API key Access Right.

    Parameters:

    Name Type Description
    providerID Number Provider ID path param
    target String Target currency. Required.
    source String Source currency. Required.
    sourceAmount String Amount in source currency. Required.
    targetAmount String Amount in target currency. Optional.
    paymentMethodId Number Payment method ID to use. Optional.
    targetNetworkCode String Network code. Optional.

    Responses:

    Name Type Description
    id Number Order ID
    providerId Number Provider ID
    orderType String Provider order type (buy)
    sourceCode String Source currency code
    targetCode String Target currency code
    walletAddress String The user will receive cryptocurrency from the crypto provider to this address. This address is generated and provided to the crypto provider by the exchange (by us).
    checkoutURL String Checkout URL
    status String Provider order status (initial, in_progress, completed, failed, expired)
    createdAt String Order creation date and time

    Socket API Reference

    Use JSON-RPC 2.0 over WebSocket connection as transport.

    Request object

    {
      "method": "newOrder",
      "params": {
        "clientOrderId": "57d5525562c945448e3cbd559bd068c4",
        "symbol": "ETHBTC",
        "side": "sell",
        "price": "0.059837",
        "quantity": "0.015"
      },
      "id": 123
    }
    

    An RPC call is represented by sending a Request object to a Server.

    The Request object has the following members:

    Notification

    {
      "jsonrpc": "2.0",
      "method": "updateTrades",
      "params": {
        "data": [
          {
            "id": 54469813,
            "price": "0.054670",
            "quantity": "0.183",
            "side": "buy",
            "timestamp": "2017-10-19T16:34:25.041Z"
          }
        ],
        "symbol": "ETHBTC"
      }
    }    
    

    A Notification is a Request object without an id member. A Request object (a Notification) signifies the lack of the Client's interest in the corresponding Response object. Therefore no Response objects need to be returned to the Client.

    The Notification object has the following members:

    Response object

    When RPC call is made, the Server MUST reply with a Response, except for Notifications cases.

    Server responses for each request. Response on success subscription is true. Example:

    {
      "jsonrpc": "2.0",
      "result": true,
      "id": 123
    }
    

    Response error

    {
      "jsonrpc": "2.0",
      "error": {
        "code": 2001,
        "message": "Symbol not found",
        "description": "Try get /api/2/public/symbol, to get list of all available symbols."
      },
      "id": 123
    }
    
    

    The Response is represented as a single JSON Object, with the following members:

    Socket Market Data

    The parameters of requests, responses, and errors correspond to REST, but have different usage procedures.
    First, you should subscribe for the required data. Then the Server will send a full snapshot of the data. After that, the Server sends an update notification.

    Get Currencies

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "getCurrency",
      "params": {
        "currency": "ETH"
      },
      "id": 123
    }
    

    Response

    {
      "jsonrpc": "2.0",
      "result": {
        "id": "ETH",
        "fullName": "Ethereum",
        "crypto": true,
        "payinEnabled": true,
        "payinPaymentId": false,
        "payinConfirmations": 2,
        "payoutEnabled": true,
        "payoutIsPaymentId": false,
        "transferEnabled": true,
        "delisted": false,
        "payoutFee": "0.001",
        "payoutMinimalAmount": "0.00958",
        "precisionPayout": 10,
        "precisionTransfer": 10
      },
      "id": 123
    }
    

    Request:

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "getCurrency",
      "params": {
        "currency": "ETH",
        "extended": true
      },
      "id": 123
    }
    

    Response

    {
      "jsonrpc":"2.0",
      "id":123,
      "result": {
        "id":"ETH",
        "fullName":"Ethereum TST",
        "crypto":true,
        "payinEnabled":true,
        "payinPaymentId":false,
        "payinConfirmations":2,
        "payoutEnabled":true,
        "payoutIsPaymentId":false,
        "transferEnabled":true,
        "delisted":false,
        "payoutFee":"0.003783645118",
        "sign":"E",
        "cryptoPaymentIdName":"",
        "cryptoType":"crypto_address",
        "qrPrefix":"ethereum:",
        "cryptoExplorer":"https://www.etherchain.org/tx/{tx}",
        "isInstrumentsStable":false
      }
    }
    

    Request methods: getCurrencies,getCurrency

    Parameters:

    Name Type Description
    currency String Currency code (for getCurrency) or currencies' codes separated by commas (for getCurrencies).
    extended Boolean Value indicating whether the extented currency details are requested.

    Get Symbols

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "getSymbol",
      "params": {
        "symbol": "ETHBTC"
      },
      "id": 123
    }
    

    Response

    {
      "jsonrpc": "2.0",
      "result": {
        "id": "ETHBTC",
        "baseCurrency": "ETH",
        "quoteCurrency": "BTC",
        "quantityIncrement": "0.001",
        "tickSize": "0.000001",
        "takeLiquidityRate": "0.001",
        "provideLiquidityRate": "-0.0001",
        "feeCurrency": "BTC"
      },
      "id": 123
    }
    

    Request methods: getSymbols,getSymbol

    Subscribe to Ticker

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "subscribeTicker",
      "params": {
        "symbol": "ETHBTC"
      },
      "id": 123
    }
    

    Notification ticker

    {
      "jsonrpc": "2.0",
      "method": "ticker",
      "params": {
        "ask": "0.054464",
        "bid": "0.054463",
        "last": "0.054463",
        "open": "0.057133",
        "low": "0.053615",
        "high": "0.057559",
        "volume": "33068.346",
        "volumeQuote": "1832.687530809",
        "timestamp": "2017-10-19T15:45:44.941Z",
        "symbol": "ETHBTC"
      }
    }
    

    Request methods: subscribeTicker, unsubscribeTicker

    Notification method: ticker

    Subscribe to Order Book

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "subscribeOrderbook",
      "params": {
        "symbol": "ETHBTC"
      },
      "id": 123
    }
    

    Notification snapshot

    {
      "jsonrpc": "2.0",
      "method": "snapshotOrderbook",
      "params": {
        "ask": [
          {
            "price": "0.054588",
            "size": "0.245"
          },
          {
            "price": "0.054590",
            "size": "0.000"
          },
          {
            "price": "0.054591",
            "size": "2.784"
          }
        ],
        "bid": [
          {
            "price": "0.054558",
            "size": "0.500"
          },
          {
            "price": "0.054557",
            "size": "0.076"
          },
          {
            "price": "0.054524",
            "size": "7.725"
          }
        ],
        "symbol": "ETHBTC",
        "sequence": 8073827,    
        "timestamp": "2018-11-19T05:00:28.193Z"
      }
    }
    

    Notification update

    {
      "jsonrpc": "2.0",
      "method": "updateOrderbook",
      "params": {    
        "ask": [
          {
            "price": "0.054590",
            "size": "0.000"
          },
          {
            "price": "0.054591",
            "size": "0.000"
          }
        ],
        "bid": [
          {
            "price": "0.054504",
             "size": "0.000"
          }
        ],
        "symbol": "ETHBTC",
        "sequence": 8073830,
        "timestamp": "2018-11-19T05:00:28.700Z"
      }
    }
    

    Request methods: subscribeOrderbook, unsubscribeOrderbook

    Notification snapshot

    Message contains a full snapshot of the Order Book.

    sequence - same as updateOrderbook sequence field Notification method: snapshotOrderbook

    Notification update

    Message contains incremental changes.
    size = 0 means that level has been deleted.
    sequence is monotonically increased for each update, each symbol has its own sequence.
    Notification method: updateOrderbook

    Subscribe to Trades

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "subscribeTrades",
      "params": {
        "symbol": "ETHBTC",
        "limit": 100
      },
      "id": 123
    }
    

    Request methods: subscribeTrades, unsubscribeTrades

    Notification snapshot

    {
      "jsonrpc": "2.0",
      "method": "snapshotTrades",
      "params": {
        "data": [
          {
            "id": 54469456,
            "price": "0.054656",
            "quantity": "0.057",
            "side": "buy",
            "timestamp": "2017-10-19T16:33:42.821Z"
          },
          {
            "id": 54469497,
            "price": "0.054656",
            "quantity": "0.092",
            "side": "buy",
            "timestamp": "2017-10-19T16:33:48.754Z"
          },
          {
            "id": 54469697,
            "price": "0.054669",
            "quantity": "0.002",
            "side": "buy",
            "timestamp": "2017-10-19T16:34:13.288Z"
          }
        ],
        "symbol": "ETHBTC"
      }
    }
    

    Notification method: snapshotTrades

    Notification update

    {
      "jsonrpc": "2.0",
      "method": "updateTrades",
      "params": {
        "data": [
          {
            "id": 54469813,
            "price": "0.054670",
            "quantity": "0.183",
            "side": "buy",
            "timestamp": "2017-10-19T16:34:25.041Z"
          }
        ],
        "symbol": "ETHBTC"
      }
    }    
    

    Notification method: updateTrades

    Get Trades

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "getTrades",
      "params": {
        "symbol": "ETHBTC",
        "limit": 3,
        "sort": "DESC",
        "by": "id"
      },
      "id": 123
    }
    

    Response

    {
      "jsonrpc": "2.0",
      "result": {
        "data": [
          {
            "id": 54472171,
            "price": "0.054443",
            "quantity": "2.213",
            "side": "sell",
            "timestamp": "2017-10-19T16:39:20.796Z"
          },
          {
            "id": 54472170,
            "price": "0.054453",
            "quantity": "0.030",
            "side": "sell",
            "timestamp": "2017-10-19T16:39:20.796Z"
          },
          {
            "id": 54472169,
            "price": "0.054454",
            "quantity": "0.052",
            "side": "sell",
            "timestamp": "2017-10-19T16:39:20.796Z"
          }
        ],
        "symbol": "ETHBTC"
      },
      "id": 123
    }
    

    Request method: getTrades

    Parameters:

    Name Type Description
    symbol String Optional parameter to filter active orders by symbol
    sort String Sort direction
    Accepted values: DESC or ASC
    Default value DESC
    by String Defines filter type
    Accepted values: timestamp or id
    Default value: timestamp
    from Datetime or Number Interval initial value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value.
    till Datetime or Number Interval end value (optional parameter)
    If sorting by timestamp is used, then Datetime, otherwise Number of index value.
    limit Number Default value: 100
    Max value: 1000
    offset Number Default value: 0
    Max value: 100000

    Subscribe to Candles

    Request methods: subscribeCandles, unsubscribeCandles

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "subscribeCandles",
      "params": {
        "symbol": "ETHBTC",
        "period": "M30",
        "limit": 100
      },
      "id": 123
    }     
    

    Notification snapshot

    {
      "jsonrpc": "2.0",
      "method": "snapshotCandles",
      "params": {
        "data": [
          {
            "timestamp": "2017-10-19T15:00:00.000Z",
            "open": "0.054801",
            "close": "0.054625",
            "min": "0.054601",
            "max": "0.054894",
            "volume": "380.750",
            "volumeQuote": "20.844237223"
          },
          {
            "timestamp": "2017-10-19T15:30:00.000Z",
            "open": "0.054616",
            "close": "0.054618",
            "min": "0.054420",
            "max": "0.054724",
            "volume": "348.527",
            "volumeQuote": "19.011854364"
          },
          {
            "timestamp": "2017-10-19T16:00:00.000Z",
            "open": "0.054587",
            "close": "0.054626",
            "min": "0.054408",
            "max": "0.054768",
            "volume": "194.014",
            "volumeQuote": "10.595416973"
          },
          {
            "timestamp": "2017-10-19T16:30:00.000Z",
            "open": "0.054614",
            "close": "0.054443",
            "min": "0.054339",
            "max": "0.054724",
            "volume": "141.213",
            "volumeQuote": "7.706358298"
          }
        ],
        "symbol": "ETHBTC",
        "period": "M30"
      }
    }
    

    Notification method: snapshotCandles

    Notification update

    {
      "jsonrpc": "2.0",
      "method": "updateCandles",
      "params": {
        "data": [
          {
            "timestamp": "2017-10-19T16:30:00.000Z",
            "open": "0.054614",
            "close": "0.054465",
            "min": "0.054339",
            "max": "0.054724",
            "volume": "141.268",
            "volumeQuote": "7.709353873"
          }
        ],
        "symbol": "ETHBTC",
        "period": "M30"
      }
    }
    

    Notification method: updateCandles

    Socket Session Authentication

    Example with BASIC algo:

    
    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "login",
      "params": {
        "algo": "BASIC",
        "pKey": "3ef4a9f8c8bf04bd8f09884b98403eae",
        "sKey": "2deb570ab58fd553a4ed3ee249fd2d51"
      }
    }
    

    Example with HS256 algo:

    
    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "login",
      "params": {
        "algo": "HS256",
        "pKey": "3ef4a9f8c8bf04bd8f09884b98403eae",
        "nonce": "N1g287gL8YOwDZr",
        "signature": "b1c0ae399c2d341866a214f7d3ed755b821c1c36fc6f17083ef05fbb55b7f986"
      }
    }
    

    Example with BEARER algo:

    
    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
        "method": "login",
        "params": {
            "algo": "BEARER",
            "pKey": "3ef4a9f8c8bf04bd8f09884b98403eae",
            "jwt": "JWT"
        }
    }
    

    Request method: login

    Params:

    Name Type Description
    algo String Encryption algorithm
    Accepted values: BASIC, HS256, or BEARER
    pKey String API public key
    sKey String API secret key, required on BASIC algo
    nonce String Random string, required on HS256 algo
    signature String HMAC SHA256 sign nonce with API secret key, required on HS256 algo
    jwt String JWT bearer token. Credentials necessary to form the token are acquired through the Authentication Service, required on BEARER algo

    Socket Trading

    Trade via socket has some major differences compared to REST:

    Subscribe to reports

    wscat -c wss://api.x-changex.com/api/2/ws
    
    {
      "method": "subscribeReports",
      "params": {}
    }
    

    Notification with currently active orders

    {
      "jsonrpc": "2.0",
      "method": "activeOrders",
      "params": [
        {
          "id": "4345613661",
          "clientOrderId": "57d5525562c945448e3cbd559bd068c3",
          "symbol": "BCCBTC",
          "side": "sell",
          "status": "new",
          "type": "limit",
          "timeInForce": "GTC",
          "quantity": "0.013",
          "price": "0.100000",
          "cumQuantity": "0.000",
          "postOnly": false,
          "createdAt": "2017-10-20T12:17:12.245Z",
          "updatedAt": "2017-10-20T12:17:12.245Z",
          "reportType": "status"
        }
      ]
    }
    

    Method: subscribeReports

    Method: activeOrders

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Notification report

    {
      "jsonrpc": "2.0",
      "method": "report",
      "params": {
        "id": "4345697765",
        "clientOrderId": "53b7cf917963464a811a4af426102c19",
        "symbol": "ETHBTC",
        "side": "sell",
        "status": "filled",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "0.001",
        "price": "0.053868",
        "cumQuantity": "0.001",
        "postOnly": false,
        "createdAt": "2017-10-20T12:20:05.952Z",
        "updatedAt": "2017-10-20T12:20:38.708Z",
        "reportType": "trade",
        "tradeQuantity": "0.001",
        "tradePrice": "0.053868",
        "tradeId": 55051694,
        "tradeFee": "-0.000000005"
      }
    }
    

    Method: report

    Params:

    Name Type Description
    id Number Order unique identifier as assigned by exchange
    clientOrderId String Order unique identifier as assigned by trader
    symbol String Trading symbol
    side String Trade side
    Accepted values: sell, buy
    status String Accepted values: new, suspended, partiallyFilled, filled, canceled, expired
    type String Accepted values: limit, market, stopLimit, stopMarket
    timeInForce String Time in Force is a special instruction used when placing a trade to indicate how long an order will remain active before it is executed or expired.
    GTC - ''Good-Till-Cancel'' order won't close until it is filled.
    IOC - ''Immediate-Or-Cancel'' order must be executed immediately. Any part of an IOC order that cannot be filled immediately will be cancelled.
    FOK - ''Fill-Or-Kill'' is a type of ''Time in Force'' designation used in securities trading that instructs a brokerage to execute a transaction immediately and completely or not execute it at all.
    Day - keeps the order active until the end of the trading day (UTC).
    GTD - ''Good-Till-Date''. The date is specified in expireTime.
    quantity Number Order quantity
    price Number Order price
    cumQuantity Number Cumulative executed quantity
    postOnly Boolean A post-only order is an order that does not remove liquidity. If your post-only order causes a match with a pre-existing order as a taker, then the order will be cancelled.
    createdAt Datetime Report creation date
    updatedAt Datetime Date of the report's last update
    stopPrice Number Required for stop-limit and stop-market orders
    expireTime Datetime Date of order expiration for timeInForce = GTD
    reportType String Accepted values: status, new, canceled, expired, suspended, trade, replaced
    tradeId Number Trade identifier. Required for reportType = trade
    tradeQuantity Number Quantity of trade. Required for reportType = trade
    tradePrice Number Trade price. Required for reportType = trade
    tradeFee Number Fee paid for trade. Required for reportType = trade
    originalRequestClientOrderId String Identifier of replaced order

    Place new order

    Request:

    {
      "method": "newOrder",
      "params": {
        "clientOrderId": "57d5525562c945448e3cbd559bd068c4",
        "symbol": "ETHBTC",
        "side": "sell",
        "price": "0.059837",
        "quantity": "0.015"
      },
      "id": 123
    }
    

    Success response:

    {
      "jsonrpc": "2.0",
      "result": {
        "id": "4345947689",
        "clientOrderId": "57d5525562c945448e3cbd559bd068c4",
        "symbol": "ETHBTC",
        "side": "sell",
        "status": "new",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "0.001",
        "price": "0.093837",
        "cumQuantity": "0.000",
        "postOnly": false,
        "createdAt": "2017-10-20T12:29:43.166Z",
        "updatedAt": "2017-10-20T12:29:43.166Z",
        "reportType": "new"
      },
      "id": 123
    }
    

    Example error response:

    {
      "jsonrpc": "2.0",
      "error": {
        "code": 20001,
        "message": "Insufficient funds",
        "description": "Check that the funds are sufficient, given commissions"
      },
      "id": 123
    }
    

    Method: newOrder

    Requires the "Place/cancel orders" API key Access Right.

    Params:

    Name Type Description
    clientOrderId String Required parameter. Uniqueness must be guaranteed within a single trading day, including all active orders.
    symbol String Trading symbol
    side String Trade side. Accepted values: sell, buy
    type String Optional parameter
    Accepted values: limit, market, stopLimit, stopMarket
    Default value: limit
    timeInForce String Optional parameter
    Accepted values: GTC, IOC, FOK, Day, GTD
    Default value: GTC
    quantity Number Order quantity
    price Number Order price. Required for limit types
    stopPrice Number Required for stop-limit and stop-market orders
    expireTime Datetime Required for timeInForce = GTD
    strictValidate Boolean Price and quantity will be checked for incrementation within the symbol's tick size and quantity step. See the symbol's tickSize and quantityIncrement
    postOnly Boolean A post-only order is an order that does not remove liquidity. If your post-only order causes a match with a pre-existing order as a taker, then order will be cancelled.
    takeLiquidityMarkup Number Optional liquidity taker fee, a fraction of order volume, such as 0.001 (for 0.1% fee)
    provideLiquidityMarkup Number Optional liquidity provider fee, a fraction of order volume, such as 0.001 (for 0.1% fee)

    Cancel order

    Request:

    {
      "method": "cancelOrder",
      "params": {
        "clientOrderId": "57d5525562c945448e3cbd559bd068c4"
      },
      "id": 123
    }
    

    Response:

    {
      "jsonrpc": "2.0",
      "result": {
        "id": "4345947689",
        "clientOrderId": "57d5525562c945448e3cbd559bd068c4",
        "symbol": "ETHBTC",
        "side": "sell",
        "status": "canceled",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "0.001",
        "price": "0.093837",
        "cumQuantity": "0.000",
        "postOnly": false,
        "createdAt": "2017-10-20T12:29:43.166Z",
        "updatedAt": "2017-10-20T12:31:26.174Z",
        "reportType": "canceled"
      },
      "id": 123
    }
    

    Method: cancelOrder

    Requires the "Place/cancel orders" API key Access Right.

    Cancel/Replace order

    Request:

    {
      "method": "cancelReplaceOrder",
      "params": {
        "clientOrderId": "9cbe79cb6f864b71a811402a48d4b5b1",
        "requestClientId": "9cbe79cb6f864b71a811402a48d4b5b2",
        "quantity": "0.002",
        "price": "0.083837"
      },
      "id": 123
    }
    

    Response:

    {
      "jsonrpc": "2.0",
      "result": {
        "id": "4346371528",
        "clientOrderId": "9cbe79cb6f864b71a811402a48d4b5b2",
        "symbol": "ETHBTC",
        "side": "sell",
        "status": "new",
        "type": "limit",
        "timeInForce": "GTC",
        "quantity": "0.002",
        "price": "0.083837",
        "cumQuantity": "0.000",
        "postOnly": false,
        "createdAt": "2017-10-20T12:47:07.942Z",
        "updatedAt": "2017-10-20T12:50:34.488Z",
        "reportType": "replaced",
        "originalRequestClientOrderId": "9cbe79cb6f864b71a811402a48d4b5b1"
      },
      "id": 123
    }
    

    The Cancel/Replace request is used to change the parameters of an existing order and to change the quantity or price attribute of an open order.

    Do not use this request to cancel the quantity remaining in an outstanding order. Use the Cancel request message for this purpose.

    It is stipulated that a newly entered order cancels a prior order that has been entered, but not yet executed.

    Method: cancelReplaceOrder

    Requires the "Place/cancel orders" API key Access Right.

    Params:

    Name Type Description
    clientOrderId String Replaced order (required parameter)
    requestClientId String clientOrderId for new order (required parameter)
    Uniqueness must be guaranteed within a single trading day, including all active orders.
    quantity Number New order quantity
    price Number New order price
    strictValidate Boolean Price and quantity will be checked for the incrementation within tick size and quantity step. See symbol's tickSize and quantityIncrement

    Get active orders

    Request:

    {
      "method": "getOrders",
      "params": {},
      "id": 123
    }
    

    Response:

    {
      "jsonrpc": "2.0",
      "result": [
        {
          "id": "4346371528",
          "clientOrderId": "9cbe79cb6f864b71a811402a48d4b5b2",
          "symbol": "ETHBTC",
          "side": "sell",
          "status": "new",
          "type": "limit",
          "timeInForce": "GTC",
          "quantity": "0.002",
          "price": "0.083837",
          "cumQuantity": "0.000",
          "postOnly": false,
          "createdAt": "2017-10-20T12:47:07.942Z",
          "updatedAt": "2017-10-20T12:50:34.488Z",
          "reportType": "replaced",
          "originalRequestClientOrderId": "9cbe79cb6f864b71a811402a48d4b5b1"
        }
      ],
      "id": 123
    }
    

    Method: getOrders

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Get trading balance

    Request:

    {
      "method": "getTradingBalance",
      "params": {},
      "id": 123
    }
    

    Response:

    {
      "jsonrpc": "2.0",
      "result": [
        {
          "currency": "BCN",
          "available": "100.000000000",
          "reserved": "0"
        },
        {
          "currency": "BTC",
          "available": "0.013634021",
          "reserved": "0"
        },
        {
          "currency": "ETH",
          "available": "0",
          "reserved": "0.00200000"
        }
      ],
      "id": 123
    }
    

    Method: getTradingBalance

    Requires the "Orderbook, History, Trading balance" API key Access Right.

    Socket Account Management

    Description

    WebSocket Account API uses the same authorization approach as described in the Socket Session Authentication section.

    API provides the following tools to manage a general account:

    Subscription to the transactions

    Method: subscribeTransactions and the corresponding unsubscription method: unsubscribeTransactions

    Income method: updateTransaction

    A full transaction model description can be found in the "Get Transactions History" section.

    A subscription to the transactions has to be used rather than transaction polling.

    A transaction notification occurs each time the transaction has been changed: such as creating a transaction, updating the pending state (for example the hash assigned) or completing a transaction. This is the easiest way to track deposits or develop real-time asset monitoring.

    A combination of the recovery mechanism and transaction subscription provides reliable and consistent information regarding transactions. For that, you should store the latest processed index and requested possible gap using a "loadTransactions" method after connecting or reconnecting the Websocket.

    Subscription request:

    {"method": "subscribeTransactions", "jsonrpc": "2.0", "params": {}, "id": 7652}
    

    Subscription result:

    {"jsonrpc":"2.0","result":true,"id": 7652}
    

    Notification. Updated Transaction:

    {
      "jsonrpc": "2.0",
      "method": "updateTransaction",
      "params": {
        "id": "76b70d1c-3dd7-423e-976e-902e516aae0e",
        "index": 7173627250,
        "type": "bankToExchange",
        "status": "success",
        "currency": "BTG",
        "amount": "0.00001000",
        "createdAt": "2021-01-31T08:19:33.892Z",
        "updatedAt": "2021-01-31T08:19:33.967Z"
      }
    }
    

    Subscription to the balance

    Method: subscribeBalance and the corresponding unsubscription method: unsubscribeBalance

    Income method: balance

    This subscription aims to provide an easy way to be informed of the current balance state. If the state has been changed or potentially changed the "balance" event will come with the actual state. Please be aware that only non-zero values present.

    Event "balance" arrives after each successful subscription.

    Subscription request:

    {"method": "subscribeBalance", "jsonrpc": "2.0", "params": {}, "id": 7653}
    

    Subscription result:

    {"jsonrpc":"2.0","result":true,"id": 7653}
    

    Notification. Updated Transaction:

    {
      "jsonrpc": "2.0",
      "method": "balance",
      "params": [
        {
          "currency": "BTC",
          "available": "0.00005821",
          "reserved": "0"
        },
        {
          "currency": "DOGE",
          "available": "11",
          "reserved": "0"
        }
      ]
    }
    

    Request Balance

    Request:

    {
      "method": "getBalance",
      "jsonrpc": "2.0",
      "params": {},
      "id": 5543
    }
    

    Response:

    {
      "jsonrpc": "2.0",
      "result": [
        {
          "currency": "BTC",
          "available": "0.00005821",
          "reserved": "0"
        },
        {
          "currency": "DOGE",
          "available": "11",
          "reserved": "0"
        }
      ],
      "id": 5543
    }
    

    Method: getBalance

    Please note that the method returns non-zero balances only.

    Find transactions

    Request:

    {
      "method": "findTransactions",
      "jsonrpc": "2.0",
      "params": {
        "limit": 10,
        "offset": 0,
        "currency": "BTG",
        "showSenders": true,
        "order": "DESC",
        "from": "2021-01-31T00:00:00.000Z",
        "till": "2021-01-31T22:33:00.555Z"
      },
      "id": 7655
    }
    

    Response:

    {
      "jsonrpc": "2.0",
      "result": [
        {
          "id": "d91b8caa-ebaa-4254-b50c-8ac717016734",
          "index": 7173628127,
          "type": "exchangeToBank",
          "status": "success",
          "currency": "BTG",
          "amount": "0.00001000",
          "createdAt": "2021-01-31T08:19:48.140Z",
          "updatedAt": "2021-01-31T08:19:48.211Z"
        },
        {
          "id": "76b70d1c-3dd7-423e-976e-902e516aae0e",
          "index": 7173627250,
          "type": "bankToExchange",
          "status": "success",
          "currency": "BTG",
          "amount": "0.00001000",
          "createdAt": "2021-01-31T08:19:33.892Z",
          "updatedAt": "2021-01-31T08:19:33.967Z"
        }
      ],
      "id": 7655
    }
    

    Method: findTransactions

    All parameters are optional.

    Parameters:

    Name Type Description
    from DateTime Optional filter by time range
    till DateTime Optional filter by time range
    currency String Optional filter by currency
    order String Sort order, can be one of DESC or ASC. Default - DESC
    limit Number Pagination. Default 100
    offset Number Pagination. Default 0
    showSenders Boolean Include senders addresses. Default - false

    Load transactions

    Request:

    {
      "method": "loadTransactions",
      "jsonrpc": "2.0",
      "params": {
        "limit": 10,
        "offset": 0,
        "currency": "BTG",
        "showSenders": true,
        "from": 7173627250
      },
      "id": 7656
    }
    

    Response:

    {
      "jsonrpc": "2.0",
      "result": [
        {
          "id": "76b70d1c-3dd7-423e-976e-902e516aae0e",
          "index": 7173627250,
          "type": "bankToExchange",
          "status": "success",
          "currency": "BTG",
          "amount": "0.00001000",
          "createdAt": "2021-01-31T08:19:33.892Z",
          "updatedAt": "2021-01-31T08:19:33.967Z"
        },
        {
          "id": "d91b8caa-ebaa-4254-b50c-8ac717016734",
          "index": 7173628127,
          "type": "exchangeToBank",
          "status": "success",
          "currency": "BTG",
          "amount": "0.00001000",
          "createdAt": "2021-01-31T08:19:48.140Z",
          "updatedAt": "2021-01-31T08:19:48.211Z"
        }
      ],
      "id": 7656
    }
    

    Method: loadTransactions

    The main difference between the method "loadTransactions" and "findTransactions":

    All parameters are optional.

    Parameters:

    Name Type Description
    from Number Optional filter by index value range (Included)
    till Number Optional filter by index value range (Excluded)
    currency String Optional filter by currency
    order String Sort order, can be one of DESC or ASC. Default - ASC
    limit Number Pagination. Default 100
    offset Number Pagination. Default 0
    showSenders Boolean Include senders addresses. Default - false

    Errors

    The xChange API uses the following error codes:

    Error code HTTP Status Code Message Note
    403 401 Action is forbidden for account
    429 429 Too many requests Action is being rate limited for account
    500 500 Internal Server Error
    503 503 Service Unavailable Try it again later
    504 504 Gateway Timeout Check the result of your request later
    1001 401 Authorization required
    1002 401 Authorization required or has been failed Check that authorization data provided
    1003 403 Action forbidden for this API key Check permissions for API key
    1004 401 Unsupported authorization method Use Basic authentication
    2001 400 Symbol not found
    2002 400 Currency not found
    2010 400 Quantity not a valid number
    2011 400 Quantity too low
    2012 400 Bad quantity More details in description
    2020 400 Price not a valid number
    2021 400 Price too low
    2022 400 Bad price More details in description
    20001 400 Insufficient funds Insufficient funds for creating order or any account operation
    20002 400 Order not found Attempt to get active order that not existing, filled, canceled or expired. Attempt to cancel not existing order. Attempt to cancel already filled or expired order.
    20003 400 Limit exceeded Withdrawal limit exceeded
    20004 400 Transaction not found Requested transaction not found
    20005 400 Payout not found
    20006 400 Payout already committed
    20007 400 Payout already rolled back
    20008 400 Duplicate clientOrderId
    20009 400 Price and quantity not changed
    20010 400 Exchange temporary closed Exchange market temporary closed on symbol
    20011 400 Payout address is invalid
    20014 400 Offchain for this payout is unavailable Address do not belong to exchange or belongs to same user or unavailable for currency
    20032 400 Margin account or position not found Create margin account before place orders or account for requested symbol not found
    20033 400 Position not changed Existed marginBalance equal requested value
    20034 400 Position in close only state
    20040 400 Margin trading forbidden
    20080 400 Internal order execution deadline exceeded Order not placed.
    20081 404 Provider not found
    20082 404 Source currency not found
    20083 404 Target currency not found
    20084 400 Source currency disabled
    20085 400 Target currency disabled
    20086 404 Payment method not found
    20087 400 Payment methods is inactive
    10001 400 Validation error Input not valid, see more in message field
    10021 400 User disabled Sub-Account API. User cant be changed

    Guide & Code Samples

    Fetch all public trades

    Fetch all trades history for a symbol and keep it updated.

    General idea: the fetch trades are sorted by ASC from latest id.

    import requests
    import time
    session = requests.session()
    
    
    def get_trades(symbol_code, from_id):
        return session.get("https://api.x-changex.com/api/2/public/trades/%s?sort=ASC&by=id&from=%d&limit=1000" % (symbol_code, from_id)).json()
    
    
    symbol = 'ETHDAI'
    from_trade_id = 1
    
    while True:
        trades = get_trades(symbol, from_trade_id)
        if len(trades) > 0:
            from_trade_id = trades[-1]['id'] + 1
            print('Loaded trades till', trades[-1]['id'], trades[-1]['timestamp'])
            if len(trades) < 1000:
                time.sleep(5)
        else:
            time.sleep(30)
    

    Get trades updated

    First version

    The fastest way is use the socket API. Subscribe for reports (method subscribeReports) and handle reportType == trade.

    Second version

    Fetch trades as in the example above but with small changes.

    import requests
    import time
    session = requests.session()
    session.auth = ("publicKey", "secretKey")
    
    def get_my_trades(from_id):
        return session.get("https://api.x-changex.com/api/2/history/trades?sort=ASC&by=id&limit=100&from=%d" % (from_id)).json()
    
    def get_recent_my_trades():
        return session.get("https://api.x-changex.com/api/2/history/trades?sort=DESC&by=id&limit=10").json()
    
    from_trade_id = 0
    
    while True:
        if from_trade_id == 0:
            recent_trades = get_recent_my_trades()
            if len(recent_trades) > 0:
                from_trade_id = recent_trades[0]['id'] + 1
                print('Last recent trade', recent_trades[0])
            else:
                print('You do not have any trades')
        else:
            trades = get_my_trades(from_trade_id)
            if len(trades) > 0:
                from_trade_id = trades[-1]['id'] + 1
                print('new trades', trades)
            else:
                print('No new trades')
        time.sleep(30)
    

    Getting new transactions

    The code in the example allows you to get all of your new deposits, withdrawals and transfers.

    The index is a 64-bit integer, that increases on any transaction update. To get all new updates of transactions you will need to request transactions with an index value which is greater than the latest one.

    For example, if you have created a withdrawal, then you get an update with a transaction hash and committed status after receiving the required number of confirmations.

    import requests
    import time
    session = requests.session()
    session.auth = ("publicKey", "secretKey")
    
    def get_my_transactions(from_index):
        return session.get("https://api.x-changex.com/api/2/account/transactions?sort=ASC&by=index&limit=100&from=%d" % (from_index)).json()
    
    def get_recent_my_transactions():
        return session.get("https://api.x-changex.com/api/2/account/transactions?sort=DESC&by=index&limit=100").json()
    
    from_index = 0
    
    while True:
        if from_index == 0:
            recent_transactions = get_recent_my_transactions()
            if len(recent_transactions) > 0:
                from_index = recent_transactions[0]['index'] + 1
                print('Last recent trade', recent_transactions[0])
            else:
                print('You do not have any transactions')
        else:
            transactions = get_my_transactions(from_index)
            if len(transactions) > 0:
                from_index = transactions[-1]['index'] + 1
                print('New and Updated transactions', transactions)
            else:
                print('No new updates')
        time.sleep(60)