Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork8k
Manual
The ccxt library is a collection of available cryptoexchanges 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.
The structure of the library can be outlined as follows:
User +-------------------------------------------------------------+ | CCXT | +------------------------------+------------------------------+ | Public | Private | +=============================================================+ │ . | │ The Unified CCXT API | │ . | | loadMarkets . fetchBalance | | fetchMarkets . createOrder | | fetchCurrencies . cancelOrder | | fetchTicker . fetchOrder | | fetchTickers . fetchOrders | | fetchOrderBook . fetchOpenOrders | | fetchOHLCV . fetchClosedOrders | | fetchStatus . fetchMyTrades | | fetchTrades . deposit | | . withdraw | │ . | +=============================================================+ │ . | | Custom Exchange API | | (Derived Classes And Their Implicit Methods) | │ . | | publicGet... . privateGet... | | publicPost... . privatePost... | | . privatePut... | | . privateDelete... | | . sign | │ . | +=============================================================+ │ . | | Base Exchange Class | │ . | +=============================================================+
Full public and private HTTP REST APIs for all exchanges are implemented. WebSocket implementations in JavaScript, PHP, Python are available inCCXT Pro, which is a professional addon to CCXT with support for WebSocket streams.
Follow us on Twitter
Read our blog on Medium
Join our Discord
CCXT Chat on Telegram (technical support)
- Announcement channels:
Besides making basic market and limit orders, some exchanges offer margin trading (leverage), various derivatives (like futures contracts and options) and also havedark pools,OTC (over-the-counter trading), merchant APIs and much more.
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:
constccxt=require('ccxt')console.log(ccxt.exchanges)
importccxtprint (ccxt.exchanges)
include'ccxt.php';var_dump (\ccxt\Exchange::$exchanges);
An exchange can be instantiated like shown in the examples below:
constccxt=require('ccxt')letexchange=newccxt.kraken()// default idletkraken1=newccxt.kraken({id:'kraken1'})letkraken2=newccxt.kraken({id:'kraken2'})letid='coinbasepro'letcoinbasepro=newccxt[id]();// from variable idconstexchangeId='binance',exchangeClass=ccxt[exchangeId],exchange=newexchangeClass({'apiKey':'YOUR_API_KEY','secret':'YOUR_SECRET',})
importccxtexchange=ccxt.okcoin ()# default idokcoin1=ccxt.okcoin ({'id':'okcoin1' })okcoin2=ccxt.okcoin ({'id':'okcoin2' })id='btcchina'btcchina=eval ('ccxt.%s ()'%id)coinbasepro=getattr (ccxt,'coinbasepro') ()# from variable idexchange_id='binance'exchange_class=getattr(ccxt,exchange_id)exchange=exchange_class({'apiKey':'YOUR_API_KEY','secret':'YOUR_SECRET',})
The ccxt library in PHP uses builtin UTC/GMT time functions, therefore you are required to set date.timezone in your php.ini or calldate_default_timezone_set() function before using the PHP version of the library. The recommended timezone setting is"UTC"
.
// PHPdate_default_timezone_set('UTC');include'ccxt.php';$bitfinex =new \ccxt\bitfinex();// default id$bitfinex1 =new \ccxt\bitfinex(array('id' =>'bitfinex1'));$bitfinex2 =new \ccxt\bitfinex(array('id' =>'bitfinex2'));$id ='kraken';$exchange ='\\ccxt\\' .$id;$kraken =new$exchange();// from variable id$exchange_id ='binance';$exchange_class ="\\ccxt\\$exchange_id";$exchange =new$exchange_class(array('apiKey' =>'YOUR_API_KEY','secret' =>'YOUR_SECRET',));
Major exchanges have the.features
property available, where you can see what methods and functionalities are supported for each market-type (if any method is set tonull/undefined
it means method is "not supported" by the exchange)
this feature is currently a work in progress and might be incomplete, feel free to report any issues you find in it
constexchange=newccxt.binance()console.log(exchange.features);// outputs like:{spot:{sandbox:true,// whether testnet is supportedcreateOrder:{triggerPrice:true,// if trigger order is supportedtriggerPriceType:undefined,// if trigger price type is supported (last, mark, index)triggerDirection:false,// if trigger direction is supported (up, down)stopLossPrice:true,// if stop-loss order is supported (read "Stop Loss Orders" paragraph)takeProfitPrice:true,// if take-profit order is supportedattachedStopLossTakeProfit:{triggerPriceType:{last:true,mark:true,index:true,},price:true,// whether 'limit' price can be used (instead of market order)},marginMode:true,// if `marginMode` param is supported (cross, isolated)timeInForce:{// supported TIF typesGTC:true,IOC:true,FOK:true,PO:true,GTD:false},hedged:false,// if `hedged` param is supported (true, false)leverage:false,// if `leverage` param is supported (true, false)selfTradePrevention:true,// if `selfTradePrevention` param is supported (true, false)trailing:true,// if trailing order is supportediceberg:true,// if iceberg order is supportedmarketBuyByCost:true,// if creating market buy order is possible with `cost` parammarketBuyRequiresPrice:true,// if creating market buy order (if 'cost' not used) requires `price` param to be set},createOrders:{'max':50,// if batch order creation is supported},fetchMyTrades:{limit:1000,// max limit per calldaysBack:undefined,// max historical period that can be accesseduntilDays:1// if `until` param is supported, then this is permitted distance from `since`},fetchOrder:{marginMode:true,// when supported, margin order should be fetched with this flagtrigger:false,// similar as abovetrailing:false// similar as above},// other methods have similar propertiesfetchOpenOrders:{limit:undefined,marginMode:true,trigger:false,trailing:false},fetchOrders:{limit:1000,daysBack:undefined,untilDays:10000,marginMode:true,trigger:false,trailing:false},fetchClosedOrders:{limit:1000,daysBackClosed:undefined,// max days-back for closed ordersdaysBackCanceled:undefined,// max days-back for canceled ordersuntilDays:10000,marginMode:true,trigger:false,trailing:false},fetchOHLCV:{paginate:true,limit:1000}},swap:{linear:{ ...},// similar to above dictinverse:{ ...},// similar to above dict}future:{linear:{ ...},// similar to above dictinverse:{ ...},// similar to above dict}}
Most of exchange properties as well as specific options can be overrided upon exchange class instantiation or afterwards, like shown below:
constexchange=newccxt.binance({'rateLimit':10000,// unified exchange property'headers':{'YOUR_CUSTOM_HTTP_HEADER':'YOUR_CUSTOM_VALUE',},'options':{'adjustForTimeDifference':true,// exchange-specific option}})exchange.options['adjustForTimeDifference']=false
exchange=ccxt.binance ({'rateLimit':10000,# unified exchange property'headers': {'YOUR_CUSTOM_HTTP_HEADER':'YOUR_CUSTOM_VALUE', },'options': {'adjustForTimeDifference':True,# exchange-specific option }})exchange.options['adjustForTimeDifference']=False
$exchange_id ='binance';$exchange_class ="\\ccxt\\$exchange_id";$exchange =new$exchange_class(array('rateLimit' =>10000,// unified exchange property'headers' =>array('YOUR_CUSTOM_HTTP_HEADER' =>'YOUR_CUSTOM_VALUE', ),'options' =>array('adjustForTimeDifference' =>true,// exchange-specific option ),));$exchange->options['adjustForTimeDifference'] =false;
In all CCXT-supported languages, you can override instance methods during runtime:
constex=newccxt.binance();ex.fetch_ticker=function(symbol,params={}){// your codes go here};console.log(ex.fetch_ticker('BTC/USDT'));
ex=ccxt.binance()defmy_overload(symbol,params= {}):# your codes go hereex.fetch_ticker=my_overloadprint(ex.fetch_ticker('BTC/USDT'))
$ex =new \ccxt\binance();$ex->add_method('fetch_ticker',function($symbol,$params = []) {// your codes go here});var_dump($ex->call_method('fetch_ticker', ['BTC/USDT']));
Some exchanges also offer separate APIs for testing purposes that allows developers to trade virtual money for free and test out their ideas. Those APIs are called"testnets", "sandboxes" or "staging environments" (with virtual testing assets) as opposed to"mainnets" and "production environments" (with real assets). Most often a sandboxed API is a clone of a production API, so, it's literally the same API, except for the URL to the exchange server.
CCXT unifies that aspect and allows the user to switch to the exchange's sandbox (if supported by the underlying exchange).To switch to the sandbox one has to call theexchange.setSandboxMode (true)
orexchange.set_sandbox_mode(true)
immediately after creating the exchange before any other call!
constexchange=newccxt.binance(config)exchange.setSandboxMode(true)// enable sandbox mode
exchange=ccxt.binance(config)exchange.set_sandbox_mode(True)# enable sandbox mode
$exchange =new \ccxt\binance($config);$exchange->set_sandbox_mode(true);// enable sandbox mode
- The
exchange.setSandboxMode (true) / exchange.set_sandbox_mode (True)
has to be your first call immediately after creating the exchange (before any other calls) - To obtain theAPI keys to the sandbox the user has to register with the sandbox website of the exchange in question and create a sandbox keypair
- Sandbox keys are not interchangeable with production keys!
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 generic exchange properties with values added for example:
{'id':'exchange'// lowercase string exchange id'name':'Exchange'// human-readable string'countries':['US','CN','EU'],// array of ISO country codes'urls':{'api':'https://api.example.com/data',// string or dictionary of base API URLs'www':'https://www.example.com'// string website URL'doc':'https://docs.example.com/api',// string URL or array of URLs},'version':'v1',// string ending with digits'api':{ ...},// dictionary of api endpoints'has':{// exchange capabilities'CORS':false,'cancelOrder':true,'createDepositAddress':false,'createOrder':true,'fetchBalance':true,'fetchCanceledOrders':false,'fetchClosedOrder':false,'fetchClosedOrders':false,'fetchCurrencies':false,'fetchDepositAddress':false,'fetchMarkets':true,'fetchMyTrades':false,'fetchOHLCV':false,'fetchOpenOrder':false,'fetchOpenOrders':false,'fetchOrder':false,'fetchOrderBook':true,'fetchOrders':false,'fetchStatus':'emulated','fetchTicker':true,'fetchTickers':false,'fetchBidsAsks':false,'fetchTrades':true,'withdraw':false,},'timeframes':{// empty if the exchange.has['fetchOHLCV'] !== true'1m':'1minute','1h':'1hour','1d':'1day','1M':'1month','1y':'1year',},'timeout':10000,// number in milliseconds'rateLimit':2000,// number in milliseconds'userAgent':'ccxt/1.1.1 ...'// string, HTTP User-Agent header'verbose':false,// boolean, output error details'markets':{ ...}// dictionary of markets/pairs by symbol'symbols':[ ...]// sorted list of string symbols (traded pairs)'currencies':{ ...}// dictionary of currencies by currency code'markets_by_id':{ ...},// dictionary of array of dictionaries (markets) by id'currencies_by_id':{ ...},// dictionary of dictionaries (markets) by id'apiKey':'92560ffae9b8a0421...',// string public apiKey (ASCII, hex, Base64, ...)'secret':'9aHjPmW+EtRRKN/Oi...'// string private secret key'password':'6kszf4aci8r',// string password'uid':'123456',// string user id'options':{ ...},// exchange-specific options// ... other properties here ...}
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
: 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.has
: This is an associative array of exchange capabilities (e.gfetchTickers
,fetchOHLCV
orCORS
).timeframes
: An associative array of timeframes, supported by the fetchOHLCV method of the exchange. This is only populated whenhas['fetchOHLCV']
property is true.timeout
: A timeout in milliseconds for a request-response roundtrip (default timeout is 10000 ms = 10 seconds). If the response is not received in that time, the library will throw anRequestTimeout
exception. You can leave the default timeout value or set it to a reasonable value. Hanging forever with no timeout is not your option, for sure. You don't have to override this option in general case.rateLimit
: A request rate limit in milliseconds. Specifies the required minimal delay between two consequent HTTP requests to the same exchange. The built-in rate-limiter is enabled by default and can be turned off by setting theenableRateLimit
property to false.enableRateLimit
: A boolean (true/false) value that enables the built-in rate limiter and throttles consecutive requests. This setting istrue
(enabled) by default.The user is required to implement ownrate limiting or leave the built-in rate limiter enabled to avoid being banned from the exchange.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. The value ofuserAgent
may be overrided by HTTPheaders
property below.headers
: An associative array of HTTP headers and their values. Default value is empty{}
. All headers will be prepended to all requests. If theUser-Agent
header is set withinheaders
, it will override whatever value is set in theuserAgent
property above.verbose
: A boolean flag indicating whether to log HTTP requests to stdout (verbose flag is false by default). Python people have an alternative way of DEBUG logging with a standard pythonic logger, which is enabled by adding these two lines to the beginning of their code:importlogginglogging.basicConfig(level=logging.DEBUG)
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 theloadMarkets() / 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 themarkets
property. Symbols are loaded and reloaded from markets. This property is a convenient shorthand for all market keys.currencies
: An associative array (a dict) of currencies by codes (usually 3 or 4 letters) available with an exchange. Currencies are loaded and reloaded from markets.markets_by_id
: An associative array of arrays of markets indexed by exchange-specific ids. Typically a length one array unless there are multiple markets with the same marketId. Markets should be loaded prior to accessing this property.apiKey
: This is your public API key string literal. Most exchanges requireAPI keys setup.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.requiredCredentials
: A unified associative dictionary that shows which of the above API credentials are required for sending private API calls to the underlying exchange (an exchange may require a specific set of keys).options
: An exchange-specific associative dictionary containing special keys and options that are accepted by the underlying exchange and supported in CCXT.precisionMode
: The exchange decimal precision counting mode, read more aboutPrecision And LimitsFor proxies -
proxyUrl
,httpUrl
,httpsUrl
,socksProxy
,wsProxy
,wssProxy
,wsSocksProxy
: An url of specific proxy. Read details inProxy section.
See this section onOverriding exchange properties.
has
: An assoc-array containing flags for exchange capabilities, including the following:'has':{'CORS':false,// has Cross-Origin Resource Sharing enabled (works from browser) or not// unified methods availability flags (can be true, false, or 'emulated'):'cancelOrder':true,'createDepositAddress':false,'createOrder':true,'fetchBalance':true,'fetchCanceledOrders':false,'fetchClosedOrder':false,'fetchClosedOrders':false,'fetchCurrencies':false,'fetchDepositAddress':false,'fetchMarkets':true,'fetchMyTrades':false,'fetchOHLCV':false,'fetchOpenOrder':false,'fetchOpenOrders':false,'fetchOrder':false,'fetchOrderBook':true,'fetchOrders':false,'fetchStatus':'emulated','fetchTicker':true,'fetchTickers':false,'fetchBidsAsks':false,'fetchTrades':true,'withdraw':false, ...}
The meaning of each flag showing availability of this or that method is:
- a value of
undefined
/None
/null
means the method is not currently implemented in ccxt (either ccxt has not unified it yet or the method isn't natively available from the exchange API) - boolean
false
specifically means that the endpoint isn't natively available from the exchange API - boolean
true
means the endpoint is natively available from the exchange API and unified in the ccxt library 'emulated'
string means the endpoint isn't natively available from the exchange API but reconstructed (as much as possible) by the ccxt library from other available true-methods
For a complete list of all exchages and their supported methods, please, refer to this example:https://github.com/ccxt/ccxt/blob/master/examples/js/exchange-capabilities.js
- a value of
Exchanges usually impose what is called arate 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 allowup 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.
Theexchange.rateLimit
property is set to a safe default which is sub-optimal. Some exchanges may have varying rate limits for different endpoints. It is up to the user to tweakrateLimit
according to application-specific purposes.
The CCXT library has a built-in experimental rate-limiter that will do the necessary throttling in background transparently to the user.WARNING: users are responsible for at least some type of rate-limiting: either by implementing a custom algorithm or by doing it with the built-in rate-limiter..
You can turn on/off the built-in rate-limiter with.enableRateLimit
property, like so:
// enable built-in rate limiting upon instantiation of the exchangeconstexchange=newccxt.bitfinex({// 'enableRateLimit': true, // enabled by default})// or switch the built-in rate-limiter on or off later after instantiationexchange.enableRateLimit=true// enableexchange.enableRateLimit=false// disable
# enable built-in rate limiting upon instantiation of the exchangeexchange=ccxt.bitfinex({# 'enableRateLimit': True, # enabled by default})# or switch the built-in rate-limiter on or off later after instantiationexchange.enableRateLimit=True# enableexchange.enableRateLimit=False# disable
// enable built-in rate limiting upon instantiation of the exchange$exchange =new \ccxt\bitfinex (array (// 'enableRateLimit' => true, // enabled by default));// or switch the built-in rate-limiter on or off later after instantiation$exchange->enableRateLimit =true;// enable$exchange->enableRateLimit =false;// disable
In case your calls hit a rate limit or get nonce errors, the ccxt library will throw anInvalidNonce
exception, or, in some cases, one of the following types:
DDoSProtection
ExchangeNotAvailable
ExchangeError
InvalidNonce
A later retry is usually enough to handle that.
The rate limiter is a property of the exchange instance, in other words, each exchange instance has its own rate limiter that is not aware of the other instances. In many cases the user should reuse the same exchange instance throughout the program. Do not use multiple instances of the same exchange with the same API keypair from the same IP address.
// DO NOT DO THIS!constbinance1=newccxt.binance()constbinance2=newccxt.binance()constbinance3=newccxt.binance()while(true){constresult=awaitPromise.all([binance1.fetchOrderBook('BTC/USDT'),binance2.fetchOrderBook('ETH/USDT'),binance3.fetchOrderBook('ETH/BTC'),])console.log(result)}
Reuse the exchange instance as much as possible as shown below:
// DO THIS INSTEAD:constbinance=newccxt.binance()while(true){constresult=awaitPromise.all([binance.fetchOrderBook('BTC/USDT'),binance.fetchOrderBook('ETH/USDT'),binance.fetchOrderBook('ETH/BTC'),])console.log(result)}
Since the rate limiter belongs to the exchange instance, destroying the exchange instance will destroy the rate limiter as well. Among the most common pitfalls with the rate limiting is creating and dropping the exchange instance over and over again. If in your program you are creating and destroying the exchange instance (say, inside a function that is called multiple times), then you are effectively resetting the rate limiter over and over and that will eventually break the rate limits. If you are recreating the exchange instance every time instead of reusing it, CCXT will try to load the markets every time. Therefore, you will force-load the markets over and over as explained in theLoading Markets section. Abusing the markets endpoint will eventually break the rate limiter as well.
// DO NOT DO THIS!asyncfunctiontick(){constexchange=newccxt.binance()constresponse=awaitexchange.fetchOrderBook('BTC/USDT')// ... some processing here ...returnresponse}while(true){constresult=awaittick()console.log(result)}
Do not break this rule unless you really understand the inner workings of the rate-limiter and you are 100% sure you know what you're doing. In order to stay safe always reuse the exchange instance throughout your functions and methods callchain like shown below:
// DO THIS INSTEAD:asyncfunctiontick(exchange){constresponse=awaitexchange.fetchOrderBook('BTC/USDT')// ... some processing here ...returnresponse}constexchange=newccxt.binance()while(true){constresult=awaittick(exchange)console.log(result)}
Some exchanges areDDoS-protected byCloudflare orIncapsula. 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.
The most common symptoms for a DDoS protection problem, rate-limiting problem or for a location-based filtering issue:
- Getting
RequestTimeout
exceptions with all types of exchange methods - Catching
ExchangeError
orExchangeNotAvailable
with HTTP error codes 400, 403, 404, 429, 500, 501, 503, etc.. - Having DNS resolving issues, SSL certificate issues and low-level connectivity issues
- Getting a template HTML page instead of JSON from the exchange
If you encounter DDoS protection errors and cannot reach a particular exchange then:
- use aproxy (this is less responsive, though)
- ask the exchange support to add you to a whitelist
- try an alternative IP within a different geographic region
- run your software in a distributed network of servers
- run your software in close proximity to the exchange (same country, same city, same datacenter, same server rack, same server)
- ...
- Currency Structure
- Market Structure
- Precision And Limits
- Loading Markets
- Symbols And Market Ids
- Market Cache Force Reload
Each exchange is a place for trading some kinds of valuables. The exchanges may use differing terms to call them:"a currency","an asset","a coin","a token","stock","commodity","crypto", "fiat", etc. A place for trading one asset for another is usually called"a market","a symbol","a trading pair","a contract", etc.
In terms of the ccxt library, every exchange offers multiplemarkets within itself. Each market is defined by two or morecurrencies. The set of markets differs from exchange to exchange opening possibilities for cross-exchange and cross-market arbitrage.
{'id':'btc',// string literal for referencing within an exchange'code':'BTC',// uppercase unified string literal code of the currency'name':'Bitcoin',// string, human-readable name, if specified'active':true,// boolean, currency status (tradeable and withdrawable)'fee':0.123,// withdrawal fee, flat'precision':8,// number of decimal digits "after the dot" (depends on exchange.precisionMode)'deposit':true// boolean, deposits are available'withdraw':true// boolean, withdraws are available'limits':{// value limits when placing orders on this market'amount':{'min':0.01,// order amount should be > min'max':1000,// order amount should be < max},'withdraw':{ ...},// withdrawal limits'deposit':{...},},'networks':{...}// network structures indexed by unified network identifiers (ERC20, TRC20, BSC, etc)'info':{ ...},// the original unparsed currency info from the exchange}
Each currency is an associative array (aka dictionary) with the following keys:
id
. The string or numeric ID of the currency within the exchange. Currency ids are used inside exchanges internally to identify coins during the request/response process.code
. An uppercase string code representation of a particular currency. Currency codes are used to reference currencies within the ccxt library (explained below).name
. A human-readable name of the currency (can be a mix of uppercase & lowercase characters).fee
. The withdrawal fee value as specified by the exchange. In most cases it means a flat fixed amount paid in the same currency. If the exchnange does not specify it via public endpoints, thefee
can beundefined/None/null
or missing.active
. A boolean indicating whether trading or funding (depositing or withdrawing) for this currency is currently possible, more about it here:active
status.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
. Precision accepted in values by exchanges upon referencing this currency. The value of this property depends onexchange.precisionMode
.limits
. The minimums and maximums for amounts (volumes), withdrawals and deposits.
{'id':'tron',// string literal for referencing within an exchange'network':'TRC20'// unified network'name':'Tron Network',// string, human-readable name, if specified'active':true,// boolean, currency status (tradeable and withdrawable)'fee':0.123,// withdrawal fee, flat'precision':8,// number of decimal digits "after the dot" (depends on exchange.precisionMode)'deposit':true// boolean, deposits are available'withdraw':true// boolean, withdraws are available'limits':{// value limits when placing orders on this market'amount':{'min':0.01,// order amount should be > min'max':1000,// order amount should be < max},'withdraw':{ ...},// withdrawal limits'deposit':{...},// deposit limits},'info':{ ...},// the original unparsed currency info from the exchange}
Each network is an associative array (aka dictionary) with the following keys:
id
. The string or numeric ID of the network within the exchange. Network ids are used inside exchanges internally to identify networks during the request/response process.network
. An uppercase string representation of a particular network. Networks are used to reference networks within the ccxt library.name
. A human-readable name of the network (can be a mix of uppercase & lowercase characters).fee
. The withdrawal fee value as specified by the exchange. In most cases it means a flat fixed amount paid in the same currency. If the exchnange does not specify it via public endpoints, thefee
can beundefined/None/null
or missing.active
. A boolean indicating whether trading or funding (depositing or withdrawing) for this currency is currently possible, more about it here:active
status.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
. Precision accepted in values by exchanges upon referencing this currency. The value of this property depends onexchange.precisionMode
.limits
. The minimums and maximums for amounts (volumes), withdrawals and deposits.
{'id':'btcusd',// string literal for referencing within an exchange'symbol':'BTC/USD',// uppercase string literal of a pair of currencies'base':'BTC',// uppercase string, unified base currency code, 3 or more letters'quote':'USD',// uppercase string, unified quote currency code, 3 or more letters'baseId':'btc',// any string, exchange-specific base currency id'quoteId':'usd',// any string, exchange-specific quote currency id'active':true,// boolean, market status'type':'spot',// spot for spot, future for expiry futures, swap for perpetual swaps, 'option' for options'spot':true,// whether the market is a spot market'margin':true,// whether the market is a margin market'future':false,// whether the market is a expiring future'swap':false,// whether the market is a perpetual swap'option':false,// whether the market is an option contract'contract':false,// whether the market is a future, a perpetual swap, or an option'settle':'USDT',// the unified currency code that the contract will settle in, only set if `contract` is true'settleId':'usdt',// the currencyId of that the contract will settle in, only set if `contract` is true'contractSize':1,// the size of one contract, only used if `contract` is true'linear':true,// the contract is a linear contract (settled in quote currency)'inverse':false,// the contract is an inverse contract (settled in base currency)'expiry':1641370465121,// the unix expiry timestamp in milliseconds, undefined for everything except market['type'] `future`'expiryDatetime':'2022-03-26T00:00:00.000Z',// The datetime contract will in iso8601 format'strike':4000,// price at which a put or call option can be exercised'optionType':'call',// call or put string, call option represents an option with the right to buy and put an option with the right to sell// note, 'taker' and 'maker' compose extended data for markets, however it might be better to use `fetchTradingFees` for more accuracy'taker':0.002,// taker fee rate, 0.002 = 0.2%'maker':0.0016,// maker fee rate, 0.0016 = 0.16%'percentage':true,// whether the taker and maker fee rate is a multiplier or a fixed flat amount'tierBased':false,// whether the fee depends on your trading tier (your trading volume)'feeSide':'get',// string literal can be 'get', 'give', 'base', 'quote', 'other''precision':{// number of decimal digits "after the dot"'price':8,// integer or float for TICK_SIZE roundingMode, might be missing if not supplied by the exchange'amount':8,// integer, might be missing if not supplied by the exchange'cost':8,// integer, very few exchanges actually have it},'limits':{// value limits when placing orders on this market'amount':{'min':0.01,// order amount should be > min'max':1000,// order amount should be < max},'price':{ ...},// same min/max limits for the price of the order'cost':{ ...},// same limits for order cost = price * amount'leverage':{ ...},// same min/max limits for the leverage of the order},'marginModes':{'cross':false,// whether pair supports cross-margin trading'isolated':false,// whether pair supports isolated-margin trading},'info':{ ...},// the original unparsed market info from the exchange}
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 asBaseCurrency/QuoteCurrency
with a slash as inBTC/USD
,LTC/CNY
orETH/EUR
, etc. Symbols are used to reference markets within the ccxt library (explained below).base
. A unified uppercase string code of base fiat or crypto currency. This is the standardized currency code that is used to refer to that currency or token throughout CCXT and throughout the Unified CCXT API, it's the language that CCXT understands.quote
. A unified uppercase string code of quoted fiat or crypto currency.baseId
. An exchange-specific id of the base currency for this market, not unified. Can be any string, literally. This is communicated to the exchange using the language the exchange understands.quoteId
. An exchange-specific id of the quote currency, not unified.active
. A boolean indicating whether or not trading this market is currently possible, more about it here:active
status.maker
. Float, 0.0015 = 0.15%. Maker fees are paid when you provide liquidity to the exchange i.e. youmarket-make an order and someone else fills it. Maker fees are usually lower than taker fees. Fees can be negative, this is very common amongst derivative exchanges. A negative fee means the exchange will pay a rebate (reward) to the user for trading this market (note, 'taker' and 'maker' publicly available fees, not taking into consideration your vip-level/volume/etc. UsefetchTradingFees
to get the fees specific to your account).taker
. Float, 0.002 = 0.2%. Taker fees are paid when youtake liquidity from the exchange and fill someone else's order.percentage
. A boolean true/false value indicating whethertaker
andmaker
are multipliers or fixed flat amounts.tierBased
. A boolean true/false value indicating whether the fee depends on your trading tier (usually, your traded volume over a period of time).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
. Precision accepted in order values by exchanges upon order placement for price, amount and cost. (The value inside this property depend on theexchange.precisionMode
).limits
. The minimums and maximums for prices, amounts (volumes) and costs (where cost = price * amount).optionType
. The type of the option,call
option represents an option with the right to buy andput
an option with the right to sell.strike
. Price at which an option can be bought or sold when it is exercised.
Theactive
flag is typically used incurrencies
andmarkets
. The exchanges might put a slightly different meaning into it. If a currency is inactive, most of the time all corresponding tickers, orderbooks and other related endpoints return empty responses, all zeroes, no data or outdated information. The user should check if the currency isactive
andreload markets periodically.
Note: thefalse
value for theactive
property doesn't always guarantee that all of the possible features like trading, withdrawing or depositing are disabled on the exchange. Likewise, neither thetrue
value guarantees that all those features are enabled on the exchange. Check the underlying exchanges' documentation and the code in CCXT for the exact meaning of theactive
flag for this or that exchange. This flag is not yet supported or implemented by all markets and may be missing.
WARNING! The information about the fee is experimental, unstable and may be partial or not available at all.
Do not confuselimits
withprecision
! Precision has nothing to do with min limits. A precision of0.01
does not necessarily mean that a minimum limit for market is0.01
. The opposite is also true: a min limit of0.01
does not necessarily mean a precision is0.01
.
Examples:
market['limits']['amount']['min'] == 0.05 &&market['precision']['amount'] == 0.0001 &&market['precision']['price'] == 0.01
- Theamount value should be >= 0.05:
+ good: 0.05, 0.051, 0.0501, 0.0502, ..., 0.0599, 0.06, 0.0601, ...- bad: 0.04, 0.049, 0.0499
- Precision of the amount should be up to 4 digits after dot (0.0001):
+ good: 0.05, 0.0501, ..., 0.06, ..., 0.0719, ...- bad: 0.05001, 0.05000, 0.06001
- Precision of the price should be up to 2 digits after dot (0.01):
+ good: 1.6, 1.61, 123.01, ..., 1234.56, ...- bad: 1.601, ..., 123.012, ..., 1234.567
(market['precision']['amount'] == -1)
A negativeprecision might only theoretically happen if exchange's
precisionMode
isSIGNIFICANT_DIGIT
orDECIMAL_PRECISION
. It means that the amount should be an integer multiple of 10 (to the absolute power specified):+ good: 10, 50, ..., 110, ... 1230, ..., 1000000, ..., 1234560, ...- bad: 9.5, ... 10.1, ..., 11, ... 200.71, ...
In case of
-2
the acceptable values would be multiple of100
(e.g. 100, 200, ... ), and so on.
Supported precision modes inexchange['precisionMode']
are:
TICK_SIZE
– almost all exchanges use this precision mode. In this mode, the numbers inmarket_or_currency['precision']
designate the minimal precision fractions (floats) for rounding or truncating.SIGNIFICANT_DIGITS
– counts non-zero digits only, some exchanges (bitfinex
and maybe a few other) implement this mode of counting decimals. With this mode of precision, the numbers inmarket_or_currency['precision']
designate the Nth place of the last significant (non-zero) decimal digit after the dot.DECIMAL_PLACES
(DEPRECATED, CCXT no longer uses this mode anywhere) – counts all digits. With this mode of precision, the numbers inmarket_or_currency['precision']
designate the number of decimal digits after the dot for further rounding or truncation.
The user is required to stay within all limits and precision! The values of the order should satisfy the following conditions:
- Order
amount
>=limits['amount']['min']
- Order
amount
<=limits['amount']['max']
- Order
price
>=limits['price']['min']
- Order
price
<=limits['price']['max']
- Order
cost
(amount * price
) >=limits['cost']['min']
- Order
cost
(amount * price
) <=limits['cost']['max']
- Precision of
amount
must be <=precision['amount']
- Precision of
price
must be <=precision['price']
The above values can be missing with some exchanges that don't provide info on limits from their API or don't have it implemented yet.
Each exchange has its own rounding, counting and padding modes.
Supported rounding modes are:
ROUND
– will round the last decimal digits to precisionTRUNCATE
– will cut off the digits after certain precision
The decimal precision counting mode is available in theexchange.precisionMode
property.
Supported padding modes are:
NO_PADDING
– default for most casesPAD_WITH_ZERO
– appends zero characters up to precision
Most of the time the user does not have to take care of precision formatting, since CCXT will handle that for the user when the user places orders or sends withdrawal requests, if the user follows the rules as described onPrecision And Limits. However, in some cases precision-formatting details may be important, so the following methods may be useful in the userland.
The exchange base class contains thedecimalToPrecision
method to help format values to the required decimal precision with support for different rounding, counting and padding modes.
functiondecimalToPrecision(x,roundingMode,numPrecisionDigits,countingMode=DECIMAL_PLACES,paddingMode=NO_PADDING)
# WARNING! The `decimal_to_precision` method is susceptible to getcontext().prec!defdecimal_to_precision(n,rounding_mode=ROUND,precision=None,counting_mode=DECIMAL_PLACES,padding_mode=NO_PADDING):
function decimalToPrecision ($x,$roundingMode =ROUND,$numPrecisionDigits =null,$countingMode =DECIMAL_PLACES,$paddingMode =NO_PADDING)
For examples of how to use thedecimalToPrecision
to format strings and floats, please, see the following files:
- Typescript:https://github.com/ccxt/ccxt/blob/master/ts/src/test/base/functions/test.number.ts
- #"https://github.com/ccxt/ccxt/blob/master/js/src/test/base/functions/test.number.js">https://github.com/ccxt/ccxt/blob/master/js/src/test/base/functions/test.number.js
- Python:https://github.com/ccxt/ccxt/blob/master/python/ccxt/test/base/test_number.py
- PHP:https://github.com/ccxt/ccxt/blob/master/php/test/base/test_number.php
Python WARNING! Thedecimal_to_precision
method is susceptible togetcontext().prec!
For users' convenience CCXT base exchange class also implements the following methods:
functionamountToPrecision(symbol,amount)functionpriceToPrecision(symbol,price)functioncostToPrecision(symbol,cost)functioncurrencyToPrecision(code,amount)
defamount_to_precision (symbol,amount):defprice_to_precision (symbol,price):defcost_to_precision (symbol,cost):defcurrency_to_precision (code,amount):
function amount_to_precision($symbol,$amount)function price_to_precision($symbol,$price)function cost_to_precision($symbol,$cost)function currency_to_precision($code,$amount)
Every exchange has its own precision settings, the above methods will help format those values according to exchange-specific precision rules, in a way that is portable and agnostic of the underlying exchange. In order to make that possible, markets and currencies have to be loaded prior to formatting any values.
Make sure toload the markets withexchange.loadMarkets()
before calling these methods!
For example:
awaitexchange.loadMarkets()constsymbol='BTC/USDT'constamount=1.2345678// amount in base currency BTCconstprice=87654.321// price in quote currency USDTconstformattedAmount=exchange.amountToPrecision(symbol,amount)constformattedPrice=exchange.priceToPrecision(symbol,price)console.log(formattedAmount,formattedPrice)
exchange.load_markets()symbol='BTC/USDT'amount=1.2345678# amount in base currency BTCprice=87654.321# price in quote currency USDTformatted_amount=exchange.amount_to_precision(symbol,amount)formatted_price=exchange.price_to_precision(symbol,price)print(formatted_amount,formatted_price)
$exchange->load_markets();$symbol ='BTC/USDT';$amount =1.2345678;// amount in base currency BTC$price =87654.321;// price in quote currency USDT$formatted_amount =$exchange->amount_to_precision($symbol,$amount);$formatted_price =$exchange->price_to_precision($symbol,$price);echo$formatted_amount,"",$formatted_price,"\n";
More practical examples that describe the behavior ofexchange.precisionMode
:
// case Aexchange.precisionMode=ccxt.DECIMAL_PLACESmarket=exchange.market(symbol)market['precision']['amount']===8// up to 8 decimals after the dotexchange.amountToPrecision(symbol,0.123456789)===0.12345678exchange.amountToPrecision(symbol,0.0000000000123456789)===0.0000000===0.0
// case Bexchange.precisionMode=ccxt.TICK_SIZEmarket=exchange.market(symbol)market['precision']['amount']===0.00000001// up to 0.00000001 precisionexchange.amountToPrecision(symbol,0.123456789)===0.12345678exchange.amountToPrecision(symbol,0.0000000000123456789)===0.00000000===0.0
// case Cexchange.precisionMode=ccxt.SIGNIFICANT_DIGITSmarket=exchange.market(symbol)market['precision']['amount']===8// up to 8 significant non-zero digitsexchange.amountToPrecision(symbol,0.0000000000123456789)===0.000000000012345678exchange.amountToPrecision(symbol,123.4567890123456789)===123.45678
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. For that reason, your first call to a unified CCXT API method like fetchTicker, fetchBalance, etc will take more time, than the consequent calls, since it has to do more work loading the market information from the exchange API. SeeNotes On Rate Limiter for more details.
In order to load markets manually beforehand call theloadMarkets ()
/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.
(async()=>{letkraken=newccxt.kraken()letmarkets=awaitkraken.loadMarkets()console.log(kraken.id,markets)})()
okcoin=ccxt.okcoin()markets=okcoin.load_markets()print(okcoin.id,markets)
$id ='huobipro';$exchange ='\\ccxt\\' .$id;$huobipro =new$exchange();$markets =$huobipro->load_markets();var_dump($huobipro->id,$markets);
Apart from the market info, theloadMarkets()
call will also load the currencies from the exchange and will cache the info in the.markets
and the.currencies
properties respectively.
The user can also bypass the cache and call unified methods for fetching that information from the exchange endpoints directly,fetchMarkets()
andfetchCurrencies()
, though using these methods is not recommended for end-users. The recommended way to preload markets is by calling theloadMarkets()
unified method. However, new exchange integrations are required to implement these methods if the underlying exchange has the corresponding API endpoints.
A currency code is a code of three to five letters, likeBTC
,ETH
,USD
,GBP
,CNY
,JPY
,DOGE
,RUB
,ZEC
,XRP
,XMR
, etc. Some exchanges have exotic currencies with longer codes.
A symbol is usually an uppercase string literal name of a pair of traded currencies with a slash in between. The first currency before the slash is usually calledbase currency, and the one after the slash is calledquote currency. Examples of a symbol are:BTC/USD
,DOGE/LTC
,ETH/EUR
,DASH/XRP
,BTC/CNY
,ZEC/XMR
,ETH/JPY
.
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, likebtcusd
,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 aren't 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.
Sometimes the user might notice a symbol like'XBTM18'
or'.XRPUSDM20180101'
or some other"exotic/rare symbols". The symbol isnot required to have a slash or to be a pair of currencies. The string in the symbol really depends on the type of the market (whether it is a spot market or a futures market, a darkpool market or an expired market, etc). Attempting to parse the symbol string is highly discouraged, one should not rely on the symbol format, it is recommended to use market properties instead.
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 argument. 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.
(async()=>{console.log(awaitexchange.loadMarkets())letbtcusd1=exchange.markets['BTC/USD']// get market structure by symbolletbtcusd2=exchange.market('BTC/USD')// same result in a slightly different wayletbtcusdId=exchange.marketId('BTC/USD')// get market id by symbolletsymbols=exchange.symbols// get an array of symbolsletsymbols2=Object.keys(exchange.markets)// same as previous lineconsole.log(exchange.id,symbols)// print all symbolsletcurrencies=exchange.currencies// a dictionary of currenciesletbitfinex=newccxt.bitfinex()awaitbitfinex.loadMarkets()bitfinex.markets['BTC/USD']// symbol → market (get market by symbol)bitfinex.markets_by_id['XRPBTC'][0]// id → market (get market by id)bitfinex.markets['BTC/USD']['id']// symbol → id (get id by symbol)bitfinex.markets_by_id['XRPBTC'][0]['symbol']// id → symbol (get symbol by id)})()
print(exchange.load_markets())etheur1=exchange.markets['ETH/EUR']# get market structure by symboletheur2=exchange.market('ETH/EUR')# same result in a slightly different wayetheurId=exchange.market_id('ETH/EUR')# get market id by symbolsymbols=exchange.symbols# get a list of symbolssymbols2=list(exchange.markets.keys())# same as previous lineprint(exchange.id,symbols)# print all symbolscurrencies=exchange.currencies# a dictionary of currencieskraken=ccxt.kraken()kraken.load_markets()kraken.markets['BTC/USD']# symbol → market (get market by symbol)kraken.markets_by_id['XXRPZUSD'][0]# id → market (get market by id)kraken.markets['BTC/USD']['id']# symbol → id (get id by symbol)kraken.markets_by_id['XXRPZUSD'][0]['symbol']# id → symbol (get symbol by id)
$var_dump($exchange->load_markets());$dashcny1 =$exchange->markets['DASH/CNY'];// get market structure by symbol$dashcny2 =$exchange->market('DASH/CNY');// same result in a slightly different way$dashcnyId =$exchange->market_id('DASH/CNY');// get market id by symbol$symbols =$exchange->symbols;// get an array of symbols$symbols2 =array_keys($exchange->markets);// same as previous linevar_dump($exchange->id,$symbols);// print all symbols$currencies =$exchange->currencies;// an associative array of currencies$okcoin ='\\ccxt\\okcoin';$okcoin =new$okcoin();$okcoin->load_markets();$okcoin->markets['BTC/USD'];// symbol → market (get market by symbol)$okcoin->markets_by_id['btc_usd'][0];// id → market (get market by id)$okcoin->markets['BTC/USD']['id'];// symbol → id (get id by symbol)$okcoin->markets_by_id['btc_usd'][0]['symbol'];// id → symbol (get symbol by id)
There is a bit of term ambiguity across various exchanges that may cause confusion among newcoming traders. Some exchanges call markets aspairs, whereas other exchanges call symbols asproducts. 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 butBTC
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
andBCH
. The nameBCC
is ambiguous for Bitcoin Cash, it is confused with BitConnect. The ccxt library will convertBCC
toBCH
where it is appropriate (some exchanges and aggregators confuse them).DRK → DASH
:DASH
was Darkcoin then became Dash (read more).BCHABC → BCH
: On November 15 2018 Bitcoin Cash forked the second time, so, now there isBCH
(for BCH ABC) andBSV
(for BCH SV).BCHSV → BSV
: This is a common substitution mapping for the Bitcoin Cash SV fork (some exchanges call itBSV
, others call itBCHSV
, we use the former).DSH → DASH
: Try not to confuse symbols and currencies. TheDSH
(Dashcoin) is not the same asDASH
(Dash). Some exchanges haveDASH
labelled inconsistently asDSH
, 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 thatDASH/BTC
is not the same asDSH/BTC
.XRB
→NANO
:NANO
is the newer code for RaiBlocks, thus, CCXT unified API will replace the olderXRB
withNANO
where needed.https://hackernoon.com/nano-rebrand-announcement-9101528a7b76USD
→USDT
: Some exchanges, like Bitfinex, HitBTC and a few other name the currency asUSD
in their listings, but those markets are actually tradingUSDT
. The confusion can come from a 3-letter limitation on symbol names or may be due to other reasons. In cases where the traded currency is actuallyUSDT
and is notUSD
– the CCXT library will performUSD
→USDT
conversion. Note, however, that some exchanges have bothUSD
andUSDT
symbols, for example, Kraken has aUSDT/USD
trading pair.
Each exchange has an associative array of substitutions for cryptocurrency symbolic codes in theexchange.commonCurrencies
property, like:
'commonCurrencies' : { 'XBT': 'BTC', 'OPTIMISM': 'OP', // ... etc}
where key represents actual name how exchange engine refers to that coin, and the value represents what you want to refer to it with through ccxt.
Sometimes the user may notice exotic symbol names with mixed-case words and spaces in the code. The logic behind having these names is explained by the rules for resolving conflicts in naming and currency-coding when one or more currencies have the same symbolic code with different exchanges:
- First, we gather all info available from the exchanges themselves about the currency codes in question. They usually have a description of their coin listings somewhere in their API or their docs, knowledgebases or elsewhere on their websites.
- When we identify each particular cryptocurrency standing behind the currency code, we look them up onCoinMarketCap.
- The currency that has the greatest market capitalization of all wins the currency code and keeps it. For example, HOT often stand for either
Holo
orHydro Protocol
. In this caseHolo
retains the codeHOT
, andHydro Protocol
will have its name as its code, literally,Hydro Protocol
. So, there may be trading pairs with symbols likeHOT/USD
(forHolo
) andHydro Protocol/USD
– those are two different markets. - If market cap of a particular coin is unknown or is not enough to determine the winner, we also take trading volumes and other factors into consideration.
- When the winner is determined all other competing currencies get their code names properly remapped and substituted within conflicting exchanges via
.commonCurrencies
.Note, it should be defined before '.loadMarkets()' happens! - Unfortunately this is a work in progress, because new currencies get listed daily and new exchanges are added from time to time, so, in general this is a never-ending process of self-correction in a quickly changing environment, practically, in"live mode". We are thankful for all reported conflicts and mismatches you may find.
Is it possible for symbols to change?
In short, yes, sometimes, but rarely. Symbolic mappings can be changed if that is absolutely required and cannot be avoided. However, all previous symbolic changes were related to resolving conflicts or forks. So far, there was no precedent of a market cap of one coin overtaking another coin with the same symbolic code in CCXT.
Can we rely on always listing the same crypto with the same symbol?
More or less ) First, this library is a work in progress, and it is trying to adapt to the everchanging reality, so there may be conflicts that we will fix by changing some mappings in the future. Ultimately, the license says "no warranties, use at your own risk". However, we don't change symbolic mappings randomly all over the place, because we understand the consequences and we'd want to rely on the library as well and we don't like to break the backward-compatibility at all.
If it so happens that a symbol of a major token is forked or has to be changed, then the control is still in the users' hands. Theexchange.commonCurrencies
property can beoverrided upon initialization or later, just like any other exchange property. If a significant token is involved, we usually post instructions on how to retain the old behavior by adding a couple of lines to the constructor params.
It depends on which exchange you are using, but some of them have a reversed (inconsistent) pairing ofbase
andquote
. They actually have base and quote misplaced (switched/reversed sides). In that case you'll see a difference of parsedbase
andquote
currency values with the unparsedinfo
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.
base currency ↓ BTC / USDT ETH / BTC DASH / ETH ↑ quote currency
We currently load spot markets with the unifiedBASE/QUOTE
symbol schema into the.markets
mapping, indexed by symbol. This would cause a naming conflict for futures and other derivatives that have the same symbol as their spot market counterparts. To accomodate both types of markets in the.markets
we require the symbols between 'future' and 'spot' markets to be distinct, as well as the symbols between 'linear' and 'inverse' contracts to be distinct.
Please, check this announcement:Unified contract naming conventions
CCXT supports the following types of derivative contracts:
future
– for expiring futures contracts that have a delivery/settlement dateswap
– for perpetual swap futures that don't have a delivery dateoption
– for option contracts (https://en.wikipedia.org/wiki/Option_contract)
A future market symbol consists of the underlying currency, the quoting currency, the settlement currency and an arbitrary identifier. Most often the identifier is the settlement date of the future contract inYYMMDD
format:
//// base asset or currency// ↓// ↓ quote asset or currency// ↓ ↓// ↓ ↓ settlement asset or currency// ↓ ↓ ↓// ↓ ↓ ↓ identifier (settlement date)// ↓ ↓ ↓ ↓// ↓ ↓ ↓ ↓'BTC/USDT:BTC-211225'// BTC/USDT futures contract settled in BTC (inverse) on 2021-12-25'BTC/USDT:USDT-211225'// BTC/USDT futures contract settled in USDT (linear, vanilla) on 2021-12-25'ETH/USDT:ETH-210625'// ETH/USDT futures contract settled in ETH (inverse) on 2021-06-25'ETH/USDT:USDT-210625'// ETH/USDT futures contract settled in USDT (linear, vanilla) on 2021-06-25
// base asset or currency// ↓// ↓ quote asset or currency// ↓ ↓// ↓ ↓ settlement asset or currency// ↓ ↓ ↓// ↓ ↓ ↓'BTC/USDT:BTC'// BTC/USDT inverse perpetual swap contract funded in BTC'BTC/USDT:USDT'// BTC/USDT linear perpetual swap contract funded in USDT'ETH/USDT:ETH'// ETH/USDT inverse perpetual swap contract funded in ETH'ETH/USDT:USDT'// ETH/USDT linear perpetual swap contract funded in USDT
//// base asset or currency// ↓// ↓ quote asset or currency// ↓ ↓// ↓ ↓ settlement asset or currency// ↓ ↓ ↓// ↓ ↓ ↓ identifier (settlement date)// ↓ ↓ ↓ ↓// ↓ ↓ ↓ ↓ strike price// ↓ ↓ ↓ ↓ ↓// ↓ ↓ ↓ ↓ ↓ type, put (P) or call (C)// ↓ ↓ ↓ ↓ ↓ ↓'BTC/USDT:BTC-211225-60000-P'// BTC/USDT put option contract strike price 60000 USDT settled in BTC (inverse) on 2021-12-25'ETH/USDT:USDT-211225-40000-C'// BTC/USDT call option contract strike price 40000 USDT settled in USDT (linear, vanilla) on 2021-12-25'ETH/USDT:ETH-210625-5000-P'// ETH/USDT put option contract strike price 5000 USDT settled in ETH (inverse) on 2021-06-25'ETH/USDT:USDT-210625-5000-C'// ETH/USDT call option contract strike price 5000 USDT settled in USDT (linear, vanilla) on 2021-06-25
Network | CCXT Code |
---|---|
Bitcoin | BTC |
Ethereum | ETH (For Ethereum) / ERC20 (For Tokens) |
Ripple | XRP |
Litecoin | LTC |
Dogecoin | DOGE |
Stellar | XLM |
Tron | TRX (For TRX) / TRC20 (For Tokens) |
Ethereum Classic | ETC |
Zcash | ZEC |
BSC (Binance Smart Chain) | BEP20 |
Monero | XMR |
Cardano | ADA |
Tezos | XTZ |
Cosmos | ATOM |
Solana | SOL |
BNB Beacon Chain | BEP2 |
Polkadot | DOT |
Algorand | ALGO |
Avalanche | AVAX |
Chainlink | LINK |
Bitcoin Cash | BCH |
Filecoin | FIL |
Kusama | KSM |
Elrond | EGLD |
THORChain | RUNE |
Internet Computer | ICP |
Near Protocol | NEAR |
Celo | CELO |
Hedera Hashgraph | HBAR |
IOTA | MIOTA |
Klaytn | KLAY |
VeChain | VET |
Theta Network | THETA |
Stacks | STX |
Bitcoin Lightning Network | LIGHTNING |
Optimism | OPTIMISM |
Arbitrum | ARBITRUM |
zkSync | zkSync |
Polygon | MATIC |
Fantom | FTM |
TheloadMarkets () / 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 themarkets
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.
(async()=>{letkraken=newccxt.kraken({verbose:true})// log HTTP requestsawaitkraken.loadMarkets()// request marketsconsole.log(kraken.id,kraken.markets)// output a full list of all loaded marketsconsole.log(Object.keys(kraken.markets))// output a short list of market symbolsconsole.log(kraken.markets['BTC/USD'])// output single market detailsawaitkraken.loadMarkets()// return a locally cached version, no reloadletreloadedMarkets=awaitkraken.loadMarkets(true)// force HTTP reload = trueconsole.log(reloadedMarkets['ETH/BTC'])})()
poloniex=ccxt.poloniex({'verbose':True})# log HTTP requestspoloniex.load_markets()# request marketsprint(poloniex.id,poloniex.markets)# output a full list of all loaded marketsprint(list(poloniex.markets.keys()))# output a short list of market symbolsprint(poloniex.markets['BTC/ETH'])# output single market detailspoloniex.load_markets()# return a locally cached version, no reloadreloadedMarkets=poloniex.load_markets(True)# force HTTP reload = Trueprint(reloadedMarkets['ETH/ZEC'])
$bitfinex =new \ccxt\bitfinex(array('verbose' =>true));// log HTTP requests$bitfinex.load_markets();// request marketsvar_dump($bitfinex->id,$bitfinex->markets);// output a full list of all loaded marketsvar_dump(array_keys ($bitfinex->markets));// output a short list of market symbolsvar_dump($bitfinex->markets['XRP/USD']);// output single market details$bitfinex->load_markets();// return a locally cached version, no reload$reloadedMarkets =$bitfinex->load_markets(true);// force HTTP reload = truevar_dump($bitfinex->markets['XRP/BTC']);
- API Methods / Endpoints
- Implicit API Methods
- Public/Private API
- Synchronous vs Asynchronous Calls
- Passing Parameters To API Methods
Each exchange offers a set of API methods. Each method of the API is called anendpoint. 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 canceling 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 theapi
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).
Most of exchange-specific API methods are implicit, meaning that they aren't defined explicitly anywhere in code. The library implements a declarative approach for defining implicit (non-unified) exchanges' API methods.
Each method of the API usually has its own endpoint. The library defines all endpoints for each particular exchange in the.api
property. Upon exchange construction an implicitmagic method (akapartial function orclosure) will be created insidedefineRestApi()/define_rest_api()
on the exchange instance for each endpoint from the list of.api
endpoints. This is performed for all exchanges universally. Each generated method will be accessible in bothcamelCase
andunder_score
notations.
The endpoints definition is afull 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. This is done automatically for all exchanges, therefore the ccxt library supportsall possible URLs offered by crypto exchanges.
Each implicit method gets a unique name which is constructed from the.api
definition. For example, a private HTTPS PUThttps://api.exchange.com/order/{id}/cancel
endpoint will have a corresponding exchange method named.privatePutOrderIdCancel()
/.private_put_order_id_cancel()
. A public HTTPS GEThttps://api.exchange.com/market/ticker/{pair}
endpoint would result in the corresponding method named.publicGetTickerPair()
/.public_get_ticker_pair()
, and so on.
An implicit method takes a dictionary of parameters, sends the request to the exchange and returns an exchange-specific JSON result from the APIas is, unparsed. To pass a parameter, add it to the dictionary explicitly under a key equal to the parameter's name. For the examples above, this would look like.privatePutOrderIdCancel ({ id: '41987a2b-...' })
and.publicGetTickerPair ({ pair: 'BTC/USD' })
.
The recommended way of working with exchanges is not using exchange-specific implicit methods but using the unified ccxt methods instead. The exchange-specific methods should be used as a fallback in cases when a corresponding unified method isn't available (yet).
To get a list of all available methods with an exchange instance, including implicit methods and unified methods you can simply do the following:
console.log (new ccxt.kraken ()) // JavaScriptprint(dir(ccxt.kraken())) # Pythonvar_dump (new \ccxt\kraken ()); // PHP
API URLs are often grouped into two sets of methods called apublic API for market data and aprivate 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
The private API is mostly used for trading and for accessing account-specific private data, therefore it requires authentication. You have to get the private API keys from the exchanges. It often means registering with an exchange website and creating the API keys for your account. Most exchanges require personal information or identification. Some exchanges will only allow trading after completing the KYC verification.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 calledmarket 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 calledtrading,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 calledmerchant,wallet,payment,ecapi (for e-commerce).
To get a list of all available methods with an exchange instance, you can simply do the following:
console.log (new ccxt.kraken ()) // JavaScriptprint(dir(ccxt.kraken())) # Pythonvar_dump (new \ccxt\kraken ()); // PHP
contract only and margin only
- methods in this documentation that are documented ascontract only ormargin only are only intended to be used for contract trading and margin trading respectively. They may work when trading in other types of markets but will most likely return irrelevant information.
In the JavaScript version of CCXT all methods are asynchronous and returnPromises that resolve with a decoded JSON object. In CCXT we use the modernasync/await syntax to work with Promises. If you're not familiar with that syntax, you can read more about ithere.
// JavaScript(async()=>{letpairs=awaitkraken.publicGetSymbolsDetails()letmarketIds=Object.keys(pairs['result'])letmarketId=marketIds[0]letticker=awaitkraken.publicGetTicker({pair:marketId})console.log(kraken.id,marketId,ticker)})()
The ccxt library supports asynchronous concurrency mode in Python 3.5+ with async/await syntax. The asynchronous Python version uses pureasyncio withaiohttp. 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 theccxt.async_support
subpackage, like in the following example:
# Pythonimportasyncioimportccxt.async_supportasccxtasyncdefprint_poloniex_ethbtc_ticker():poloniex=ccxt.poloniex()print(awaitpoloniex.fetch_ticker('ETH/BTC'))awaitpolonix.close()# close the exchange instance when you don't need it anymoreasyncio.run(print_poloniex_ethbtc_ticker())
CCXT support PHP 8+ versions. The library has both synchronous and asynchronous versions. To use synchronous version, use\ccxt
namespace (i.e.new ccxt\binance()
) and to use asynchronous version, use\ccxt\async
namespace (i.e.new ccxt\async\binance()
). Asynchronous version usesReactPHP library in the background. In async mode you have all the same properties and methods, but any networking API method should be decorated with the\React\Async\await
keyword and your script should be in a ReactPHP wrapper:
// PHP<?phpinclude'vendor/autoload.php';usefunctionReact\Async\await;$okx =new \ccxt\async\okx();while (true) {$result =await($okx->fetch_ticker('ETH/BTC'));var_dump($result);}
See further examples in theexamples/php
directory; look for filenames that include theasync
word. Also, make sure you have installed the required dependencies usingcomposer require recoil/recoil clue/buzz-react react/event-loop recoil/react react/http
. Lastly,this article provides a good introduction to the methods used here. While syntactically the change is simple (i.e., just using ayield
keyword before relevant methods), concurrency has significant implications for the overall design of your code.
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.
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:
bitso.publicGetTicker ({ book: 'eth_mxn' }) // JavaScriptccxt.zaif().public_get_ticker_pair ({ 'pair': 'btc_jpy' }) # Python$luno->public_get_ticker (array ('pair' => 'XBTIDR')); // PHP
The unified methods of exchanges might expect and will accept variousparams
which affect their functionality, like:
params= {'type':'margin','isIsolated':'TRUE'}# --------------┑# params will go as the last argument to the unified method |# vbinance.create_order('BTC/USDT','limit','buy',amount,price,params)
An exchange will not accept the params from a different exchange, they're not interchangeable. The list of accepted parameters is defined by each specific exchange.
To find which parameters can be passed to a unified method:
- either open theexchange-specific implementation file and search for the desired function (i.e.
createOrder
) to inspect and find out the details ofparams
usage - or go to the exchange's API docs and read the list of parameters for your specific function or endpoint (i.e.
order
)
For a full list of accepted method parameters for each exchange, please consultAPI docs.
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:
Method Name | Base API URL | Endpoint URL |
---|---|---|
publicGetIdOrderbook | https://bitbay.net/API/Public | {id}/orderbook |
publicGetPairs | https://bitlish.com/api | pairs |
publicGetJsonMarketTicker | https://www.bitmarket.net | json/{market}/ticker |
privateGetUserMargin | https://bitmex.com | user/margin |
privatePostTrade | https://btc-x.is/api | trade |
tapiCancelOrder | https://yobit.net | tapi/CancelOrder |
... | ... | ... |
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:
exchange.methodName () // camelcase pseudocodeexchange.method_name() // underscore pseudocode
To get a list of all available methods with an exchange instance, you can simply do the following:
console.log (new ccxt.kraken ()) // JavaScriptprint(dir(ccxt.hitbtc())) # Pythonvar_dump (new \ccxt\okcoin ()); // PHP
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 array of markets (objects with properties such assymbol
,base
,quote
etc.). Some exchanges do not have means for obtaining a list of markets via their online API. For those, the list of markets is hardcoded.fetchCurrencies ()
: Fetches all available currencies an exchange and returns an associative dictionary of currencies (objects with properties such ascode
,name
, etc.). Some exchanges do not have means for obtaining currencies via their online API. For those, the currencies will be extracted from market pairs or hardcoded.loadMarkets ([reload])
: Returns the list of markets as an object indexed by symbol and caches it with the exchange instance. Returns cached markets if loaded already, unless thereload = true
flag is forced.fetchOrderBook (symbol, limit = undefined, params = {})
: Fetch L2/L3 order book for a particular market trading symbol.fetchStatus (params = {})
: Returns information regarding the exchange status from either the info hardcoded in the exchange instance or the API, if available.fetchL2OrderBook (symbol, limit = undefined, params)
: Level 2 (price-aggregated) order book for a particular symbol.fetchTrades (symbol, since, limit, 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)
createOrders(orders, params)
createLimitBuyOrder (symbol, amount, price, param)
createLimitSellOrder (symbol, amount, price, param)
createMarketBuyOrder (symbol, amount, param)
createMarketSellOrder (symbol, amount, param)
cancelOrder (id, symbol, params)
fetchOrder (id, symbol, params)
fetchOrders (symbol, since, limit, params)
fetchOpenOrders (symbol, since, limit, params)
fetchCanceledOrders (symbol, since, limit, params)
fetchClosedOrders (symbol, since, limit, params)
fetchMyTrades (symbol, since, limit, params)
fetchOpenInterest (symbol, params)
fetchVolatilityHistory (code, params)
fetchUnderlyingAssets ()
fetchSettlementHistory (symbol, since, limit, params)
fetchLiquidations (symbol, since, limit, params)
fetchMyLiquidations (symbol, since, limit, params)
fetchGreeks (symbol, params)
fetchAllGreeks (symbols, params)
fetchCrossBorrowRate (code, params)
fetchCrossBorrowRates (params)
fetchIsolatedBorrowRate (symbol, params)
fetchIsolatedBorrowRates (params)
fetchOption (symbol, params)
fetchOptionChain (code, params)
fetchConvertQuote (fromCode, toCode, amount, params)
createConvertTrade (id, fromCode, toCode, amount, params)
fetchFundingRate (symbol, params)
fetchFundingRates (symbols, params)
fetchFundingRateHistory (symbol, since, limit, params)
fetchFundingRateInterval (symbol, params)
fetchFundingRateIntervals (symbols, params)
fetchLongShortRatio (symbol, params)
- ...
TODO: better formatting
Note, that most of methods of the unified API accept an optionalparams
argument. It is an associative array (a dictionary, empty by default) containing the params you want to override. The contents ofparams
are exchange-specific, consult the exchanges' API documentation for supported fields and values. Use theparams
dictionary if you need to pass a custom setting or an optional parameter to your unified query.
(async()=>{constparams={'foo':'bar',// exchange-specific overrides in unified queries'Hello':'World!',// see their docs for more details on parameter names}// the overrides go into the last argument to the unified call ↓ HEREconstresult=awaitexchange.fetchOrderBook(symbol,length,params)})()
params= {'foo':'bar',# exchange-specific overrides in unified queries'Hello':'World!',# see their docs for more details on parameter names}# overrides go in the last argument to the unified call ↓ HEREresult=exchange.fetch_order_book(symbol,length,params)
$params = array ('foo' =>'bar',// exchange-specific overrides in unified queries'Hello' =>'World!',// see their docs for more details on parameter names}// overrides go into the last argument to the unified call ↓ HERE$result =$exchange->fetch_order_book ($symbol,$length,$params);
Most of unified methods will return either a single object or a plain array (a list) of objects (trades, orders, transactions and so on). However, very few exchanges (if any at all) will return all orders, all trades, all ohlcv candles or all transactions at once. Most often their APIslimit
output to a certain number of most recent objects.YOU CANNOT GET ALL OBJECTS SINCE THE BEGINNING OF TIME TO THE PRESENT MOMENT IN JUST ONE CALL. Practically, very few exchanges will tolerate or allow that.
To fetch historical orders or trades, the user will need to traverse the data in portions or "pages" of objects. Pagination often implies"fetching portions of data one by one" in a loop.
In most cases users arerequired to use at least some type of pagination in order to get the expected results consistently. If the user does not apply any pagination, most methods will return the exchanges' default, which may start from the beginning of history or may be a subset of most recent objects. The default behaviour (without pagination) is exchange-specific! The means of pagination are often used with the following methods in particular:
fetchTrades()
fetchOHLCV()
fetchOrders()
fetchCanceledOrders()
fetchClosedOrder()
fetchClosedOrders()
fetchOpenOrder()
fetchOpenOrders()
fetchMyTrades()
fetchTransactions()
fetchDeposit()
fetchDeposits()
fetchWithdrawals()
With methods returning lists of objects, exchanges may offer one or more types of pagination. CCXT unifiesdate-based pagination by default, with timestampsin milliseconds throughout the entire library.
Warning: this is an experimental feature and might produce unexpected/incorrect results in some instances.
Recently, CCXT introduced a way to paginate through several results automatically by just providing thepaginate
flag insideparams,
lifting this work from the userland. Most leading exchanges support it, and more will be added in the future, but the easiest way to check it is to look in the method's documentation and search for thepagination parameter. As always there are exceptions, and some endpoints might not provide a way to paginate either through a timestamp or a cursor, and in those cases, there's nothing CCXT can do about it.
Right now, we have three different ways of paginating:
- dynamic/time-based: uses the
until
andsince
parameters to paginate through dynamic results like (trades, orders, transactions, etc). Since we don't know a priori how many entries are available to be fetched, it will perform one request at a time until we reach the end of the data or the maximum amount of pagination calls (configurable through an option) - deterministic: when we can pre-compute the boundaries of each page, it will perform the requests concurrently for maximum performance. This applies to OHLCV, Funding Rates, and Open Interest and also respects the
paginationCalls
option. - cursor-based: when the exchange provides a cursor inside the response, we extract the cursor and perform the subsequent request until the end of the data or reach the maximum number of pagination calls.
The user cannot select the pagination method used, it will depend from implementation to implementation, considering the exchange API's features.
We can't perform an infinite amount of requests, and some of them might throw an error for different reasons, thus, we have some options that allow the user to control these variables and other pagination specificities.
All the options below, should be provided insideparams
, you can check the examples below
- paginate: (boolean) indicates that the user wants to paginate through different pages to get more data. Default isfalse.
- paginationCalls: (integer) allows the user to control the maximum amount of requests to paginate the data. Due to the rate limits, this value should not be too high. Default is 10.
- maxRetries: (integer) how many times should the pagination mechanism retry upon getting an error. Default is 3
- paginationDirection: (string) Only applies to the dynamic pagination and it can be eitherforward (start the pagination from some time in the past and paginate forward) orbackward (start from the most recent time and paginate backward). Ifforward is selected then asince parameter must also be provided. Default isbackward.
- maxEntriesPerRequest: (integer): The max amount of entries per request so that we can maximize the data retrieved per call. It varies from endpoint to endpoint and CCXT will populate this value for you, but you can override it if needed.
trades=awaitbinance.fetch_trades("BTC/USDT",params= {"paginate":True})# dynamic/time-basedohlcv=awaitbinance.fetch_ohlcv("BTC/USDT",params= {"paginate":True,"paginationCalls":5})# deterministic-pagination will perform 5 requeststrades=awaitbinance.fetch_trades("BTC/USDT",since=1664812416000,params= {"paginate":True,"paginationDirection":"forward"})# dynamic/time-based pagination starting from 1664812416000ledger=awaitbybit.fetch_ledger(params= {"paginate":True})# bybit returns a cursor so the pagination will be cursor-basedfunding_rates=awaitbinance.fetch_funding_rate_history("BTC/USDT:USDT",params= {"paginate":True,"maxEntriesPerRequest":50})# customizes the number of entries per request
All unified timestamps throughout the CCXT library are integersin milliseconds unless explicitly stated otherwise.
Below is the set of methods for working with UTC dates and timestamps and for converting between them:
exchange.parse8601('2018-01-01T00:00:00Z')==1514764800000// integer in milliseconds, Z = UTCexchange.iso8601(1514764800000)=='2018-01-01T00:00:00Z'// from milliseconds to iso8601 stringexchange.seconds()// integer UTC timestamp in secondsexchange.milliseconds()// integer UTC timestamp in milliseconds
This is the type of pagination currently used throughout the CCXT Unified API. The user supplies asince
timestampin milliseconds (!) and a number tolimit
results. To traverse the objects of interest page by page, the user runs the following (below is pseudocode, it may require overriding some exchange-specific params, depending on the exchange in question):
if(exchange.has['fetchTrades']){letsince=exchange.milliseconds()-86400000// -1 day from now// alternatively, fetch from a certain starting datetime// let since = exchange.parse8601 ('2018-01-01T00:00:00Z')letallTrades=[]while(since<exchange.milliseconds()){constsymbol=undefined// change for your symbolconstlimit=20// change for your limitconsttrades=awaitexchange.fetchTrades(symbol,since,limit)if(trades.length){since=trades[trades.length-1]['timestamp']+1allTrades=allTrades.concat(trades)}else{break}}}
ifexchange.has['fetchOrders']:since=exchange.milliseconds ()-86400000# -1 day from now# alternatively, fetch from a certain starting datetime# since = exchange.parse8601('2018-01-01T00:00:00Z')all_orders= []whilesince<exchange.milliseconds ():symbol=None# change for your symbollimit=20# change for your limitorders=awaitexchange.fetch_orders(symbol,since,limit)iflen(orders):since=orders[len(orders)-1]['timestamp']+1all_orders+=orderselse:break
if ($exchange->has['fetchMyTrades']) {$since = exchange->milliseconds () -86400000;// -1 day from now// alternatively, fetch from a certain starting datetime// $since = $exchange->parse8601 ('2018-01-01T00:00:00Z');$all_trades =array ();while (since < exchange->milliseconds ()) {$symbol =null;// change for your symbol$limit =20;// change for your limit$trades =$exchange->fetchMyTrades ($symbol,$since,$limit);if (count($trades)) {$since =$trades[count($trades) -1]['timestamp'] +1;$all_trades =array_merge ($all_trades,$trades); }else {break; } }}
The user supplies afrom_id
of the object, from where the query should continue returning results, and a number tolimit
results. This is the default with some exchanges, however, this type is not unified (yet). To paginate objects based on their ids, the user would run the following:
if(exchange.has['fetchTrades']){letfrom_id='abc123'// all ids are stringsletallTrades=[]while(true){constsymbol=undefined// change for your symbolconstsince=undefinedconstlimit=20// change for your limitconstparams={'from_id':from_id,// exchange-specific non-unified parameter name}consttrades=awaitexchange.fetchTrades(symbol,since,limit,params)if(trades.length){from_id=trades[trades.length-1]['id']allTrades.push(trades)}else{break}}}
ifexchange.has['fetchOrders']:from_id='abc123'# all ids are stringsall_orders= []whileTrue:symbol=None# change for your symbolsince=Nonelimit=20# change for your limitparams= {'from_id':from_id,# exchange-specific non-unified parameter name }orders=awaitexchange.fetch_orders(symbol,since,limit,params)iflen(orders):from_id=orders[len(orders)-1]['id']all_orders+=orderselse:break
if ($exchange->has['fetchMyTrades']) {$from_id ='abc123'// all ids are strings$all_trades =array ();while (true) {$symbol =null;// change for your symbol$since =null;$limit =20;// change for your limit$params =array ('from_id' =>$from_id,// exchange-specific non-unified parameter name );$trades =$exchange->fetchMyTrades ($symbol,$since,$limit,$params);if (count($trades)) {$from_id =$trades[count($trades) -1]['id'];$all_trades =array_merge ($all_trades,$trades); }else {break; } }}
The user supplies a page number or aninitial "cursor" value. The exchange returns a page of results and thenext "cursor" value, to proceed from. Most of exchanges that implement this type of pagination will either return the next cursor within the response itself or will return the next cursor values within HTTP response headers.
See an example implementation here:https://github.com/ccxt/ccxt/blob/master/examples/py/coinbasepro-fetch-my-trades-pagination.py
Upon each iteration of the loop the user has to take the next cursor and put it into the overrided params for the next query (on the following iteration):
if(exchange.has['fetchTrades']){letpage=0// exchange-specific type and valueletallTrades=[]while(true){constsymbol=undefined// change for your symbolconstsince=undefinedconstlimit=20// change for your limitconstparams={'page':page,// exchange-specific non-unified parameter name}consttrades=awaitexchange.fetchTrades(symbol,since,limit,params)if(trades.length){// not thread-safu and exchange-specific !last_json_response=exchange.parseJson(exchange.last_http_response)page=last_json_response['cursor']allTrades.push(trades)}else{break}}}
ifexchange.has['fetchOrders']:cursor=0# exchange-specific type and valueall_orders= []whileTrue:symbol=None# change for your symbolsince=Nonelimit=20# change for your limitparams= {'cursor':cursor,# exchange-specific non-unified parameter name }orders=awaitexchange.fetch_orders(symbol,since,limit,params)iflen(orders):# not thread-safu and exchange-specific !cursor=exchange.last_response_headers['CB-AFTER']all_orders+=orderselse:break
if ($exchange->has['fetchMyTrades']) {$start ='0'// exchange-specific type and value$all_trades =array ();while (true) {$symbol =null;// change for your symbol$since =null;$limit =20;// change for your limit$params =array ('start' =>$start,// exchange-specific non-unified parameter name );$trades =$exchange->fetchMyTrades ($symbol,$since,$limit,$params);if (count($trades)) {// not thread-safu and exchange-specific !$last_json_response =$exchange->parse_json ($exchange->last_http_response);$start =$last_json_response['next'];$all_trades =array_merge ($all_trades,$trades); }else {break; } }}
- Order Book
- Price Tickers
- OHLCV Candlestick Charts
- Public Trades
- Exchange Time
- Exchange Status
- Borrow Rates
- Borrow Rate History
- Leverage Tiers
- Funding Rate
- Funding Rate History
- Open Interest History
- Volatility History
- Underlying Assets
- Liquidations
- Greeks
- OptionChain
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 theorder book for a particular market. An order book is also often calledmarket depth. The order book information is used in the trading decision making process.
To get data on order books, you can use
fetchOrderBook ()
// for a single markets order booksfetchOrderBooks ( symbols )
// for multiple markets order booksfetchOrderBooks ()
// for the order books of all markets
asyncfetchOrderBook(symbol,limit=undefined,params={})
Parameters
- symbol (String)required Unified CCXT symbol (e.g.
"BTC/USDT"
) - limit (Integer) The number of orders to return in the order book (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
asyncfetchOrderBooks(symbols=undefined,limit=undefined,params={})
Parameters
- symbols ([String]) Unified CCXT symbols (e.g.
["BTC/USDT", "ETH/USDT"]
) - limit (Integer) The number of orders to return in the order book (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- A dictionary oforder book structures indexed by market symbols
delay=2000// milliseconds = seconds * 1000(async()=>{for(symbolinexchange.markets){console.log(awaitexchange.fetchOrderBook(symbol))awaitnewPromise(resolve=>setTimeout(resolve,delay))// rate limit}})()
importtimedelay=2# secondsforsymbolinexchange.markets:print (exchange.fetch_order_book (symbol))time.sleep (delay)# rate limit
$delay =2000000;// microseconds = seconds * 1000000foreach ($exchange->marketsas$symbol =>$market) {var_dump ($exchange->fetch_order_book ($symbol));usleep ($delay);// rate limit}
{'bids':[[price,amount],// [ float, float ][price,amount], ...],'asks':[[price,amount],[price,amount], ...],'symbol':'ETH/BTC',// a unified market symbol'timestamp':1499280391811,// Unix Timestamp in milliseconds (seconds * 1000)'datetime':'2017-07-05T18:47:14.692Z',// ISO8601 datetime string with milliseconds'nonce':1499280391811,// an increasing unique identifier of the orderbook snapshot}
The timestamp and datetime may be missing (undefined/None/null
) if the exchange in question does not provide a corresponding value in the API response.
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.
- The
orderbook['timestamp']
is the time when the exchange generated this orderbook response (before replying it back to you). This may be missing (undefined/None/null
), as documented in the Manual, not all exchanges provide a timestamp there. If it is defined, then it is the UTC timestampin milliseconds since 1 Jan 1970 00:00:00. - Some exchanges may index orders in the orderbook by order ids, in that case the order id may be returned as the third element of bids and asks:
[ price, amount, id ]
. This is often the case with L3 orderbooks without aggregation. The orderid
, if shown in the orderbook, refers to the orderbook and does not necessarily correspond to the actual order id from the exchanges' database as seen by the owner or by the others. The order id is anid
of the row inside the orderbook, but not necessarily the true-id
of the order (though, they may be equal as well, depending on the exchange in question). - In some cases the exchanges may supply L2 aggregated orderbooks with order counts for each aggregated level, in that case the order count may be returned as the third element of bids and asks:
[ price, amount, count ]
. Thecount
tells how many orders are aggregated on each price level in bids and asks. - Also, some exchanges may return the order timestamp as the third element of bids and asks:
[ price, amount, timestamp ]
. Thetimestamp
tells when the order was placed on the orderbook.
Some exchanges accept a dictionary of extra parameters to thefetchOrderBook () / fetch_order_book ()
function.All extraparams
are exchange-specific (non-unified). You will need to consult exchanges docs if you want to override a particular param, like the depth of the order book. You can get a limited count of returned orders or a desired level of aggregation (akamarket depth) by specifying an limit argument and exchange-specific extraparams
like so:
(asyncfunctiontest(){constccxt=require('ccxt')constexchange=newccxt.bitfinex()constlimit=5constorders=awaitexchange.fetchOrderBook('BTC/USD',limit,{// this parameter is exchange-specific, all extra params have unique names per exchange'group':1,// 1 = orders are grouped by price, 0 = orders are separate})})()
importccxt# return up to ten bidasks on each side of the order book stacklimit=10ccxt.cex().fetch_order_book('BTC/USD',limit)
// instantiate the exchange by id$exchange ='\\ccxt\\kraken';$exchange =new$exchange ();// up to ten orders on each side, for example$limit =20;var_dump ($exchange->fetch_order_book ('BTC/USD',$limit));
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 arenot 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 thefetchL2OrderBook(symbol, limit, params)
orfetch_l2_order_book(symbol, limit, params)
unified method for that.
Thelimit
argument does not guarantee that the number of bids or asks will always be equal tolimit
. It designates the upper boundary or the maximum, so at some moment in time there may be less thanlimit
bids or asks. This is the case when the exchange does not have enough orders on the orderbook. However, if the underlying exchange API does not support alimit
parameter for the orderbook endpoint at all, then thelimit
argument will be ignored. CCXT does not trimbids
andasks
if the exchange returns more than you request.
In order to get current best price (query market price) and calculate bidask spread take first elements from bid and ask, like so:
letorderbook=awaitexchange.fetchOrderBook(exchange.symbols[0])letbid=orderbook.bids.length ?orderbook.bids[0][0] :undefinedletask=orderbook.asks.length ?orderbook.asks[0][0] :undefinedletspread=(bid&&ask) ?ask-bid :undefinedconsole.log(exchange.id,'market price',{ bid, ask, spread})
orderbook=exchange.fetch_order_book (exchange.symbols[0])bid=orderbook['bids'][0][0]iflen (orderbook['bids'])>0elseNoneask=orderbook['asks'][0][0]iflen (orderbook['asks'])>0elseNonespread= (ask-bid)if (bidandask)elseNoneprint (exchange.id,'market price', {'bid':bid,'ask':ask,'spread':spread })
$orderbook =$exchange->fetch_order_book ($exchange->symbols[0]);$bid =count ($orderbook['bids']) ?$orderbook['bids'][0][0] :null;$ask =count ($orderbook['asks']) ?$orderbook['asks'][0][0] :null;$spread = ($bid &&$ask) ?$ask -$bid :null;$result =array ('bid' =>$bid,'ask' =>$ask,'spread' =>$spread);var_dump ($exchange->id,'market price',$result);
A price ticker contains statistics for a particular market/symbol for some period of time in recent past, usually last 24 hours. The methods for fetching tickers are described below.
// one tickerfetchTicker(symbol,params={})// examplefetchTicker('ETH/BTC')fetchTicker('BTC/USDT')
// multiple tickersfetchTickers(symbols=undefined,params={})// for all tickers at once// for examplefetchTickers()// all symbolsfetchTickers(['ETH/BTC','BTC/USDT'])// an array of specific symbols
Check theexchange.has['fetchTicker']
andexchange.has['fetchTickers']
properties of the exchange instance to determine if the exchange in question does support these methods.
Please, note, that callingfetchTickers ()
without a symbol is usually strictly rate-limited, an exchange may ban you if you poll that endpoint too frequently.
A ticker is a statistical calculation with the information calculated over the past 24 hours for a specific market.
The structure of a ticker is as follows:
{'symbol':stringsymbolofthemarket('BTC/USD','ETH/BTC', ...)'info':{theoriginalnon-modifiedunparsedreplyfromexchangeAPI},'timestamp':int(64-bitUnixTimestampinmillisecondssinceEpoch1Jan1970)'datetime':ISO8601datetimestringwithmilliseconds'high':float,// highest price'low':float,// lowest price'bid':float,// current best bid (buy) price'bidVolume':float,// current best bid (buy) amount (may be missing or undefined)'ask':float,// current best ask (sell) price'askVolume':float,// current best ask (sell) amount (may be missing or undefined)'vwap':float,// volume weighed average price'open':float,// opening price'close':float,// price of last trade (closing price for current period)'last':float,// same as `close`, duplicated for convenience'previousClose':float,// closing price for the previous period'change':float,// absolute change, `last - open`'percentage':float,// relative change, `(change/open) * 100`'average':float,// average price, `(last + open) / 2`'baseVolume':float,// volume of base currency traded for last 24 hours'quoteVolume':float,// volume of quote currency traded for last 24 hours}
- All fields in the ticker represent the past 24 hours prior to
timestamp
. - The
bidVolume
is the volume (amount) of current best bid in the orderbook. - The
askVolume
is the volume (amount) of current best ask in the orderbook. - The
baseVolume
is the amount of base currency traded (bought or sold) in last 24 hours. - The
quoteVolume
is the amount of quote currency traded (bought or sold) in last 24 hours.
All prices in ticker structure are in quote currency. Some fields in a returned ticker structure may be undefined/None/null.
base currency ↓ BTC / USDT ETH / BTC DASH / ETH ↑ quote currency
Timestamp and datetime are both Universal Time Coordinated (UTC) in milliseconds.
ticker['timestamp']
is the time when the exchange generated this response (before replying it back to you). It may be missing (undefined/None/null
), as documented in the Manual, not all exchanges provide a timestamp there. If it is defined, then it is a UTC timestampin milliseconds since 1 Jan 1970 00:00:00.exchange.last_response_headers['Date']
is the date-time string of the last HTTP response received (from HTTP headers). The 'Date' parser should respect the timezone designated there. The precision of the date-time is 1 second, 1000 milliseconds. This date should be set by the exchange server when the message originated according to the following standards:
Although some exchanges do mix-in orderbook's top bid/ask prices into their tickers (and some exchanges even serve top bid/ask volumes) you should not treat a ticker as afetchOrderBook
replacement. The main purpose of a ticker is to serve statistical data, as such, treat it as "live 24h OHLCV". It is known that exchanges discourage frequentfetchTicker
requests by imposing stricter rate limits on these queries. If you need a unified way to access bids and asks you should usefetchL[123]OrderBook
family instead.
To get historical prices and volumes use the unifiedfetchOHLCV
method where available. To get historical mark, index, and premium index prices, add one of'price': 'mark'
,'price': 'index'
,'price': 'premiumIndex'
respectively to theparams-overrides offetchOHLCV
. There are also convenience methodsfetchMarkPriceOHLCV
,fetchIndexPriceOHLCV
, andfetchPremiumIndexOHLCV
that obtain the mark, index and premiumIndex historical prices and volumes.
Methods for fetching tickers:
fetchTicker (symbol[, params = {}])
, symbol is required, params are optionalfetchTickers ([symbols = undefined[, params = {}]])
, both arguments optional
To get the individual ticker data from an exchange for a particular trading pair or a specific symbol – call thefetchTicker (symbol)
:
if(exchange.has['fetchTicker']){console.log(await(exchange.fetchTicker('BTC/USD')))// ticker for BTC/USDletsymbols=Object.keys(exchange.markets)letrandom=Math.floor(Math.random()*(symbols.length-1))console.log(exchange.fetchTicker(symbols[random]))// ticker for a random symbol}
importrandomif (exchange.has['fetchTicker']):print(exchange.fetch_ticker('LTC/ZEC'))# ticker for LTC/ZECsymbols=list(exchange.markets.keys())print(exchange.fetch_ticker(random.choice(symbols)))# ticker for a random symbol
//(don't forget to set your timezone properly!)if ($exchange->has['fetchTicker']) {var_dump ($exchange->fetch_ticker ('ETH/CNY'));// ticker for ETH/CNY$symbols =array_keys ($exchange->markets);$random =rand () %count ($symbols);var_dump ($exchange->fetch_ticker ($symbols[$random]));// ticker for a random symbol}
Some exchanges (not all of them) also support fetching all tickers at once. Seetheir docs for details. You can fetch all tickers with a single call like so:
if(exchange.has['fetchTickers']){console.log(await(exchange.fetchTickers()))// all tickers indexed by their symbols}
if (exchange.has['fetchTickers']):print(exchange.fetch_tickers())# all tickers indexed by their symbols
if ($exchange->has['fetchTickers']) {var_dump ($exchange->fetch_tickers ());// all tickers indexed by their symbols}
Fetching all tickers requires more traffic than fetching a single ticker. Also, note that some exchanges impose higher rate-limits on subsequent fetches of all tickers (see their docs on corresponding endpoints for details).The cost of thefetchTickers()
call in terms of rate limit is often higher than average. If you only need one ticker, fetching by a particular symbol is faster as well. You probably want to fetch all tickers only if you really need all of them and, most likely, you don't want to fetchTickers more frequently than once in a minute or so.
Also, some exchanges may impose additional requirements on thefetchTickers()
call, sometimes you can't fetch the tickers for all symbols because of the API limitations of the exchange in question. Some exchanges accept a list of symbols in HTTP URL query params, however, because URL length is limited, and in extreme cases exchanges can have thousands of markets – a list of all their symbols simply would not fit in the URL, so it has to be a limited subset of their symbols. Sometimes, there are other reasons for requiring a list of symbols, and there may be a limit on the number of symbols you can fetch at once, but whatever the limitation, please, blame the exchange. To pass the symbols of interest to the exchange, you can supply a list of strings as the first argument to fetchTickers:
//JavaScriptif(exchange.has['fetchTickers']){console.log(await(exchange.fetchTickers(['ETH/BTC','LTC/BTC'])))// listed tickers indexed by their symbols}
if (exchange.has['fetchTickers']):print(exchange.fetch_tickers(['ETH/BTC','LTC/BTC']))# listed tickers indexed by their symbols
if ($exchange->has['fetchTickers']) {var_dump ($exchange->fetch_tickers (array ('ETH/BTC','LTC/BTC')));// listed tickers indexed by their symbols}
Note that the list of symbols is not required in most cases, but you must add additional logic if you want to handle all possible limitations that might be imposed on the exchanges' side.
Like most methods of the Unified CCXT API, the last argument to fetchTickers is theparams
argument for overriding request parameters that are sent towards the exchange.
The structure of the returned value is as follows:
{'info':{ ...},// the original JSON response from the exchange as is'BTC/USD':{ ...},// a single ticker for BTC/USD'ETH/BTC':{ ...},// a ticker for ETH/BTC ...}
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.
UNDER CONSTRUCTION
Most exchanges have endpoints for fetching OHLCV data, but some of them don't. The exchange boolean (true/false) property namedhas['fetchOHLCV']
indicates whether the exchange supports candlestick data series or not.
To fetch OHLCV candles/bars from an exchange, ccxt has thefetchOHLCV
method, which is declared in the following way:
fetchOHLCV(symbol,timeframe='1m',since=undefined,limit=undefined,params={})
You can call the unifiedfetchOHLCV
/fetch_ohlcv
method to get the list of OHLCV candles for a particular symbol like so:
letsleep=(ms)=>newPromise(resolve=>setTimeout(resolve,ms));if(exchange.has.fetchOHLCV){for(symbolinexchange.markets){awaitsleep(exchange.rateLimit)// millisecondsconsole.log(awaitexchange.fetchOHLCV(symbol,'1m'))// one minute}}
importtimeifexchange.has['fetchOHLCV']:forsymbolinexchange.markets:time.sleep (exchange.rateLimit/1000)# time.sleep wants secondsprint (symbol,exchange.fetch_ohlcv (symbol,'1d'))# one day
if ($exchange->has['fetchOHLCV']) {foreach ($exchange->marketsas$symbol =>$market) {usleep ($exchange->rateLimit *1000);// usleep wants microsecondsvar_dump ($exchange->fetch_ohlcv ($symbol,'1M'));// one month }}
To get the list of available timeframes for your exchange see thetimeframes
property. Note that it is only populated whenhas['fetchOHLCV']
is true as well.
The returned list of candles may have one or more missing periods, if the exchange did not have any trades for the specified timerange and symbol. To a user that would appear as gaps in a continuous list of candles. That is considered normal. If the exchange did not have any candles at that time, the CCXT library will show the results as returned from the exchange itself.
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 (akaREST polling) latest OHLCVs and storing them in a CSV file or in a database.
Note that the info from the last (current) candle may be incomplete until the candle is closed (until the next candle starts).
Like with most other unified and implicit methods, thefetchOHLCV
method accepts as its last argument an associative array (a dictionary) of extraparams
, which is used tooverride default values that are sent in requests to the exchanges. The contents ofparams
are exchange-specific, consult the exchanges' API documentation for supported fields and values.
Thesince
argument is an integer UTC timestampin milliseconds (everywhere throughout the library with all unified methods).
Ifsince
is not specified thefetchOHLCV
method will return the time range as is the default from the exchange itself. This is not a bug. Some exchanges will return candles from the beginning of time, others will return most recent candles only, the exchanges' default behaviour is expected. Thus, without specifyingsince
the range of returned candles will be exchange-specific. One should pass thesince
argument to ensure getting precisely the history range needed.
Currently, the structure CCXT uses does not include the raw response from the exchange. However, users might be able to override the return value by doing:
constex=newccxt.coinbase();constoriginalParser=ex.parseOHLCV.bind(ex);ex.parseOHLCV=((ohlcv,market=undefined)=>{return{'result':originalParser(ohlcv,market),'raw':ohlcv,};});constresult=awaitex.fetchOHLCV('BTC/USDT','1m');console.log(result[0]);
# add raw member at last position in listasyncdeftest():ex=ccxt.async_support.coinbase()prase_ohlcv_original=ex.parse_ohlcvdefprase_ohlcv_custom(ohlcv,market):res=prase_ohlcv_original(ohlcv,market)res.append(ohlcv)returnresex.parse_ohlcv=prase_ohlcv_customresult=awaitex.fetch_ohlcv('BTC/USDT','1m')print (result[0])asyncio.run(test())
Trading strategies require fresh up-to-date information for technical analysis, indicators and signals. Building a speculative trading strategy based on the OHLCV candles received from the exchange may have critical drawbacks. Developers should account for the details explained in this section to build successful bots.
First and foremost, when using CCXT you're talking to the exchanges directly. CCXT is not a server, nor a service, it's a software library. All data that you are getting with CCXT is received directly from the exchanges first-hand.
The exchanges usually provide two categories of public market data:
- Fast primary first-order data that includes real time orderbooks and trades or fills
- Slow second-order data that includes secondary tickers and kline OHLCV candles, that are calculated from the first-order data
The primary first-order data is updated by the exchanges APIs in pseudo real time, or as close to real time as possible, as fast as possible. The second-order data requires time for the exchange to calculate it. For example, a ticker is nothing more than a rolling 24-hour statistical cut of orderbooks and trades. OHLCV candles and volumes are also calculated from first-order trades and represent fixed statistical cuts of specific periods. The volume traded within an hour is just a sum of traded volumes of the corresponding trades that happened within that hour.
Obviously, it takes some time for the exchange to collect the first-order data and calculate the secondary statistical data from it. That literally means thattickers and OHLCVs are always slower than orderbooks and trades. In other words, there is always some latency in the exchange API between the moment when a trade happens and the moment when a corresponding OHLCV candle is updated or published by the exchange API.
The latency (or how much time is needed by the exchange API for calculating the secondary data) depends on how fast the exchange engine is, so it is exchange-specific. Top exchange engines will usually return and update fresh last-minute OHLCV candles and tickers at a very fast rate. Some exchanges might do it in regular intervals like once a second or once in a few seconds. Slow exchange engines might take minutes to update the secondary statistical information, their APIs might return the current most recent OHLCV candle a few minutes late.
If your strategy depends on the fresh last-minute most recent data you don't want to build it based on tickers or OHLCVs received from the exchange. Tickers and exchanges' OHLCVs are only suitable for display purposes, or for simple trading strategies for hour-timeframes or day-timeframes that are less susceptible to latency.
Thankfully, the developers of time-critical trading strategies don't have to rely on secondary data from the exchanges and can calculate the OHLCVs and tickers in the userland. That may be faster and more efficient than waiting for the exchanges to update the info on their end. One can aggregate the public trade history by polling it frequently and calculate candles by walking over the list of trades - please take a look into "build-ohlcv-bars" file insideexamples folder
Due to the differences in their internal implementations the exchanges may be faster to update their primary and secondary market data over WebSockets. The latency remains exchange-specific, cause the exchange engine still needs time to calculate the secondary data, regardless of whether you're polling it over the RESTful API with CCXT or getting updates via WebSockets with CCXT Pro. WebSockets can improve the networking latency, so a fast exchange will work even better, but adding the support for WS subscriptions will not make a slow exchange engine work much faster.
If you want to stay on top of the second-order data latency, then you will have to calculate it on your side and beat the exchange engine in speed of doing so. Depending on the needs of your application, it may be tricky, since you will need to handle redundancy, "data holes" in the history, exchange downtimes, and other aspects of data aggregation which is a whole universe in itself that is impossible to fully cover in this Manual.
The fetchOHLCV method shown above returns a list (a flat array) of OHLCV candles represented by the following structure:
[[1504541580000,// UTC timestamp in milliseconds, integer4235.4,// (O)pen price, float4240.6,// (H)ighest price, float4230.0,// (L)owest price, float4230.7,// (C)losing price, float37.72941911// (V)olume float (usually in terms of the base currency, the exchanges docstring may list whether quote or base units are used)], ...]
The list of candles is returned sorted in ascending (historical/chronological) order, oldest candle first, most recent candle last.
To obtain historical Mark, Index Price and Premium Index candlesticks pass the'price'
params-override tofetchOHLCV
. The'price'
parameter accepts one of the following values:
'mark'
'index'
'premiumIndex'
// JavaScriptasyncfunctionmain(){constexchange=newccxt.binanceusdm()constmarkKlines=awaitexchange.fetchOHLCV('ADA/USDT','1h',undefined,undefined,{'price':'mark'})console.log(markKlines)constindexKlines=awaitexchange.fetchOHLCV('ADA/USDT','1h',undefined,undefined,{'price':'index'})console.log(indexKlines)}main()
There are also convenience methodsfetchMarkOHLCV
,fetchIndexOHLCV
andfetchPremiumIndexOHLCV
asyncfunctionmain(){constexchange=newccxt.binanceusdm()constmarkKlines=awaitexchange.fetchMarkOHLCV('ADA/USDT','1h')console.log(markKlines)constindexKlines=awaitexchange.fetchIndexOHLCV('ADA/USDT','1h')console.log(indexKlines)}main()
exchange=ccxt.binance()response=exchange.fetch_ohlcv('ADA/USDT','1h',params={'price':'index'})pprint(response)# Convenience methodsmark_klines=exchange.fetch_mark_ohlcv('ADA/USDT','1h')index_klines=exchange.fetch_index_ohlcv('ADA/USDT','1h')pprint(mark_klines)pprint(index_klines)
Some exchanges don't offer any OHLCV method, and for those, the ccxt library will emulate OHLCV candles fromPublic Trades. In that case you will seeexchange.has['fetchOHLCV'] = 'emulated'
. However, because the trade history is usually very limited, the emulated fetchOHLCV methods cover most recent info only and should only be used as a fallback, when no other option is available.
WARNING: the fetchOHLCV emulation is experimental!
UNDER CONSTRUCTION
- this is under heavy development right now, contributions appreciated
You can call the unifiedfetchTrades
/fetch_trades
method to get the list of most recent trades for a particular symbol. ThefetchTrades
method is declared in the following way:
asyncfetchTrades(symbol,since=undefined,limit=undefined,params={})
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:
if(exchange.has['fetchTrades']){letsleep=(ms)=>newPromise(resolve=>setTimeout(resolve,ms));for(symbolinexchange.markets){console.log(awaitexchange.fetchTrades(symbol))}}
importtimeifexchange.has['fetchTrades']:forsymbolinexchange.markets:# ensure you have called loadMarkets() or load_markets() method.print (symbol,exchange.fetch_trades (symbol))
if ($exchange->has['fetchTrades']) {foreach ($exchange->marketsas$symbol =>$market) {var_dump ($exchange->fetch_trades ($symbol)); }}
The fetchTrades method shown above returns an ordered list of trades (a flat array, sorted by timestamp in ascending order, oldest trade first, most recent trade last). A list of trades is represented by thetrade structure.
[{'info':{ ...},// the original decoded JSON as is'id':'12345-67890:09876/54321',// string trade id'timestamp':1502962946216,// Unix timestamp in milliseconds'datetime':'2017-08-17 12:42:48.000',// ISO8601 datetime with milliseconds'symbol':'ETH/BTC',// symbol'order':'12345-67890:09876/54321',// string order id or undefined/None/null'type':'limit',// order type, 'market', 'limit' or undefined/None/null'side':'buy',// direction of the trade, 'buy' or 'sell''takerOrMaker':'taker',// string, 'taker' or 'maker''price':0.06917684,// float price in quote currency'amount':1.5,// amount of base currency'cost':0.10376526,// total cost, `price * amount`,'fee':{// if provided by exchange or calculated by ccxt'cost':0.0015,// float'currency':'ETH',// usually base currency for buys, quote currency for sells'rate':0.002,// the fee rate (if available)},'fees':[// an array of fees if paid in multiple currencies{// if provided by exchange or calculated by ccxt'cost':0.0015,// float'currency':'ETH',// usually base currency for buys, quote currency for sells'rate':0.002,// the fee rate (if available)},]}, ...]
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.
The second optional argumentsince
reduces the array by timestamp, the thirdlimit
argument reduces by number (count) of returned items.
If the user does not specifysince
, thefetchTrades
method will return the default range of public trades from the exchange. The default set is exchange-specific, some exchanges will return trades starting from the date of listing a pair on the exchange, other exchanges will return a reduced set of trades (like, last 24 hours, last 100 trades, etc). If the user wants precise control over the timeframe, the user is responsible for specifying thesince
argument.
Most of unified methods will return either a single object or a plain array (a list) of objects (trades). However, very few exchanges (if any at all) will return all trades at once. Most often their APIslimit
output to a certain number of most recent objects.YOU CANNOT GET ALL OBJECTS SINCE THE BEGINNING OF TIME TO THE PRESENT MOMENT IN JUST ONE CALL. Practically, very few exchanges will tolerate or allow that.
To fetch historical trades, the user will need to traverse the data in portions or "pages" of objects. Pagination often implies"fetching portions of data one by one" in a loop.
In most cases users arerequired to use at least some type of pagination in order to get the expected results consistently.
On the other hand,some exchanges don't support pagination for public trades at all. In general the exchanges will provide just the most recent trades.
ThefetchTrades ()
/fetch_trades()
method also accepts an optionalparams
(assoc-key array/dict, empty by default) as its fourth argument. You can use it to pass extra params to method calls or to override a particular default value (where supported by the exchange). See the API docs for your exchange for more details.
ThefetchTime()
method (if available) returns the current integer timestamp in milliseconds from the exchange server.
fetchTime(params={})
The exchange status describes the latest known information on the availability of the exchange API. This information is either hardcoded into the exchange class or fetched live directly from the exchange API. ThefetchStatus(params = {})
method can be used to get this information. The status returned byfetchStatus
is one of:
- Hardcoded into the exchange class, e.g. if the API has been broken or shutdown.
- Updated using the exchange ping or
fetchTime
endpoint to see if its alive - Updated using the dedicated exchange API status endpoint.
fetchStatus(params={})
ThefetchStatus()
method will return a status structure like shown below:
{'status':'ok',// 'ok', 'shutdown', 'error', 'maintenance''updated':undefined,// integer, last updated timestamp in milliseconds if updated via the API'eta':undefined,// when the maintenance or outage is expected to end'url':undefined,// a link to a GitHub issue or to an exchange post on the subject}
The possible values in thestatus
field are:
'ok'
means the exchange API is fully operational'shutdown
' means the exchange was closed, and theupdated
field should contain the datetime of the shutdown'error'
means that either the exchange API is broken, or the implementation of the exchange in CCXT is broken'maintenance'
means regular maintenance, and theeta
field should contain the datetime when the exchange is expected to be operational again
margin only
When short trading or trading with leverage on a spot market, currency must be borrowed. Interest is accrued for the borrowed currency.
Data on the borrow rate for a currency can be retrieved using
fetchCrossBorrowRate ()
for a single currencies borrow ratefetchCrossBorrowRates ()
for all currencies borrow ratesfetchIsolatedBorrowRate ()
for a trading pairs borrow ratefetchIsolatedBorrowRates ()
for all trading pairs borrow ratesfetchBorrowRatesPerSymbol ()
for the borrow rates of currencies in individual markets
fetchCrossBorrowRate(code,params={})
Parameters
- code (String) Unified CCXT currency code, required (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"settle": "USDT"}
)
Returns
fetchCrossBorrowRates(params={})
Parameters
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"startTime": 1610248118000}
)
Returns
- A dictionary ofborrow rate structures with unified currency codes as keys
fetchIsolatedBorrowRate(symbol,params={})
Parameters
- symbol (String) Unified CCXT market symbol, required (e.g.
"BTC/USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"settle": "USDT"}
)
Returns
fetchIsolatedBorrowRates(params={})
Parameters
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"startTime": 1610248118000}
)
Returns
- A dictionary ofisolated borrow rate structures with unified market symbols as keys
{symbol:'BTC/USDT',// Unified market symbolbase:'BTC',// Unified currency code of the base currencybaseRate:0.00025,// A decimal value rate that interest is accrued atquote:'USDT',// Unified currency code of the quote currencyquoteRate:0.00025,// A decimal value rate that interest is accrued atperiod:86400000,// The amount of time in milliseconds that is required to accrue the interest amount specified by ratetimestamp:1646956800000,// Timestamp for when the currency had this ratedatetime:'2022-03-11T00:00:00.000Z',// Datetime for when the currency had this rateinfo:[ ...]}
{currency:'USDT',// Unified currency coderate:0.0006,// A ratio of the rate that interest is accrued atperiod:86400000,// The amount of time in milliseconds that is required to accrue the interest amount specified by ratetimestamp:1646956800000,// Timestamp for when the currency had this ratedatetime:'2022-03-11T00:00:00.000Z',// Datetime for when the currency had this rateinfo:[ ...]}
margin only
ThefetchBorrowRateHistory
method retrieves a history of a currencies borrow interest rate at specific time slots
fetchBorrowRateHistory(code,since=undefined,limit=undefined,params={})
Parameters
- code (String)required Unified CCXT currency code (e.g.
"USDT"
) - since (Integer) Timestamp for the earliest borrow rate (e.g.
1645807945000
) - limit (Integer) The maximum number ofborrow rate structures to retrieve (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array ofborrow rate structures
contract only
- Leverage Tier methods are private onbinance
ThefetchLeverageTiers()
method can be used to obtain the maximum leverage for a market at varying position sizes. It can also be used to obtain the maintenance margin rate, and the max tradeable amount for a market when that information is not available from the market object
While you can obtain the absolute maximum leverage for a market by accessingmarket['limits']['leverage']['max']
, for many contract markets, the maximum leverage will depend on the size of your position.
You can access those limits by using
fetchMarketLeverageTiers()
(single symbol)fetchLeverageTiers([symbol1, symbol2, ...])
(multiple symbols)fetchLeverageTiers()
(all market symbols)
fetchMarketLeverageTiers(symbol,params={})
Parameters
- symbol (String)required Unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"settle": "usdt"}
)
Returns
fetchLeverageTiers(symbols=undefined,params={})
Parameters
- symbols ([String]) Unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"settle": "usdt"}
)
Returns
- an array ofleverage-tiers-structures
[{"tier":1,// tier index"symbol":"BTC/USDT",// the market symbol that the leverage tier applies to"currency":"USDT",// the currency that minNotional and maxNotional are in"minNotional":0,// the lowest amount of this tier // stake = 0.0"maxNotional":10000,// the highest amount of this tier // max stake amount at 75x leverage = 133.33333333333334"maintenanceMarginRate":0.0065,// maintenance margin rate"maxLeverage":75,// max available leverage for this market when the value of the trade is > minNotional and < maxNotional"info":{ ...}// Response from exchange},{"tier":2,"symbol":"BTC/USDT","currency":"USDT","minNotional":10000,// min stake amount at 50x leverage = 200.0"maxNotional":50000,// max stake amount at 50x leverage = 1000.0"maintenanceMarginRate":0.01,"maxLeverage":50,"info":{ ...},}, ...{"tier":9,"symbol":"BTC/USDT","currency":"USDT","minNotional":20000000,"maxNotional":50000000,"maintenanceMarginRate":0.5,"maxLeverage":1,"info":{ ...},},]
In the example above:
- stakes below 133.33 = a max leverage of 75
- stakes from 200 + 1000 = a max leverage of 50
- a stake amount of 150 = a max leverage of (10000 / 150) = 66.66
- stakes between 133.33-200 = a max leverage of (10000 / stake) = 50.01 -> 74.99
Note for Huobi users: Huobi uses both leverage and amount to determine maintenance margin rates:https://www.huobi.com/support/en-us/detail/900000089903
contract only
Data on the current, most recent, and next funding rates can be obtained using the methods
fetchFundingRates ()
for all market symbolsfetchFundingRates ([ symbol1, symbol2, ... ])
for multiple market symbolsfetchFundingRate (symbol)
for a single market symbol
fetchFundingRate(symbol,params={})
Parameters
- symbol (String)required Unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
fetchFundingRates(symbols=undefined,params={})
Parameters
- symbols ([String]) An optional array/list of unified CCXT symbols (e.g.
["BTC/USDT:USDT", "ETH/USDT:USDT"]
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array offunding rate structures indexed by market symbols
contract only
Retrieve the current funding interval using the following methods:
fetchFundingInterval (symbol)
for a single market symbolfetchFundingIntervals ()
for all market symbolsfetchFundingIntervals ([ symbol1, symbol2, ... ])
for multiple market symbols
fetchFundingInterval(symbol,params={})
Parameters
- symbol (String)required Unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
fetchFundingIntervals(symbols=undefined,params={})
Parameters
- symbols ([String]) An optional array/list of unified CCXT symbols (e.g.
["BTC/USDT:USDT", "ETH/USDT:USDT"]
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array offunding rate structures
{info:{ ...},symbol:'BTC/USDT:USDT',markPrice:39294.43,indexPrice:39291.78,interestRate:0.0003,estimatedSettlePrice:undefined,timestamp:undefined,datetime:undefined,fundingRate:0.000072,fundingTimestamp:1645833600000,fundingDatetime:'2022-02-26T00:00:00.000Z',nextFundingRate:-0.000018,// nextFundingRate is actually two funding rates from nownextFundingTimestamp:undefined,nextFundingDatetime:undefined,previousFundingRate:undefined,previousFundingTimestamp:undefined,previousFundingDatetime:undefined,interval:'8h',}
contract only
fetchFundingRateHistory(symbol=undefined,since=undefined,limit=undefined,params={})
Parameters
- symbol (String) Unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - since (Integer) Timestamp for the earliest funding rate (e.g.
1645807945000
) - limit (Integer) The maximum number of funding rates to retrieve (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array offunding rate history structures
{info:{ ...},symbol:"BTC/USDT:USDT",fundingRate:-0.000068,timestamp:1642953600000,datetime:"2022-01-23T16:00:00.000Z"}
contract only
Use thefetchOpenInterest
method to get the current open interest for a symbol from the exchange.
fetchOpenInterest(symbol,params={})
Parameters
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- A dictionary ofopen interest structures
contract only
Use thefetchOpenInterestHistory
method to get a history of open interest for a symbol from the exchange.
fetchOpenInterestHistory(symbol,timeframe='5m',since=undefined,limit=undefined,params={})
Parameters
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - timeframe (String) Check exchange.timeframes for available values
- since (Integer) Timestamp for the earliest open interest record (e.g.
1645807945000
) - limit (Integer) The maximum number ofopen interest structures to retrieve (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Note for OKX users: instead of a unified symbol okx.fetchOpenInterestHistory expects a unified currency code in thesymbol argument (e.g.'BTC'
).
Returns
- An array ofopen interest structures
{symbol:'BTC/USDT',baseVolume:80872.801,// deprecatedquoteVolume:3508262107.38,// deprecatedopenInterestAmount:80872.801,openInterestValue:3508262107.38,timestamp:1649379000000,datetime:'2022-04-08T00:50:00.000Z',info:{symbol:'BTCUSDT',sumOpenInterest:'80872.80100000',sumOpenInterestValue:'3508262107.38000000',timestamp:'1649379000000'}}
option only
Use thefetchVolatilityHistory
method to get the volatility history for the code of an options underlying asset from the exchange.
fetchVolatilityHistory(code,params={})
Parameters
- code (String)required Unified CCXT currency code (e.g.
"BTC"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array ofvolatility history structures
{ info:{"period":7,"value":"0.23854072","time":"1690574400000"}timestamp:1649379000000,datetime:'2023-07-28T00:50:00.000Z',volatility:0.23854072,}
contract only
Use thefetchUnderlyingAssets
method to get the market id's of underlying assets for a contract market type from the exchange.
fetchUnderlyingAssets(params={})
Parameters
- params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"instType": "OPTION"}
) - params.type (String) Unified marketType, the default is 'option' (e.g.
"option"
)
Returns
['BTC_USDT','ETH_USDT','DOGE_USDT']
contract only
Use thefetchSettlementHistory
method to get the public settlement history for a contract market from the exchange.
fetchSettlementHistory(symbol=undefined,since=undefined,limit=undefined,params={})
Parameters
- symbol (String) Unified CCXT symbol (e.g.
"BTC/USDT:USDT-230728-25500-P"
) - since (Integer) Timestamp for the earliest settlement (e.g.
1694073600000
) - limit (Integer) The maximum number of settlements to retrieve (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array ofsettlement history structures
{info:{ ...},symbol:'BTC/USDT:USDT-230728-25500-P',price:25761.35807869,timestamp:1694073600000,datetime:'2023-09-07T08:00:00.000Z',}
Use thefetchLiquidations
method to get the public liquidations of a trading pair from the exchange.
fetchLiquidations(symbol,since=undefined,limit=undefined,params={})
Parameters
- symbol (String) Unified CCXT symbol (e.g.
"BTC/USDT:USDT-231006-25000-P"
) - since (Integer) Timestamp for the earliest liquidation (e.g.
1694073600000
) - limit (Integer) The maximum number of liquidations to retrieve (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"until": 1645807945000}
)
Returns
- An array ofliquidation structures
[{'info':{ ...},// the original decoded JSON as is'symbol':'BTC/USDT:USDT-231006-25000-P',// unified CCXT market symbol'contracts':2,// the number of derivative contracts'contractSize':0.001,// the contract size for the trading pair'price':27038.64,// the average liquidation price in the quote currency'baseValue':0.002,// value in the base currency (contracts * contractSize)'quoteValue':54.07728,// value in the quote currency ((contracts * contractSize) * price)'timestamp':1696996782210,// Unix timestamp in milliseconds'datetime':'2023-10-11 03:59:42.000',// ISO8601 datetime with milliseconds}, ...]
option only
Use thefetchGreeks
method to get the public greeks and implied volatility of an options trading pair from the exchange. UsefetchAllGreeks
to get the greeks for all symbols or multiple symbols.The greeks measure how factors like the underlying assets price, time to expiration, volatility, and interest rates, affect the price of an options contract.
fetchGreeks(symbol,params={})
Parameters
- symbol (String) Unified CCXT symbol (e.g.
"BTC/USD:BTC-240927-40000-C"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"category": "options"}
)
Returns
fetchAllGreeks(symbols=undefined,params={})
Parameters
- symbols (String) Unified CCXT symbol (e.g.
"BTC/USD:BTC-240927-40000-C"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"category": "options"}
)
// for examplefetchAllGreeks () // all symbolsfetchAllGreeks ([ 'BTC/USD:BTC-240927-40000-C', 'ETH/USD:ETH-240927-4000-C' ]) // an array of specific symbols
Returns
- A list ofgreeks structure
{'symbol':'BTC/USD:BTC-240927-40000-C',// unified CCXT market symbol'timestamp':1699593511632,// unix timestamp in milliseconds'datetime':'2023-11-10T05:18:31.632Z',// ISO8601 datetime with milliseconds'delta':0.59833,// measures the rate of change in the options price per $1 change in the underlying assets price'gamma':0.00002,// measures the rate of change in the delta per $1 change in the underlying assets price'theta':-13.4441,// measures the dollar amount that an options price will decline per day'vega':142.30124,// measures the dollar amount that an options price changes with a 1% change in the implied volatility'rho':131.82621,// measures the dollar amount that an options price changes with a 1% change in interest rates'vanna':0.06671,// measures the amount that an options delta changes with a 1% change in implied volatility'volga':925.95015,// measures the amount that an options vega changes with a 1% change in implied volatility'charm':0.18433,// measures the amount that an options delta changes each day until expiration'bidSize':2.2,// the options bid amount'askSize':9,// the options ask amount'bidImpliedVolatility':60.06,// the expected percentage price change of the underlying asset, over the remaining life of the option, calculated using the bid price'askImpliedVolatility':61.85,// the expected percentage price change of the underlying asset, over the remaining life of the option, calculated using the ask price'markImpliedVolatility':60.86,// the expected percentage price change of the underlying asset, over the remaining life of the option, calculated using the mark price'bidPrice':0.214,// the bid price of the option'askPrice':0.2205,// the ask price of the option'markPrice':0.2169,// the mark price of the option'lastPrice':0.215,// the last price of the option'underlyingPrice':39165.86,// the current market price of the underlying asset'info':{ ...},// the original decoded JSON as is}
option only
Use thefetchOption
method to get the public details of a single option contract from the exchange.
fetchOption(symbol,params={})
Parameters
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USD:BTC-240927-40000-C"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"category": "options"}
)
Returns
Use thefetchOptionChain
method to get the public option chain data of an underlying currency from the exchange.
fetchOptionChain(code,params={})
Parameters
- code (String) Unified CCXT currency code (e.g.
"BTC"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"category": "options"}
)
Returns
- A list ofoption chain structures
{'info':{ ...},// the original decoded JSON as is'currency':'BTC',// unified CCXT currency code'symbol':'BTC/USD:BTC-240927-40000-C',// unified CCXT market symbol'timestamp':1699593511632,// unix timestamp in milliseconds'datetime':'2023-11-10T05:18:31.632Z',// ISO8601 datetime with milliseconds'impliedVolatility':60.06,// the expected percentage price change of the underlying asset, over the remaining life of the option'openInterest':10,// the number of open options contracts that have not been settled'bidPrice':0.214,// the bid price of the option'askPrice':0.2205,// the ask price of the option'midPrice':0.2205,// the price in between the bid and the ask'markPrice':0.2169,// the mark price of the option'lastPrice':0.215,// the last price of the option'underlyingPrice':39165.86,// the current market price of the underlying asset'change':15.43,// the 24 hour price change in a dollar amount'percentage':11.86,// the 24 hour price change as a percentage'baseVolume':100.86,// the volume in units of the base currency'quoteVolume':23772.86,// the volume in units of the quote currency}
contract only
Use thefetchLongShortRatio
method to fetch the current long short ratio of a symbol and use thefetchLongShortRatioHistory
to fetch the history of long short ratios for a symbol.
fetchLongShortRatio (symbol, period)
for the current ratio of a single market symbolfetchLongShortRatioHistory (symbol, period, since, limit)
for the history of ratios of a single market symbol
fetchLongShortRatio(symbol,period=undefined,params={})
Parameters
- symbol (String)required Unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - period (String) The period to calculate the ratio from (e.g.
"24h"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
fetchLongShortRatioHistory(symbol=undefined,period=undefined,since=undefined,limit=undefined,params={})
Parameters
- symbol (String) Unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - period (String) The period to calculate the ratio from (e.g.
"24h"
) - since (Integer) Timestamp for the earliest ratio (e.g.
1645807945000
) - limit (Integer) The maximum number of ratios to retrieve (e.g.
10
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- an array oflong short ratio structures
{info:{ ...},symbol:'BTC/USDT:USDT',timestamp:1645833600000,datetime:'2022-02-26T00:00:00.000Z',timeframe:'24h',longShortRatio:0.000072,}
- Authentication
- Sign In
- API Keys Setup
- Accounts
- Account Balance
- Orders
- My Trades
- Ledger
- Deposit
- Withdrawal
- Deposit Addresses
- Transfers
- Fees
- Borrow Interest
- Borrow And Repay Margin
- Margin
- Margin Mode
- Leverage
- Positions
- Funding History
- Conversion
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.
The exchanges' private APIs will usually allow the following types of interaction:
- the current state of the user's account balance can be obtained with the
fetchBalance()
method as described in theAccount Balance section - the user can place and cancel orders with
createOrder()
,cancelOrder()
, as well as fetch current open orders and the past order history with methods likefetchOrder
,fetchOrders()
,fetchOpenOrder()
,fetchOpenOrders()
,fetchCanceledOrders
,fetchClosedOrder
,fetchClosedOrders
, as described in the section onOrders - the user can query the history of past trades executed with their account using
fetchMyTrades
, as described in theMy Trades section, also seeHow Orders Are Related To Trades - the user can query their positions with
fetchPositions()
andfetchPosition()
as described in thePositions section - the user can fetch the history of their transactions (on-chaintransactions which are eitherdeposits to the exchange account orwithdrawals from the exchange account) with
fetchTransactions()
, or withfetchDeposit()
,fetchDeposits()
fetchWithdrawal()
, andfetchWithdrawals()
separately, depending on what is available from the exchange API - if the exchange API provides a ledger endpoint, the user can fetch a history of all money movements that somehow affected the balance, with
fetchLedger
that will return all accounting ledger entries such as trades, deposits, withdrawals, internal transfers between accounts, rebates, bonuses, fees, staking profits and so on, as described in theLedger section.
Authentication with all exchanges is handled automatically if provided with proper API keys. The process of authentication usually goes through the following pattern:
- 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.
- Append public apiKey and nonce to other endpoint params, if any, then serialize the whole thing for signing.
- Sign the serialized params using HMAC-SHA256/384/512 or MD5 with your secret key.
- 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.
You should not share the same API keypair across multiple instances of an exchange running simultaneously, in separate scripts or in multiple threads. Using the same keypair from different instances simultaneously may cause all sorts of unexpected behaviour.
DO NOT REUSE API KEYS WITH DIFFERENT SOFTWARE! The other software will screw your nonce too high. If you getInvalidNonce errors – make sure to generate a fresh new keypair first and foremost.
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.
The API credentials usually include the following:
apiKey
. This is your public API Key and/or Token. This part isnon-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 oruid for short. It can be a string or numeric literal. You should set it, if that is explicitly required by your exchange. Seetheir 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. Seetheir 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 apiKey and 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.
For checking if the user has supplied all the required credentials theExchange
base class has a method calledexchange.checkRequiredCredentials()
orexchange.check_required_credentials()
. Calling that method will throw anAuthenticationError
, if some of the credentials are missing or empty. TheExchange
base class also has propertyexchange.requiredCredentials
that allows a user to see which credentials are required for this or that exchange, as shown below:
constccxt=require('ccxt')constexchange=newccxt.binance()console.log(exchange.requiredCredentials)// prints required credentialsexchange.checkRequiredCredentials()// throw AuthenticationError
importccxtexchange=ccxt.coinbasepro()print(exchange.requiredCredentials)# prints required credentialsexchange.check_required_credentials()# raises AuthenticationError
include'ccxt.php';$exchange =new \ccxt\bittrex ();var_dump($exchange->requiredCredentials);// prints required credentials$exchange->check_required_credentials();// throws AuthenticationError
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:
constccxt=require('ccxt')// any timeletkraken=newccxt.kraken()kraken.apiKey='YOUR_KRAKEN_API_KEY'kraken.secret='YOUR_KRAKEN_SECRET_KEY'// upon instantiationletokcoin=newccxt.okcoin({apiKey:'YOUR_OKCOIN_API_KEY',secret:'YOUR_OKCOIN_SECRET_KEY',})// from variable idconstexchangeId='binance',exchangeClass=ccxt[exchangeId],exchange=newexchangeClass({'apiKey':'YOUR_API_KEY','secret':'YOUR_SECRET',})
importccxt# any timebitfinex=ccxt.bitfinex ()bitfinex.apiKey='YOUR_BFX_API_KEY'bitfinex.secret='YOUR_BFX_SECRET'# upon instantiationhitbtc=ccxt.hitbtc ({'apiKey':'YOUR_HITBTC_API_KEY','secret':'YOUR_HITBTC_SECRET_KEY',})# from variable idexchange_id='binance'exchange_class=getattr(ccxt,exchange_id)exchange=exchange_class({'apiKey':'YOUR_API_KEY','secret':'YOUR_SECRET',})
include'ccxt.php'// any time$hitbtc =new \ccxt\hitbtc ();$hitbtc->apiKey ='YOUR_HITBTC_API_KEY';$hitbtc->secret ='YOUR_HITBTC_SECRET_KEY';// upon instantiation$zaif =new \ccxt\zaif (array ('apiKey' =>'YOUR_ZAIF_API_KEY','secret' =>'YOUR_ZAIF_SECRET_KEY'));// from variable id$exchange_id ='binance';$exchange_class ="\\ccxt\\$exchange_id";$exchange =new$exchange_class (array ('apiKey' =>'YOUR_API_KEY','secret' =>'YOUR_SECRET',));
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 escapingalways write your credentials in single quotes, not double quotes ('VERY_GOOD'
,"VERY_BAD"
).
When you get errors like"Invalid API-key, IP, or permissions for action."
or"API-key format invalid"
, then, most likely, the problem is not within ccxt, please avoid opening a new issue unless you ensure that:
- You don't have typos, empty spaces, or quotes in your keys
- Your current IP address (checkIPv4 orIPv6) is added into API-KEY's whitelist (if you use proxy, consider that too)
- You have selected the correct options in permissions list for that api-key
- You are not accidentally mixing "testnet" api-keys or "testnet" mode in your script
- You have checked alreadyreported issues about this error
Some exchanges required you to sign in prior to calling private methods, which can be done using thesignIn
method
signIn(params={})
Parameters
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"2fa": "329293"}
)
Returns
- response from the exchange
The default nonce is defined by the underlying exchange. You can 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, readAPI docs for your exchange 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 anonce
parameter to the exchange constructor or by setting it explicitly on exchange object:
// JavaScript// 1: custom nonce redefined in constructor parametersletnonce=1letkraken1=newccxt.kraken({nonce:()=>nonce++})// 2: nonce redefined explicitlyletkraken2=newccxt.kraken()kraken2.nonce=function(){returnnonce++}// uses same nonce as kraken1// 3: milliseconds nonceletkraken3=newccxt.kraken({nonce:function(){returnthis.milliseconds()},})// 4: newer ES syntaxletkraken4=newccxt.kraken({nonce(){returnthis.milliseconds()},})
In Python and PHP you can do the same by subclassing and overriding nonce function of a particular exchange class:
# Python# 1: the shortestcoinbasepro=ccxt.coinbasepro({'nonce':ccxt.Exchange.milliseconds})# 2: custom nonceclassMyKraken(ccxt.kraken):n=1defnonce(self):returnself.n+=1# 3: milliseconds nonceclassMyBitfinex(ccxt.bitfinex):defnonce(self):returnself.milliseconds()# 4: milliseconds nonce inlinehitbtc=ccxt.hitbtc({'nonce':lambda:int(time.time()*1000)})# 5: milliseconds nonceacx=ccxt.acx({'nonce':lambda:ccxt.Exchange.milliseconds()})
// PHP// 1: custom nonce valueclass Myokcoinextends \ccxt\okcoin {publicfunction__construct ($options =array ()) {parent::__construct (array_merge (array ('i' =>1),$options)); }publicfunctionnonce () {return$this->i++; }}// 2: milliseconds nonceclass MyZaifextends \ccxt\zaif {publicfunction__construct ($options =array ()) {parent::__construct (array_merge (array ('i' =>1),$options)); }publicfunctionnonce () {return$this->milliseconds (); }}
You can get all the accounts associated with a profile by using thefetchAccounts()
method
fetchAccounts(params={})
ThefetchAccounts()
method will return a structure like shown below:
[{id:"s32kj302lasli3930",type:"main",name:"main",code:"USDT",info:{ ...}},{id:"20f0sdlri34lf90",name:"customAccount",type:"margin",code:"USDT",info:{ ...}},{id:"4oidfk40dadeg4328",type:"spot",name:"spotAccount32",code:"BTC",info:{ ...}}, ...]
Types of account is one of theunified account types orsubaccount
To query for balance and get the amount of funds available for trading or funds locked in orders, use thefetchBalance
method:
fetchBalance(params={})
Parameters
- params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"currency": "usdt"}
)
Returns
{'info':{ ...},// the original untouched non-parsed reply with details'timestamp':1499280391811,// Unix Timestamp in milliseconds (seconds * 1000)'datetime':'2017-07-05T18:47:14.692Z',// ISO8601 datetime string with milliseconds//-------------------------------------------------------------------------// indexed by availability of funds first, then by currency'free':{// money, available for trading, by currency'BTC':321.00,// floats...'USD':123.00, ...},'used':{ ...},// money on hold, locked, frozen, or pending, by currency'total':{ ...},// total (free + used), by currency'debt':{ ...},// debt, by currency//-------------------------------------------------------------------------// indexed by currency first, then by availability of funds'BTC':{// string, three-letter currency code, uppercase'free':321.00// float, money available for trading'used':234.00,// float, money on hold, locked, frozen or pending'total':555.00,// float, total balance (free + used)},'USD':{// ...'free':123.00// ...'used':456.00,'total':579.00,}, ...}
Thetimestamp
anddatetime
values may be undefined or missing if the underlying exchange does not provide them.
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.
(async()=>{console.log(awaitexchange.fetchBalance())})()
print (exchange.fetch_balance ())
var_dump ($exchange->fetch_balance ());
- this part of the unified API is currenty a work in progress- there may be some issues and missing implementations here and there- contributions, pull requests and feedback appreciated
Most of the time you can query orders by an id or by a symbol, 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 where possible.
The list of methods for querying orders consists of the following:
fetchCanceledOrders (symbol = undefined, since = undefined, limit = undefined, params = {})
fetchClosedOrder (id, symbol = undefined, params = {})
fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {})
fetchOpenOrder (id, symbol = undefined, params = {})
fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {})
fetchOrder (id, symbol = undefined, params = {})
fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {})
Note that the naming of those methods indicates if the method returns a single order or multiple orders (an array/list of orders). ThefetchOrder()
method requires a mandatory order id argument (a string). Some exchanges also require a symbol to fetch an order by id, where order ids can intersect with various trading pairs. Also, note that all other methods above return an array (a list) of orders. Most of them will require a symbol argument as well, however, some exchanges allow querying with a symbol unspecified (meaningall symbols).
The library will throw a NotSupported exception if a user calls a method that is not available from the exchange or is not implemented in ccxt.
To check if any of the above methods are available, look into the.has
property of the exchange:
'use strict';constccxt=require('ccxt')constid='poloniex'exchange=newccxt[id]()console.log(exchange.has)
importccxtid='binance'exchange=getattr(ccxt,id)()print(exchange.has)
$exchange =new \ccxt\bitfinex();print_r ($exchange->has);// or var_dump
A typical structure of the.has
property usually contains the following flags corresponding to order API methods for querying orders:
exchange.has={// ... other flags ...'fetchOrder':true,// available from the exchange directly and implemented in ccxt'fetchOrders':false,// not available from the exchange or not implemented in ccxt'fetchOpenOrders':true,'fetchClosedOrders':'emulated',// not available from the exchange, but emulated in ccxt// ... other flags ...}
The meanings of booleantrue
andfalse
are obvious. A string value ofemulated
means that particular method is missing in the exchange API and ccxt will workaround that where possible on the client-side.
The exchanges' order management APIs differ by design. The user has to understand the purpose of each specific method and how they're combined together into a complete order API:
fetchCanceledOrders()
- fetches a list of canceled ordersfetchClosedOrder()
- fetches a single closed order by order idfetchClosedOrders()
– fetches a list of closed (or canceled) orders.fetchMyTrades()
– though not a part of the orders' API, it is closely related, since it provides the history of settled trades.fetchOpenOrder()
- fetches a single open order by order idfetchOpenOrders()
– fetches a list of open orders.fetchOrder()
– fetches a single order (open or closed) by orderid
.fetchOrders()
– fetches a list of all orders (either open or closed/canceled).createOrder()
– used for placing orderscreateOrders()
– used for placing multiple orders within the same requestcancelOrder()
– used for canceling a single ordercancelOrders()
- used for canceling multiple orderscancelAllOrders()
- used for canceling all orderscancelAllOrdersAfter()
- used for canceling all orders after the given timeout
The majority of the exchanges will have a way of fetching currently-open orders. Thus, theexchange.has['fetchOpenOrders']
. If that method is not available, then most likely theexchange.has['fetchOrders']
that will provide a list of all orders. The exchange will return a list of open orders either fromfetchOpenOrders()
or fromfetchOrders()
. One of the two methods is usually available from any exchange.
Some exchanges will provide the order history, other exchanges will not. If the underlying exchange provides the order history, then theexchange.has['fetchClosedOrders']
or theexchange.has['fetchOrders']
. If the underlying exchange does not provide the order history, thenfetchClosedOrders()
andfetchOrders()
are not available. In the latter case, the user is required to build a local cache of orders and track the open orders usingfetchOpenOrders()
andfetchOrder()
for order statuses and for marking them as closed locally in the userland (when they're not open anymore).
If the underlying exchange does not have methods for order history (fetchClosedOrders()
andfetchOrders()
), then it will providefetchOpenOrders
+ the trade history withfetchMyTrades
(seeHow Orders Are Related To Trades). That set of information is in many cases enough for tracking in a live-trading robot. If there's no order history – you have to track your live orders and restore historical info from open orders and historical trades.
In general, the underlying exchanges will usually provide one or more of the following types of historical data:
fetchClosedOrders()
fetchOrders()
fetchMyTrades()
Any of the above three methods may be missing, but the exchanges APIs will usually provide at least one of the three methods.
If the underlying exchange does not provide historical orders, the CCXT library will not emulate the missing functionality – it has to be added on the user side where necessary.
Please, note, that a certain method may be missing either because the exchange does not have a corresponding API endpoint, or because CCXT has not implemented it yet (the library is also a work in progress). In the latter case, the missing method will be added as soon as possible.
All methods returning lists of trades and lists of orders, accept the secondsince
argument and the thirdlimit
argument:
fetchTrades()
(public)fetchMyTrades()
(private)fetchOrders()
fetchOpenOrders()
fetchClosedOrders()
fetchCanceledOrders()
The second argumentsince
reduces the array by timestamp, the thirdlimit
argument reduces by number (count) of returned items.
If the user does not specifysince
, thefetchTrades()/fetchOrders()
methods will return the default set of results from the exchange. The default set is exchange-specific, some exchanges will return trades or recent orders starting from the date of listing a pair on the exchange, other exchanges will return a reduced set of trades or orders (like, last 24 hours, last 100 trades, first 100 orders, etc). If the user wants precise control over the timeframe, the user is responsible for specifying thesince
argument.
NOTE: not all exchanges provide means for filtering the lists of trades and orders by starting time, so, the support forsince
andlimit
is exchange-specific. However, most exchanges do provide at least some alternative for "pagination" and "scrolling" which can be overrided with extraparams
argument.
Some exchanges do not have a method for fetching closed orders or all orders. They will offer just thefetchOpenOrders()
endpoint, and sometimes also afetchOrder
endpoint as well. Those exchanges don't have any methods for fetching the order history. To maintain the order history for those exchanges the user has to store a dictionary or a database of orders in the userland and update the orders in the database after calling methods likecreateOrder()
,fetchOpenOrders()
,cancelOrder()
,cancelAllOrders()
.
To get the details of a particular order by its id, use thefetchOrder()
/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:
if(exchange.has['fetchOrder']){// you can use the params argument for custom overridesletorder=awaitexchange.fetchOrder(id,symbol=undefined,params={})}
Some exchanges don't have an endpoint for fetching an order by id, ccxt will emulate it where possible. For now it may still be missing here and there, as this is a work in progress.
You can pass custom overrided key-values in the additional params argument to supply a specific order type, or some other setting if needed.
Below are examples of using the fetchOrder method to get order info from an authenticated exchange instance:
(asyncfunction(){constorder=awaitexchange.fetchOrder(id)console.log(order)})()
ifexchange.has['fetchOrder']:order=exchange.fetch_order(id)print(order)# Python 3.7+ asyncio (asynchronous)importasyncioimportccxt.async_supportasccxtifexchange.has['fetchOrder']:order=asyncio.run(exchange.fetch_order(id))print(order)
if ($exchange->has['fetchOrder']) {$order =$exchange->fetch_order($id);var_dump($order);}
if(exchange.has['fetchOrders'])exchange.fetchOrders(symbol=undefined,since=undefined,limit=undefined,params={})
Some exchanges don't have an endpoint for fetching all orders, ccxt will emulate it where possible. For now it may still be missing here and there, as this is a work in progress.
if(exchange.has['fetchOpenOrders'])exchange.fetchOpenOrders(symbol=undefined,since=undefined,limit=undefined,params={})
Do not confuseclosed orders withtrades akafills ! An order can be closed (filled) with multiple opposing trades! So, aclosed order is not the same as atrade. In general, the order does not have afee
at all, but each particular user trade does havefee
,cost
and other properties. However, many exchanges propagate those properties to the orders as well.
Some exchanges don't have an endpoint for fetching closed orders, ccxt will emulate it where possible. For now it may still be missing here and there, as this is a work in progress.
if(exchange.has['fetchClosedOrders'])exchange.fetchClosedOrders(symbol=undefined,since=undefined,limit=undefined,params={})
Most of methods returning orders within ccxt unified API will yield an order structure as described below:
{'id':'12345-67890:09876/54321',// string'clientOrderId':'abcdef-ghijklmnop-qrstuvwxyz',// a user-defined clientOrderId, if any'datetime':'2017-08-17 12:42:48.000',// ISO8601 datetime of 'timestamp' with milliseconds'timestamp':1502962946216,// order placing/opening Unix timestamp in milliseconds'lastTradeTimestamp':1502962956216,// Unix timestamp of the most recent trade on this order'status':'open',// 'open', 'closed', 'canceled', 'expired', 'rejected''symbol':'ETH/BTC',// symbol'type':'limit',// 'market', 'limit''timeInForce':'GTC',// 'GTC', 'IOC', 'FOK', 'PO''side':'buy',// 'buy', 'sell''price':0.06917684,// float price in quote currency (may be empty for market orders)'average':0.06917684,// float average filling price'amount':1.5,// ordered amount of base currency'filled':1.1,// filled amount of base currency'remaining':0.4,// remaining amount to fill'cost':0.076094524,// 'filled' * 'price' (filling price used where available)'trades':[ ...],// a list of order trades/executions'fee':{// fee info, if available'currency':'BTC',// which currency the fee is (usually quote)'cost':0.0009,// the fee amount in that currency'rate':0.002,// the fee rate (if available)},'info':{ ...},// the original unparsed order structure as is}
- The
status
of an order is usually either'open'
(not filled or partially filled),'closed'
(fully filled), or'canceled'
(unfilled and canceled, or partially filled then canceled). - Some exchanges allow the user to specify an expiration timestamp upon placing a new order. If the order is not filled by that time, its
status
becomes'expired'
. - Use the
filled
value to determine if the order is filled, partially filled or fully filled, and by how much. - The work on
'fee'
info is still in progress, fee info may be missing partially or entirely, depending on the exchange capabilities. - The
fee
currency may be different from both traded currencies (for example, an ETH/BTC order with fees in USD). - The
lastTradeTimestamp
timestamp may have no value and may beundefined/None/null
where not supported by the exchange or in case of an open order (an order that has not been filled nor partially filled yet). - The
lastTradeTimestamp
, if any, designates the timestamp of the last trade, in case the order is filled fully or partially, otherwiselastTradeTimestamp
isundefined/None/null
. - Order
status
prevails or has precedence over thelastTradeTimestamp
. - The
cost
of an order is:{ filled * price }
- The
cost
of an order means the totalquote volume of the order (whereas theamount
is thebase volume). The value ofcost
should be as close to the actual most recent known order cost as possible. Thecost
field itself is there mostly for convenience and can be deduced from other fields. - The
clientOrderId
field can be set upon placing orders by the user withcustom order params. Using theclientOrderId
the user can later distinguish between own orders. This is only available for the exchanges that do supportclientOrderId
at this time.
ThetimeInForce
field may beundefined/None/null
if not specified by the exchange. The unification oftimeInForce
is a work in progress.
Possible values for thetimeInForce
field:
'GTC'
=Good Till Cancel(ed), the order stays on the orderbook until it is matched or canceled.'IOC'
=Immediate Or Cancel, the order has to be matched immediately and filled either partially or completely, the unfilled remainder is canceled (or the entire order is canceled).'FOK'
=Fill Or Kill, the order has to get fully filled and closed immediately, otherwise the entire order is canceled.'PO'
=Post Only, the order is either placed as a maker order, or it is canceled. This means the order must be placed on orderbook for at at least time in an unfilled state. The unification ofPO
as atimeInForce
option is a work in progress with unified exchanges havingexchange.has['createPostOnlyOrder'] == True
.
There are different types of orders that a user can send to the exchange, regular orders eventually land in the orderbook of a corresponding symbol, others orders may be more advanced. Here is a list outlining various types of orders:
- Limit Orders – regular orders having an
amount
in base currency (how much you want to buy or sell) and aprice
in quote currency (for which price you want to buy or sell). - Market Orders – regular orders having an
amount
in base currency (how much you want to buy or sell)- Market Buys – some exchanges require market buy orders with an
amount
in quote currency (how much you want to spend for buying)
- Market Buys – some exchanges require market buy orders with an
- Trigger Orders akaconditional orders – an advanced type of order used to wait for a certain condition on a market and then react automatically: when a
triggerPrice
is reached, the trigger order gets triggered and then a regular limitprice
or market price order is placed, that eventually results in entering a position or exiting a position - Stop Loss Orders – almost the same as trigger orders, but used to close a position to stop further losses on that position: when the price reaches
triggerPrice
then the stop loss order is triggered that results in placing another regular limit or market order to close a position at a specific limitprice
or at market price (a position with a stop loss order attached to it). - Take Profit Orders – a counterpart to stop loss orders, this type of order is used to close a position to take existing profits on that position: when the price reaches
triggerPrice
then the take profit order is triggered that results in placing another regular limit or market order to close a position at a specific limitprice
or at market price (a position with a take profit order attached to it). - StopLoss And TakeProfit Orders Attached To A Position – advanced orders, consisting of three orders of types listed above: a regular limit or market order placed to enter a position with stop loss and/or take profit orders that will be placed upon opening that position and will be used to close that position later (when a stop loss is reached, it will close the position and will cancel its take profit counterpart, and vice versa, when a take profit is reached, it will close the position and will cancel its stop loss counterpart, these two counterparts are also known as "OCO orders – one cancels the other), apart from the
amount
(andprice
for the limit order) to open a position it will also require atriggerPrice
for a stop loss order (with a limitprice
if it's a stop loss limit order) and/or atriggerPrice
for a take profit order (with a limitprice
if it's a take profit limit order). - Trailing Orders – an order that is automatically adjusted relative to an open position,
trailingAmount
can be set to trail a specified quote amount behind the open position ortrailingPercent
can be set to trail a specified percent behind the open position, when the market price of the position is equal to the trailing order this results in entering a new position or exiting a position depending on if the trailing order has thereduceOnly
parameter set to true or not.
Placing an order always requires asymbol
that the user has to specify (which market you want to trade).
To place an order use thecreateOrder
method. You can use theid
from the returned unifiedorder structure to query the status and the state of the order later. If you need to place multiple orders simultaneously, you can check the availability of thecreateOrders
method.
createOrder(symbol,type,side,amount,price=undefined,params={})
createOrders(orders,params={})// orders is a list in which each element contains a symbol, type, side, amount, price and params
Parameters
- symbol (String)required Unified CCXT market symbol
- Make sure the symbol in question exists with the target exchange and is available for trading.
- siderequired a string literal for the direction of your order.Unified sides:
buy
give quote currency and receive base currency; for example, buyingBTC/USD
means that you will receive bitcoins for your dollars.sell
give base currency and receive quote currency; for example, buyingBTC/USD
means that you will receive dollars for your bitcoins.
- type a string literal type of orderUnified types:
- market not allowed by some exchanges, seetheir docs for details
- limit
- see #custom-order-params and #other-order-types for non-unified types
- amount, how much of currency you want to trade usually, but not always, in units of the base currency of the trading pair symbol (the units for some exchanges are dependent on the side of the order: see their API docs for details.)
- price the price at which the order is to be fullfilled at in units of the quote currency (ignored in market orders)
- params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"settle": "usdt"}
)
Returns
- A successful order call returns aorder structure
Notes on createOrder
- Some exchanges will allow to trade with limit orders only.
Some fields from the returned order structure may beundefined / None / null
if that information is not returned from the exchange API's response. The user is guaranteed that thecreateOrder
method will return a unifiedorder structure that will contain at least the orderid
and theinfo
(a raw response from the exchange "as is"):
{'id':'string',// order id'info':{ ...},// decoded original JSON response from the exchange as is}
- There is a common error that happens when creating orders for contract markets:
"must be greater than minimum amount precision of 1"
This error happens when the exchange is expecting a natural number of contracts (1,2,3, etc) in theamount
argument ofcreateOrder
. Themarket structure has a key calledcontractSize
. Each contract is worth a certain amount of the base asset that is determined by thecontractSize
. The number of contracts multiplied by thecontractSize
is equal to the base amount.Base amount = (contracts * contractSize)
so to derive the number of contracts you should enter in theamount
argument you can solve for contracts:contracts = (Base amount / contractSize)
.
Here is an example of finding thecontractSize
:
awaitexchange.loadMarkets()symbol='BTC/USDT:USDT'market=exchange.market(symbol)print(market['contractSize'])# Let's say you want to convert 0.5 BTC to the number of contracts:number_contracts=round((0.5*1)/market['contractSize'])
Limit orders placed on the order book of the exchange for a price specified by the trader. They are fullfilled(closed) when there are no orders in the same market at a better price, and another trader creates amarket order or an opposite order for a price that matches or exceeds the price of the limit order.
Limit orders may not be fully filled. This happens when the filling order is for a smaller amount than the amount specified by the limit order.
// camelCaseNotationexchange.createLimitSellOrder(symbol,amount,price,params)exchange.createLimitBuyOrder(symbol,amount,price,params)// underscore_notationexchange.create_limit_sell_order(symbol,amount,price,params)exchange.create_limit_buy_order(symbol,amount,price,params)// using general createLimitOrder and side = 'buy' or 'sell'exchange.createLimitOrder(symbol,side,amount,price,params)exchange.create_limit_order(symbol,side,amount,price,params)// using general createOrder, type = 'limit' and side = 'buy' or 'sell'exchange.createOrder(symbol,'limit',side,amount,price,params)exchange.create_order(symbol,'limit',side,amount,price,params)
also known as
- market price orders
- spot price orders
- instant orders
Market orders are executed immediately by fulfilling one of more already existing orders from the ask side of the exchanges order book. The orders that your market order fulfills are chosen from th top of the order book stack, meaning your market order is fulfilled at the best price available. When placing a market order you don't need to specify the price of the order, and if the price is specified, it will be ignored.
You are not guaranteed that the order will be executed for the price you observe prior to placing your order. There are multiple reasons for this, including:
price slippage a slight change of the price for the traded market while your order is being executed. Reasons for price slippage include, but are not limited to
- networking roundtrip latency
- high loads on the exchange
- price volatility
unequivocal order sizes if a market order is for an amount that is larger than the size of the top order on the order book, then after the top order is filled, the market order will proceed to fill the next order in the order book, which means the market order is filled at multiple prices
// camelCaseNotationexchange.createMarketSellOrder(symbol,amount,params)exchange.createMarketBuyOrder(symbol,amount,params)// underscore_notationexchange.create_market_sell_order(symbol,amount,params)exchange.create_market_buy_order(symbol,amount,params)// using general createMarketOrder and side = 'buy' or 'sell'exchange.createMarketOrder(symbol,side,amount,params)exchange.create_market_order(symbol,side,amount,params)// using general createOrder, type = 'market' and side = 'buy' or 'sell'exchange.createOrder(symbol,'market',side,amount, ...)exchange.create_order(symbol,'market',side,amount, ...)
Note, that some exchanges will not accept market orders (they allow limit orders only). In order to detect programmatically if the exchange in question does support market orders or not, you can use the.has['createMarketOrder']
exchange property:
if(exchange.has['createMarketOrder']){ ...}
ifexchange.has['createMarketOrder']: ...
if ($exchange->has['createMarketOrder']) {...}
In general, when placing amarket buy
ormarket sell
order the user has to specify just the amount of the base currency to buy or sell. However, with some exchanges market buy orders implement a different approach to calculating the value of the order.
Suppose you're trading BTC/USD and the current market price for BTC is over 9000 USD. For a market buy or market sell you could specify anamount
of 2 BTC and that would result inplus or minus 18000 USD (more or less ;)) on your account, depending on the side of the order.
With market buys some exchanges require the total cost of the order in the quote currency! The logic behind it is simple, instead of taking the amount of base currency to buy or sell some exchanges operate with"how much quote currency you want to spend on buying in total".
To place a market buy order with those exchanges you would not specify an amount of 2 BTC, instead you should somehow specify the total cost of the order, that is, 18000 USD in this example. The exchanges that treatmarket buy
orders in this way have an exchange-specific optioncreateMarketBuyOrderRequiresPrice
that allows specifying the total cost of amarket buy
order in two ways.
The first is the default and if you specify theprice
along with theamount
the total cost of the order would be calculated inside the lib from those two values with a simple multiplication (cost = amount * price
). The resultingcost
would be the amount in USD quote currency that will be spent on this particular market buy order.
// this example is oversimplified and doesn't show all the code that is// required to handle the errors and exchange metadata properly// it shows just the concept of placing a market buy orderconstexchange=newccxt.cex({'apiKey':YOUR_API_KEY,'secret':'YOUR_SECRET',// 'options': {// 'createMarketBuyOrderRequiresPrice': true, // default// },});(async()=>{// when `createMarketBuyOrderRequiresPrice` is true, we can pass the price// so that the total cost of the order would be calculated inside the library// by multiplying the amount over price (amount * price)constsymbol='BTC/USD'constamount=2// BTCconstprice=9000// USD// cost = amount * price = 2 * 9000 = 18000 (USD)// note that we don't use createMarketBuyOrder here, instead we use createOrder// createMarketBuyOrder will omit the price and will not work when// exchange.options['createMarketBuyOrderRequiresPrice'] = trueconstorder=awaitexchange.createOrder(symbol,'market','buy',amount,price)console.log(order)})()
The second alternative is useful in cases when the user wants to calculate and specify the resulting total cost of the order himself. That can be done by setting thecreateMarketBuyOrderRequiresPrice
option tofalse
to switch it off:
constexchange=newccxt.cex({'apiKey':YOUR_API_KEY,'secret':'YOUR_SECRET','options':{'createMarketBuyOrderRequiresPrice':false,// switch off},})// or, to switch it off later, after the exchange instantiation, you can doexchange.options['createMarketBuyOrderRequiresPrice']=false;(async()=>{// when `createMarketBuyOrderRequiresPrice` is true, we can pass the price// so that the total cost of the order would be calculated inside the library// by multiplying the amount over price (amount * price)constsymbol='BTC/USD'constamount=2// BTCconstprice=9000// USDcost=amount*price// ← instead of the amount cost goes ↓ hereconstorder=awaitexchange.createMarketBuyOrder(symbol,cost)console.log(order)})()
More about it:
- https://github.com/ccxt/ccxt/issues/564#issuecomment-347458566
- https://github.com/ccxt/ccxt/issues/4914#issuecomment-478199357
- https://github.com/ccxt/ccxt/issues/4799#issuecomment-470966769
- https://github.com/ccxt/ccxt/issues/5197#issuecomment-496270785
It is also possible to emulate amarket
order with alimit
order.
WARNING this method can be risky due to high volatility, use it at your own risk and only use it when you know really well what you're doing!
Most of the time amarket sell
can be emulated with alimit sell
at a very low price – the exchange will automatically make it a taker order for market price (the price that is currently in your best interest from the ones that are available in the order book). When the exchange detects that you're selling for a very low price it will automatically offer you the best buyer price available from the order book. That is effectively the same as placing a market sell order. Thus market orders can be emulated with limit orders (where missing).
The opposite is also true – amarket buy
can be emulated with alimit buy
for a very high price. Most exchanges will again close your order for best available price, that is, the market price.
However, you should never rely on that entirely,ALWAYS test it with a small amount first! You can try that in their web interface first to verify the logic. You can sell the minimal amount at a specified limit price (an affordable amount to lose, just in case) and then check the actual filling price in trade history.
Limit price orders are also known aslimit 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.
// camelCaseStyleexchange.createLimitBuyOrder(symbol,amount,price[,params])exchange.createLimitSellOrder(symbol,amount,price[,params])// underscore_styleexchange.create_limit_buy_order(symbol,amount,price[,params])exchange.create_limit_sell_order(symbol,amount,price[,params])
Coming from traditional trading, the term "Stop order" has been a bit ambigious, so instead of it, in CCXT we use term "Trigger" order. When symbol's price reaches your "trigger"("stop") price, the order is activated asmarket
orlimit
order, depending which one you had chosen.
We have different classification of trigger orders:
- standaloneTrigger order to buy/sell coin (open/close position)
- standaloneStop Loss orTake Profit designed to close open positions.
- a Stop Loss or Take Profit order attached to a primary order (Conditional Trigger Order).
Traditional "stop" order (which you might see across exchanges' websites) is now called "trigger" order across CCXT library. Implemented by adding atriggerPrice
parameter. They are independent basic trigger orders that can open or close a position.
- Typically, it is activated when price of the underlying asset/contract crosses the
triggerPrice
fromany direction. However, some exchanges' API require to settriggerDirection
too, which triggers order depending whether price is above or belowtriggerPrice
. For example, if you want to trigger limit order (buy 0.1ETH
at limit price1500
) once pair price crosses1700
:
constparams={'triggerPrice':1700,}constorder=awaitexchange.createOrder('ETH/USDT','market','buy',0.1,1500,params)
params= {'triggerPrice':1700,}order=exchange.create_order('ETH/USDT','market','buy',0.1,1500,params)
$params = {'triggerPrice':1700,}$order =$exchange->create_order ('ETH/USDT','market','buy',0.1,1500,$params)
Typically, exchange automatically determinestriggerPrice
's direction (whether it is "above" or "below" current price), however, some exchanges require that you providetriggerDirection
with eitherascending
ordescending
values:
params = { 'triggerPrice': 1700, 'triggerDirection': 'ascending', // order will be triggered when price goes upward and touches 1700}
Note, you can also addreduceOnly: true
param to the trigger order (with a possibletriggerDirection: 'ascending/descending'
param), so it would act as "stop-loss" or "take-profit" order. However, for some exchanges we support "stop-loss" and "take-profit" trigger order types, which automatically involvereduceOnly
andtriggerDirection
handling (see them below).
The same as Trigger Orders, but the direction matters. Implemented by specifying astopLossPrice
parameter (for the stop loss triggerPrice), and also automatically implementedtriggerDirection
on behalf of user, so instead of regular Trigger Order, you can use this as an alternative.
Suppose you entered a long position (you bought) at 1000 and want to protect yourself from losses from a possible price drop below 700. You would place a stop loss order with triggerPrice at 700. For that stop loss order either you would specify a limit price or it will be executed at market price.
| price | amount----|---------------- | 1500 | 200 | 1400 | 300 a | 1300 | 100 s | 1200 | 200 k | 1100 | 300 | 1000 | 100 <--- you bought to enter a long position here at 1000 | 900 | 100----|---------------- last price is 900 | 800 | 100 | 700 | 200 <------- you place a stop loss order here at 700 <----------------------+ b | 600 | 100 when your stopLossPrice is reached from above | i | 500 | 300 it will close your position at market price below 700 ----------------+ d | 400 | 200 <- or it will be executed at your limit price lower that stopLossPrice -+ | 300 | 100 | 200 | 100
Suppose you entered a short position (you sold) at 700 and want to protect yourself from losses from a possible price pump above 1300. You would place a stop loss order with triggerPrice at 1300. For that stop loss order either you would specify a limit price or it will be executed at market price.
| price | amount----|---------------- | 1500 | 200 | 1400 | 300 <------------------------------------------------------------------------+ a | 1300 | 100 <------ you place a stop loss order here at 1300 <---------------------+ | s | 1200 | 200 when your stopLossPrice is reached from below | | k | 1100 | 300 it will close your position at market price above 1300 --------------+ | | 1000 | 100 or it will be executed at your limit price higher than stopLossPrice -+ | 900 | 100----|---------------- last price is 900 (you sold at 700) | 800 | 100 | 700 | 200 <--- you sold to enter a short position here at 700 b | 600 | 100 i | 500 | 300 d | 400 | 200 | 300 | 100 | 200 | 100
Stop Loss orders are activated when the price of the underlying asset/contract:
- drops below the
stopLossPrice
from above, for sell orders. (eg: to close a long position, and avoid further losses) - rises above the
stopLossPrice
from below, for buy orders (eg: to close a short position, and avoid further losses)
// for a stop loss orderconstparams={'stopLossPrice':55.45,// your stop loss price}constorder=awaitexchange.createOrder(symbol,type,side,amount,price,params)
# for a stop loss orderparams= {'stopLossPrice':55.45,# your stop loss price}order=exchange.create_order (symbol,type,side,amount,price,params)
// for a stop loss order$params = {'stopLossPrice':55.45,// your stop loss price}$order =$exchange->create_order ($symbol,$type,$side,$amount,$price,$params);
The same as Stop Loss Orders, but the direction matters. Implemented by specifying atakeProfitPrice
parameter (for the take profit triggerPrice).
Suppose you entered a long position (you bought) at 1000 and want to get your profits from a possible price pump above 1300. You would place a take profit order with triggerPrice at 1300. For that take profit order either you would specify a limit price or it will be executed at market price.
| price | amount----|---------------- | 1500 | 200 | 1400 | 300 <------------------------------------------------------------------------------+ a | 1300 | 100 <--- it will close your position at market price above 1300 | s | 1200 | 200 when your takeProfitPrice is reached from below | k | 1100 | 300 or it will be executed at your limit price higher than your takeProfitPrice -+ | 1000 | 100 <- you bought to enter a long position here at 1000 | 900 | 100----|---------------- last price is 900 | 800 | 100 | 700 | 200 b | 600 | 100 i | 500 | 300 d | 400 | 200 | 300 | 100 | 200 | 100
Suppose you entered a short position (you sold) at 700 and want to get your profits from a possible price drop below 600. You would place a take profit order with triggerPrice at 600. For that take profit order either you would specify a limit price or it will be executed at market price.
| price | amount----|---------------- | 1500 | 200 | 1400 | 300 a | 1300 | 100 s | 1200 | 200 k | 1100 | 300 | 1000 | 100 | 900 | 100----|---------------- last price is 900 (you sold at 700) | 800 | 100 | 700 | 200 <--- you sold to enter a short position here at 700 b | 600 | 100 <------ you place a take profit order here at 600 i | 500 | 300 when your takeProfitPrice is reached from above d | 400 | 200 it will be close your position at market price below 600 | 300 | 100 <- or it will be executed at your limit price lower than your takeProfitPrice | 200 | 100
Take Profit orders are activated when the price of the underlying:
- rises above the
takeProfitPrice
from below, for sell orders (eg: to close a long position, at a profit) - drops below the
takeProfitPrice
from above, for buy orders (eg: to close a short position, at a profit)
// for a take profit orderconstparams={'takeProfitPrice':120.45,// your take profit price}constorder=awaitexchange.createOrder(symbol,type,side,amount,price,params)
# for a take profit orderparams= {'takeProfitPrice':120.45,# your take profit price}order=exchange.create_order (symbol,type,side,amount,price,params)
// for a take profit order$params = {'takeProfitPrice':120.45,// your take profit price}$order =$exchange->create_order ($symbol,$type,$side,$amount,$price,$params);
Take Profit /Stop Loss Orders which are tied to a position-opening primary order. Implemented by supplying a dictionary parameters forstopLoss
andtakeProfit
describing each respectively.
- By default stopLoss and takeProfit orders will be the same magnitude as primary order but in the opposite direction.
- Attached trigger orders are conditional on the primary order being executed.
- Not supported by all exchanges.
- Both
stopLoss
andtakeProfit
or either can be supplied, this depends on exchange.
Note: This is still under unification and is work in progress
constparams={'stopLoss':{'triggerPrice':12.34,// at what price it will trigger'price':12.00,// if exchange supports, 'price' param would be limit price (for market orders, don't include this param)},'takeProfit':{// similar params here}}constorder=awaitexchange.createOrder('SOL/USDT','limit','buy',0.5,13,params)
params= {'stopLoss': {'triggerPrice':12.34,# at what price it will trigger'price':12.00,# if exchange supports, 'price' param would be limit price (for market orders, don't include this param) },'takeProfit': {# similar params here }}order=exchange.create_order ('SOL/USDT','limit','buy',0.5,13,params)
$params = ['stopLoss': ['triggerPrice'=>12.34,// at what price it will trigger'price'=>12.00,// if exchange supports, 'price' param would be limit price (for market orders, don't include this param) ],'takeProfit'=> [// similar params here ]]$order =$exchange->create_order ('SOL/USDT','limit','buy',0.5,13,$params);
For exchanges, where it is not possible to use attached SL &TP, after submitting an entry order, you can immediatelly submit another order (even though position might not be open yet) withtriggerPrice
andreduceOnly: true
params, so it can still act as a stoploss order for your upcoming position (note, this approach might not work for some exchanges).
Trailing Orders trail behind an open position. Implemented by supplying float parameters fortrailingPercent
ortrailingAmount
.
- A trailing order continually adjusts the order price at a fixed percent or fixed quote amount away from the current market price.
- A trailing order trails behind a position as it moves in one direction, but not in the opposite direction.
- If the position value rises, the trailing order changes, but if the position value drops the trailing order stays the same until the order is executed.
- A trailing order can be placed independently after opening a position.
- Implemented by filling in either the
trailingPercent
ortrailingAmount
parameter depending on the exchange. - The price argument can be used as the
trailingTriggerPrice
, and the type argument can be used to differentiate between limit and market trailing orders if needed.
Not supported by all exchanges.
Note: This is still under unification and is a work in progress
symbol='BTC/USDT:USDT';type='market';side='sell';amount=1.0;price=undefined;constparams={'trailingPercent':1.0,// percentage away from the current market price 1.0 is equal to 1%// 'trailingAmount': 100.0, // quote amount away from the current market price// 'trailingTriggerPrice': 44500.0, // the price to trigger activating a trailing stop order// 'reduceOnly': true, // set to true if you want to close a position, set to false if you want to open a new position}constorder=awaitexchange.createOrder(symbol,type,side,amount,price,params)
symbol='BTC/USDT:USDT'type='market'side='sell'amount=1.0price=Noneparams= {'trailingPercent':1.0,# percentage away from the current market price 1.0 is equal to 1%# 'trailingAmount': 100.0, # quote amount away from the current market price# 'trailingTriggerPrice': 44500.0, # the price to trigger activating a trailing stop order# 'reduceOnly': True, # set to True if you want to close a position, set to False if you want to open a new position}order=exchange.create_order (symbol,type,side,amount,price,params)
$symbol ='BTC/USDT:USDT';$type ='market';$side ='sell';$amount =1.0;$price =null;$params = {'trailingPercent':1.0,// percentage away from the current market price 1.0 is equal to 1%// 'trailingAmount': 100.0, // quote amount away from the current market price// 'trailingTriggerPrice': 44500.0, // the price to trigger activating a trailing stop order// 'reduceOnly': true, // set to true if you want to close a position, set to false if you want to open a new position}$order =$exchange->create_order ($symbol,$type,$side,$amount,$price,$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 theparams
argument to your unified API call. All custom params are exchange-specific, of course, and aren't interchangeable, do not expect those custom params for one exchange to work with another exchange.
// use a custom order typebitfinex.createLimitSellOrder('BTC/USD',1,10,{'type':'trailing-stop'})
# add a custom order flagkraken.create_market_buy_order('BTC/USD',1, {'trading_agreement':'agree'})
// add custom user id to your order$hitbtc->create_order ('BTC/USD','limit','buy',1,3000,array ('clientOrderId' =>'123'));
- this part of the unified API is currenty a work in progress- there may be some issues and missing implementations here and there- contributions, pull requests and feedback appreciated
The user can specify a customclientOrderId
field can be set upon placing orders with theparams
. Using theclientOrderId
one can later distinguish between own orders. This is only available for the exchanges that do supportclientOrderId
at this time. For the exchanges that don't support it will either throw an error upon supplying theclientOrderId
or will ignore it setting theclientOrderId
toundefined/None/null
.
exchange.createOrder(symbol,type,side,amount,price,{'clientOrderId':'Hello',})
exchange.create_order(symbol,type,side,amount,price, {'clientOrderId':'World',})
$exchange->create_order($symbol,$type,$side,$amount,$price,array('clientOrderId' =>'Foobar',))
If exchange supportsfeature forhedged
orders, user can passparams['hedged'] = true
increateOrder
to open ahedged
position instead of defaultone-way
mode order. However, if exchange supports.has['setPositionMode']
then those exchanges might not supporthedged
param directly throughcreateOrder
, instead on such exchange you need to change teh account-mode at first usingsetPositionMode() and then runcreateOrder
(withouthedged
param) and it will place hedged order by default.
To edit an order, you can use theeditOrder
method
editOrder(id,symbol,type,side,amount,price=undefined,params={})
Parameters
- id (String)required Order id (e.g.
1645807945000
) - symbol (String)required Unified CCXT market symbol
- side (String)required the direction of your order.Unified sides:
buy
give quote currency and receive base currency; for example, buyingBTC/USD
means that you will receive bitcoins for your dollars.sell
give base currency and receive quote currency; for example, buyingBTC/USD
means that you will receive dollars for your bitcoins.
- type (String)required type of orderUnified types:
market
not allowed by some exchanges, seetheir docs for detailslimit
- see #custom-order-params and #other-order-types for non-unified types
- amount (Number)required how much of currency you want to trade usually, but not always, in units of the base currency of the trading pair symbol (the units for some exchanges are dependent on the side of the order: see their API docs for details.)
- price (Float) the price at which the order is to be fullfilled at in units of the quote currency (ignored in market orders)
- params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"settle": "usdt"}
)
Returns
To cancel an existing order use
cancelOrder ()
for a single ordercancelOrders ()
for multiple orderscancelAllOrders ()
for all open orderscancelAllOrdersAfter ()
for all open orders after the given timeout
cancelOrder(id,symbol=undefined,params={})
Parameters
- id (String)required Order id (e.g.
1645807945000
) - symbol (String) Unified CCXT market symbolrequired on some exchanges (e.g.
"BTC/USDT"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"settle": "usdt"}
)
Returns
cancelOrders(ids,symbol=undefined,params={})
Parameters
- ids ([String])required Order ids (e.g.
1645807945000
) - symbol (String) Unified CCXT market symbolrequired on some exchanges (e.g.
"BTC/USDT"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"settle": "usdt"}
)
Returns
- An array oforder structures
asynccancelAllOrders(symbol=undefined,params={})
Parameters
- symbol (String) Unified CCXT market symbolrequired on some exchanges (e.g.
"BTC/USDT"
) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"settle": "usdt"}
)
Returns
- An array oforder structures
asynccancelAllOrdersAfter(timeout,params={})
Parameters
- timeout (number) countdown time in millisecondsrequired on some exchanges, 0 represents cancel the timer (e.g.
10
\ ) - params (Dictionary) Extra parameters specific to the exchange API endpoint (e.g.
{"type": "spot"}
\ )
Returns
- An object
ThecancelOrder()
is usually used on open orders only. However, it may happen that your order gets executed (filled and closed)before your cancel-request comes in, so a cancel-request might hit an already-closed order.
A cancel-request might also throw aOperationFailed
indicating that the order might or might not have been canceled successfully and whether you need to retry or not. Consecutive calls tocancelOrder()
may hit an already canceled order as well.
As such,cancelOrder()
can throw anOrderNotFound
exception in these cases:
- canceling an already-closed order
- canceling an already-canceled order
- this part of the unified API is currenty a work in progress- there may be some issues and missing implementations here and there- contributions, pull requests and feedback appreciated
A trade is also often calleda fill
. Each trade is a result of order execution. Note, that orders and trades have a one-to-many relationship: an execution of one order may result in several trades. However, when one order matches another opposing order, the pair of two matching orders yields one trade. Thus, when an order matches multiple opposing orders, this yields multiple trades, one trade per each pair of matched orders.
To put it shortly, an order can containone or more trades. Or, in other words, an order can befilled with one or more trades.
For example, an orderbook can have the following orders (whatever trading symbol or pair it is):
| price | amount----|---------------- a | 1.200 | 200 s | 1.100 | 300 k | 0.900 | 100----|---------------- b | 0.800 | 100 i | 0.700 | 200 d | 0.500 | 100
All specific numbers above aren't real, this is just to illustrate the way orders and trades are related in general.
A seller decides to place a sell limit order on the ask side for a price of 0.700 and an amount of 150.
| price | amount----|---------------- ↓ a | 1.200 | 200 ↓ s | 1.100 | 300 ↓ k | 0.900 | 100 ↓----|---------------- ↓ b | 0.800 | 100 ↓ sell 150 for 0.700 i | 0.700 | 200 -------------------- d | 0.500 | 100
As the price and amount of the incoming sell (ask) order cover more than one bid order (ordersb
andi
), the following sequence of events usually happens within an exchange engine very quickly, but not immediately:
Order
b
is matched against the incoming sell because their prices intersect. Their volumes"mutually annihilate" each other, so, the bidder gets 100 for a price of 0.800. The seller (asker) will have their sell order partially filled by bid volume 100 for a price of 0.800. Note that for the filled part of the order the seller gets a better price than he asked for initially. He asked for 0.7 at least but got 0.8 instead which is even better for the seller. Most conventional exchanges fill orders for the best price available.A trade is generated for the order
b
against the incoming sell order. That trade"fills" the entire orderb
and most of the sell order. One trade is generated per each pair of matched orders, whether the amount was filled completely or partially. In this example the seller amount (100) fills orderb
completely (closes the orderb
) and also fills the selling order partially (leaves it open in the orderbook).Order
b
now has a status ofclosed
and a filled volume of 100. It contains one trade against the selling order. The selling order has anopen
status and a filled volume of 100. It contains one trade against orderb
. Thus each order has just one fill-trade so far.The incoming sell order has a filled amount of 100 and has yet to fill the remaining amount of 50 from its initial amount of 150 in total.
The intermediate state of the orderbook is now (orderb
isclosed
and is not in the orderbook anymore):
| price | amount----|---------------- ↓ a | 1.200 | 200 ↓ s | 1.100 | 300 ↓ k | 0.900 | 100 ↓----|---------------- ↓ sell remaining 50 for 0.700 i | 0.700 | 200 ----------------------------- d | 0.500 | 100
Order
i
is matched against the remaining part of incoming sell, because their prices intersect. The amount of buying orderi
which is 200 completely annihilates the remaining sell amount of 50. The orderi
is filled partially by 50, but the rest of its volume, namely the remaining amount of 150 will stay in the orderbook. The selling order, however, is fulfilled completely by this second match.A trade is generated for the order
i
against the incoming sell order. That trade partially fills orderi
. And completes the filling of the sell order. Again, this is just one trade for a pair of matched orders.Order
i
now has a status ofopen
, a filled amount of 50, and a remaining amount of 150. It contains one filling trade against the selling order. The selling order has aclosed
status now and it has completely filled its total initial amount of 150. However, it contains two trades, the first against orderb
and the second against orderi
. Thus each order can have one or more filling trades, depending on how their volumes were matched by the exchange engine.
After the above sequence takes place, the updated orderbook will look like this.
| price | amount----|---------------- a | 1.200 | 200 s | 1.100 | 300 k | 0.900 | 100----|---------------- i | 0.700 | 150 d | 0.500 | 100
Notice that the orderb
has disappeared, the selling order also isn't there. All closed and fully-filled orders disappear from the orderbook. The orderi
which was filled partially and still has a remaining volume and anopen
status, is still there.
Most of unified methods will return either a single object or a plain array (a list) of objects (trades). However, very few exchanges (if any at all) will return all trades at once. Most often their APIslimit
output to a certain number of most recent objects.YOU CANNOT GET ALL OBJECTS SINCE THE BEGINNING OF TIME TO THE PRESENT MOMENT IN JUST ONE CALL. Practically, very few exchanges will tolerate or allow that.
As with all other unified methods for fetching historical data, thefetchMyTrades
method accepts asince
argument fordate-based pagination. Just like with all other unified methods throughout the CCXT library, thesince
argument forfetchMyTrades
must be aninteger timestamp in milliseconds.
To fetch historical trades, the user will need to traverse the data in portions or "pages" of objects. Pagination often implies"fetching portions of data one by one" in a loop.
In many cases asymbol
argument is required by the exchanges' APIs, therefore you have to loop over all symbols to get all your trades. If thesymbol
is missing and the exchange requires it then CCXT will throw anArgumentsRequired
exception to signal the requirement to the user. And then thesymbol
has to be specified. One of the approaches is to filter the relevant symbols from the list of all symbols by looking at non-zero balances as well as transactions (withdrawals and deposits). Also, the exchanges will have a limit on how far back in time you can go.
In most cases users arerequired to use at least some type ofpagination in order to get the expected results consistently.
// fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {})if(exchange.has['fetchMyTrades']){consttrades=awaitexchange.fetchMyTrades(symbol,since,limit,params)}
# fetch_my_trades(symbol=None, since=None, limit=None, params={})ifexchange.has['fetchMyTrades']:exchange.fetch_my_trades(symbol=None,since=None,limit=None,params={})
// fetch_my_trades($symbol = null, $since = null, $limit = null, $params = array())if ($exchange->has['fetchMyTrades']) {$trades =$exchange->fetch_my_trades($symbol,$since,$limit,$params);}
Returns ordered array[]
of trades (most recent trade last).
Trades denote the exchange of one currency for another, unliketransactions, which denote a transfer of a given coin.
{'info':{ ...},// the original decoded JSON as is'id':'12345-67890:09876/54321',// string trade id'timestamp':1502962946216,// Unix timestamp in milliseconds'datetime':'2017-08-17 12:42:48.000',// ISO8601 datetime with milliseconds'symbol':'ETH/BTC',// symbol'order':'12345-67890:09876/54321',// string order id or undefined/None/null'type':'limit',// order type, 'market', 'limit' or undefined/None/null'side':'buy',// direction of the trade, 'buy' or 'sell''takerOrMaker':'taker',// string, 'taker' or 'maker''price':0.06917684,// float price in quote currency'amount':1.5,// amount of base currency'cost':0.10376526,// total cost, `price * amount`,'fee':{// provided by exchange or calculated by ccxt'cost':0.0015,// float'currency':'ETH',// usually base currency for buys, quote currency for sells'rate':0.002,// the fee rate (if available)},'fees':[// an array of fees if paid in multiple currencies{// if provided by exchange or calculated by ccxt'cost':0.0015,// float'currency':'ETH',// usually base currency for buys, quote currency for sells'rate':0.002,// the fee rate (if available)},],}
- The work on
'fee'
and'fees'
info is still in progress, fee info may be missing partially or entirely, depending on the exchange capabilities. - The
fee
currency may be different from both traded currencies (for example, an ETH/BTC order with fees in USD). - The
cost
of the trade meansamount * price
. It is the totalquote volume of the trade (whereasamount
is thebase volume). The cost field itself is there mostly for convenience and can be deduced from other fields. - The
cost
of the trade is a"gross" value. That is the value pre-fee, and the fee has to be applied afterwards.
// fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {})if(exchange.has['fetchOrderTrades']){consttrades=awaitexchange.fetchOrderTrades(orderId,symbol,since,limit,params)}
# fetch_order_trades(id, symbol=None, since=None, limit=None, params={})ifexchange.has['fetchOrderTrades']:exchange.fetch_order_trades(order_id,symbol=None,since=None,limit=None,params={})
// fetch_order_trades ($id, $symbol = null, $since = null, $limit = null, $params = array())if ($exchange->has['fetchOrderTrades']) {$trades =$exchange->fetch_order_trades($order_id,$symbol,$since,$limit,$params);}
The ledger is simply the history of changes, actions done by the user or operations that altered the user's balance in any way, that is, the history of movements of all funds from/to all accounts of the user which includes
- deposits and withdrawals (funding)
- amounts incoming and outcoming in result of a trade or an order
- trading fees
- transfers between accounts
- rebates, cashbacks and other types of events that are subject to accounting.
Data on ledger entries can be retrieved using
fetchLedgerEntry ()
for a ledger entryfetchLedger ( code )
for multiple ledger entries of the same currencyfetchLedger ()
for all ledger entries
fetchLedgerEntry(id,code=undefined,params={})
Parameters
- id (String)required Ledger entry id
- code (String) Unified CCXT currency code, required (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"type": "deposit"}
)
Returns
asyncfetchLedger(code=undefined,since=undefined,limit=undefined,params={})
Parameters
- code (String) Unified CCXT currency code;required if fetching all ledger entries for all assets at once is not supported (e.g.
"USDT"
) - since (Integer) Timestamp (ms) of the earliest time to retrieve withdrawals for (e.g.
1646940314000
) - limit (Integer) The number ofledger entry structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array ofledger entry structures
{'id':'hqfl-f125f9l2c9',// string id of the ledger entry, e.g. an order id'direction':'out',// or 'in''account':'06d4ab58-dfcd-468a',// string id of the account if any'referenceId':'bf7a-d4441fb3fd31',// string id of the trade, transaction, etc...'referenceAccount':'3146-4286-bb71',// string id of the opposite account (if any)'type':'trade',// string, reference type, see below'currency':'BTC',// string, unified currency code, 'ETH', 'USDT'...'amount':123.45,// absolute number, float (does not include the fee)'timestamp':1544582941735,// milliseconds since epoch time in UTC'datetime':"2018-12-12T02:49:01.735Z",// string of timestamp, ISO8601'before':0,// amount of currency on balance before'after':0,// amount of currency on balance after'status':'ok',// 'ok, 'pending', 'canceled''fee':{// object or undefined'cost':54.321,// absolute number on top of the amount'currency':'ETH',// string, unified currency code, 'ETH', 'USDT'...},'info':{ ...},// raw ledger entry as is from the exchange}
The type of the ledger entry is the type of the operation associated with it. If the amount comes due to a sell order, then it is associated with a corresponding trade type ledger entry, and the referenceId will contain associated trade id (if the exchange in question provides it). If the amount comes out due to a withdrawal, then is associated with a corresponding transaction.
trade
transaction
fee
rebate
cashback
referral
transfer
airdrop
whatever
- ...
ThereferenceId
field holds the id of the corresponding event that was registered by adding a new item to the ledger.
Thestatus
field is there to support for exchanges that include pending and canceled changes in the ledger. The ledger naturally represents the actual changes that have taken place, therefore the status is'ok'
in most cases.
The ledger entry type can be associated with a regular trade or a funding transaction (deposit or withdrawal) or an internaltransfer
between two accounts of the same user. If the ledger entry is associated with an internal transfer, theaccount
field will contain the id of the account that is being altered with the ledger entry in question. ThereferenceAccount
field will contain the id of the opposite account the funds are transferred to/from, depending on thedirection
('in'
or'out'
).
In order to deposit cryptocurrency funds to an exchange you must get an address from the exchange for the currency you want to deposit usingfetchDepositAddress
. You can then call thewithdraw
method with the specified currency and address.
To deposit fiat currency on an exchange you can use thedeposit
method with data retrieved from thefetchDepositMethodId
method.this deposit feature is currently supported on coinbase only, feel free to report any issues you find
deposit ()
deposit(id,code=undefined,params={})
Parameters
- id (String)required Deposit id
- code (String) Fiat currency code, required (e.g.
"USD"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"account": "fiat"}
)
Returns
fetchDepositMethodId ()
fetchDepositMethodId(id,params={})
Parameters
- id (String)required Deposit id
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"account": "fiat"}
)
Returns
fetchDepositMethodIds ()
fetchDepositMethodIds(params={})
Parameters
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"account": "fiat"}
)
Returns
- An array ofdeposit id structures
The deposit id structure returned fromfetchDepositMethodId
,fetchDepositMethodIds
look like this:
{'info':{},// raw unparsed data as returned from the exchange'id':'75ab52ff-f25t',// the deposit id'currency':'USD',// fiat currency'verified':true,// whether funding through this id is verified or not'tag':'from credit card',// tag / memo / name of funding source}
Data on deposits made to an account can be retrieved using
fetchDeposit ()
for a single depositfetchDeposits ( code )
for multiple deposits of the same currencyfetchDeposits ()
for all deposits to an account
fetchDeposit(id,code=undefined,params={})
Parameters
- id (String)required Deposit id
- code (String) Unified CCXT currency code, required (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"network": "TRX"}
)
Returns
fetchDeposits(code=undefined,since=undefined,limit=undefined,params={})
Parameters
- code (String) Unified CCXT currency code (e.g.
"USDT"
) - since (Integer) Timestamp (ms) of the earliest time to retrieve deposits for (e.g.
1646940314000
) - limit (Integer) The number oftransaction structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array oftransaction structures
Thewithdraw
method can be used to withdraw funds from an account
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. Seetheir docs for details.
withdraw(code,amount,address,tag=undefined,params={})
withdraw(code,amount,address,tag=None,params={})
withdraw ($code,$amount,$address,$tag =null,$params =array ())
Parameters
- code (String)required Unified CCXT currency code (e.g.
"USDT"
) - amount (Float)required The amount of currency to withdraw (e.g.
20
) - address (String)required The recipient address of the withdrawal (e.g.
"TEY6qjnKDyyq5jDc3DJizWLCdUySrpQ4yp"
) - tag (String) Required for some networks (e.g.
"52055"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"network": "TRX"}
)
Returns
Data on withdrawals made to an account can be retrieved using
fetchWithdrawal ()
for a single withdrawalfetchWithdrawals ( code )
for multiple withdrawals of the same currencyfetchWithdrawals ()
for all withdrawals from an account
fetchWithdrawal(id,code=undefined,params={})
Parameters
- id (String)required Withdrawal id
- code (String) Unified CCXT currency code (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"network": "TRX"}
)
fetchWithdrawals(code=undefined,since=undefined,limit=undefined,params={})
Parameters
- code (String) Unified CCXT currency code (e.g.
"USDT"
) - since (Integer) Timestamp (ms) of the earliest time to retrieve withdrawals for (e.g.
1646940314000
) - limit (Integer) The number oftransaction structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array oftransaction structures
It is also possible to pass the parameters as the fourth argument with or without a specified tag
withdraw(code,amount,address,{ tag,network:'ETH'})
withdraw(code,amount,address, {'tag':tag,'network':'ETH' })
withdraw ($code,$amount,$address,array('tag' => tag,'network' ->'ETH' ));
The following aliases ofnetwork
allow for withdrawing crypto on multiple chains
Currency | Network |
---|---|
ETH | ERC20 |
TRX | TRC20 |
BSC | BEP20 |
BNB | BEP2 |
HT | HECO |
OMNI | OMNI |
You may set the value ofexchange.withdraw ('USDT', 100, 'TVJ1fwyJ1a8JbtUxZ8Km95sDFN9jhLxJ2D', { 'network': 'TRX' })
in order to withdraw USDT on the TRON chain, or 'BSC' to withdraw USDT on Binance Smart Chain. In the table above BSC and BEP20 are equivalent aliases, so it doesn't matter which one you use as they both will achieve the same effect.
Transactions denote a transfer of a given coin, unliketrades, which denote the exchange of one currency for another.
- deposit structure
- withdrawal structure
{'info':{ ...},// the JSON response from the exchange as is'id':'123456',// exchange-specific transaction id, string'txid':'0x68bfb29821c50ca35ef3762f887fd3211e4405aba1a94e448a4f218b850358f0','timestamp':1534081184515,// timestamp in milliseconds'datetime':'2018-08-12T13:39:44.515Z',// ISO8601 string of the timestamp'addressFrom':'0x38b1F8644ED1Dbd5DcAedb3610301Bf5fa640D6f',// sender'address':'0x02b0a9b7b4cDe774af0f8e47cb4f1c2ccdEa0806',// "from" or "to"'addressTo':'0x304C68D441EF7EB0E2c056E836E8293BD28F8129',// receiver'tagFrom','0xabcdef',// "tag" or "memo" or "payment_id" associated with the sender'tag':'0xabcdef'// "tag" or "memo" or "payment_id" associated with the address'tagTo':'0xhijgklmn',// "tag" or "memo" or "payment_id" associated with the receiver'type':'deposit',// 'withdrawal' or 'transfer', string'amount':1.2345,// float (does not include the fee)'currency':'ETH',// a common unified currency code, string'status':'pending',// 'ok', 'failed', 'canceled', string'updated':undefined,// UTC timestamp of most recent status change in ms'comment':'a comment or message defined by the user if any','fee':{// the entire fee structure may be undefined'currency':'ETH',// a unified fee currency code'cost':0.1234,// float'rate':undefined,// approximately, fee['cost'] / amount, float},}
addressFrom
oraddressTo
may beundefined/None/null
, if the exchange in question does not specify all sides of the transaction- The semantics of the
address
field is exchange-specific. In some cases it can contain the address of the sender, in other cases it may contain the address of the receiver. The actual value depends on the exchange. - The
updated
field is the UTC timestamp in milliseconds of the most recent change of status of that funding operation, be itwithdrawal
ordeposit
. It is necessary if you want to track your changes in time, beyond a static snapshot. For example, if the exchange in question reportscreated_at
andconfirmed_at
for a transaction, then theupdated
field will take the value ofMath.max (created_at, confirmed_at)
, that is, the timestamp of the most recent change of the status. - The
updated
field may beundefined/None/null
in certain exchange-specific cases. - The
fee
substructure may be missing, if not supplied within the reply coming from the exchange. - The
comment
field may beundefined/None/null
, otherwise it will contain a message or note defined by the user upon creating the transaction. - Be careful when handling the
tag
and theaddress
. Thetag
isNOT an arbitrary user-defined string of your choice! You cannot send user messages and comments in thetag
. The purpose of thetag
field is to address your wallet properly, so it must be correct. You should only use thetag
received from the exchange you're working with, otherwise your transaction might never arrive to its destination. - The
type
field may bedeposit/withdrawal
or, in some cases (when the exchange's endpoint returns both internal transfers and blockchain transactions, e.g.ccxt.coinlist
), could betransfer
.
// fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {})if(exchange.has['fetchDeposits']){constdeposits=awaitexchange.fetchDeposits(code,since,limit,params)}else{thrownewError(exchange.id+' does not have the fetchDeposits method')}
# fetch_deposits(code = None, since = None, limit = None, params = {})ifexchange.has['fetchDeposits']:deposits=exchange.fetch_deposits(code,since,limit,params)else:raiseException (exchange.id+' does not have the fetch_deposits method')
// fetch_deposits ($code = null, $since = null, $limit = null, $params = {})if ($exchange->has['fetchDeposits']) {$deposits =$exchange->fetch_deposits ($code,$since,$limit,$params);}else {thrownewException ($exchange->id .' does not have the fetch_deposits method');}
// fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {})if(exchange.has['fetchWithdrawals']){constwithdrawals=awaitexchange.fetchWithdrawals(code,since,limit,params)}else{thrownewError(exchange.id+' does not have the fetchWithdrawals method')}
# fetch_withdrawals(code = None, since = None, limit = None, params = {})ifexchange.has['fetchWithdrawals']:withdrawals=exchange.fetch_withdrawals(code,since,limit,params)else:raiseException (exchange.id+' does not have the fetch_withdrawals method')
// fetch_withdrawals ($code = null, $since = null, $limit = null, $params = {})if ($exchange->has['fetchWithdrawals']) {$withdrawals =$exchange->fetch_withdrawals ($code,$since,$limit,$params);}else {thrownewException ($exchange->id .' does not have the fetch_withdrawals method');}
// fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {})if(exchange.has['fetchTransactions']){consttransactions=awaitexchange.fetchTransactions(code,since,limit,params)}else{thrownewError(exchange.id+' does not have the fetchTransactions method')}
# fetch_transactions(code = None, since = None, limit = None, params = {})ifexchange.has['fetchTransactions']:transactions=exchange.fetch_transactions(code,since,limit,params)else:raiseException (exchange.id+' does not have the fetch_transactions method')
// fetch_transactions ($code = null, $since = null, $limit = null, $params = {})if ($exchange->has['fetchTransactions']) {$transactions =$exchange->fetch_transactions ($code,$since,$limit,$params);}else {thrownewException ($exchange->id .' does not have the fetch_transactions method');}
The address for depositing can be either an already existing address that was created previously with the exchange or it can be created upon request. In order to see which of the two methods are supported, check theexchange.has['fetchDepositAddress']
andexchange.has['createDepositAddress']
properties.
fetchDepositAddress(code,params={})createDepositAddress(code,params={})
Parameters
- code (String)required Unified CCXT currency code (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
Some exchanges may also have a method for fetching multiple deposit addresses at once or all of them at once.
fetchDepositAddresses(codes=undefined,params={})
Parameters
- code ([String]) Array of unified CCXT currency codes. May or may not be required depending on the exchange (e.g.
["USDT", "BTC"]
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- an array ofaddress structures
fetchDepositAddressesByNetwork(code,params={})
Parameters
- code (String)required Unified CCXT currency code (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- an array ofaddress structures
The address structures returned fromfetchDepositAddress
,fetchDepositAddresses
,fetchDepositAddressesByNetwork
andcreateDepositAddress
look like this:
{'info':response,// raw unparsed data as returned from the exchange'currency':'USDC',// currency code'network':'ERC20',// a deposit/withdraw networks, ERC20, TRC20, BSC20 (see below)'address':'0x',// blockchain address in terms of the requested currency and network'tag':undefined,// tag / memo / paymentId for particular currencies (XRP, XMR, ...)}
With certain currencies, like AEON, BTS, GXS, NXT, SBD, STEEM, STR, XEM, XLM, XMR, XRP, an additional argumenttag
is usually required by exchanges. Other currencies will have thetag
set toundefined / None / null
. The tag is a memo or a message or a payment id that is attached to a withdrawal transaction. The tag is mandatory for those currencies and it identifies the recipient user account.
Be careful when specifying thetag
and theaddress
. Thetag
isNOT an arbitrary user-defined string of your choice! You cannot send user messages and comments in thetag
. The purpose of thetag
field is to address your wallet properly, so it must be correct. You should only use thetag
received from the exchange you're working with, otherwise your transaction might never arrive to its destination.
Thenetwork
field is relatively new, it may beundefined / None / null
or missing entirely in certain cases (with some exchanges), but will be added everywhere eventually. It is still in the process of unification.
Thetransfer
method makes internal transfers of funds between accounts on the same exchange. This can include subaccounts or accounts of different types (spot
,margin
,future
, ...). If an exchange is separated on CCXT into a spot and futures class (e.g.binanceusdm
,kucoinfutures
, ...), then the methodtransferIn
may be available to transfer funds into the futures account, and the methodtransferOut
may be available to transfer funds out of the futures account
transfer(code,amount,fromAccount,toAccount,params={})
Parameters
- code (String) Unified CCXT currency code (e.g.
"USDT"
) - amount (Float) The amount of currency to transfer (e.g.
10.5
) - fromAccount (String) The account to transfer funds from.
- toAccount (String) The account to transfer funds to.
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
) - params.symbol (String) Market symbol when transfering to or from a margin account (e.g.
'BTC/USDT'
)
fromAccount
andtoAccount
can accept the exchange account id or one of the following unified values:
funding
for some exchangesfunding
andspot
are the same accountmain
for some exchanges that allow for subaccountsspot
margin
future
swap
lending
You can retrieve all the account types by selecting the keys from `exchange.options['accountsByType']
Some exchanges allow transfers to email addresses, phone numbers or to other users by user id.
Returns
transferIn(code,amount,params={})transferOut(code,amount,params={})
Parameters
- code (String) Unified CCXT currency code (e.g.
"USDT"
) - amount (Float) The amount of currency to transfer (e.g.
10.5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
fetchTransfers(code=undefined,since=undefined,limit=undefined,params={})
Parameters
- code (String) Unified CCXT currency code (e.g.
"USDT"
) - since (Integer) Timestamp (ms) of the earliest time to retrieve transfers for (e.g.
1646940314000
) - limit (Integer) The number oftransfer structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array oftransfer structures
fetchTransfer(id,since=undefined,limit=undefined,params={})
Parameters
- id (String) tranfer id (e.g.
"12345"
) - since (Integer) Timestamp (ms) of the earliest time to retrieve transfers for (e.g.
1646940314000
) - limit (Integer) The number oftransfer structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
{info:{ ...},id:"93920432048",timestamp:1646764072000,datetime:"2022-03-08T18:27:52.000Z",currency:"USDT",amount:11.31,fromAccount:"spot",toAccount:"future",status:"ok"}
This section of the Unified CCXT API is under development.
Fees are often grouped into two categories:
- Trading fees. Trading fee is the amount payable to the exchange, usually a percentage of volume traded (filled).
- Transaction fees. The amount payable to the exchange upon depositing and withdrawing as well as the underlying crypto transaction fees (tx fees).
Because the fee structure can depend on the actual volume of currencies traded by the user, the fees can be account-specific. Methods to work with account-specific fees:
fetchTradingFee(symbol,params={})fetchTradingFees(params={})fetchDepositWithdrawFees(codes=undefined,params={})fetchDepositWithdrawFee(code,params={})
The fee methods will return a unified fee structure, which is often present with orders and trades as well. The fee structure is a common format for representing the fee info throughout the library. Fee structures are usually indexed by market or currency.
Because this is still a work in progress, some or all of methods and info described in this section may be missing with this or that exchange.
DO NOT use the.fees
property of the exchange instance as most often it contains the predefined/hardcoded info. Actual fees should only be accessed from markets and currencies.
NOTE: Previously we used fetchTransactionFee(s) to fetch the transaction fees, which are now DEPRECATED and these functions have been replace by fetchDepositWithdrawFee(s)
You callfetchTradingFee
/fetchTradingFees
to fetch the trading fees,fetchDepositWithdrawFee
/fetchDepositWithdrawFees
to fetch the deposit & withdraw fees.
Orders, private trades, transactions and ledger entries may define the following info in theirfee
field:
{'currency':'BTC',// the unified fee currency code'rate':percentage,// the fee rate, 0.05% = 0.0005, 1% = 0.01, ...'cost':feePaid,// the fee cost (amount * fee rate)}
fetchTradingFees(params={})
{'withdraw':{'BTC':0.00001,'ETH':0.001,'LTC':0.0003,},'deposit':{'BTC':0,},'info':{ ...},}
fetchDepositWithdrawFees(codes,params={})
{'BTC':{'withdraw':{'fee':0.0005,'percentage':false},'deposit':{'fee':undefined,'percentage':undefined},'networks':{'BTC':{'deposit':{'fee':undefined,'percentage':undefined},'withdraw':{'fee':0.0005,'percentage':false}}},'info':{ ...},}, ...}
Trading fees are properties of markets. Most often trading fees are loaded into the markets by thefetchMarkets
call. Sometimes, however, the exchanges serve fees from different endpoints.
ThecalculateFee
method can be used to precalculate trading fees that will be paid.WARNING! This method is experimental, unstable and may produce incorrect results in certain cases. You should only use it with caution. Actual fees may be different from the values returned fromcalculateFee
, this is just for precalculation. Do not rely on precalculated values, because market conditions change frequently. It is difficult to know in advance whether your order will be a market taker or maker.
calculateFee(symbol,type,side,amount,price,takerOrMaker='taker',params={})
ThecalculateFee
method will return a unified fee structure with precalculated fees for an order with specified params.
Accessing trading fee rates should be done viafetchTradingFees
which is the recommended approach. If that method is not supported by exchange, then via the.markets
property, like so:
exchange.markets['ETH/BTC']['taker']// taker fee rate for ETH/BTCexchange.markets['BTC/USD']['maker']// maker fee rate for BTC/USD
The markets stored under the.markets
property may contain additional fee related information:
{'taker':0.002,// taker fee rate, 0.002 = 0.2%'maker':0.0016,// maker fee rate, 0.0016 = 0.16%'percentage':true,// whether the taker and maker fee rate is a multiplier or a fixed flat amount'tierBased':false,// whether the fee depends on your trading tier (your trading volume)'tiers':{'taker':[[0,0.0026],// tupple (trade volume in USD, taker fee) ordered by increasing volume[50000,0.0024], ...],'maker':[[0,0.0016],// tupple (trade volume in USD, maker fee) ordered by increasing volume[50000,0.0014], ...],},}
WARNING! fee related information is experimental, unstable and may only be partial available or not at all.
Maker fees are paid when you provide liquidity to the exchange i.e. youmarket-make an order and someone else fills it. Maker fees are usually lower than taker fees. Similarly, taker fees are paid when youtake liquidity from the exchange and fill someone else's order.
Fees can be negative, this is very common amongst derivative exchanges. A negative fee means the exchange will pay a rebate (reward) to the user for the trading.
Also, some exchanges might not specify fees as percentage of volume, check thepercentage
field of the market to be sure.
Some exchanges have an endpoint for fetching the trading fee schedule, this is mapped to the unified methodsfetchTradingFees
, andfetchTradingFee
fetchTradingFee(symbol,params={})
Parameters
- symbol (String)required Unified market symbol (e.g.
"BTC/USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"currency": "quote"}
)
Returns
fetchTradingFees(params={})
Parameters
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"currency": "quote"}
)
Returns
- An array oftrading fee structures
{'ETH/BTC':{'maker':0.001,'taker':0.002,'info':{ ...},'symbol':'ETH/BTC',},'LTC/BTC':{'maker':0.001,'taker':0.002,'info':{ ...},'symbol':'LTC/BTC',},}
Transaction fees are properties of currencies (account balance).
Accessing transaction fee rates should be done via the.currencies
property. This aspect is not unified yet and is subject to change.
exchange.currencies['ETH']['fee']// tx/withdrawal fee rate for ETHexchange.currencies['BTC']['fee']// tx/withdrawal fee rate for BTC
Some exchanges have an endpoint for fetching the transaction fee schedule, this is mapped to the unified methods
fetchTransactionFee ()
for a single transaction fee schedulefetchTransactionFees ()
for all transaction fee schedules
fetchTransactionFee(code,params={})
Parameters
- code (String)required Unified CCXT currency code, required (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"type": "deposit"}
) - params.network (String) Specify unified CCXT network (e.g.
{"network": "TRC20"}
)
Returns
fetchTransactionFees(codes=undefined,params={})
Parameters
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"type": "deposit"}
)
Returns
- An array oftransaction fee structures
{'withdraw':{'BTC':0.00001,'ETH':0.001,'LTC':0.0003,},'deposit':{'BTC':0,},'info':{ ...},}
- margin only
To trade with leverage in spot or margin markets, currency must be borrowed as a loan. This borrowed currency must be payed back with interest. To obtain the amount of interest that has accrued you can use thefetchBorrowInterest
method
fetchBorrowInterest(code=undefined,symbol=undefined,since=undefined,limit=undefined,params={})
Parameters
- code (String) The unified currency code for the currency of the interest (e.g.
"USDT"
) - symbol (String) The market symbol of an isolated margin market, if undefined, the interest for cross margin markets is returned (e.g.
"BTC/USDT:USDT"
) - since (Integer) Timestamp (ms) of the earliest time to receive interest records for (e.g.
1646940314000
) - limit (Integer) The number ofborrow interest structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array ofborrow interest structures
{ info:{ ...}// Unparsed exchange responsesymbol:'BTC/USDT',// The market that the interest was accrued incurrency:'USDT',// The currency of the interestinterest:0.00004842,// The amount of interest that was chargedinterestRate:0.0002,// The borrow interest rateamountBorrowed:5.81,// The amount of currency that was borrowedmarginMode:'cross',// The margin mode of the borrowed amounttimestamp:1648699200000,// The timestamp that the interest was chargeddatetime:'2022-03-31T04:00:00.000Z',// The datetime that the interest was charged}
margin only
To borrow and repay currency as a margin loan useborrowCrossMargin
,borrowIsolatedMargin
,repayCrossMargin
andrepayIsolatedMargin
.
borrowCrossMargin(code,amount,params={})repayCrossMargin(code,amount,params={})
Parameters
- code (String)required The unified currency code for the currency to be borrowed or repaid (e.g.
"USDT"
) - amount (Float)required The amount of margin to borrow or repay (e.g.
20.92
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"rate": 0.002}
)
Returns
borrowIsolatedMargin(symbol,code,amount,params={})repayIsolatedMargin(symbol,code,amount,params={})
Parameters
- symbol (String)required The unified CCXT market symbol of an isolated margin market (e.g.
"BTC/USDT"
) - code (String)required The unified currency code for the currency to be borrowed or repaid (e.g.
"USDT"
) - amount (Float)required The amount of margin to borrow or repay (e.g.
20.92
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"rate": 0.002}
)
Returns
{id:'1234323',// integer, the transaction idcurrency:'USDT',// string, the currency that is borrowed or repaidamount:5.81,// float, the amount of currency that was borrowed or repaidsymbol:'BTC/USDT:USDT',// string, unified market symboltimestamp:1648699200000,// integer, the timestamp of when the transaction was madedatetime:'2022-03-31T04:00:00.000Z',// string, the datetime of when the transaction was madeinfo:{ ...}// Unparsed exchange response}
margin and contract only
Note: through the manual we use term "collateral" which means current margin balance, but do not confuse it with "initial margin" or "maintenance margin":
collateral (current margin balance) = initial margin + realized & unrealized profit
.
For example, when you had opened an isolated position with50$ initial margin and the position has unrealized profit of-15$, then your position'scollateral will be35$. However, if we take that Maintenance Margin requirement (to keep the position open) by exchange hints$25 for that position, then your collateral should not drop below it, otherwise the position will be liquidated.
To increase, reduce or set your margin balance (collateral) in an open leveraged position, useaddMargin
,reduceMargin
andsetMargin
respectively. This is kind of like adjusting the amount of leverage you're using with a position that's already open.
Some scenarios to use these methods include
- if the trade is going against you, you can add margin to, reducing the risk of liquidation
- if your trade is going well you can reduce your position's margin balance and take profits
addMargin(symbol,amount,params={})reduceMargin(symbol,amount,params={})setMargin(symbol,amount,params={})
Parameters
- symbol (String)required Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - amount (String)required Amount of margin to add or reduce (e.g.
20
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"leverage": 5}
)
Returns
You can fetch the history of margin adjustments made using the methods above or automatically by the exchange using the following method
fetchMarginAdjustmentHistory(symbol=undefined,type=undefined,since=undefined,limit=undefined,params={})
Parameters
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - type (String) "add" or "reduce"
- since (Integer) Timestamp (ms) of the earliest time to retrieve margin adjustments for for (e.g.
1646940314000
) - limit (Integer) The number ofmargin structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"auto": true}
)
Returns
{info:{ ...},type:'add',// 'add', 'reduce', 'set'amount:1,// amount added, reduced, or settotal:2,// total margin or undefined if not specified by the exchangecode:'USDT',symbol:'XRP/USDT:USDT',status:'ok'}
margin and contract only
Updates the type of margin used to be either
cross
One account is used to share collateral between markets. Margin is taken from total account balance to avoid liquidation when needed.isolated
Each market, keeps collateral in a separate account
setMarginMode(marginMode,symbol=undefined,params={})
Parameters
- marginMode (String)required the type of margin usedUnified margin types:
"cross"
"isolated"
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
)required on most exchanges. Is not required when the margin mode is not specific to a market - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"leverage": 5}
)
Returns
- response from the exchange
Common reasons for why an exchange might have
exchange.has['setMarginMode']==false
include
- the exchange does not offer leveraged trading
- the exchange only offers one of
cross
orisolated
margin modes, but does not offer both - margin mode must be set using an exchange specific parameter within
params
when usingcreateOrder
Some exchange apis return an error response when a request is sent to set the margin mode to the mode that it is already set to (e.g. Sending a request to set the margin mode tocross
for the marketBTC/USDT:USDT
when the account already hasBTC/USDT:USDT
set to use cross margin). CCXT doesn't see this as an error because the end result is what the user wanted, so the error is suppressed and the error result is returned as an object.
e.g.
{code:-4046,msg:'No need to change margin type.'}
Some methods allow the usage of amarginMode
parameter that can be set to eithercross
orisolated
. This can be useful for specifying themarginMode
directly within the methods params, for use with spot margin or contract markets. To specify a spot margin market, you need to use a unified spot symbol or set the market type to spot, while setting the marginMode parameter tocross
orisolated
.
Create a Spot Margin Order:
Use a unified spot symbol, while setting the marginMode parameter.
constparams={'marginMode':'isolated',// or 'cross'}constorder=awaitexchange.createOrder('ETH/USDT','market','buy',0.1,1500,params)
params= {'marginMode':'isolated',# or 'cross'}order=exchange.create_order ('ETH/USDT','market','buy',0.1,1500,params)
$params = {'marginMode':'isolated',// or 'cross'}$order =$exchange->create_order ('ETH/USDT','market','buy',0.1,1500,$params);
margin and contract only
ThefetchMarginMode()
method can be used to obtain the set margin mode for a market. ThefetchMarginModes()
method can be used to obtain the set margin mode for multiple markets at once.
You can access the set margin mode by using:
fetchMarginMode()
(single symbol)fetchMarginModes([symbol1, symbol2, ...])
(multiple symbols)fetchMarginModes()
(all market symbols)
fetchMarginMode(symbol,params={})
Parameters
- symbol (String)required A unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"subType": "linear"}
)
Returns
fetchMarginModes(symbols=undefined,params={})
Parameters
- symbols ([String]) A list of unified CCXT symbols (e.g.
[ "BTC/USDT:USDT" ]
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"subType": "linear"}
)
Returns
- an array ofmargin-mode-structures
{"info":{ ...}// response from the exchange"symbol":"BTC/USDT:USDT",// unified market symbol"marginMode":"cross",// the margin mode either cross or isolated}
margin and contract only
setLeverage(leverage,symbol=undefined,params={})
Parameters
- leverage (Integer)required The desired leverage
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
)required on most exchanges. Is not required when leverage is not specific to a market (e.g. If leverage is set for the account and not per market) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"marginMode": "cross"}
)
Returns
- response from the exchange
margin and contract only
ThefetchLeverage()
method can be used to obtain the set leverage for a market. ThefetchLeverages()
method can be used to obtain the set leverage for multiple markets at once.
You can access the set leverage by using:
fetchLeverage()
(single symbol)fetchLeverages([symbol1, symbol2, ...])
(multiple symbols)fetchLeverages()
(all market symbols)
fetchLeverage(symbol,params={})
Parameters
- symbol (String)required A unified CCXT symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"marginMode": "cross"}
)
Returns
fetchLeverages(symbols=undefined,params={})
Parameters
- symbols ([String]) A list of unified CCXT symbols (e.g.
[ "BTC/USDT:USDT" ]
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"marginMode": "cross"}
)
Returns
- an array ofleverage-structures
{"info":{ ...}// response from the exchange"symbol":"BTC/USDT:USDT",// unified market symbol"marginMode":"cross",// the margin mode either cross or isolated"longLeverage":100,// the set leverage for a long position"shortLeverage":75,// the set leverage for a short position}
This can include futures with a set expiry date, perpetual swaps with funding payments, and inverse futures or swaps.Information about the positions can be served from different endpoints depending on the exchange.In the case that there are multiple endpoints serving different types of derivatives CCXT will default to just loading the "linear" (as oppose to the "inverse") contracts or the "swap" (as opposed to the "future") contracts.
contract only
To get information about positions currently held in contract markets, use
- fetchPosition () // for a single market
- fetchPositions () // for all positions
- fetchAccountPositions () // TODO
- fetchPositionHistory () // for single historical position
- fetchPositionsHistory () // for historical positions
fetchPosition(symbol,params={})// for a single market
Parameters
- symbol (String)required Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
fetchPositions(symbols=undefined,params={})fetchAccountPositions(symbols=undefined,params={})
Parameters
- symbols ([String]) Unified CCXT market symbols, do not set to retrieve all positions (e.g.
["BTC/USDT:USDT"]
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array ofposition structures
fetchPositionHistory(symbol=undefined,since=undefined,limit=undefined,params={})
Parameters
- symbol ([String]) Unified CCXT market symbols, do not set to retrieve all positions (e.g.
["BTC/USDT:USDT"]
) - since (Integer) Timestamp (ms) of the earliest time to retrieve positions for (e.g.
1646940314000
) - limit (Integer) The number ofposition structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array ofposition structures
{'info':{ ...},// json response returned from the exchange as is'id':'1234323',// string, position id to reference the position, similar to an order id'symbol':'BTC/USD',// uppercase string literal of a pair of currencies'timestamp':1607723554607,// integer unix time since 1st Jan 1970 in milliseconds'datetime':'2020-12-11T21:52:34.607Z',// ISO8601 representation of the unix time above'isolated':true,// boolean, whether or not the position is isolated, as opposed to cross where margin is added automatically'hedged':false,// boolean, whether or not the position is hedged, i.e. if trading in the opposite direction will close this position or make a new one'side':'long',// string, long or short'contracts':5,// float, number of contracts bought, aka the amount or size of the position'contractSize':100,// float, the size of one contract in quote units'entryPrice':20000,// float, the average entry price of the position'markPrice':20050,// float, a price that is used for funding calculations'notional':100000,// float, the value of the position in the settlement currency'leverage':100,// float, the leverage of the position, related to how many contracts you can buy with a given amount of collateral'collateral':5300,// float, the maximum amount of collateral that can be lost, affected by pnl'initialMargin':5000,// float, the amount of collateral that is locked up in this position'maintenanceMargin':1000,// float, the mininum amount of collateral needed to avoid being liquidated'initialMarginPercentage':0.05,// float, the initialMargin as a percentage of the notional'maintenanceMarginPercentage':0.01,// float, the maintenanceMargin as a percentage of the notional'unrealizedPnl':300,// float, the difference between the market price and the entry price times the number of contracts, can be negative'liquidationPrice':19850,// float, the price at which collateral becomes less than maintenanceMargin'marginMode':'cross',// string, can be cross or isolated'percentage':3.32,// float, represents unrealizedPnl / initialMargin * 100}
Positions allow you to borrow money from an exchange to go long or short on an market. Some exchanges require you to pay a funding fee to keep the position open.
When you go long on a position you are betting that the price will be higher in the future and that the price will never be less than theliquidationPrice
.
As the price of the underlying index changes so does the unrealisedPnl and as a consequence the amount of collateral you have left in the position (since you can only close it at market price or worse). At some price you will have zero collateral left, this is called the "bust" or "zero" price. Beyond this point, if the price goes in the opposite direction far enough, the collateral of the position will drop below themaintenanceMargin
. The maintenanceMargin acts as a safety buffer between your position and negative collateral, a scenario where the exchange incurs losses on your behalf. To protect itself the exchange will swiftly liquidate your position if and when this happens. Even if the price returns back above the liquidationPrice you will not get your money back since the exchange sold all thecontracts
you bought at market. In other words the maintenanceMargin is a hidden fee to borrow money.
It is recommended to use themaintenanceMargin
andinitialMargin
instead of themaintenanceMarginPercentage
andinitialMarginPercentage
since these tend to be more accurate. The maintenanceMargin might be calculated from other factors outside of the maintenanceMarginPercentage including the funding rate and taker fees, for example onkucoin.
An inverse contract will allow you to go long or short on BTC/USD by putting up BTC as collateral. Our API for inverse contracts is the same as for linear contracts. The amounts in an inverse contracts are quoted as if they were traded USD/BTC, however the price is still quoted terms of BTC/USD. The formula for the profit and loss of a inverse contract is(1/markPrice - 1/price) * contracts
. The profit and loss and collateral will now be quoted in BTC, and the number of contracts are quoted in USD.
contract only
To quickly close open positions with a market order, use
- closePosition (symbol) // for a single market
- closeAllPositions (symbol) // for all positions
closePosition(symbol:string,side:OrderSide=undefined,params={}):Promise<Order>
Parameters
- symbol (String)required Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - sideoptional a string literal for the direction of your order. Some exchanges require it.Unified sides:
buy
give quote currency and receive base currency; for example, buyingBTC/USD
means that you will receive bitcoins for your dollars.sell
give base currency and receive quote currency; for example, buyingBTC/USD
means that you will receive dollars for your bitcoins.
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
closeAllPositions(params={}):Promise<Position[]>
Parameters
- params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- A list oforder structures
margin and contract only
Method used for setting position mode:
true
- sets tohedged modefalse
- sets toone-way mode
set_position_mode(false,symbol=undefined,params={})
Parameters
- hedged (String)required hedged-mode value:
true
false
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint
Returns
- response from the exchange
It is the price at which theinitialMargin + unrealized = collateral = maintenanceMargin
. The price has gone in the opposite direction of your position to the point where the is only maintenanceMargin collateral left and if it goes any further the position will have negative collateral.
// if long(liquidationPrice-price)*contracts=maintenanceMargin// if short(price-liquidationPrice)*contracts=maintenanceMargin// if inverse long(1/liquidationPrice-1/price)*contracts=maintenanceMargin// if inverse short(1/price-1/liquidationPrice)*contracts=maintenanceMargin
contract only
Perpetual swap (also known as perpetual future) contracts maintain a market price that mirrors the price of the asset they are based on because funding fees are exchanged between traders who hold positions in perpetual swap markets.
If the contract is being traded at a price that is higher than the price of the asset they represent, then traders in long positions pay a funding fee to traders in short positions at specific times of day, which encourages more traders to enter short positions prior to these times.
If the contract is being traded at a price that is lower than the price of the asset they represent, then traders in short positions pay a funding fee to traders in long positions at specific times of day, which encourages more traders to enter long positions prior to these times.
These fees are usually exchanged between traders with no commission going to the exchange
ThefetchFundingHistory
method can be used to retrieve an accounts history of funding fees paid or received
fetchFundingHistory(symbol=undefined,since=undefined,limit=undefined,params={})
Parameters
- symbol (String) Unified CCXT market symbol (e.g.
"BTC/USDT:USDT"
) - since (Integer) Timestamp (ms) of the earliest time to retrieve funding history for (e.g.
1646940314000
) - limit (Integer) The number offunding history structures to retrieve (e.g.
5
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"endTime": 1645807945000}
)
Returns
- An array offunding history structures
{info:{ ...},symbol:"XRP/USDT:USDT",code:"USDT",timestamp:1646954920000,datetime:"2022-03-08T16:00:00.000Z",id:"1520286109858180",amount:-0.027722}
ThefetchConvertQuote
method can be used to retrieve a quote that can be used for a conversion trade.The quote usually needs to be used within a certain timeframe specified by the exchange for the convert trade to execute successfully.
fetchConvertQuote(fromCode,toCode,amount=undefined,params={})
Parameters
- fromCode (String)required The unified currency code for the currency to convert from (e.g.
"USDT"
) - toCode (String)required The unified currency code for the currency to be converted into (e.g.
"USDC"
) - amount (Float) Amount to convert in units of the from currency (e.g.
20.0
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"toAmount": 2.9722}
)
Returns
ThecreateConvertTrade
method can be used to create a conversion trade order using the id retrieved from fetchConvertQuote.The quote usually needs to be used within a certain timeframe specified by the exchange for the convert trade to execute successfully.
createConvertTrade(id,fromCode,toCode,amount=undefined,params={})
Parameters
- id (String)required Conversion quote id (e.g.
1645807945000
) - fromCode (String)required The unified currency code for the currency to convert from (e.g.
"USDT"
) - toCode (String)required The unified currency code for the currency to be converted into (e.g.
"USDC"
) - amount (Float) Amount to convert in units of the from currency (e.g.
20.0
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"toAmount": 2.9722}
)
Returns
ThefetchConvertTrade
method can be used to fetch a specific conversion trade using the trades id.
fetchConvertTrade(id,code=undefined,params={})
Parameters
- id (String)required Conversion trade id (e.g.
"80794187SDHJ25"
) - code (String) The unified currency code of the conversion trade (e.g.
"USDT"
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"toAmount": 2.9722}
)
Returns
ThefetchConvertTradeHistory
method can be used to fetch the conversion history for a specified currency code.
fetchConvertTradeHistory(code=undefined,since=undefined,limit=undefined,params={})
Parameters
- code (String) The unified currency code to fetch conversion trade history for (e.g.
"USDT"
) - since (Integer) Timestamp of the earliest conversion (e.g.
1645807945000
) - limit (Integer) The maximum number of conversion structures to retrieve (e.g.
10
) - params (Dictionary) Parameters specific to the exchange API endpoint (e.g.
{"toAmount": 2.9722}
)
Returns
- An array ofconversion structures
{info:{ ...},timestamp:1646954920000,datetime:"2022-03-08T16:00:00.000Z",id:"1520286109858180",fromCurrency:"USDT",fromAmount:3.0,toCurrency:"USDC",toAmount:2.9722,price:0.97,fee:0.0}
In some specific cases you may want a proxy, when:
- Exchange is not available in your location
- Your IP is forbidden by exchange
- You experience random restriction by exchange, likeDDoS protection by Cloudflare
However, beware that each added intermediary might add some latency to requests.
Note for Go users: After setting any proxy property, you must callUpdateProxySettings()
to apply the changes:
exchange:=ccxt.NewBinance(nil)exchange.ProxyUrl="http://your-proxy-url:8080"exchange.UpdateProxySettings()// Required in Go to apply proxy settings
However be aware that each added intermediary might add some latency to requests.
CCXT supports the following proxy types (note, each of them also havecallback support):
This property prepends an url to API requests. It might be useful for simple redirection orbypassing CORS browser restriction.
ex = ccxt.binance();ex.proxyUrl = 'YOUR_PROXY_URL';
while 'YOUR_PROXY_URL' could be like (use the slash accordingly):
https://cors-anywhere.herokuapp.com/
http://127.0.0.1:8080/
http://your-website.com/sample-script.php?url=
- etc
So requests will be made to i.e.https://cors-anywhere.herokuapp.com/https://exchange.xyz/api/endpoint
. ( You can also have a small proxy script running on your device/webserver to use it in.proxyUrl
- "sample-local-proxy-server" inexamples folder). To customize the target url, you can also overrideurlEncoderForProxyUrl
method of instance.
This approach worksonly for REST requests, but not for websocket connections. ((How to test if your proxy works))[#test-if-your-proxy-works]
To set a real http(s) proxy for your scripts, you need to have an access to a remotehttp or https proxy, so calls will be made directly to the target exchange, tunneled through your proxy server:
ex.httpProxy = 'http://1.2.3.4:8080/';// orex.httpsProxy = 'http://1.2.3.4:8080/';
This approach only affectsnon-websocket requests of ccxt. To route CCXT's WebSockets connections through proxy, you need to specifically setwsProxy
(orwssProxy
) property, in addition to thehttpProxy
(orhttpsProxy
), so your script should be like:
ex.httpProxy = 'http://1.2.3.4:8080/';ex.wsProxy = 'http://1.2.3.4:8080/';
So, both connections (HTTP & WS) would go through proxies.((How to test if your proxy works))[#test-if-your-proxy-works]
You can also usesocks proxy with the following format:
// from protocols: socks, socks5, socks5hex.socksProxy = 'socks5://1.2.3.4:8080/';ex.wsSocksProxy = 'socks://1.2.3.4:8080/';
((How to test if your proxy works))[#test-if-your-proxy-works]
After setting any of the above listed proxy properties in your ccxt snippet, you can test whether it works by pinging some IP echoing websites - check a "proxy-usage" file inexamples.
**Instead of setting a property, you can also use callbacksproxyUrlCallback, http(s)ProxyCallback, socksProxyCallback
:
myEx.proxyUrlCallback = function (url, method, headers, body) { ... return 'http://1.2.3.4/'; }
If you need for special cases, you can overrideuserAgent
property like:
exchange.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)...'
Depending your programming language, you can set custom proxy agents.
- For JS, seethis example
- For Python, see the following examples:proxies-for-synchronous-python,proxy-asyncio-aiohttp-python-3,proxy-asyncio-aiohttp-socks,proxy-sync-python-requests-2-and-3
CORS (known asCross-Origin Resource Sharing) affects mostly browsers and is the cause of the well-know warningNo 'Access-Control-Allow-Origin' header is present on the requested resource
. It happens when a script (running in a browser) makes a request to a 3rd party domain (by default such requests are blocked, unless the target domain explicitly allows it).So, in such cases you will need to communicate with a "CORS" proxy, which would redirect requests (as opposed to direct browser-side request) to the target exchange. To set a CORS proxy, you can runsample-local-proxy-server-with-cors example file and in ccxt set the.proxyUrl
property to route requests through cors/proxy server.
Some users might want to control how CCXT handles arithmetic operations. Even though it uses numeric types by default, users can switch to fixed-point math using string types. This can be done by:
constex=newccxt.coinbase();ex.number=String;// String | Number
ex=ccxt.coinbase()ex.number=str# str | float
$ex =newccxt\\coinbase();$ex->number ='strval';// 'strval' | 'floatval'
varex=newccxt.coinbase();ex.number=typeof(String);// typeof(String) | typeof(float)
- Retry Mechanism
- Exception Hierarchy
- ExchangeError
- OperationFailed
- DDoSProtection
- RateLimitExceeded
- RequestTimeout
- RequestTimeout
- ExchangeNotAvailable
- InvalidNonce
The error handling with CCXT is done with the exception mechanism that is natively available with all languages.
To handle the errors you should add atry
block around the call to a unified method and catch the exceptions like you would normally do with your language:
// try to call a unified methodtry{constresponse=awaitexchange.fetchTicker('ETH/BTC')console.log(response)}catch(e){// if the exception is thrown, it is "caught" and can be handled here// the handling reaction depends on the type of the exception// and on the purpose or business logic of your applicationif(einstanceofccxt.NetworkError){console.log(exchange.id,'fetchTicker failed due to a network error:',e.message)// retry or whatever}elseif(einstanceofccxt.ExchangeError){console.log(exchange.id,'fetchTicker failed due to exchange error:',e.message)// retry or whatever}else{console.log(exchange.id,'fetchTicker failed with:',e.message)// retry or whatever}}
# try to call a unified methodtry:response=awaitexchange.fetch_order_book('ETH/BTC')print(response)exceptccxt.NetworkErrorase:print(exchange.id,'fetch_order_book failed due to a network error:',str(e))# retry or whateverexceptccxt.ExchangeErrorase:print(exchange.id,'fetch_order_book failed due to exchange error:',str(e))# retry or whateverexceptExceptionase:print(exchange.id,'fetch_order_book failed with:',str(e))# retry or whatever
// try to call a unified methodtry {$response =$exchange->fetch_trades('ETH/BTC');print_r($response);}catch (\ccxt\NetworkError$e) {echo$exchange->id .' fetch_trades failed due to a network error:' .$e->getMessage () ."\n";// retry or whatever}catch (\ccxt\ExchangeError$e) {echo$exchange->id .' fetch_trades failed due to exchange error:' .$e->getMessage () ."\n";// retry or whatever}catch (Exception$e) {echo$exchange->id .' fetch_trades failed with:' .$e->getMessage () ."\n";// retry or whatever}
When dealing with HTTP requests, it's important to understand that requests might fail for various reasons. Common causes of these failures include the server being unavailable, network instability, or temporary server issues. To handle such scenarios gracefully, CCXT provide an option to automatically retry failed requests. You can set the value ofmaxRetriesOnFailure
andmaxRetriesOnFailureDelay
to configure the number of retries and the delay between retries, example:
exchange.options['maxRetriesOnFailure']=3# if we get an error like the ones mentioned above we will retry up to three times per requestexchange.options['maxRetriesOnFailureDelay']=1000# we will wait 1000ms (1s) between retries
It's important to highlight that only server/network-related issues will be part of the retry mechanism; if the user gets an error due toInsufficientFunds
orInvalidOrder,
the request will not be repeated.
All exceptions are derived from the base BaseError exception, which, in its turn, is defined in the ccxt library like so:
classBaseErrorextendsError{constructor(){super()// a workaround to make `instanceof BaseError` work in ES5this.constructor=BaseErrorthis.__proto__=BaseError.prototype}}
classBaseError (Exception):pass
class BaseErrorextends \Exception {}
The exception inheritance hierarchy lives in this file:https://github.com/ccxt/ccxt/blob/master/ts/src/base/errorHierarchy.ts , and visually can be outlined like shown below:
+ BaseError|+---+ ExchangeError| || +---+ OperationRejected| || +---+ BadRequest| | || | +---+ BadSymbol| || +---+ AuthenticationError| | || | +---+ PermissionDenied| | || | +---+ AccountSuspended| || +---+ ArgumentsRequired| || +---+ BadResponse| | || | +---+ NullResponse| || +---+ InsufficientFunds| || +---+ InvalidAddress| | || | +---+ AddressPending| || +---+ InvalidOrder| | || | +---+ OrderNotFound| | || | +---+ OrderNotCached| | || | +---+ CancelPending| | || | +---+ OrderImmediatelyFillable| | || | +---+ OrderNotFillable| | || | +---+ DuplicateOrderId| || +---+ NotSupported||+---+ OperationFailed (recoverable) | +---+ NetworkError (recoverable) | +---+ InvalidNonce | +---+ RequestTimeout | +---+ ExchangeNotAvailable | | | +---+ OnMaintenance | +---+ RateLimitExceeded | +---+ DDoSProtection
TheBaseError
class is a generic root error class for all sorts of errors, including accessibility and request/response mismatch. If you don't need to catch any specific subclass of exceptions, you can just useBaseError
, where all exception types are being caught.
FromBaseError
derives two different families of errors:OperationFailed
andExchangeError
(they also have their specific sub-types, as explained below).
AnOperationFailed
might happen when user sendscorrectly constructed & valid request to exchange, but a non-deterministic problem occurred:
- maintenance ongoing
- internet/network connectivitiy issues
- DDoS protections
- "Server busy, try again"...
Such exceptions are temporary and re-trying the request again might be enough. However, if the error still happens, then it may indicate some persistent problem with the exchange or with your connection.
OperationFailed
has the following sub-types:RequestTimeout
,DDoSProtection
(includes sub-typeRateLimitExceeded
),ExchangeNotAvailable
,InvalidNonce
.
This exception is thrown in cases when cloud/hosting services (Cloudflare, Incapsula or etc..) limits requests from user/region/location or when the exchange API restricts user because of making abnormal requests. This exception also contains specific sub-type exceptionRateLimitExceeded
, which directly means that user makes much frequent requests than tolerated by exchange API engine.
This exception is raised when the connection with the exchange fails or data is not fully received in a specified amount of time. This is controlled by the exchange's.timeout
property. When aRequestTimeout
is raised, the user doesn't know the outcome of a request (whether it was accepted by the exchange server or not).
Thus it's advised to handle this type of exception in the following manner:
- for fetching requests it is safe to retry the call
- for a request to
cancelOrder()
a user is required to retry the same call the second time. A subsequent retry tocancelOrder()
will return one of the following possible results:- a request is completed successfully, meaning the order has been properly canceled now
- an
OrderNotFound
exception is raised, which means the order was either already canceled on the first attempt or has been executed (filled and closed) in the meantime between the two attempts.
- if a request to
createOrder()
fails with aRequestTimeout
the user should:- call
fetchOrders()
,fetchOpenOrders()
,fetchClosedOrders()
to check if the request to place the order has succeeded and the order is now open - if the order is not
'open'
the user shouldfetchBalance()
to check if the balance has changed since the order was created on the first run and then was filled and closed by the time of the second check.
- call
This type of exception is thrown when the underlying exchange is unreachable. The ccxt library also throws this error if it detects any of the following keywords in response:
offline
unavailable
busy
retry
wait
maintain
maintenance
maintenancing
Raised when your nonce is less than the previous nonce used with your keypair, as described in theAuthentication section. This type of exception is thrown in these cases (in order of precedence for checking):
- You are not rate-limiting your requests or sending too many of them too often.
- Your API keys are not fresh and new (have been used with some different software or script already, just always create a new keypair when you add this or that exchange).
- The same keypair is shared across multiple instances of the exchange class (for example, in a multithreaded environment or in separate processes).
- Your system clock is out of synch. System time should be synched with UTC in a non-DST timezone at a rate of once every ten minutes or even more frequently because of the clock drifting.Enabling time synch in Windows is usually not enough! You have to set it up with the OS Registry (Google"time synch frequency" for your OS).
In contrast toOperationFailed
, theExchangeError
is mostly happening when the request is impossible to succeed (because of factors listed below), so even if you retry the same request hundreds of times, they will still fail, because the request is being made incorrectly.
Possible reasons for this exception:
- endpoint is switched off by the exchange
- symbol not found on the exchange
- required parameter is missing
- the format of parameters is incorrect
- some problem happening on user-side that needs to be fixed
ExchangeError
has the following sub-type exceptions:
NotSupported
: when the endpoint/operation is not offered or supported by the exchange API.BadRequest
: user sends anincorrectly constructed request/parameter/action that is invalid/unallowed (i.e.: "invalid number", "forbidden symbol", "size beyond min/max limits", "incorrect precision", etc). Retrying would not help in this case, the request needs to be fixed/adjusted first.OperationRejected
- user sends acorrectly constructed request (that should be accepted by the exchange in a typical case), but some deterministic factor prevents your request to succeed. For example, your current account status might not allow it (i.e. "please close existing positions before changing the leverage", "too many pending orders", "your account in wrong position/margin mode") or at the give moment symbol is not tradable (i.e. "MarketClosed") or some explained factors, where you need to take a specific action (i.e. change some setting at first, or wait till specific moment). So, once again:OperationFailed can be blindly re-tried and should success, whileOperationRejected
is a failure that depends on specific exact factors that need to be considered, before request can be retried.AuthenticationError
: 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 needapiKey
andsecret
, sometimes you also needuid
and/orpassword
if exchange API requires it.PermissionDenied
: when there's no access for specified action or insufficient permissions on the specifiedapiKey
.InsufficientFunds
: when you don't have enough currency on your account balance to place an order.InvalidAddress
: when encountering a bad funding address or a funding address shorter than.minFundingAddressLength
(10 characters by default) in a call tofetchDepositAddress
,createDepositAddress
orwithdraw
.InvalidOrder
: the base class for all exceptions related to the unified order API.OrderNotFound
: when you are trying to fetch or cancel a non-existent order.
In case you experience any difficulty connecting to a particular exchange, do the following in order of precedence:
- Make sure that you have the most recent version of ccxt.Never trust your package installer (whether it is
npm
,pip
orcomposer
), instead always check youractual (real) runtime version number by running this code in your environment:console.log(ccxt.version)// JavaScript
print('CCXT version:',ccxt.__version__)# Python
echo"CCXT v." . \ccxt\Exchange::VERSION ."\n";// PHP
- Check theIssues orAnnouncements for recent updates.
- Make sure you have not turned offrate-limiter with
enableRateLimit: false
(If anyone has custom rate-limit solution built, ensure it does not misbehave). - If you use ccxt's proxy functionality, ensure it does not misbehave.
- Turn
verbose = true
to get more detail about it!Yourcode to reproduce the issue + verbose output is required in order to get help.exchange = ccxt.binance()exchange.load_markets()exchange.verbose = True # for less noise, you can set that after `load_markets`, but if the error happens during `load_markets` then place this line before it# ... your codes here ...
- Python people can turn on DEBUG logging level with a standard pythonic logger, by adding these two lines to the beginning of their code:
importlogginglogging.basicConfig(level=logging.DEBUG)
- Use verbose mode to make sure that the used API credentials correspond to the keys you intend to use. Make sure there's no confusion of keypairs.
- Try a fresh new keypair if possible.
- Read the answers to Frequently Asked Questions:https://github.com/ccxt/ccxt/wiki/FAQ
- Check the permissions on the keypair with the exchange website!
- Check your nonce. If you used your API keys with other software, you most likely shouldoverride your nonce function to match your previous nonce value. A nonce usually can be easily reset by generating a new unused keypair. If you are getting nonce errors with an existing key, try with a new API key that hasn't been used yet.
- 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 or enable the built-in rate-limiter, like shown in the long-pollerexamples, alsohere.
- Read thedocs for your exchange and compare your verbose output to the docs.
- Check your connectivity with the exchange by accessing it with your browser.
- Check your connection with the exchange through aproxy.
- 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.
- 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).
- Make sure that your system time in sync with the rest of the world's clocks since otherwise you may get invalid nonce errors.
Further Notes:
- Use the
verbose = true
option or instantiate your troublesome exchange withnew ccxt.exchange ({ 'verbose': true })
to see the HTTP requests and responses in details. The verbose output will also be of use for us to debug it if you submit an issue on GitHub. - Use DEBUG logging in Python!
- Some exchanges are not available in certain countries, using aproxy might be the solution in such cases.
- If you are getting authentication errors or'invalid keys' errors, those are most likely due to a nonce issue.
- Some exchanges do not state it clearly if they fail to authenticate your request. In those circumstances they might respond with an exotic error code, like HTTP 502 Bad Gateway Error or something that's even less related to the actual cause of the error.
(If the page is not being rendered for you, you can refer to the mirror athttps://docs.ccxt.com/)
https://ccxt.pro
Exchanges
Install
Manual
- Supported Exchanges
- Exchanges By Country
- Install
- Manual
- Error Handling
- Troubleshooting
- Examples
- Knowledge Base (wip)
- Contributing
- API Reference (wip)
- Frequently Asked Questions
- New Exchanges