Overview – ccxt documentation

The ccxt library is a collection of available crypto exchanges or exchange classes. Each class implements the public and private API for a particular crypto exchange. All exchanges are derived from the base Exchange class and share a set of common methods. To access a particular exchange from ccxt library you need to create an instance of corresponding exchange class. Supported exchanges are updated frequently and new exchanges are added regularly.

Full public and private HTTP REST APIs for all exchanges are implemented. WebSocket and FIX implementations in JavaScript, PHP, Python and other languages coming soon.

The ccxt library currently supports the following 90 cryptocurrency exchange markets and trading APIs:

Besides making basic market and limit orders, some exchanges offer margin trading (leverage), various derivatives (like futures contracts and options) and also have dark pools, OTC (over-the-counter trading), merchant APIs and much more.

Instantiation¶

To connect to an exchange and start trading you need to instantiate an exchange class from ccxt library.

To get the full list of ids of supported exchanges programmatically:

An exchange can be instantiated like shown in the examples below:

The ccxt library in PHP uses builtin UTC/GMT time functions, therefore you are required to set date.timezone in your php.ini or call date_default_timezone_set () function before using the PHP version of the library. The recommended timezone setting is ",UTC", .

Exchange Structure¶

Every exchange has a set of properties and methods, most of which you can override by passing an associative array of params to an exchange constructor. You can also make a subclass and override everything.

Here’s an overview of base exchange properties with values added for example:

Exchange Properties¶

Below is a detailed description of each of the base exchange properties:

  • id : Each exchange has a default id. The id is not used for anything, it’s a string literal for user-land exchange instance identification purposes. You can have multiple links to the same exchange and differentiate them by ids. Default ids are all lowercase and correspond to exchange names.
  • name : This is a string literal containing the human-readable exchange name.
  • countries : A string literal or an array of string literals of 2-symbol ISO country codes, where the exchange is operating from.
  • urls[‘api’] : The single string literal base URL for API calls or an associative array of separate URLs for private and public APIs.
  • urls[‘www’] : The main HTTP website URL.
  • urls[‘doc’] : A single string URL link to original documentation for exchange API on their website or an array of links to docs.
  • version : A string literal containing version identifier for current exchange API. The ccxt library will append this version string to the API Base URL upon each request. You don’t have to modify it, unless you are implementing a new exchange API. The version identifier is a usually a numeric string starting with a letter ‘,v’ in some cases, like v1.1. Do not override it unless you are implementing your own new crypto exchange class.
  • api : An associative array containing a definition of all API endpoints exposed by a crypto exchange. The API definition is used by ccxt to automatically construct callable instance methods for each available endpoint.
  • hasFetchTickers : This is a boolean property indicating if the exchange has the fetchTickers () method available. When this property is false, the exchange will also throw a NotSupported exception upon a call to fetchTickers ().
  • hasFetchOHLCV : This is a boolean property indicating if the exchange has the fetchOHLCV () method available. When this property is false, the exchange will also throw a NotSupported exception upon a call to fetchOHLCV (). Also, if this property is true, the timeframes property is populated as well.
  • timeframes : An associative array of timeframes, supported by the fetchOHLCV method of the exchange. This is only populated when hasFetchTickers property is true.
  • timeout : A timeout in milliseconds for a request-response roundtrip (default timeout is 10000 ms = 10 seconds). You should always set it to a reasonable value, hanging forever with no timeout is not your option, for sure.
  • rateLimit : A request rate limit in milliseconds. Specifies the required minimal delay between two consequent HTTP requests to the same exchange. This parameter is not used for now (reserved for future).
  • userAgent : An object to set HTTP User-Agent header to. The ccxt library will set its User-Agent by default. Some exchanges may not like it. If you are having difficulties getting a reply from an exchange and want to turn User-Agent off or use the default one, set this value to false, undefined, or an empty string.
  • verbose : A boolean flag indicating whether to log HTTP requests to stdout (verbose flag is false by default).
  • markets : An associative array of markets indexed by common trading pairs or symbols. Markets should be loaded prior to accessing this property. Markets are unavailable until you call the loadMarkets() / load_markets() method on exchange instance.
  • symbols : A non-associative array (a list) of symbols available with an exchange, sorted in alphabetical order. These are the keys of the markets property. Symbols are loaded and reloaded from markets. This property is a convenient shorthand for all market keys.
  • currencies : A non-associative array (a list) of currency codes (usually 3 or 4 letters) available with an exchange, sorted in alphabetical order. Currencies are loaded and reloaded from markets.
  • markets_by_id : An associative array of markets indexed by exchange-specific ids. Markets should be loaded prior to accessing this property.
  • proxy : A string literal containing base URL of http(s) proxy, ” by default. For use with web browsers and from blocked locations. An example of a proxy string is ‘http://crossorigin.me/’ . The absolute exchange endpoint URL is appended to this string before sending the HTTP request.
  • apiKey : This is your public API key string literal. Most exchanges require this for trading (see below).
  • secret : Your private secret API key string literal. Most exchanges require this as well together with the apiKey.
  • password : A string literal with your password/phrase. Some exchanges require this parameter for trading, but most of them don’t.
  • uid : A unique id of your account. This can be a string literal or a number. Some exchanges also require this for trading, but most of them don’t.

Rate Limit¶

Exchanges usually impose what is called a rate limit. Exchanges will remember and track your user credentials and your IP address and will not allow you to query the API too frequently. They balance their load and control traffic congestion to protect API servers from (D)DoS and misuse.

WARNING: Stay under the rate limit to avoid ban!

Most exchanges allow up to 1 or 2 requests per second. Exchanges may temporarily restrict your access to their API or ban you for some period of time if you are too aggressive with your requests.

DDoS Protection By Cloudflare / Incapsula¶

Some exchanges are DDoS-protected by Cloudflare or Incapsula. Your IP can get temporarily blocked during periods of high load. Sometimes they even restrict whole countries and regions. In that case their servers usually return a page that states a HTTP 40x error or runs an AJAX test of your browser / captcha test and delays the reload of the page for several seconds. Then your browser/fingerprint is granted access temporarily and gets added to a whitelist or receives a HTTP cookie for further use.

If you encounter DDoS protection errors and cannot reach a particular exchange then: – try later – use a proxy (this is less responsive, though) – ask the exchange support to add you to a whitelist – run your software in close proximity to the exchange (same country, same city, same datacenter, same server rack, same server) – try an alternative IP within a different geographic region – run your software in a distributed network of servers – .

In case your calls hit a rate limit or get nonce errors, the ccxt library will throw an exception of one of the following types: – DDoSProtectionError – ExchangeNotAvailable – ExchangeError

Sequential requests¶

Each exchange is a place for trading some kinds of valuables. Sometimes they are called with various different terms like instruments, symbols, trading pairs, currencies, tokens, stocks, commodities, contracts, etc, but they all mean the same – a trading pair, a symbol or a financial instrument.

In terms of the ccxt library, every exchange offers multiple markets within itself. The set of markets differs from exchange to exchange opening possibilities for cross-exchange and cross-market arbitrage. A market is usually a pair of traded crypto/fiat currencies.

Market Structure¶

Each market is an associative array (aka dictionary) with the following keys:

  • id . The string or numeric ID of the market or trade instrument within the exchange. Market ids are used inside exchanges internally to identify trading pairs during the request/response process.
  • symbol . An uppercase string code representation of a particular trading pair or instrument. This is usually written as BaseCurrency/QuoteCurrency with a slash as in BTC/USD , LTC/CNY or ETH/EUR , etc. Symbols are used to reference markets within the ccxt library (explained below).
  • base . An uppercase string code of base fiat or crypto currency.
  • quote . An uppercase string code of quoted fiat or crypto currency.
  • info . An associative array of non-common market properties, including fees, rates, limits and other general market information. The internal info array is different for each particular market, its contents depend on the exchange.
  • precision . The amounts of decimal digits accepted in order values by exchanges upon order placement for price, amount and cost.
  • limits . The minimums and maximums for prices, amounts (volumes) and costs (where cost = price * amount).

The “precision“ and “limits“ params are currently under heavy development, some of these fields may be missing here and there until the unification process is complete. This does not influence most of the orders but can be significant in extreme cases of very large or very small orders.

Loading Markets¶

In most cases you are required to load the list of markets and trading symbols for a particular exchange prior to accessing other API methods. If you forget to load markets the ccxt library will do that automatically upon your first call to the unified API. It will send two HTTP requests, first for markets and then the second one for other data, sequentially.

In order to load markets manually beforehand call the loadMarkets () / load_markets () method on an exchange instance. It returns an associative array of markets indexed by trading symbol. If you want more control over the execution of your logic, preloading markets by hand is recommended.

Market Ids And Symbols¶

Market ids are used during the REST request-response process to reference trading pairs within exchanges. The set of market ids is unique per exchange and cannot be used across exchanges. For example, the BTC/USD pair/market may have different ids on various popular exchanges, like btcusd , BTCUSD , XBTUSD , btc/usd , 42 (numeric id), BTC/USD , Btc/Usd , tBTCUSD , XXBTZUSD . You don’t need to remember or use market ids, they are there for internal HTTP request-response purposes inside exchange implementations.

The ccxt library abstracts uncommon market ids to symbols, standardized to a common format. Symbols are not the same as market ids. Every market is referenced by a corresponding symbol. Symbols are common across exchanges which makes them suitable for arbitrage and many other things.

A symbol is an uppercase string literal name for a pair of traded currencies with a slash in between. A currency is a code of three or four uppercase letters, like BTC , ETH , USD , GBP , CNY , LTC , JPY , DOGE , RUB , ZEC , XRP , XMR , etc. Some exchanges have exotic currencies with longer names. The first currency before the slash is usually called base currency, and the one after the slash is called quote currency. Examples of a symbol are: BTC/USD , DOGE/LTC , ETH/EUR , DASH/XRP , BTC/CNY , ZEC/XMR , ETH/JPY .

Market structures are indexed by symbols and ids. The base exchange class also has builtin methods for accessing markets by symbols. Most API methods require a symbol to be passed in their first parameter. You are often required to specify a symbol when querying current prices, making orders, etc.

Most of the time users will be working with market symbols. You will get a standard userland exception if you access non-existent keys in these dicts.

Naming Consistency¶

There is a bit of term ambiguity across various exchanges that may cause confusion among newcoming traders. Some exchanges call markets as pairs, whereas other exchanges call symbols as products. In terms of the ccxt library, each exchange contains one or more trading markets. Each market has an id and a symbol. Most symbols are pairs of base currency and quote currency.

Exchanges в†’ Markets в†’ Symbols в†’ Currencies

Historically various symbolic names have been used to designate same trading pairs. Some cryptocurrencies (like Dash) even changed their names more than once during their ongoing lifetime. For consistency across exchanges the ccxt library will perform the following known substitutions for symbols and currencies:

  • XBT в†’ BTC : XBT is newer but BTC is more common among exchanges and sounds more like bitcoin (read more).
  • BCC в†’ BCH : The Bitcoin Cash fork is often called with two different symbolic names: BCC and BCH . The name BCC is ambiguous for Bitcoin Cash, it is confused with BitConnect. The ccxt library will convert BCC to BCH where it is appropriate (some exchanges and aggregators confuse them).
  • DRK в†’ DASH : DASH was Darkcoin then became Dash (read more).
  • DSH в†’ DASH : Try not to confuse symbols and currencies. The DSH (Dashcoin) is not the same as DASH (Dash). Some exchanges have DASH labelled inconsistently as DSH , the ccxt library does a correction for that as well ( DSH в†’ DASH ), but only on certain exchanges that have these two currencies confused, whereas most exchanges have them both correct. Just remember that DASH/BTC is not the same as DSH/BTC .

Consistency Of Base And Quote Currencies¶

It depends on which exchange you are using, but some of them have a reversed (inconsistent) pairing of base and quote . They actually have base and quote misplaced (switched/reversed sides). In that case you’ll see a difference of parsed base and quote currency values with the unparsed info in the market substructure.

For those exchanges the ccxt will do a correction, switching and normalizing sides of base and quote currencies when parsing exchange replies. This logic is financially and terminologically correct. If you want less confusion, remember the following rule: base is always before the slash, quote is always after the slash in any symbol and with any market.

Market Cache Force Reload¶

The loadMarkets () / load_markets () is also a dirty method with a side effect of saving the array of markets on the exchange instance. You only need to call it once per exchange. All subsequent calls to the same method will return the locally saved (cached) array of markets.

When exchange markets are loaded, you can then access market information any time via the markets property. This property contains an associative array of markets indexed by symbol. If you need to force reload the list of markets after you have them loaded already, pass the reload = true flag to the same method again.

Each exchange offers a set of API methods. Each method of the API is called an endpoint. Endpoints are HTTP URLs for querying various types of information. All endpoints return JSON in response to client requests.

Usually, there is an endpoint for getting a list of markets from an exchange, an endpoint for retrieving an order book for a particular market, an endpoint for retrieving trade history, endpoints for placing and cancelling orders, for money deposit and withdrawal, etc. Basically every kind of action you could perform within a particular exchange has a separate endpoint URL offered by the API.

Because the set of methods differs from exchange to exchange, the ccxt library implements the following: – a public and private API for all possible URLs and methods – a unified API supporting a subset of common methods

The endpoint URLs are predefined in the api property for each exchange. You don’t have to override it, unless you are implementing a new exchange API (at least you should know what you’re doing).

The endpoint definition is a list of all API URLs exposed by an exchange. This list gets converted to callable methods upon exchange instantiation. Each URL in the API endpoint list gets a corresponding callable method. For example, if an exchange offers an HTTP GET URL for querying prices like https://example.com/public/quotes , it is converted to a method named example.publicGetQuotes () / $example->,publicGetQuotes () . This is done automatically for all exchanges, therefore the ccxt library supports all possible URLs offered by crypto exchanges.

Public/Private API¶

API URLs are often grouped into two sets of methods called a public API for market data and a private API for trading and account access. These groups of API methods are usually prefixed with a word ‘,public’ or ‘,private’.

A public API is used to access market data and does not require any authentication whatsoever. Most exchanges provide market data openly to all (under their rate limit). With the ccxt library anyone can access market data out of the box without having to register with the exchanges and without setting up account keys and passwords.

Public APIs include the following: – instruments/trading pairs – price feeds (exchange rates) – order books (L1, L2, L3. ) – trade history (closed orders, transactions, executions) – tickers (spot / 24h price) – OHLCV series for charting – other public endpoints

For trading with private API you need to obtain API keys from/to exchanges. It often means registering with exchanges and creating API keys with your account. Most exchanges require personal info or identification. Some kind of verification may be necessary as well.

If you want to trade you need to register yourself, this library will not create accounts or API keys for you. Some exchange APIs expose interface methods for registering an account from within the code itself, but most of exchanges don’t. You have to sign up and create API keys with their websites.

Private APIs allow the following: – manage personal account info – query account balances – trade by making market and limit orders – create deposit addresses and fund accounts – request withdrawal of fiat and crypto funds – query personal open / closed orders – query positions in margin/leverage trading – get ledger history – transfer funds between accounts – use merchant services

Some exchanges offer the same logic under different names. For example, a public API is also often called market data, basic, market, mapi, api, price, etc. All of them mean a set of methods for accessing data available to public. A private API is also often called trading, trade, tapi, exchange, account, etc.

A few exchanges also expose a merchant API which allows you to create invoices and accept crypto and fiat payments from your clients. This kind of API is often called merchant, wallet, payment, ecapi (for e-commerce).

To get a list of all available methods with an exchange instance, you can simply do the following:

Synchronous vs Asynchronous Calls¶

In the JavaScript version of CCXT all methods are asynchronous and return Promises that resolve with a decoded JSON object. In CCXT we use the modern async/await syntax to work with Promises. If you’re not familiar with that syntax, you can read more about it here.

The ccxt library supports asynchronous concurrency mode in Python 3.5+ with async/await syntax. The asynchronous Python version uses pure asyncio with aiohttp. In async mode you have all the same properties and methods, but most methods are decorated with an async keyword. If you want to use async mode, you should link against the ccxt.async subpackage, like in the following example:

In PHP all API methods are synchronous.

Returned JSON Objects¶

All public and private API methods return raw decoded JSON objects in response from the exchanges, as is, untouched. The unified API returns JSON-decoded objects in a common format and structured uniformly across all exchanges.

Passing Parameters To API Methods¶

The set of all possible API endpoints differs from exchange to exchange. Most of methods accept a single associative array (or a Python dict) of key-value parameters. The params are passed as follows:

For a full list of accepted method parameters for each exchange, please consult API docs.

API Method Naming Conventions¶

An exchange method name is a concatenated string consisting of type (public or private), HTTP method (GET, POST, PUT, DELETE) and endpoint URL path like in the following examples:

The ccxt library supports both camelcase notation (preferred in JavaScript) and underscore notation (preferred in Python and PHP), therefore all methods can be called in either notation or coding style in any language. Both of these notations work in JavaScript, Python and PHP:

To get a list of all available methods with an exchange instance, you can simply do the following:

Unified API¶

The unified ccxt API is a subset of methods common among the exchanges. It currently contains the following methods:

  • fetchMarkets () : Fetches a list of all available markets from an exchange and returns an abstracted JSON-decoded response, an array of markets. Some exchanges do not have means for obtaining a list of markets via their online API, for those the list of markets is hardcoded.
  • loadMarkets ([reload]) : Loads the list of markets indexed by symbol and caches it with the exchange instance. Returns cached markets if loaded already, unless the reload = true flag is forced.
  • fetchOrderBook (symbol[, params]) : Fetch an order book for a particular market trading symbol.
  • fetchL2OrderBook (symbol[, params]) : Level 2 (price-aggregated) order book for a particular symbol.
  • fetchTrades (symbol[, params]) : Fetch recent trades for a particular trading symbol.
  • fetchTicker (symbol) : Fetch latest ticker data by trading symbol.
  • fetchBalance () : Fetch Balance.
  • createOrder (symbol, type, side, amount[, price[, params]])
  • createLimitBuyOrder (symbol, amount, price[, params])
  • createLimitSellOrder (symbol, amount, price[, params])
  • createMarketBuyOrder (symbol, amount[, params])
  • createMarketSellOrder (symbol, amount[, params])
  • cancelOrder (id[, symbol[, params]])
  • fetchOrder (id[, symbol[, params]])
  • fetchOrders ([symbol[, params]])
  • fetchOpenOrders ([symbol[, params]])
  • fetchClosedOrders ([symbol[, params]])
  • .

Note, that most of methods of the unified API accept an optional params parameter. It is an associative array (a dictionary, empty by default) containing the params you want to override. Use the params dictionary if you need to pass a custom setting or an optional parameter to your unified query.

Order Book / Market Depth¶

Exchanges expose information on open orders with bid (buy) and ask (sell) prices, volumes and other data. Usually there is a separate endpoint for querying current state (stack frame) of the order book for a particular market. An order book is also often called market depth. The order book information is used in the trading decision making process.

The method for fetching an order book for a particular symbol is named fetchOrderBook or fetch_order_book . It accepts a symbol and an optional dictionary with extra params (if supported by a particular exchange). The method for fetching the order book is called like shown below:

The structure of a returned order book is as follows:

Prices and amounts are floats. The bids array is sorted by price in descending order. The best (highest) bid price is the first element and the worst (lowest) bid price is the last element. The asks array is sorted by price in ascending order. The best (lowest) ask price is the first element and the worst (highest) ask price is the last element. Bid/ask arrays can be empty if there are no corresponding orders in the order book of an exchange.

Exchanges may return the stack of orders in various levels of details for analysis. It is either in full detail containing each and every order, or it is aggregated having slightly less detail where orders are grouped and merged by price and volume. Having greater detail requires more traffic and bandwidth and is slower in general but gives a benefit of higher precision. Having less detail is usually faster, but may not be enough in some very specific cases.

Some exchanges accept a second dictionary of extra parameters to the fetchOrderBook () / fetch_order_book () function allowing you to get the level of aggregation you need, like so:

The levels of detail or levels of order book aggregation are often number-labelled like L1, L2, L3. – L1: less detail for quickly obtaining very basic info, namely, the market price only. It appears to look like just one order in the order book. – L2: most common level of aggregation where order volumes are grouped by price. If two orders have the same price, they appear as one single order for a volume equal to their total sum. This is most likely the level of aggregation you need for the majority of purposes. – L3: most detailed level with no aggregation where each order is separate from other orders. This LOD naturally contains duplicates in the output. So, if two orders have equal prices they are not merged together and it’s up to the exchange’s matching engine to decide on their priority in the stack. You don’t really need L3 detail for successful trading. In fact, you most probably don’t need it at all. Therefore some exchanges don’t support it and always return aggregated order books.

If you want to get an L2 order book, whatever the exchange returns, use the fetchL2OrderBook(symbol, params) or fetch_l2_order_book(symbol, params) unified method for that.

Market Price¶

In order to get current best price (query market price) and calculate bidask spread take first elements from bid and ask, like so:

Price Tickers¶

A price ticker contains statistics for a particular market/symbol for some period of time in recent past, usually last 24 hours. The structure of a ticker is as follows:

Timestamp and datetime are both Universal Time Coordinated (UTC).

Individually By Symbol¶

To get the individual ticker data from an exchange for each particular trading pair or symbol call the fetchTicker (symbol) :

All At Once¶

Some markets (not all of them) also support fetching all tickers at once. See their docs for details. You can fetch all tickers with a single call like so:

Fetching all tickers requires more traffic than fetching a single ticker. If you only need one ticker, fetching by a particular symbol is faster in general. You probably want to fetch all tickers only if you really need all of them.

The structure of returned value is as follows:

A general solution for fetching all tickers from all exchanges (even the ones that don’t have a corresponding API endpoint) is on the way, this section will be updated soon.

Async Mode / Concurrency¶

OHLCV Candlestick Charts¶

Most exchanges have endpoints for fetching OHLCV data, but some of them don’t. The exchange boolean (true/false) property named hasFetchOHLCV indicates whether the exchange supports candlestick data series or not.

The fetchOHLCV method is declared in the following way:

You can call the unified fetchOHLCV / fetch_ohlcv method to get the list of most recent OHLCV candles for a particular symbol like so:

To get the list of available timeframes for your exchange see the timeframes property. Note that it is only populated when hasFetchTickers is true as well.

There’s a limit on how far back in time your requests can go. Most of exchanges will not allow to query detailed candlestick history (like those for 1-minute and 5-minute timeframes) too far in the past. They usually keep a reasonable amount of most recent candles, like 1000 last candles for any timeframe is more than enough for most of needs. You can work around that limitation by continuously fetching (aka REST polling) latest OHLCVs and storing them in a CSV file or in a database.

The fetchOHLCV method shown above returns a list (a flat array) of OHLCV candles represented by the following structure:

Trades, Orders, Executions, Transactions¶

You can call the unified fetchTrades / fetch_trades method to get the list of most recent trades for a particular symbol. The fetchTrades method is declared in the following way:

For example, if you want to print recent trades for all symbols one by one sequentially (mind the rateLimit!) you would do it like so:

The fetchTrades method shown above returns a list (a flat array) of trades represented by the following structure:

Most exchanges return most of the above fields for each trade, though there are exchanges that don’t return the type, the side, the trade id or the order id of the trade. Most of the time you are guaranteed to have the timestamp, the datetime, the symbol, the price and the amount of each trade.

Also, the fetchTrades () / fetch_trades() method has an optional second argument params (an assoc-key array/dict, empty by default). You can use it to pass extra params (if supported by your exchange), for example, the offset, the sorting direction, the limit (count) of returned trades and some other params (see the API docs for your exchange for more details).

In order to be able to access your user account, perform algorithmic trading by placing market and limit orders, query balances, deposit and withdraw funds and so on, you need to obtain your API keys for authentication from each exchange you want to trade with. They usually have it available on a separate tab or page within your user account settings. API keys are exchange-specific and cannnot be interchanged under any circumstances.

Authentication¶

Authentication with all exchanges is handled automatically if provided with proper API keys. The process of authentication usually goes through the following pattern:

  1. Generate new nonce. A nonce is an integer, often a Unix Timestamp in seconds or milliseconds (since epoch January 1, 1970). The nonce should be unique to a particular request and constantly increasing, so that no two requests share the same nonce. Each next request should have greater nonce than the previous request. The default nonce is a 32-bit Unix Timestamp in seconds.
  2. Append public apiKey and nonce to other endpoint params, if any, then serialize the whole thing for signing.
  3. Sign the serialized params using HMAC-SHA256/384/512 or MD5 with your secret key.
  4. Append the signature in Hex or Base64 and nonce to HTTP headers or body.

This process may differ from exchange to exchange. Some exchanges may want the signature in a different encoding, some of them vary in header and body param names and formats, but the general pattern is the same for all of them.

The authentication is already handled for you, so you don’t need to perform any of those steps manually unless you are implementing a new exchange class. The only thing you need for trading is the actual API key pair.

API Keys Setup¶

The API credentials usually include the following:

  • apiKey . This is your public API Key and/or Token. This part is non-secret, it is included in your request header or body and sent over HTTPS in open text to identify your request. It is often a string in Hex or Base64 encoding or an UUID identifier.
  • secret . This is your private key. Keep it secret, don’t tell it to anybody. It is used to sign your requests locally before sending them to exchanges. The secret key does not get sent over the internet in the request-response process and should not be published or emailed. It is used together with the nonce to generate a cryptographically strong signature. That signature is sent with your public key to authenticate your identity. Each request has a unique nonce and therefore a unique cryptographic signature.
  • uid . Some exchanges (not all of them) also generate a user id or uid for short. It can be a string or numeric literal. You should set it, if that is explicitly required by your exchange. See their docs for details.
  • password . Some exchanges (not all of them) also require your password/phrase for trading. You should set this string, if that is explicitly required by your exchange. See their docs for details.

In order to create API keys find the API tab or button in your user settings on the exchange website. Then create your keys and copy-paste them to your config file. Your config file permissions should be set appropriately, unreadable to anyone except the owner.

Remember to keep your secret key safe from unauthorized use, do not send or tell it to anybody. A leak of the secret key or a breach in security can cost you a fund loss.

To set up an exchange for trading just assign the API credentials to an existing exchange instance or pass them to exchange constructor upon instantiation, like so:

Note that your private requests will fail with an exception or error if you don’t set up your API credentials before you start trading. To avoid character escaping always write your credentials in single quotes, not double quotes ( ‘VERY_GOOD’ , ",VERY_BAD", ).

Querying Account Balance¶

The returned balance structure is as follows:

Some exchanges may not return full balance info. Many exchanges do not return balances for your empty or unused accounts. In that case some currencies may be missing in returned balance structure.

Also, some exchanges cannot return certain fields and are only capable of telling a total balance (without details). Therefore some or all of the free, used and total amounts may be undefined, None or null. You need to account for that when working with returned balances.

Orders¶

Querying Orders¶

Most of the time you can query orders by their ids or statuses, though not all exchanges offer a full and flexible set of endpoints for querying orders. Some exchanges might not have a method for fetching recently closed orders, the other can lack a method for getting an order by id, etc. The ccxt library will target those cases by making workarounds if possible.

By Order Id¶

To get details of a particular order by its id, use the fetchOrder / fetch_order method. Some exchanges also require a symbol even when fetching a particular order by id.

The signature of the fetchOrder/fetch_order method is as follows:

You can pass custom overrided key-values in additional params if needed. Below are examples of using the fetchOrder method to get order info from an authenticated exchange instance:

All Orders¶

Open Orders¶

Closed Orders¶

Trades / Transactions / Fills / Executions¶

Recent Trades¶
Trades By Order Id¶

Order Structure¶

Most of methods returning orders within ccxt unified API will usually yield an order structure as described below:

Placing Orders¶

To place an order you will need the following information:

  • symbol , a string literal symbol of the market you wish to trade on, like BTC/USD , ZEC/ETH , DOGE/DASH , etc.
  • side , a string literal for the direction of your order, buy or sell . When you place a buy order you give quote currency and receive base currency. For example, buying BTC/USD means that you will receive bitcoins for your dollars. When you are selling BTC/USD the outcome is the opposite and you receive dollars for your bitcoins.
  • type , a string literal type of order, ccxt currently supports market and limit orders
  • amount , how much of currency you want to trade. This usually refers to base currency of the trading pair symbol, though some exchanges require the amount in quote currency and a few of them require base or quote amount depending on the side of the order. See their API docs for details.
  • price , how much quote currency you are willing to pay for a trade lot of base currency (for limit orders only)

A successful call to a unified method for placing market or limit orders returns the following structure:

Some exchanges will allow to trade with limit orders only. See their docs for details.

Market Orders¶

Market price orders are also known as spot price orders, instant orders or simply market orders. A market order gets executed immediately. The matching engine of the exchange closes the order (fulfills it) with one or more transactions from the top of the order book stack.

The exchange will close your market order for the best price available. You are not guaranteed though, that the order will be executed for the price you observe prior to placing your order. There can be a slight change of the price for the traded market while your order is being executed, also known as price slippage. The price can slip because of networking roundtrip latency, high loads on the exchange, price volatility and other factors. When placing a market order you don’t need to specify the price of the order.

Note, that some exchanges will not accept market orders (they allow limit orders only).

Limit Orders¶

Limit price orders are also known as limit orders. Some exchanges accept limit orders only. Limit orders require a price (rate per unit) to be submitted with the order. The exchange will close limit orders if and only if market price reaches the desired level.

Custom Order Params¶

Some exchanges allow you to specify optional parameters for your order. You can pass your optional parameters and override your query with an associative array using the params argument to your unified API call.

Cancelling Orders¶

To cancel an existing order pass the order id to cancelOrder (id, symbol, params) / cancel_order (id, symbol, params) method. Note, that some exchanges require a second symbol parameter even to cancel a known order by id. The usage is shown in the following examples:

Funding Your Account¶

Deposit¶

Withdraw¶

The withdraw method returns a dictionary containing the withdrawal id, which is usually the txid of the onchain transaction itself, or an internal withdrawal request id registered within the exchange. The returned value looks as follows:

Some exchanges require a manual approval of each withdrawal by means of 2FA (2-factor authentication). In order to approve your withdrawal you usually have to either click their secret link in your email inbox or enter a Google Authenticator code or an Authy code on their website to verify that withdrawal transaction was requested intentionally.

In some cases you can also use the withdrawal id to check withdrawal status later (whether it succeeded or not) and to submit 2FA confirmation codes, where this is supported by the exchange. See their docs for details.

Ledger¶

Overriding The Nonce¶

The default nonce is a 32-bit Unix Timestamp in seconds. You should override it with a milliseconds-nonce if you want to make private requests more frequently than once per second! Most exchanges will throttle your requests if you hit their rate limits, read `API docs for your exchange <,https://github.com/kroitor/ccxt/wiki/Exchanges>,`__ carefully!

In case you need to reset the nonce it is much easier to create another pair of keys for using with private APIs. Creating new keys and setting up a fresh unused keypair in your config is usually enough for that.

In some cases you are unable to create new keys due to lack of permissions or whatever. If that happens you can still override the nonce. Base market class has the following methods for convenience:

  • seconds () : returns a Unix Timestamp in seconds.
  • milliseconds () : same in milliseconds (ms = 1000 * s, thousandths of a second).
  • microseconds () : same in microseconds (Ојs = 1000 * ms, millionths of a second).

There are exchanges that confuse milliseconds with microseconds in their API docs, let’s all forgive them for that, folks. You can use methods listed above to override the nonce value. If you need to use the same keypair from multiple instances simultaneously use closures or a common function to avoid nonce conflicts. In Javascript you can override the nonce by providing a nonce parameter to the exchange constructor or by setting it explicitly on exchange object:

In Python and PHP you can do the same by subclassing and overriding nonce function of a particular exchange class:

All exceptions are derived from the base BaseError exception, which, in its turn, is defined in the ccxt library like so:

Below is an outline of exception inheritance hierarchy:

  • BaseError : Generic error class for all sorts of errors, including accessibility and request/response mismatch. Users should catch this exception at the very least, if no error differentiation is required.
  • ExchangeError : This exception is thrown when an exchange server replies with an error in JSON, possible reasons:
  • endpoint is switched off by the exchange
  • symbol not found on the exchange
  • some additional endpoint parameter required by the exchange is missing
  • the format of some parameters passed into the endpoint is incorrect
  • an exchange replies with an unclear answer
  • NotSupported : This exception is raised if the endpoint is not offered/not supported by the exchange API.
  • InsufficientFunds : This exception is raised when you don’t have enough currency on your account to make an order.
  • AuthenticationError : Raised when an exchange requires one of the API credentials that you’ve missed to specify, or when there’s a mistake in the keypair or an outdated nonce. Most of the time you need apiKey and secret , some times you also need uid and/or password .
  • NetworkError : All errors related to networking are usually recoverable, meaning that networking problems, traffic congestion, unavailability is usually time-dependent. Making a retry later is usually enough to recover from a NetworkError, but if it doesn’t go away, then it may indicate some persistent problem with the exchange or with your connection.
  • DDoSProtection : This exception is thrown whenever a Cloudflare / Incapsula / rate limiter restrictions are enforced upon on you or the region you’re connecting from. The ccxt library does a case-insensitive match of the response received from the exchange to one of the following keywords:
  • cloudflare
  • incapsula
  • RequestTimeout : The name literally says it all. This exception is raised when connection with the exchange fails or data is not fully received in a specified amount of time. This is controlled by the timeout option.
  • ExchangeNotAvailable : The ccxt library throws this error if it detects any of the following keywords in response:
    • offline
    • unavailable
    • busy
    • retry
    • wait
    • maintain
    • maintenance
    • maintenancing
    • In case you experience any difficulty connecting to a particular exchange, do the following in order of precedence:

      1. Check the CHANGELOG for recent updates.
      2. Turn verbose = true to get more detail about it.
      3. Check you API credentials. Try a fresh new keypair if possible.
      4. Check your nonce. If you used your API keys with other software, you most likely should override your nonce function to match your previous nonce value. A nonce usually can be easily reset by generating a new unused keypair.
      5. Check your request rate if you are getting nonce errors. Your private requests should not follow one another quickly. You should not send them one after another in a split second or in short time. The exchange will most likely ban you if you don’t make a delay before sending each new request. In other words, you should not hit their rate limit by sending unlimited private requests too frequently. Add a delay to your subsequent requests, like show in the long-poller examples, also here.
      6. Read the docs for your exchange and compare your verbose output to the docs.
      7. Check your connectivity with the exchange by accessing it with your browser.
      8. Check your connection with the exchange through a proxy. Read the Proxy section for more details.
      9. Try accesing the exchange from a different computer or a remote server, to see if this is a local or global issue with the exchange.
      10. Check if there were any news from the exchange recently regarding downtime for maintenance. Some exchanges go offline for updates regularly (like once a week).

      Related video: 20- How to Scan for Subdomain Takeover Vulnerability


      Leave a Reply

      Your email address will not be published. Required fields are marked *