mirror of
https://github.com/discountry/ritmex-bot.git
synced 2026-09-11 01:08:07 +00:00
commit
This commit is contained in:
@@ -0,0 +1,188 @@
|
||||
# Awesome CCXT
|
||||
|
||||
Suggestions and contributions are always welcome! Make sure to read the [contribution guidelines](#contributing)
|
||||
|
||||
- [Awesome CCXT](#awesome-ccxt)
|
||||
- [Trading bots](#trading-bots)
|
||||
- [Trading toolkits](#trading-toolkits)
|
||||
- [Trading terminals](#trading-terminals)
|
||||
- [Analytics platforms](#analytics-platforms)
|
||||
- [API](#api)
|
||||
- [AI](#ai)
|
||||
- [Utils](#utils)
|
||||
- [Languages](#languages)
|
||||
- [Javascript examples](#javascript-examples)
|
||||
- [Python examples](#python-examples)
|
||||
- [PHP examples](#php-examples)
|
||||
- [Articles](#articles)
|
||||
- [Videos](#videos)
|
||||
- [Contributing](#contributing)
|
||||
|
||||
## Trading bots
|
||||
|
||||
- [Supertrend crypto bot](https://github.com/hackingthemarkets/supertrend-crypto-bot) - Python, pandas. Has a good video tutorial.
|
||||
- [CryptoMon Bot](https://github.com/jchristov/cryptomon-bot) - Helps tracking of your cryptocurrency investments and making smart, informed buy/sell decisions.
|
||||
- [ZenBot](https://github.com/carlos8f/zenbot) - A command-line cryptocurrency trading bot using Node.js and MongoDB.
|
||||
- [Titan](https://github.com/Denton24646/Titan) - Based on python, flask, postgres.
|
||||
- [Python-crypto-Bot](https://github.com/Seigneur774/Python-crypto-Bot)
|
||||
- [Nash](https://github.com/joelsfoster/Nash) - Arbitrage bot on meteorjs
|
||||
- [cryptodaemon](https://github.com/gmark4212/cryptodaemon) - Bot watches which currencies are now in a significant decline but have the potential for growth.
|
||||
- [pine-bot-client](https://github.com/kzh-dev/pine-bot-client)
|
||||
- [cryptobot](https://github.com/Zane-/cryptobot) - lowhighbot, poolbot, releasebot
|
||||
- [ccxt-trader](https://github.com/Schnides123/ccxt-trader) - cryptocurrency arbitrage calculator on #python
|
||||
- [KryptoBot](https://github.com/eristoddle/KryptoBot)
|
||||
- [blockbid-ccxt-tutorials](https://github.com/thomasdavis/blockbid-ccxt-tutorials)
|
||||
- [trader0](https://github.com/kebnekaise-io/trader0)
|
||||
- [bakuchi](https://github.com/tsu-nera/bakuchi) - arbitrage bot
|
||||
- [Superalgos](https://github.com/superalgos/superalgos) - Trading bot platform, node.js, tensorflow
|
||||
|
||||
## Signals
|
||||
|
||||
- [Peregrine](https://github.com/wardbradt/peregrine) - Arbitrage on python.
|
||||
- [ccxt-arbitrage](https://github.com/ArthurAnanda/ccxt-arbitrage-v1)
|
||||
- [crypto-arbitrage-framework](https://github.com/hzjken/crypto-arbitrage-framework)
|
||||
- [Nash](https://github.com/joelsfoster/Nash) - Arbitrage bot on meteorjs
|
||||
- [ccxt-trade-mgr](https://github.com/notlesh/ccxt-trade-mgr) - take profit vs. stop loss
|
||||
- [EasyTrage](https://github.com/Vikrammel/EasyTrage) - crypto arbitrage bot in MERN
|
||||
- [Automatic-Arbitrage-Crypto-exchange](https://github.com/ZgodaRafal/Automatic-Arbitrage-Crypto-exchange)
|
||||
- [Cryptocurrency-Multi-Exchange-Arbitrage-Strategy](https://github.com/chicago-joe/Cryptocurrency-Multi-Exchange-Arbitrage-Strategy)
|
||||
|
||||
## Trading toolkits
|
||||
|
||||
- [The Coinbase Pro trading toolkit (CPTT)](https://github.com/coinbase/coinbase-pro-trading-toolkit) – a trading toolkit developed by the coinbase team that integrates with ccxt, bitfinex, bitmex, bittrex, coinbasePro, gemini, poloniex.
|
||||
- [bt-ccxt-store](https://github.com/Dave-Vallance/bt-ccxt-store) – Store with backtesting. #python
|
||||
- [ZTOM](https://github.com/ztomsy/ztom) - #python, #backtesting, #rest, orders manager, loggin, reporting, throttling control.
|
||||
- [TradingSystemDemo](https://github.com/FWangTrading/TradingSystemDemo) - #Catalyst, #CryptoCompare, #backtesting, #alerts, #trading, #python
|
||||
- [Visuccxt](https://github.com/wnklb/Visuccxt) - #python
|
||||
- [DataSynchronizer](https://github.com/stockmlbot/DataSynchronizer)
|
||||
- [Trading-indicator](https://github.com/thanhnguyennguyen/trading-indicator) - fetch data with ccxt and generate indicators
|
||||
|
||||
## Trading terminals
|
||||
|
||||
- [Kupi-terminal](https://github.com/kupi-network/kupi-terminal) - Customized, extendable trading platform based on js, vue, react, express (rest api), mongo. Can: plot OHLCV, buy/sell, show balances, history balances, orders, trades, my orders, my trades.
|
||||
- [ccxt-trading-cp](https://github.com/michnovka/ccxt-trading-cp) - Trading terminal in console: plot OHLCV, find arbitrage signals, buy/sell, show balances.
|
||||
- [Auto-Trade-Crypto-Bot](https://github.com/dev4Fun/Auto-Trade-Crypto-Bot) - Crypto trading #bot in #python with #telegram.
|
||||
- [ccxt-exchange-template](https://github.com/AdrenalineAI/ccxt-exchange-template) - python
|
||||
|
||||
## Analytics platforms
|
||||
|
||||
- [CoinTop](https://github.com/fatihacet/CoinTop) - portfolio with secure access to keys
|
||||
- [DACP](https://github.com/Pyeskyhigh/DACP) - portfolio
|
||||
- [hodlwatch](https://github.com/belaczek/hodlwatch) - portfolio
|
||||
- [Live-Crypto-Dashboard-and-DB](https://github.com/srozov/Live-Crypto-Dashboard-and-DB) - python, sentiments
|
||||
|
||||
## API
|
||||
|
||||
- [sanic-ccxt](https://github.com/zloyuser/sanic-ccxt) - Unified REST API on #python
|
||||
- [ccxt-rest](https://github.com/franz-see/ccxt-rest) - Unified REST API on #javascript
|
||||
- [ccxt-microservice](https://github.com/xeno14/ccxt-microservice) - Unified REST API on #python
|
||||
- [mpakus/ccxt-server](https://github.com/mpakus/ccxt-server) - #javascript
|
||||
- [imloama/ccxt-server](https://github.com/imloama/ccxt-server) - #typescript
|
||||
- [ccxt-private-ws](https://github.com/invao/ccxt-private-ws) - private websocket connections with CCXT compatible data layout
|
||||
|
||||
## AI
|
||||
|
||||
- [Taurus](https://github.com/OptimalPandemic/taurus) - A cryptocurrency trading platform using deep reinforcement learning.
|
||||
|
||||
## Utils
|
||||
|
||||
- [bitcoin-chart-cli](https://github.com/madnight/bitcoin-chart-cli) by [madnight](https://github.com/madnight) – a command-line console util that draws Bitcoin, Ether, Litecoin and many altcoin charts right in the terminal!
|
||||
- [node-red-contrib-ccxt](https://github.com/masalinas/node-red-contrib-ccxt) - Node-red integration.
|
||||
- [freqcache](https://github.com/creslinux/freqcache) - A environment to control egress and ingress data from ccxt fronted trading bots for security and scalability
|
||||
- [candlestick-convert](https://github.com/valamidev/candlestick-convert) - [Object,Object] => [[],[]]
|
||||
- [crypto-exporter](https://github.com/ix-ai/crypto-exporter) - An exporter capable of connecting to multiple exchanges and getting account balances and exchange rates
|
||||
- [ccxtreplay](https://github.com/xCuri0/ccxtreplay) - collect data from ccxt exchanges and replay it for backtesting
|
||||
|
||||
## Languages
|
||||
|
||||
- [CCXT](https://github.com/ccxt/ccxt) - Javascript, python, php, C#.
|
||||
- [kizzx2/ccxt-rs](https://github.com/kizzx2/ccxt-rs) - Rust.
|
||||
- [irbis-labs/ccxt-rs](https://github.com/irbis-labs/ccxt-rs) - Rust. Early version. See branch 'preview'.
|
||||
- [CCXT.NET](https://github.com/lisa3907/ccxt.net) - C#.
|
||||
- [ccxtex](https://github.com/metachaos-systems/ccxtex) - Elixir/Erlang.
|
||||
- [ccxt.dart](https://github.com/Sach97/ccxt.dart) - Dart.
|
||||
- [ccxt-go](https://github.com/prompt-cash/ccxt-go) - Go.
|
||||
|
||||
## Javascript examples
|
||||
|
||||
- [Examples from ccxt](https://github.com/ccxt/ccxt/tree/master/examples/js)
|
||||
- [Using ccxt and technicalindicators to calculate MACD for BTC/USDT with Node.js](https://runkit.com/dhilipb/macd-for-btc-usdt) – A runkit sample showing how to fetch data and run statistical calculations.
|
||||
|
||||
## Python examples
|
||||
|
||||
- [Examples from ccxt](https://github.com/ccxt/ccxt/tree/master/examples/py)
|
||||
- [ccxt_notes](https://github.com/yinruiqing/ccxt_notes) - jupiter notebooks
|
||||
- [51bitqunt](https://github.com/ramoslin02/51bitqunt) - video playlist
|
||||
|
||||
## PHP examples
|
||||
|
||||
- [Examples from ccxt](https://github.com/ccxt/ccxt/tree/master/examples/php)
|
||||
|
||||
## Articles
|
||||
|
||||
- [Enigma Catalyst](https://blog.enigma.co/enigma-announces-catalyst-0-4-our-biggest-release-yet-fa31a5ffa4b1) – The major effort towards decentralized exchanges integrates ccxt!
|
||||
- [Playing with CCXT in Google Colab](https://medium.com/@ccxt/playing-with-ccxt-in-google-colab-23522ac8a6cb) – An article on how useful Colab can be for quick prototyping and testing your trading ideas with CCXT.
|
||||
- [CC Power Analytics Part 1: How to get the data of the exchanges](https://www.linkedin.com/pulse/part-1-cc-power-analytics-how-get-data-exchanges-steve-rein/) – The first part of a series of articles on cryptocurrency analytics.
|
||||
- [Looking for arbitrage opportunies with ccxt](https://steemit.com/steemdev/@codewithcheese/looking-for-arbitrage-opportunies-with-javascript-library-cctx-supporting-70-exchanges) – An article @steemit on getting arbitrage started with ccxt for crypto-arbitrage.
|
||||
- [A n00bs Guide To Deep Cryptocurrency Trading](https://medium.com/@LeonFedden/deep-cryptocurrency-trading-1e64af6d280a) – An article @ Medium on deep neural trading using ccxt for backend tasks.
|
||||
- [Let’s write a cryptocurrency bot](https://medium.com/@joeldg/an-advanced-tutorial-a-new-crypto-currency-trading-bot-boilerplate-framework-e777733607ae) – A multi-part advanced tutorial on a new cryptocurrency trading framework also integrating ccxt.
|
||||
- [Download Cryptocurrency Data with CCXT](https://backtest-rookies.com/2018/03/08/download-cryptocurrency-data-with-ccxt/) – A sample script to download historical data from exchanges with a video overview: [Easy Python script to download crypto currency market data with CCXT package](https://www.youtube.com/watch?v=PTGkJsrF7kQ).
|
||||
- [Experiments : Creating a Crypto Twitter Bot to Announce Newly Listed CryptoCoins](https://medium.com/@kennychuaio/experiments-creating-a-crypto-twitter-bot-to-announce-newly-listed-cryptocoins-9cd23930f5cb) – An article on how to integrate with CCXT and Twitter to get new currencies from exchanges automatically.
|
||||
- [How to make your own trading bot](https://codeburst.io/how-to-make-your-own-trading-bot-83b5c6e35036) – A tutorial on algortrading in Python.
|
||||
- [Writing crypto trading bot in Python with Telegram and ccxt](https://medium.com/@maxAvdyushkin/writing-crypto-trading-bot-in-python-with-telegram-and-ccxt-80632a00c637) – A tutorial on programming a Telegram bot in Python with CCXT
|
||||
- [Data science is eating the world — Here’s how you can start exploring it](https://medium.com/covee-network/data-science-is-eating-the-world-heres-how-you-can-start-exploring-it-37501414af15) – An article on collecting and analyzing financial big data.
|
||||
- [Chasing fake volume: a crypto-plague](https://medium.com/@sylvainartplayribes/chasing-fake-volume-a-crypto-plague-ea1a3c1e0b5e) – An article @ Medium on trading volumes analysis.
|
||||
- [CCXTが便利な理由!CCXTライブラリをインストールしよう](https://ryota-trade.com/?p=476) – An article in Japanese on getting CCXT up and runining.
|
||||
- [Bitflyerや各取引所の個別APIをCCXTライブラリ経由で直接利用する方法](https://ryota-trade.com/?p=629) – How to use Bitflyer and individual API of each exchange directly via the CCXT library.
|
||||
- [CCXTライブラリでBitflyerに注文を出す方法をマスターする](https://ryota-trade.com/?p=662) – Master placing orders on Bitflyer with the CCXT library.
|
||||
- [CCXTでBitflyerに出した注文を管理・キャンセルする方法](https://ryota-trade.com/?p=759) – How to manage and cancel orders placed on Bitflyer with CCXT
|
||||
- [Bitflyerの未約定の全注文をCCXTで一括でキャンセルする方法](https://ryota-trade.com/?p=833) – How to cancel all uncommitted orders of Bitflyer in bulk with CCXT
|
||||
- [Python3とCCXTライブラリを用いたBitMEX自動売買bot作成Tips](https://note.mu/akagami/n/n0af0a96c261f) – An article in Japanese on getting started with CCXT and a few bot tips.
|
||||
- [BitMEX 自動売買BOT開発 (API編) ① 開発環境の構築、APIライブラリの詳細、全APIマップ](https://note.mu/mazmex7/n/n1a3a0293ce82) – An article on developing an automatic BitMEX trading bot.
|
||||
- [仮想通貨トレード Bot 制作に便利な CCXT ライブラリに関する知見まとめ (Python 随時更新)](http://www.stray-scrapbook.work/entry/2018/04/03/205700) – A summary on Python version of CCXT API in Japanese.
|
||||
- [Python3とCCXTを使用して仮想通貨の自動売買プログラムを作る](http://www.hacky.xyz/entry/2018/03/18/200822) – Automatic cryptocurrency trading using Python 3 and CCXT
|
||||
- [ccxtを使って裁定取引botを作ってみたらなぜか虚しくなった件](https://qiita.com/reon777/items/21ed87f19cdd50f08bd9) – An article in Japanese explaining the basics of programming an arbitrage bot with CCXT.
|
||||
- [Python 3 / BitMEX の BOT を作ろう CCXT + BOT サンプルコード 〈基礎編〉](https://note.mu/mman/n/n5a9083864335) – A sample of basic BitMEX bot with CCXT in Python 3.
|
||||
- [ccxtがbtcfxbot界隈でちょっと話題になっていたので使ってみた](http://cryptojapan.ml/entry/2018/03/01/151752) – Trying CCXT for a basic bot.
|
||||
- [python異步加協程獲取比特幣市場信息](https://hk.saowen.com/a/18a648f24d6e7f54981e9db4411b56730a35dd2b3b27519083543bcd6198cd27) – An article in Chinese on using CCXT with Python.
|
||||
- [Лучшая криптотрейдинг библиотека?](http://medium.com/@vladthelittleone/лучшая-криптотрейдинг-библиотека-67e308f96c1f) – An article in Russian on setting up CCXT to connect and trade with crypto exchanges.
|
||||
|
||||
## Videos
|
||||
|
||||
- [The Evolution of CCXT](https://www.youtube.com/watch?v=O5HrvSLeo90) – An awesome Gource visualization video on YouTube! )
|
||||
- [A Video Crash-Course On Using CCXT](https://www.youtube.com/playlist?list=PLIFBTFgFpoJ-xGRz3v_2nF7f9HKZrfSpj) – A series of awesome video tutorials on getting started with CCXT!
|
||||
- [Download Cryptocurrency Data with CCXT](https://backtest-rookies.com/2018/03/08/download-cryptocurrency-data-with-ccxt/) – A sample script to download historical data from exchanges with a video overview: [Easy Python script to download crypto currency market data with CCXT package](https://www.youtube.com/watch?v=PTGkJsrF7kQ).
|
||||
- [Python数字货币量化交易开发入门视频-利用CCXT获取bitmex交易所的行情数据](https://www.bilibili.com/video/av44339579/) – An video in Chinese on how to get started with CCXT in Python and a tutorial on OHLCV + Pandas export to CSV.
|
||||
- [数字货币量化交易1 【群友 Shadow 自制】ccxt 的python版本安装及使用入门](https://www.bilibili.com/video/av21795165) – Trading Digital Currencies 1: Installing and using the Python version of ccxt (video in Chinese)
|
||||
- [数字货币量化交易2 【群友 林军 自制】ccxt Unified API命令详解及node版本使用演示](https://www.bilibili.com/video/av21842290) – Trading Digital Currencies 2: Using unified CCXT API (video in Chinese)
|
||||
- [数字货币量化交易3 ccxt Custom API命令详解及node版本使用演示](https://www.bilibili.com/video/av21842988)
|
||||
– Trading Digital Currencies 3: Details on using custom exchange-specific [implicit methods](https://github.com/ccxt/ccxt/wiki/Manual#implicit-api-methods) in ccxt (video in Chinese)
|
||||
- [Algorithmic Trading - Aula 4](https://www.youtube.com/watch?v=BkKebXrhMGY) – A video introduction to algorithmic trading with CCXT from Curso Algo Trading in Portuguese language.
|
||||
- [Présentation de projet - Créer un Bot Telegram de A à Z (+CCXT)](https://www.youtube.com/watch?v=yayJKRtg5M4) – La création d'un bot Telegram en Node.js, qui va rechercher des informations sur les différentes marketpalce de crypto-monnaies, et cela via la librairie CCXT.
|
||||
- [Which Bitcoin crypto currency bot project? Gekko vs ccxt vs Tribeca vs Blackbird](https://www.youtube.com/watch?v=Bn2p-nkbVdE) – A video comparison of opensource cryptocurrency trading platforms.
|
||||
|
||||
## Other
|
||||
|
||||
- [Projects based on ccxt](https://github.com/ccxt/ccxt/network/dependents) – A list of hundreds of ccxt-based projects by developers from all over the world!
|
||||
- [LOC-Extension](https://github.com/walkjivefly/LOC-Extension) – a LibreOffice extension which embeds ccxt to provide cryptocurrency price lookup in your spreadsheets.
|
||||
- [exchange-connector](https://github.com/donvadicastro/exchange-connector) - Exchange connector over ccxt and kafka
|
||||
- [ccew](https://github.com/saytoken/ccew) - has the same scheme as ccxt, but provide data by websocket
|
||||
|
||||
## Contributing
|
||||
|
||||
Please ensure your pull request adheres to the following:
|
||||
|
||||
- Search previous suggestions before making a new one to ensure yours is not a duplicate.
|
||||
- Make an individual pull request for each suggestion.
|
||||
- Use the following format: [NAME](LINK) - DESCRIPTION.
|
||||
- Keep descriptions simple.
|
||||
- New categories, or improvements to the existing ones are welcome.
|
||||
- End all descriptions with a period.
|
||||
- Try to ensure your pull requests only have one commit if possible. You can squash your commits into one before submitting.
|
||||
- Make your pull request titles and descriptions as detailed as possible. Explain why an asset or resources deserves to be added to the list.
|
||||
- Make sure your additions are in alphabetical order. This includes the headers and items themselves.
|
||||
- Ensure that assets you submit are of high quality, documented well, and are recently maintained. It also helps if they're popular so I can research them before adding them to the list.
|
||||
- This is not meant to be used as a list to advertise your own assets. Free or open-source assets should be prioritized over paid assets if they are of similar quality and feature sets.
|
||||
|
||||
## Special thanks
|
||||
This was forked from /sindresorhus/awesone. Special thanks to [](https://github.com/sindresorhus/awesome) for starting this list and those that contributed to it [contributors](https://github.com/suenot/awesome-ccxt/graphs/contributors), this wouldn't be possible without you!
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../CHANGELOG.md
|
||||
@@ -0,0 +1,156 @@
|
||||
# CCXT CLI (Command-Line Interface)
|
||||
|
||||
CCXT includes an example that allows calling all exchange methods and properties from command line. One doesn't even have to be a programmer or write code – any user can use it!
|
||||
|
||||
The CLI interface is a program in CCXT that takes the exchange name and some params from the command line and executes a corresponding call from CCXT printing the output of the call back to the user. Thus, with CLI you can use CCXT out of the box, not a single line of code needed.
|
||||
|
||||
CCXT command line interface is very handy and useful for:
|
||||
|
||||
- bash api scripting
|
||||
- cron/crontab trading automation
|
||||
- resolving issues with your code
|
||||
- debugging the exchange errors
|
||||
- performing quick cryptocurrency trading from command-line
|
||||
- aggregating data for backtesting
|
||||
- adding interoperability with other systems and frameworks
|
||||
- learning the basics of cryptocurrency exchange trading
|
||||
- learning CCXT and the advanced aspects of APIs
|
||||
- writing new exchange integrations
|
||||
- contributing code to CCXT
|
||||
|
||||
For the CCXT library users – we highly recommend to try CLI at least a few times to get a feel of it.
|
||||
For the CCXT library developers – CLI is more than just a recommendation, it's a must.
|
||||
|
||||
The best way to learn and understand CCXT CLI – is by experimentation, trial and error. **Warning: CLI executes your command and does not ask for a confirmation after you launch it, so be careful with numbers, confusing amounts with prices can cause a loss of funds.**
|
||||
|
||||
The same CLI design is implemented in all supported languages, TypeScript, JavaScript, Python and PHP – for the purposes of example code for the developers.
|
||||
In other words, the existing CLI contains three implementations that are in many ways identical. The code in those three CLI examples is intended to be "easily understandable".
|
||||
|
||||
The source code of the CLI is available here:
|
||||
|
||||
- https://github.com/ccxt/ccxt/blob/master/examples/ts/cli.ts
|
||||
- https://github.com/ccxt/ccxt/blob/master/examples/js/cli.js
|
||||
- https://github.com/ccxt/ccxt/blob/master/examples/py/cli.py
|
||||
- https://github.com/ccxt/ccxt/blob/master/examples/php/cli.php
|
||||
|
||||
## Install globally
|
||||
```shell
|
||||
npm -g ccxt
|
||||
```
|
||||
- Update using `npm update ccxt -g`
|
||||
|
||||
## Install
|
||||
|
||||
1. Clone the CCXT repository:
|
||||
```shell
|
||||
git clone https://github.com/ccxt/ccxt
|
||||
```
|
||||
2. Change directory to the cloned repository:
|
||||
```shell
|
||||
cd ccxt
|
||||
```
|
||||
3. Install the dependencies:
|
||||
- Node.js + npm: `npm install`
|
||||
- PHP + Composer: `composer install`
|
||||
|
||||
4. Run the script:
|
||||
- Node.js: `node examples/js/cli okx fetchTicker ETH/USDT`
|
||||
- Python: `python3 examples/py/cli.py okx fetch_ticker ETH/USDT`
|
||||
- PHP: `php -f examples/php/cli.php okx fetch_ticker ETH/USDT`
|
||||
|
||||
## Usage
|
||||
|
||||
The CLI script requires at least one argument, that is, the exchange id ([the list of supported exchanges and their ids](https://github.com/ccxt/ccxt#supported-cryptocurrency-exchange-markets)). If you don't specify the exchange id, the script will print the list of all exchange ids for reference.
|
||||
|
||||
Upon launch, CLI will create and initialize the exchange instance and will also call [exchange.loadMarkets()](https://github.com/ccxt/ccxt/wiki/Manual#loading-markets) on that exchange.
|
||||
If you don't specify any other command-line arguments to CLI except the exchange id argument, then the CLI script will print out all the contents of the exchange object, including the list of all the methods and properties and all the loaded markets (the output may be extremely long in that case).
|
||||
|
||||
Normally, following the exchange id argument one would specify a method name to call with its arguments or an exchange property to inspect on the exchange instance.
|
||||
|
||||
### Inspecting Exchange Properties
|
||||
|
||||
If the only parameter you specify to CLI is the exchange id, then it will print out the contents of the exchange instance including all properties, methods, markets, currencies, etc. **Warning: exchange contents are HUGE and this will dump A LOT of output to your screen!**
|
||||
|
||||
```shell
|
||||
node examples/js/cli bybit
|
||||
```
|
||||
|
||||
You can specify the name of the property of the exchange to narrow the output down to a reasonable size.
|
||||
|
||||
```shell
|
||||
node examples/js/cli okx markets # will print out the list of all the loaded markets
|
||||
node examples/js/cli binance currencies # will print out a table of all the loaded currencies
|
||||
node examples/js/cli gate options # will print out the contents of the exchange-specific options
|
||||
```
|
||||
|
||||
You can easily view which methods are supported on the various exchanges:
|
||||
|
||||
```shell
|
||||
node examples/js/exchange-capabilities | less -S -R
|
||||
```
|
||||
|
||||
### Calling A Unified Method By Name
|
||||
|
||||
Calling unified methods is easy:
|
||||
|
||||
```shell
|
||||
node examples/js/cli okx fetchOrderBook BTC/USDT # will fetch the orderbook from exchange instance and will print it out as a table
|
||||
node examples/js/cli binance fetchTrades ETH/USDT # will fetch a list of most recent public trades and will print a table of them
|
||||
node examples/js/cli bitget fetchTickers # will fetch all tickers one by one
|
||||
node examples/js/cli bitget fetchTickers --table # will fetch all tickers and will print them out as a table
|
||||
node examples/js/cli bitget fetchTickers '["BTC/USDT","ETH/USDT"]' # will fetch the tickers specified in the array argument
|
||||
```
|
||||
|
||||
Exchange specific parameters can be set in the last argument of every unified method:
|
||||
|
||||
```shell
|
||||
node examples/js/cli bybit setMarginMode isolated BTC/USDT '{"leverage":"8"}' # set the margin mode while specifying the exchange specific leverage parameter
|
||||
```
|
||||
|
||||
### Calling An Exchange-Specific Method By Name
|
||||
|
||||
Here's an example of fetching the order book on okx in sandbox mode using the implicit API and the exchange specific instId and sz parameters:
|
||||
|
||||
```shell
|
||||
node examples/js/cli okx publicGetMarketBooks '{"instId":"BTC-USDT","sz":"3"}' --sandbox
|
||||
```
|
||||
|
||||
## Authentication And Overrides
|
||||
|
||||
Public exchange APIs don't require authentication. You can use the CLI to call any method of a public API. The difference between public APIs and private APIs is described in the Manual, here: [Public/Private API](https://github.com/ccxt/ccxt/wiki/Manual#publicprivate-api).
|
||||
|
||||
For private API calls, by default the CLI script will look for API keys in the `keys.local.json` file in the root of the repository cloned to your working directory and will also look up exchange credentials in the environment variables. More details here: [Adding Exchange Credentials](https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#adding-exchange-credentials).
|
||||
|
||||
## Unified API vs Exchange-Specific API
|
||||
|
||||
CLI supports all possible methods and properties that exist on the exchange instance.
|
||||
|
||||
### Run with jq
|
||||
Install jq
|
||||
|
||||
#### **Ubuntu**
|
||||
```shell
|
||||
sudo apt-get install jq
|
||||
```
|
||||
#### **Brew (Mac)**
|
||||
```shell
|
||||
brew install jq
|
||||
```
|
||||
#### **Choco (Windows)**
|
||||
```shell
|
||||
choco install jq -y
|
||||
```
|
||||
|
||||
#### Examples
|
||||
- Get ticker price of BTC/USDT: `ccxt binance fetchTicker BTC/USDT | jq '.price'
|
||||
- watch price and amount of trades:
|
||||
```shell
|
||||
`ccxt binance watchTrades BTC/USDT --raw | jq -c '[.[] | {price: .price, amount: .amount}]'`
|
||||
```
|
||||
|
||||
- fuzzy search between trades (requires fzf):
|
||||
```shell
|
||||
`ccxt binance fetchTrades --raw | jq -c '.[]' | fzf`
|
||||
```
|
||||
|
||||

|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../CONTRIBUTING.md
|
||||
@@ -0,0 +1,11 @@
|
||||
# CCXT Certification Program · 
|
||||
|
||||
The structure of CCXT defines a good, portable and cross-compatible standard for exchanges' API interfaces, that is implemented in the CCXT Unified API. Exchanges are welcome to apply for our certification program. Certification is technically supervised and quality-assured by members of the CCXT Dev Team. That implies that an exchange having a "certified" badge is properly implemented and tested by the authors of CCXT. Certification means less bugs, more functionality, priority support and a much more stable and efficient implementation in general.
|
||||
|
||||
## Requirements
|
||||
|
||||
Getting integrated and certified requires the exchange to implement a quality API. Please, see the full list of technical requirements here: https://github.com/ccxt/ccxt/wiki/Requirements
|
||||
|
||||
## Contact Us
|
||||
|
||||
For inquiries on getting your exchange integrated, listed and certified: info@ccxt.trade
|
||||
@@ -0,0 +1,54 @@
|
||||
# CCXT Cryptocurrency Trading Library Examples
|
||||
|
||||

|
||||
|
||||
To run the ccxt examples from any folder type one of the following commands in console.
|
||||
|
||||
## Typescript
|
||||
|
||||
[Typescript Examples](/examples/ts/)
|
||||
|
||||
---
|
||||
|
||||
## JavaScript
|
||||
|
||||
[JavaScript Examples](/examples/js/)
|
||||
|
||||
```shell
|
||||
node path/to/example.js # substitute for actual filename here
|
||||
```
|
||||
|
||||
These examples might require the following super-useful high-quality Node.js modules by [xpl](https://github.com/xpl):
|
||||
|
||||
- [ololog](https://github.com/xpl/ololog): Platform-agnostic logging with blackjack and hookers ([ololog @ npm](https://npmjs.com/package/ololog))
|
||||
- [ansicolor](https://github.com/xpl/ansicolor): A quality JavaScript library for the ANSI color/style management ([ansicolor @ npm](https://npmjs.com/package/ansicolor))
|
||||
- [as-table](https://github.com/xpl/as-table): A simple function that prints objects as ASCII tables ([as-table @ npm](https://npmjs.com/package/as-table))
|
||||
|
||||
All of the modules above are installed with the ccxt library devDependencies by npm automatically.
|
||||
|
||||
<img width="842" alt="bitcoin ascii chart" src="https://user-images.githubusercontent.com/1294454/29673849-156f58c6-88f9-11e7-8955-fb3f37467234.png">
|
||||
|
||||
---
|
||||
|
||||
## PHP
|
||||
|
||||
[PHP Examples](/examples/php/)
|
||||
|
||||
```shell
|
||||
php -f path/to/example.php # substitute for actual filename here
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Python
|
||||
|
||||
[Python Examples](/examples/py/)
|
||||
|
||||

|
||||
|
||||
```shell
|
||||
python path/to/example.py # substitute for actual filename here
|
||||
```
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
# Exchanges By Country
|
||||
|
||||
The ccxt library currently supports the following cryptocurrency exchange markets and trading APIs:
|
||||
|
||||
|country / region |logo |id |name |ver |
|
||||
|--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|-----------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------:|
|
||||
| Australia | [](https://btcmarkets.net) | btcmarkets | [BTC Markets](https://btcmarkets.net) | [](https://api.btcmarkets.net/doc/v3) |
|
||||
| Australia | [](https://www.coinspot.com.au/register?code=PJURCU) | coinspot | [CoinSpot](https://www.coinspot.com.au/register?code=PJURCU) | [](https://www.coinspot.com.au/api) |
|
||||
| Australia | [](https://www.independentreserve.com) | independentreserve | [Independent Reserve](https://www.independentreserve.com) | [](https://www.independentreserve.com/API) |
|
||||
| Australia | [](https://timex.io/?refcode=1x27vNkTbP1uwkCck) | timex | [TimeX](https://timex.io/?refcode=1x27vNkTbP1uwkCck) | [](https://plasma-relay-backend.timex.io/swagger-ui/index.html) |
|
||||
| Austria | [](https://onetrading.com/) | onetrading | [One Trading](https://onetrading.com/) | [](https://docs.onetrading.com) |
|
||||
| Bahamas | [](https://oceanex.pro/signup?referral=VE24QX) | oceanex | [OceanEx](https://oceanex.pro/signup?referral=VE24QX) | [](https://api.oceanex.pro/doc/v1) |
|
||||
| Bermuda | [](https://global.hashkey.com/en-US/register/invite?invite_code=82FQUN) | hashkey | [HashKey Global](https://global.hashkey.com/en-US/register/invite?invite_code=82FQUN) | [](https://hashkeyglobal-apidoc.readme.io/) |
|
||||
| Brazil | [](https://www.mercadobitcoin.com.br) | mercado | [Mercado Bitcoin](https://www.mercadobitcoin.com.br) | [](https://www.mercadobitcoin.com.br/api-doc) |
|
||||
| Brazil | [](https://www.novadax.com.br/?s=ccxt) | novadax | [NovaDAX](https://www.novadax.com.br/?s=ccxt) | [](https://doc.novadax.com/pt-BR/) |
|
||||
| British Virgin Islands | [](https://www.bitfinex.com) | bitfinex | [Bitfinex](https://www.bitfinex.com) | [](https://docs.bitfinex.com/v2/docs/) |
|
||||
| British Virgin Islands | [](https://www.bybit.com/register?affiliate_id=35953) | bybit | [Bybit](https://www.bybit.com/register?affiliate_id=35953) | [](https://bybit-exchange.github.io/docs/inverse/) |
|
||||
| British Virgin Islands | [](https://partner.coincatch.cc/bg/92hy70391729607848548) | coincatch | [CoinCatch](https://partner.coincatch.cc/bg/92hy70391729607848548) | [](https://coincatch.github.io/github.io/en/) |
|
||||
| Canada | [](https://app.cryptomus.com/signup/?ref=JRP4yj) | cryptomus | [Cryptomus](https://app.cryptomus.com/signup/?ref=JRP4yj) | [](https://doc.cryptomus.com/personal) |
|
||||
| Canada | [](https://one.ndax.io/bfQiSL) | ndax | [NDAX](https://one.ndax.io/bfQiSL) | [](https://apidoc.ndax.io/) |
|
||||
| Cayman Islands | [](https://latoken.com/invite?r=mvgp2djk) | latoken | [Latoken](https://latoken.com/invite?r=mvgp2djk) | [](https://api.latoken.com) |
|
||||
| Cayman Islands | [](https://trade.mode.network?ref=MODETRADE) | modetrade | [Mode Trade](https://trade.mode.network?ref=MODETRADE) | [](undefined) |
|
||||
| Cayman Islands | [](https://www.toobit.com/en-US/r?i=IFFPy0) | toobit | [Toobit](https://www.toobit.com/en-US/r?i=IFFPy0) | [](https://toobit-docs.github.io/apidocs/spot/v1/en/) |
|
||||
| Cayman Islands | [](https://woox.io/register?ref=DIJT0CNL) | woo | [WOO X](https://woox.io/register?ref=DIJT0CNL) | [](https://docs.woox.io/) |
|
||||
| Cayman Islands | [](https://dex.woo.org/en/trade?ref=CCXT) | woofipro | [WOOFI PRO](https://dex.woo.org/en/trade?ref=CCXT) | [](https://orderly.network/docs/build-on-evm/building-on-evm) |
|
||||
| China | [](https://b1.run/users/new?code=D3LLBVFT) | bigone | [BigONE](https://b1.run/users/new?code=D3LLBVFT) | [](https://open.big.one/docs/api.html) |
|
||||
| China | [](http://www.bitmart.com/?r=rQCFLh) | bitmart | [BitMart](http://www.bitmart.com/?r=rQCFLh) | [](https://developer-pro.bitmart.com/) |
|
||||
| China | [](https://www.coinex.com/register?refer_code=yw5fz) | coinex | [CoinEx](https://www.coinex.com/register?refer_code=yw5fz) | [](https://docs.coinex.com/api/v2) |
|
||||
| China | [](https://www.htx.com.vc/invite/en-us/1h?invite_code=6rmm2223) | htx | [HTX](https://www.htx.com.vc/invite/en-us/1h?invite_code=6rmm2223) | [](https://huobiapi.github.io/docs/spot/v1/en/) |
|
||||
| China | [](https://www.lbank.com/login/?icode=7QCY) | lbank | [LBank](https://www.lbank.com/login/?icode=7QCY) | [](https://www.lbank.com/en-US/docs/index.html) |
|
||||
| China | [](https://www.my.okx.com/join/CCXT2023) | myokx | [MyOKX (EEA)](https://www.my.okx.com/join/CCXT2023) | [](https://my.okx.com/docs-v5/en/#overview) |
|
||||
| China | [](https://www.okcoin.com/account/register?flag=activity&channelId=600001513) | okcoin | [OKCoin](https://www.okcoin.com/account/register?flag=activity&channelId=600001513) | [](https://www.okcoin.com/docs/en/) |
|
||||
| China | [](https://www.okx.com/join/CCXT2023) | okx | [OKX](https://www.okx.com/join/CCXT2023) | [](https://www.okx.com/docs-v5/en/) |
|
||||
| China | [](https://www.app.okx.com/join/CCXT2023) | okxus | [OKX (US)](https://www.app.okx.com/join/CCXT2023) | [](https://app.okx.com/docs-v5/en/#overview) |
|
||||
| China | [](https://phemex.com/register?referralCode=EDNVJ) | phemex | [Phemex](https://phemex.com/register?referralCode=EDNVJ) | [](https://phemex-docs.github.io/#overview) |
|
||||
| Cyprus | [](https://cex.io/r/0/up105393824/0/) | cex | [CEX.IO](https://cex.io/r/0/up105393824/0/) | [](https://trade.cex.io/docs/) |
|
||||
| Czech Republic | [](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | coinmate | [CoinMate](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | [](https://coinmate.docs.apiary.io) |
|
||||
| EU | [](https://cex.io/r/0/up105393824/0/) | cex | [CEX.IO](https://cex.io/r/0/up105393824/0/) | [](https://trade.cex.io/docs/) |
|
||||
| EU | [](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | coinmate | [CoinMate](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | [](https://coinmate.docs.apiary.io) |
|
||||
| EU | [](https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj) | paymium | [Paymium](https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj) | [](https://github.com/Paymium/api-documentation) |
|
||||
| Estonia | [](https://go.coinmetro.com/?ref=crypto24) | coinmetro | [Coinmetro](https://go.coinmetro.com/?ref=crypto24) | [](https://documenter.getpostman.com/view/3653795/SVfWN6KS) |
|
||||
| Estonia | [](https://whitebit.com/referral/d9bdf40e-28f2-4b52-b2f9-cd1415d82963) | whitebit | [WhiteBit](https://whitebit.com/referral/d9bdf40e-28f2-4b52-b2f9-cd1415d82963) | [](https://github.com/whitebit-exchange/api-docs) |
|
||||
| Estonia | [](https://auth.zondaglobal.com/ref/jHlbB4mIkdS1) | zonda | [Zonda](https://auth.zondaglobal.com/ref/jHlbB4mIkdS1) | [](https://docs.zondacrypto.exchange/) |
|
||||
| France | [](https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj) | paymium | [Paymium](https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj) | [](https://github.com/Paymium/api-documentation) |
|
||||
| Hong Kong | [](http://www.bitmart.com/?r=rQCFLh) | bitmart | [BitMart](http://www.bitmart.com/?r=rQCFLh) | [](https://developer-pro.bitmart.com/) |
|
||||
| Hong Kong | [](https://hitbtc.com/?ref_id=5a5d39a65d466) | hitbtc | [HitBTC](https://hitbtc.com/?ref_id=5a5d39a65d466) | [](https://api.hitbtc.com) |
|
||||
| India | [](https://ref.bitbns.com/1090961) | bitbns | [Bitbns](https://ref.bitbns.com/1090961) | [](https://bitbns.com/trade/#/api-trading/) |
|
||||
| Indonesia | [](https://coincheck.com) | coincheck | [coincheck](https://coincheck.com) | [](https://coincheck.com/documents/exchange/api) |
|
||||
| Indonesia | [](https://indodax.com/ref/testbitcoincoid/1) | indodax | [INDODAX](https://indodax.com/ref/testbitcoincoid/1) | [](https://github.com/btcid/indodax-official-api-docs) |
|
||||
| Indonesia | [](https://tokocrypto.com) | tokocrypto | [Tokocrypto](https://tokocrypto.com) | [](https://www.tokocrypto.com/apidocs/) |
|
||||
| Israel | [](https://bit2c.co.il/Aff/63bfed10-e359-420c-ab5a-ad368dab0baf) | bit2c | [Bit2C](https://bit2c.co.il/Aff/63bfed10-e359-420c-ab5a-ad368dab0baf) | [](https://www.bit2c.co.il/home/api) |
|
||||
| Japan | [](https://backpack.exchange/join/ccxt) | backpack | [Backpack](https://backpack.exchange/join/ccxt) | [](https://docs.backpack.exchange/) |
|
||||
| Japan | [](https://bitbank.cc/) | bitbank | [bitbank](https://bitbank.cc/) | [](https://docs.bitbank.cc/) |
|
||||
| Japan | [](https://bitflyer.com) | bitflyer | [bitFlyer](https://bitflyer.com) | [](https://lightning.bitflyer.com/docs?lang=en) |
|
||||
| Japan | [](https://www.bittrade.co.jp/register/?invite_code=znnq3) | bittrade | [BitTrade](https://www.bittrade.co.jp/register/?invite_code=znnq3) | [](https://api-doc.bittrade.co.jp) |
|
||||
| Japan | [](https://www.btcbox.co.jp/) | btcbox | [BtcBox](https://www.btcbox.co.jp/) | [](https://blog.btcbox.jp/en/archives/8762) |
|
||||
| Japan | [](https://coincheck.com) | coincheck | [coincheck](https://coincheck.com) | [](https://coincheck.com/documents/exchange/api) |
|
||||
| Japan | [](https://zaif.jp) | zaif | [Zaif](https://zaif.jp) | [](https://techbureau-api-document.readthedocs.io/ja/latest/index.html) |
|
||||
| Lithuania | [](https://exmo.me/?ref=131685) | exmo | [EXMO](https://exmo.me/?ref=131685) | [](https://exmo.me/en/api_doc?ref=131685) |
|
||||
| Lithuania | [](https://p2pb2b.com?referral=ee784c53) | p2b | [p2b](https://p2pb2b.com?referral=ee784c53) | [](https://github.com/P2B-team/p2b-api-docs/blob/master/api-doc.md) |
|
||||
| Malta | [](https://bequant.io/referral/dd104e3bee7634ec) | bequant | [Bequant](https://bequant.io/referral/dd104e3bee7634ec) | [](https://api.bequant.io/) |
|
||||
| Malta | [](https://crypto.com/exch/kdacthrnxt) | cryptocom | [Crypto.com](https://crypto.com/exch/kdacthrnxt) | [](https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html) |
|
||||
| Mexico | [](https://bitso.com/?ref=itej) | bitso | [Bitso](https://bitso.com/?ref=itej) | [](https://bitso.com/api_info) |
|
||||
| Netherlands | [](https://bitvavo.com/?a=24F34952F7) | bitvavo | [Bitvavo](https://bitvavo.com/?a=24F34952F7) | [](https://docs.bitvavo.com/) |
|
||||
| Netherlands | [](https://www.deribit.com/reg-1189.4038) | deribit | [Deribit](https://www.deribit.com/reg-1189.4038) | [](https://docs.deribit.com/v2) |
|
||||
| New Zealand | [](https://www.independentreserve.com) | independentreserve | [Independent Reserve](https://www.independentreserve.com) | [](https://www.independentreserve.com/API) |
|
||||
| Panama | [](https://ox.fun/register?shareAccountId=5ZUD4a7G) | oxfun | [OXFUN](https://ox.fun/register?shareAccountId=5ZUD4a7G) | [](https://docs.ox.fun/) |
|
||||
| Philippines | [](https://coins.ph/) | coinsph | [Coins.ph](https://coins.ph/) | [](https://coins-docs.github.io/rest-api) |
|
||||
| Russia | [](https://cex.io/r/0/up105393824/0/) | cex | [CEX.IO](https://cex.io/r/0/up105393824/0/) | [](https://trade.cex.io/docs/) |
|
||||
| Russia | [](https://www.yobit.net) | yobit | [YoBit](https://www.yobit.net) | [](https://www.yobit.net/en/api/) |
|
||||
| Saint Kitts and Nevis | [](https://fmfw.io/referral/da948b21d6c92d69) | fmfwio | [FMFW.io](https://fmfw.io/referral/da948b21d6c92d69) | [](https://api.fmfw.io/) |
|
||||
| Seychelles | [](https://www.bitmex.com/app/register/NZTR1q) | bitmex | [BitMEX](https://www.bitmex.com/app/register/NZTR1q) | [](https://www.bitmex.com/app/apiOverview) |
|
||||
| Seychelles | [](https://www.kucoin.com/ucenter/signup?rcode=E5wkqe) | kucoin | [KuCoin](https://www.kucoin.com/ucenter/signup?rcode=E5wkqe) | [](https://docs.kucoin.com) |
|
||||
| Seychelles | [](https://futures.kucoin.com/?rcode=E5wkqe) | kucoinfutures | [KuCoin Futures](https://futures.kucoin.com/?rcode=E5wkqe) | [](https://docs.kucoin.com/futures) |
|
||||
| Seychelles | [](https://www.mexc.com/register?inviteCode=mexc-1FQ1GNu1) | mexc | [MEXC Global](https://www.mexc.com/register?inviteCode=mexc-1FQ1GNu1) | [](https://mexcdevelop.github.io/apidocs/) |
|
||||
| Seychelles | [](https://www.probit.com/r/34608773) | probit | [ProBit](https://www.probit.com/r/34608773) | [](https://docs-en.probit.com) |
|
||||
| Seychelles | [](https://www.xt.com/en/accounts/register?ref=9PTM9VW) | xt | [XT](https://www.xt.com/en/accounts/register?ref=9PTM9VW) | [](https://doc.xt.com/) |
|
||||
| Singapore | [](https://ascendex.com/en-us/register?inviteCode=EL6BXBQM) | ascendex | [AscendEX](https://ascendex.com/en-us/register?inviteCode=EL6BXBQM) | [](https://ascendex.github.io/ascendex-pro-api/#ascendex-pro-api-documentation) |
|
||||
| Singapore | [](https://www.bitget.com/expressly?languageType=0&channelCode=ccxt&vipCode=tg9j) | bitget | [Bitget](https://www.bitget.com/expressly?languageType=0&channelCode=ccxt&vipCode=tg9j) | [](https://www.bitget.com/api-doc/common/intro) |
|
||||
| Singapore | [](https://www.bitrue.com/affiliate/landing?cn=600000&inviteCode=EZWETQE) | bitrue | [Bitrue](https://www.bitrue.com/affiliate/landing?cn=600000&inviteCode=EZWETQE) | [](https://github.com/Bitrue-exchange/bitrue-official-api-docs) |
|
||||
| Singapore | [](https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp) | digifinex | [DigiFinex](https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp) | [](https://docs.digifinex.com) |
|
||||
| Singapore | [](https://www.luno.com/invite/44893A) | luno | [luno](https://www.luno.com/invite/44893A) | [](https://www.luno.com/en/api) |
|
||||
| South Africa | [](https://www.luno.com/invite/44893A) | luno | [luno](https://www.luno.com/invite/44893A) | [](https://www.luno.com/en/api) |
|
||||
| South Korea | [](https://www.bithumb.com) | bithumb | [Bithumb](https://www.bithumb.com) | [](https://apidocs.bithumb.com) |
|
||||
| South Korea | [](http://www.bitmart.com/?r=rQCFLh) | bitmart | [BitMart](http://www.bitmart.com/?r=rQCFLh) | [](https://developer-pro.bitmart.com/) |
|
||||
| South Korea | [](https://coinone.co.kr) | coinone | [CoinOne](https://coinone.co.kr) | [](https://doc.coinone.co.kr) |
|
||||
| South Korea | [](https://www.gate.io/signup/2436035) | gate | [Gate.io](https://www.gate.io/signup/2436035) | [](https://www.gate.io/docs/developers/apiv4/en/) |
|
||||
| South Korea | [](https://pro.hollaex.com/signup?affiliation_code=QSWA6G) | hollaex | [HollaEx](https://pro.hollaex.com/signup?affiliation_code=QSWA6G) | [](https://apidocs.hollaex.com) |
|
||||
| South Korea | [](https://www.probit.com/r/34608773) | probit | [ProBit](https://www.probit.com/r/34608773) | [](https://docs-en.probit.com) |
|
||||
| South Korea | [](https://upbit.com) | upbit | [Upbit](https://upbit.com) | [](https://docs.upbit.com/docs/%EC%9A%94%EC%B2%AD-%EC%88%98-%EC%A0%9C%ED%95%9C) |
|
||||
| St. Vincent & Grenadines | [](https://www.delta.exchange/app/signup/?code=IULYNB) | delta | [Delta Exchange](https://www.delta.exchange/app/signup/?code=IULYNB) | [](https://docs.delta.exchange) |
|
||||
| Switzerland | [](https://wx.network) | wavesexchange | [Waves.Exchange](https://wx.network) | [](https://docs.wx.network) |
|
||||
| Taiwan | [](https://www.bitopro.com) | bitopro | [BitoPro](https://www.bitopro.com) | [](https://github.com/bitoex/bitopro-offical-api-docs/blob/master/v3-1/rest-1/rest.md) |
|
||||
| Turkey | [](https://www.btcturk.com) | btcturk | [BTCTurk](https://www.btcturk.com) | [](https://github.com/BTCTrader/broker-api-docs) |
|
||||
| UK | [](https://www.bitstamp.net) | bitstamp | [Bitstamp](https://www.bitstamp.net) | [](https://www.bitstamp.net/api) |
|
||||
| UK | [](https://bit.team/auth/sign-up?ref=bitboy2023) | bitteam | [BIT.TEAM](https://bit.team/auth/sign-up?ref=bitboy2023) | [](https://bit.team/trade/api/documentation) |
|
||||
| UK | [](https://cex.io/r/0/up105393824/0/) | cex | [CEX.IO](https://cex.io/r/0/up105393824/0/) | [](https://trade.cex.io/docs/) |
|
||||
| UK | [](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | coinmate | [CoinMate](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | [](https://coinmate.docs.apiary.io) |
|
||||
| UK | [](https://www.luno.com/invite/44893A) | luno | [luno](https://www.luno.com/invite/44893A) | [](https://www.luno.com/en/api) |
|
||||
| US | [](https://alpaca.markets) | alpaca | [Alpaca](https://alpaca.markets) | [](https://alpaca.markets/docs/) |
|
||||
| US | [](https://www.binance.us/?ref=35005074) | binanceus | [Binance US](https://www.binance.us/?ref=35005074) | [](https://github.com/binance-us/binance-official-api-docs) |
|
||||
| US | [](https://bingx.com/invite/OHETOM) | bingx | [BingX](https://bingx.com/invite/OHETOM) | [](https://bingx-api.github.io/docs/) |
|
||||
| US | [](http://www.bitmart.com/?r=rQCFLh) | bitmart | [BitMart](http://www.bitmart.com/?r=rQCFLh) | [](https://developer-pro.bitmart.com/) |
|
||||
| US | [](https://blofin.com/register?referral_code=f79EsS) | blofin | [BloFin](https://blofin.com/register?referral_code=f79EsS) | [](https://blofin.com/docs) |
|
||||
| US | [](https://btc-alpha.com/?r=123788) | btcalpha | [BTC-Alpha](https://btc-alpha.com/?r=123788) | [](https://btc-alpha.github.io/api-docs) |
|
||||
| US | [](https://www.coinbase.com/join/58cbe25a355148797479dbd2) | coinbase | [Coinbase Advanced](https://www.coinbase.com/join/58cbe25a355148797479dbd2) | [](https://developers.coinbase.com/api/v2) |
|
||||
| US | [](https://coinbase.com/) | coinbaseexchange | [Coinbase Exchange](https://coinbase.com/) | [](https://docs.cloud.coinbase.com/exchange/docs/) |
|
||||
| US | [](https://international.coinbase.com) | coinbaseinternational | [Coinbase International](https://international.coinbase.com) | [](https://docs.cloud.coinbase.com/intx/docs) |
|
||||
| US | [](https://gemini.com/) | gemini | [Gemini](https://gemini.com/) | [](https://docs.gemini.com/rest-api) |
|
||||
| US | [](hibachi.xyz/r/ZBL2YFWIHU) | hibachi | [Hibachi](hibachi.xyz/r/ZBL2YFWIHU) | [](undefined) |
|
||||
| US | [](https://www.kraken.com) | kraken | [Kraken](https://www.kraken.com) | [](https://docs.kraken.com/rest/) |
|
||||
| US | [](https://futures.kraken.com/) | krakenfutures | [Kraken Futures](https://futures.kraken.com/) | [](https://docs.kraken.com/api/docs/futures-api/trading/market-data/) |
|
||||
| US | [](https://www.my.okx.com/join/CCXT2023) | myokx | [MyOKX (EEA)](https://www.my.okx.com/join/CCXT2023) | [](https://my.okx.com/docs-v5/en/#overview) |
|
||||
| US | [](https://www.okcoin.com/account/register?flag=activity&channelId=600001513) | okcoin | [OKCoin](https://www.okcoin.com/account/register?flag=activity&channelId=600001513) | [](https://www.okcoin.com/docs/en/) |
|
||||
| US | [](https://www.okx.com/join/CCXT2023) | okx | [OKX](https://www.okx.com/join/CCXT2023) | [](https://www.okx.com/docs-v5/en/) |
|
||||
| US | [](https://www.app.okx.com/join/CCXT2023) | okxus | [OKX (US)](https://www.app.okx.com/join/CCXT2023) | [](https://app.okx.com/docs-v5/en/#overview) |
|
||||
| US | [](https://poloniex.com/signup?c=UBFZJRPJ) | poloniex | [Poloniex](https://poloniex.com/signup?c=UBFZJRPJ) | [](https://api-docs.poloniex.com/spot/) |
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# Supported Exchanges
|
||||
<!--- init list -->The CCXT library currently supports the following 104 cryptocurrency exchange markets and trading APIs:
|
||||
|
||||
|logo |id |name |ver |type |certified |pro |
|
||||
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|----------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------:|--------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
|
||||
| [](https://alpaca.markets) | alpaca | [Alpaca](https://alpaca.markets) | [](https://alpaca.markets/docs/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://omni.apex.exchange/trade) | apex | [Apex](https://omni.apex.exchange/trade) | [](https://api-docs.pro.apex.exchange) |  | | [](https://ccxt.pro) |
|
||||
| [](https://ascendex.com/en-us/register?inviteCode=EL6BXBQM) | ascendex | [AscendEX](https://ascendex.com/en-us/register?inviteCode=EL6BXBQM) | [](https://ascendex.github.io/ascendex-pro-api/#ascendex-pro-api-documentation) |  | | [](https://ccxt.pro) |
|
||||
| [](https://bequant.io/referral/dd104e3bee7634ec) | bequant | [Bequant](https://bequant.io/referral/dd104e3bee7634ec) | [](https://api.bequant.io/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://b1.run/users/new?code=D3LLBVFT) | bigone | [BigONE](https://b1.run/users/new?code=D3LLBVFT) | [](https://open.big.one/docs/api.html) |  | | |
|
||||
| [](https://accounts.binance.com/en/register?ref=D7YA7CLY) | binance | [Binance](https://accounts.binance.com/en/register?ref=D7YA7CLY) | [](https://developers.binance.com/en) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://accounts.binance.com/en/register?ref=D7YA7CLY) | binancecoinm | [Binance COIN-M](https://accounts.binance.com/en/register?ref=D7YA7CLY) | [](https://binance-docs.github.io/apidocs/delivery/en/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://www.binance.us/?ref=35005074) | binanceus | [Binance US](https://www.binance.us/?ref=35005074) | [](https://github.com/binance-us/binance-official-api-docs) |  | | [](https://ccxt.pro) |
|
||||
| [](https://accounts.binance.com/en/register?ref=D7YA7CLY) | binanceusdm | [Binance USDⓈ-M](https://accounts.binance.com/en/register?ref=D7YA7CLY) | [](https://binance-docs.github.io/apidocs/futures/en/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://bingx.com/invite/OHETOM) | bingx | [BingX](https://bingx.com/invite/OHETOM) | [](https://bingx-api.github.io/docs/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://bit2c.co.il/Aff/63bfed10-e359-420c-ab5a-ad368dab0baf) | bit2c | [Bit2C](https://bit2c.co.il/Aff/63bfed10-e359-420c-ab5a-ad368dab0baf) | [](https://www.bit2c.co.il/home/api) |  | | |
|
||||
| [](https://bitbank.cc/) | bitbank | [bitbank](https://bitbank.cc/) | [](https://docs.bitbank.cc/) |  | | |
|
||||
| [](https://ref.bitbns.com/1090961) | bitbns | [Bitbns](https://ref.bitbns.com/1090961) | [](https://bitbns.com/trade/#/api-trading/) |  | | |
|
||||
| [](https://www.bitfinex.com) | bitfinex | [Bitfinex](https://www.bitfinex.com) | [](https://docs.bitfinex.com/v2/docs/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://bitflyer.com) | bitflyer | [bitFlyer](https://bitflyer.com) | [](https://lightning.bitflyer.com/docs?lang=en) |  | | |
|
||||
| [](https://www.bitget.com/expressly?languageType=0&channelCode=ccxt&vipCode=tg9j) | bitget | [Bitget](https://www.bitget.com/expressly?languageType=0&channelCode=ccxt&vipCode=tg9j) | [](https://www.bitget.com/api-doc/common/intro) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://www.bithumb.com) | bithumb | [Bithumb](https://www.bithumb.com) | [](https://apidocs.bithumb.com) |  | | [](https://ccxt.pro) |
|
||||
| [](http://www.bitmart.com/?r=rQCFLh) | bitmart | [BitMart](http://www.bitmart.com/?r=rQCFLh) | [](https://developer-pro.bitmart.com/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://www.bitmex.com/app/register/NZTR1q) | bitmex | [BitMEX](https://www.bitmex.com/app/register/NZTR1q) | [](https://www.bitmex.com/app/apiOverview) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://www.bitopro.com) | bitopro | [BitoPro](https://www.bitopro.com) | [](https://github.com/bitoex/bitopro-offical-api-docs/blob/master/v3-1/rest-1/rest.md) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.bitrue.com/affiliate/landing?cn=600000&inviteCode=EZWETQE) | bitrue | [Bitrue](https://www.bitrue.com/affiliate/landing?cn=600000&inviteCode=EZWETQE) | [](https://github.com/Bitrue-exchange/bitrue-official-api-docs) |  | | [](https://ccxt.pro) |
|
||||
| [](https://bitso.com/?ref=itej) | bitso | [Bitso](https://bitso.com/?ref=itej) | [](https://bitso.com/api_info) |  | | |
|
||||
| [](https://www.bitstamp.net) | bitstamp | [Bitstamp](https://www.bitstamp.net) | [](https://www.bitstamp.net/api) |  | | [](https://ccxt.pro) |
|
||||
| [](https://bit.team/auth/sign-up?ref=bitboy2023) | bitteam | [BIT.TEAM](https://bit.team/auth/sign-up?ref=bitboy2023) | [](https://bit.team/trade/api/documentation) |  | | |
|
||||
| [](https://bitvavo.com/?a=24F34952F7) | bitvavo | [Bitvavo](https://bitvavo.com/?a=24F34952F7) | [](https://docs.bitvavo.com/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://bl3p.eu) | bl3p | [BL3P](https://bl3p.eu) | [](https://github.com/BitonicNL/bl3p-api/tree/master/docs) |  | | |
|
||||
| [](https://blockchain.com) | blockchaincom | [Blockchain.com](https://blockchain.com) | [](https://api.blockchain.com/v3) |  | | [](https://ccxt.pro) |
|
||||
| [](https://blofin.com/register?referral_code=f79EsS) | blofin | [BloFin](https://blofin.com/register?referral_code=f79EsS) | [](https://blofin.com/docs) |  | | [](https://ccxt.pro) |
|
||||
| [](https://btc-alpha.com/?r=123788) | btcalpha | [BTC-Alpha](https://btc-alpha.com/?r=123788) | [](https://btc-alpha.github.io/api-docs) |  | | |
|
||||
| [](https://www.btcbox.co.jp/) | btcbox | [BtcBox](https://www.btcbox.co.jp/) | [](https://blog.btcbox.jp/en/archives/8762) |  | | |
|
||||
| [](https://btcmarkets.net) | btcmarkets | [BTC Markets](https://btcmarkets.net) | [](https://api.btcmarkets.net/doc/v3) |  | | |
|
||||
| [](https://www.btcturk.com) | btcturk | [BTCTurk](https://www.btcturk.com) | [](https://github.com/BTCTrader/broker-api-docs) |  | | |
|
||||
| [](https://www.bybit.com/register?affiliate_id=35953) | bybit | [Bybit](https://www.bybit.com/register?affiliate_id=35953) | [](https://bybit-exchange.github.io/docs/inverse/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://cex.io/r/0/up105393824/0/) | cex | [CEX.IO](https://cex.io/r/0/up105393824/0/) | [](https://trade.cex.io/docs/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.coinbase.com/join/58cbe25a355148797479dbd2) | coinbase | [Coinbase Advanced](https://www.coinbase.com/join/58cbe25a355148797479dbd2) | [](https://developers.coinbase.com/api/v2) |  | | [](https://ccxt.pro) |
|
||||
| [](https://coinbase.com/) | coinbaseexchange | [Coinbase Exchange](https://coinbase.com/) | [](https://docs.cloud.coinbase.com/exchange/docs/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://international.coinbase.com) | coinbaseinternational | [Coinbase International](https://international.coinbase.com) | [](https://docs.cloud.coinbase.com/intx/docs) |  | | [](https://ccxt.pro) |
|
||||
| [](https://partner.coincatch.cc/bg/92hy70391729607848548) | coincatch | [CoinCatch](https://partner.coincatch.cc/bg/92hy70391729607848548) | [](https://coincatch.github.io/github.io/en/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://coincheck.com) | coincheck | [coincheck](https://coincheck.com) | [](https://coincheck.com/documents/exchange/api) |  | | |
|
||||
| [](https://www.coinex.com/register?refer_code=yw5fz) | coinex | [CoinEx](https://www.coinex.com/register?refer_code=yw5fz) | [](https://docs.coinex.com/api/v2) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://coinlist.co) | coinlist | [Coinlist](https://coinlist.co) | [](https://trade-docs.coinlist.co) |  | | |
|
||||
| [](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | coinmate | [CoinMate](https://coinmate.io?referral=YTFkM1RsOWFObVpmY1ZjMGREQmpTRnBsWjJJNVp3PT0) | [](https://coinmate.docs.apiary.io) |  | | |
|
||||
| [](https://go.coinmetro.com/?ref=crypto24) | coinmetro | [Coinmetro](https://go.coinmetro.com/?ref=crypto24) | [](https://documenter.getpostman.com/view/3653795/SVfWN6KS) |  | | |
|
||||
| [](https://coinone.co.kr) | coinone | [CoinOne](https://coinone.co.kr) | [](https://doc.coinone.co.kr) |  | | |
|
||||
| [](https://coins.ph/) | coinsph | [Coins.ph](https://coins.ph/) | [](https://coins-docs.github.io/rest-api) |  | | |
|
||||
| [](https://www.coinspot.com.au/register?code=PJURCU) | coinspot | [CoinSpot](https://www.coinspot.com.au/register?code=PJURCU) | [](https://www.coinspot.com.au/api) |  | | |
|
||||
| [](https://crypto.com/exch/kdacthrnxt) | cryptocom | [Crypto.com](https://crypto.com/exch/kdacthrnxt) | [](https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://app.cryptomus.com/signup/?ref=JRP4yj) | cryptomus | [Cryptomus](https://app.cryptomus.com/signup/?ref=JRP4yj) | [](https://doc.cryptomus.com/personal) |  | | |
|
||||
| [](https://app.defx.com/join/6I2CZ7) | defx | [Defx X](https://app.defx.com/join/6I2CZ7) | [](https://docs.defx.com/docs) |  | | |
|
||||
| [](https://www.delta.exchange/app/signup/?code=IULYNB) | delta | [Delta Exchange](https://www.delta.exchange/app/signup/?code=IULYNB) | [](https://docs.delta.exchange) |  | | |
|
||||
| [](https://www.deribit.com/reg-1189.4038) | deribit | [Deribit](https://www.deribit.com/reg-1189.4038) | [](https://docs.deribit.com/v2) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.derive.xyz/invite/3VB0B) | derive | [derive](https://www.derive.xyz/invite/3VB0B) | [](https://docs.derive.xyz/docs/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp) | digifinex | [DigiFinex](https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp) | [](https://docs.digifinex.com) |  | | |
|
||||
| [](https://www.ellipx.com) | ellipx | [Ellipx](https://www.ellipx.com) | [](https://docs.google.com/document/d/1ZXzTQYffKE_EglTaKptxGQERRnunuLHEMmar7VC9syM) |  | | |
|
||||
| [](https://exmo.me/?ref=131685) | exmo | [EXMO](https://exmo.me/?ref=131685) | [](https://exmo.me/en/api_doc?ref=131685) |  | | |
|
||||
| [](https://fmfw.io/referral/da948b21d6c92d69) | fmfwio | [FMFW.io](https://fmfw.io/referral/da948b21d6c92d69) | [](https://api.fmfw.io/) |  | | |
|
||||
| [](https://www.gate.io/signup/2436035) | gate | [Gate.io](https://www.gate.io/signup/2436035) | [](https://www.gate.io/docs/developers/apiv4/en/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://gemini.com/) | gemini | [Gemini](https://gemini.com/) | [](https://docs.gemini.com/rest-api) |  | | [](https://ccxt.pro) |
|
||||
| [](https://global.hashkey.com/en-US/register/invite?invite_code=82FQUN) | hashkey | [HashKey Global](https://global.hashkey.com/en-US/register/invite?invite_code=82FQUN) | [](https://hashkeyglobal-apidoc.readme.io/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://hitbtc.com/?ref_id=5a5d39a65d466) | hitbtc | [HitBTC](https://hitbtc.com/?ref_id=5a5d39a65d466) | [](https://api.hitbtc.com) |  | | |
|
||||
| [](https://pro.hollaex.com/signup?affiliation_code=QSWA6G) | hollaex | [HollaEx](https://pro.hollaex.com/signup?affiliation_code=QSWA6G) | [](https://apidocs.hollaex.com) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.htx.com.vc/invite/en-us/1h?invite_code=6rmm2223) | htx | [HTX](https://www.htx.com.vc/invite/en-us/1h?invite_code=6rmm2223) | [](https://huobiapi.github.io/docs/spot/v1/en/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://www.huobi.co.jp/register/?invite_code=znnq3) | huobijp | [Huobi Japan](https://www.huobi.co.jp/register/?invite_code=znnq3) | [](https://api-doc.huobi.co.jp) |  | | [](https://ccxt.pro) |
|
||||
| [](https://app.hyperliquid.xyz/) | hyperliquid | [Hyperliquid](https://app.hyperliquid.xyz/) | [](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://idex.io) | idex | [IDEX](https://idex.io) | [](https://api-docs-v3.idex.io/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.independentreserve.com) | independentreserve | [Independent Reserve](https://www.independentreserve.com) | [](https://www.independentreserve.com/API) |  | | [](https://ccxt.pro) |
|
||||
| [](https://indodax.com/ref/testbitcoincoid/1) | indodax | [INDODAX](https://indodax.com/ref/testbitcoincoid/1) | [](https://github.com/btcid/indodax-official-api-docs) |  | | |
|
||||
| [](https://www.kraken.com) | kraken | [Kraken](https://www.kraken.com) | [](https://docs.kraken.com/rest/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://futures.kraken.com/) | krakenfutures | [Kraken Futures](https://futures.kraken.com/) | [](https://docs.futures.kraken.com/#introduction) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.kucoin.com/ucenter/signup?rcode=E5wkqe) | kucoin | [KuCoin](https://www.kucoin.com/ucenter/signup?rcode=E5wkqe) | [](https://docs.kucoin.com) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://futures.kucoin.com/?rcode=E5wkqe) | kucoinfutures | [KuCoin Futures](https://futures.kucoin.com/?rcode=E5wkqe) | [](https://docs.kucoin.com/futures) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://kuna.io?r=kunaid-gvfihe8az7o4) | kuna | [Kuna](https://kuna.io?r=kunaid-gvfihe8az7o4) | [](https://kuna.io/documents/api) |  | | |
|
||||
| [](https://latoken.com/invite?r=mvgp2djk) | latoken | [Latoken](https://latoken.com/invite?r=mvgp2djk) | [](https://api.latoken.com) |  | | |
|
||||
| [](https://www.lbank.com/login/?icode=7QCY) | lbank | [LBank](https://www.lbank.com/login/?icode=7QCY) | [](https://www.lbank.com/en-US/docs/index.html) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.luno.com/invite/44893A) | luno | [luno](https://www.luno.com/invite/44893A) | [](https://www.luno.com/en/api) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.mercadobitcoin.com.br) | mercado | [Mercado Bitcoin](https://www.mercadobitcoin.com.br) | [](https://www.mercadobitcoin.com.br/api-doc) |  | | |
|
||||
| [](https://www.mexc.com/register?inviteCode=mexc-1FQ1GNu1) | mexc | [MEXC Global](https://www.mexc.com/register?inviteCode=mexc-1FQ1GNu1) | [](https://mexcdevelop.github.io/apidocs/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://www.my.okx.com/join/CCXT2023) | myokx | [MyOKX (EEA)](https://www.my.okx.com/join/CCXT2023) | [](https://my.okx.com/docs-v5/en/#overview) |  | | [](https://ccxt.pro) |
|
||||
| [](https://one.ndax.io/bfQiSL) | ndax | [NDAX](https://one.ndax.io/bfQiSL) | [](https://apidoc.ndax.io/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.novadax.com.br/?s=ccxt) | novadax | [NovaDAX](https://www.novadax.com.br/?s=ccxt) | [](https://doc.novadax.com/pt-BR/) |  | | |
|
||||
| [](https://oceanex.pro/signup?referral=VE24QX) | oceanex | [OceanEx](https://oceanex.pro/signup?referral=VE24QX) | [](https://api.oceanex.pro/doc/v1) |  | | |
|
||||
| [](https://www.okcoin.com/account/register?flag=activity&channelId=600001513) | okcoin | [OKCoin](https://www.okcoin.com/account/register?flag=activity&channelId=600001513) | [](https://www.okcoin.com/docs/en/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.okx.com/join/CCXT2023) | okx | [OKX](https://www.okx.com/join/CCXT2023) | [](https://www.okx.com/docs-v5/en/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://onetrading.com/) | onetrading | [One Trading](https://onetrading.com/) | [](https://docs.onetrading.com) |  | | [](https://ccxt.pro) |
|
||||
| [](https://ox.fun/register?shareAccountId=5ZUD4a7G) | oxfun | [OXFUN](https://ox.fun/register?shareAccountId=5ZUD4a7G) | [](https://docs.ox.fun/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://p2pb2b.com?referral=ee784c53) | p2b | [p2b](https://p2pb2b.com?referral=ee784c53) | [](https://github.com/P2B-team/p2b-api-docs/blob/master/api-doc.md) |  | | [](https://ccxt.pro) |
|
||||
| [](https://app.paradex.trade/r/ccxt24) | paradex | [Paradex](https://app.paradex.trade/r/ccxt24) | [](https://docs.api.testnet.paradex.trade/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj) | paymium | [Paymium](https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj) | [](https://github.com/Paymium/api-documentation) |  | | |
|
||||
| [](https://phemex.com/register?referralCode=EDNVJ) | phemex | [Phemex](https://phemex.com/register?referralCode=EDNVJ) | [](https://phemex-docs.github.io/#overview) |  | | [](https://ccxt.pro) |
|
||||
| [](https://poloniex.com/signup?c=UBFZJRPJ) | poloniex | [Poloniex](https://poloniex.com/signup?c=UBFZJRPJ) | [](https://api-docs.poloniex.com/spot/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.probit.com/r/34608773) | probit | [ProBit](https://www.probit.com/r/34608773) | [](https://docs-en.probit.com) |  | | [](https://ccxt.pro) |
|
||||
| [](https://timex.io/?refcode=1x27vNkTbP1uwkCck) | timex | [TimeX](https://timex.io/?refcode=1x27vNkTbP1uwkCck) | [](https://plasma-relay-backend.timex.io/swagger-ui/index.html) |  | | |
|
||||
| [](https://tokocrypto.com) | tokocrypto | [Tokocrypto](https://tokocrypto.com) | [](https://www.tokocrypto.com/apidocs/) |  | | |
|
||||
| [](https://tradeogre.com) | tradeogre | [tradeogre](https://tradeogre.com) | [](https://tradeogre.com/help/api) |  | | [](https://ccxt.pro) |
|
||||
| [](https://upbit.com) | upbit | [Upbit](https://upbit.com) | [](https://docs.upbit.com/docs/%EC%9A%94%EC%B2%AD-%EC%88%98-%EC%A0%9C%ED%95%9C) |  | | [](https://ccxt.pro) |
|
||||
| [](https://app.vertexprotocol.com?referrer=0xCfC9BaB96a2eA3d3c3F031c005e82E1D9F295aC1) | vertex | [Vertex](https://app.vertexprotocol.com?referrer=0xCfC9BaB96a2eA3d3c3F031c005e82E1D9F295aC1) | [](https://docs.vertexprotocol.com/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://wx.network) | wavesexchange | [Waves.Exchange](https://wx.network) | [](https://docs.wx.network) |  | | |
|
||||
| [](https://whitebit.com/referral/d9bdf40e-28f2-4b52-b2f9-cd1415d82963) | whitebit | [WhiteBit](https://whitebit.com/referral/d9bdf40e-28f2-4b52-b2f9-cd1415d82963) | [](https://github.com/whitebit-exchange/api-docs) |  | | [](https://ccxt.pro) |
|
||||
| [](https://woox.io/register?ref=DIJT0CNL) | woo | [WOO X](https://woox.io/register?ref=DIJT0CNL) | [](https://docs.woox.io/) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://dex.woo.org/en/trade?ref=CCXT) | woofipro | [WOOFI PRO](https://dex.woo.org/en/trade?ref=CCXT) | [](https://orderly.network/docs/build-on-evm/building-on-evm) |  | [](https://github.com/ccxt/ccxt/wiki/Certification) | [](https://ccxt.pro) |
|
||||
| [](https://www.xt.com/en/accounts/register?ref=9PTM9VW) | xt | [XT](https://www.xt.com/en/accounts/register?ref=9PTM9VW) | [](https://doc.xt.com/) |  | | [](https://ccxt.pro) |
|
||||
| [](https://www.yobit.net) | yobit | [YoBit](https://www.yobit.net) | [](https://www.yobit.net/en/api/) |  | | |
|
||||
| [](https://zaif.jp) | zaif | [Zaif](https://zaif.jp) | [](https://techbureau-api-document.readthedocs.io/ja/latest/index.html) |  | | |
|
||||
| [](https://auth.zondaglobal.com/ref/jHlbB4mIkdS1) | zonda | [Zonda](https://auth.zondaglobal.com/ref/jHlbB4mIkdS1) | [](https://docs.zondacrypto.exchange/) |  | | |<!--- init list -->
|
||||
@@ -0,0 +1,172 @@
|
||||
# Frequently Asked Questions
|
||||
|
||||
|
||||
## I'm trying to run the code, but it's not working, how do I fix it?
|
||||
|
||||
If your question is formulated in a short manner like the above, we won't help. We don't teach programming. If you're unable to read and understand the [Manual](https://github.com/ccxt/ccxt/wiki) or you can't follow precisely the guides from the [CONTRIBUTING](https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md) doc on how to report an issue, we won't help either. Read the CONTRIBUTING guides on how to report an issue and read the Manual. You should not risk anyone's money and time without reading the entire Manual very carefully. You should not risk anything if you're not used to a lot of reading with tons of details. Also, if you don't have the confidence with the programming language you're using, there are much better places for coding fundamentals and practice. Search for `python tutorials`, `js videos`, play with examples, this is how other people climb up the learning curve. No shortcuts, if you want to learn something.
|
||||
|
||||
## What is required to get help?
|
||||
|
||||
When asking a question:
|
||||
|
||||
- Use the search button for duplicates first!
|
||||
- **Post your request and response in `verbose` mode!** Add `exchange.verbose = true` right before the line you're having issues with, and copypaste what you see on your screen. It's written and mentioned everywhere, in the [Troubleshooting](https://github.com/ccxt/ccxt/wiki/Manual#troubleshooting) section, in the [README](https://github.com/ccxt/ccxt/blob/master/README.md) and in many answers to similar questions among [previous issues](https://github.com/ccxt/ccxt/issues) and [pull requests](https://github.com/ccxt/ccxt/pulls). No excuses. The verbose output should include both the request and response from the exchange.
|
||||
- Include the full error callstack!
|
||||
- Write your programming language **and language version number**
|
||||
- Write the CCXT / CCXT Pro library version number
|
||||
- Which exchange it is
|
||||
- Which method you're trying to call
|
||||
|
||||
- **Post your code** to reproduce the problem. Make it a complete short runnable program, don't swallow the lines and make it as compact as you can (5-10 lines of code), including the exchange instantation code. Remove all irrelevant parts from it, leaving just the essence of the code to reproduce the issue.
|
||||
- **DON'T POST SCREENSHOTS OF CODE OR ERRORS, POST THE OUTPUT AND CODE IN PLAIN TEXT!**
|
||||
- **Surround code and output with triple backticks: ```GOOD```**.
|
||||
- Don't confuse the backtick symbol (`) with the quote symbol (\'): '''BAD'''
|
||||
- Don't confuse a single backtick with triple backticks: `BAD`
|
||||
|
||||
- **DO NOT POST YOUR `apiKey` AND `secret`!** Keep them safe (remove them before posting)!
|
||||
|
||||
## I am calling a method and I get an error, what am I doing wrong?
|
||||
|
||||
You're not reporting the issue properly ) Please, help the community to help you ) Read this and follow the steps: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue. Once again, your code to reproduce the issue and your verbose request and response **ARE REQUIRED**. *Just the error traceback, or just the response, or just the request, or just the code – is not enough!*
|
||||
|
||||
## I got an incorrect result from a method call, can you help?
|
||||
|
||||
Basically the same answer as the previous question. Read and follow **precisely**: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue. Once again, your code to reproduce the issue and your verbose request and response **ARE REQUIRED**. *Just the error traceback, or just the response, or just the request, or just the code – is not enough!*
|
||||
|
||||
## Can you implement feature `foo` in exchange `bar`?
|
||||
|
||||
Yes, we can. And we will, if nobody else does that before us. There's very little point in asking this type of questions, because the answer is always positive. When someone asks if we can do this or that, the question is not about our abilities, it all boils down to time and management needed for implementing all accumulated feature requests.
|
||||
|
||||
Moreover, this is an open-source library which is a work in progress. This means, that this project is intended to be developed by the community of users, who are using it. What you're asking is not whether we can or cannot implement it, in fact you're actually telling us to go do that particular task and this is not how we see a voluntary collaboration. Your contributions, PRs and commits are welcome: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code.
|
||||
|
||||
We don't give promises or estimates on the free open-source work. If you wish to speed it up, feel free to reach out to us via info@ccxt.trade.
|
||||
|
||||
## When will you add feature `foo` for exchange `bar` ? What's the estimated time? When should we expect this?
|
||||
|
||||
We don't give promises or estimates on the open-source work. The reasoning behind this is explained in the previous paragraph.
|
||||
|
||||
## When will you add the support for an exchange requested in the Issues?
|
||||
|
||||
Again, we can't promise on the dates for adding this or that exchange, due to reasons outlined above. The answer will always remain the same: _as soon as we can_.
|
||||
|
||||
## How long should I wait for a feature to be added? I need to decide whether to implement it myself or to wait for the CCXT Dev Team to implement it for me.
|
||||
|
||||
Please, go for implemeting it yourself, do not wait for us. We will add it as soon as we can. Also, your contributions are very welcome:
|
||||
|
||||
- https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
|
||||
|
||||
## What's your progress on adding the feature `foo` that was requested earlier? How do you do implementing exchange `bar`?
|
||||
|
||||
This type of questions is usually a waste of time, because answering it usually requires too much time for context-switching, and it often takes more time to answer this question, than to actually satisfy the request with code for a new feature or a new exchange. The progress of this open-source project is also open, so, whenever you're wondering how it is doing, take a look into commit history.
|
||||
|
||||
## What is the status of this PR? Any update?
|
||||
|
||||
If it is not merged, it means that the PR contains errors, that should be fixed first. If it could be merged as is – we would merge it, and you wouldn't have asked this question in the first place. The most frequent reason for not merging a PR is a violation of any of the [CONTRIBUTING guidelines](https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#derived-exchange-classes). Those guidelines should be taken literally, cannot skip a single line or word from there if you want your PR to be merged quickly. Code contributions that do not break the guidelines get merged almost immediately (usually, within hours).
|
||||
|
||||
## Can you point out the errors or what should I edit in my PR to get it merged into master branch?
|
||||
|
||||
Unfortunately, we don't always have the time to quickly list out each and every single error in the code that prevents it from merging. It is often easier and faster to just go and fix the error rather than explain what one should do to fix it. Most of them are already outlined in the [CONTRIBUTING guidelines](https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#derived-exchange-classes). The main rule of thumb is to follow **all guidelines literally**.
|
||||
|
||||
## Hey! The fix you've uploaded is in TypeScript, would you fix JavaScript / Python / PHP as well, please?
|
||||
|
||||
Our build system generates exchange-specific JavaScript, Python and PHP code for us automatically, so it is transpiled from TypeScript, and there's no need to fix all languages separately one by one.
|
||||
|
||||
Thus, if it is fixed in TypeScript, it is fixed in JavaScript NPM, Python pip and PHP Composer as well. The automatic build usually takes 15-20 minutes. Just upgrade your version with `npm`, `pip` or `composer` **after the new version arrives** and you'll be fine.
|
||||
|
||||
More about it here:
|
||||
|
||||
- https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#multilanguage-support
|
||||
- https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#transpiled-generated-files
|
||||
|
||||
|
||||
|
||||
## How to create an order with takeProfit+stopLoss?
|
||||
Some exchanges support `createOrder` with the additional "attached" `stopLoss` & `takeProfit` sub-orders - view [StopLoss And TakeProfit Orders Attached To A Position](Manual.md#stoploss-and-takeprofit-orders-attached-to-a-position).
|
||||
However, some exchanges might not support that feature and you will need to run separate `createOrder` methods to add conditional order (e.g. ***trigger order | stoploss order | takeprofit order**) to the already open position - view [Conditional orders](Manual.md#Conditional Orders).
|
||||
You can also check them by looking at `exchange.has['createOrderWithTakeProfitAndStopLoss']`, `exchange.has['createStopLossOrder']` and `exchange.has['createTakeProfitOrder']`, however they are not as precise as `.features` property.
|
||||
|
||||
## How to create a spot market buy with cost?
|
||||
To create a market-buy order with cost, first, you need to check if the exchange supports that feature (`exchange.has['createMarketBuyOrderWithCost']).
|
||||
If it does, then you can use the `createMarketBuyOrderWithCost` method.
|
||||
Example:
|
||||
```Python
|
||||
order = await exchange.createMarketBuyOrderWithCost(symbol, cost)
|
||||
```
|
||||
|
||||
## What does the `createMarketBuyRequiresPrice` option mean?
|
||||
|
||||
Many exchanges require the amount to be in the quote currency (they don't accept the base amount) when placing spot-market buy orders. In those cases, the exchange will have the option `createMarketBuyRequiresPrice` set to `true`.
|
||||
|
||||
Example: If you wanted to buy BTC/USDT with a market buy-order, you would need to provide an amount = 5 USDT instead of 0.000X. We have a check to prevent errors that explicitly require the price because users will usually provide the amount in the base currency.
|
||||
|
||||
So by default, if you do, `create_order(symbol, 'market,' 'buy,' 10)` will throw an error if the exchange has that option (`createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false...`).
|
||||
|
||||
If the exchange requires the cost and the user provided the base amount, we need to request an extra parameter **price** and multiply them to get the cost. If you're aware of this behavior, you can simply disable `createMarketBuyOrderRequiresPrice` and pass the cost in the amount parameter, but disabling it does not mean you can place the order using the base amount instead of the quote.
|
||||
|
||||
If you do `create_order(symbol, 'market', 'buy', 0.001, 20000)` ccxt will use the required price to calculate the cost by doing `0.01*20000` and send that value to the exchange.
|
||||
|
||||
If you want to provide the cost directly in the amount argument, you can do `exchange.options['createMarketBuyOrderRequiresPrice'] = False` (you acknowledge that the amount will be the cost for market-buy) and then you can do `create_order(symbol, 'market', 'buy', 10)`
|
||||
|
||||
This is basically to avoid a user doing this: `create_order('SHIB/USDT', market, buy, 1000000)` and thinking he's trying to buy 1kk of shib but in reality he's buying 1kk USDT worth of SHIB. For that reason, by default ccxt always accepts the base currency in the amount parameter.
|
||||
|
||||
Alternatively, you can use the functions `createMarketBuyOrderWithCost`/ `createMarketSellOrderWithCost` if they are available.
|
||||
|
||||
See more: [Market Buys](Manual.md#market-buys)
|
||||
|
||||
## What's the difference between trading spot and swap/perpetual futures?
|
||||
Spot trading involves buying or selling a financial instrument (like a cryptocurrency) for immediate delivery. It's straightforward, involving the direct exchange of assets.
|
||||
|
||||
Swap trading, on the other hand, involves derivative contracts where two parties exchange financial instruments or cash flows at a set date in the future, based on the underlying asset. Swaps are often used for leverage, speculation, or hedging and do not necessarily involve the exchange of the underlying asset until the contract expires.
|
||||
|
||||
|
||||
Besides that, you will be handling contracts if you're trading swaps and not the base currency (e.g., BTC) directly, so if you create an order with `amount = 1`, the amount in BTC will vary depending on the `contractSize`. You can check the contract size by doing:
|
||||
|
||||
```Python
|
||||
await exchange.loadMarkets()
|
||||
symbol = 'XRP/USDT:USDT'
|
||||
market = exchange.market(symbol)
|
||||
print(market['contractSize'])
|
||||
```
|
||||
|
||||
## How to place a reduceOnly order?
|
||||
A reduceOnly order is a type of order that can only reduce a position, not increase it. To place a reduceOnly order, you typically use the createOrder method with a reduceOnly parameter set to true. This ensures that the order will only execute if it decreases the size of an open position, and it will either partially fill or not fill at all if executing it would increase the position size.
|
||||
|
||||
<!-- tabs:start -->
|
||||
#### **Javascript**
|
||||
```javascript
|
||||
const params = {
|
||||
'reduceOnly': true, // set to true if you want to close a position, set to false if you want to open a new position
|
||||
}
|
||||
const order = await exchange.createOrder (symbol, type, side, amount, price, params)
|
||||
```
|
||||
#### **Python**
|
||||
```python
|
||||
params = {
|
||||
'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)
|
||||
```
|
||||
#### **PHP**
|
||||
```php
|
||||
$params = {
|
||||
'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);
|
||||
```
|
||||
<!-- tabs:end -->
|
||||
|
||||
|
||||
See more: [Trailing Orders](Manual.md#trailing-orders)
|
||||
|
||||
## How to check the endpoint used by the unified method?
|
||||
To check the endpoint used by a unified method in the CCXT library, you would typically need to refer to the source code of the library for the specific exchange implementation you're interested in. The unified methods in CCXT abstract away the details of the specific endpoints they interact with, so this information is not directly exposed via the library's API. For detailed inspection, you can look at the implementation of the method for the particular exchange in the CCXT library's source code on GitHub.
|
||||
|
||||
See more: [Unified API](Manual.md#unified-api)
|
||||
|
||||
## How to differentiate between previousFundingRate, fundingRate and nextFundingRate in the funding rate structure?
|
||||
The funding rate structure has three different funding rate values that can be returned:
|
||||
1. `previousFundingRate`refers to the most recently completed rate.
|
||||
2. `fundingRate` is the upcoming rate. This value is always changing until the funding time passes and then it becomes the previousFundingRate.
|
||||
3. `nextFundingRate` is only supported on a few exchanges and is the predicted funding rate after the upcoming rate. This value is two funding rates from now.
|
||||
|
||||
As an example, say it is 12:30. The `previousFundingRate` happened at 12:00 and we're looking to see what the upcoming funding rate will be by checking the `fundingRate` value. In this example, given 4-hour intervals, the `fundingRate` will happen in the future at 4:00 and the `nextFundingRate` is the predicted rate that will happen at 8:00.
|
||||
@@ -0,0 +1,235 @@
|
||||
## Install
|
||||
|
||||
The easiest way to install the ccxt library is to use builtin package managers:
|
||||
|
||||
- [ccxt in **NPM**](http://npmjs.com/package/ccxt) (JavaScript / Node v15+)
|
||||
- [ccxt in **PyPI**](https://pypi.python.org/pypi/ccxt) (Python 3)
|
||||
|
||||
This library is shipped as an all-in-one module implementation with minimalistic dependencies and requirements:
|
||||
|
||||
- [ccxt.js](https://github.com/ccxt/ccxt/blob/master/js/ccxt.js) in JavaScript
|
||||
- [./python/](https://github.com/ccxt/ccxt/blob/master/python/) in Python (generated from JS)
|
||||
- [ccxt.php](https://github.com/ccxt/ccxt/blob/master/ccxt.php) in PHP (generated from JS)
|
||||
|
||||
You can also clone it into your project directory from [ccxt GitHub repository](https://github.com/ccxt/ccxt) and copy files
|
||||
manually into your working directory with language extension appropriate for your environment.
|
||||
|
||||
```shell
|
||||
git clone https://github.com/ccxt/ccxt.git
|
||||
```
|
||||
|
||||
An alternative way of installing this library is to build a custom bundle from source. Choose exchanges you need in `exchanges.cfg`.
|
||||
|
||||
### JavaScript (NPM)
|
||||
|
||||
JavaScript version of ccxt works both in Node and web browsers. Requires ES6 and `async/await` syntax support (Node 15+). When compiling with Webpack and Babel, make sure it is [not excluded](https://github.com/ccxt-dev/ccxt/issues/225#issuecomment-331582275) in your `babel-loader` config.
|
||||
|
||||
[ccxt crypto trading library in npm](http://npmjs.com/package/ccxt)
|
||||
|
||||
```shell
|
||||
npm install ccxt
|
||||
```
|
||||
|
||||
```javascript
|
||||
var ccxt = require ('ccxt')
|
||||
|
||||
console.log (ccxt.exchanges) // print all available exchanges
|
||||
```
|
||||
|
||||
### JavaScript (for use with the `<script>` tag):
|
||||
|
||||
All-in-one browser bundle (dependencies included), served from a CDN of your choice:
|
||||
|
||||
* jsDelivr: https://cdn.jsdelivr.net/npm/ccxt@4.5.7/dist/ccxt.browser.min.js
|
||||
* unpkg: https://unpkg.com/ccxt@4.5.7/dist/ccxt.browser.min.js
|
||||
* ccxt: https://cdn.ccxt.com/latest/ccxt.min.js
|
||||
|
||||
You can obtain a live-updated version of the bundle by removing the version number from the URL (the `@a.b.c` thing) or the /latest/ on our cdn — however, we do not recommend to do that, as it may break your app eventually. Also, please keep in mind that we are not responsible for the correct operation of those CDN servers.
|
||||
|
||||
```html
|
||||
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/ccxt@4.5.7/dist/ccxt.browser.min.js"></script>
|
||||
```
|
||||
|
||||
We also provide webpack minified and tree-shaken versions of the library starting from version 3.0.35 - Visit https://cdn.ccxt.com to browse the prebundled versions we distribute.
|
||||
|
||||
| name | size |
|
||||
|----------------|--------|
|
||||
| binance.min.js | ~300kb |
|
||||
| bitget.min.js | ~200kb |
|
||||
| bitmart.min.js | ~200kb |
|
||||
| bybit.min.js | ~300kb |
|
||||
| ccxt.min.js | ~3mb |
|
||||
| huobi.min.js | ~300kb |
|
||||
| kucoin.min.js | ~200kb |
|
||||
| mexc.min.js | ~200kb |
|
||||
| okx.min.js | ~250kb |
|
||||
|
||||
Note: the file sizes are subject to change.
|
||||
|
||||
```html
|
||||
<script type="text/javascript" src="https://cdn.ccxt.com/3.0.35/ccxt.min.js"></script>
|
||||
```
|
||||
|
||||
Here is an [example](https://cdn.ccxt.com/example.html) using a custom bybit bundle from our cdn in the browser
|
||||
|
||||
```html
|
||||
<html>
|
||||
<head>
|
||||
<script type="text/javascript" src="https://cdn.ccxt.com/latest/bybit.min.js"></script>
|
||||
<script>
|
||||
async function update () {
|
||||
const bid = document.querySelector ('#bid')
|
||||
const ask = document.querySelector ('#ask')
|
||||
const updates = document.querySelector ('#updates')
|
||||
|
||||
const bybit = new ccxt.pro.bybit ()
|
||||
window.bybit = bybit
|
||||
const ticker = await bybit.fetchTicker ('BTC/USDT:USDT')
|
||||
bid.innerText = ticker.bid.toFixed (2)
|
||||
ask.innerText = ticker.ask.toFixed (2)
|
||||
while (true) {
|
||||
const trades = await bybit.watchTrades ('BTC/USDT:USDT')
|
||||
// const trades = await bybit.fetchTrades ('BTC/USDT:USDT', 1)
|
||||
const trade = trades[0]
|
||||
|
||||
const notify = document.createElement ('li')
|
||||
notify.innerHTML = `<strong>${trade.datetime.slice (11, 19)}</strong> ${trade.amount.toFixed (3)} btc was bought at ${trade.price.toFixed (1)}`
|
||||
notify.style = 'padding-top: 8px;'
|
||||
updates.appendChild (notify)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
|
||||
<body onload="update()">
|
||||
<h3>The current bitcoin bid on bybit is <span id="bid"></span><br><br>and the best ask is <span id="ask"></span></h3>
|
||||
<ul id="updates" style="color: red;"></ul>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
The default entry point for the browser is `window.ccxt` and it creates a global ccxt object:
|
||||
|
||||
```javascript
|
||||
console.log (ccxt.exchanges) // print all available exchanges
|
||||
```
|
||||
|
||||
### Custom JavaScript Builds
|
||||
|
||||
It takes time to load all scripts and resources. The problem with in-browser usage is that the entire CCXT library weighs a few megabytes which is a lot for a web application. Sometimes it is also critical for a Node app. Therefore to lower the loading time you might want to make your own custom build of CCXT for your app with just the exchanges you need. CCXT uses webpack to remove dead code paths to make the package smaller.
|
||||
|
||||
Follow these steps:
|
||||
|
||||
```bash
|
||||
# 1. clone the repository
|
||||
|
||||
git clone --depth 1 https://github.com/ccxt/ccxt.git
|
||||
|
||||
# 2. go to the cloned repository
|
||||
|
||||
cd ccxt
|
||||
|
||||
# 3. install dependencies
|
||||
|
||||
npm install
|
||||
|
||||
# 4. edit exchanges.cfg for the exchanges of your interest
|
||||
|
||||
echo -e "binance\nokx" > exchanges.cfg
|
||||
|
||||
# 5. build the library
|
||||
|
||||
npm run export-exchanges
|
||||
npm run bundle-browser
|
||||
|
||||
# 6a. copy the browser file to your project folder if you are buildig a web application
|
||||
|
||||
cp dist/ccxt.browser.js path/to/your/html/project
|
||||
|
||||
# 6b. or link against the library if you are building a Node.js application
|
||||
npm link
|
||||
cd path/to/your/node/project
|
||||
npm link ccxt
|
||||
|
||||
# 6c. directly import ccxt from the entry point
|
||||
touch app.js
|
||||
|
||||
# inside of app.js
|
||||
|
||||
import ccxt from './js/ccxt.js'
|
||||
console.log (ccxt)
|
||||
|
||||
# now you can run your app like so
|
||||
|
||||
node app.js
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
[ccxt algotrading library in PyPI](https://pypi.python.org/pypi/ccxt)
|
||||
|
||||
```shell
|
||||
pip install ccxt
|
||||
```
|
||||
|
||||
```python
|
||||
import ccxt
|
||||
print(ccxt.exchanges) # print a list of all available exchange classes
|
||||
```
|
||||
|
||||
The library supports concurrent asynchronous mode with asyncio and async/await in Python 3.5.3+
|
||||
|
||||
```python
|
||||
import ccxt.async_support as ccxt # link against the asynchronous version of ccxt
|
||||
```
|
||||
|
||||
### PHP
|
||||
|
||||
The autoloadable version of ccxt can be installed with [**Packagist/Composer**](https://packagist.org/packages/ccxt/ccxt) (PHP 8.1+).
|
||||
|
||||
It can also be installed from the source code: [**`ccxt.php`**](https://raw.githubusercontent.com/ccxt/ccxt/master/php)
|
||||
|
||||
It requires common PHP modules:
|
||||
|
||||
- cURL
|
||||
- mbstring (using UTF-8 is highly recommended)
|
||||
- PCRE
|
||||
- iconv
|
||||
- gmp
|
||||
|
||||
```php
|
||||
include "ccxt.php";
|
||||
var_dump (\ccxt\Exchange::$exchanges); // print a list of all available exchange classes
|
||||
```
|
||||
|
||||
The library supports concurrent asynchronous mode using tools from [ReactPHP](https://reactphp.org/) in PHP 8.1+. Read the [Manual](https://github.com/ccxt/ccxt/wiki) for more details.
|
||||
|
||||
### .net/C#
|
||||
|
||||
[ccxt in C# with **Nugget**](https://www.nuget.org/packages/ccxt) (netstandard 2.0 and netstandard 2.1)
|
||||
```c#
|
||||
using ccxt;
|
||||
Console.WriteLine(ccxt.Exchanges) // check this later
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
You can get CCXT installed in a container along with all the supported languages and dependencies. This may be useful if you want to contribute to CCXT (e.g. run the build scripts and tests — please see the [Contributing](https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md) document for the details on that).
|
||||
|
||||
You don't need the Docker image if you're not going to develop CCXT. If you just want to use CCXT – just install it as a regular package into your project.
|
||||
|
||||
Using `docker-compose` (in the cloned CCXT repository):
|
||||
|
||||
```shell
|
||||
docker-compose run --rm ccxt
|
||||
```
|
||||
|
||||
Alternatively:
|
||||
|
||||
```shell
|
||||
docker build . --tag ccxt
|
||||
docker run -it ccxt
|
||||
```
|
||||
|
||||
## Proxy
|
||||
If you are unable to obtain data from exchanges due to location restrictions read the [proxy](https://github.com/ccxt/ccxt/wiki/Manual#proxy) section.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,97 @@
|
||||
Welcome to the ccxt wiki!
|
||||
|
||||
> We recommend to visit our full documentation at https://docs.ccxt.com
|
||||
|
||||
## General Information
|
||||
|
||||
- [Supported Exchanges](https://github.com/ccxt/ccxt/wiki/Exchange-Markets)
|
||||
- [Exchanges By Country](https://github.com/ccxt/ccxt/wiki/Exchange-Markets-By-Country)
|
||||
|
||||
## How To Install
|
||||
|
||||
- [Install](https://github.com/ccxt/ccxt/wiki/Install)
|
||||
- [Node.js](https://github.com/ccxt/ccxt/wiki/Install#nodejs)
|
||||
- [Python](https://github.com/ccxt/ccxt/wiki/Install#python)
|
||||
- [PHP](https://github.com/ccxt/ccxt/wiki/Install#php)
|
||||
- [Web Browsers](https://github.com/ccxt/ccxt/wiki/Install#web-browsers)
|
||||
- [Docker](https://github.com/ccxt/ccxt/wiki/Install#docker)
|
||||
- [Proxy](https://github.com/ccxt/ccxt/wiki/Install#proxy)
|
||||
- [CORS (Access-Control-Allow-Origin)](https://github.com/ccxt/ccxt/wiki/Install#cors-access-control-allow-origin)
|
||||
|
||||
## How To Use
|
||||
|
||||
- [User Manual](https://github.com/ccxt/ccxt/wiki/Manual)
|
||||
- [Architecture Overview](https://github.com/ccxt/ccxt/wiki/Manual#overview)
|
||||
- [Instantiation](https://github.com/ccxt/ccxt/wiki/Manual#instantiation)
|
||||
- [Exchange Structure](https://github.com/ccxt/ccxt/wiki/Manual#exchange-structure)
|
||||
- [Exchange Properties](https://github.com/ccxt/ccxt/wiki/Manual#exchange-properties)
|
||||
- [Rate Limit](https://github.com/ccxt/ccxt/wiki/Manual#rate-limit)
|
||||
- [Markets](https://github.com/ccxt/ccxt/wiki/Manual#markets)
|
||||
- [Symbols And Market Ids](https://github.com/ccxt-dev/ccxt/wiki/Manual#symbols-and-market-ids)
|
||||
- [API Methods / Endpoints](https://github.com/ccxt/ccxt/wiki/Manual#api-methods--endpoints)
|
||||
- [Implicit API Methods](https://github.com/ccxt/ccxt/wiki/Manual#implicit-api-methods)
|
||||
- [Public/Private API](https://github.com/ccxt/ccxt/wiki/Manual#publicprivate-api)
|
||||
- [Synchronous vs Asynchronous Calls](https://github.com/ccxt/ccxt/wiki/Manual#synchronous-vs-asynchronous-calls)
|
||||
- [Unified API](https://github.com/ccxt/ccxt/wiki/Manual#unified-api)
|
||||
- [Overriding Params](https://github.com/ccxt/ccxt/wiki/Manual#overriding-unified-api-params)
|
||||
- [Pagination](https://github.com/ccxt/ccxt/wiki/Manual#pagination)
|
||||
- [Automatic Pagination](https://github.com/ccxt/ccxt/wiki/Manual#automatic-pagination)
|
||||
- [Public API](https://github.com/ccxt/ccxt/wiki/Manual#public-api)
|
||||
- [Order Book](https://github.com/ccxt/ccxt/wiki/Manual#order-book)
|
||||
- [Market Depth](https://github.com/ccxt/ccxt/wiki/Manual#market-depth)
|
||||
- [Price Tickers](https://github.com/ccxt/ccxt/wiki/Manual#price-tickers)
|
||||
- [OHLCV Candlestick Charts](https://github.com/ccxt/ccxt/wiki/Manual#ohlcv-candlestick-charts)
|
||||
- [Public Trades](https://github.com/ccxt/ccxt/wiki/Manual#trades-executions-transactions)
|
||||
- [Private API](https://github.com/ccxt/ccxt/wiki/Manual#private-api)
|
||||
- [Authentication](https://github.com/ccxt/ccxt/wiki/Manual#authentication)
|
||||
- [API Keys Setup](https://github.com/ccxt/ccxt/wiki/Manual#api-keys-setup)
|
||||
- [Querying Account Balance](https://github.com/ccxt/ccxt/wiki/Manual#account-balance)
|
||||
- [Orders](https://github.com/ccxt/ccxt/wiki/Manual#orders)
|
||||
- [Querying Orders](https://github.com/ccxt/ccxt/wiki/Manual#querying-orders)
|
||||
- [By Order Id](https://github.com/ccxt-dev/ccxt/wiki/Manual#by-order-id)
|
||||
- [All Orders](https://github.com/ccxt-dev/ccxt/wiki/Manual#all-orders)
|
||||
- [Open Orders](https://github.com/ccxt-dev/ccxt/wiki/Manual#open-orders)
|
||||
- [Closed Orders](https://github.com/ccxt-dev/ccxt/wiki/Manual#closed-orders)
|
||||
- [Order Structure](https://github.com/ccxt/ccxt/wiki/Manual#order-structure)
|
||||
- [Placing Orders](https://github.com/ccxt/ccxt/wiki/Manual#placing-orders)
|
||||
- [Market Orders](https://github.com/ccxt/ccxt/wiki/Manual#market-orders)
|
||||
- [Limit Orders](https://github.com/ccxt/ccxt/wiki/Manual#limit-orders)
|
||||
- [Custom Params](https://github.com/ccxt/ccxt/wiki/Manual#custom-order-params)
|
||||
- [Canceling Orders](https://github.com/ccxt/ccxt/wiki/Manual#canceling-orders)
|
||||
- [Personal Trades](https://github.com/ccxt-dev/ccxt/wiki/Manual#personal-trades)
|
||||
- [Funding Your Account](https://github.com/ccxt/ccxt/wiki/Manual#ledger)
|
||||
- [Deposit](https://github.com/ccxt/ccxt/wiki/Manual#deposit)
|
||||
- [Withdraw](https://github.com/ccxt/ccxt/wiki/Manual#withdraw)
|
||||
- [Transactions](https://github.com/ccxt/ccxt/wiki/Manual#transactions)
|
||||
- [Deposit](https://github.com/ccxt/ccxt/wiki/Manual#deposit)
|
||||
- [Withdrawal](https://github.com/ccxt/ccxt/wiki/Manual#withdrawal)
|
||||
- [All Transactions](https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure)
|
||||
- [Fees](https://github.com/ccxt/ccxt/wiki/Manual#fees)
|
||||
- [Trading Fees](https://github.com/ccxt/ccxt/wiki/Manual#trading-fees)
|
||||
- [Transaction Fees](https://github.com/ccxt/ccxt/wiki/Manual#transaction-fees)
|
||||
|
||||
## WebSocket Support
|
||||
|
||||
- [CCXT Pro](https://github.com/ccxt/ccxt/wiki/ccxt.pro)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- [Frequently Asked Questions](https://github.com/ccxt/ccxt/wiki/FAQ)
|
||||
- [Overriding The Nonce](https://github.com/ccxt/ccxt/wiki/Manual#overriding-the-nonce)
|
||||
- [Error Handling](https://github.com/ccxt/ccxt/wiki/Manual#error-handling)
|
||||
- [Troubleshooting](https://github.com/ccxt/ccxt/wiki/Manual#troubleshooting)
|
||||
- [How To Submit An Issue](https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue)
|
||||
- [CCXT CLI: Command-Line Interface](https://github.com/ccxt/ccxt/wiki/CLI)
|
||||
|
||||
## Examples
|
||||
|
||||
- [Usage Examples](https://docs.ccxt.com/#/Examples)
|
||||
|
||||
## New Exchanges
|
||||
|
||||
- [Certification](https://github.com/ccxt/ccxt/wiki/Certification)
|
||||
- [Requirements](https://github.com/ccxt/ccxt/wiki/Requirements)
|
||||
|
||||
## API Reference
|
||||
|
||||
- [API Reference](https://docs.ccxt.com/#/spec)
|
||||
@@ -0,0 +1,47 @@
|
||||
# CCXT Integration Requirements
|
||||
|
||||
The exchange is required to implement the following list of methods and structures in order to get integrated with CCXT.
|
||||
|
||||
## Public API
|
||||
|
||||
#### Exchange Information, Fee Schedule and Trading Rules
|
||||
|
||||
- [`fetchMarkets`](https://github.com/ccxt/ccxt/wiki/Manual#loading-markets) – a list of trading pairs and their statuses + [market structure](https://github.com/ccxt/ccxt/wiki/Manual#market-structure)
|
||||
- [`fetchCurrencies`](https://github.com/ccxt/ccxt/wiki/Manual#loading-markets) – a list of tokens or assets and their statuses + [currency structure](https://github.com/ccxt/ccxt/wiki/Manual#currency-structure)
|
||||
- `fetchTradingLimits` – min/max order volume, price, cost, precision, etc...
|
||||
- `fetchTradingFees` – trading fees, either public or personal
|
||||
- `fetchFundingLimits` – a list of withdrawal limits
|
||||
|
||||
#### Market Data
|
||||
|
||||
- [`fetchTicker`](https://github.com/ccxt/ccxt/wiki/Manual#price-tickers) – 24h volumes and stats + [ticker structure](https://github.com/ccxt/ccxt/wiki/Manual#ticker-structure)
|
||||
- [`fetchOrderBook`](https://github.com/ccxt/ccxt/wiki/Manual#order-book) – L2/L3 + [orderbook structure](https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure)
|
||||
- [`fetchTrades`](https://github.com/ccxt/ccxt/wiki/Manual#trades-executions-transactions) – a list of recent public trades + [trade structure](https://github.com/ccxt/ccxt/wiki/Manual#trade-structure)
|
||||
- [`fetchOHLCV`](https://github.com/ccxt/ccxt/wiki/Manual#ohlcv-candlestick-charts) – a list of candles or kline data for traded volumes in different timeframes 1m, 15m, 1h, 1d, ... + [OHLCV structure](https://github.com/ccxt/ccxt/wiki/Manual#ohlcv-structure)
|
||||
|
||||
## Private API
|
||||
|
||||
#### Trading
|
||||
|
||||
- [`fetchBalance`](https://github.com/ccxt/ccxt/wiki/Manual#querying-account-balance) – for all types of accounts + [balance structure](https://github.com/ccxt/ccxt/wiki/Manual#balance-structure)
|
||||
- `fetchAccounts` – required if the exchange has multiple accounts or sub-accounts
|
||||
- [`createOrder`](https://github.com/ccxt/ccxt/wiki/Manual#placing-orders) – *limit/market* orders + [order structure](https://github.com/ccxt/ccxt/wiki/Manual#order-structure)
|
||||
- [`cancelOrder`](https://github.com/ccxt/ccxt/wiki/Manual#canceling-orders)
|
||||
- `editOrder` – change the price and/or amount of an open order
|
||||
|
||||
#### Trading History
|
||||
|
||||
- [`fetchOrder`](https://github.com/ccxt/ccxt/wiki/Manual#querying-orders) – one order by order id + [order structure](https://github.com/ccxt/ccxt/wiki/Manual#order-structure)
|
||||
- [`fetchOpenOrders`](https://github.com/ccxt/ccxt/wiki/Manual#querying-orders) – a list of all open orders
|
||||
- [`fetchOrders`](https://github.com/ccxt/ccxt/wiki/Manual#querying-orders) – a list of all orders
|
||||
- [`fetchMyTrades`](https://github.com/ccxt/ccxt/wiki/Manual#personal-trades) – the personal history of filled trades for the account + [trade structure](https://github.com/ccxt/ccxt/wiki/Manual#trade-structure)
|
||||
|
||||
#### Funding
|
||||
|
||||
- [`fetchDepositAddress`](https://github.com/ccxt/ccxt/wiki/Manual#funding-your-account) – deposit address(es) + [address structure](https://github.com/ccxt/ccxt/wiki/Manual#address-structure)
|
||||
- [`fetchDeposits`](https://github.com/ccxt/ccxt/wiki/Manual#transactions)
|
||||
- [`fetchWithdrawals`](https://github.com/ccxt/ccxt/wiki/Manual#transactions)
|
||||
- [`fetchTransactions`](https://github.com/ccxt/ccxt/wiki/Manual#transactions) + [transaction structure](https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure)
|
||||
- [`fetchLedger`](https://github.com/ccxt/ccxt/wiki/Manual#ledger) – transactions, transfers, referrals, cashbacks + [ledger entry structure](https://github.com/ccxt/ccxt/wiki/Manual#ledger-entry-structure)
|
||||
- [`withdraw`](https://github.com/ccxt/ccxt/wiki/Manual#withdraw)
|
||||
- `transfer` – required if exchange has multiple accounts or sub-accounts
|
||||
@@ -0,0 +1,62 @@
|
||||
# CCXT Statistics
|
||||
|
||||
## JavaScript / npm
|
||||
|
||||

|
||||

|
||||

|
||||
<!--  -->
|
||||
<!--  -->
|
||||
<!--  -->
|
||||
<!--  -->
|
||||
|
||||
## Python / PyPI
|
||||
|
||||

|
||||

|
||||

|
||||
<!--  -->
|
||||
<!--  -->
|
||||
|
||||
## PHP / Packagist
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
## GitHub
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
<!--  -->
|
||||
<!--  -->
|
||||
|
||||

|
||||

|
||||
|
||||
<!--
|
||||
|
||||
### GitHub Search Hits
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
-->
|
||||
|
||||
## Opencollective
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
@@ -0,0 +1,14 @@
|
||||

|
||||
|
||||
# CCXT
|
||||
|
||||
> CryptoCurrency eXchange Trading Library.
|
||||
|
||||
- support for many cryptocurrency exchanges
|
||||
- fully implemented public and private APIs
|
||||
- optional normalized data for cross-exchange analytics and arbitrage
|
||||
- an out of the box unified API that is extremely easy to integrate
|
||||
- works in Node 15+, Python 3, PHP 8.1+, and web browsers
|
||||
|
||||
[GitHub](https://github.com/ccxt/ccxt/)
|
||||
[Get Started](#Overview)
|
||||
@@ -0,0 +1,109 @@
|
||||
|
||||
- [Install](Install.md)
|
||||
- [Examples](Examples.md)
|
||||
- [Manual](Manual.md)
|
||||
- [CCXT Pro](ccxt.pro.manual.md)
|
||||
- [Contributing](CONTRIBUTING.md)
|
||||
- [Supported Exchanges](Exchange-Markets.md)
|
||||
- [Exchanges By Country](Exchange-Markets-By-Country.md)
|
||||
- [API Spec By Method](baseSpec.md)
|
||||
- [FAQ](FAQ.md)
|
||||
- [Changelog](CHANGELOG.md)
|
||||
- [Awesome](Awesome.md)
|
||||
- API Spec by Exchange
|
||||
- [alpaca](exchanges/alpaca.md)
|
||||
- [apex](exchanges/apex.md)
|
||||
- [ascendex](exchanges/ascendex.md)
|
||||
- [backpack](exchanges/backpack.md)
|
||||
- [bigone](exchanges/bigone.md)
|
||||
- [binance](exchanges/binance.md)
|
||||
- [bingx](exchanges/bingx.md)
|
||||
- [bit2c](exchanges/bit2c.md)
|
||||
- [bitbank](exchanges/bitbank.md)
|
||||
- [bitbns](exchanges/bitbns.md)
|
||||
- [bitfinex](exchanges/bitfinex.md)
|
||||
- [bitflyer](exchanges/bitflyer.md)
|
||||
- [bitget](exchanges/bitget.md)
|
||||
- [bithumb](exchanges/bithumb.md)
|
||||
- [bitmart](exchanges/bitmart.md)
|
||||
- [bitmex](exchanges/bitmex.md)
|
||||
- [bitopro](exchanges/bitopro.md)
|
||||
- [bitrue](exchanges/bitrue.md)
|
||||
- [bitso](exchanges/bitso.md)
|
||||
- [bitstamp](exchanges/bitstamp.md)
|
||||
- [bitteam](exchanges/bitteam.md)
|
||||
- [bittrade](exchanges/bittrade.md)
|
||||
- [bitvavo](exchanges/bitvavo.md)
|
||||
- [blockchaincom](exchanges/blockchaincom.md)
|
||||
- [blofin](exchanges/blofin.md)
|
||||
- [btcalpha](exchanges/btcalpha.md)
|
||||
- [btcbox](exchanges/btcbox.md)
|
||||
- [btcmarkets](exchanges/btcmarkets.md)
|
||||
- [btcturk](exchanges/btcturk.md)
|
||||
- [bybit](exchanges/bybit.md)
|
||||
- [cex](exchanges/cex.md)
|
||||
- [coinbase](exchanges/coinbase.md)
|
||||
- [coinbaseexchange](exchanges/coinbaseexchange.md)
|
||||
- [coinbaseinternational](exchanges/coinbaseinternational.md)
|
||||
- [coincatch](exchanges/coincatch.md)
|
||||
- [coincheck](exchanges/coincheck.md)
|
||||
- [coinex](exchanges/coinex.md)
|
||||
- [coinmate](exchanges/coinmate.md)
|
||||
- [coinmetro](exchanges/coinmetro.md)
|
||||
- [coinone](exchanges/coinone.md)
|
||||
- [coinsph](exchanges/coinsph.md)
|
||||
- [coinspot](exchanges/coinspot.md)
|
||||
- [cryptocom](exchanges/cryptocom.md)
|
||||
- [cryptomus](exchanges/cryptomus.md)
|
||||
- [defx](exchanges/defx.md)
|
||||
- [delta](exchanges/delta.md)
|
||||
- [deribit](exchanges/deribit.md)
|
||||
- [derive](exchanges/derive.md)
|
||||
- [digifinex](exchanges/digifinex.md)
|
||||
- [exmo](exchanges/exmo.md)
|
||||
- [foxbit](exchanges/foxbit.md)
|
||||
- [gate](exchanges/gate.md)
|
||||
- [gemini](exchanges/gemini.md)
|
||||
- [hashkey](exchanges/hashkey.md)
|
||||
- [hibachi](exchanges/hibachi.md)
|
||||
- [hitbtc](exchanges/hitbtc.md)
|
||||
- [hollaex](exchanges/hollaex.md)
|
||||
- [htx](exchanges/htx.md)
|
||||
- [hyperliquid](exchanges/hyperliquid.md)
|
||||
- [independentreserve](exchanges/independentreserve.md)
|
||||
- [indodax](exchanges/indodax.md)
|
||||
- [kraken()](exchanges/kraken().md)
|
||||
- [krakenfutures](exchanges/krakenfutures.md)
|
||||
- [kucoin](exchanges/kucoin.md)
|
||||
- [kucoinfutures](exchanges/kucoinfutures.md)
|
||||
- [latoken](exchanges/latoken.md)
|
||||
- [lbank](exchanges/lbank.md)
|
||||
- [luno](exchanges/luno.md)
|
||||
- [mercado](exchanges/mercado.md)
|
||||
- [mexc](exchanges/mexc.md)
|
||||
- [modetrade](exchanges/modetrade.md)
|
||||
- [ndax](exchanges/ndax.md)
|
||||
- [novadax](exchanges/novadax.md)
|
||||
- [oceanex](exchanges/oceanex.md)
|
||||
- [okcoin](exchanges/okcoin.md)
|
||||
- [okx](exchanges/okx.md)
|
||||
- [onetrading](exchanges/onetrading.md)
|
||||
- [oxfun](exchanges/oxfun.md)
|
||||
- [p2b](exchanges/p2b.md)
|
||||
- [paradex()](exchanges/paradex().md)
|
||||
- [paymium](exchanges/paymium.md)
|
||||
- [phemex](exchanges/phemex.md)
|
||||
- [poloniex](exchanges/poloniex.md)
|
||||
- [probit](exchanges/probit.md)
|
||||
- [timex](exchanges/timex.md)
|
||||
- [tokocrypto](exchanges/tokocrypto.md)
|
||||
- [toobit](exchanges/toobit.md)
|
||||
- [upbit](exchanges/upbit.md)
|
||||
- [wavesexchange](exchanges/wavesexchange.md)
|
||||
- [whitebit](exchanges/whitebit.md)
|
||||
- [woo](exchanges/woo.md)
|
||||
- [woofipro](exchanges/woofipro.md)
|
||||
- [xt](exchanges/xt.md)
|
||||
- [yobit](exchanges/yobit.md)
|
||||
- [zaif](exchanges/zaif.md)
|
||||
- [zonda](exchanges/zonda.md)
|
||||
@@ -0,0 +1,29 @@
|
||||
{{>deprecated~}}
|
||||
{{>description~}}
|
||||
{{>scope~}}
|
||||
{{>summary~}}
|
||||
{{>augments~}}
|
||||
{{>implements~}}
|
||||
{{>mixes~}}
|
||||
{{>default~}}
|
||||
{{>chainable~}}
|
||||
{{>overrides~}}
|
||||
{{>returns~}}
|
||||
{{>category~}}
|
||||
{{>throws~}}
|
||||
{{>fires~}}
|
||||
{{>this~}}
|
||||
{{>access~}}
|
||||
{{>readOnly~}}
|
||||
{{>requires~}}
|
||||
{{>customTags~}}
|
||||
{{>see~}}
|
||||
{{>since~}}
|
||||
{{>version~}}
|
||||
{{>authors~}}
|
||||
{{>license~}}
|
||||
{{>copyright~}}
|
||||
{{>todo~}}
|
||||
{{>params~}}
|
||||
{{>properties~}}
|
||||
{{>examples~}}
|
||||
@@ -0,0 +1,3 @@
|
||||
{{#if deprecated}}`DEPRECATED`
|
||||
|
||||
{{/if~}}
|
||||
@@ -0,0 +1,4 @@
|
||||
{{>header~}}
|
||||
{{>body}}
|
||||
##### Supported exchanges
|
||||
{{>member-index-list~}}
|
||||
@@ -0,0 +1,9 @@
|
||||
|
||||
<a name="{{name}}" id="{{getFragment this}}"></a>
|
||||
|
||||
{{#if exchange}}
|
||||
{{>heading-indent}}[{{exchange}}](#{{getFragment this}})
|
||||
{{else}}
|
||||
{{>heading-indent}}{{name}}
|
||||
{{/if~}}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{{#if (isFunction this)}}
|
||||
* [{{exchange}}](/exchanges/{{exchange}}.md#{{getFragment this}})
|
||||
{{/if}}
|
||||
{{#indexChildren ~}}
|
||||
{{>member-index-list~}}
|
||||
{{/indexChildren}}
|
||||
@@ -0,0 +1,9 @@
|
||||
{{#children inherited=undefined ~}}
|
||||
{{>header~}}
|
||||
{{>body}}
|
||||
|
||||
```javascript
|
||||
{{exchange}}.{{name}} ({{methodSig this}})
|
||||
```
|
||||
|
||||
{{/children~}}
|
||||
@@ -0,0 +1,12 @@
|
||||
{{#if params}}
|
||||
|
||||
{{tableHead params "name|Param" "type|Type" "optional|Required" "description|Description" ~}}
|
||||
|
||||
{{#tableRow params "name" "type" "optional" "description" ~}}
|
||||
| {{#if @col1}}{{name}} | {{/if~}}
|
||||
{{#if @col2}}{{>linked-type-list types=(cleanNames type.names) delimiter=", " }} | {{/if~}}
|
||||
{{#if @col3}}{{#unless optional}}Yes{{else}}No{{/unless}} | {{/if~}}
|
||||
{{#if @col4}}{{{stripNewlines (inlineLinks description)}}} |{{/if}}
|
||||
{{/tableRow}}
|
||||
|
||||
{{/if}}
|
||||
@@ -0,0 +1,12 @@
|
||||
{{#if returns}}
|
||||
{{#if returns.[0].description~}}
|
||||
**Returns**: {{#each returns~}}
|
||||
{{#if type~}}
|
||||
{{#if type.names}}{{>linked-type-list types=(cleanNames type.names) delimiter=" \| " ~}}{{/if}}
|
||||
{{~#if description}} - {{{inlineLinks description}}}{{/if~}}
|
||||
{{else~}}
|
||||
{{{inlineLinks description}~}}
|
||||
{{/if~}}
|
||||
{{~/each}}
|
||||
|
||||
{{/if}}{{/if}}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,44 @@
|
||||
# CCXT Pro
|
||||
|
||||
CCXT supports WebSockets (`Pro` part) for many exchanges.
|
||||
|
||||
- [User Manual](ccxt.pro.manual)
|
||||
- [Architecture Overview](ccxt.pro.manual#overview)
|
||||
- [Prerequisites](ccxt.pro.manual#prerequisites)
|
||||
- [Streaming Specifics](ccxt.pro.manual#streaming-specifics)
|
||||
- [Linking](ccxt.pro.manual#linking)
|
||||
- [Instantiation](ccxt.pro.manual#instantiation)
|
||||
- [Exchange Properties](ccxt.pro.manual#exchange-properties)
|
||||
- [Unified API](ccxt.pro.manual#unified-api)
|
||||
- [Public Methods](ccxt.pro.manual#public-methods)
|
||||
- [Market Data](ccxt.pro.manual#market-data)
|
||||
- [`watchOrderBook (symbol, limit, params)`](ccxt.pro.manual#watchOrderBook)
|
||||
- [`watchOrderBookForSymbols (symbols, limit, params)`](ccxt.pro.manual#watchOrderBookForSymbols)
|
||||
- [`watchTicker (symbol, params)`](ccxt.pro.manual#watchTicker)
|
||||
- [`watchTickers (symbols, params)`](ccxt.pro.manual#watchTickers)
|
||||
- [`watchOHLCV (symbol, timeframe, since, limit, params)`](ccxt.pro.manual#watchOHLCV)
|
||||
- [`watchOHLCVForSymbols (symbolsAndTimeframes, since, limit, params)`](ccxt.pro.manual#watchOHLCVForSymbols)
|
||||
- [`watchTrades (symbol, since, limit, params)`](ccxt.pro.manual#watchTrades)
|
||||
- [`watchTradesForSymbols (symbols, since, limit, params)`](ccxt.pro.manual#watchTradesForSymbols)
|
||||
- [`watchBidsAsks (symbols, params)`](ccxt.pro.manual#watchBidsAsks)
|
||||
- [`watchLiquidations (symbol, since, limit, params)`](ccxt.pro.manual#watchBidsAsks)
|
||||
- [`watchLiquidationsForSymbols (symbols, since, limit, params)`](ccxt.pro.manual#watchForSymbols)
|
||||
- [Private Methods](ccxt.pro.manual#private-methods)
|
||||
- [Authentication](ccxt.pro.manual#authentication)
|
||||
- [Trading](ccxt.pro.manual#trading)
|
||||
- [`watchBalance (params)`](ccxt.pro.manual#watchBalance)
|
||||
- [`watchOrders (symbol, since, limit, params)`](ccxt.pro.manual#watchOrders)
|
||||
- [`watchOrdersForSymbols (symbols, since, limit, params)`](ccxt.pro.manual#watchOrdersForSymbols)
|
||||
- [`watchPosition (symbol, since, limit, params)`](ccxt.pro.manual#watchPosition)
|
||||
- [`watchPositions (symbols, since, limit, params)`](ccxt.pro.manual#watchPositions)
|
||||
- [`watchMyTrades (symbol, since, limit, params)`](https://github.com/ccxt-dev/ccxt/wiki/ccxt.pro/Manual#watchMyTrades)
|
||||
- [`watchDepositsWithdrawals (code, limit, params)`](https://github.com/ccxt/ccxt/wiki/Manual#watchDepositsWithdrawals)
|
||||
- [`watchMyLiquidations (symbols, since, limit, params)`](https://github.com/ccxt/ccxt/wiki/Manual#watchMyLiquidations)
|
||||
- [`watchMyLiquidationsForSymbols (symbols, since, limit, params)`](https://github.com/ccxt/ccxt/wiki/Manual#watchMyLiquidationsForSymbols)
|
||||
- REST alternatives:
|
||||
In addition to above methods, some major exchanges also support websocket methods for REST methods, like `createOrderWs` (which has same signature as `createOrder`). You can find them in `exchange.has` dictionary.
|
||||
- [UnWatch](ccxt.pro.manual#unwatch) (for stopping **watch** methods).
|
||||
- [Error Handling](ccxt.pro.manual#error-handling)
|
||||
- [Troubleshooting](https://github.com/ccxt/ccxt/wiki/Manual#troubleshooting)
|
||||
- [How To Submit An Issue](https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-submit-an-issue)
|
||||
- [Usage Examples](https://github.com/ccxt/ccxt/tree/master/examples)
|
||||
@@ -0,0 +1,303 @@
|
||||
<style>ul { margin-bottom: -10px; }</style>
|
||||
|
||||
# [<-](Examples?id=javascript)
|
||||
|
||||
# CCXT JavaScript Examples
|
||||
|
||||
These examples might require the following super-useful high-quality Node.js modules by [xpl](https://github.com/xpl):
|
||||
|
||||
- [ansicolor](https://github.com/xpl/ansicolor): A quality JavaScript library for the ANSI color/style management ([ansicolor @ npm](https://npmjs.com/package/ansicolor))
|
||||
- [as-table](https://github.com/xpl/as-table): A simple function that prints objects as ASCII tables ([as-table @ npm](https://npmjs.com/package/as-table))
|
||||
- [ololog](https://github.com/xpl/ololog): Platform-agnostic logging with blackjack and hookers ([ololog @ npm](https://npmjs.com/package/ololog))
|
||||
|
||||
All of the modules above are installed with the ccxt library devDependencies by npm automatically.
|
||||
|
||||
To run the ccxt JavaScript examples from any folder type in console:
|
||||
|
||||
```shell
|
||||
node path/to/example.js # substitute for actual filename here
|
||||
```
|
||||
|
||||
|
||||
- [Advanced Error Handling](./examples/js/advanced-error-handling.md)
|
||||
|
||||
- [Aggregate Orderbook](./examples/js/aggregate-orderbook.md)
|
||||
|
||||
- [Apex Example](./examples/js/apex-example.md)
|
||||
|
||||
- [Arbitrage Pairs](./examples/js/arbitrage-pairs.md)
|
||||
|
||||
- [Basic Chart](./examples/js/basic-chart.md)
|
||||
|
||||
- [Basic Orderbook Polling](./examples/js/basic-orderbook-polling.md)
|
||||
|
||||
- [Bcc Vs Bch](./examples/js/bcc-vs-bch.md)
|
||||
|
||||
- [Benchmark](./examples/js/benchmark.md)
|
||||
|
||||
- [Binance Fetch All Deposits](./examples/js/binance-fetch-all-deposits.md)
|
||||
|
||||
- [Binance Fetch Ohlcv Many Symbols Async Await](./examples/js/binance-fetch-ohlcv-many-symbols-async-await.md)
|
||||
|
||||
- [Binance Fetch Ohlcv Many Symbols Promise Then Callbacks](./examples/js/binance-fetch-ohlcv-many-symbols-promise-then-callbacks.md)
|
||||
|
||||
- [Binance Fetchticker Delivery Vs Future](./examples/js/binance-fetchTicker-delivery-vs-future.md)
|
||||
|
||||
- [Binance Futures Transfer From Sub Account To Master](./examples/js/binance-futures-transfer-from-sub-account-to-master.md)
|
||||
|
||||
- [Binance Margin Stop Order](./examples/js/binance-margin-stop-order.md)
|
||||
|
||||
- [Binance Server Time](./examples/js/binance-server-time.md)
|
||||
|
||||
- [Binance Universal Transfer](./examples/js/binance-universal-transfer.md)
|
||||
|
||||
- [Bitfinex Fetch Trades](./examples/js/bitfinex-fetch-trades.md)
|
||||
|
||||
- [Bitfinex2 Fetch Trades](./examples/js/bitfinex2-fetch-trades.md)
|
||||
|
||||
- [Bitmex Browser Cors Proxy](./examples/js/bitmex-browser-cors-proxy.md)
|
||||
|
||||
- [Bitpanda Fetchmytrades Reduce](./examples/js/bitpanda-fetchMyTrades-reduce.md)
|
||||
|
||||
- [Bitrue Fetch Balance](./examples/js/bitrue-fetch-balance.md)
|
||||
|
||||
- [Bitstamp Private Api](./examples/js/bitstamp-private-api.md)
|
||||
|
||||
- [Bitstamp Public Api](./examples/js/bitstamp-public-api.md)
|
||||
|
||||
- [Bittrex Balance](./examples/js/bittrex-balance.md)
|
||||
|
||||
- [Bittrex Fetch Closed Orders History](./examples/js/bittrex-fetch-closed-orders-history.md)
|
||||
|
||||
- [Blockchaincom Withdrawal](./examples/js/blockchaincom-withdrawal.md)
|
||||
|
||||
- [Build Ohlcv Bars](./examples/js/build-ohlcv-bars.md)
|
||||
|
||||
- [Builtin Rate Limiting Rest Poller](./examples/js/builtin-rate-limiting-rest-poller.md)
|
||||
|
||||
- [Bybit Trailing](./examples/js/bybit-trailing.md)
|
||||
|
||||
- [Bybit Updated](./examples/js/bybit-updated.md)
|
||||
|
||||
- [Coinbase Fetch All Balances](./examples/js/coinbase-fetch-all-balances.md)
|
||||
|
||||
- [Coinex Fetch All Deposit Addresses Using Fetchdepositaddress](./examples/js/coinex-fetch-all-deposit-addresses-using-fetchDepositAddress.md)
|
||||
|
||||
- [Coinex Futures](./examples/js/coinex-futures.md)
|
||||
|
||||
- [Coinone Fetch Tickers](./examples/js/coinone-fetch-tickers.md)
|
||||
|
||||
- [Coinone Markets](./examples/js/coinone-markets.md)
|
||||
|
||||
- [Compare Two Exchanges Capabilities](./examples/js/compare-two-exchanges-capabilities.md)
|
||||
|
||||
- [Cors Proxy](./examples/js/cors-proxy.md)
|
||||
|
||||
- [Create Order Handle Errors](./examples/js/create-order-handle-errors.md)
|
||||
|
||||
- [Create Order Position With Takeprofit Stoploss](./examples/js/create-order-position-with-takeprofit-stoploss.md)
|
||||
|
||||
- [Create Order With Retry](./examples/js/create-order-with-retry.md)
|
||||
|
||||
- [Create Order Ws Example](./examples/js/create-order-ws-example.md)
|
||||
|
||||
- [Create Orders Example](./examples/js/create-orders-example.md)
|
||||
|
||||
- [Create Trailing Amount Order](./examples/js/create-trailing-amount-order.md)
|
||||
|
||||
- [Create Trailing Percent Order](./examples/js/create-trailing-percent-order.md)
|
||||
|
||||
- [Credentials](./examples/js/credentials.md)
|
||||
|
||||
- [Custom Proxy Agent For Js](./examples/js/custom-proxy-agent-for-js.md)
|
||||
|
||||
- [Custom Proxy Url](./examples/js/custom-proxy-url.md)
|
||||
|
||||
- [Delta Maintenance Margin Rate Max Leverage](./examples/js/delta-maintenance-margin-rate-max-leverage.md)
|
||||
|
||||
- [Env Variables](./examples/js/env-variables.md)
|
||||
|
||||
- [Error Handling](./examples/js/error-handling.md)
|
||||
|
||||
- [Exchange Capabilities](./examples/js/exchange-capabilities.md)
|
||||
|
||||
- [Exchanges By Volume](./examples/js/exchanges-by-volume.md)
|
||||
|
||||
- [Exchanges](./examples/js/exchanges.md)
|
||||
|
||||
- [Fetch All Balances](./examples/js/fetch-all-balances.md)
|
||||
|
||||
- [Fetch All Tickers To Files 2](./examples/js/fetch-all-tickers-to-files-2.md)
|
||||
|
||||
- [Fetch All Tickers To Files](./examples/js/fetch-all-tickers-to-files.md)
|
||||
|
||||
- [Fetch Balance](./examples/js/fetch-balance.md)
|
||||
|
||||
- [Fetch Create Deposit Address](./examples/js/fetch-create-deposit-address.md)
|
||||
|
||||
- [Fetch First Ohlcv Timestamp](./examples/js/fetch-first-ohlcv-timestamp.md)
|
||||
|
||||
- [Fetch From Many Exchanges Simultaneously](./examples/js/fetch-from-many-exchanges-simultaneously.md)
|
||||
|
||||
- [Fetch Funding Rate History](./examples/js/fetch-funding-rate-history.md)
|
||||
|
||||
- [📂 Fetch Futures](https://github.com/ccxt/ccxt/tree/master/./examples/js/fetch-futures)
|
||||
|
||||
- [Fetch Ohlcv From To Mark Index Premium](./examples/js/fetch-ohlcv-from-to-mark-index-premium.md)
|
||||
|
||||
- [Fetch Ohlcv Many Exchanges Continuosly](./examples/js/fetch-ohlcv-many-exchanges-continuosly.md)
|
||||
|
||||
- [Fetch Ohlcv](./examples/js/fetch-ohlcv.md)
|
||||
|
||||
- [Fetch Okex Futures](./examples/js/fetch-okex-futures.md)
|
||||
|
||||
- [Fetch Orders](./examples/js/fetch-orders.md)
|
||||
|
||||
- [Fetch Ticker From Multiple Exchanges](./examples/js/fetch-ticker-from-multiple-exchanges.md)
|
||||
|
||||
- [Fetch Ticker Where Available](./examples/js/fetch-ticker-where-available.md)
|
||||
|
||||
- [📂 Fetch Tickers](https://github.com/ccxt/ccxt/tree/master/./examples/js/fetch-tickers)
|
||||
|
||||
- [Gateio Create Batch Order](./examples/js/gateio-create-batch-order.md)
|
||||
|
||||
- [Gateio Futures](./examples/js/gateio-futures.md)
|
||||
|
||||
- [Gateio Open Close Contract](./examples/js/gateio-open-close-contract.md)
|
||||
|
||||
- [Gateio Swaps](./examples/js/gateio-swaps.md)
|
||||
|
||||
- [Gdax Fetch Trades Pagination](./examples/js/gdax-fetch-trades-pagination.md)
|
||||
|
||||
- [Hibachi Example](./examples/js/hibachi-example.md)
|
||||
|
||||
- [Hitbtc2 Withdraw](./examples/js/hitbtc2-withdraw.md)
|
||||
|
||||
- [How To Import One Exchange Esm](./examples/js/how-to-import-one-exchange-esm.md)
|
||||
|
||||
- [Huobi Futures](./examples/js/huobi-futures.md)
|
||||
|
||||
- [Huobi Open Close Contract](./examples/js/huobi-open-close-contract.md)
|
||||
|
||||
- [Huobi Swaps](./examples/js/huobi-swaps.md)
|
||||
|
||||
- [Huobipro Market Buy Sell Fetch Trading Limits](./examples/js/huobipro-market-buy-sell-fetch-trading-limits.md)
|
||||
|
||||
- [Hybridcjsexample](./examples/js/hybridCJSExample.md)
|
||||
|
||||
- [Hybridesmexample](./examples/js/hybridESMExample.md)
|
||||
|
||||
- [Idex Fetch Balance](./examples/js/idex-fetch-balance.md)
|
||||
|
||||
- [Instantiate All At Once](./examples/js/instantiate-all-at-once.md)
|
||||
|
||||
- [Instantiate All From Json](./examples/js/instantiate-all-from-json.md)
|
||||
|
||||
- [Kraken Create And Close Position](./examples/js/kraken-create-and-close-position.md)
|
||||
|
||||
- [Kraken Fetch Order Trades](./examples/js/kraken-fetch-order-trades.md)
|
||||
|
||||
- [Kraken Margin Trading](./examples/js/kraken-margin-trading.md)
|
||||
|
||||
- [Kucoin Rate Limit](./examples/js/kucoin-rate-limit.md)
|
||||
|
||||
- [Latoken Example](./examples/js/latoken-example.md)
|
||||
|
||||
- [Live Orderbook](./examples/js/live-orderbook.md)
|
||||
|
||||
- [Live Ticker](./examples/js/live-ticker.md)
|
||||
|
||||
- [Live Tickers](./examples/js/live-tickers.md)
|
||||
|
||||
- [Load All Contracts](./examples/js/load-all-contracts.md)
|
||||
|
||||
- [Load All Symbols At Once](./examples/js/load-all-symbols-at-once.md)
|
||||
|
||||
- [Load All Tickers At Once](./examples/js/load-all-tickers-at-once.md)
|
||||
|
||||
- [Load Markets To Files](./examples/js/load-markets-to-files.md)
|
||||
|
||||
- [Looping Over All Symbols Of Specific Exchanges](./examples/js/looping-over-all-symbols-of-specific-exchanges.md)
|
||||
|
||||
- [Looping Over Specific Symbols Of All Exchanges](./examples/js/looping-over-specific-symbols-of-all-exchanges.md)
|
||||
|
||||
- [Margin Loan Borrow Buy Sell Repay](./examples/js/margin-loan-borrow-buy-sell-repay.md)
|
||||
|
||||
- [Market Status And Currency Status](./examples/js/market-status-and-currency-status.md)
|
||||
|
||||
- [Ohlcv Console Chart](./examples/js/ohlcv-console-chart.md)
|
||||
|
||||
- [Okex Fetch Closed Orders Archive](./examples/js/okex-fetch-closed-orders-archive.md)
|
||||
|
||||
- [Okex Transfer](./examples/js/okex-transfer.md)
|
||||
|
||||
- [Okx Poll Fetch My Trades](./examples/js/okx-poll-fetch-my-trades.md)
|
||||
|
||||
- [Okx Poll Rate Limit](./examples/js/okx-poll-rate-limit.md)
|
||||
|
||||
- [Order Book Extra Level Depth Param](./examples/js/order-book-extra-level-depth-param.md)
|
||||
|
||||
- [Phemex Create Order Position With Takeprofit Stoploss](./examples/js/phemex-create-order-position-with-takeprofit-stoploss.md)
|
||||
|
||||
- [Poll Ohlcv](./examples/js/poll-ohlcv.md)
|
||||
|
||||
- [Poloniex Fetch Order Books](./examples/js/poloniex-fetch-order-books.md)
|
||||
|
||||
- [Poloniex Limits Amount Min](./examples/js/poloniex-limits-amount-min.md)
|
||||
|
||||
- [Proxy Round Robin](./examples/js/proxy-round-robin.md)
|
||||
|
||||
- [Proxy Usage](./examples/js/proxy-usage.md)
|
||||
|
||||
- [Sample Local Proxy Server With Cors](./examples/js/sample-local-proxy-server-with-cors.md)
|
||||
|
||||
- [Search All Exchanges](./examples/js/search-all-exchanges.md)
|
||||
|
||||
- [Shared Load Markets](./examples/js/shared-load-markets.md)
|
||||
|
||||
- [Sort Swap Markets By Hourly Price Change](./examples/js/sort-swap-markets-by-hourly-price-change.md)
|
||||
|
||||
- [Symbols](./examples/js/symbols.md)
|
||||
|
||||
- [Theocean](./examples/js/theocean.md)
|
||||
|
||||
- [Tickers](./examples/js/tickers.md)
|
||||
|
||||
- [Validate Paginated Data](./examples/js/validate-paginated-data.md)
|
||||
|
||||
- [Watch Ohlcv For Symbols](./examples/js/watch-OHLCV-For-Symbols.md)
|
||||
|
||||
- [Watch Ohlcv](./examples/js/watch-OHLCV.md)
|
||||
|
||||
- [Watch Orderbook For Symbols](./examples/js/watch-OrderBook-For-Symbols.md)
|
||||
|
||||
- [Watch Trades For Symbols](./examples/js/watch-Trades-For-Symbols.md)
|
||||
|
||||
- [Watch Tickers](./examples/js/watch-tickers.md)
|
||||
|
||||
- [Watchohlcvforsymbols](./examples/js/watchOHLCVForSymbols.md)
|
||||
|
||||
- [Watchorderbookforsymbols](./examples/js/watchOrderBookForSymbols.md)
|
||||
|
||||
- [Watchpositions Many Exchanges Continuosly.d](./examples/js/watchPositions-many-exchanges-continuosly.d.md)
|
||||
|
||||
- [Watchpositions Many Exchanges Continuosly.d.ts](./examples/js/watchPositions-many-exchanges-continuosly.d.ts.md)
|
||||
|
||||
- [Watchpositions Many Exchanges Continuosly](./examples/js/watchPositions-many-exchanges-continuosly.md)
|
||||
|
||||
- [Watchpositions.d](./examples/js/watchPositions.d.md)
|
||||
|
||||
- [Watchpositions.d.ts](./examples/js/watchPositions.d.ts.md)
|
||||
|
||||
- [Watchpositions](./examples/js/watchPositions.md)
|
||||
|
||||
- [Watchpositionsforsymbols.d](./examples/js/watchPositionsForSymbols.d.md)
|
||||
|
||||
- [Watchpositionsforsymbols.d.ts](./examples/js/watchPositionsForSymbols.d.ts.md)
|
||||
|
||||
- [Watchpositionsforsymbols](./examples/js/watchPositionsForSymbols.md)
|
||||
|
||||
- [Watchtradesforsymbols](./examples/js/watchTradesForSymbols.md)
|
||||
|
||||
- [Withdraw From One Exchange To Another](./examples/js/withdraw-from-one-exchange-to-another.md)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
- [Advanced Error Handling](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
"use strict";
|
||||
|
||||
const ccxt = require ('../../ccxt.js');
|
||||
|
||||
// instantiate the exchange
|
||||
let exchange = new ccxt.coinbasepro ({
|
||||
'apiKey': 'XXXXXXXXXXXXXX',
|
||||
'secret': 'YYYYYYYYYYYYYY',
|
||||
});
|
||||
|
||||
async function checkOrders(){
|
||||
try {
|
||||
// fetch orders
|
||||
let orders = await exchange.fetchOrders ('BTC/USDT');
|
||||
// output the result
|
||||
console.log (exchange.id, 'fetched orders', orders);
|
||||
} catch (e) {
|
||||
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
|
||||
console.log ('[DDoS Protection] ' + e.message);
|
||||
} else if (e instanceof ccxt.RequestTimeout) {
|
||||
console.log ('[Request Timeout] ' + e.message);
|
||||
} else if (e instanceof ccxt.AuthenticationError) {
|
||||
console.log ('[Authentication Error] ' + e.message);
|
||||
} else if (e instanceof ccxt.ExchangeNotAvailable) {
|
||||
console.log ('[Exchange Not Available Error] ' + e.message);
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
console.log ('[Exchange Error] ' + e.message);
|
||||
} else if (e instanceof ccxt.NetworkError) {
|
||||
console.log ('[Network Error] ' + e.message);
|
||||
} else {
|
||||
// you can throw it if you want to stop the execution
|
||||
// console.log ('[Exception ' + e.constructor.name + '] ' + e.message);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// for demonstrational purposes, we use 1000 ms interval
|
||||
setInterval(checkOrders, 1000);
|
||||
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
- [Aggregate Orderbook](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
const aggregateOrderBookSide = function (orderbookSide, precision = undefined) {
|
||||
const result = []
|
||||
const amounts = {}
|
||||
for (let i = 0; i < orderbookSide.length; i++) {
|
||||
const ask = orderbookSide[i]
|
||||
let price = ask[0]
|
||||
if (precision !== undefined) {
|
||||
price = ccxt.decimalToPrecision (price, ccxt.ROUND, precision, ccxt.TICK_SIZE)
|
||||
}
|
||||
amounts[price] = (amounts[price] || 0) + ask[1]
|
||||
}
|
||||
Object.keys (amounts).forEach (price => {
|
||||
result.push ([
|
||||
parseFloat (price),
|
||||
amounts[price]
|
||||
])
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
const aggregateOrderBook = function (orderbook, precision = undefined) {
|
||||
let asks = aggregateOrderBookSide(orderbook['asks'], precision)
|
||||
let bids = aggregateOrderBookSide(orderbook['bids'], precision)
|
||||
return {
|
||||
'asks': ccxt.sortBy (asks, 0),
|
||||
'bids': ccxt.sortBy (bids, 0, true),
|
||||
'timestamp': orderbook['timestamp'],
|
||||
'datetime': orderbook['datetime'],
|
||||
'nonce': orderbook['nonce'],
|
||||
};
|
||||
}
|
||||
|
||||
;(async () => {
|
||||
|
||||
const exchange = new ccxt.coinbasepro()
|
||||
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
// exchange.verbose = true // uncomment for verbose debug output
|
||||
|
||||
// level 2 (default)
|
||||
const orderbook = await exchange.fetchOrderBook('BTC/USD')
|
||||
|
||||
// or level 3
|
||||
// const orderbook = await exchange.fetchOrderBook('BTC/USD', undefined, { 'level': 3 })
|
||||
|
||||
const step = 0.5 // 0.01, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0
|
||||
console.log (aggregateOrderBook (orderbook, step))
|
||||
|
||||
})();
|
||||
```
|
||||
@@ -0,0 +1,103 @@
|
||||
- [Apex Example](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
async function example() {
|
||||
const exchange = new ccxt.apex({
|
||||
'apiKey': 'your api Key',
|
||||
'secret': 'your api secret',
|
||||
'walletAddress': 'your eth address',
|
||||
'options': {
|
||||
'accountId': 'your account id',
|
||||
'passphrase': 'your api passphrase',
|
||||
'seeds': 'your zklink omni seed',
|
||||
'brokerId': '',
|
||||
},
|
||||
});
|
||||
exchange.setSandboxMode (true)
|
||||
const fetchTime = await exchange.fetchTime();
|
||||
console.log(fetchTime);
|
||||
//const transfer = await exchange.transfer('USDT', 1.1);
|
||||
//console.log(transfer);
|
||||
//const transferFromContract = await exchange.transfer('USDT', 1.2, 'contract', 'spot');
|
||||
//console.log(transferFromContract);
|
||||
//const fetchCurrencies = await exchange.fetchCurrencies();
|
||||
//console.log(fetchCurrencies);
|
||||
//const fetchBalance = await exchange.fetchBalance();
|
||||
//console.log(fetchBalance);
|
||||
//const fetchMarkets = await exchange.fetchMarkets();
|
||||
//console.log(fetchMarkets);
|
||||
//const fetchTicker = await exchange.fetchTicker('BTC-USDT');
|
||||
//console.log(fetchTicker);
|
||||
//const fetchTickers = await exchange.fetchTickers();
|
||||
//console.log(fetchTickers);
|
||||
//const fetchTrades = await exchange.fetchTrades('BTC-USDT');
|
||||
//console.log(fetchTrades);
|
||||
//const fetchOHLCV = await exchange.fetchOHLCV('BTC-USDT','1m', undefined, 200);
|
||||
//console.log(fetchOHLCV);
|
||||
//const fechOrderBook = await exchange.fetchOrderBook('BTC-USDT');
|
||||
//console.log(fechOrderBook);
|
||||
//const fetchOpenInterest = await exchange.fetchOpenInterest('BTC-USDT');
|
||||
//console.log(fetchOpenInterest);
|
||||
|
||||
//const fetchTransfers = await exchange.fetchTransfers();
|
||||
//console.log(fetchTransfers);
|
||||
//const fetchTransfer = await exchange.fetchTransfer();
|
||||
//console.log(fetchTransfer);
|
||||
|
||||
//const createOrderRes1 = await exchange.createOrder('BTC-USDT', 'LIMIT', 'SELL', 0.001, 100000, {'reduceOnly':true});
|
||||
//console.log(createOrderRes1);
|
||||
const createOrderRes1 = await exchange.createOrder('BTC-USDT', 'STOP_LIMIT', 'BUY', 0.001, 100000, {'triggerPriceType':'INDEX', 'triggerPrice':'10100'});
|
||||
console.log(createOrderRes1);
|
||||
|
||||
const fetchOpenOrders = await exchange.fetchOpenOrders();
|
||||
console.log(fetchOpenOrders);
|
||||
//const fetchOpenOrder = await exchange.fetchOrder(undefined,undefined,{"clientOrderId":'apexomni-615910568987983964-1741322302826-253839'});
|
||||
//console.log(fetchOpenOrder);
|
||||
//const cancelOrder = await exchange.cancelOrder('685707935650677596');
|
||||
//console.log(cancelOrder);
|
||||
//const cancelOrder1 = await exchange.cancelOrder(undefined,undefined,{"clientOrderId":'apexomni-615910568987983964-1741324574601-908656'});
|
||||
//console.log(cancelOrder1);
|
||||
//const cancelAllOrders = await exchange.cancelAllOrders();
|
||||
//console.log(cancelAllOrders);
|
||||
|
||||
//const setLeverage = await exchange.setLeverage(5,'BTC-USDT');
|
||||
//console.log(setLeverage);
|
||||
|
||||
//const fetchPositions = await exchange.fetchPositions();
|
||||
//console.log(fetchPositions);
|
||||
|
||||
//const fetchOrder = await exchange.fetchOrder('685781264227107164');
|
||||
//console.log(fetchOrder);
|
||||
|
||||
//const fetchOrderTrades = await exchange.fetchOrderTrades('685781264227107164'); //{"clientOrderId":'apexomni-615910568987983964-1741339789276-640091'}
|
||||
//console.log(fetchOrderTrades);
|
||||
|
||||
|
||||
let since = exchange.milliseconds () - 86400000*1; // -1 day from now
|
||||
let allTrades = [];
|
||||
let page = 0;
|
||||
while (since < exchange.milliseconds ()) {
|
||||
const params = {
|
||||
'page': page, // exchange-specific non-unified parameter name
|
||||
}
|
||||
const trades = await exchange.fetchFundingHistory ('BTC-USDT', since, 20, params)
|
||||
if (trades.length) {
|
||||
allTrades = allTrades.concat (trades)
|
||||
page++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
allTrades = exchange.sortBy(allTrades, 'timestamp');
|
||||
|
||||
|
||||
const createOrderRes = await exchange.createOrder('BTC-USDT', 'LIMIT', 'BUY', 0.001, 70000, {'reduceOnly':true,'postOnly':true});
|
||||
console.log(createOrderRes);
|
||||
console.log('end');
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,135 @@
|
||||
- [Arbitrage Pairs](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
import fs from 'fs';
|
||||
import ansicolor from 'ansicolor';
|
||||
import ololog from 'ololog';
|
||||
|
||||
const log = ololog.configure ({ locate: false }), verbose = process.argv.includes ('--verbose'), keysGlobal = 'keys.json', keysLocal = 'keys.local.json', keysFile = fs.existsSync (keysLocal) ? keysLocal : (fs.existsSync (keysGlobal) ? keysGlobal : false), config = keysFile ? require ('../../' + keysFile) : {};
|
||||
|
||||
let printSupportedExchanges = function () {
|
||||
log ('Supported exchanges:', ccxt.exchanges.join (', ').green)
|
||||
}
|
||||
|
||||
let printUsage = function () {
|
||||
log ('Usage: node', process.argv[1], 'id1'.green, 'id2'.yellow, 'id3'.blue, '...')
|
||||
printSupportedExchanges ()
|
||||
}
|
||||
|
||||
let printExchangeSymbolsAndMarkets = function (exchange) {
|
||||
log (getExchangeSymbols (exchange))
|
||||
log (getExchangeMarketsTable (exchange))
|
||||
}
|
||||
|
||||
let getExchangeMarketsTable = (exchange) => {
|
||||
return asTable.configure ({ delimiter: ' | ' }) (Object.values (markets))
|
||||
}
|
||||
|
||||
let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));
|
||||
|
||||
let proxies = [
|
||||
'', // no proxy by default
|
||||
'https://crossorigin.me/',
|
||||
'https://cors-anywhere.herokuapp.com/',
|
||||
]
|
||||
|
||||
;(async function main () {
|
||||
|
||||
if (process.argv.length > 3) {
|
||||
|
||||
let ids = process.argv.slice (2)
|
||||
let exchanges = {}
|
||||
|
||||
log (ids.join (', ').yellow)
|
||||
|
||||
// load all markets from all exchanges
|
||||
for (let id of ids) {
|
||||
|
||||
let settings = config[id] || {}
|
||||
|
||||
// instantiate the exchange by id
|
||||
let exchange = new ccxt[id] (ccxt.extend ({
|
||||
// verbose,
|
||||
// 'proxy': 'https://cors-anywhere.herokuapp.com/',
|
||||
}, settings))
|
||||
|
||||
// save it in a dictionary under its id for future use
|
||||
exchanges[id] = exchange
|
||||
|
||||
// load all markets from the exchange
|
||||
let markets = await exchange.loadMarkets ()
|
||||
|
||||
// basic round-robin proxy scheduler
|
||||
let currentProxy = 0
|
||||
let maxRetries = proxies.length
|
||||
|
||||
for (let numRetries = 0; numRetries < maxRetries; numRetries++) {
|
||||
|
||||
try { // try to load exchange markets using current proxy
|
||||
|
||||
exchange.proxy = proxies[currentProxy]
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
} catch (e) { // rotate proxies in case of connectivity errors, catch all other exceptions
|
||||
|
||||
// swallow connectivity exceptions only
|
||||
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
|
||||
log.bright.yellow ('[DDoS Protection Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.RequestTimeout) {
|
||||
log.bright.yellow ('[Timeout Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.AuthenticationError) {
|
||||
log.bright.yellow ('[Authentication Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeNotAvailable) {
|
||||
log.bright.yellow ('[Exchange Not Available Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
log.bright.yellow ('[Exchange Error] ' + e.message)
|
||||
} else {
|
||||
throw e; // rethrow all other exceptions
|
||||
}
|
||||
|
||||
// retry next proxy in round-robin fashion in case of error
|
||||
currentProxy = ++currentProxy % proxies.length
|
||||
}
|
||||
}
|
||||
|
||||
log (id.green, 'loaded', exchange.symbols.length.toString ().green, 'markets')
|
||||
}
|
||||
|
||||
log ('Loaded all markets'.green)
|
||||
|
||||
// get all unique symbols
|
||||
let uniqueSymbols = ccxt.unique (ccxt.flatten (ids.map (id => exchanges[id].symbols)))
|
||||
|
||||
// filter out symbols that are not present on at least two exchanges
|
||||
let arbitrableSymbols = uniqueSymbols
|
||||
.filter (symbol =>
|
||||
ids.filter (id =>
|
||||
(exchanges[id].symbols.indexOf (symbol) >= 0)).length > 1)
|
||||
.sort ((id1, id2) => (id1 > id2) ? 1 : ((id2 > id1) ? -1 : 0))
|
||||
|
||||
// print a table of arbitrable symbols
|
||||
let table = arbitrableSymbols.map (symbol => {
|
||||
let row = { symbol }
|
||||
for (let id of ids)
|
||||
if (exchanges[id].symbols.indexOf (symbol) >= 0)
|
||||
row[id] = id
|
||||
return row
|
||||
})
|
||||
|
||||
log (asTable.configure ({ delimiter: ' | ' }) (table))
|
||||
|
||||
} else {
|
||||
|
||||
printUsage ()
|
||||
|
||||
}
|
||||
|
||||
process.exit ()
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,34 @@
|
||||
- [Basic Chart](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asciichart from 'asciichart';
|
||||
import asTable from 'as-table';
|
||||
import ololog from 'ololog'
|
||||
import ansicolor from 'ansicolor';
|
||||
|
||||
const log = ololog.configure ({ locate: false })
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
;(async function main () {
|
||||
|
||||
// experimental, not yet implemented for all exchanges
|
||||
// your contributions are welcome ;)
|
||||
|
||||
const index = 4 // [ timestamp, open, high, low, close, volume ]
|
||||
const ohlcv = await new ccxt.okcoin ().fetchOHLCV ('BTC/USD', '15m')
|
||||
const lastPrice = ohlcv[ohlcv.length - 1][index] // closing price
|
||||
const series = ohlcv.map (x => x[index]) // closing price
|
||||
const bitcoinRate = ('₿ = $' + lastPrice).green
|
||||
const chart = asciichart.plot (series, { height: 15, padding: ' ' })
|
||||
log.yellow ("\n" + chart, bitcoinRate, "\n")
|
||||
process.exit ()
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
- [Basic Orderbook Polling](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
const id = 'huobipro', exchange = new ccxt[id] ({ enableRateLimit: true }), symbol = 'ETH/BTC';(async function main () {
|
||||
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
for (let i = 0; i < 2000; i++) {
|
||||
|
||||
const orderbook = await exchange.fetchOrderBook (symbol)
|
||||
console.log (new Date (), i, symbol, orderbook.asks[0], orderbook.bids[0])
|
||||
}
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,121 @@
|
||||
- [Bcc Vs Bch](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
import ololog from 'ololog'
|
||||
import config from '../../keys.json';
|
||||
import ansicolor from 'ansicolor';
|
||||
|
||||
const log = ololog.configure ({ locate: false })
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms))
|
||||
|
||||
let proxies = [
|
||||
'', // no proxy by default
|
||||
'https://crossorigin.me/',
|
||||
'https://cors-anywhere.herokuapp.com/',
|
||||
]
|
||||
|
||||
;(async function main () {
|
||||
|
||||
let ids = ccxt.exchanges
|
||||
let exchanges = {}
|
||||
|
||||
// instantiate all exchanges
|
||||
ccxt.exchanges.forEach (id => {
|
||||
if (id in ccxt)
|
||||
exchanges[id] = new (ccxt)[id] ({
|
||||
verbose: false,
|
||||
substituteCommonCurrencyCodes: true,
|
||||
})
|
||||
})
|
||||
|
||||
// set up api keys appropriately
|
||||
for (let id in config) {
|
||||
if (id in exchanges)
|
||||
for (let key in config[id])
|
||||
exchanges[id][key] = config[id][key]
|
||||
}
|
||||
|
||||
log (ids.join (', ').yellow)
|
||||
|
||||
// load all markets from all exchanges
|
||||
|
||||
await Promise.all (ids.map (async id => {
|
||||
|
||||
let exchange = exchanges[id]
|
||||
|
||||
// basic round-robin proxy scheduler
|
||||
let currentProxy = 0
|
||||
let maxRetries = proxies.length
|
||||
|
||||
for (let numRetries = 0; numRetries < maxRetries; numRetries++) {
|
||||
|
||||
try { // try to load exchange markets using current proxy
|
||||
|
||||
exchange.proxy = proxies[currentProxy]
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
} catch (e) { // rotate proxies in case of connectivity errors, catch all other exceptions
|
||||
|
||||
// swallow connectivity exceptions only
|
||||
if ((e instanceof ccxt.DDoSProtection) || e.message.includes ('ECONNRESET')) {
|
||||
log.bright.yellow (exchange.id + ' [DDoS Protection]')
|
||||
} else if (e instanceof ccxt.RequestTimeout) {
|
||||
log.bright.yellow (exchange.id + ' [Request Timeout] ' + e.message)
|
||||
} else if (e instanceof ccxt.AuthenticationError) {
|
||||
log.bright.yellow (exchange.id + ' [Authentication Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeNotAvailable) {
|
||||
log.bright.yellow (exchange.id + ' [Exchange Not Available] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
log.bright.yellow (exchange.id + ' [Exchange Error] ' + e.message)
|
||||
} else {
|
||||
throw e; // rethrow all other exceptions
|
||||
}
|
||||
|
||||
// retry next proxy in round-robin fashion in case of error
|
||||
currentProxy = ++currentProxy % proxies.length
|
||||
}
|
||||
}
|
||||
|
||||
if (exchange.symbols)
|
||||
log (id.green, 'loaded', exchange.symbols.length.toString ().green, 'markets')
|
||||
|
||||
}))
|
||||
|
||||
log ('Loaded all markets'.green)
|
||||
|
||||
let table = ccxt.exchanges.map (id => {
|
||||
console.log (id)
|
||||
let exchange = exchanges[id]
|
||||
if (exchange.currencies) {
|
||||
let hasBCC = exchange.currencies.includes ('BCC')
|
||||
let hasBCH = exchange.currencies.includes ('BCH')
|
||||
let hasBoth = (hasBCC && hasBCH)
|
||||
return {
|
||||
id,
|
||||
'BCC': hasBoth ? id.green : (hasBCC ? id.yellow : ''),
|
||||
'BCH': hasBCH ? id.green : '',
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
'id': id.red,
|
||||
'BCC': '',
|
||||
'BCH': '',
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
log (asTable.configure ({ delimiter: ' | ' }) (table))
|
||||
|
||||
process.exit ()
|
||||
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,110 @@
|
||||
- [Benchmark](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import { spawn } from 'child_process';
|
||||
import asTable from 'as-table';
|
||||
import ccxt, { version } from '../../js/ccxt.js';
|
||||
const stats = (times) => {
|
||||
// calculate statistics
|
||||
const sum = times.reduce((a, b) => a + b, 0);
|
||||
const avg = Math.round(sum / times.length);
|
||||
const min = Math.min(...times);
|
||||
const max = Math.max(...times);
|
||||
times.sort((a, b) => a - b);
|
||||
const median = times.length % 2 === 0 ? (times[times.length / 2 - 1] + times[times.length / 2]) / 2 : times[Math.floor(times.length / 2)];
|
||||
return { min, 'average': avg, max, median, 'iterations': times.length };
|
||||
};
|
||||
async function benchmark(exchangeId, method, args, verbose = false, minIterations = 10, argsv = '') {
|
||||
const exchange = new ccxt.pro[exchangeId]({});
|
||||
const languages = ['js', 'py', 'php', 'cs'];
|
||||
const commands = languages.map((language) => ({
|
||||
'language': language,
|
||||
'method': method,
|
||||
'command': `npm run cli.${language} ${exchangeId} ${method} ${args.join(' ')} -- ${argsv} --poll`,
|
||||
}));
|
||||
const wsMethod = method + 'Ws';
|
||||
if (exchange.has[wsMethod]) {
|
||||
const wsCommands = languages.map((language) => ({
|
||||
'language': language,
|
||||
'method': wsMethod,
|
||||
'command': `npm run cli.${language} ${exchangeId} ${wsMethod} ${args.join(' ')} -- ${argsv} --poll`,
|
||||
}));
|
||||
commands.push(...wsCommands);
|
||||
}
|
||||
const regex = /iteration (\d+) passed in (\d+) ms/g;
|
||||
async function runCommand(command) {
|
||||
if (verbose) {
|
||||
console.log(exchange.iso8601(new Date().getTime()), ' running command:', command);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const [cmd, ...args] = command.split(' ');
|
||||
const child = spawn(cmd, args);
|
||||
const matches = [];
|
||||
const language = command.slice(8, 15);
|
||||
child.stdout.on('data', (data) => {
|
||||
const message = data.toString();
|
||||
matches.push(...Array.from(message.matchAll(regex)));
|
||||
const match = matches[matches.length - 1];
|
||||
if (match && match[1] && match[2]) {
|
||||
const iteration = parseInt(match[1]);
|
||||
const time = parseInt(match[2]);
|
||||
if (iteration <= minIterations) {
|
||||
if (verbose) {
|
||||
console.log(exchange.iso8601(new Date().getTime()), `${language} iteration ${iteration} passed in ${time} ms`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
const times = matches.map((m) => parseInt(m[2]));
|
||||
child.kill();
|
||||
if (verbose) {
|
||||
console.log(exchange.iso8601(new Date().getTime()), `killed process - ${language} iteration ${iteration} passed in ${time} ms`);
|
||||
}
|
||||
resolve({ times });
|
||||
}
|
||||
}
|
||||
});
|
||||
child.stderr.on('data', (data) => {
|
||||
const message = data.toString();
|
||||
console.error(exchange.iso8601(new Date().getTime()), `command ${command} failed. stderr: ${message}`);
|
||||
const times = matches.map((m) => parseInt(m[2]));
|
||||
resolve({ times });
|
||||
});
|
||||
child.on('close', (code) => {
|
||||
const times = matches.map((m) => parseInt(m[2]));
|
||||
resolve({ times });
|
||||
console.log(exchange.iso8601(new Date().getTime()), `${language} child process exited with code ${code}`);
|
||||
});
|
||||
child.on('error', (err) => {
|
||||
console.error(exchange.iso8601(new Date().getTime()), `command ${command} failed. error: ${err}`);
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
const benchmarks = [];
|
||||
const results = await Promise.all(commands.map((c) => runCommand(c.command)));
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
const result = results[i];
|
||||
benchmarks.push({ 'language': commands[i].language, 'method': commands[i].method, ...stats(result.times) });
|
||||
}
|
||||
if (verbose) {
|
||||
const rawResults = results.map((r, i) => ({ 'language': commands[i].language, 'method': commands[i].method, ...stats(r.times), 'times': r.times }));
|
||||
console.log(rawResults);
|
||||
}
|
||||
console.log(asTable(benchmarks));
|
||||
}
|
||||
const [_, , exchangeId, methodName, ...params] = process.argv.filter((x) => !x.startsWith('--'));
|
||||
const verbose = process.argv.includes('--verbose');
|
||||
const minIterationsString = process.argv.find((x) => x.startsWith('--min-iterations='))?.slice(18);
|
||||
const minIterations = minIterationsString ? parseInt(minIterationsString) : 10;
|
||||
const argsv = process.argv.filter((x) => x.startsWith('--') && !x.startsWith('--min-iterations')).join(' ');
|
||||
console.log((new Date()).toISOString());
|
||||
console.log('Node.js:', process.version);
|
||||
console.log('CCXT v' + version);
|
||||
const start = new Date().getTime();
|
||||
await benchmark(exchangeId, methodName, params, verbose, minIterations, argsv);
|
||||
const end = new Date().getTime();
|
||||
console.log((new Date().toISOString()), 'Total time:', end - start, 'ms');
|
||||
process.exit(0);
|
||||
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
- [Binance Fetch All Deposits](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
(async function main () {
|
||||
|
||||
const exchange = new ccxt.binance ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET',
|
||||
})
|
||||
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
// exchange.verbose = true // uncomment for debugging
|
||||
|
||||
const ninetyDays = 90 * 24 * 60 * 60 * 1000;
|
||||
let startTime = exchange.parse8601 ('2018-01-01T00:00:00')
|
||||
const now = exchange.milliseconds ()
|
||||
const currencyCode = undefined // any currency
|
||||
|
||||
let allTransactions = []
|
||||
|
||||
while (startTime < now) {
|
||||
|
||||
const endTime = startTime + ninetyDays
|
||||
|
||||
const transactions = await exchange.fetchDeposits (currencyCode, startTime, undefined, {
|
||||
'endTime': endTime,
|
||||
})
|
||||
if (transactions.length) {
|
||||
const lastTransaction = transactions[transactions.length - 1]
|
||||
startTime = lastTransaction['timestamp'] + 1
|
||||
allTransactions = allTransactions.concat (transactions)
|
||||
} else {
|
||||
startTime = endTime;
|
||||
}
|
||||
}
|
||||
|
||||
console.log ('Fetched', allTransactions.length, 'transactions')
|
||||
for (let i = 0; i < allTransactions.length; i++) {
|
||||
const transaction = allTransactions[i]
|
||||
console.log (i, transaction['datetime'], transaction['txid'], transaction['currency'], transaction['amount'])
|
||||
}
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
- [Binance Fetch Ohlcv Many Symbols Async Await](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
'use strict';
|
||||
|
||||
const ccxt = require ('../../js/ccxt.js')
|
||||
|
||||
console.log('CCXT Version:', ccxt.version)
|
||||
|
||||
async function symbolLoop (exchange, symbol, timeframe) {
|
||||
while (true) {
|
||||
try {
|
||||
const ohlcvs = await exchange.fetchOHLCV (symbol, timeframe)
|
||||
console.log (exchange.iso8601 (exchange.milliseconds ()), exchange.id, symbol, ohlcvs.length, 'OHLCV candles received')
|
||||
// await exchange.sleep (60 * 1000) // sleep if necessary, though not required
|
||||
} catch (e) {
|
||||
console.log (exchange.iso8601 (exchange.milliseconds ()), exchange.id, symbol, e.constructor.name, e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main () {
|
||||
const exchange = new ccxt.binance ()
|
||||
await exchange.loadMarkets ()
|
||||
// exchange.verbose = true // uncomment for debugging purposes if necessary
|
||||
const symbols = [
|
||||
'BTC/USDT', // unified symbols used here as opposed to exchange-specific market ids
|
||||
'ETH/USDT', // more about unified symbols vs exchange-specific ids here:
|
||||
'ADA/USDT', // https://github.com/ccxt/ccxt/wiki/Manual#markets
|
||||
]
|
||||
const timeframe = '1m'
|
||||
const loops = symbols.map (symbol => symbolLoop (exchange, symbol, timeframe))
|
||||
await Promise.all (loops)
|
||||
}
|
||||
|
||||
|
||||
main ()
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
- [Binance Fetch Ohlcv Many Symbols Promise Then Callbacks](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
'use strict';
|
||||
|
||||
const ccxt = require ('../../js/ccxt.js')
|
||||
|
||||
console.log('CCXT Version:', ccxt.version)
|
||||
|
||||
function symbolLoop (exchange, symbol, timeframe) {
|
||||
exchange.fetchOHLCV (symbol, timeframe).then (ohlcvs => {
|
||||
console.log (exchange.iso8601 (exchange.milliseconds ()), exchange.id, symbol, ohlcvs.length, 'OHLCV candles received')
|
||||
setTimeout (() => symbolLoop (exchange, symbol, timeframe), 0)
|
||||
}).catch (e => {
|
||||
console.log (exchange.iso8601 (exchange.milliseconds ()), exchange.id, symbol, e.constructor.name, e.message)
|
||||
setTimeout (() => symbolLoop (exchange, symbol, timeframe), 0)
|
||||
})
|
||||
}
|
||||
|
||||
function main () {
|
||||
const exchange = new ccxt.binance ()
|
||||
// exchange.verbose = true // uncomment for debugging purposes if necessary
|
||||
const symbols = [
|
||||
'BTC/USDT', // unified symbols used here as opposed to exchange-specific market ids
|
||||
'ETH/USDT', // more about unified symbols vs exchange-specific ids here:
|
||||
'ADA/USDT', // https://github.com/ccxt/ccxt/wiki/Manual#markets
|
||||
]
|
||||
const timeframe = '1m'
|
||||
exchange.loadMarkets ().then (markets => {
|
||||
for (const symbol of symbols) {
|
||||
setTimeout (() => symbolLoop (exchange, symbol, timeframe), 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
main ()
|
||||
```
|
||||
@@ -0,0 +1,36 @@
|
||||
- [Binance Fetchticker Delivery Vs Future](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
async function fetchTickers (exchange) {
|
||||
let tickers = undefined
|
||||
try {
|
||||
// await exchange.loadMarkets () // optional
|
||||
tickers = await exchange.fetchTickers ()
|
||||
} catch (e) {
|
||||
console.error (e.constructor.name, e.message)
|
||||
}
|
||||
return tickers
|
||||
}
|
||||
|
||||
(async () => {
|
||||
|
||||
const future = new ccxt.binance ({ options: { defaultType: 'future' }})
|
||||
const delivery = new ccxt.binance ({ options: { defaultType: 'delivery' }})
|
||||
|
||||
// ...
|
||||
|
||||
const futureTickers = await fetchTickers (future);
|
||||
console.log (futureTickers)
|
||||
|
||||
console.log ('-------------------------------------------')
|
||||
|
||||
const deliveryTickers = await fetchTickers (delivery);
|
||||
console.log (deliveryTickers)
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,47 @@
|
||||
- [Binance Futures Transfer From Sub Account To Master](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
// https://github.com/ccxt/ccxt/issues/10181
|
||||
|
||||
async function main () {
|
||||
|
||||
const exchange = new ccxt.binance ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET',
|
||||
})
|
||||
|
||||
const markets = await exchange.loadMarkets ()
|
||||
|
||||
// exchange.verbose = true // uncomment for debugging purposes
|
||||
|
||||
const fromEmail = 'sender@example.com' // edit for your values
|
||||
, toEmail = 'receiver@example.com' // edit for your values
|
||||
, code = 'USDT' // edit for your values
|
||||
, amount = 100 // edit for your values
|
||||
, futuresType = 1 // 1 for USDT-margined futures,2 for coin-margined futures
|
||||
|
||||
const currency = exchange.currency (code);
|
||||
|
||||
const response = await exchange.sapiPostSubAccountFuturesInternalTransfer ({
|
||||
'fromEmail': fromEmail, // sender email
|
||||
'toEmail': toEmail, // recipient email
|
||||
'futuresType': futuresType, // 1 for USDT-margined futures,2 for coin-margined futures
|
||||
'asset': currency['id'],
|
||||
'amount': exchange.currencyToPrecision (code, amount),
|
||||
})
|
||||
|
||||
console.log (response)
|
||||
|
||||
}
|
||||
|
||||
main ()
|
||||
|
||||
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
- [Binance Margin Stop Order](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
async function main () {
|
||||
|
||||
const exchange = new ccxt.binance({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_API_SECRET',
|
||||
'options': {
|
||||
'defaultType': 'margin',
|
||||
},
|
||||
})
|
||||
|
||||
const markets = await exchange.loadMarkets ()
|
||||
|
||||
exchange.verbose = true // uncomment for debugging purposes if necessary
|
||||
|
||||
const symbol = 'BTC/USDT'
|
||||
const type = 'STOP_LOSS_LIMIT'
|
||||
const side = 'buy'
|
||||
const amount = YOUR_AMOUNT_HERE
|
||||
const price = YOUR_PRICE_HERE
|
||||
const params = {
|
||||
'stopPrice': YOUR_STOP_PRICE_HERE,
|
||||
'timeInForce': 'GTC',
|
||||
}
|
||||
|
||||
try {
|
||||
const order = await exchange.createOrder (symbol, type, side, amount, price, params)
|
||||
console.log (order)
|
||||
} catch (e) {
|
||||
console.log (e.constructor.name, e.message)
|
||||
}
|
||||
}
|
||||
|
||||
main ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
- [Binance Server Time](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import ololog from 'ololog'
|
||||
|
||||
const log = ololog.configure ({ locate: false })
|
||||
|
||||
const binance = new ccxt['binance'] ()
|
||||
const recvWindow = binance.options.recvWindow
|
||||
const aheadWindow = 1000
|
||||
|
||||
async function test () {
|
||||
const localStartTime = Date.now ()
|
||||
const { serverTime } = await binance.publicGetTime ()
|
||||
const localFinishTime = Date.now ()
|
||||
const estimatedLandingTime = (localFinishTime + localStartTime) / 2
|
||||
|
||||
const diff = serverTime - estimatedLandingTime
|
||||
|
||||
log (`request departure time: ${binance.iso8601 (localStartTime)}`)
|
||||
log (`response arrival time: ${binance.iso8601 (localFinishTime)}`)
|
||||
log (`server time: ${binance.iso8601 (serverTime)}`)
|
||||
log (`request landing time (est): ${binance.iso8601 (estimatedLandingTime)}, ${Math.abs (diff)} ms ${Math.sign (diff) > 0 ? 'behind' : 'ahead of'} server`)
|
||||
log ('\n')
|
||||
|
||||
if (diff < -aheadWindow) {
|
||||
log.error.red (`your request will likely be rejected if local time is ahead of the server's time for more than ${aheadWindow} ms \n`)
|
||||
}
|
||||
|
||||
if (diff > recvWindow) {
|
||||
log.error.red (`your request will likely be rejected if local time is behind server time for more than ${recvWindow} ms\n`)
|
||||
}
|
||||
}
|
||||
|
||||
test ();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
- [Binance Universal Transfer](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
(async () => {
|
||||
|
||||
// apiKey must have universal transfer permissions
|
||||
const binance = new ccxt.binance ({
|
||||
"apiKey": "",
|
||||
"secret": "",
|
||||
})
|
||||
|
||||
console.log (await binance.transfer ('USDT', 1, 'spot', 'future'))
|
||||
const transfers = await binance.fetchTransfers ();
|
||||
console.log ('got ', transfers.length, ' transfers')
|
||||
console.log (await binance.transfer ('USDT', 1, 'spot', 'cross')) // For transfer to cross margin wallet
|
||||
console.log (await binance.transfer ('USDT', 1, 'spot', 'ADA/USDT')) // For transfer to an isolated margin wallet
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
- [Bitfinex Fetch Trades](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import log from 'ololog';
|
||||
import asTable from 'as-table';
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
const // ----------------------------------------------------------------------------
|
||||
table = asTable.configure ({ delimiter: ' | ' });(async () => {
|
||||
|
||||
const exchange = new ccxt.bitfinex ({
|
||||
'verbose': process.argv.includes ('--verbose'),
|
||||
'timeout': 60000,
|
||||
})
|
||||
|
||||
try {
|
||||
|
||||
const response = await exchange.fetchTrades ('ETH/BTC', 1518983548636 - 2 * 24 * 60 * 60 * 1000)
|
||||
log (table (response))
|
||||
log (response.length.toString (), 'trades')
|
||||
log.green ('Succeeded.')
|
||||
|
||||
} catch (e) {
|
||||
|
||||
log.dim ('--------------------------------------------------------')
|
||||
log (e.constructor.name, e.message)
|
||||
log.dim ('--------------------------------------------------------')
|
||||
log.dim (exchange.last_http_response)
|
||||
log.error ('Failed.')
|
||||
}
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
- [Bitfinex2 Fetch Trades](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
import log from 'ololog';
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
const // ----------------------------------------------------------------------------
|
||||
table = asTable.configure ({ delimiter: ' | ' });(async () => {
|
||||
|
||||
const exchange = new ccxt.bitfinex2 ({
|
||||
'verbose': process.argv.includes ('--verbose'),
|
||||
'timeout': 60000,
|
||||
})
|
||||
|
||||
try {
|
||||
|
||||
const response = await exchange.fetchTrades ('ETH/BTC', 1518983548636 - 2 * 24 * 60 * 60 * 1000)
|
||||
log (table (response))
|
||||
log (response.length.toString (), 'trades')
|
||||
log.green ('Succeeded.')
|
||||
|
||||
} catch (e) {
|
||||
|
||||
log.dim ('--------------------------------------------------------')
|
||||
log (e.constructor.name, e.message)
|
||||
log.dim ('--------------------------------------------------------')
|
||||
log.dim (exchange.last_http_response)
|
||||
log.error ('Failed.')
|
||||
}
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
- [Bitmex Browser Cors Proxy](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
// JavaScript CORS Proxy
|
||||
// Save this in a file like cors.js and run with `node cors [port]`
|
||||
// It will listen for your requests on the port you pass in command line or port 8080 by default
|
||||
let port = (process.argv.length > 2) ? parseInt (process.argv[2]) : 8080 // default
|
||||
require ('cors-anywhere').createServer ({
|
||||
setHeaders: { 'origin': 'https://www.bitmex.com' }
|
||||
}).listen (port, '0.0.0.0')
|
||||
|
||||
```
|
||||
@@ -0,0 +1,41 @@
|
||||
- [Bitpanda Fetchmytrades Reduce](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
const bitpanda = new ccxt.bitpanda ({
|
||||
"apiKey": "INSERTYOURAPIKEY"
|
||||
})
|
||||
|
||||
|
||||
// output
|
||||
`
|
||||
fetching USDT/EUR trades on bitpanda
|
||||
---------------------------------------------
|
||||
maker volume 6621.81 USDT maker fee 5.62 USDT
|
||||
taker volume 2544.82 USDT taker fee 3.27 USDT
|
||||
|
||||
sold 9166.63 USDT for 7802.38 EUR
|
||||
bought 0.00 USDT for 0.00 EUR
|
||||
`
|
||||
|
||||
;(async () => {
|
||||
const market = {
|
||||
symbol: 'USDT/EUR',
|
||||
base: 'USDT',
|
||||
quote: 'EUR',
|
||||
}
|
||||
console.log ('fetching', market.symbol, 'trades on bitpanda')
|
||||
console.log ('---------------------------------------------')
|
||||
const trades = await bitpanda.fetchMyTrades ('USDT/EUR')
|
||||
const makers = trades.filter (x => x.takerOrMaker === 'maker')
|
||||
const takers = trades.filter (x => x.takerOrMaker === 'taker')
|
||||
console.log ('maker volume', makers.reduce ((a, b) => a + b.amount, 0).toFixed (2), market.base, 'maker fee', makers.reduce ((a, b) => a + b.fee['cost'], 0).toFixed (2), market.base)
|
||||
console.log ('taker volume', takers.reduce ((a, b) => a + b.amount, 0).toFixed (2), market.base, 'taker fee', takers.reduce ((a, b) => a + b.fee['cost'], 0).toFixed (2), market.base)
|
||||
const sells = trades.filter (x => x.side === 'sell')
|
||||
const buys = trades.filter (x => x.side === 'buy')
|
||||
console.log ('\nsold', sells.reduce ((a, b) => a + b.amount, 0).toFixed (2), market.base, 'for', sells.reduce ((a, b) => a + b.cost, 0).toFixed (2), market.quote)
|
||||
console.log ('bought', buys.reduce ((a, b) => a + b.amount, 0).toFixed (2), market.base, 'for', buys.reduce ((a, b) => a + b.cost, 0).toFixed (2), market.quote)
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,34 @@
|
||||
- [Bitrue Fetch Balance](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
async function main () {
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
const exchange = new ccxt.bitrue ({
|
||||
"apiKey": "YOUR_API_KEY",
|
||||
"secret": "YOUR_SECRET",
|
||||
})
|
||||
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
exchange.verbose = true
|
||||
|
||||
try {
|
||||
|
||||
const balance = await exchange.fetchBalance ()
|
||||
console.log (balance)
|
||||
|
||||
} catch (e) {
|
||||
console.log (e.constructor.name, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
main ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,120 @@
|
||||
- [Bitstamp Private Api](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
import ololog from 'ololog'
|
||||
import ansicolor from 'ansicolor';
|
||||
|
||||
const log = ololog.configure({ locate: false })
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
;(async () => {
|
||||
let apiUrl = 'https://www.bitstamp.net/api';
|
||||
|
||||
// instantiate the exchange
|
||||
let exchange = new ccxt.bitstamp({
|
||||
'apiKey': 'APIKEY',
|
||||
'secret': 'APISECRET',
|
||||
'uid': 'ACCOUNTID',
|
||||
'urls': {
|
||||
'api': {
|
||||
'public': apiUrl,
|
||||
'private': apiUrl,
|
||||
'v1': apiUrl
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
try {
|
||||
// fetch account balance from the exchange
|
||||
let balance = await exchange.fetchBalance()
|
||||
log('balance'.green, balance.total)
|
||||
|
||||
// fetch fees
|
||||
let singleFee = await exchange.fetchTradingFee('BTC/USD')
|
||||
log('fee'.green, 'BTC/USD', singleFee)
|
||||
let tradingFees = await exchange.fetchTradingFees()
|
||||
log('tradingFees'.green, tradingFees)
|
||||
let fundingFees = await exchange.fetchFundingFees()
|
||||
log('fundingFees'.green, fundingFees)
|
||||
let fees = await exchange.fetchFees()
|
||||
log('fees'.green, fees)
|
||||
|
||||
// my trades
|
||||
let myTrades = await exchange.fetchMyTrades('BTC/USD', undefined, 5)
|
||||
log('myTrades'.green, asTable(myTrades))
|
||||
|
||||
// user transactions
|
||||
let transactions = await exchange.fetchTransactions()
|
||||
log('Transactions'.green, asTable(transactions))
|
||||
|
||||
// ledger
|
||||
let ledger = await exchange.fetchLedger()
|
||||
log('Ledger'.green, asTable(ledger))
|
||||
|
||||
// deposits
|
||||
let deposits = await exchange.fetchDeposits()
|
||||
log('Deposits'.green, asTable(deposits))
|
||||
|
||||
// create new limit order
|
||||
let newOrder = await exchange.createOrder('BTC/USD', 'limit', 'buy', 0.01, 8000)
|
||||
console.log('New limit order'.green, newOrder);
|
||||
|
||||
// open orders
|
||||
let openOrders = await exchange.fetchOpenOrders()
|
||||
log('Open orders'.green, asTable(openOrders))
|
||||
|
||||
// order data
|
||||
let orderData = await exchange.fetchOrder(newOrder.id)
|
||||
console.log('Order data'.green, orderData);
|
||||
|
||||
// cancel order
|
||||
let canceledOrder = await exchange.cancelOrder(newOrder.id)
|
||||
console.log('Canceled order'.green, canceledOrder);
|
||||
|
||||
// create market order
|
||||
let marketOrder = await exchange.createOrder('BTC/USD', 'market', 'buy', 0.01)
|
||||
console.log('New market order'.green, marketOrder);
|
||||
|
||||
// open orders
|
||||
let secondOpenOrders = await exchange.fetchOpenOrders()
|
||||
log('Open orders'.green, asTable(secondOpenOrders))
|
||||
|
||||
// deposit address
|
||||
let paxDeposit = await exchange.fetchDepositAddress("XLM")
|
||||
log('Pax deposit address'.green, paxDeposit)
|
||||
|
||||
// withdrawal
|
||||
let ethWithdraw = await exchange.withdraw("ETH", 0.01, "0x6c28cb9dd2f4e3bb6f56c822bc306f3b8a3e7c08")
|
||||
log('ETH withdrawal'.green, ethWithdraw)
|
||||
|
||||
// withdrawals
|
||||
let withdrawals = await exchange.fetchWithdrawals()
|
||||
log('Withdrawals'.green, asTable(withdrawals))
|
||||
|
||||
} catch (e) {
|
||||
|
||||
if (e instanceof ccxt.DDoSProtection || e.message.includes('ECONNRESET')) {
|
||||
log.bright.yellow('[DDoS Protection] ' + e.message)
|
||||
} else if (e instanceof ccxt.RequestTimeout) {
|
||||
log.bright.yellow('[Request Timeout] ' + e.message)
|
||||
} else if (e instanceof ccxt.AuthenticationError) {
|
||||
log.bright.yellow('[Authentication Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeNotAvailable) {
|
||||
log.bright.yellow('[Exchange Not Available Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
log.bright.yellow('[Exchange Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.NetworkError) {
|
||||
log.bright.yellow('[Network Error] ' + e.message)
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
})()
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
- [Bitstamp Public Api](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import log from 'ololog';
|
||||
import asTable from 'as-table';
|
||||
|
||||
|
||||
const table = asTable.configure ({ delimiter: ' | ' }), id = 'bitstamp', exchange = new ccxt[id] ({ enableRateLimit: true }), symbol = 'BTC/USD';(async function main () {
|
||||
|
||||
// Markets data
|
||||
const markets = await exchange.fetchMarkets ()
|
||||
console.log('Total number of markets: ', Object.keys(markets).length);
|
||||
|
||||
// Currencies
|
||||
const currencies = await exchange.fetchCurrencies ()
|
||||
console.log('Currencies: ', JSON.stringify(currencies));
|
||||
|
||||
// Order book data
|
||||
const orderbook = await exchange.fetchOrderBook (symbol)
|
||||
console.log ('Order book ', symbol, orderbook.asks[0], orderbook.bids[0])
|
||||
|
||||
// Ticker
|
||||
const ticker = await exchange.fetchTicker (symbol)
|
||||
console.log ('Ticker ', symbol, " bid ", ticker.bid, " ask ", ticker.ask)
|
||||
|
||||
// Trades
|
||||
const response = await exchange.fetchTrades (symbol, null, 10)
|
||||
log (table (response))
|
||||
|
||||
// OHLC data
|
||||
const candles = await exchange.fetchOHLCV (symbol, '1m', undefined, 10);
|
||||
const first = candles[0]
|
||||
const last = candles[candles.length - 1]
|
||||
console.log (
|
||||
'Fetched', candles.length, symbol, 'candles',
|
||||
'from', exchange.iso8601 (first[0]),
|
||||
'to', exchange.iso8601 (last[0])
|
||||
)
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
- [Bittrex Balance](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
import ansicolor from 'ansicolor';
|
||||
import ololog from 'ololog'
|
||||
|
||||
const log = ololog.configure ({ locate: false })
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms))
|
||||
|
||||
;(async () => {
|
||||
|
||||
// instantiate the exchange
|
||||
let exchange = new ccxt.bittrex ({
|
||||
"apiKey": "471b47a06c384e81b24072e9a8739064",
|
||||
"secret": "694025686e9445589787e8ca212b4cff",
|
||||
})
|
||||
|
||||
|
||||
try {
|
||||
|
||||
// fetch account balance from the exchange
|
||||
let balance = await exchange.fetchBalance ()
|
||||
|
||||
// output the result
|
||||
log (exchange.name.green, 'balance', balance)
|
||||
|
||||
} catch (e) {
|
||||
|
||||
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
|
||||
log.bright.yellow ('[DDoS Protection] ' + e.message)
|
||||
} else if (e instanceof ccxt.RequestTimeout) {
|
||||
log.bright.yellow ('[Request Timeout] ' + e.message)
|
||||
} else if (e instanceof ccxt.AuthenticationError) {
|
||||
log.bright.yellow ('[Authentication Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeNotAvailable) {
|
||||
log.bright.yellow ('[Exchange Not Available Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
log.bright.yellow ('[Exchange Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.NetworkError) {
|
||||
log.bright.yellow ('[Network Error] ' + e.message)
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
- [Bittrex Fetch Closed Orders History](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import ololog from 'ololog';
|
||||
import asTable from 'as-table';
|
||||
|
||||
|
||||
const { noLocate } = ololog;
|
||||
const log = noLocate;
|
||||
|
||||
const exchange = new ccxt.bittrex ({
|
||||
'enableRateLimit': true,
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_API_SECRET',
|
||||
});(async () => {
|
||||
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
const symbol = 'ETH/BTC'
|
||||
, market = exchange.markets[symbol]
|
||||
, startingDate = '2017-01-01T00:00:00'
|
||||
, now = exchange.milliseconds ()
|
||||
|
||||
log.bright.green ('\nFetching history for:', symbol, '\n')
|
||||
|
||||
let allOrders = []
|
||||
let since = exchange.parse8601 (startingDate)
|
||||
|
||||
while (since < now) {
|
||||
|
||||
try {
|
||||
|
||||
log.bright.blue ('Fetching history for', symbol, 'since', exchange.iso8601 (since))
|
||||
const orders = await exchange.fetchClosedOrders (symbol, since)
|
||||
log.green.dim ('Fetched', orders.length, 'orders')
|
||||
|
||||
allOrders = allOrders.concat (orders)
|
||||
|
||||
if (orders.length) {
|
||||
|
||||
const lastOrder = orders[orders.length - 1]
|
||||
since = lastOrder['timestamp'] + 1
|
||||
|
||||
} else {
|
||||
|
||||
break // no more orders left for this symbol, move to next one
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
|
||||
log.red.unlimited (e)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// omit the following keys for a compact table output
|
||||
// otherwise it won't fit into the screen width
|
||||
const omittedKeys = [
|
||||
'info',
|
||||
'timestamp',
|
||||
'lastTradeTimestamp',
|
||||
'fee',
|
||||
]
|
||||
|
||||
log.yellow (asTable (allOrders.map (order => exchange.omit (order, omittedKeys))))
|
||||
log.green ('Fetched', allOrders.length, symbol, 'orders in total')
|
||||
|
||||
// do whatever you want to do with them, calculate profit loss, etc...
|
||||
|
||||
}) ()
|
||||
|
||||
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
- [Blockchaincom Withdrawal](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
"use strict";
|
||||
|
||||
const ccxt = require('../../ccxt.js')
|
||||
const asTable = require('as-table')
|
||||
const log = require('ololog').configure({ locate: false })
|
||||
|
||||
|
||||
const exchange = new ccxt.blockchaincom({
|
||||
'secret': 'YOUR_API_SECRET',
|
||||
})
|
||||
|
||||
// blockchaincom specific internal beneficiary id
|
||||
const address = 'BENEFICIARY_ID';
|
||||
|
||||
|
||||
(async () => {
|
||||
|
||||
const markets = await exchange.loadMarkets ()
|
||||
|
||||
try {
|
||||
const code = 'USDT'
|
||||
const amount = 5
|
||||
|
||||
// fetch withdrawal beneficiary ids
|
||||
const whiteList = await exchange.privateGetWhitelistCurrency({'currency': code})
|
||||
log('Withdrawl Whitelist', whiteList)
|
||||
//
|
||||
// [
|
||||
// {
|
||||
// "whitelistId":"adcd73fb-9ba6-41o7-8c0d-7013482cb88f", // unique id for each beneficiary, to be passed in as address into withdraw ()
|
||||
// "name":"John Doe",
|
||||
// "currency":"USDT"
|
||||
// }
|
||||
// ]
|
||||
//
|
||||
|
||||
// withdrawal
|
||||
let withdrawal = await exchange.withdraw(code, amount, address, undefined);
|
||||
log('Withdrawal', withdrawal)
|
||||
|
||||
} catch (e) {
|
||||
if (e instanceof ccxt.DDoSProtection || e.message.includes('ECONNRESET')) {
|
||||
log('[DDoS Protection] ' + e.message)
|
||||
} else if (e instanceof ccxt.RequestTimeout) {
|
||||
log('[Request Timeout] ' + e.message)
|
||||
} else if (e instanceof ccxt.AuthenticationError) {
|
||||
log('[Authentication Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeNotAvailable) {
|
||||
log('[Exchange Not Available Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
log('[Exchange Error] ' + e.message)
|
||||
} else if (e instanceof ccxt.NetworkError) {
|
||||
log('[Network Error] ' + e.message)
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
})()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,54 @@
|
||||
- [Build Ohlcv Bars](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
// Bulding OHLCV array from trades (executions) data is a bit tricky. For example, if you want to build 100 ohlcv bars of 1-minute timeframe, then you have to fetch the 100 minutes of trading data. So, higher timeframe bars require more trading data (i.e. building 100 bars of 1-day timeframe OHLCV would require massive amount of trading data, which might not be desirable for user, because of data-usage rate limits)
|
||||
async function example_with_fetch_trades() {
|
||||
const exch = new ccxt.binance({});
|
||||
const timeframe = '1m';
|
||||
const symbol = 'OGN/USDT';
|
||||
const since = exch.milliseconds() - 1000 * 60 * 30; // last 30 mins
|
||||
const limit = 1000;
|
||||
const trades = await exch.fetchTrades(symbol, since, limit);
|
||||
const generatedBars = exch.buildOHLCVC(trades, timeframe, since, limit);
|
||||
// you can ignore 6th index ("count" field) from ohlcv entries, which is not part of OHLCV standard structure and is just added internally by `buildOHLCVC` method
|
||||
console.log('[REST] Constructed', generatedBars.length, 'bars from trades: ', generatedBars);
|
||||
}
|
||||
async function example_with_watch_trades() {
|
||||
const exch = new ccxt.pro.binance({});
|
||||
const timeframe = '1m';
|
||||
const symbol = 'DOGE/USDT';
|
||||
const limit = 1000;
|
||||
const since = exch.milliseconds() - 10 * 60 * 1000 * 1000; // last 10 hrs
|
||||
let collectedTrades = [];
|
||||
const collectedBars = [];
|
||||
while (true) {
|
||||
const wsTrades = await exch.watchTrades(symbol, since, limit, {});
|
||||
collectedTrades = collectedTrades.concat(wsTrades);
|
||||
const generatedBars = exch.buildOHLCVC(collectedTrades, timeframe, since, limit);
|
||||
// Note: first bar would be partially constructed bar and its 'open' & 'high' & 'low' prices (except 'close' price) would probably have different values compared to real bar on chart, because the first obtained trade timestamp might be somewhere in the middle of timeframe period, so the pre-period would be missing because we would not have trades data. To fix that, you can get older data with `fetchTrades` to fill up bars till start bar.
|
||||
for (let i = 0; i < generatedBars.length; i++) {
|
||||
const bar = generatedBars[i];
|
||||
const barTimestamp = bar[0];
|
||||
const collectedBarsLength = collectedBars.length;
|
||||
const lastCollectedBarTimestamp = collectedBarsLength > 0 ? collectedBars[collectedBarsLength - 1][0] : 0;
|
||||
if (barTimestamp === lastCollectedBarTimestamp) {
|
||||
// if timestamps are same, just updarte the last bar
|
||||
collectedBars[collectedBarsLength - 1] = bar;
|
||||
}
|
||||
else if (barTimestamp > lastCollectedBarTimestamp) {
|
||||
collectedBars.push(bar);
|
||||
// remove the trades from saved array, which were till last collected bar's open timestamp
|
||||
collectedTrades = exch.filterBySinceLimit(collectedTrades, barTimestamp);
|
||||
}
|
||||
}
|
||||
// Note: first bar would carry incomplete values, please read comment in "buildOHLCVCFromWatchTrades" method definition for further explanation
|
||||
console.log('[WS] Constructed', collectedBars.length, 'bars from', symbol, 'trades: ', collectedBars);
|
||||
}
|
||||
}
|
||||
await example_with_fetch_trades();
|
||||
await example_with_watch_trades();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
- [Builtin Rate Limiting Rest Poller](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import log from 'ololog';
|
||||
import { nice as ansi } from 'ansicolor';
|
||||
import asTable from 'as-table';
|
||||
|
||||
const exchange = new ccxt.coinbasepro ()
|
||||
const repeat = 100
|
||||
|
||||
async function test (symbol) {
|
||||
|
||||
for (let i = 0; i < repeat; i++) {
|
||||
let ticker = await exchange.fetchTicker (symbol)
|
||||
log (exchange.id.green, exchange.iso8601 (exchange.milliseconds ()), ticker['datetime'], symbol.green, ticker['last'])
|
||||
}
|
||||
}
|
||||
|
||||
const concurrent = [
|
||||
test ('BTC/USD'),
|
||||
test ('ETH/BTC'),
|
||||
test ('ETH/USD')
|
||||
]
|
||||
|
||||
Promise.all (concurrent)
|
||||
```
|
||||
@@ -0,0 +1,67 @@
|
||||
- [Bybit Trailing](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
'use strict';
|
||||
|
||||
const ccxt = require ('../../ccxt');
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
const exchange = new ccxt.bybit({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_API_KEY',
|
||||
})
|
||||
|
||||
// exchange.set_sandbox_mode(true) // enable sandbox mode
|
||||
|
||||
// Example 1 :: Swap : open position and set trailing stop and close it
|
||||
async function example1 () {
|
||||
exchange['options']['defaultType'] = 'swap'; // very important set swap as default type
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
const symbol = 'LTC/USDT:USDT';
|
||||
const market = exchange.market(symbol);
|
||||
|
||||
// fetch swap balance
|
||||
const balance = await exchange.fetchBalance ();
|
||||
console.log (balance)
|
||||
|
||||
// create order and open position
|
||||
const type = 'market';
|
||||
const side = 'buy';
|
||||
const amount = 0.1
|
||||
const price = undefined;
|
||||
const createOrder = await exchange.createOrder (symbol, type, side, amount, price);
|
||||
console.log ('Created order id:', createOrder['id'])
|
||||
|
||||
// set trailing stop
|
||||
const rawSide = 'Buy'; // or 'Sell'
|
||||
const trailing_stop = 30; // YOUR TRAILING STOP HERE
|
||||
const trailingParams = {
|
||||
'symbol': market['id'],
|
||||
'side': rawSide,
|
||||
'trailing_stop': trailing_stop
|
||||
}
|
||||
const trailing_response = await exchange.privatePostPrivateLinearPositionTradingStop (trailingParams);
|
||||
console.log(trailing_response)
|
||||
|
||||
// check opened position
|
||||
const symbols = [ symbol ];
|
||||
const positions = await exchange.fetchPositions (symbols);
|
||||
console.log (positions)
|
||||
|
||||
// Close position by issuing a order in the opposite direction
|
||||
const params = {
|
||||
'reduce_only': true
|
||||
}
|
||||
const closePositionOrder = await exchange.createOrder (symbol, type, side, amount, price, params);
|
||||
console.log (closePositionOrder);
|
||||
}
|
||||
|
||||
async function main () {
|
||||
await example1 ();
|
||||
}
|
||||
|
||||
main ();
|
||||
```
|
||||
@@ -0,0 +1,159 @@
|
||||
- [Bybit Updated](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
'use strict';
|
||||
|
||||
const ccxt = require ('../../dist/cjs/ccxt.js');
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
const exchange = new ccxt.bybit ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET_KEY',
|
||||
})
|
||||
|
||||
// Example 1: Spot : fetch balance, create order, cancel it and check canceled orders
|
||||
async function example1 () {
|
||||
exchange['options']['defaultType'] = 'spot'; // very important set spot as default type
|
||||
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
// fetch spot balance
|
||||
const balance = await exchange.fetchBalance ();
|
||||
console.log (balance)
|
||||
|
||||
// create order
|
||||
const symbol = 'LTC/USDT';
|
||||
const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', 50, 0.1);
|
||||
console.log ('Created order id:', createOrder['id'])
|
||||
|
||||
// cancel order
|
||||
const cancelOrder = await exchange.cancelOrder (createOrder['id'], symbol);
|
||||
|
||||
// Check canceled orders (bybit does not have a single endpoint to check orders
|
||||
// we have to choose whether to check open or closed orders and call fetchOpenOrders
|
||||
// or fetchClosedOrders respectively
|
||||
const canceledOrders = await exchange.fetchClosedOrders (symbol);
|
||||
console.log (canceledOrders);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
|
||||
// Example 2 :: Swap : fetch balance, open a position and close it
|
||||
async function example2 () {
|
||||
exchange['options']['defaultType'] = 'swap'; // very important set swap as default type
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
// fetch swap balance
|
||||
const balance = await exchange.fetchBalance ();
|
||||
console.log (balance)
|
||||
|
||||
// create order and open position
|
||||
const symbol = 'LTC/USDT:USDT';
|
||||
const createOrder = await exchange.createOrder (symbol, 'market', 'buy', 0.1);
|
||||
console.log ('Created order id:', createOrder['id'])
|
||||
|
||||
// check opened position
|
||||
const symbols = [ symbol ];
|
||||
const positions = await exchange.fetchPositions (symbols);
|
||||
console.log (positions)
|
||||
|
||||
// Close position by issuing a order in the opposite direction
|
||||
const params = {
|
||||
'reduce_only': true
|
||||
}
|
||||
const closePositionOrder = await exchange.createOrder (symbol, 'market', 'sell', 0.1, undefined, params);
|
||||
console.log (closePositionOrder);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
|
||||
// Example 3 :: USDC Swap : fetch balance, open a position and close it
|
||||
async function example3 () {
|
||||
exchange['options']['defaultType'] = 'swap'; // very important set swap as default type
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
// fetch USDC swap balance
|
||||
// when no symbol is available we can show our intent
|
||||
// of using USDC endpoints by either using defaultSettle in options or
|
||||
// settle in params
|
||||
// Using Options: exchange['options']['defaultSettle'] = 'USDC';
|
||||
// Using params:
|
||||
const balanceParams = {
|
||||
'settle': 'USDC'
|
||||
}
|
||||
const balance = await exchange.fetchBalance (balanceParams);
|
||||
console.log (balance)
|
||||
|
||||
// create order and open position
|
||||
// taking into consideration that USDC markets do not support
|
||||
// market orders
|
||||
const symbol = 'BTC/USD:USDC';
|
||||
const amount = 0.1;
|
||||
const price = 29940 // adjust this accordingly
|
||||
const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', amount, price);
|
||||
console.log ('Created order id:', createOrder['id'])
|
||||
|
||||
// check if the order was filled and the position opened
|
||||
const symbols = [ symbol ];
|
||||
const positions = await exchange.fetchPositions (symbols);
|
||||
console.log (positions)
|
||||
|
||||
// close position (assuming it was already opened) by issuing an order in the opposite direction
|
||||
const params = {
|
||||
'reduce_only': true
|
||||
}
|
||||
const closePositionOrder = await exchange.createOrder (symbol, 'limit', 'sell', amount, price, params);
|
||||
console.log (closePositionOrder);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
|
||||
// Example 4 :: Future : fetch balance, create stop-order and check open stop-orders
|
||||
async function example4 () {
|
||||
exchange['options']['defaultType'] = 'future'; // very important set future as default type
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
// fetch future balance
|
||||
const balance = await exchange.fetchBalance ();
|
||||
console.log (balance)
|
||||
|
||||
// create stop-order
|
||||
const symbol = 'ETH/USD:ETH-220930';
|
||||
const amount = 10; // in USD for inverse futures
|
||||
const price = 1200;
|
||||
const side = 'buy';
|
||||
const type = 'limit';
|
||||
const stopOrderParams = {
|
||||
'position_idx': 0, // 0 One-Way Mode, 1 Buy-side, 2 Sell-side, default = 0
|
||||
'stopPrice': 1000, // mandatory for stop orders
|
||||
'basePrice': 1100 // mandatory for stop orders
|
||||
}
|
||||
const stopOrder = await exchange.createOrder (symbol, type, side, amount, price, stopOrderParams);
|
||||
console.log ('Created order id:', stopOrder['id'])
|
||||
|
||||
// check opened stop-order
|
||||
const openOrderParams = {
|
||||
'stop': true
|
||||
}
|
||||
const openOrders = await exchange.fetchOpenOrders (symbol, undefined, undefined, openOrderParams);
|
||||
console.log (openOrders)
|
||||
|
||||
// Cancell open stop-order
|
||||
const cancelOrder = await exchange.cancelOrder (stopOrder['id'], symbol, openOrderParams);
|
||||
console.log (cancelOrder);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
|
||||
async function main () {
|
||||
await example1 ();
|
||||
await example2 ();
|
||||
await example3 ();
|
||||
await example4 ();
|
||||
|
||||
}
|
||||
|
||||
main ();
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
- [Coinbase Fetch All Balances](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
"use strict";
|
||||
|
||||
const ccxt = require ('../../js/ccxt.js')
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
async function fetchAllBalances (exchange) {
|
||||
const params = {}
|
||||
let balance = {}
|
||||
while (true) {
|
||||
const response = await exchange.fetchBalance (params)
|
||||
balance = exchange.extend (balance, response)
|
||||
const info = exchange.safeValue (response, 'info', {})
|
||||
const pagination = exchange.safeValue (info, 'pagination', {})
|
||||
const startingAfter = exchange.safeString (pagination, 'next_starting_after')
|
||||
if (startingAfter !== undefined) {
|
||||
params['starting_after'] = startingAfter
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return balance
|
||||
}
|
||||
|
||||
async function main () {
|
||||
const exchange = new ccxt.coinbase ({
|
||||
// Value is the "name" field in the api_key.json file Coinbase will offer for download
|
||||
apiKey: 'organizations/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/apiKeys/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
|
||||
// This is the "privateKey" field in that JSON file
|
||||
secret: '-----BEGIN EC PRIVATE KEY-----\nxxx...xxx==\n-----END EC PRIVATE KEY-----',
|
||||
})
|
||||
const markets = await exchange.loadMarkets ()
|
||||
// coinbase.verbose = true // uncomment for debugging purposes if necessary
|
||||
const balance = await fetchAllBalances (exchange)
|
||||
console.log (balance)
|
||||
}
|
||||
|
||||
main ()
|
||||
|
||||
```
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
- [Coinex Fetch All Deposit Addresses Using Fetchdepositaddress](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
"use strict";
|
||||
|
||||
const ccxt = require ('../../ccxt')
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
// https://github.com/ccxt/ccxt/issues/15405
|
||||
|
||||
async function main () {
|
||||
|
||||
const exchange = new ccxt.coinex ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_API_SECRET',
|
||||
});
|
||||
|
||||
// exchange.verbose = true // uncomment for debugging purposes
|
||||
|
||||
await exchange.loadMarkets ();
|
||||
const addresses = {};
|
||||
const promises = [];
|
||||
|
||||
async function fetchDepositAddress (currency, network) {
|
||||
try {
|
||||
const response = await exchange.fetchDepositAddress(currency, { 'network': network });
|
||||
addresses[currency][network] = response['address']
|
||||
}
|
||||
catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
const currencies = Object.keys (exchange.currencies);
|
||||
|
||||
for (const currency of currencies) {
|
||||
const networks = Object.keys (exchange.currencies[currency]['networks']);
|
||||
for (const network of networks) {
|
||||
addresses[currency] = {};
|
||||
promises.push (fetchDepositAddress (currency, network));
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all (promises);
|
||||
|
||||
console.log (addresses)
|
||||
};
|
||||
|
||||
main ();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,80 @@
|
||||
- [Coinex Futures](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
'use strict';
|
||||
|
||||
const ccxt = require ('../../ccxt');
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
let exchange = new ccxt.coinex({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET_KEY',
|
||||
})
|
||||
|
||||
// Example 1 :: Swap : fetch balance, create a limit swap order with leverage
|
||||
async function example1 () {
|
||||
exchange['options']['defaultType'] = 'swap';
|
||||
exchange.options['defaultMarginMode'] = 'cross' // or isolated
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
const symbol = 'ADA/USDT:USDT';
|
||||
|
||||
// fetchBalance
|
||||
const balance = await exchange.fetchBalance ();
|
||||
console.log (balance)
|
||||
|
||||
// set the desired leverage (has to be made before placing the order and for a specific symbol)
|
||||
const leverage = 8;
|
||||
const leverage_response = await exchange.setLeverage(leverage, symbol)
|
||||
|
||||
// create limit order
|
||||
const amount = 50;
|
||||
const price = 0.3 // adjust this accordingly
|
||||
const createOrder = await exchange.createOrder (symbol, 'limit', 'buy', amount, price);
|
||||
console.log ('Created order id:', createOrder['id'])
|
||||
}
|
||||
|
||||
// Example 2 :: Swap :: open a position and close it
|
||||
async function example2 () {
|
||||
exchange['options']['defaultType'] = 'swap';
|
||||
exchange.options['defaultMarginMode'] = 'cross' // or isolated
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
const symbol = 'ADA/USDT:USDT';
|
||||
|
||||
// fetchBalance
|
||||
const balance = await exchange.fetchBalance ();
|
||||
console.log (balance)
|
||||
|
||||
// set the desired leverage (has to be made before placing the order and for a specific symbol)
|
||||
const leverage = 8;
|
||||
const leverage_response = await exchange.setLeverage(leverage, symbol)
|
||||
|
||||
// create market order and open position
|
||||
const amount = 50;
|
||||
const createOrder = await exchange.createOrder (symbol, 'market', 'buy', amount);
|
||||
console.log ('Created order id:', createOrder['id'])
|
||||
|
||||
// check if the order was filled and the position opened
|
||||
const position = await exchange.fetchPositions (symbol);
|
||||
console.log (position)
|
||||
|
||||
// close position (assuming it was already opened) by issuing an order in the opposite direction
|
||||
const params = {
|
||||
'reduce_only': true
|
||||
}
|
||||
const closePositionOrder = await exchange.createOrder (symbol, 'market', 'sell', amount, undefined, params);
|
||||
console.log (closePositionOrder);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
|
||||
async function main () {
|
||||
await example1 ();
|
||||
await example2 ();
|
||||
}
|
||||
|
||||
main ();
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
- [Coinone Fetch Tickers](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import { nice as ansi } from 'ansicolor';
|
||||
import ololog from 'ololog';
|
||||
import asTable from 'as-table';
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
const { noLocate } = ololog;
|
||||
const log = noLocate;
|
||||
|
||||
const table = asTable.configure ({
|
||||
delimiter: ' | '.dim,
|
||||
right: true,
|
||||
});
|
||||
|
||||
const exchange = new ccxt.coinone ({
|
||||
'verbose': process.argv.includes ('--verbose'),
|
||||
})
|
||||
|
||||
let printTickersAsTable = function (exchange, tickers) {
|
||||
log (exchange.id.green, exchange.iso8601 (exchange.milliseconds ()))
|
||||
log ('Fetched', Object.values (tickers).length.toString ().green, 'tickers:')
|
||||
log (table (ccxt.sortBy (Object.values (tickers), 'symbol', false)))
|
||||
}
|
||||
|
||||
async function fetchAllAndPrint () {
|
||||
const tickers = await exchange.fetchTickers ()
|
||||
log ('---------------------------------------- fetchTickers ----------------------------------------')
|
||||
printTickersAsTable (exchange, tickers)
|
||||
}
|
||||
|
||||
async function fetchOneByOneAndPrint () {
|
||||
const markets = await exchange.loadMarkets ()
|
||||
const symbols = Object.keys (markets)
|
||||
const tickers = []
|
||||
|
||||
log ('---------------------------------------- fetchTicker (one by one) ----------------------------------------')
|
||||
|
||||
for (let i = 0; i < symbols.length; i++) {
|
||||
const ticker = await exchange.fetchTicker (symbols[i])
|
||||
tickers.push (ticker)
|
||||
log (`${i+1} / ${symbols.length}`)
|
||||
log ('\u001b[1A'.repeat (2)) // cursor up
|
||||
}
|
||||
|
||||
printTickersAsTable (exchange, tickers)
|
||||
}
|
||||
|
||||
(async () => {
|
||||
await fetchAllAndPrint ()
|
||||
log ('\n')
|
||||
await fetchOneByOneAndPrint ()
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
- [Coinone Markets](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import log from 'ololog';
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
const exchange = new ccxt.coinone ({
|
||||
'verbose': process.argv.includes ('--verbose'),
|
||||
})
|
||||
|
||||
;(async function main () {
|
||||
|
||||
const markets = await exchange.loadMarkets ()
|
||||
log (markets)
|
||||
log ('\n' + exchange['name'] + ' supports ' + Object.keys (markets).length + ' pairs')
|
||||
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,42 @@
|
||||
- [Compare Two Exchanges Capabilities](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
async function example() {
|
||||
const prefix = '-';
|
||||
const exchange_1 = new ccxt.okx();
|
||||
const exchange_2 = new ccxt.htx();
|
||||
const keys_1 = Object.keys(exchange_1.has);
|
||||
const keys_2 = Object.keys(exchange_2.has);
|
||||
// check missing from exchange-1
|
||||
console.log('### checking missing functionalities from exchange-1:', exchange_1.id);
|
||||
for (let i = 0; i < keys_2.length; i++) {
|
||||
const key = keys_2[i];
|
||||
if (exchange_2.has[key]) {
|
||||
if (!keys_1.includes(key)) {
|
||||
console.log(prefix, key, 'does not exist in', exchange_1.id, 'as opposed to', exchange_2.id);
|
||||
}
|
||||
else if (exchange_2.has[key] !== exchange_1.has[key]) {
|
||||
console.log(prefix, key, '> ', exchange_1.id, ':', exchange_1.has[key], ',', exchange_2.id, ':', exchange_2.has[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// check missing from exchange-2
|
||||
console.log('### checking missing functionalities from exchange-2:', exchange_2.id);
|
||||
for (let i = 0; i < keys_1.length; i++) {
|
||||
const key = keys_1[i];
|
||||
if (exchange_1.has[key]) {
|
||||
if (!keys_2.includes(key)) {
|
||||
console.log(prefix, key, 'does not exist in', exchange_2.id, 'as opposed to', exchange_1.id);
|
||||
}
|
||||
else if (exchange_1.has[key] !== exchange_2.has[key]) {
|
||||
console.log(prefix, key, '> ', exchange_2.id, ':', exchange_2.has[key], ',', exchange_1.id, ':', exchange_1.has[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
- [Cors Proxy](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
// JavaScript CORS Proxy
|
||||
// Save this in a file like cors.js and run with `node cors [port]`
|
||||
// It will listen for your requests on the port you pass in command line or port 8080 by default
|
||||
let port = (process.argv.length > 2) ? parseInt (process.argv[2]) : 8080 // default
|
||||
require ('cors-anywhere').createServer ().listen (port, '0.0.0.0')
|
||||
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
- [Create Order Handle Errors](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
(async () => {
|
||||
|
||||
const exchange = new ccxt.bittrex ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET_KEY',
|
||||
'verbose': false, // set to true to see more debugging output
|
||||
'timeout': 60000,
|
||||
})
|
||||
|
||||
// try to load markets first, retry on request timeouts until it succeeds:
|
||||
|
||||
while (true) {
|
||||
|
||||
try {
|
||||
|
||||
await exchange.loadMarkets ();
|
||||
break;
|
||||
|
||||
} catch (e) {
|
||||
|
||||
if (e instanceof ccxt.RequestTimeout)
|
||||
console.log (exchange.iso8601 (Date.now ()), e.constructor.name, e.message)
|
||||
}
|
||||
}
|
||||
|
||||
const symbol = 'ETH/BTC'
|
||||
const orderType = 'limit'
|
||||
const side = 'sell'
|
||||
const amount = 0.321;
|
||||
const price = 0.123;
|
||||
|
||||
// try just one attempt to create an order
|
||||
|
||||
try {
|
||||
|
||||
const response = await exchange.createOrder (symbol, orderType, side, amount, price);
|
||||
console.log (response);
|
||||
console.log ('Succeeded');
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.log (exchange.iso8601 (Date.now ()), e.constructor.name, e.message)
|
||||
console.log ('Failed');
|
||||
|
||||
}
|
||||
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
- [Create Order Position With Takeprofit Stoploss](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
// @ts-nocheck
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
console.log('CCXT Version:', ccxt.version);
|
||||
// ------------------------------------------------------------------------------
|
||||
async function example() {
|
||||
// at this moment, only OKX support embedded stop-loss & take-profit orders in unified manner. other exchanges are being added actively and will be available soon.
|
||||
const exchange = new ccxt.okx({
|
||||
"apiKey": "YOUR_API_KEY",
|
||||
"secret": "YOUR_API_SECRET",
|
||||
"password": "YOUR_API_PASSWORD", // if exchange does not require password, comment out this line
|
||||
});
|
||||
const symbol = 'DOGE/USDT:USDT';
|
||||
const side = 'buy'; // 'buy' | 'sell'
|
||||
const order_type = 'limit'; // 'market' | 'limit'
|
||||
const amount = 1; // how many contracts (see `market(symbol).contractSize` to find out coin portion per one contract)
|
||||
await exchange.loadMarkets();
|
||||
const market = exchange.market(symbol);
|
||||
const ticker = await exchange.fetchTicker(symbol);
|
||||
const last_price = ticker['last'];
|
||||
const ask_price = ticker['ask'];
|
||||
const bid_price = ticker['bid'];
|
||||
// if order_type is 'market', then price is not needed
|
||||
let price = undefined;
|
||||
// if order_type is 'limit', then set a price at your desired level
|
||||
if (order_type === 'limit') {
|
||||
price = (side === 'buy') ? bid_price * 0.95 : ask_price * 1.05; // i.e. 5% from current price
|
||||
}
|
||||
// set trigger price for stop-loss/take-profit to 2% from current price
|
||||
// (note, across different exchanges "trigger" price can be also mentioned with different synonyms, like "activation price", "stop price", "conditional price", etc. )
|
||||
const stop_loss_trigger_price = (order_type === 'market' ? last_price : price) * (side === 'buy' ? 0.98 : 1.02);
|
||||
const take_profit_trigger_price = (order_type === 'market' ? last_price : price) * (side === 'buy' ? 1.02 : 0.98);
|
||||
// when symbol's price reaches your predefined "trigger price", stop-loss order would be activated as a "market order". but if you want it to be activated as a "limit order", then set a 'price' parameter for it
|
||||
const params = {
|
||||
'stopLoss': {
|
||||
'triggerPrice': stop_loss_trigger_price,
|
||||
// set a 'price' to act as limit order, otherwise remove it for a market order
|
||||
'price': stop_loss_trigger_price * 0.98,
|
||||
},
|
||||
'takeProfit': {
|
||||
'triggerPrice': take_profit_trigger_price,
|
||||
// set a 'price' to act as limit order, otherwise remove it for a market order
|
||||
'price': take_profit_trigger_price * 0.98,
|
||||
},
|
||||
// note that some exchanges might require some exchange specific parameter when opening a position, i.e.:
|
||||
// 'posSide': 'long', // for phemex hedge-mode api
|
||||
};
|
||||
const position_amount = market['contractSize'] * amount;
|
||||
const position_value = position_amount * last_price;
|
||||
// log
|
||||
console.log('Going to open a position', 'for', amount, 'contracts worth', position_amount, market['base'], '~', position_value, market['settle'], 'using', side, order_type, 'order (', (order_type === 'limit' ? exchange.priceToPrecision(symbol, price) : ''), '), using the following params:');
|
||||
console.log(params);
|
||||
console.log('-----------------------------------------------------------------------');
|
||||
// exchange.verbose = True // uncomment for debugging purposes if necessary
|
||||
try {
|
||||
const created_order = await exchange.createOrder(symbol, order_type, side, amount, price, params);
|
||||
console.log("Created an order", created_order);
|
||||
// Fetch all your open orders for this symbol
|
||||
// - use 'fetchOpenOrders' or 'fetchOrders' and filter with 'open' status
|
||||
// - note, that some exchanges might return one order object with embedded stoploss/takeprofit fields, while other exchanges might have separate stoploss/takeprofit order objects
|
||||
const all_open_orders = await exchange.fetchOpenOrders(symbol);
|
||||
console.log("Fetched all your orders for this symbol", all_open_orders);
|
||||
// To cancel a limit order, use "exchange.cancel_order(created_order['id'], symbol)""
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e.toString());
|
||||
}
|
||||
}
|
||||
await example();
|
||||
// NOTES:
|
||||
// - Sometimes you might experience, when their stop-loss/take-profit order might not become activated, even though on chart the price had crossed that "trigger-price" order was not executed . That happens because some exchange might be using mark-price (instead of last-price) as a reference-price, so that mark-price might reach your trigger-price and it would activate your SL/TP order (even though on your symbol's chart you are viewing the "last-price" by default, which could have different movements than the mark-price).
|
||||
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
- [Create Order With Retry](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
const tryToCreateOrder = async function (exchange, symbol, type, side, amount, price, params) {
|
||||
|
||||
try {
|
||||
|
||||
const order = await exchange.createOrder (symbol, type, side, amount, price, params)
|
||||
return order
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.log (e.constructor.name, e.message)
|
||||
|
||||
if (e instanceof ccxt.NetworkError) {
|
||||
|
||||
// retry on networking errors
|
||||
return false
|
||||
|
||||
} else {
|
||||
|
||||
throw e // break on all other exceptions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
const exchange = new ccxt.bytetrade ({
|
||||
'apiKey': 'classic123', // edit here
|
||||
'secret': 'ebcefff7de475ffe15e864ca3e3e410edf7e94fffd1f9af34edf9434e2bfff1b', // edit here
|
||||
})
|
||||
|
||||
//
|
||||
// make a classic bytetrade account - one that is linked to an email or phone number
|
||||
// then click on your username in the top right and then export
|
||||
// you will get a file like this:
|
||||
//
|
||||
// future garage icon motion panda garage motion task science head garage notable
|
||||
// ebcefff7de475ffe15e864ca3e3e410edf7e94fffd1f9af34edf9434e2bfff1b
|
||||
// classic123
|
||||
//
|
||||
// the second line is your secret and the third line is your apiKey
|
||||
//
|
||||
|
||||
const symbol = 'XRP/USDT' // edit here
|
||||
const type = 'limit ' // edit here
|
||||
const side = 'buy' // edit here
|
||||
const amount = 10 // edit here
|
||||
const price = 1 // edit here
|
||||
const params = {} // edit here
|
||||
|
||||
;(async () => {
|
||||
let order = false
|
||||
while (true) {
|
||||
order = await tryToCreateOrder (exchange, symbol, type, side, amount, price, params)
|
||||
if (order !== false) {
|
||||
break
|
||||
}
|
||||
}
|
||||
console.log (order)
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
- [Create Order Ws Example](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
async function example() {
|
||||
const exchange = new ccxt.pro.binance({
|
||||
'apiKey': 'MY_API_KEY',
|
||||
'secret': 'MY_SECRET',
|
||||
});
|
||||
exchange.setSandboxMode(true);
|
||||
exchange.verbose = true; // uncomment for debugging purposes if necessary
|
||||
// load markets
|
||||
await exchange.loadMarkets();
|
||||
const symbol = 'ETH/USDT';
|
||||
const type = 'limit';
|
||||
const side = 'buy';
|
||||
const amount = 0.01;
|
||||
let price = 1000;
|
||||
let orders = [];
|
||||
for (let i = 1; i < 5; i++) {
|
||||
const response = await exchange.createOrderWs(symbol, type, side, amount, price);
|
||||
price += i;
|
||||
orders.push(response);
|
||||
}
|
||||
console.log(orders);
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
- [Create Orders Example](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
async function example() {
|
||||
const exchange = new ccxt.binance({
|
||||
'apiKey': 'MY_API_KEY',
|
||||
'secret': 'MY_SECRET',
|
||||
});
|
||||
exchange.setSandboxMode(true);
|
||||
await exchange.loadMarkets();
|
||||
exchange.verbose = true; // uncomment for debugging purposes if necessary
|
||||
const orders = await exchange.createOrders([
|
||||
{ 'symbol': 'LTC/USDT:USDT', 'type': 'limit', 'side': 'buy', 'amount': 10, 'price': 55 },
|
||||
{ 'symbol': 'ETH/USDT:USDT', 'type': 'market', 'side': 'buy', 'amount': 0.5 },
|
||||
]);
|
||||
console.log(orders);
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,42 @@
|
||||
- [Create Trailing Amount Order](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
async function example() {
|
||||
const exchange = new ccxt.bingx({
|
||||
'apiKey': 'MY_API_KEY',
|
||||
'secret': 'MY_SECRET',
|
||||
});
|
||||
// exchange.setSandboxMode (true);
|
||||
// exchange.verbose = true; // uncomment for debugging purposes if necessary
|
||||
await exchange.loadMarkets();
|
||||
const symbol = 'BTC/USDT:USDT';
|
||||
const order_type = 'market';
|
||||
const side = 'sell';
|
||||
const amount = 0.0001;
|
||||
const price = undefined;
|
||||
const reduceOnly = true;
|
||||
const trailingAmount = 100;
|
||||
// const trailingTriggerPrice = undefined; // not supported on all exchanges
|
||||
const params = {
|
||||
'reduceOnly': reduceOnly,
|
||||
'trailingAmount': trailingAmount,
|
||||
// 'trailingTriggerPrice': trailingTriggerPrice,
|
||||
};
|
||||
try {
|
||||
const create_order = await exchange.createOrder(symbol, order_type, side, amount, price, params);
|
||||
// Alternatively use the createTrailingAmountOrder method:
|
||||
// const create_order = await exchange.createTrailingAmountOrder (symbol, order_type, side, amount, price, trailingAmount, trailingTriggerPrice, {
|
||||
// 'reduceOnly': reduceOnly,
|
||||
// });
|
||||
console.log(create_order);
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e.toString());
|
||||
}
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,42 @@
|
||||
- [Create Trailing Percent Order](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
async function example() {
|
||||
const exchange = new ccxt.bingx({
|
||||
'apiKey': 'MY_API_KEY',
|
||||
'secret': 'MY_SECRET',
|
||||
});
|
||||
// exchange.setSandboxMode (true);
|
||||
// exchange.verbose = true; // uncomment for debugging purposes if necessary
|
||||
await exchange.loadMarkets();
|
||||
const symbol = 'BTC/USDT:USDT';
|
||||
const order_type = 'market';
|
||||
const side = 'sell';
|
||||
const amount = 0.0001;
|
||||
const price = undefined;
|
||||
const reduceOnly = true;
|
||||
const trailingPercent = 10;
|
||||
// const trailingTriggerPrice = undefined; // not supported on all exchanges
|
||||
const params = {
|
||||
'reduceOnly': reduceOnly,
|
||||
'trailingPercent': trailingPercent,
|
||||
// 'trailingTriggerPrice': trailingTriggerPrice,
|
||||
};
|
||||
try {
|
||||
const create_order = await exchange.createOrder(symbol, order_type, side, amount, price, params);
|
||||
// Alternatively use the createTrailingAmountOrder method:
|
||||
// const create_order = await exchange.createTrailingPercentOrder (symbol, order_type, side, amount, price, trailingPercent, trailingTriggerPrice, {
|
||||
// 'reduceOnly': reduceOnly,
|
||||
// });
|
||||
console.log(create_order);
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e.toString());
|
||||
}
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
- [Credentials](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
{
|
||||
"hitbtc": { "apiKey": "b6aad581670b30fb25d1c91cdbe8ca5c", "secret": "fa394ced37a488f9b5826a2d9ce39ae3" },
|
||||
"bitso": { "apiKey": "xZnHRmdlgJ", "secret": "e156bb7f7ab3a831afbc7a80f7866b9e" },
|
||||
"coincheck": { "apiKey": "dCyzY2T6w0DFhaco", "secret": "JpI0eMmxfa0tEpk3X-dNwyclSASJkl-S" }
|
||||
}
|
||||
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
- [Custom Proxy Agent For Js](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
// @ts-nocheck
|
||||
// to set custom "proxy-agent" for ccxt
|
||||
import ccxt from 'ccxt';
|
||||
import HttpProxyAgent from 'http-proxy-agent';
|
||||
import HttpsProxyAgent from 'https-proxy-agent';
|
||||
const proxy = 'http://1.2.3.4:5678';
|
||||
const httpAgent = new HttpProxyAgent(proxy);
|
||||
const httpsAgent = new HttpsProxyAgent(proxy);
|
||||
// then pass it through constructor
|
||||
const kraken = new ccxt.kraken({ agent: httpAgent /* or httpsAgent */ });
|
||||
// or set it later
|
||||
kraken.agent = agent;
|
||||
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
- [Custom Proxy Url](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
(async function main () {
|
||||
|
||||
const kraken1 = new ccxt.kraken ({
|
||||
proxy: function (url) {
|
||||
return 'https://example.com/?url=' + encodeURIComponent (url)
|
||||
},
|
||||
})
|
||||
|
||||
console.log (await kraken1.loadMarkets ())
|
||||
|
||||
const kraken2 = new ccxt.kraken ({
|
||||
proxy: function (url) {
|
||||
return 'https://cors-anywhere.herokuapp.com/' + url
|
||||
},
|
||||
})
|
||||
|
||||
console.log (await kraken2.loadMarkets ())
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
- [Delta Maintenance Margin Rate Max Leverage](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version);
|
||||
|
||||
function getMaxLeverage (market, positionSize) {
|
||||
/**
|
||||
* @description Equation taken from https://www.delta.exchange/contracts/
|
||||
* @param {object} market CCXT market
|
||||
* @param {float} positionSize The value of the position in quote currency
|
||||
* @returns The maximum leverage available for the market for the given position size
|
||||
*/
|
||||
const info = market['info'];
|
||||
const maxLeverageNotional = Number (info['max_leverage_notional']);
|
||||
const initialMarginScalingFactor = Number (info['initial_margin_scaling_factor']);
|
||||
let initialMargin = Number (info['initial_margin']);
|
||||
|
||||
if (positionSize <= maxLeverageNotional) {
|
||||
const initialMarginRatio = initialMargin / 100;
|
||||
return 1 / initialMarginRatio;
|
||||
} else {
|
||||
initialMargin = initialMargin + (initialMarginScalingFactor * (positionSize - maxLeverageNotional));
|
||||
const initialMarginRatio = initialMargin / 100;
|
||||
return 1 / initialMarginRatio;
|
||||
}
|
||||
}
|
||||
|
||||
function getMaintenanceMarginRate (market, positionSize) {
|
||||
/**
|
||||
* @description Equation taken from https://www.delta.exchange/contracts/
|
||||
* @param {object} market CCXT market
|
||||
* @param {float} positionSize The value of the position in quote currency
|
||||
* @returns The maintenance margin rate as a percentage for the market with the given position size
|
||||
*/
|
||||
const info = market['info'];
|
||||
const maxLeverageNotional = Number (info['max_leverage_notional']);
|
||||
const maintenanceMarginScalingFactor = Number (info['maintenance_margin_scaling_factor']);
|
||||
const maintenanceMargin = Number (info['maintenance_margin']);
|
||||
|
||||
if (positionSize <= maxLeverageNotional) {
|
||||
return maintenanceMargin;
|
||||
} else {
|
||||
return maintenanceMargin + (maintenanceMarginScalingFactor * (positionSize - maxLeverageNotional));
|
||||
}
|
||||
}
|
||||
|
||||
async function main () {
|
||||
|
||||
const exchange = new ccxt.delta();
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
const symbol = 'ADA/USDT:USDT';
|
||||
const market = exchange.market (symbol);
|
||||
|
||||
// Gets the maximum leverage and maintenance margin rate for a position worth 100,000 USDT on the ADA/USDT:USDT market
|
||||
const maxLeverage = getMaxLeverage(market, 100000);
|
||||
const maintenanceMarginRate = getMaintenanceMarginRate(market, 100000);
|
||||
console.log(maxLeverage, maintenanceMarginRate);
|
||||
}
|
||||
|
||||
main ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
- [Env Variables](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import ololog from 'ololog'
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
const log = ololog.configure.handleNodeErrors (), asTable = require("as-table").configure({ delimiter: " | " });
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
(async () => {
|
||||
|
||||
const exchange = new ccxt.coinbase ({
|
||||
verbose: process.argv.includes ('--verbose'),
|
||||
timeout: 60000,
|
||||
apiKey: process.env.KEY,
|
||||
secret: process.env.SECRET
|
||||
});
|
||||
|
||||
const balance = await exchange.fetchBalance ()
|
||||
log.green (balance)
|
||||
|
||||
})()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,94 @@
|
||||
- [Error Handling](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
const verbose = process.argv.includes ('--verbose');
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const printSupportedExchanges = () => console.log ('Supported exchanges:', ccxt.exchanges.join (', '))
|
||||
|
||||
const printUsage = () => {
|
||||
console.log ('Usage: node', process.argv[1], 'id'.green)
|
||||
printSupportedExchanges ()
|
||||
}
|
||||
|
||||
const run = async (id) => {
|
||||
|
||||
// check if the exchange is supported by ccxt
|
||||
const exchangeFound = ccxt.exchanges.indexOf (id) > -1
|
||||
|
||||
if (exchangeFound) {
|
||||
|
||||
console.log ('Instantiating', id, 'exchange')
|
||||
|
||||
// instantiate the exchange by id
|
||||
const exchange = new ccxt[id] ({ verbose })
|
||||
|
||||
// try to load markets and catch the errors if any
|
||||
try {
|
||||
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
} catch (e) {
|
||||
|
||||
if (e instanceof ccxt.NetworkError) {
|
||||
console.log (exchange.id, 'loadMarkets failed due to a network error:', e.message)
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
console.log (exchange.id, 'loadMarkets failed due to exchange error:', e.message)
|
||||
} else {
|
||||
console.log (exchange.id, 'loadMarkets failed with:', e.message)
|
||||
}
|
||||
|
||||
// rethrow the error "higher up" the call chain
|
||||
throw e
|
||||
}
|
||||
|
||||
// try to fetch a ticker and catch the errors if any
|
||||
try {
|
||||
|
||||
const symbol = 'ETH/BTC'
|
||||
const response = await exchange.fetchTicker (symbol)
|
||||
console.log (response)
|
||||
|
||||
} catch (e) {
|
||||
|
||||
if (e instanceof ccxt.NetworkError) {
|
||||
console.log (exchange.id, 'fetchTicker failed due to a network error:', e.message)
|
||||
} else if (e instanceof ccxt.ExchangeError) {
|
||||
console.log (exchange.id, 'fetchTicker failed due to exchange error:', e.message)
|
||||
} else {
|
||||
console.log (exchange.id, 'fetchTicker failed with:', e.message)
|
||||
}
|
||||
|
||||
// rethrow the error "higher up" the call chain
|
||||
throw e
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
console.log ('Exchange', id, 'not found')
|
||||
printSupportedExchanges ()
|
||||
}
|
||||
}
|
||||
|
||||
;(async function main () {
|
||||
|
||||
if (process.argv.length > 2) {
|
||||
|
||||
let id = process.argv[2]
|
||||
await run (id)
|
||||
|
||||
} else {
|
||||
|
||||
printUsage ()
|
||||
}
|
||||
|
||||
process.exit ()
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,141 @@
|
||||
- [Exchange Capabilities](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import ololog from 'ololog';
|
||||
import ansicolor from 'ansicolor';
|
||||
import asTable from 'as-table';
|
||||
|
||||
const { noLocate } = ololog;
|
||||
const log = noLocate;
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
|
||||
|
||||
const csv = process.argv.includes ('--csv'), delimiter = csv ? ',' : '|', asTableConfig = { delimiter: ' ' + delimiter + ' ', /* print: require ('string.ify').noPretty */ }
|
||||
|
||||
asTable.configure (asTableConfig);
|
||||
|
||||
const sortCertified = process.argv.includes ('--sort-certified') || process.argv.includes ('--certified')
|
||||
const exchangesArgument = process.argv.find (arg => arg.startsWith ('--exchanges='))
|
||||
const exchangesArgumentParts = exchangesArgument ? exchangesArgument.split ('=') : []
|
||||
const selectedExchanges = (exchangesArgumentParts.length > 1) ? exchangesArgumentParts[1].split (',') : []
|
||||
|
||||
console.log (ccxt.iso8601 (ccxt.milliseconds ()))
|
||||
console.log ('CCXT v' + ccxt.version)
|
||||
|
||||
async function main () {
|
||||
|
||||
let total = 0
|
||||
let notImplemented = 0
|
||||
let inexistentApi = 0
|
||||
let implemented = 0
|
||||
let emulated = 0
|
||||
|
||||
const exchangeNames = ccxt.exchanges
|
||||
let exchanges = exchangeNames.map (id => new ccxt[id] ())
|
||||
exchanges = exchanges.map (exchange => exchange.pro ? new ccxt.pro[exchange.id] () : exchange)
|
||||
if (sortCertified) {
|
||||
exchanges.sort((a, b) => {
|
||||
if (a.certified && !b.certified) {
|
||||
return -1;
|
||||
} else if (!a.certified && b.certified) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
const metainfo = ccxt.flatten (exchanges.map (exchange => Object.keys (exchange.has)))
|
||||
const reduced = metainfo.reduce ((previous, current) => {
|
||||
previous[current] = (previous[current] || 0) + 1
|
||||
return previous
|
||||
}, {})
|
||||
const unified = Object.entries (reduced).filter (([ _, count ]) => count > 1)
|
||||
const methods = unified.map (([ method, _ ]) => method).sort ()
|
||||
if (selectedExchanges.length > 0) {
|
||||
exchanges = exchanges.filter ((exchange) => selectedExchanges.includes(exchange.id))
|
||||
}
|
||||
const table = asTable (exchanges.map (exchange => {
|
||||
let result = {};
|
||||
const basics = [
|
||||
'CORS',
|
||||
'spot',
|
||||
'margin',
|
||||
'swap',
|
||||
'future',
|
||||
'option',
|
||||
];
|
||||
|
||||
ccxt.unique (basics.concat (methods)).forEach (key => {
|
||||
|
||||
total += 1
|
||||
|
||||
let coloredString = '';
|
||||
|
||||
const feature = exchange.has[key]
|
||||
const isFunction = (typeof exchange[key] === 'function')
|
||||
const isBasic = basics.includes (key)
|
||||
|
||||
if (feature === false) {
|
||||
// if explicitly set to 'false' in exchange.has (to exclude mistake, we check if it's undefined too)
|
||||
coloredString = exchange.id.red.dim
|
||||
inexistentApi += 1
|
||||
} else if (feature === 'emulated') {
|
||||
// if explicitly set to 'emulated' in exchange.has
|
||||
coloredString = exchange.id.yellow
|
||||
emulated += 1
|
||||
} else if (feature) {
|
||||
if (isBasic) {
|
||||
// if neither 'false' nor 'emulated', and if method exists
|
||||
coloredString = exchange.id.green
|
||||
implemented += 1
|
||||
} else {
|
||||
if (isFunction) {
|
||||
coloredString = exchange.id.green
|
||||
implemented += 1
|
||||
} else {
|
||||
// the feature is available in exchange.has and not implemented
|
||||
// this is an error
|
||||
coloredString = exchange.id.lightMagenta
|
||||
}
|
||||
}
|
||||
} else {
|
||||
coloredString = exchange.id.lightRed
|
||||
notImplemented += 1
|
||||
}
|
||||
|
||||
result[key] = coloredString
|
||||
})
|
||||
|
||||
return result
|
||||
}))
|
||||
|
||||
if (csv) {
|
||||
let lines = table.split ("\n")
|
||||
lines = lines.slice (0, 1).concat (lines.slice (2))
|
||||
log (lines.join ("\n"))
|
||||
} else {
|
||||
log (table)
|
||||
}
|
||||
|
||||
log ('Summary: ',
|
||||
ccxt.exchanges.length.toString (), 'exchanges; ',
|
||||
'Methods [' + total.toString () + ' total]: ',
|
||||
implemented.toString ().green, 'implemented,',
|
||||
emulated.toString ().yellow, 'emulated,',
|
||||
(inexistentApi.toString ().red.dim), 'inexistentApi,',
|
||||
(notImplemented.toString ().lightRed), 'notImplemented',
|
||||
)
|
||||
|
||||
log("\nMessy? Try piping to less (e.g. node script.js | less -S -R --header=3 )\n".red)
|
||||
|
||||
}
|
||||
|
||||
main ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
- [Exchanges By Volume](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
(async () => {
|
||||
|
||||
// const exchanges = [
|
||||
// 'bittrex',
|
||||
// 'poloniex',
|
||||
// 'bitfinex'
|
||||
// ]
|
||||
|
||||
const exchanges = ccxt.exchanges
|
||||
|
||||
const symbol = 'BTC/USDT'
|
||||
const tickers = {}
|
||||
const volumeField = 'baseVolume'
|
||||
|
||||
console.log ('-----------------------------------------------------------')
|
||||
|
||||
await Promise.all (exchanges.map (exchangeId =>
|
||||
|
||||
new Promise (async (resolve, reject) => {
|
||||
|
||||
try {
|
||||
|
||||
const exchange = new ccxt[exchangeId] ()
|
||||
|
||||
const ticker = await exchange.fetchTicker (symbol)
|
||||
|
||||
if (ticker[volumeField] !== undefined) {
|
||||
tickers[exchangeId] = ticker
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.log (exchangeId, e.message.slice (0, 100))
|
||||
}
|
||||
|
||||
resolve ()
|
||||
|
||||
})
|
||||
|
||||
))
|
||||
|
||||
console.log ('-----------------------------------------------------------')
|
||||
|
||||
console.log (Object
|
||||
.keys (tickers)
|
||||
.sort ((a, b) =>
|
||||
((tickers[a][volumeField] > tickers[b][volumeField]) ? 1 : ((tickers[a][volumeField] < tickers[b][volumeField]) ? -1 : 0)))
|
||||
.reverse ()
|
||||
.map (id => ({
|
||||
id,
|
||||
symbol,
|
||||
'volume': tickers[id][volumeField],
|
||||
}))
|
||||
)
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
- [Exchanges](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import countries from '../../build/countries.js';
|
||||
import asTable from 'as-table';
|
||||
import ololog from 'ololog'
|
||||
import ansicolor from 'ansicolor';
|
||||
const log = ololog.configure ({ locate: false })
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
process.on ('uncaughtException', e => { log.bright.red.error (e); process.exit (1) })
|
||||
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })
|
||||
|
||||
let exchanges = {}
|
||||
|
||||
ccxt.exchanges.forEach (id => { exchanges[id] = new (ccxt)[id] () })
|
||||
|
||||
log ('The ccxt library supports', (ccxt.exchanges.length.toString ()).green, 'exchanges:')
|
||||
|
||||
var countryName = function (code) {
|
||||
return ((countries[code] !== undefined) ? countries[code] : code)
|
||||
}
|
||||
|
||||
log (asTable.configure ({ delimiter: ' | ' }) (Object.values (exchanges).map (exchange => {
|
||||
|
||||
let countries = Array.isArray (exchange.countries) ?
|
||||
exchange.countries.map (countryName).join (', ') :
|
||||
countryName (exchange.countries)
|
||||
|
||||
let website = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www
|
||||
|
||||
return {
|
||||
id: exchange.id,
|
||||
name: exchange.name,
|
||||
url: website,
|
||||
countries: countries,
|
||||
}
|
||||
|
||||
})))
|
||||
|
||||
```
|
||||
@@ -0,0 +1,225 @@
|
||||
- [Fetch All Balances](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import { PAD_WITH_ZERO } from '../../js/src/base/functions/number.js';
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import ansicolor from 'ansicolor';
|
||||
import asTable from 'as-table';
|
||||
import ololog from 'ololog';
|
||||
|
||||
ansicolor.nice
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const table = asTable.configure ({
|
||||
delimiter: '|'.lightGray.dim,
|
||||
right: true,
|
||||
title: x => String (x).lightGray,
|
||||
print: x => {
|
||||
if (typeof x === 'object') {
|
||||
const j = JSON.stringify (x).trim ()
|
||||
if (j.length < 100) return j
|
||||
}
|
||||
return String (x)
|
||||
}
|
||||
}),
|
||||
{ ROUND, DECIMAL_PLACES, decimalToPrecision, omit, unique, flatten, extend } = ccxt,
|
||||
log = ololog.handleNodeErrors ().noLocate.unlimited;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
// set up keys and settings, if any
|
||||
const keysGlobal = path.resolve ('keys.json')
|
||||
const keysLocal = path.resolve ('keys.local.json')
|
||||
|
||||
const keysGlobalExists = fs.existsSync (keysGlobal)
|
||||
const keysLocalExists = fs.existsSync (keysLocal)
|
||||
|
||||
if (!(keysGlobalExists || keysLocalExists)) {
|
||||
const lines = [
|
||||
'This script requires a keys.json or a keys.local.json file containing the API keys in JSON format',
|
||||
'{',
|
||||
' "binance": {',
|
||||
' "apiKey": "YOUR_API_KEY",',
|
||||
' "secret": "YOUR_SECRET"',
|
||||
' }',
|
||||
' "bitfinex": {',
|
||||
' "apiKey": "YOUR_API_KEY",',
|
||||
' "secret": "YOUR_SECRET"',
|
||||
' }',
|
||||
'}'
|
||||
]
|
||||
const errorMessage = lines.join ("\n")
|
||||
log.red.bright (errorMessage)
|
||||
process.exit ()
|
||||
}
|
||||
|
||||
let globalKeysFile = keysGlobalExists ? keysGlobal : false
|
||||
let localKeysFile = keysLocalExists ? keysLocal : globalKeysFile
|
||||
const dynamicLocalKeysFile = JSON.parse (fs.readFileSync (localKeysFile));
|
||||
let settings = localKeysFile ? (dynamicLocalKeysFile || {}) : {}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const timeout = 30000
|
||||
|
||||
const coins = [
|
||||
'BTC',
|
||||
'ETH',
|
||||
'BNB',
|
||||
'EUR',
|
||||
'LTC',
|
||||
'USD',
|
||||
'USDC',
|
||||
'USDT',
|
||||
'BUSD',
|
||||
'XRP',
|
||||
'DOGE',
|
||||
'YFI',
|
||||
'LINK',
|
||||
'XLM',
|
||||
'ADA',
|
||||
'SOL',
|
||||
]
|
||||
|
||||
function initializeAllExchanges () {
|
||||
let numErrors = 0
|
||||
const ignore = [
|
||||
'bcex',
|
||||
'bitsane',
|
||||
'chbtc',
|
||||
'coinbasepro',
|
||||
'jubi',
|
||||
'hitbtc',
|
||||
'bitstamp1',
|
||||
'bitfinex2',
|
||||
'upbit',
|
||||
'huobipro',
|
||||
]
|
||||
const result = []
|
||||
ccxt.exchanges.filter (exchangeId => (!ignore.includes (exchangeId))).forEach (exchangeId => {
|
||||
try {
|
||||
const verbose = false
|
||||
const exchange = new ccxt[exchangeId] ({
|
||||
timeout,
|
||||
verbose,
|
||||
... (settings[exchangeId] || {})
|
||||
})
|
||||
exchange.checkRequiredCredentials ()
|
||||
result.push (exchange)
|
||||
} catch (e) {
|
||||
numErrors++
|
||||
log.red (exchangeId, 'initialization failed', e.constructor.name, e.message.slice (0, 100));
|
||||
}
|
||||
})
|
||||
log ('Initialized', ccxt.exchanges.length - numErrors, 'of', ccxt.exchanges.length, 'exchanges,',
|
||||
numErrors, 'error' + (((numErrors < 1) || (numErrors > 1)) ? 's' : '') + ',',
|
||||
ignore.length, 'skipped')
|
||||
return result
|
||||
}
|
||||
|
||||
(async () => {
|
||||
|
||||
const exchanges = initializeAllExchanges ()
|
||||
console.log (exchanges.map (exchange => exchange.id))
|
||||
let results = []
|
||||
const priceOracle = new ccxt.gate ()
|
||||
const tickers = await priceOracle.fetchTickers ()
|
||||
await Promise.all (exchanges.map ((exchange) => (async function () {
|
||||
|
||||
try {
|
||||
|
||||
if (exchange.has['signIn']) {
|
||||
await exchange.signIn ()
|
||||
}
|
||||
|
||||
const balance = await exchange.fetchTotalBalance ()
|
||||
if (!balance) {
|
||||
throw new Error (exchange.id + ' erroneous balance')
|
||||
}
|
||||
const keys = Object.keys (balance).sort ()
|
||||
const nonzeroBalance = {}
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i]
|
||||
if (coins.includes (key)) {
|
||||
const value = balance[key]
|
||||
const valueToPrecision = decimalToPrecision (value, ROUND, 8, DECIMAL_PLACES)
|
||||
if (valueToPrecision !== '0') {
|
||||
nonzeroBalance[key] = valueToPrecision
|
||||
}
|
||||
}
|
||||
}
|
||||
const numNonzeroKeys = Object.keys (nonzeroBalance).length
|
||||
if (numNonzeroKeys < 1) {
|
||||
log.yellow (exchange.id + ' empty balance')
|
||||
} else {
|
||||
log.green (exchange.id, numNonzeroKeys, 'currencies')
|
||||
results.push ({ exchange: exchange.id, ... nonzeroBalance })
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
log.red (exchange.id, e.constructor.name, e.message.split ("\n")[0].slice (0, 100))
|
||||
}
|
||||
|
||||
}) ()))
|
||||
|
||||
results = ccxt.sortBy (results, 'exchange')
|
||||
|
||||
const currencies = unique (flatten (results.map (result => Object.keys (omit (result, 'exchange')))))
|
||||
currencies.sort ()
|
||||
|
||||
const total = {}
|
||||
for (let i = 0; i < currencies.length; i++) {
|
||||
const currency = currencies[i]
|
||||
let sum = 0
|
||||
results.forEach (result => {
|
||||
if (currency in result) {
|
||||
sum += parseFloat (result[currency])
|
||||
}
|
||||
})
|
||||
total[currency] = decimalToPrecision (sum, ROUND, 8, DECIMAL_PLACES)
|
||||
}
|
||||
|
||||
results.push (extend ({ 'exchange': 'total' }, total))
|
||||
|
||||
results = results.map (result => {
|
||||
let value = 0;
|
||||
const convertTo = 'USD'
|
||||
currencies.forEach (currency => {
|
||||
if (currency === convertTo) {
|
||||
if (currency in result) {
|
||||
value += parseFloat (result[currency])
|
||||
}
|
||||
} else {
|
||||
const symbol = currency + '/' + convertTo
|
||||
if (symbol in tickers) {
|
||||
if (currency in result) {
|
||||
const ticker = tickers[symbol]
|
||||
value += parseFloat (result[currency]) * ticker['last']
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return extend ({
|
||||
'exchange': result.exchange,
|
||||
'$': decimalToPrecision (value, ROUND, 2, DECIMAL_PLACES, PAD_WITH_ZERO),
|
||||
}, result);
|
||||
})
|
||||
|
||||
const tableResults = table (results)
|
||||
|
||||
log (tableResults)
|
||||
|
||||
log.green ('Currencies:', currencies)
|
||||
|
||||
console.log (new Date ())
|
||||
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
- [Fetch All Tickers To Files 2](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import { writeFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const enableRateLimit = true, exchanges = {}, tickers = {};
|
||||
|
||||
|
||||
ccxt.exchanges.forEach (id => {
|
||||
try {
|
||||
const exchange = new ccxt[id] ()
|
||||
if (exchange.has['fetchTickers']) {
|
||||
exchanges[id] = exchange
|
||||
}
|
||||
} catch (e) {
|
||||
console.log ('Failed to initialize', id, e.constructor.name, e.message)
|
||||
}
|
||||
})
|
||||
|
||||
async function main () {
|
||||
|
||||
console.log ('Started')
|
||||
const start = Date.now ()
|
||||
|
||||
try {
|
||||
const promises = Object.values (exchanges).map (exchange => (
|
||||
(async () => {
|
||||
console.log (exchange.id)
|
||||
try {
|
||||
const response = await exchange.fetchTickers ()
|
||||
tickers[exchange.id] = response
|
||||
} catch (e) {
|
||||
console.log ('Failed to fetchTickers() from', exchange.id)
|
||||
}
|
||||
}) ()
|
||||
))
|
||||
await Promise.all (promises)
|
||||
} catch (e) {
|
||||
console.log ('Failed awaiting all exchanges to complete')
|
||||
}
|
||||
|
||||
Object.entries (tickers).forEach (([ id, response ]) => {
|
||||
const folder = 'C:/myproject/tickers'
|
||||
const filename = `${id}-tickers.json`
|
||||
console.log (path.join (folder, filename))
|
||||
writeFileSync (path.join (folder, filename), JSON.stringify (response))
|
||||
})
|
||||
|
||||
const end = Date.now ()
|
||||
console.log (`Fetched tickers in ${(end - start) / 1000} seconds`)
|
||||
|
||||
}
|
||||
|
||||
main ()
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
- [Fetch All Tickers To Files](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import ololog from 'ololog';
|
||||
|
||||
const { noLocate } = ololog;
|
||||
const log = noLocate;
|
||||
|
||||
import fs from 'fs';
|
||||
|
||||
// the numWorkers constant defines the number of concurrent workers
|
||||
// those aren't really threads in terms of the async environment
|
||||
// set this to the number of cores in your CPU * 2
|
||||
// or play with this number to find a setting that works best for you
|
||||
|
||||
const numWorkers = 8;(async () => {
|
||||
|
||||
// make an array of all exchanges
|
||||
const exchanges = ccxt.exchanges
|
||||
|
||||
// filter coinmarketcap and theocean
|
||||
// coinmarketcap isn't really an exchange
|
||||
// theocean requires web3 dependencies to be installed
|
||||
|
||||
.filter (id => ![ 'coinmarketcap', 'theocean' ].includes (id))
|
||||
|
||||
// instantiate each exchange and save it to the exchanges list
|
||||
|
||||
.map (id => new ccxt[id] ())
|
||||
|
||||
// the worker function for each "async thread"
|
||||
const worker = async function () {
|
||||
|
||||
// while the array of all exchanges is not empty
|
||||
while (exchanges.length > 0) {
|
||||
|
||||
// pop one exchange from the array
|
||||
const exchange = exchanges.pop ()
|
||||
|
||||
// check if it has the necessary method implemented
|
||||
if (exchange.has['fetchTickers']) {
|
||||
|
||||
// try to do "the work" and handle errors if any
|
||||
try {
|
||||
|
||||
// fetch the response for all tickers from the exchange
|
||||
const tickers = await exchange.fetchTickers ()
|
||||
|
||||
// make a filename from exchange id
|
||||
const filename = exchange.id + '.json'
|
||||
|
||||
// save the response to a file
|
||||
fs.writeFileSync (filename, JSON.stringify ({ tickers }));
|
||||
|
||||
// print out a message on success
|
||||
log.green (exchange.id, 'tickers saved to', filename)
|
||||
|
||||
} catch (e) {
|
||||
|
||||
// in case of error - print it out and ignore it further
|
||||
log.red (e.constructor.name, e.message)
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
log.red (exchange.id, "has['fetchTickers'] = false");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// create numWorkers "threads" (they aren't really threads)
|
||||
const workers = [ ... Array (numWorkers) ].map (_ => worker ())
|
||||
|
||||
// wait for all of them to execute or fail
|
||||
await Promise.all (workers)
|
||||
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,33 @@
|
||||
- [Fetch Balance](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
"use strict";
|
||||
|
||||
const ccxt = require ('../../ccxt.js');
|
||||
|
||||
// instantiate the exchange
|
||||
let exchange = new ccxt.coinbasepro ({
|
||||
'apiKey': 'XXXXXXXXXXXXXX',
|
||||
'secret': 'YYYYYYYYYYYYYY',
|
||||
'password': 'ZZZZZZ', // if exchange requires password
|
||||
});
|
||||
|
||||
|
||||
async function checkMyBalance() {
|
||||
try {
|
||||
// fetch account balance from the exchange
|
||||
let myBalance = await exchange.fetchBalance ();
|
||||
|
||||
// output the result
|
||||
console.log (exchange.id, 'fetched balance', myBalance);
|
||||
|
||||
} catch (e) {
|
||||
// fpr advanced error-handling, see the "advanced-error-handling.js" example file
|
||||
console.log ('[' + e.constructor.name + '] ' + e.message);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
checkMyBalance();
|
||||
```
|
||||
@@ -0,0 +1,106 @@
|
||||
- [Fetch Create Deposit Address](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
// ----------------------------------------------------------------------------
|
||||
// setup
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// setup
|
||||
|
||||
const // change me
|
||||
defaultCurrencyCode = 'BTC',
|
||||
// change me
|
||||
// currency code specified in commandline args ↓
|
||||
// you can call this script like node examples/js/fetch-create-deposit-address ETH
|
||||
exchangeId = 'poloniex',
|
||||
currencyCode = process.argv[3] || defaultCurrencyCode,
|
||||
exchange = new ccxt[exchangeId] ({
|
||||
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET',
|
||||
|
||||
'enableRateLimit': true, // ←- required! https://github.com/ccxt/ccxt/wiki/Manual#rate-limit
|
||||
|
||||
// 'verbose': true, // ←- uncomment this for verbose output
|
||||
|
||||
// additional credentials might be required in exchange-specific cases:
|
||||
// uid or password for Coinbase Pro, etc...
|
||||
});
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
if (!exchange.has['fetchDepositAddress']) {
|
||||
|
||||
console.log ('The exchange does not support fetchDepositAddress() yet')
|
||||
process.exit ()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
;(async () => {
|
||||
|
||||
try {
|
||||
|
||||
console.log ('Trying to fetch deposit address for ' + currencyCode + ' from ' + exchangeId + '...')
|
||||
|
||||
let fetchResult = await exchange.fetchDepositAddress (currencyCode)
|
||||
|
||||
console.log ('Successfully fetched deposit address for ' + currencyCode)
|
||||
console.log (fetchResult)
|
||||
|
||||
} catch (e) {
|
||||
|
||||
// never skip proper error handling, whatever it is you're building
|
||||
// actually, with crypto error handling should be the largest part of your code
|
||||
|
||||
if (e instanceof ccxt.InvalidAddress) {
|
||||
|
||||
console.log ('The address for ' + currencyCode + ' does not exist yet')
|
||||
|
||||
if (exchange.has['createDepositAddress']) {
|
||||
|
||||
console.log ('Attempting to create a deposit address for ' + currencyCode + '...')
|
||||
|
||||
try {
|
||||
|
||||
const createResult = await exchange.createDepositAddress (currencyCode)
|
||||
|
||||
// console.log (createResult) // for debugging
|
||||
|
||||
console.log ('Successfully created a deposit address for ' + currencyCode + ', fetching the deposit address now...')
|
||||
|
||||
try {
|
||||
|
||||
let fetchResult = await exchange.fetchDepositAddress (currencyCode)
|
||||
|
||||
console.log ('Successfully fetched deposit address for ' + currencyCode)
|
||||
console.log (fetchResult);
|
||||
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.log ('Failed to fetch deposit address for ' + currencyCode, e.constructor.name, e.message)
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.log ('Failed to create deposit address for ' + currencyCode, e.constructor.name, e.message)
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
console.log ('The exchange does not support createDepositAddress()')
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
console.log ('There was an error while fetching deposit address for ' + currencyCode, e.constructor.name, e.message)
|
||||
}
|
||||
}
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
- [Fetch First Ohlcv Timestamp](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
// ###### Description ######
|
||||
//
|
||||
// This function tries to fetch the "listing time" of a symbol by fetching the earliest available bar in daily resolution.
|
||||
// Top-tier exchanges also support fetching smaller timeframes (eg. 1 minute) even several years back, so for those exchanges you can also use `useMinuteTimeframe = true` argument to get the timestamp rounded to the earliest minute bar (instead of daily bar timestamp).
|
||||
// See usage in the end of this file
|
||||
async function fetchFirstBarTimestamp(exchange, symbol, useMinuteTimeframe = false) {
|
||||
// set some constants
|
||||
const millisecondsPerDay = 86400000;
|
||||
const minutesPerDay = 1440;
|
||||
const minimumTimestamp = 1230768000000; // 2009-01-01 (bitcoin created year)
|
||||
// get market features
|
||||
const market = exchange.market(symbol);
|
||||
const marketType = exchange.safeString(market, 'type');
|
||||
let features = exchange.safeDict(exchange.features, marketType, {});
|
||||
if (market['subType'] !== undefined) {
|
||||
features = exchange.safeDict(features, market['subType'], {});
|
||||
}
|
||||
const ohlcv = exchange.safeDict(features, 'fetchOHLCV');
|
||||
if (ohlcv === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const limit = exchange.safeInteger(ohlcv, 'limit');
|
||||
const fetchParams = { 'maxRetriesOnFailure': 3 };
|
||||
// start loop
|
||||
let currentSince = exchange.milliseconds() - millisecondsPerDay * (limit - 1);
|
||||
let foundStartTime = 0;
|
||||
// eslint-disable-next-line
|
||||
while (true) {
|
||||
currentSince = Math.max(currentSince, minimumTimestamp);
|
||||
const dailyBars = await exchange.fetchOHLCV(symbol, '1d', currentSince, limit, fetchParams);
|
||||
if (dailyBars.length <= 0) {
|
||||
break; // if no days returned, then probably start date was passed
|
||||
}
|
||||
const firstTs = dailyBars[0][0];
|
||||
if (firstTs === foundStartTime) {
|
||||
// if the first timestamp is equal to the last-fetched timestamp, then break here, because some exchanges still return initial bar even if since is much ahead to listing time
|
||||
break;
|
||||
}
|
||||
foundStartTime = firstTs;
|
||||
currentSince = foundStartTime - millisecondsPerDay * (limit - 1); // shift 'since' one step back
|
||||
if (dailyBars.length === 1) {
|
||||
// in some cases, some exchanges might still return first bar of chart when endtime overlaps previous day
|
||||
break;
|
||||
}
|
||||
}
|
||||
// if minute resolution needed
|
||||
if (useMinuteTimeframe) {
|
||||
const maxIteration = Math.ceil(minutesPerDay / limit) * 2;
|
||||
const allPromises = [];
|
||||
for (let i = 0; i < maxIteration; i++) {
|
||||
currentSince = foundStartTime - millisecondsPerDay + i * limit * 60 * 1000; // shift one-duration back for more accuracy for different kind of exchanges, like OKX, where first daily bar is offset by one day, but minute bars present
|
||||
allPromises.push(exchange.fetchOHLCV(symbol, '1m', currentSince, limit, fetchParams));
|
||||
}
|
||||
const allResponses = await Promise.all(allPromises);
|
||||
// find earliest bar
|
||||
for (let i = 0; i < allResponses.length; i++) {
|
||||
const response = allResponses[i];
|
||||
if (response.length > 0) {
|
||||
foundStartTime = response[0][0];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return foundStartTime;
|
||||
}
|
||||
// ###### Usage ######
|
||||
const runExample = false; // set to true to run example
|
||||
if (runExample) {
|
||||
const myEx = new ccxt.binance();
|
||||
await myEx.loadMarkets();
|
||||
const symbol = 'TRUMP/USDT';
|
||||
const earliest_timestamp = await fetchFirstBarTimestamp(myEx, symbol, true);
|
||||
console.log('- Earliest bar timestamp:', earliest_timestamp, ', readable: ', myEx.iso8601(earliest_timestamp));
|
||||
console.log('- market.created value:', myEx.market(symbol)['created']);
|
||||
}
|
||||
export default fetchFirstBarTimestamp;
|
||||
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
- [Fetch From Many Exchanges Simultaneously](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import log from 'ololog';
|
||||
|
||||
const symbol = 'ETH/BTC'
|
||||
const exchanges = [ 'coinbasepro', 'hitbtc2', 'poloniex' ]
|
||||
|
||||
;(async () => {
|
||||
|
||||
const result = await Promise.all (exchanges.map (async id => {
|
||||
|
||||
const exchange = new ccxt[id] ()
|
||||
const ticker = await exchange.fetchTicker (symbol)
|
||||
return exchange.extend ({ 'exchange': id }, ticker)
|
||||
|
||||
}))
|
||||
|
||||
log (result);
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
- [Fetch Funding Rate History](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
|
||||
const table = asTable.configure ({ delimiter: ' | ' });
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version)
|
||||
|
||||
async function main () {
|
||||
|
||||
const exchange = new ccxt.binanceusdm()
|
||||
, symbol = 'ETH/USDT'
|
||||
, since = undefined
|
||||
, limit = undefined
|
||||
, params = {}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// fetch the history of the funding rate for a symbol
|
||||
|
||||
const response = await exchange.fetchFundingRateHistory (symbol, since, limit, params)
|
||||
|
||||
console.log (table (response))
|
||||
|
||||
}
|
||||
|
||||
main ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,78 @@
|
||||
- [Fetch Ohlcv From To Mark Index Premium](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
"use strict";
|
||||
|
||||
const ccxt = require ('../../ccxt')
|
||||
|
||||
const exchange = new ccxt.binance ();
|
||||
|
||||
const symbols = [ 'BTC/USDT', 'ETH/USDT', 'ADA/USDT'];
|
||||
// start from i.e. 01 february 2022
|
||||
// you can use milliseconds integer or also parse uniform datetime string, i.e. exchange.parse8601 ('2020-02-01T00:00:00Z')
|
||||
const fromTimestamp = 1643659200000;
|
||||
const tillTimestamp = exchange.milliseconds ();
|
||||
const timeframe = '1h';
|
||||
const itemsLimit = 1000;
|
||||
const fetchMethod = 'fetchOHLCV'; // if using swap exchanges, you can also use fetchMarkOHLCV, fetchIndexOHLCV, fetchPremiumIndexOHLCV
|
||||
|
||||
async function myDataFetch (symbol) {
|
||||
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
// get the duration of one timeframe period in milliseconds
|
||||
const duration = exchange.parseTimeframe (timeframe) * 1000;
|
||||
console.log ('Fetching', symbol, timeframe, 'candles', 'from', exchange.iso8601 (fromTimestamp), 'to', exchange.iso8601 (tillTimestamp), '...');
|
||||
|
||||
let result = [];
|
||||
let since = fromTimestamp;
|
||||
do {
|
||||
|
||||
try {
|
||||
|
||||
const candles = await exchange[fetchMethod] (symbol, timeframe, since, itemsLimit);
|
||||
|
||||
const message = '[' + symbol + '] Fetched ' + candles.length + ' ' + timeframe + ' candles since ' + exchange.iso8601 (since);
|
||||
|
||||
if (candles.length) {
|
||||
|
||||
const first = candles[0];
|
||||
const last = candles[candles.length - 1];
|
||||
console.log ( message, ' | first', exchange.iso8601 (first[0]), ' | last', exchange.iso8601 (last[0]) );
|
||||
|
||||
// store your candles to a database or to a file here
|
||||
// ...
|
||||
result = result.concat (candles);
|
||||
since = last[0] + duration // next start from last candle timestamp + duration
|
||||
|
||||
} else {
|
||||
console.log ( message, ' | moving into next period');
|
||||
since = since + duration * itemsLimit; // next start from the current period's end
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.log (symbol, e.constructor.name, e.message, ' Taking small pause...');
|
||||
await exchange.sleep (2000);
|
||||
// retry on next iteration
|
||||
}
|
||||
|
||||
} while (since + duration <= tillTimestamp)
|
||||
|
||||
console.log (symbol + ' completed !');
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
async function checkAllSymbols() {
|
||||
// download in parallel
|
||||
await Promise.all (symbols.map (symbol => myDataFetch (symbol)));
|
||||
// you can also do one by one (but that is not much optimal)
|
||||
//for (const symbol of symbols) {
|
||||
// const data = await myDataFetch (symbol);
|
||||
}
|
||||
checkAllSymbols();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
- [Fetch Ohlcv Many Exchanges Continuosly](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
// fetch and handle constinuosly
|
||||
async function fetchOHLCVContinuously(exchange, symbol) {
|
||||
while (true) {
|
||||
try {
|
||||
const ohlcv = await exchange.fetchOHLCV(symbol);
|
||||
const ohlcvLength = ohlcv.length;
|
||||
console.log('Fetched ', exchange.id, ' - ', symbol, ' candles. last candle: ', ohlcv[ohlcvLength - 1]);
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// start exchanges and fetch OHLCV loop
|
||||
async function startExchange(exchangeName, symbols) {
|
||||
const ex = new ccxt[exchangeName]({});
|
||||
const promises = [];
|
||||
for (let i = 0; i < symbols.length; i++) {
|
||||
const symbol = symbols[i];
|
||||
promises.push(fetchOHLCVContinuously(ex, symbol));
|
||||
}
|
||||
await Promise.all(promises);
|
||||
await ex.close();
|
||||
}
|
||||
// main function
|
||||
async function example() {
|
||||
const exchanges = ['binance', 'okx', 'kraken'];
|
||||
const symbols = ['BTC/USDT', 'ETH/USDT'];
|
||||
const promises = [];
|
||||
for (let i = 0; i < exchanges.length; i++) {
|
||||
const exchangeName = exchanges[i];
|
||||
promises.push(startExchange(exchangeName, symbols));
|
||||
}
|
||||
await Promise.all(promises);
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
- [Fetch Ohlcv](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
// AUTO-TRANSPILE //
|
||||
async function example() {
|
||||
const myex = new ccxt.okx({});
|
||||
const fromTimestamp = myex.milliseconds() - 86400 * 1000; // last 24 hrs
|
||||
const ohlcv = await myex.fetchOHLCV('BTC/USDT', '1m', fromTimestamp, 3, { 'whatever': 123 });
|
||||
const length = ohlcv.length;
|
||||
if (length > 0) {
|
||||
const lastPrice = ohlcv[length - 1][4];
|
||||
console.log('Fetched ', length, ' candles for ', myex.id, ': last close ', lastPrice);
|
||||
}
|
||||
else {
|
||||
console.log('No candles have been fetched');
|
||||
}
|
||||
}
|
||||
await example();
|
||||
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
- [Fetch Okex Futures](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
async function test () {
|
||||
|
||||
const exchange = new ccxt.okex ()
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
for (let symbol in exchange.markets) {
|
||||
|
||||
const market = exchange.markets[symbol]
|
||||
|
||||
if (market['future']) {
|
||||
console.log ('----------------------------------------------------')
|
||||
console.log (symbol, await exchange.fetchTicker (symbol))
|
||||
await ccxt.sleep (exchange.rateLimit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
- [Fetch Orders](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
import log from 'ololog';
|
||||
import ansicolor from 'ansicolor';
|
||||
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
const exchange = new ccxt.bittrex ({
|
||||
apiKey: "YOUR_API_KEY",
|
||||
secret: "YOUR_SECRET",
|
||||
})
|
||||
|
||||
async function test () {
|
||||
|
||||
const orders = await exchange.fetchOrders ()
|
||||
|
||||
log (asTable (orders.map (order => ccxt.omit (order, [ 'timestamp', 'info' ]))))
|
||||
|
||||
const order = await exchange.fetchOrder (orders[0]['id'])
|
||||
|
||||
log (order)
|
||||
}
|
||||
|
||||
test ()
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
- [Fetch Ticker From Multiple Exchanges](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
(async () => {
|
||||
|
||||
const exchanges = [
|
||||
'bittrex',
|
||||
'poloniex',
|
||||
]
|
||||
|
||||
const symbol = 'BTC/USDT'
|
||||
const tickers = {}
|
||||
|
||||
await Promise.all (exchanges.map (exchangeId =>
|
||||
|
||||
new Promise (async (resolve, reject) => {
|
||||
|
||||
const exchange = new ccxt[exchangeId] ()
|
||||
|
||||
while (true) {
|
||||
|
||||
const ticker = await exchange.fetchTicker (symbol)
|
||||
tickers[exchangeId] = ticker
|
||||
|
||||
Object.keys (tickers).map (exchangeId => {
|
||||
const ticker = tickers[exchangeId]
|
||||
console.log (ticker['datetime'], exchangeId, ticker['bid'], ticker['ask'])
|
||||
})
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
))
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,80 @@
|
||||
- [Fetch Ticker Where Available](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
|
||||
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
import asTable from 'as-table';
|
||||
import log from 'ololog';
|
||||
import ansicolor from 'ansicolor';
|
||||
|
||||
|
||||
ansicolor.nice
|
||||
|
||||
let printUsage = function () {
|
||||
log ('Usage: node', process.argv[1], 'symbol'.green)
|
||||
}
|
||||
|
||||
;(async function main () {
|
||||
|
||||
if (process.argv.length > 2) {
|
||||
|
||||
let symbol = process.argv[2].toUpperCase ()
|
||||
|
||||
for (let i = 0; i < ccxt.exchanges.length; i++) {
|
||||
|
||||
let id = ccxt.exchanges[i]
|
||||
|
||||
const exchange = new ccxt[id] ()
|
||||
if (exchange.has.fetchTicker) {
|
||||
|
||||
try {
|
||||
|
||||
await exchange.loadMarkets ()
|
||||
|
||||
if (exchange.symbols.includes (symbol)) {
|
||||
|
||||
log (id.green)
|
||||
|
||||
const ticker = await exchange.fetchTicker (symbol)
|
||||
|
||||
log.dim (ticker)
|
||||
|
||||
if (ticker['baseVolume'] && ticker['quoteVolume']) {
|
||||
|
||||
if (ticker['bid'] > 1) {
|
||||
|
||||
if (ticker['baseVolume'] > ticker['quoteVolume'])
|
||||
log (id.bright, 'baseVolume > quoteVolume ← !'.bright)
|
||||
|
||||
} else {
|
||||
|
||||
if (ticker['baseVolume'] < ticker['quoteVolume'])
|
||||
log (id.bright, 'baseVolume < quoteVolume ← !'.bright)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
log (id.yellow)
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
|
||||
log.error (id.red, e.toString ().red)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
printUsage ()
|
||||
}
|
||||
|
||||
process.exit ()
|
||||
|
||||
}) ()
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
- [Gateio Create Batch Order](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
const ccxt = require ('../../ccxt');
|
||||
|
||||
console.log ('CCXT Version:', ccxt.version);
|
||||
|
||||
async function main () {
|
||||
|
||||
const exchange = new ccxt.gateio ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_API_SECRET',
|
||||
});
|
||||
await exchange.loadMarkets ();
|
||||
|
||||
const ada = exchange.market ('ADA/USDT');
|
||||
const xrp = exchange.market ('XRP/USDT');
|
||||
|
||||
const orders = await exchange.privateSpotPostBatchOrders (
|
||||
[
|
||||
{
|
||||
text: "t-123456",
|
||||
currency_pair: ada['id'],
|
||||
type: "limit",
|
||||
account: "spot",
|
||||
side: "buy",
|
||||
amount: "3",
|
||||
price: "0.4",
|
||||
},
|
||||
{
|
||||
text: "t-123456",
|
||||
currency_pair: xrp['id'],
|
||||
type: "limit",
|
||||
account: "spot",
|
||||
side: "buy",
|
||||
amount: "3",
|
||||
price: "0.47",
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
console.log (orders);
|
||||
|
||||
};
|
||||
|
||||
main ();
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
- [Gateio Futures](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
import ccxt from '../../js/ccxt.js';
|
||||
|
||||
|
||||
const exchange = new ccxt.gateio ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET_KEY',
|
||||
'options': {
|
||||
'defaultType': 'future',
|
||||
},
|
||||
})
|
||||
|
||||
;(async () => {
|
||||
// exchange.setSandboxMode (true)
|
||||
|
||||
const markets = await exchange.loadMarkets ()
|
||||
|
||||
// exchange.verbose = true // uncomment for debugging purposes if necessary
|
||||
|
||||
// Example 1: Creating a future (market) order
|
||||
try {
|
||||
|
||||
// find a future
|
||||
const futures = []
|
||||
for (const [key, market] of Object.entries(markets)) {
|
||||
if (market['future']) {
|
||||
futures.push(market);
|
||||
}
|
||||
}
|
||||
if (futures.length > 0) {
|
||||
const market = futures[0];
|
||||
const symbol = market['symbol'] // example: BTC/USDT:USDT-220318
|
||||
const type = 'market'
|
||||
const side = 'buy'
|
||||
const amount = 1
|
||||
|
||||
// placing an order
|
||||
const order = await exchange.createOrder (symbol, type, side, amount)
|
||||
console.log (order)
|
||||
|
||||
// fetching open orders
|
||||
const openOrders = await exchange.fetchOpenOrders(symbol)
|
||||
console.log(openOrders)
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.log (e.constructor.name, e.message)
|
||||
}
|
||||
|
||||
}) ()
|
||||
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
- [Gateio Open Close Contract](./examples/js/)
|
||||
|
||||
|
||||
```javascript
|
||||
const ccxt = require ('../../ccxt');
|
||||
|
||||
|
||||
const exchange = new ccxt.gateio ({
|
||||
'apiKey': 'YOUR_API_KEY',
|
||||
'secret': 'YOUR_SECRET',
|
||||
'options': {
|
||||
'defaultType': 'swap',
|
||||
'marginMode': 'cross'
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
;(async () => {
|
||||
|
||||
// exchange.setSandboxMode (true)
|
||||
|
||||
const markets = await exchange.loadMarkets ()
|
||||
|
||||
// exchange.verbose = true // uncomment for debugging purposes if necessary
|
||||
|
||||
// Example: creating and closing a contract
|
||||
let symbol = 'LTC/USDT:USDT'
|
||||
let type = 'market'
|
||||
let side = 'buy'
|
||||
let amount = 1
|
||||
let price = undefined
|
||||
|
||||
try {
|
||||
// fetching current balance
|
||||
const balance = await exchange.fetchBalance()
|
||||
console.log(balance)
|
||||
|
||||
// placing an order / opening contract position
|
||||
const order = await exchange.createOrder (symbol, type, side, amount, price)
|
||||
console.log (order)
|
||||
|
||||
// closing it by issuing an oposite contract
|
||||
// and therefore close our previous position
|
||||
side = 'sell'
|
||||
type = 'market'
|
||||
reduce_only = true
|
||||
params = {'reduce_only': reduce_only}
|
||||
const opositeOrder = await exchange.createOrder (symbol, type, side, amount, price, params)
|
||||
console.log (opositeOrder)
|
||||
} catch (e) {
|
||||
console.log (e.constructor.name, e.message)
|
||||
}
|
||||
}) ()
|
||||
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user