### PHP Example: Load Markets and Format Values Source: https://docs.ccxt.com/Manual?id=a-single-ticker-for-one-symbol Example demonstrating how to load markets and then use `amount_to_precision` and `price_to_precision` in PHP. ```php $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"; ``` -------------------------------- ### Run JavaScript Examples Source: https://docs.ccxt.com/Examples Execute JavaScript examples using Node.js. Ensure you have the necessary Node.js modules installed. ```shell node path/to/example.js # substitute for actual filename here ``` -------------------------------- ### Python Example: Load Markets and Format Values Source: https://docs.ccxt.com/Manual?id=a-single-ticker-for-one-symbol Example demonstrating how to load markets and then use `amount_to_precision` and `price_to_precision` in Python. ```python 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) print(formatted_amount, formatted_price) ``` -------------------------------- ### Call Implicit Public GET Method (JavaScript) Source: https://docs.ccxt.com/?id=balance-structure Example of calling a public HTTPS GET endpoint using its implicit method. Parameters are passed in a dictionary. ```javascript .publicGetTickerPair ({ pair: 'BTC/USD' }) ``` -------------------------------- ### Require CCXT in Node.js Source: https://docs.ccxt.com/Install?id=custom-javascript-builds Load the CCXT library in a Node.js application after installation. This example logs all available exchanges. ```javascript var ccxt = require ('ccxt') console.log (ccxt.exchanges) // print all available exchangesCopy to clipboardErrorCopied ``` -------------------------------- ### Example Usage (PHP) Source: https://docs.ccxt.com/?id=take-profit-orders Demonstrates how to load markets and then use `amount_to_precision` and `price_to_precision` in PHP. ```APIDOC ## Example Usage (PHP) ```php $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"; ``` ``` -------------------------------- ### JavaScript Example: Load Markets and Format Values Source: https://docs.ccxt.com/Manual?id=a-single-ticker-for-one-symbol Example demonstrating how to load markets and then use `amountToPrecision` and `priceToPrecision` in JavaScript. ```javascript await exchange.loadMarkets () const symbol = 'BTC/USDT' const amount = 1.2345678 // amount in base currency BTC const price = 87654.321 // price in quote currency USDT const formattedAmount = exchange.amountToPrecision (symbol, amount) const formattedPrice = exchange.priceToPrecision (symbol, price) console.log (formattedAmount, formattedPrice) ``` -------------------------------- ### Fetch Trades with Forward Pagination Source: https://docs.ccxt.com/?id=api-methods--endpoints Example of fetching trades with forward time-based pagination, starting from a specific timestamp. ```APIDOC ## Fetch Trades with Forward Pagination ### Description Example of fetching trades with forward time-based pagination, starting from a specific timestamp. ### Method `fetch_trades` ### Endpoint `trades` ### Parameters #### Path Parameters - **since** (integer) - Required - The starting timestamp in milliseconds. #### Query Parameters - **paginate** (boolean) - Required - Set to `True` to enable pagination. - **paginationDirection** (string) - Required - Set to `"forward"` for forward pagination. ### Request Example ```javascript await binance.fetch_trades("BTC/USDT", since = 1664812416000, params = {"paginate": True, "paginationDirection": "forward"}) ``` ``` -------------------------------- ### Fetch Balance - Python Example Source: https://docs.ccxt.com/?id=transaction-structure A Python example showing how to call the `fetch_balance` method and print the returned balance structure. ```python print (exchange.fetch_balance ()) ``` -------------------------------- ### Fetch Trades with Forward Time-Based Pagination Source: https://docs.ccxt.com/?id=methods-for-markets-and-currencies Example of fetching trades with forward time-based pagination, starting from a specific timestamp. ```APIDOC ## Fetch Trades with Forward Time-Based Pagination ### Description Example of fetching trades with forward time-based pagination, starting from a specific timestamp. ### Method `fetch_trades` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters - **symbol** (string) - Required - The symbol to fetch trades for (e.g., "BTC/USDT"). #### Query Parameters - **since** (integer) - Required - The starting timestamp in milliseconds. - **params** (object) - Optional - Object containing pagination parameters. - **paginate** (boolean) - Required - Set to `true` to enable pagination. - **paginationDirection** (string) - Required - Set to `forward`. ``` -------------------------------- ### Example Usage (Python) Source: https://docs.ccxt.com/?id=take-profit-orders Demonstrates how to load markets and then use `amount_to_precision` and `price_to_precision` in Python. ```APIDOC ## Example Usage (Python) ```python 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) print(formatted_amount, formatted_price) ``` ``` -------------------------------- ### watchTradesForSymbols Source: https://docs.ccxt.com/exchanges/gemini?id=fetchorders Gets the list of most recent trades for multiple symbols. Allows specifying a start time and a limit for the trades fetched. ```APIDOC ## watchTradesForSymbols ### Description Get the list of most recent trades for a list of symbols. ### Method `gemini.watchTradesForSymbols(symbols[, since, limit, params])` ### Parameters #### Path Parameters - **symbols** (Array) - Required - unified symbol of the market to fetch trades for - **since** (int) - Optional - timestamp in ms of the earliest trade to fetch - **limit** (int) - Optional - the maximum amount of trades to fetch - **params** (object) - Optional - extra parameters specific to the exchange API endpoint ### Returns - `Array` - a list of trade structures ### See - https://docs.gemini.com/websocket-api/#multi-market-data ``` -------------------------------- ### Fetch Balance - PHP Example Source: https://docs.ccxt.com/?id=transaction-structure A PHP example demonstrating the usage of the `fetch_balance` method and displaying the result using `var_dump`. ```php var_dump ($exchange->fetch_balance ()); ``` -------------------------------- ### watchTrades Source: https://docs.ccxt.com/exchanges/bullish?id=fetchdepositswithdrawals Gets the list of most recent trades for a particular symbol. Requires a unified symbol and optionally accepts a start time and limit. ```APIDOC ## watchTrades ### Description Get the list of most recent trades for a particular symbol. ### Method `bullish.watchTrades(symbol[, since, limit, params])` ### Parameters #### Path Parameters - **symbol** (string) - Required - Unified symbol of the market to fetch trades for - **since** (int) - Optional - Timestamp in ms of the earliest trade to fetch - **limit** (int) - Optional - The maximum amount of trades to fetch - **params** (object) - Optional - Extra parameters specific to the exchange API endpoint ### Returns `Array` - A list of trade structures. ``` -------------------------------- ### Instantiate Exchange with Default ID (Python) Source: https://docs.ccxt.com/?id=api-key-permissions Create an exchange instance using its default ID in Python. This is the simplest way to get started. ```python import ccxt exchange = ccxt.okcoin () # default id ``` -------------------------------- ### Example Usage Source: https://docs.ccxt.com/?id=order-book--market-depth Demonstrates how to use `amountToPrecision` and `priceToPrecision` after loading markets. ```APIDOC ## Example Usage Here's how you can use these methods in practice: ### Javascript ```javascript await exchange.loadMarkets () const symbol = 'BTC/USDT' const amount = 1.2345678 // amount in base currency BTC const price = 87654.321 // price in quote currency USDT const formattedAmount = exchange.amountToPrecision (symbol, amount) const formattedPrice = exchange.priceToPrecision (symbol, price) console.log (formattedAmount, formattedPrice) ``` ### Python ```python 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) print(formatted_amount, formatted_price) ``` ### PHP ```php $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"; ``` ``` -------------------------------- ### Watch Trades for Multiple Symbols Source: https://docs.ccxt.com/exchanges/aster?id=addmargin Use this method to get a list of recent trades for multiple symbols. You can specify a start time and a limit. ```javascript aster.watchTradesForSymbols (symbols[, since, limit, params]) ``` -------------------------------- ### Listing Available Methods (JavaScript, Python, PHP) Source: https://docs.ccxt.com/?id=account-types Provides examples for listing all available methods on an exchange instance using console.log in JavaScript, print(dir()) in Python, and var_dump() in PHP. ```javascript console.log (new ccxt.kraken ()) // JavaScript ``` ```python print(dir(ccxt.hitbtc())) # Python ``` ```php var_dump (new \ccxt\okcoin ()); // PHP ``` -------------------------------- ### List Available Exchange Methods (JavaScript) Source: https://docs.ccxt.com/Manual?id=ccxt-pro Example of how to instantiate an exchange and log its available methods in JavaScript. ```javascript console.log (new ccxt.kraken ()) ``` -------------------------------- ### Fetch Deposit and Withdraw Fees Example Source: https://docs.ccxt.com/?id=closing-positions Use fetchDepositWithdrawFees to get deposit and withdraw fees for specified currencies. This method replaces the deprecated fetchTransactionFee(s). ```javascript exchange.fetchDepositWithdrawFees (codes, params = {}) ``` ```json { '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': { ... }, }, ... } ``` -------------------------------- ### Get Supported Exchange IDs in Python Source: https://docs.ccxt.com/Manual?id=account-types This Python code retrieves a list of all exchange IDs supported by the ccxt library. Ensure ccxt is installed. ```python import ccxt print (ccxt.exchanges)Copy to clipboardErrorCopied ``` -------------------------------- ### Fetch Balance - JavaScript Example Source: https://docs.ccxt.com/?id=transaction-structure An asynchronous JavaScript example demonstrating how to call the `fetchBalance` method and log the result to the console. ```javascript (async () => { console.log (await exchange.fetchBalance ()) }) () ``` -------------------------------- ### Fetch Recent Trades - Woofipro Source: https://docs.ccxt.com/exchanges/woofipro?id=cancelallorders Gets the list of most recent trades for a particular symbol. You can specify a start timestamp and a limit for the number of trades to fetch. ```javascript woofipro.fetchTrades (symbol[, since, limit, params])Copy to clipboardErrorCopied ``` -------------------------------- ### Fetch Order Book Examples Source: https://docs.ccxt.com/?id=rate-limit Examples demonstrating how to fetch an order book and implement rate limiting in JavaScript, Python, and PHP. ```APIDOC ## Fetch Order Book Examples This section provides examples of how to fetch an order book and implement rate limiting using different programming languages. ### Javascript ```javascript delay = 2000 // milliseconds = seconds * 1000 (async () => { for (symbol in exchange.markets) { console.log (await exchange.fetchOrderBook (symbol)) await new Promise (resolve => setTimeout (resolve, delay)) // rate limit } }) () ``` ### Python ```python import time delay = 2 # seconds for symbol in exchange.markets: print (exchange.fetch_order_book (symbol)) time.sleep (delay) # rate limit ``` ### PHP ```php $delay = 2000000; // microseconds = seconds * 1000000 foreach ($exchange->markets as $symbol => $market) { var_dump ($exchange->fetch_order_book ($symbol)); usleep ($delay); // rate limit } ``` ``` -------------------------------- ### Fetch Recent Trades - Modetrade Source: https://docs.ccxt.com/exchanges/modetrade?id=fetchclosedorders Gets the list of most recent trades for a particular symbol. You can specify a start timestamp and a limit for the number of trades to fetch. ```javascript modetrade.fetchTrades (symbol[, since, limit, params])Copy to clipboardErrorCopied ``` -------------------------------- ### Watch Trades (C#) Source: https://docs.ccxt.com/ccxt.pro.manual This C# example shows how to instantiate a Binance exchange object using CCXT Pro and continuously watch for trades on the BTC/USDT market. It uses async/await for non-blocking operations. ```csharp using ccxt.pro; public async static Task Watch() { var exchange = new binance(); while (true) { var trades = await exchange.WatchTrades("BTC/USDT"); Console.WriteLine("Trades: " + JsonConvert.SerializeObject(trades, Formatting.Indented)); } } ``` -------------------------------- ### watchTrades Source: https://docs.ccxt.com/exchanges/dydx?id=unwatchohlcv Subscribes to the trades channel to get the list of most recent trades for a particular symbol. Allows specifying a start time and a limit for the number of trades. ```APIDOC ## watchTrades ### Description Gets the list of most recent trades for a particular symbol. ### Method `dydx.watchTrades (symbol[, since, limit, params])` ### Parameters #### Path Parameters - **symbol** (string) - Required - Unified symbol of the market to fetch trades for - **since** (int) - Optional - Timestamp in ms of the earliest trade to fetch - **limit** (int) - Optional - The maximum amount of trades to fetch - **params** (object) - Optional - Extra parameters specific to the exchange API endpoint ### Returns - `Array` - A list of trade structures ``` -------------------------------- ### Fetch Deposits Example Source: https://docs.ccxt.com/?id=%23%23%23account-balance Demonstrates how to fetch deposits for a given currency, since a specific timestamp, up to a limit, and with additional parameters. It includes checks for exchange support of the 'fetchDeposits' method. ```javascript // fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) if (exchange.has['fetchDeposits']) { const deposits = await exchange.fetchDeposits (code, since, limit, params) } else { throw new Error (exchange.id + ' does not have the fetchDeposits method') } ``` ```python # fetch_deposits(code = None, since = None, limit = None, params = {}) if exchange.has['fetchDeposits']: deposits = exchange.fetch_deposits(code, since, limit, params) else: raise Exception (exchange.id + ' does not have the fetch_deposits method') ``` ```php // fetch_deposits ($code = null, $since = null, $limit = null, $params = {}) if ($exchange->has['fetchDeposits']) { $deposits = $exchange->fetch_deposits ($code, $since, $limit, $params); } else { throw new Exception ($exchange->id . ' does not have the fetch_deposits method'); } ``` -------------------------------- ### Get Raw OHLCV Response Source: https://docs.ccxt.com/?id=methods-for-markets-and-currencies Explains how to modify the `parseOHLCV` method to include the raw response from the exchange in the returned data. Includes examples in Javascript and Python. ```APIDOC ## Get Raw OHLCV Response ### Description Allows users to include the raw response from the exchange within the parsed OHLCV data by overriding the `parseOHLCV` method. ### Usage Examples **Javascript** ```javascript const ex = new ccxt.coinbase(); const originalParser = ex.parseOHLCV.bind(ex); ex.parseOHLCV = ((ohlcv, market = undefined) => { return { 'result': originalParser(ohlcv, market), 'raw': ohlcv, }; }); const result = await ex.fetchOHLCV('BTC/USDT', '1m'); console.log (result[0]); ``` **Python** ```python # add raw member at last position in list async def test(): ex = ccxt.async_support.coinbase() prase_ohlcv_original = ex.parse_ohlcv def prase_ohlcv_custom(ohlcv, market): res = prase_ohlcv_original(ohlcv, market) res.append(ohlcv) return res ex.parse_ohlcv = prase_ohlcv_custom result = await ex.fetch_ohlcv('BTC/USDT', '1m') print (result[0]) asyncio.run(test()) ``` ``` -------------------------------- ### List Available Exchange Methods (Python) Source: https://docs.ccxt.com/Manual?id=ccxt-pro Example of how to instantiate an exchange and print its available methods using Python's dir() function. ```python print(dir(ccxt.hitbtc())) ``` -------------------------------- ### Instantiate Exchange Instances (Python) Source: https://docs.ccxt.com/Manual?id=a-single-ticker-for-one-symbol Demonstrates creating exchange instances, including default, custom ID, and API key authenticated instances. ```python import ccxt exchange = ccxt.okcoin () # default id okcoin1 = ccxt.okcoin ({ 'id': 'okcoin1' }) okcoin2 = ccxt.okcoin ({ 'id': 'okcoin2' }) id = 'btcchina' btcchina = eval ('ccxt.%s ()' % id) coinbasepro = getattr (ccxt, 'coinbasepro') () # from variable id exchange_id = 'binance' exchange_class = getattr(ccxt, exchange_id) exchange = exchange_class({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', }) ``` -------------------------------- ### Cursor-based Pagination Example (PHP) Source: https://docs.ccxt.com/?id=custom-order-params Shows cursor-based pagination for fetching trades, using custom 'start' parameters and extracting the next cursor from the JSON response. ```APIDOC ## fetchMyTrades with Custom Pagination Parameters ### Description This PHP example illustrates cursor-based pagination for fetching user trades by employing custom 'start' parameters and extracting the subsequent cursor from the JSON response. ### Method `$exchange->fetchMyTrades($symbol, $since, $limit, $params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php 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-safe 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; } } } ``` ### Response #### Success Response (200) - `trades` (Array) - An array of trade objects. - `next` (String) - The cursor for the next page of results, extracted from the parsed JSON response. #### Response Example (Response structure depends on the exchange and `fetchMyTrades` implementation) ``` -------------------------------- ### Fetch Balance - Usage Examples Source: https://docs.ccxt.com/Manual?id=adjusting-exchange-options Examples of how to call the `fetchBalance` method in different programming languages. ```javascript (async () => { console.log (await exchange.fetchBalance ()) }) () ``` ```python print (exchange.fetch_balance ()) ``` ```php var_dump ($exchange->fetch_balance ()); ``` -------------------------------- ### Fetch Recent Trades - Zaif Source: https://docs.ccxt.com/exchanges/zaif?id=fetchorderbook Gets a list of the most recent trades for a given market symbol. You can specify a start time (since) and a limit for the number of trades. ```javascript zaif.fetchTrades (symbol[, since, limit, params])Copy to clipboardErrorCopied ``` -------------------------------- ### Watch Trades - Luno Source: https://docs.ccxt.com/exchanges/luno?id=cancelorder Gets the list of most recent trades for a specific symbol on Luno. You can specify a start time (since) and a limit for the number of trades to fetch. ```javascript luno.watchTrades (symbol[, since, limit, params]) ``` -------------------------------- ### Load Markets Example (PHP) Source: https://docs.ccxt.com/?id=ddos-protection-by-cloudflare-incapsula Demonstrates how to load markets, access market data, and force a reload using the `load_markets` method in PHP. ```APIDOC ## Load Markets Example (PHP) ### Description This example shows how to initialize an exchange, load its markets, access market information, and force a reload of the market data. ### Usage ```php $bitfinex = new \ccxt\bitfinex(array('verbose' => true)); // log HTTP requests $bitfinex->load_markets(); // request markets var_dump($bitfinex->id, $bitfinex->markets); // output a full list of all loaded markets var_dump(array_keys ($bitfinex->markets)); // output a short list of market symbols var_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 = true var_dump($bitfinex->markets['XRP/BTC']); ``` ``` -------------------------------- ### Fetch Order Book Example Source: https://docs.ccxt.com/?id=api-methods-endpoints Demonstrates how to fetch an order book using the unified fetch_order_book method, with examples in JavaScript and PHP. It also shows how to pass exchange-specific parameters. ```APIDOC ## fetch_order_book ### Description Fetches the order book for a given symbol. Exchange-specific parameters can be passed in the `params` object. ### Method Signature `exchange.fetch_order_book(symbol, length, params) ` ### Parameters - **symbol** (string) - The trading pair symbol. - **length** (integer) - The number of orders to retrieve (optional, exchange-dependent). - **params** (object) - Exchange-specific parameters. ### Request Example (JavaScript) ```javascript // overrides go in the last argument to the unified call result = exchange.fetch_order_book(symbol, length, params) ``` ### Request Example (PHP) ```php $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 $result = $exchange->fetch_order_book ($symbol, $length, $params); ``` ### Pagination This section explains the general concept of pagination for methods that return lists of objects, such as trades, orders, and transactions. It highlights that APIs often limit the number of results per call and that users may need to implement pagination to retrieve all data. CCXT unifies date-based pagination using `until` and `since` timestamps in milliseconds. Automatic pagination using a `paginate` flag in `params` is an experimental feature that supports dynamic/time-based, deterministic, and cursor-based pagination methods. ```