This commit is contained in:
discountry
2025-10-03 15:28:16 +08:00
parent d5c4b04746
commit fcb83bd16b
925 changed files with 165721 additions and 4 deletions
+491
View File
@@ -0,0 +1,491 @@
<style>ul { margin-bottom: -10px; }</style>
# [<-](Examples?id=python)
# CCXT Python Examples
To run Python examples from any folder, type in console:
```shell
python path/to/example.py # substitute for actual filename here
```
Example files starting with `async-` require Python 3.6 with `async`/`await` and async generators support.
![basic-chart](https://user-images.githubusercontent.com/1294454/29979754-6d62354c-8f4f-11e7-9e0a-22e87b4a093b.jpg)
## See Also
[co3k-crypto-currency-note](https://github.com/co3k/co3k-crypto-currency-note/blob/master/Untitled.ipynb) an example of using ccxt to fetch OHLCV candles from Kraken and charting them with matplotlib in a Jupyter Notebook, made by [co3k](https://github.com/co3k).
- [Aiohttp Custom Session Connector](./examples/py/aiohttp-custom-session-connector.md)
- [All Exchanges](./examples/py/all-exchanges.md)
- [Arbitrage Pairs](./examples/py/arbitrage-pairs.md)
- [Asciichart](./examples/py/asciichart.md)
- [Async Analyse Augur V1 Vs V2 Exchanges](./examples/py/async-analyse-augur-v1-vs-v2-exchanges.md)
- [Async Balance Coinbasepro](./examples/py/async-balance-coinbasepro.md)
- [Async Balance Gdax](./examples/py/async-balance-gdax.md)
- [Async Balance](./examples/py/async-balance.md)
- [Async Balances](./examples/py/async-balances.md)
- [Async Basic Callchain](./examples/py/async-basic-callchain.md)
- [Async Basic Orderbook](./examples/py/async-basic-orderbook.md)
- [Async Basic Rate Limiter](./examples/py/async-basic-rate-limiter.md)
- [Async Basic](./examples/py/async-basic.md)
- [Async Binance Cancel Option Order](./examples/py/async-binance-cancel-option-order.md)
- [Async Binance Create Margin Order](./examples/py/async-binance-create-margin-order.md)
- [Async Binance Create Option Order](./examples/py/async-binance-create-option-order.md)
- [Async Binance Create Trailing Percent Order](./examples/py/async-binance-create-trailing-percent-order.md)
- [Async Binance Fetch Margin Balance With Options](./examples/py/async-binance-fetch-margin-balance-with-options.md)
- [Async Binance Fetch Margin Balance With Params](./examples/py/async-binance-fetch-margin-balance-with-params.md)
- [Async Binance Fetch Option Ohlcv](./examples/py/async-binance-fetch-option-OHLCV.md)
- [Async Binance Fetch Option Details](./examples/py/async-binance-fetch-option-details.md)
- [Async Binance Fetch Option Order](./examples/py/async-binance-fetch-option-order.md)
- [Async Binance Fetch Option Orderbook](./examples/py/async-binance-fetch-option-orderbook.md)
- [Async Binance Fetch Option Position](./examples/py/async-binance-fetch-option-position.md)
- [Async Binance Fetch Option Ticker](./examples/py/async-binance-fetch-option-ticker.md)
- [Async Binance Fetch Ticker Continuously](./examples/py/async-binance-fetch-ticker-continuously.md)
- [Async Binance Futures Vs Spot](./examples/py/async-binance-futures-vs-spot.md)
- [Async Binance Margin Borrow](./examples/py/async-binance-margin-borrow.md)
- [Async Binance Margin Repay](./examples/py/async-binance-margin-repay.md)
- [Async Binance Usdm Fetch Continuous Klines Ohlcv](./examples/py/async-binance-usdm-fetch-continuous-klines-ohlcv.md)
- [Async Bitfinex Public Get Symbols](./examples/py/async-bitfinex-public-get-symbols.md)
- [Async Bitget Perpetual Futures Swaps](./examples/py/async-bitget-perpetual-futures-swaps.md)
- [Async Bitstamp Create Limit Buy Order](./examples/py/async-bitstamp-create-limit-buy-order.md)
- [Async Bitstamp Create Order Cancel Order](./examples/py/async-bitstamp-create-order-cancel-order.md)
- [Async Bittrex Orderbook](./examples/py/async-bittrex-orderbook.md)
- [Async Bybit Transfer](./examples/py/async-bybit-transfer.md)
- [Async Fetch Balance](./examples/py/async-fetch-balance.md)
- [Async Fetch Many Orderbooks Continuously](./examples/py/async-fetch-many-orderbooks-continuously.md)
- [Async Fetch Ohlcv Indicators Discord Webhook](./examples/py/async-fetch-ohlcv-indicators-discord-webhook.md)
- [Async Fetch Ohlcv Multiple Symbols Continuously](./examples/py/async-fetch-ohlcv-multiple-symbols-continuously.md)
- [Async Fetch Order Book From Many Exchanges](./examples/py/async-fetch-order-book-from-many-exchanges.md)
- [Async Fetch Ticker](./examples/py/async-fetch-ticker.md)
- [Async Gather Concurrency](./examples/py/async-gather-concurrency.md)
- [Async Gdax Fetch Order Book Continuously](./examples/py/async-gdax-fetch-order-book-continuously.md)
- [Async Generator Basic](./examples/py/async-generator-basic.md)
- [Async Generator Multiple Tickers](./examples/py/async-generator-multiple-tickers.md)
- [Async Generator Ticker Poller](./examples/py/async-generator-ticker-poller.md)
- [Async Hollaex Sandbox](./examples/py/async-hollaex-sandbox.md)
- [Async Instantiate All At Once](./examples/py/async-instantiate-all-at-once.md)
- [Async Kucoin Rate Limit](./examples/py/async-kucoin-rate-limit.md)
- [Async Macd](./examples/py/async-macd.md)
- [Async Market Making Symbols](./examples/py/async-market-making-symbols.md)
- [Async Multiple Accounts](./examples/py/async-multiple-accounts.md)
- [Async Multiple Parallel Calls](./examples/py/async-multiple-parallel-calls.md)
- [Async Okx Create Margin Order](./examples/py/async-okx-create-margin-order.md)
- [Async Okx Margin Borrow](./examples/py/async-okx-margin-borrow.md)
- [Async Okx Margin Repay](./examples/py/async-okx-margin-repay.md)
- [Async Okx Positional Orders](./examples/py/async-okx-positional-orders.md)
- [Async Orderbooks From Multiple Exchanges At Once](./examples/py/async-orderbooks-from-multiple-exchanges-at-once.md)
- [Async Orderbooks](./examples/py/async-orderbooks.md)
- [Async Rtt](./examples/py/async-rtt.md)
- [Async Theocean Orderbook](./examples/py/async-theocean-orderbook.md)
- [Async Theocean Tickers](./examples/py/async-theocean-tickers.md)
- [Async Ticker](./examples/py/async-ticker.md)
- [Async Tickers From Many Exchanges At Once](./examples/py/async-tickers-from-many-exchanges-at-once.md)
- [Async Tickers](./examples/py/async-tickers.md)
- [Async With Threads](./examples/py/async-with-threads.md)
- [Async](./examples/py/async.md)
- [Balance Coinbasepro](./examples/py/balance-coinbasepro.md)
- [Balance Gdax](./examples/py/balance-gdax.md)
- [Balance Kraken](./examples/py/balance-kraken.md)
- [Balances](./examples/py/balances.md)
- [Basic Chart](./examples/py/basic-chart.md)
- [Basic Rate Limiting](./examples/py/basic-rate-limiting.md)
- [Binance Batch Orders](./examples/py/binance-batch-orders.md)
- [Binance Coin Margined Take Profit](./examples/py/binance-coin-margined-take-profit.md)
- [Binance Conditional Orders](./examples/py/binance-conditional-orders.md)
- [Binance Create Oco Order With Implicit Methods](./examples/py/binance-create-oco-order-with-implicit-methods.md)
- [Binance Ema](./examples/py/binance-ema.md)
- [Binance Fetch All My Trades Paginate By Id](./examples/py/binance-fetch-all-my-trades-paginate-by-id.md)
- [Binance Fetch All My Trades](./examples/py/binance-fetch-all-my-trades.md)
- [Binance Fetch All Trades](./examples/py/binance-fetch-all-trades.md)
- [Binance Fetch Ohlcv Closing Time 1](./examples/py/binance-fetch-ohlcv-closing-time-1.md)
- [Binance Fetch Ohlcv Closing Time 2](./examples/py/binance-fetch-ohlcv-closing-time-2.md)
- [Binance Fetch Ohlcv Pagination](./examples/py/binance-fetch-ohlcv-pagination.md)
- [Binance Fetch Ohlcv Quote Volume](./examples/py/binance-fetch-ohlcv-quote-volume.md)
- [Binance Fetch Ohlcv To Csv](./examples/py/binance-fetch-ohlcv-to-csv.md)
- [Binance Fetch Ohlcv](./examples/py/binance-fetch-ohlcv.md)
- [Binance Fiat](./examples/py/binance-fiat.md)
- [Binance Futures Margin](./examples/py/binance-futures-margin.md)
- [Binance Futures Positions](./examples/py/binance-futures-positions.md)
- [Binance Futures Set Leverage Implicit Api](./examples/py/binance-futures-set-leverage-implicit-api.md)
- [Binance Futures Set Leverage](./examples/py/binance-futures-set-leverage.md)
- [Binance Market Order Quote Usdt](./examples/py/binance-market-order-quote-usdt.md)
- [Binance Poll Balance](./examples/py/binance-poll-balance.md)
- [Binance Poll Positions](./examples/py/binance-poll-positions.md)
- [Binance Savings Endpoints](./examples/py/binance-savings-endpoints.md)
- [Binance Spot Trailing](./examples/py/binance-spot-trailing.md)
- [Binance Stop Loss Take Profit](./examples/py/binance-stop-loss-take-profit.md)
- [Binance Test Order](./examples/py/binance-test-order.md)
- [Binance Universal Transfer](./examples/py/binance-universal-transfer.md)
- [Binance Usdm Fetch Continuous Klines Ohlcv](./examples/py/binance-usdm-fetch-continuous-klines-ohlcv.md)
- [Bitfinex Rate Limiting](./examples/py/bitfinex-rate-limiting.md)
- [Bitget Perpetual Futures Swaps](./examples/py/bitget-perpetual-futures-swaps.md)
- [Bitmex Cancel Orders](./examples/py/bitmex-cancel-orders.md)
- [Bitmex Create Order](./examples/py/bitmex-create-order.md)
- [Bitmex Fetch Ohlcv With Extra Params](./examples/py/bitmex-fetch-ohlcv-with-extra-params.md)
- [Bitmex Ohlcv Convert 5m To 15m](./examples/py/bitmex-ohlcv-convert-5m-to-15m.md)
- [Bitmex Order Value](./examples/py/bitmex-order-value.md)
- [Bittrex Fetch Closed Orders History](./examples/py/bittrex-fetch-closed-orders-history.md)
- [Build Ohlcv Bars](./examples/py/build-ohlcv-bars.md)
- [Builtin Rate Limiting Long Poller](./examples/py/builtin-rate-limiting-long-poller.md)
- [Bybit Usdc Create Option Order](./examples/py/bybit-USDC-create-option-order.md)
- [Bybit Conditional Orders](./examples/py/bybit-conditional-orders.md)
- [Bybit Positions](./examples/py/bybit-positions.md)
- [Bybit Trailling](./examples/py/bybit-trailling.md)
- [Bybit Updated](./examples/py/bybit-updated.md)
- [Cli](./examples/py/cli.md)
- [Coinbase Cancel Order](./examples/py/coinbase-cancel-order.md)
- [Coinbase Create Order](./examples/py/coinbase-create-order.md)
- [Coinbase Fetch Ohlcv](./examples/py/coinbase-fetch-OHLCV.md)
- [Coinbase Fetch Order](./examples/py/coinbase-fetch-order.md)
- [Coinbase Fetch Ticker](./examples/py/coinbase-fetch-ticker.md)
- [Coinbase Fetch Trades](./examples/py/coinbase-fetch-trades.md)
- [Coinbasepro Fetch My Trades Pagination](./examples/py/coinbasepro-fetch-my-trades-pagination.md)
- [Coinex Futures](./examples/py/coinex-futures.md)
- [Coinone Fetch Tickers](./examples/py/coinone-fetch-tickers.md)
- [Coinone Markets](./examples/py/coinone-markets.md)
- [Compare Two Exchanges Capabilities](./examples/py/compare-two-exchanges-capabilities.md)
- [Create Order Position With Takeprofit Stoploss](./examples/py/create-order-position-with-takeprofit-stoploss.md)
- [Create Order Ws Example](./examples/py/create-order-ws-example.md)
- [Create Orders Example](./examples/py/create-orders-example.md)
- [Create Trailing Amount Order](./examples/py/create-trailing-amount-order.md)
- [Create Trailing Percent Order](./examples/py/create-trailing-percent-order.md)
- [Exchange Save Load Markets Cache](./examples/py/exchange-save-load-markets-cache.md)
- [Exchanges By Country](./examples/py/exchanges-by-country.md)
- [Exchanges](./examples/py/exchanges.md)
- [Fetch All Okex Ohclv](./examples/py/fetch-all-okex-ohclv.md)
- [Fetch All Tickers](./examples/py/fetch-all-tickers.md)
- [Fetch Balance Asset Valuation](./examples/py/fetch-balance-asset-valuation.md)
- [Fetch Bitfinex Ohlcv History](./examples/py/fetch-bitfinex-ohlcv-history.md)
- [Fetch Coinbasepro Ohlcv Sequentially](./examples/py/fetch-coinbasepro-ohlcv-sequentially.md)
- [Fetch Create Deposit Address](./examples/py/fetch-create-deposit-address.md)
- [Fetch First Ohlcv Timestamp](./examples/py/fetch-first-ohlcv-timestamp.md)
- [Fetch Gdax Ohlcv Sequentially](./examples/py/fetch-gdax-ohlcv-sequentially.md)
- [Fetch Ohlcv Cex](./examples/py/fetch-ohlcv-cex.md)
- [Fetch Ohlcv Kraken](./examples/py/fetch-ohlcv-kraken.md)
- [Fetch Ohlcv Many Exchanges Continuosly](./examples/py/fetch-ohlcv-many-exchanges-continuosly.md)
- [Fetch Ohlcv Mark Index Price](./examples/py/fetch-ohlcv-mark-index-price.md)
- [Fetch Ohlcv On New Candle](./examples/py/fetch-ohlcv-on-new-candle.md)
- [Fetch Ohlcv Sequentially](./examples/py/fetch-ohlcv-sequentially.md)
- [Fetch Ohlcv](./examples/py/fetch-ohlcv.md)
- [Fetch Okex Futures](./examples/py/fetch-okex-futures.md)
- [Fetch Open Orders](./examples/py/fetch-open-orders.md)
- [Fetch Order Book Rtt](./examples/py/fetch-order-book-rtt.md)
- [Fetch Orders](./examples/py/fetch-orders.md)
- [Fetch Ticker Many Exchanges Many Symbols](./examples/py/fetch-ticker-many-exchanges-many-symbols.md)
- [Fetch_longer_ohlcv_through_multiple_calls_and_save_to_csv](./examples/py/fetch_longer_ohlcv_through_multiple_calls_and_save_to_csv.md)
- [Gateio Fetch Ohlcv Pagination](./examples/py/gateio-fetch-ohlcv-pagination.md)
- [Gateio Futures](./examples/py/gateio-futures.md)
- [Gateio Open Close Contract](./examples/py/gateio-open-close-contract.md)
- [Gateio Swaps](./examples/py/gateio-swaps.md)
- [Gdax Fetch My Trades Pagination](./examples/py/gdax-fetch-my-trades-pagination.md)
- [Hitbtc Withdraw](./examples/py/hitbtc-withdraw.md)
- [Huobi Futures](./examples/py/huobi-futures.md)
- [Huobi Open Close Contract](./examples/py/huobi-open-close-contract.md)
- [Huobi Open Close Position Bbo](./examples/py/huobi-open-close-position-bbo.md)
- [Huobi Spot](./examples/py/huobi-spot.md)
- [Huobi Swaps](./examples/py/huobi-swaps.md)
- [Instantiate All At Once](./examples/py/instantiate-all-at-once.md)
- [Kraken Conditional Close Order](./examples/py/kraken-conditional-close-order.md)
- [Kraken Create And Close Position](./examples/py/kraken-create-and-close-position.md)
- [Kraken Fetch My Trades Pagination](./examples/py/kraken-fetch-my-trades-pagination.md)
- [Krakenfutures Basic](./examples/py/krakenfutures-basic.md)
- [Kucoin Fetch All Deposit Addresses By Network](./examples/py/kucoin-fetch-all-deposit-addresses-by-network.md)
- [Kucoin Fetch All Deposit Addresses](./examples/py/kucoin-fetch-all-deposit-addresses.md)
- [Kucoin Fetch Closed Orders Pagination](./examples/py/kucoin-fetch-closed-orders-pagination.md)
- [Kucoin Rate Limit](./examples/py/kucoin-rate-limit.md)
- [Kucoin Withdraw Chain](./examples/py/kucoin-withdraw-chain.md)
- [Kucoinfutures Create Stop Order](./examples/py/kucoinfutures-create-stop-order.md)
- [Latoken Create Order](./examples/py/latoken-create-order.md)
- [Latoken Example](./examples/py/latoken-example.md)
- [Manual Rate Limiting Long Poller](./examples/py/manual-rate-limiting-long-poller.md)
- [Margin Leverage Order Kraken](./examples/py/margin-leverage-order-kraken.md)
- [Margin Loan Borrow Buy Sell Repay](./examples/py/margin-loan-borrow-buy-sell-repay.md)
- [Measure Latency](./examples/py/measure-latency.md)
- [Minimal 2 Lines](./examples/py/minimal-2-lines.md)
- [Multiple Subscriptions Watchxforsymbols](./examples/py/multiple-subscriptions-watchXForSymbols.md)
- [Normalize Sparse Candle Timestamps](./examples/py/normalize-sparse-candle-timestamps.md)
- [Okx Fetch All My Trades](./examples/py/okx-fetch-all-my-trades.md)
- [Okx Fetch Closed Orders Pagenumber Pagination](./examples/py/okx-fetch-closed-orders-pagenumber-pagination.md)
- [Okx Position Takeprofit Stoploss](./examples/py/okx-position-takeprofit-stoploss.md)
- [Okx Transfer](./examples/py/okx-transfer.md)
- [Order Book Extra Level Depth Param](./examples/py/order-book-extra-level-depth-param.md)
- [Phemex Create Order Position With Takeprofit Stoploss](./examples/py/phemex-create-order-position-with-takeprofit-stoploss.md)
- [Phemex Create Stop Order](./examples/py/phemex-create-stop-order.md)
- [Phemex Leverage Orders](./examples/py/phemex-leverage-orders.md)
- [Phemex Open Cancel Close Positions](./examples/py/phemex-open-cancel-close-positions.md)
- [Phemex Perpetual Balance](./examples/py/phemex-perpetual-balance.md)
- [Phemex Positions](./examples/py/phemex-positions.md)
- [Phemex Transfer](./examples/py/phemex-transfer.md)
- [Playing_with_ccxt_example](./examples/py/playing_with_ccxt_example.md)
- [Poloniex Fetch Ohlcv Continuously](./examples/py/poloniex-fetch-ohlcv-continuously.md)
- [Poloniex Fetch Ohlcv With Pagination](./examples/py/poloniex-fetch-ohlcv-with-pagination.md)
- [Poloniex Fetch Order Books](./examples/py/poloniex-fetch-order-books.md)
- [Poloniex Fetch Trades Continuously](./examples/py/poloniex-fetch-trades-continuously.md)
- [Poloniex Fetch Trades With Pagination To Csv](./examples/py/poloniex-fetch-trades-with-pagination-to-csv.md)
- [Poloniex Python2 Memleak Test](./examples/py/poloniex-python2-memleak-test.md)
- [Poloniex Python3 Memleak Test](./examples/py/poloniex-python3-memleak-test.md)
- [Proxy Usage](./examples/py/proxy-usage.md)
- [Rsi](./examples/py/rsi.md)
- [Rtt](./examples/py/rtt.md)
- [Sample Local Proxy Server With Cors](./examples/py/sample-local-proxy-server-with-cors.md)
- [Set_markets_from_exchange](./examples/py/set_markets_from_exchange.md)
- [Sign In](./examples/py/sign-in.md)
- [Sort Swap Markets By Hourly Price Change](./examples/py/sort-swap-markets-by-hourly-price-change.md)
- [Source Ip Address](./examples/py/source-ip-address.md)
- [Symbols](./examples/py/symbols.md)
- [Test Server](./examples/py/test-server.md)
- [Theocean](./examples/py/theocean.md)
- [Tickers](./examples/py/tickers.md)
- [Watch Ohlcv For Symbols](./examples/py/watch-OHLCV-For-Symbols.md)
- [Watch Ohlcv](./examples/py/watch-OHLCV.md)
- [Watch Orderbook For Symbols](./examples/py/watch-OrderBook-For-Symbols.md)
- [Watch Trades For Symbols](./examples/py/watch-Trades-For-Symbols.md)
- [Watch Tickers](./examples/py/watch-tickers.md)
- [Watchohlcvforsymbols](./examples/py/watchOHLCVForSymbols.md)
- [Watchorderbookforsymbols](./examples/py/watchOrderBookForSymbols.md)
- [Watchpositions Many Exchanges Continuosly](./examples/py/watchPositions-many-exchanges-continuosly.md)
- [Watchpositions](./examples/py/watchPositions.md)
- [Watchpositionsforsymbols](./examples/py/watchPositionsForSymbols.md)
- [Watchtradesforsymbols](./examples/py/watchTradesForSymbols.md)
- [Wazirx Create Cancel Orders](./examples/py/wazirx-create-cancel-orders.md)
- [Withdraw From One Exchange To Another](./examples/py/withdraw-from-one-exchange-to-another.md)
- [Ws_test_load](./examples/py/ws_test_load.md)
@@ -0,0 +1,31 @@
- [Aiohttp Custom Session Connector](./examples/py/)
```python
# pip install aiohttp_socks
import asyncio
import ccxt.async_support as ccxt
import aiohttp
import aiohttp_socks
async def test():
connector = aiohttp_socks.ProxyConnector.from_url('socks5://user:password@127.0.0.1:1080')
session = aiohttp.ClientSession(connector=connector)
exchange = ccxt.binance({
'session': session,
# ...
})
# ...
await exchange.close() # Close the exchange
await session.close() # don't forget to close the session
# ...
asyncio.run(test())
```
@@ -0,0 +1,25 @@
- [All Exchanges](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
for exchange_id in ccxt.exchanges:
try:
exchange = getattr(ccxt, exchange_id)()
print(exchange_id)
# do what you want with this exchange
# pprint(dir(exchange))
except Exception as e:
print(e)
```
@@ -0,0 +1,136 @@
- [Arbitrage Pairs](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
def style(s, style):
return style + s + '\033[0m'
def green(s):
return style(s, '\033[92m')
def blue(s):
return style(s, '\033[94m')
def yellow(s):
return style(s, '\033[93m')
def red(s):
return style(s, '\033[91m')
def pink(s):
return style(s, '\033[95m')
def bold(s):
return style(s, '\033[1m')
def underline(s):
return style(s, '\033[4m')
def dump(*args):
print(' '.join([str(arg) for arg in args]))
def print_exchanges():
dump('Supported exchanges:', ', '.join(ccxt.exchanges))
def print_usage():
dump("Usage: python " + sys.argv[0], green('id1'), yellow('id2'), blue('id3'), '...')
proxies = [
'', # no proxy by default
'https://crossorigin.me/',
'https://cors-anywhere.herokuapp.com/',
]
if len(sys.argv) > 2:
ids = list(sys.argv[1:])
exchanges = {}
dump(ids)
dump(yellow(' '.join(ids)))
for id in ids: # load all markets from all exchange exchanges
# instantiate the exchange by id
exchange = getattr(ccxt, id)()
# save it in a dictionary under its id for future use
exchanges[id] = exchange
# load all markets from the exchange
markets = exchange.load_markets()
# basic round-robin proxy scheduler
currentProxy = -1
maxRetries = len(proxies)
for numRetries in range(0, maxRetries):
# try proxies in round-robin fashion
currentProxy = (currentProxy + 1) % len(proxies)
try: # try to load exchange markets using current proxy
exchange.proxy = proxies[currentProxy]
exchange.load_markets()
except ccxt.DDoSProtection as e:
dump(yellow(type(e).__name__), e.args)
except ccxt.RequestTimeout as e:
dump(yellow(type(e).__name__), e.args)
except ccxt.AuthenticationError as e:
dump(yellow(type(e).__name__), e.args)
except ccxt.ExchangeNotAvailable as e:
dump(yellow(type(e).__name__), e.args)
except ccxt.ExchangeError as e:
dump(yellow(type(e).__name__), e.args)
except ccxt.NetworkError as e:
dump(yellow(type(e).__name__), e.args)
except Exception as e: # reraise all other exceptions
raise
dump(green(id), 'loaded', green(str(len(exchange.symbols))), 'markets')
dump(green('Loaded all markets'))
allSymbols = [symbol for id in ids for symbol in exchanges[id].symbols]
# get all unique symbols
uniqueSymbols = list(set(allSymbols))
# filter out symbols that are not present on at least two exchanges
arbitrableSymbols = sorted([symbol for symbol in uniqueSymbols if allSymbols.count(symbol) > 1])
# print a table of arbitrable symbols
table = []
dump(green(' symbol | ' + ''.join([' {:<15} | '.format(id) for id in ids])))
dump(green(''.join(['-----------------+-' for x in range(0, len(ids) + 1)])))
for symbol in arbitrableSymbols:
string = ' {:<15} | '.format(symbol)
row = {}
for id in ids:
# if a symbol is present on a exchange print that exchange's id in the row
string += ' {:<15} | '.format(id if symbol in exchanges[id].symbols else '')
dump(string)
else:
print_usage()
```
+70
View File
@@ -0,0 +1,70 @@
- [Asciichart](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This file is a copied implementation from my asciichart repository on GitHub
# https://github.com/kroitor/asciichart
from math import cos
# from math import sin
from math import pi
from math import floor
from math import ceil
def plot(series, cfg={}):
minimum = min(series)
maximum = max(series)
interval = abs(float(maximum) - float(minimum))
offset = cfg['offset'] if 'offset' in cfg else 3
# padding = cfg['padding'] if 'padding' in cfg else ' '
height = cfg['height'] if 'height' in cfg else interval
ratio = height / interval
# print(minimum,ratio,type(minimum))
min2 = floor(float(minimum) * ratio)
max2 = ceil(float(maximum) * ratio)
intmin2 = int(min2)
intmax2 = int(max2)
rows = abs(intmax2 - intmin2)
width = len(series) + offset
# format = cfg['format'] if 'format' in cfg else lambda x: (padding + '{:.2f}'.format(x))[:-len(padding)]
result = [[' '] * width for i in range(rows + 1)]
# axis and labels
for y in range(intmin2, intmax2 + 1):
label = '{:8.2f}'.format(float(maximum) - ((y - intmin2) * interval / rows))
result[y - intmin2][max(offset - len(label), 0)] = label
result[y - intmin2][offset - 1] = '┼' if y == 0 else '┤'
y0 = int(series[0] * ratio - min2)
result[rows - y0][offset - 1] = '┼' # first value
for x in range(0, len(series) - 1): # plot the line
y0 = int(round(series[x + 0] * ratio) - intmin2)
y1 = int(round(series[x + 1] * ratio) - intmin2)
if y0 == y1:
result[rows - y0][x + offset] = '─'
else:
result[rows - y1][x + offset] = '╰' if y0 > y1 else '╭'
result[rows - y0][x + offset] = '╮' if y0 > y1 else '╯'
start = min(y0, y1) + 1
end = max(y0, y1)
for y in range(start, end):
result[rows - y][x + offset] = '│'
return '\n'.join([''.join(row) for row in result])
if __name__ == '__main__':
width = 180
series = [15 * cos(i * ((pi * 4) / width)) for i in range(width)]
print(plot(series))
```
@@ -0,0 +1,92 @@
- [Async Analyse Augur V1 Vs V2 Exchanges](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from typing import Optional
import ccxt.async_support as ccxt
unchecked_exchanges = []
def is_symbol_match(
symbol: str,
allowed_infix: str,
disallowed_infix: Optional[str] = None
) -> bool:
"""This function is to keep everything that has allowed_infix=REP, but
excpude everything that has disallowed_infix=DREP, except for when you encounter something like: REPV2/DREP
Returns True if this symbol is allowed to be in the list.
Args:
symbol (str): the symbol to evaluate
allowed_infix (str): the allowed infix for both currencies in this symbol
disallowed_infix (Optional[str], optional): the disallowed infix for when the other currency is does not have the allowed infix. Defaults to None.
Returns:
bool:
"""
parts = symbol.split('/')
if disallowed_infix:
for i, currency in enumerate(parts):
if disallowed_infix in currency:
# if one currency contains for instance disallowed_infix=DREP,
# then the other currency must contain allowed_infix=REP to be allowed, else disallow
return allowed_infix in parts[i + 1 % 2]
return any([allowed_infix in currency for currency in parts])
async def check_symbol_infix(exchange, symbol_infix, exclude_infix=None):
try:
await exchange.load_markets()
except Exception as exc:
# exchange could not load_markets for some reason...
unchecked_exchanges.append(exchange.id)
else:
matching_symbols = [
symbol for symbol in exchange.symbols
if is_symbol_match(symbol, symbol_infix, exclude_infix)
]
if matching_symbols:
print(
f'on exchange {exchange.id} these symbols contain {symbol_infix}:'
)
for symbol in matching_symbols:
print(f' - {symbol}:')
# print(f' exchange specific market info: {exchange.markets[symbol]["info"]}')
if 'V1' in symbol:
print(' - marked V1')
if 'V2' in symbol:
print(' - marked V2')
print()
await exchange.close()
async def main():
tasks = []
for exchange_id in ccxt.exchanges:
exchange = getattr(ccxt, exchange_id)()
tasks.append(
check_symbol_infix(
exchange, symbol_infix='REP', exclude_infix='DREP'
)
)
await asyncio.gather(*tasks)
print(f'errors for exchanges: {", ".join(unchecked_exchanges)}')
asyncio.run(main())
```
@@ -0,0 +1,29 @@
- [Async Balance Coinbasepro](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test():
exchange = ccxt.coinbasepro({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'password': "YOUR_PASSWORD",
'verbose': True, # switch it to False if you don't want the HTTP log
})
# move to sandbox
exchange.urls['api'] = exchange.urls['test']
print(await exchange.fetch_balance())
asyncio.run(test())
```
@@ -0,0 +1,29 @@
- [Async Balance Gdax](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test():
gdax = ccxt.gdax({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'password': "YOUR_PASSWORD",
'verbose': True, # switch it to False if you don't want the HTTP log
})
# move gdax to sandbox
gdax.urls['api'] = 'https://api-public.sandbox.gdax.com'
print(await gdax.fetch_balance())
asyncio.run(test())
```
@@ -0,0 +1,27 @@
- [Async Balance](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test():
bittrex = ccxt.bittrex({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'verbose': True, # switch it to False if you don't want the HTTP log
})
print(await bittrex.fetch_balance())
await bittrex.close()
asyncio.run(test())
```
@@ -0,0 +1,36 @@
- [Async Balances](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test(exchange):
print(await exchange.fetch_balance())
await exchange.close()
kraken = ccxt.kraken({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'verbose': True, # switch it to False if you don't want the HTTP log
})
bitfinex = ccxt.bitfinex({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'verbose': True, # switch it to False if you don't want the HTTP log
})
[asyncio.ensure_future(test(exchange)) for exchange in [kraken, bitfinex]]
pending = asyncio.Task.all_tasks()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*pending))
```
@@ -0,0 +1,81 @@
- [Async Basic Callchain](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def run_all_exchanges(exchange_ids):
results = {}
for exchange_id in exchange_ids:
exchange = getattr(ccxt, exchange_id)({
'options': {
'useWebapiForFetchingFees': False,
}
})
symbol = 'ETH/BTC'
print('Exchange:', exchange_id)
print(exchange_id, 'symbols:')
markets = await load_markets(exchange, symbol) # ←----------- STEP 1
print(list(markets.keys()))
print(symbol, 'ticker:')
ticker = await fetch_ticker(exchange, symbol) # ←------------ STEP 2
print(ticker)
print(symbol, 'orderbook:')
orderbook = await fetch_orderbook(exchange, symbol) # ←------ STEP 3
print(orderbook)
await exchange.close() # ←----------- LAST STEP GOES AFTER ALL CALLS
results[exchange_id] = ticker
return results
async def load_markets(exchange, symbol):
try:
result = await exchange.load_markets()
return result
except ccxt.BaseError as e:
print(type(e).__name__, str(e), str(e.args))
raise e
async def fetch_ticker(exchange, symbol):
try:
result = await exchange.fetch_ticker(symbol)
return result
except ccxt.BaseError as e:
print(type(e).__name__, str(e), str(e.args))
raise e
async def fetch_orderbook(exchange, symbol):
try:
result = await exchange.fetch_order_book(symbol)
return result
except ccxt.BaseError as e:
print(type(e).__name__, str(e), str(e.args))
raise e
if __name__ == '__main__':
exchange_ids = ['bitfinex', 'okex', 'exmo']
exchanges = []
results = asyncio.run(run_all_exchanges(exchange_ids))
print([(exchange_id, ticker) for exchange_id, ticker in results.items()])
```
@@ -0,0 +1,33 @@
- [Async Basic Orderbook](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test():
exchange = ccxt.okex({
# 'proxy': 'https://cors-anywhere.herokuapp.com/',
# 'origin': 'foobar', # when using CORS proxies, set this to some random string
})
try:
orderbook = await exchange.fetch_order_book('BTC/USDT')
await exchange.close()
return orderbook
except ccxt.BaseError as e:
print(type(e).__name__, str(e), str(e.args))
raise e
asyncio.run(test())
```
@@ -0,0 +1,25 @@
- [Async Basic Rate Limiter](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance()
for i in range(0, 100):
# this can be any call instead of fetch_ticker, really
print(await exchange.fetch_ticker('ETH/BTC'))
await exchange.close()
asyncio.run(main())
```
+25
View File
@@ -0,0 +1,25 @@
- [Async Basic](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test_binance():
exchange = ccxt.binance()
markets = await exchange.load_markets()
await exchange.close()
return markets
if __name__ == '__main__':
print(asyncio.run(test_binance()))
```
@@ -0,0 +1,44 @@
- [Async Binance Cancel Option Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
market_id = 'ETH-230214-1525-C'
symbol = 'ETH/USDT:USDT-230214-1525-C'
order_id = 4612100534317768959
try:
response = await exchange.cancel_order(order_id, symbol)
# Implicit API:
# response = await exchange.eapiPrivateDeleteOrder({
# 'symbol': market_id,
# 'orderId': order_id,
# })
pprint(response)
except Exception as e:
print('cancel_order() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,44 @@
- [Async Binance Create Margin Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
try:
# change the values here
symbol = 'BTC/USDT'
price = 9000
amount = 1
type = 'limit' # or market
side = 'buy'
order = await exchange.create_order(symbol, type, side, amount, price, {
'type': 'margin',
})
pprint(order)
except ccxt.InsufficientFunds as e:
print('create_order() failed  not enough funds')
print(e)
except Exception as e:
print('create_order() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,53 @@
- [Async Binance Create Option Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
symbol = 'ETH/USDT:USDT-221028-1700-C'
order_type = 'limit'
side = 'buy'
amount = 1
price = 2.1
try:
response = await exchange.create_order(symbol, order_type, side, amount, price)
# Implicit API:
# response = await exchange.eapiPrivatePostOrder({
# # ETH/USDT call option strike 1700 USDT expiry on 2022-10-28
# 'symbol': 'ETH-221028-1700-C',
# 'side': 'BUY',
# 'type': 'LIMIT',
# 'quantity': 1,
# 'price': 2.1,
# })
pprint(response)
except ccxt.InsufficientFunds as e:
print('create_order() failed - not enough funds')
print(e)
except Exception as e:
print('create_order() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,53 @@
- [Async Binance Create Trailing Percent Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binanceusdm({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
try:
# change the values here
symbol = 'BTC/USDT:USDT'
type = 'market'
side = 'sell'
amount = 0.1
price = None
order = await exchange.create_order(symbol, type, side, amount, price, {
'trailingPercent': 5,
'reduceOnly': True,
# 'trailingTriggerPrice': 45000,
})
# Or you can call the create_trailing_percent_order method:
# trailing_percent = 5
# trailing_trigger_price = 45000
# params = {
# 'reduceOnly': True,
# }
# order = await exchange.create_trailing_percent_order (symbol, type, side, amount, price, trailing_percent, trailing_trigger_price, params)
pprint(order)
except ccxt.InsufficientFunds as e:
print('create_order() failed - not enough funds')
print(e)
except Exception as e:
print('create_order() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,39 @@
- [Async Binance Fetch Margin Balance With Options](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
"options": {
"fetchBalance": "margin",
},
# set verbose mode to True for debugging output
# 'verbose': True,
})
while True:
try:
balance = await exchange.fetch_balance()
pprint(balance)
except Exception as e:
print('fetch_balance() failed')
print(e)
break
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,34 @@
- [Async Binance Fetch Margin Balance With Params](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
while True:
try:
balance = await exchange.fetch_balance({'type': 'margin'})
pprint(balance)
except Exception as e:
print('fetch_balance() failed')
print(e)
break
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,48 @@
- [Async Binance Fetch Option Ohlcv](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
market_id = 'ETH-221028-1700-C'
symbol = 'ETH/USDT:USDT-221028-1700-C'
timeframe = '1m'
since = 1592317127349
limit = 10
try:
response = await exchange.fetch_OHLCV(symbol, timeframe, since, limit)
# Implicit API:
# response = await exchange.eapiPublicGetKlines({
# 'symbol': market_id,
# 'interval': timeframe,
# # 'startTime': since, # optional
# # 'limit': limit, # optional
# })
pprint(response)
except Exception as e:
print('fetch_OHLCV() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,39 @@
- [Async Binance Fetch Option Details](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
market_id = 'ETH-221028-1700-C'
try:
response = await exchange.eapiPublicGetMark({
# 'symbol': market_id, # optional
})
pprint(response)
except Exception as e:
print('eapiPublicGetMark() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,46 @@
- [Async Binance Fetch Option Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
market_id = 'ETH-221028-1700-C'
symbol = 'ETH/USDT:USDT-221028-1700-C'
since = 1677102900000
limit = 10
order_id = 4612098335294532880
try:
response = await exchange.fetch_open_orders(symbol, since, limit)
# Implicit API:
# response = await exchange.eapiPrivateGetOpenOrders({
# # 'symbol': market_id, # optional
# # 'orderId': order_id, # optional
# })
pprint(response)
except Exception as e:
print('fetch_open_orders() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,44 @@
- [Async Binance Fetch Option Orderbook](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
market_id = 'ETH-221028-1500-C'
symbol = 'ETH/USDT:USDT-221028-1500-C'
limit = 10
try:
response = await exchange.fetch_order_book(symbol, limit)
# Implicit API:
# response = await exchange.eapiPublicGetDepth({
# 'symbol': market_id,
# # 'limit': limit, # optional
# })
pprint(response)
except Exception as e:
print('fetch_order_book() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,42 @@
- [Async Binance Fetch Option Position](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
market_id = 'ETH-221028-1700-C'
symbol = 'ETH/USDT:USDT-221028-1700-C'
try:
response = await exchange.fetch_position(symbol)
# Implicit API:
# response = await exchange.eapiPrivateGetPosition({
# # 'symbol': market_id, # optional
# })
pprint(response)
except Exception as e:
print('fetch_position() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,42 @@
- [Async Binance Fetch Option Ticker](./examples/py/)
```python
# -*- coding: utf-8 -*-
# This example uses the implicit API, in the future we will have options unified which will make things easier.
# You can check if the unified methods are ready-to-use (createOrder, fetchOrder etc) by checking: `is_unified = exchange.has['option']`
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
market_id = 'ETH-221028-1700-C'
symbol = 'ETH/USDT:USDT-221028-1700-C'
try:
response = await exchange.fetch_ticker(symbol)
# Implicit API:
# response = await exchange.eapiPublicGetTicker({
# # 'symbol': market_id, # optional
# })
pprint(response)
except Exception as e:
print('fetch_ticker() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,49 @@
- [Async Binance Fetch Ticker Continuously](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def main(symbol):
# you can set enableRateLimit = True to enable the built-in rate limiter
# this way you request rate will never hit the limit of an exchange
# the library will throttle your requests to avoid that
exchange = ccxt.binance()
while True:
print('--------------------------------------------------------------')
print(exchange.iso8601(exchange.milliseconds()), 'fetching', symbol, 'ticker from', exchange.name)
# this can be any call instead of fetch_ticker, really
try:
ticker = await exchange.fetch_ticker(symbol)
print(exchange.iso8601(exchange.milliseconds()), 'fetched', symbol, 'ticker from', exchange.name)
print(ticker)
except ccxt.RequestTimeout as e:
print('[' + type(e).__name__ + ']')
print(str(e)[0:200])
# will retry
except ccxt.DDoSProtection as e:
print('[' + type(e).__name__ + ']')
print(str(e.args)[0:200])
# will retry
except ccxt.ExchangeNotAvailable as e:
print('[' + type(e).__name__ + ']')
print(str(e.args)[0:200])
# will retry
except ccxt.ExchangeError as e:
print('[' + type(e).__name__ + ']')
print(str(e)[0:200])
break # won't retry
asyncio.run(main('BTC/USDT'))
```
@@ -0,0 +1,51 @@
- [Async Binance Futures Vs Spot](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def load(exchange, symbol, type='spot'):
exchange.options['defaultType'] = type
await exchange.load_markets(True)
try:
return {
'balance': await exchange.fetch_balance(),
# you actually want pagination here
# https://github.com/ccxt/ccxt/wiki/Manual#pagination
# but this will do as an example, tweak it for your needs
'orders': await exchange.fetch_orders(symbol),
'open orders': await exchange.fetch_open_orders(symbol),
'closed orders': await exchange.fetch_closed_orders(symbol),
'my trades': await exchange.fetch_my_trades(symbol),
}
except Exception as e:
print('\n\nError in load() with type =', type, '-', e)
raise e
async def run():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
symbol = 'BTC/USDT'
everything = {
'spot': await load(exchange, symbol, 'spot'),
'future': await load(exchange, symbol, 'future'),
}
await exchange.close()
return everything
asyncio.run(run())
```
@@ -0,0 +1,43 @@
- [Async Binance Margin Borrow](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
code = 'BTC'
amount = 1
currency = exchange.currency(code)
try:
response = await exchange.sapi_post_margin_loan({
'asset': currency['id'],
'amount': exchange.currency_to_precision(code, amount)
})
pprint(response)
except ccxt.InsufficientFunds as e:
print('sapi_post_margin_loan() failed  not enough funds')
print(e)
except Exception as e:
print('sapi_post_margin_loan() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,40 @@
- [Async Binance Margin Repay](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'verbose': True, # for debug output
})
await exchange.load_markets()
code = 'BTC'
amount = 1
currency = exchange.currency(code)
try:
response = await exchange.sapi_post_margin_repay({
'asset': currency['id'],
'amount': exchange.currency_to_precision(code, amount)
})
pprint(response)
except Exception as e:
print('sapi_post_margin_repay() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,50 @@
- [Async Binance Usdm Fetch Continuous Klines Ohlcv](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asyncio import run
import ccxt.async_support as ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
def table(values):
first = values[0]
keys = list(first.keys()) if isinstance(first, dict) else range(0, len(first))
widths = [max([len(str(v[k])) for v in values]) for k in keys]
string = ' | '.join(['{:<' + str(w) + '}' for w in widths])
return "\n".join([string.format(*[str(v[k]) for k in keys]) for v in values])
async def main():
exchange = ccxt.binanceusdm()
try:
await exchange.load_markets()
timeframe = '1m'
limit = 1
symbol = 'BTC/USDT'
market = exchange.market(symbol)
timeframe = '1m'
params = {
'pair': market['id'],
'contractType': 'PERPETUAL', # 'PERPETUAL', 'CURRENT_MONTH', 'NEXT_MONTH', 'CURRENT_QUARTER', 'NEXT_QUARTER'
'interval': exchange.timeframes[timeframe],
}
# https://binance-docs.github.io/apidocs/futures/en/#continuous-contract-kline-candlestick-data
ohlcvs = await exchange.fapiPublic_get_continuousklines(params)
print(table([o for o in ohlcvs]))
print(table([[exchange.iso8601(int(o[0]))] + o[1:] for o in ohlcvs]))
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
run(main())
```
@@ -0,0 +1,27 @@
- [Async Bitfinex Public Get Symbols](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test():
bitfinex = ccxt.bitfinex({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'verbose': True, # switch it to False if you don't want the HTTP log
})
print(await bitfinex.public_get_symbols())
await bitfinex.close()
asyncio.run(test())
```
@@ -0,0 +1,60 @@
- [Async Bitget Perpetual Futures Swaps](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asyncio import run
import ccxt.async_support as ccxt
async def main():
exchange = ccxt.bitget({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'password': 'YOUR_API_PASSWORD',
'options': {
'defaultType': 'swap',
}
})
try:
markets = await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
# fetching balance
balance = await exchange.fetch_balance()
print(balance['total'])
# placing a limit order
symbol = 'ETH/USDT:USDT'
type = 'limit'
side = 'buy'
amount = 1 # how many contracts to buy or sell, integer number of contracts
price = 3000
order = await exchange.create_order(symbol, type, side, amount, price)
print(order)
# placing a market order
symbol = 'ETH/USDT:USDT'
type = 'market'
side = 'sell'
amount = 1 # how many contracts to buy or sell, integer number of contracts
order = await exchange.create_order(symbol, type, side, amount)
print(order)
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
run(main())
```
@@ -0,0 +1,50 @@
- [Async Bitstamp Create Limit Buy Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test():
exchange = ccxt.bitstamp({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
response = None
try:
await exchange.load_markets() # force-preload markets first
exchange.verbose = True # this is for debugging
symbol = 'BTC/USD' # change for your symbol
amount = 1.0 # change the amount
price = 6000.00 # change the price
try:
response = await exchange.create_limit_buy_order(symbol, amount, price)
except Exception as e:
print('Failed to create order with', exchange.id, type(e).__name__, str(e))
except Exception as e:
print('Failed to load markets from', exchange.id, type(e).__name__, str(e))
await exchange.close()
return response
print(asyncio.run(test()))
```
@@ -0,0 +1,62 @@
- [Async Bitstamp Create Order Cancel Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
from asyncio import run
import ccxt.async_support as ccxt
from pprint import pprint
print('CCXT Version:', ccxt.__version__)
async def main():
exchange = ccxt.bitstamp({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'uid': 'YOUR_UID',
})
markets = await exchange.load_markets()
exchange.verbose = True # enable verbose mode after loading the markets
print('-------------------------------------------------------------------')
try:
balance = await exchange.fetch_balance()
pprint(balance)
except Exception as e:
print('Failed to fetch the balance')
print(type(e).__name__, str(e))
order = None
print('-------------------------------------------------------------------')
try:
symbol = 'BTC/USDT'
market = exchange.market(symbol)
base = market['base']
quote = market['quote']
pprint(balance[base])
pprint(balance[quote])
amount = 0.001
price = 40000
order_type = 'limit'
side = 'sell'
order = await exchange.create_order(symbol, order_type, side, amount, price)
pprint(order)
except Exception as e:
print('Failed to place', symbol, 'order')
print(type(e).__name__, str(e))
print('-------------------------------------------------------------------')
if order is not None:
try:
response = await exchange.cancel_order(order['id'], order['symbol'])
pprint(response)
except Exception as e:
print('Failed to cancel', symbol, 'order')
print(type(e).__name__, str(e))
print('-------------------------------------------------------------------')
await exchange.close()
run(main())
```
@@ -0,0 +1,33 @@
- [Async Bittrex Orderbook](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
if not sys.version >= '3.6':
print('This script requires Python 3.6+')
sys.exit()
import ccxt.async_support as ccxt # noqa: E402
async def poll():
exchange = ccxt.bittrex()
while True:
yield await exchange.fetch_order_book('BTC/USDT')
await asyncio.sleep(exchange.rateLimit / 1000)
async def main():
async for orderbook in poll():
print(orderbook['bids'][0], orderbook['asks'][0])
asyncio.run(main())
```
@@ -0,0 +1,36 @@
- [Async Bybit Transfer](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.bybit({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
try:
pprint(await exchange.fetch_transfers()) # Fetch your transfer history
# pprint(await exchange.transfer('USDT', 1.0, 'swap', 'spot')) # Transfer to the spot wallet
# pprint(await exchange.transfer('USDT', 1.0, 'spot', 'future')) # Transfer to the Derivatives wallet
# pprint(await exchange.transfer('USDT', 1.0, 'spot', 'swap')) # Transfer to the Derivatives wallet
# pprint(await exchange.transfer('USDC', 1.0, 'spot', 'option')) # Transfer to the USDC Derivatives wallet
except Exception as e:
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,34 @@
- [Async Fetch Balance](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test():
exchange = ccxt.bitstamp({
# "verbose": True, # useful for debugging purposes, uncomment if needed
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'uid': 'YOUR_UID',
# i'm adding a CORS proxy here, because my country is blocked by bitstamp
# you don't need this, so it's safe to comment it out
# "proxy": "https://cors-anywhere.herokuapp.com/",
# "origin": "bitstamp"
})
print(await exchange.fetch_balance())
await exchange.close() # don't forget to close it when you're done
return True
if __name__ == '__main__':
print('CCXT version:', ccxt.__version__)
print(asyncio.run(test()))
```
@@ -0,0 +1,51 @@
- [Async Fetch Many Orderbooks Continuously](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asyncio import gather, run
import ccxt.async_support as ccxt # noqa: E402
async def symbol_loop(exchange, symbol):
print('Starting the', exchange.id, 'symbol loop with', symbol)
while True:
try:
orderbook = await exchange.fetch_order_book(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
# --------------------> DO YOUR LOGIC HERE <------------------
except Exception as e:
print(str(e))
# raise e # uncomment to break all loops in case of an error in any one of them
break # you can break just this one loop if it fails
async def exchange_loop(exchange_id, symbols):
print('Starting the', exchange_id, 'exchange loop with', symbols)
exchange = getattr(ccxt, exchange_id)()
loops = [symbol_loop(exchange, symbol) for symbol in symbols]
await gather(*loops)
await exchange.close()
async def main():
exchanges = {
'okex': ['BTC/USDT', 'ETH/BTC', 'ETH/USDT'],
'binance': ['BTC/USDT', 'ETH/BTC'],
'bitfinex': ['BTC/USDT'],
}
loops = [exchange_loop(exchange_id, symbols) for exchange_id, symbols in exchanges.items()]
await gather(*loops)
run(main())
```
@@ -0,0 +1,62 @@
- [Async Fetch Ohlcv Indicators Discord Webhook](./examples/py/)
```python
from asyncio import run, gather, ensure_future
import pandas_ta as ta
import pandas as pd
import ccxt.async_support as ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
async def send_discord_webhook_messsage(exchange, symbol, message):
payload = {
"username": "Kj Bot Top 10 Coins 15 Min TF",
"content" : message
}
# change your webhook URL here
url = 'https://discord.com/api/webhooks/xxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
method = 'POST'
headers = {'Content-Type': 'application/json'}
body = exchange.json(payload)
try:
await exchange.fetch(url, method, headers, body)
except Exception as e:
print(type(e).__name__, str(e))
async def run_ohlcv_loop(exchange, symbol, timeframe, limit):
since = None
while True:
try:
ohlcv = await exchange.fetch_ohlcv(symbol, timeframe, since, limit)
if len(ohlcv):
df = pd.DataFrame(ohlcv, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
rsi = df.ta.rsi()
df = pd.concat([df,rsi], axis=1)
last_row = df.iloc[-1]
previous_row = df.iloc[-2]
if last_row['RSI_14'] and previous_row['RSI_14']:
now = exchange.milliseconds()
iso8601 = exchange.iso8601(now)
print(iso8601, timeframe, symbol, '\tRSI_14 =', last_row['RSI_14'])
rsienterob = previous_row['RSI_14'] < 70 and last_row['RSI_14'] > 70
if rsienterob:
message = iso8601 + ' ' + timeframe + ' ' + symbol + ' is entering overbought zone'
print(message)
ensure_future(send_discord_webhook_messsage(exchange, symbol, message))
except Exception as e:
print(type(e).__name__, str(e))
async def main():
exchange = ccxt.binance()
timeframe = '1m'
limit = 50
symbols = [ 'BTC/USDT', 'ETH/USDT' ]
loops = [run_ohlcv_loop(exchange, symbol, timeframe, limit) for symbol in symbols]
await gather(*loops)
await exchange.close()
run(main())
```
@@ -0,0 +1,41 @@
- [Async Fetch Ohlcv Multiple Symbols Continuously](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asyncio import run, gather
import ccxt.async_support as ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
async def fetch_ohlcv(exchange, symbol, timeframe, limit):
since = None
while True:
try:
ohlcv = await exchange.fetch_ohlcv(symbol, timeframe, since, limit)
if len(ohlcv):
first_candle = ohlcv[0]
datetime = exchange.iso8601(first_candle[0])
print(datetime, exchange.id, symbol, first_candle[1:])
except Exception as e:
print(type(e).__name__, str(e))
async def main():
exchange = ccxt.binance()
timeframe = '1m'
limit = 1
symbols = [ 'BTC/USDT', 'ETH/USDT' ]
loops = [fetch_ohlcv(exchange, symbol, timeframe, limit) for symbol in symbols]
await gather(*loops)
await exchange.close()
run(main())
```
@@ -0,0 +1,54 @@
- [Async Fetch Order Book From Many Exchanges](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
exchange_ids = [ 'binance', 'kucoin', 'huobipro' ]
symbol = 'ETH/BTC'
async def loop(exchange_id, symbol):
exchange_class = getattr(ccxt, exchange_id)
exchange = exchange_class()
orderbook = {}
try:
await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes
orderbook = await exchange.fetch_order_book(symbol)
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
return exchange.extend (orderbook, {
'exchange_id': exchange_id,
'symbol': symbol,
})
async def run(exchange_ids, symbol):
coroutines = [loop(exchange_id, symbol) for exchange_id in exchange_ids]
return await asyncio.gather(*coroutines)
main = run(exchange_ids, symbol)
results = asyncio.run(main)
for result in results:
bids = result['bids']
asks = result['asks']
print(
result['exchange_id'],
result['symbol'],
'top bid', bids[0], 'of', len(bids), 'bids,',
'top ask', asks[0], 'of', len(asks), 'asks'
)
```
@@ -0,0 +1,17 @@
- [Async Fetch Ticker](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
pprint(asyncio.run(ccxt.binance().fetch_ticker('ETH/BTC')))
```
@@ -0,0 +1,78 @@
- [Async Gather Concurrency](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def work(exchange_id):
# create it once per program lifetime
exchange = getattr(ccxt, exchange_id)()
print(exchange_id, 'loaded')
try:
# load markets once, first and foremost
# https://github.com/ccxt/ccxt/wiki/Manual#loading-markets
await exchange.load_markets()
# use the same exchange instance to iterate over loaded symbols
# https://github.com/ccxt/ccxt/wiki/Manual#symbols-and-market-ids
for symbol in exchange.symbols:
try:
# fetch the orderbook for each next symbol
orderbook = await exchange.fetch_order_book(symbol)
# ADD YOUR SUCCESS HANDLING HERE
print(exchange_id, 'fetched', symbol, 'orderbook')
except Exception as e:
# ADD YOUR ERROR HANDLING HERE
# https://github.com/ccxt/ccxt/wiki/Manual#error-handling
print(exchange_id, 'could not fetch', symbol, 'orderbook:', type(e).__name__)
except Exception as e:
# ADD YOUR ERROR HANDLING HERE
print(exchange_id, 'could not load markets:', type(e).__name__)
# when you're done, don't forget to close the exchange instance properly
# otherwise you will get "Unclosed client session" exception
await exchange.close()
async def main():
# https://stackoverflow.com/questions/48483348/limited-concurrency-with-asyncio
max_concurrency = 5 # how many exchanges at once
tasks = set()
loop = asyncio.get_running_loop()
# loop over all exchanges
for exchange_id in ccxt.exchanges:
# wait for some exchange to finish before adding a new one
if len(tasks) >= max_concurrency:
_done, tasks = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
tasks.add(loop.create_task(work(exchange_id)))
# wait for the remaining exchanges to finish
await asyncio.wait(tasks)
asyncio.run(main())
```
@@ -0,0 +1,28 @@
- [Async Gdax Fetch Order Book Continuously](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def main(symbol):
exchange = ccxt.binance()
while True:
print('--------------------------------------------------------------')
print(exchange.iso8601(exchange.milliseconds()), 'fetching', symbol, 'ticker from', exchange.name)
# this can be any call really
ticker = await exchange.fetch_order_book(symbol)
print(exchange.iso8601(exchange.milliseconds()), 'fetched', symbol, 'ticker from', exchange.name)
print(ticker)
asyncio.run(main('BTC/USDT'))
```
@@ -0,0 +1,28 @@
- [Async Generator Basic](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def poll():
exchange = ccxt.poloniex()
while True:
yield await exchange.fetch_ticker('ETH/BTC')
async def main():
async for ticker in poll():
print(ticker)
asyncio.run(main())
```
@@ -0,0 +1,28 @@
- [Async Generator Multiple Tickers](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import ccxt.async_support as ccxt
async def poll(tickers):
i = 0
kraken = ccxt.kraken()
while True:
symbol = tickers[i % len(tickers)]
yield (symbol, await kraken.fetch_ticker(symbol))
i += 1
await asyncio.sleep(kraken.rateLimit / 1000)
async def main():
async for (symbol, ticker) in poll(['BTC/USD', 'ETH/BTC', 'BTC/EUR']):
print(symbol, ticker)
asyncio.run(main())
```
@@ -0,0 +1,33 @@
- [Async Generator Ticker Poller](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def poll():
kraken = ccxt.kraken({
'apiKey': "hEvQNMDIeoCJbr7W/ZBb5CGOrx3G0lWF5B3zqa1JBxdZlEaL8EK+D0Mw",
'secret': "JaE9wI6Nwgh5oRxiHcVxurwzwBxwc05W/qv/k1srGg4s3EYuXPpNkLLM5NYbbWpM8rCyijIeDavRuqWbU0ZV9A==",
# 'verbose': True, # switch it to False if you don't want the HTTP log
})
while True:
yield await kraken.fetch_ticker('BTC/USD')
await asyncio.sleep(kraken.rateLimit / 1000)
async def main():
async for ticker in poll():
print(ticker)
asyncio.run(main())
```
@@ -0,0 +1,37 @@
- [Async Hollaex Sandbox](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asyncio import run
async def test():
import ccxt.async_support as ccxt
print('CCXT Version', ccxt.__version__)
# local sandbox keys
exchange = ccxt.hollaex({
'apiKey': "YOUR_SANDBOX_API_KEY",
'secret': "YOUR_SANDBOX_SECRET",
})
exchange.set_sandbox_mode(True)
markets = await exchange.load_markets()
exchange.verbose = True
balance = await exchange.fetch_balance()
print(f"balance: {balance}")
await exchange.close()
run(test())
```
@@ -0,0 +1,29 @@
- [Async Instantiate All At Once](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import asyncio
import ccxt.async_support as ccxt # noqa: E402
exchanges = {} # a placeholder for your instances
async def main():
for id in ccxt.exchanges:
exchange = getattr(ccxt, id)
exchanges[id] = exchange()
# now exchanges dictionary contains all exchange instances...
print(await exchanges['bittrex'].fetch_order_book('ETH/BTC'))
# close the aiohttp session object
for id in exchanges:
await exchanges[id].close()
asyncio.run(main())
```
@@ -0,0 +1,47 @@
- [Async Kucoin Rate Limit](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asyncio import run
import ccxt.async_support as ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
async def main():
exchange = ccxt.kucoin()
markets = await exchange.load_markets()
i = 0
while True:
try:
symbol = 'BTC/USDT'
timeframe = '5m'
since = None
limit = 1000
ohlcvs = await exchange.fetch_ohlcv(symbol, timeframe, since, limit)
now = exchange.milliseconds()
datetime = exchange.iso8601(now)
print(datetime, i, 'fetched', len(ohlcvs), symbol, timeframe, 'candles',
'from', exchange.iso8601(ohlcvs[0][0]),
'to', exchange.iso8601(ohlcvs[len(ohlcvs)-1][0]))
except ccxt.RateLimitExceeded as e:
now = exchange.milliseconds()
datetime = exchange.iso8601(now)
print(datetime, i, type(e).__name__, str(e))
await exchange.sleep(10000)
except Exception as e:
print(type(e).__name__, str(e))
raise e
i += 1
run (main())
```
+52
View File
@@ -0,0 +1,52 @@
- [Async Macd](./examples/py/)
```python
# -*- coding: utf-8 -*-
from asyncio import gather, run
import pandas_ta as ta
import pandas as pd
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
async def run_ohlcv_loop(exchange, symbol, timeframe, limit):
since = None
fast = 12
slow = 26
signal = 9
while True:
try:
ohlcv = await exchange.fetch_ohlcv(symbol, timeframe, since, limit)
if len(ohlcv):
df = pd.DataFrame(ohlcv, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
macd = df.ta.macd(fast=fast, slow=slow, signal=signal)
df = pd.concat([df, macd], axis=1)
print('----------------------------------------------------------')
print(exchange.iso8601(exchange.milliseconds()), symbol, timeframe)
print(df[-signal:])
except Exception as e:
print(type(e).__name__, str(e))
async def main():
exchange = ccxt.binance()
timeframe = '1m'
limit = 50
symbols = [
'BTC/USDT',
'ETH/USDT',
]
loops = [run_ohlcv_loop(exchange, symbol, timeframe, limit) for symbol in symbols]
await gather(*loops)
await exchange.close()
run(main())
```
@@ -0,0 +1,43 @@
- [Async Market Making Symbols](./examples/py/)
```python
# -*- coding: utf-8 -*-
from asyncio import gather, run
from pprint import pprint
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def load_markets(exchange):
results = None
try:
await exchange.load_markets()
print('Loaded', len(exchange.symbols), exchange.id, 'symbols')
results = []
for market in exchange.markets.values():
if market['maker'] <= 0:
results.append({'exchange': exchange.id, 'symbol': market['symbol']})
if len(results) < 1:
results = None
except:
results = None
await exchange.close()
return results
async def main():
exchanges = [getattr(ccxt, exchange_id)() for exchange_id in ccxt.exchanges]
# exchanges = [exchange for exchange in exchanges if exchange.certified]
results = await gather(*[load_markets(exchange) for exchange in exchanges])
results = [result for result in results if result is not None]
pprint(results)
run(main())
```
@@ -0,0 +1,37 @@
- [Async Multiple Accounts](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def fetch_balance_n_times(code, account, n):
exchange_class = getattr(ccxt, account['exchange_id'])
exchange = exchange_class(account['params'])
for i in range(0, n):
balance = await exchange.fetch_balance()
print(exchange.id, code, 'balance:', balance[code])
await exchange.close()
async def test():
n = 10 # fetch 10 times
code = 'BTC'
accounts = [
{'exchange_id': 'binance', 'params': {'id': 'Binance1', 'apiKey': 'YOUR_API_KEY_1', 'secret': 'YOUR_API_SECRET_1'}},
{'exchange_id': 'binance', 'params': {'id': 'Binance2', 'apiKey': 'YOUR_API_KEY_2', 'secret': 'YOUR_API_SECRET_2'}},
]
coroutines = [fetch_balance_n_times(code, account, n) for account in accounts]
await asyncio.gather(*coroutines)
if __name__ == '__main__':
asyncio.run(test())
```
@@ -0,0 +1,56 @@
- [Async Multiple Parallel Calls](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt.async_support as ccxt
from asyncio import run, gather
print('CCXT Version:', ccxt.__version__)
# This example demonstrates how to execute multiple requests asynchronously.
# The requests will be executed in parallel independently of each other.
# In order to let them run in parallel the user has to disable the rate limiter.
# Disabling the rate limiter is not recommended, unless you really know
# what you are doing! If you are too aggressive with your requests and
# you don't do proper request timing precisely, the exchange can ban you!
# https://github.com/ccxt/ccxt/wiki/
# https://github.com/ccxt/ccxt/wiki/Manual
# https://github.com/ccxt/ccxt/wiki/Manual#rate-limit
async def main():
exchange = ccxt.ftx({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'enableRateLimit': False, # not recommended
})
markets = await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes
symbol = 'BTC/USDT'
loops = [
exchange.fetch_balance(),
exchange.fetch_order_book(symbol),
exchange.fetch_open_orders()
]
results = await gather(*loops)
print('Balance:')
print(results[0])
print('------------------------------------------------------------------')
print(symbol, 'orderbook:')
print(results[1])
print('------------------------------------------------------------------')
print('Open orders:')
print(results[2])
await exchange.close()
run(main())
```
@@ -0,0 +1,47 @@
- [Async Okx Create Margin Order](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.okx({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# okx requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication
'password': 'YOUR_API_PASSWORD',
# 'verbose': True, # for debug output
})
try:
# change the values here
symbol = 'BTC/USDT'
price = 123.45
amount = 54.321
type = 'limit' # or market
side = 'sell'
order = await exchange.create_order(symbol, type, side, amount, price, {
'margin': True,
'marginMode': 'cross',
})
pprint(order)
except ccxt.InsufficientFunds as e:
print('create_order() failed  not enough funds')
print(e)
except Exception as e:
print('create_order() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,41 @@
- [Async Okx Margin Borrow](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.okx({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# okx requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication
'password': 'YOUR_API_PASSWORD',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
code = 'BTC'
amount = 1
try:
response = await exchange.borrowCrossMargin(code, amount)
pprint(response)
except ccxt.InsufficientFunds as e:
print('borrowCrossMargin() failed  not enough funds')
print(e)
except Exception as e:
print('borrowCrossMargin() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,44 @@
- [Async Okx Margin Repay](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def main():
exchange = ccxt.okx({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# okx requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication
'password': 'YOUR_API_PASSWORD',
# 'verbose': True, # for debug output
})
await exchange.load_markets()
code = 'BTC'
amount = 1
order_id = 'YOUR_ORDER_ID_FROM_BORROWING'
try:
response = await exchange.repayCrossMargin(code, amount, {
'ordId': order_id,
})
pprint(response)
except ccxt.InsufficientFunds as e:
print('repayCrossMargin() failed  not enough funds')
print(e)
except Exception as e:
print('repayCrossMargin() failed')
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,64 @@
- [Async Okx Positional Orders](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
from pprint import pprint
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
# or
# import ccxtpro as ccxt
print('CCXT Version:', ccxt.__version__)
async def main():
exchange = ccxt.okx({
'apiKey': 'YOUR_API_KEY', # https://github.com/ccxt/ccxt/wiki/Manual#authentication
'secret': 'YOUR_API_SECRET',
'password': 'YOUR_API_PASSWORD',
'options': {
'defaultType': 'future',
},
})
try:
markets = await exchange.load_markets()
exchange.verbose = True # uncomment for debugging
print('---------------------------------------------------------------')
print('Futures balance:')
futures_balance = await exchange.fetch_balance()
pprint(futures_balance)
print('---------------------------------------------------------------')
print('Futures symbols:')
print([market['symbol'] for market in markets.values() if market['future']])
print('---------------------------------------------------------------')
symbol = 'BTC/USDT:USDT-201225' # a futures symbol
market = exchange.market(symbol)
pprint(market)
print('---------------------------------------------------------------')
type = '1' # 1:open long 2:open short 3:close long 4:close short for futures
side = None # irrelevant for futures
amount = 1 # how many contracts you want to buy or sell
price = 17000 # limit price
params = {
# 'order_type': '4', # uncomment for a market order, makes limit price irrelevant
# 'leverage': '10', # or '20'
}
order = await exchange.create_order(symbol, type, side, amount, price, params)
print('Order:')
pprint(order)
print('---------------------------------------------------------------')
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,64 @@
- [Async Orderbooks From Multiple Exchanges At Once](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import ccxt
import ccxt.async_support as ccxta # noqa: E402
import time
import os
import sys
symbol = 'ETH/BTC'
def sync_client(exchange_id):
orderbook = None
exchange = getattr(ccxt, exchange_id)()
try:
exchange.load_markets()
market = exchange.market(symbol)
orderbook = exchange.fetch_order_book(market['symbol'])
except Exception as e:
print(type(e).__name__, str(e))
return { 'exchange': exchange.id, 'orderbook': orderbook }
async def async_client(exchange_id):
orderbook = None
exchange = getattr(ccxta, exchange_id)()
try:
await exchange.load_markets()
market = exchange.market(symbol)
orderbook = await exchange.fetch_order_book(market['symbol'])
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
return { 'exchange': exchange.id, 'orderbook': orderbook }
async def multi_orderbooks(exchanges):
input_coroutines = [async_client(exchange) for exchange in exchanges]
orderbooks = await asyncio.gather(*input_coroutines, return_exceptions=True)
return orderbooks
if __name__ == '__main__':
# Consider review request rate limit in the methods you call
exchanges = ["kucoin", "bittrex", "bitfinex", "poloniex", "huobipro"]
tic = time.time()
a = asyncio.run(multi_orderbooks(exchanges))
print("async call spend:", time.time() - tic)
time.sleep(1)
tic = time.time()
a = [sync_client(exchange) for exchange in exchanges]
print("sync call spend:", time.time() - tic)
```
@@ -0,0 +1,47 @@
- [Async Orderbooks](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import ccxt
import ccxt.async_support as ccxta # noqa: E402
import time
import os
import sys
async def async_client(exchange, symbol):
client = getattr(ccxta, exchange)()
await client.load_markets()
if symbol not in client.symbols:
raise Exception(exchange + ' does not support symbol ' + symbol)
while True:
try:
orderbook = await client.fetch_order_book(symbol)
datetime = client.iso8601(client.milliseconds())
print(datetime, client.id, symbol, orderbook['bids'][0], orderbook['asks'][0])
except Exception as e:
print(type(e).__name__, e.args, str(e)) # comment if not needed
# break # uncomment to break it
# pass # uncomment to do nothing and just retry again on next iteration
# or add your own reaction according to the purpose of your app
await client.close()
async def multi_orderbooks(exchanges, symbol):
input_coroutines = [async_client(exchange, symbol) for exchange in exchanges]
await asyncio.gather(*input_coroutines, return_exceptions=True)
if __name__ == '__main__':
# Consider review request rate limit in the methods you call
exchanges = ["bittrex", "bitfinex", "poloniex"]
symbol = 'ETH/BTC'
asyncio.run(multi_orderbooks(exchanges, symbol))
```
+80
View File
@@ -0,0 +1,80 @@
- [Async Rtt](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asyncio import run
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
# or
# import ccxtpro as ccxt # if you're using ccxtpro
# WARNING!
# This example measures the round-trip time when placing orders with an exchange
# In order to measure the speed of requests it disables the rate-limiting
# Disabling the rate-limiter is required to do an accurate measurement
# If you keep running without a rate limiter for a long time the exchange will ban you
# In a live production system always use either the built-in rate limiter or make your own
async def main():
# the exchange instance has to be reused
# do not recreate the exchange before each call!
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_API_SECRET',
# 'uid': 'YOUR_UID', # some exchanges require this
# 'password': 'YOUR_API_PASSWORD', # some exchanges require this
# if you do not rate-limit your requests the exchange can ban you!
'enableRateLimit': False, # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit
})
await exchange.load_markets() # https://github.com/ccxt/ccxt/wiki/Manual#loading-markets
# exchange.verbose = True # uncomment for debugging purposes if needed
symbol = 'BTC/USDC'
market = exchange.market(symbol)
ticker = await exchange.fetch_ticker(symbol)
amount = market['limits']['amount']['min']
# we will place limit buy order at 3/4 of the price to make sure they're not triggered
price = ticker['last'] * 0.8
amount = round(market['limits']['cost']['min'] / price, 4)
results = []
for i in range(0, 10):
started = exchange.milliseconds()
order = await exchange.create_order(symbol, 'limit', 'buy', amount, price)
ended = exchange.milliseconds()
elapsed = ended - started
results.append(elapsed)
await exchange.cancel_order(order['id'], order['symbol'])
pprint(order)
pprint(results)
rtt = int(sum(results) / len(results))
print('Successfully tested 10 orders, the average round-trip time per order is', rtt, 'milliseconds')
await exchange.close()
run(main())
```
@@ -0,0 +1,33 @@
- [Async Theocean Orderbook](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
if not sys.version >= '3.6':
print('This script requires Python 3.6+')
sys.exit()
import ccxt.async_support as ccxt # noqa: E402
async def poll():
exchange = ccxt.theocean()
while True:
yield await exchange.fetch_order_book('WETH/TUSD')
await asyncio.sleep(exchange.rateLimit / 1000)
async def main():
async for orderbook in poll():
print(orderbook['bids'][0], orderbook['asks'][0])
asyncio.run(main())
```
@@ -0,0 +1,47 @@
- [Async Theocean Tickers](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
def get_active_symbols(exchange):
return [symbol for symbol in exchange.symbols if is_active_symbol(exchange, symbol)]
def is_active_symbol(exchange, symbol):
return ('.' not in symbol) and (('active' not in exchange.markets[symbol]) or (exchange.markets[symbol]['active']))
async def fetch_ticker(exchange, symbol):
ticker = await exchange.fetchTicker(symbol)
print(exchange.id, symbol, ticker)
return ticker
async def fetch_tickers(id):
exchange = getattr(ccxt, id)()
await exchange.load_markets()
print(exchange.id, 'fetching all tickers by simultaneous multiple concurrent requests')
symbols_to_load = get_active_symbols(exchange)
input_coroutines = [fetch_ticker(exchange, symbol) for symbol in symbols_to_load]
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
for ticker, symbol in zip(tickers, symbols_to_load):
if not isinstance(ticker, dict):
print(exchange.id, symbol, 'error')
else:
print(exchange.id, symbol, 'ok')
print(exchange.id, 'fetched', len(list(tickers)), 'tickers')
await exchange.close()
asyncio.run(fetch_tickers('theocean'))
```
@@ -0,0 +1,28 @@
- [Async Ticker](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
async def test(id, symbol):
exchange = getattr(ccxt, id)()
ticker = await exchange.fetch_ticker(symbol)
await exchange.close()
return ticker
if __name__ == '__main__':
id = 'binance'
symbol = 'ETH/BTC'
pprint(asyncio.run(test(id, symbol)))
```
@@ -0,0 +1,50 @@
- [Async Tickers From Many Exchanges At Once](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import ccxt
import ccxt.async_support as ccxta # noqa: E402
import time
import os
import sys
def sync_client(exchange):
client = getattr(ccxt, exchange)()
tickers = client.fetch_tickers()
return tickers
async def async_client(exchange):
client = getattr(ccxta, exchange)()
tickers = await client.fetch_tickers()
await client.close()
return tickers
async def multi_tickers(exchanges):
input_coroutines = [async_client(exchange) for exchange in exchanges]
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
return tickers
if __name__ == '__main__':
# Consider review request rate limit in the methods you call
exchanges = ["coinex", "bittrex", "bitfinex", "poloniex", "hitbtc"]
tic = time.time()
a = asyncio.run(multi_tickers(exchanges))
print("async call spend:", time.time() - tic)
time.sleep(1)
tic = time.time()
a = [sync_client(exchange) for exchange in exchanges]
print("sync call spend:", time.time() - tic)
```
@@ -0,0 +1,45 @@
- [Async Tickers](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
def get_active_symbols(exchange):
return [symbol for symbol in exchange.symbols if is_active_symbol(exchange, symbol)]
def is_active_symbol(exchange, symbol):
return ('.' not in symbol) and (('active' not in exchange.markets[symbol]) or (exchange.markets[symbol]['active']))
async def fetch_ticker(exchange, symbol):
ticker = await exchange.fetchTicker(symbol)
print(exchange.id, symbol, ticker)
return ticker
async def fetch_tickers(exchange):
await exchange.load_markets()
print(exchange.id, 'fetching all tickers by simultaneous multiple concurrent requests')
symbols_to_load = get_active_symbols(exchange)
input_coroutines = [fetch_ticker(exchange, symbol) for symbol in symbols_to_load]
tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
for ticker, symbol in zip(tickers, symbols_to_load):
if not isinstance(ticker, dict):
print(exchange.id, symbol, 'error')
else:
print(exchange.id, symbol, 'ok')
print(exchange.id, 'fetched', len(list(tickers)), 'tickers')
asyncio.run(fetch_tickers(ccxt.bitfinex()))
```
@@ -0,0 +1,42 @@
- [Async With Threads](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import threading
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def test(loop):
exchange = ccxt.bittrex({
'asyncio_loop': loop,
})
print(await exchange.fetch_ticker('ETH/BTC'))
await exchange.close()
def function_in_a_thread():
# get_event_loop doesn't work inside a thread
loop = asyncio.new_event_loop()
loop.run_until_complete(test(loop))
def another_threaded_function():
global_loop.run_until_complete(test(global_loop))
global_loop = asyncio.get_event_loop()
thread = threading.Thread(target=function_in_a_thread)
thread2 = threading.Thread(target=another_threaded_function)
thread.start()
thread2.start()
thread.join()
thread2.join()
```
+38
View File
@@ -0,0 +1,38 @@
- [Async](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import functools
import os
import sys
import ccxt.async_support as ccxt # noqa: E402
async def print_ticker(symbol, id):
# verbose mode will show the order of execution to verify concurrency
exchange = getattr(ccxt, id)({'verbose': True})
print(await exchange.fetch_ticker(symbol))
await exchange.close()
if __name__ == '__main__':
symbol = 'ETH/BTC'
print_ethbtc_ticker = functools.partial(print_ticker, symbol)
[asyncio.ensure_future(print_ethbtc_ticker(id)) for id in [
'bitfinex',
'poloniex',
'kraken',
'bittrex',
'hitbtc',
]]
loop = asyncio.get_event_loop()
pending = asyncio.all_tasks(loop)
loop.run_until_complete(asyncio.gather(*pending))
```
@@ -0,0 +1,25 @@
- [Balance Coinbasepro](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.coinbasepro({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'password': 'zdmj8o7byla',
'verbose': True, # switch it to False if you don't want the HTTP log
})
# move to sandbox
exchange.urls['api'] = exchange.urls['test']
print(exchange.fetch_balance())
```
@@ -0,0 +1,25 @@
- [Balance Gdax](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
gdax = ccxt.gdax({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'password': "YOUR_PASSWORD",
'verbose': True, # switch it to False if you don't want the HTTP log
})
# move gdax to sandbox
gdax.urls['api'] = 'https://api-public.sandbox.gdax.com'
print(gdax.fetch_balance())
```
@@ -0,0 +1,21 @@
- [Balance Kraken](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
kraken = ccxt.kraken({
'apiKey': "YOUR_API_KEY",
'secret': "YOUR_SECRET",
'verbose': True, # switch it to False if you don't want the HTTP log
})
print(kraken.fetch_balance())
```
+87
View File
@@ -0,0 +1,87 @@
- [Balances](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
def style(s, style):
return style + s + '\033[0m'
def green(s):
return style(s, '\033[92m')
def blue(s):
return style(s, '\033[94m')
def yellow(s):
return style(s, '\033[93m')
def red(s):
return style(s, '\033[91m')
def pink(s):
return style(s, '\033[95m')
def bold(s):
return style(s, '\033[1m')
def underline(s):
return style(s, '\033[4m')
def dump(*args):
print(' '.join([str(arg) for arg in args]))
# instantiate exchanges
coinbasepro = ccxt.coinbasepro({
'apiKey': '92560ffae9b8a01d012726c698bcb2f1', # standard
'secret': '9aHjPmW+EtRRKN/OiZGjXh8OxyThnDL4mMDre4Ghvn8wjMniAr5jdEZJLN/knW6FHeQyiz3dPIL5ytnF0Y6Xwg==',
'password': '6kszf4aci8r', # requires a password!
})
coinbasepro.urls['api'] = coinbasepro.urls['test'] # use the testnet
hitbtc = ccxt.hitbtc({
'apiKey': '18339694544745d9357f9e7c0f7c41bb',
'secret': '8340a60fb4e9fc73a169c26c7a7926f5',
})
try:
# fetch account balance from the exchange
coinbaseproBalance = coinbasepro.fetch_balance()
# output the result
dump(green(coinbasepro.name), 'balance', coinbaseproBalance)
# fetch another one
hitbtcBalance = hitbtc.fetch_balance()
# output the result
dump(green(hitbtc.name), 'balance', hitbtcBalance)
except ccxt.DDoSProtection as e:
print(type(e).__name__, e.args, 'DDoS Protection (ignoring)')
except ccxt.RequestTimeout as e:
print(type(e).__name__, e.args, 'Request Timeout (ignoring)')
except ccxt.ExchangeNotAvailable as e:
print(type(e).__name__, e.args, 'Exchange Not Available due to downtime or maintenance (ignoring)')
except ccxt.AuthenticationError as e:
print(type(e).__name__, e.args, 'Authentication Error (missing API keys, ignoring)')
```
+45
View File
@@ -0,0 +1,45 @@
- [Basic Chart](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from asciichart import plot
import ccxt # noqa: E402
kraken = ccxt.kraken()
coinbasepro = ccxt.coinbasepro()
symbol = 'BTC/USD'
# each ohlcv candle is a list of [ timestamp, open, high, low, close, volume ]
index = 4 # use close price from each ohlcv candle
def print_chart(exchange, symbol, timeframe):
print("\n" + exchange.name + ' ' + symbol + ' ' + timeframe + ' chart:')
# get a list of ohlcv candles
ohlcv = exchange.fetch_ohlcv(symbol, timeframe)
# get the ohlCv (closing price, index == 4)
series = [x[index] for x in ohlcv]
# print the chart
print("\n" + plot(series[-120:], {'height': 20})) # print the chart
last = ohlcv[len(ohlcv) - 1][index] # last closing price
return last
last = print_chart(kraken, 'BTC/USD', '1h')
print("\n" + kraken.name + " ₿ = $" + str(last) + "\n") # print last closing price
last = print_chart(coinbasepro, 'BTC/USD', '1h')
print("\n" + coinbasepro.name + " ₿ = $" + str(last) + "\n") # print last closing price
```
@@ -0,0 +1,29 @@
- [Basic Rate Limiting](./examples/py/)
```python
# -*- coding: utf-8 -*-
from pprint import pprint
import os
import sys
import ccxt # noqa: E402
symbol = 'ETH/BTC'
exchange = ccxt.poloniex({
'enableRateLimit': True, # enabled by default
})
# print 10 times with appropriate delay
for i in range(0, 10):
print('--------------------------------------------------------------------')
ticker = exchange.fetch_ticker(symbol)
ticker = exchange.omit(ticker, 'info')
pprint(ticker)
```
@@ -0,0 +1,37 @@
- [Binance Batch Orders](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binance({
"apiKey": "YOUR_API_KEY",
"secret": "YOUR_SECRET",
})
orders = [
{
"symbol" : "BTCUSDT",
"side" : "BUY",
"positionSide" : "LONG",
"type" : "MARKET",
"quantity": float(0.005)
}
]
orders = [exchange.encode_uri_component(exchange.json(order), safe=",") for order in orders]
response = exchange.fapiPrivatePostBatchOrders({
'batchOrders': '[' + ','.join(orders) + ']'
})
print(response)
```
@@ -0,0 +1,42 @@
- [Binance Coin Margined Take Profit](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binancecoinm({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = exchange.load_markets()
exchange.verbose = True # uncomment for debugging purposes if necessary
# edit for your values below
symbol = 'EOS/USD'
order_type = 'TAKE_PROFIT'
side = 'sell'
amount = YOUR_AMOUNT_HERE
price = YOUR_LIMIT_PRICE_HERE
stopPrice = YOUR_STOP_PRICE
params = {'stopPrice': stopPrice}
try:
order = exchange.create_order(symbol, order_type, side, amount, price, params)
print(order)
except Exception as e:
print(type(e).__name__, str(e))
```
@@ -0,0 +1,50 @@
- [Binance Conditional Orders](./examples/py/)
```python
import ccxt
from pprint import pprint
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binanceusdm({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_API_SECRET',
})
print('Loading markets from', exchange.id)
exchange.load_markets()
print('Loaded markets from', exchange.id)
exchange.verbose = True
symbol = 'ETH/USDT'
type = 'market'
side = 'buy' # long
amount = 10
order1 = exchange.create_order(symbol, 'market', 'buy', amount)
order1_price = order1['price']
if order1_price is None:
order1_price = order1['average']
if order1_price is None:
cumulative_quote = float(order1['info']['cumQuote'])
executed_quantity = float(order1['info']['executedQty'])
order1_price = cumulative_quote / executed_quantity
pprint(order1)
print('---------------------------------------------------------------------')
stop_loss_params = {'stopPrice': order1_price * 0.9}
order2 = exchange.create_order(symbol, 'stop_market', 'sell', amount, None, stop_loss_params)
pprint(order2)
print('---------------------------------------------------------------------')
take_profit_params = {'stopPrice': order1_price * 1.6}
order3 = exchange.create_order(symbol, 'take_profit_market', 'sell', amount, None, take_profit_params)
pprint(order3)
```
@@ -0,0 +1,43 @@
- [Binance Create Oco Order With Implicit Methods](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'options': {'adjustForTimeDifference': True}
})
symbol = 'SCRT/BTC'
market = exchange.market(symbol)
amount = 26
price = 0.00002
stop_price = 0.000016
stop_limit_price = 0.000015
response = exchange.private_post_order_oco({
'symbol': market['id'],
'side': 'SELL', # SELL, BUY
'quantity': exchange.amount_to_precision(symbol, amount),
'price': exchange.price_to_precision(symbol, price),
'stopPrice': exchange.price_to_precision(symbol, stop_price),
'stopLimitPrice': exchange.price_to_precision(symbol, stop_limit_price), # If provided, stopLimitTimeInForce is required
'stopLimitTimeInForce': 'GTC', # GTC, FOK, IOC
# 'listClientOrderId': exchange.uuid(), # A unique Id for the entire orderList
# 'limitClientOrderId': exchange.uuid(), # A unique Id for the limit order
# 'limitIcebergQty': exchangea.amount_to_precision(symbol, limit_iceberg_quantity),
# 'stopClientOrderId': exchange.uuid() # A unique Id for the stop loss/stop loss limit leg
# 'stopIcebergQty': exchange.amount_to_precision(symbol, stop_iceberg_quantity),
# 'newOrderRespType': 'ACK', # ACK, RESULT, FULL
})
print(response)
```
+34
View File
@@ -0,0 +1,34 @@
- [Binance Ema](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import pandas_ta as ta
import pandas as pd
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
def main():
exchange = ccxt.binance()
markets = exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes
ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1m')
if len(ohlcv):
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['datetime'] = pd.to_datetime(df['timestamp'], unit='ms')
ema = df.ta.ema()
df = pd.concat([df, ema], axis=1)
print(df)
main()
```
@@ -0,0 +1,59 @@
- [Binance Fetch All My Trades Paginate By Id](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'options': {
# 'defaultType': 'spot', // spot, future, margin
# },
})
exchange.load_markets ()
# exchange.verbose = True # uncomment for debugging
symbol = 'ETH/BTC'
from_id = '0'
params = { 'fromId': from_id }
previous_from_id = from_id
all_trades = []
while True:
print('------------------------------------------------------------------')
print('Fetching with params', params)
trades = exchange.fetch_my_trades(symbol, None, None, params)
print('Fetched', len(trades), 'trades')
if len(trades):
# for i in range(0, len(trades)):
# trade = trades[i]
# print (i, trade['id'], trade['datetime'], trade['amount'])
last_trade = trades[len(trades) - 1]
if last_trade['id'] == previous_from_id:
break
else:
previous_from_id = last_trade['id']
params['fromId'] = last_trade['id']
all_trades = all_trades + trades
else:
break
print('Fetched', len(all_trades), 'trades')
for i in range(0, len(all_trades)):
trade = all_trades[i]
print (i, trade['id'], trade['datetime'], trade['amount'])
```
@@ -0,0 +1,55 @@
- [Binance Fetch All My Trades](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# 'options': {
# 'defaultType': 'spot', // spot, future, margin
# },
})
exchange.load_markets ()
# exchange.verbose = True # uncomment for debugging
symbol = 'BTC/USDT'
day = 24 * 60 * 60 * 1000
start_time = exchange.parse8601 ('2020-03-01T00:00:00')
now = exchange.milliseconds ()
all_trades = []
while start_time < now:
print('------------------------------------------------------------------')
print('Fetching trades from', exchange.iso8601(start_time))
end_time = start_time + day
trades = exchange.fetch_my_trades (symbol, start_time, None, {
'endTime': end_time,
})
if len(trades):
last_trade = trades[len(trades) - 1]
start_time = last_trade['timestamp'] + 1
all_trades = all_trades + trades
else:
start_time = end_time
print('Fetched', len(all_trades), 'trades')
for i in range(0, len(all_trades)):
trade = all_trades[i]
print (i, trade['id'], trade['datetime'], trade['amount'])
```
@@ -0,0 +1,52 @@
- [Binance Fetch All Trades](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import csv
import ccxt # noqa: E402
exchange = ccxt.binance()
markets = exchange.load_markets()
symbol = 'ETH/BTC'
market = exchange.market(symbol)
one_hour = 3600 * 1000
since = exchange.parse8601('2018-12-12T00:00:00')
now = exchange.milliseconds()
end = exchange.parse8601(exchange.ymd(now) + 'T00:00:00')
previous_trade_id = None
filename = exchange.id + '_' + market['id'] + '.csv'
with open(filename, mode="w") as csv_f:
csv_writer = csv.DictWriter(csv_f, delimiter=",", fieldnames=["timestamp", "size", "price", "side"])
csv_writer.writeheader()
while since < end:
try:
trades = exchange.fetch_trades(symbol, since)
print(exchange.iso8601(since), len(trades), 'trades')
if len(trades):
last_trade = trades[-1]
if previous_trade_id != last_trade['id']:
since = last_trade['timestamp']
previous_trade_id = last_trade['id']
for trade in trades:
csv_writer.writerow({
'timestamp': trade['timestamp'],
'size': trade['amount'],
'price': trade['price'],
'side': trade['side'],
})
else:
since += one_hour
else:
since += one_hour
except ccxt.NetworkError as e:
print(type(e).__name__, str(e))
exchange.sleep(60000)
```
@@ -0,0 +1,23 @@
- [Binance Fetch Ohlcv Closing Time 1](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binance()
symbol = 'BTC/USDT'
timeframe = '1h'
timeframe_duration_in_seconds = exchange.parse_timeframe(timeframe)
timeframe_duration_in_milliseconds = timeframe_duration_in_seconds * 1000
ohlcvs = exchange.fetch_ohlcv(symbol, timeframe)
for ohlcv in ohlcvs:
print([exchange.iso8601(ohlcv[0] + timeframe_duration_in_milliseconds - 1)] + ohlcv[1:])
```
@@ -0,0 +1,48 @@
- [Binance Fetch Ohlcv Closing Time 2](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import asciichart
import ccxt # noqa: E402
class MyBinance(ccxt.binance):
def parse_ohlcv(self, ohlcv, market=None):
#
# [
# 1591478520000,
# "0.02501300",
# "0.02501800",
# "0.02500000",
# "0.02500000",
# "22.19000000",
# 1591478579999,
# "0.55490906",
# 40,
# "10.92900000",
# "0.27336462",
# "0"
# ]
#
return [
self.safe_integer(ohlcv, 6),
self.safe_number(ohlcv, 1),
self.safe_number(ohlcv, 2),
self.safe_number(ohlcv, 3),
self.safe_number(ohlcv, 4),
self.safe_number(ohlcv, 5),
]
exchange = MyBinance()
symbol = 'BTC/USDT'
timeframe = '1h'
ohlcvs = exchange.fetch_ohlcv(symbol, timeframe)
for ohlcv in ohlcvs:
print([exchange.iso8601(ohlcv[0])] + ohlcv[1:])
```
@@ -0,0 +1,43 @@
- [Binance Fetch Ohlcv Pagination](./examples/py/)
```python
# -*- coding: utf-8 -*-
import ccxt # noqa: E402
def table(values):
first = values[0]
keys = list(first.keys()) if isinstance(first, dict) else range(0, len(first))
widths = [max([len(str(v[k])) for v in values]) for k in keys]
string = ' | '.join(['{:<' + str(w) + '}' for w in widths])
return "\n".join([string.format(*[str(v[k]) for k in keys]) for v in values])
def main():
exchange = ccxt.binance()
markets = exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
since = exchange.parse8601('2022-01-01T00:00:00Z')
symbol = 'BTC/USDT'
timeframe = '1h'
all_ohlcvs = []
while True:
try:
ohlcvs = exchange.fetch_ohlcv(symbol, timeframe, since)
all_ohlcvs += ohlcvs
if len(ohlcvs):
print('Fetched', len(ohlcvs), symbol, timeframe, 'candles from', exchange.iso8601(ohlcvs[0][0]))
since = ohlcvs[-1][0] + 1
else:
break
except Exception as e:
print(type(e).__name__, str(e))
print('Fetched', len(all_ohlcvs), symbol, timeframe, 'candles in total')
if len(all_ohlcvs):
print(table([[exchange.iso8601(o[0])] + o[1:] for o in all_ohlcvs]))
main()
```
@@ -0,0 +1,55 @@
- [Binance Fetch Ohlcv Quote Volume](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
def table(values):
first = values[0]
keys = list(first.keys()) if isinstance(first, dict) else range(0, len(first))
widths = [max([len(str(v[k])) for v in values]) for k in keys]
string = ' | '.join(['{:<' + str(w) + '}' for w in widths])
return "\n".join([string.format(*[str(v[k]) for k in keys]) for v in values])
class Binance(ccxt.binance):
def parse_ohlcv(self, ohlcv, market=None):
#
# [
# 1591478520000, # open time
# "0.02501300", # open
# "0.02501800", # high
# "0.02500000", # low
# "0.02500000", # close
# "22.19000000", # volume
# 1591478579999, # close time
# "0.55490906", # quote asset volume
# 40, # number of trades
# "10.92900000", # taker buy base asset volume
# "0.27336462", # taker buy quote asset volume
# "0" # ignore
# ]
#
return [
self.safe_integer(ohlcv, 0),
self.safe_number(ohlcv, 1),
self.safe_number(ohlcv, 2),
self.safe_number(ohlcv, 3),
self.safe_number(ohlcv, 4),
self.safe_number(ohlcv, 7), # << here
]
exchange = Binance()
markets = exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1h')
print(table(ohlcv))
```
@@ -0,0 +1,66 @@
- [Binance Fetch Ohlcv To Csv](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import csv
import ccxt # noqa: E402
def retry_fetch_ohlcv(exchange, max_retries, symbol, timeframe, since, limit):
num_retries = 0
try:
num_retries += 1
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, since, limit)
# print('Fetched', len(ohlcv), symbol, 'candles from', exchange.iso8601 (ohlcv[0][0]), 'to', exchange.iso8601 (ohlcv[-1][0]))
return ohlcv
except Exception:
if num_retries > max_retries:
raise # Exception('Failed to fetch', timeframe, symbol, 'OHLCV in', max_retries, 'attempts')
def scrape_ohlcv(exchange, max_retries, symbol, timeframe, since, limit):
timeframe_duration_in_seconds = exchange.parse_timeframe(timeframe)
timeframe_duration_in_ms = timeframe_duration_in_seconds * 1000
timedelta = limit * timeframe_duration_in_ms
now = exchange.milliseconds()
all_ohlcv = []
fetch_since = since
while fetch_since < now:
ohlcv = retry_fetch_ohlcv(exchange, max_retries, symbol, timeframe, fetch_since, limit)
fetch_since = (ohlcv[-1][0] + 1) if len(ohlcv) else (fetch_since + timedelta)
all_ohlcv = all_ohlcv + ohlcv
if len(all_ohlcv):
print(len(all_ohlcv), 'candles in total from', exchange.iso8601(all_ohlcv[0][0]), 'to', exchange.iso8601(all_ohlcv[-1][0]))
else:
print(len(all_ohlcv), 'candles in total from', exchange.iso8601(fetch_since))
return exchange.filter_by_since_limit(all_ohlcv, since, None, key=0)
def write_to_csv(filename, data):
with open(filename, mode='w') as output_file:
csv_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerows(data)
def scrape_candles_to_csv(filename, exchange_id, max_retries, symbol, timeframe, since, limit):
# instantiate the exchange by id
exchange = getattr(ccxt, exchange_id)()
# convert since from string to milliseconds integer if needed
if isinstance(since, str):
since = exchange.parse8601(since)
# preload all markets from the exchange
exchange.load_markets()
# fetch all candles
ohlcv = scrape_ohlcv(exchange, max_retries, symbol, timeframe, since, limit)
# save them to csv file
write_to_csv(filename, ohlcv)
print('Saved', len(ohlcv), 'candles from', exchange.iso8601(ohlcv[0][0]), 'to', exchange.iso8601(ohlcv[-1][0]), 'to', filename)
# Binance's BTC/USDT candles start on 2017-08-17
scrape_candles_to_csv('binance.csv', 'binance', 3, 'BTC/USDT', '1m', '2017-08-17T00:00:00Z', 100)
```
@@ -0,0 +1,43 @@
- [Binance Fetch Ohlcv](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import asciichart
import ccxt # noqa: E402
binance = ccxt.binance()
symbol = 'BTC/USDT'
timeframe = '1h'
# each ohlcv candle is a list of [ timestamp, open, high, low, close, volume ]
index = 4 # use close price from each ohlcv candle
height = 15
length = 80
def print_chart(exchange, symbol, timeframe):
print("\n" + exchange.name + ' ' + symbol + ' ' + timeframe + ' chart:')
# get a list of ohlcv candles
ohlcv = exchange.fetch_ohlcv(symbol, timeframe)
# get the ohlCv (closing price, index == 4)
series = [x[index] for x in ohlcv]
# print the chart
print("\n" + asciichart.plot(series[-length:], {'height': height})) # print the chart
last = ohlcv[len(ohlcv) - 1][index] # last closing price
return last
last = print_chart(binance, symbol, timeframe)
print("\n" + binance.name + " ₿ = $" + str(last) + "\n") # print last closing price
```
@@ -0,0 +1,28 @@
- [Binance Fiat](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = exchange.load_markets()
fiat_currencies = [currency['code'] for currency in exchange.currencies.values() if currency['info']['isLegalMoney']]
fiat_markets = [market for market in exchange.markets.values() if ((market['base'] in fiat_currencies) or (market['quote'] in fiat_currencies))]
for market in fiat_markets:
print(market['symbol'])
```
@@ -0,0 +1,199 @@
- [Binance Futures Margin](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
# Must read before your start:
#
# - https://github.com/ccxt/ccxt/wiki/Manual
# - https://github.com/ccxt/ccxt/wiki/Manual#implicit-api-methods
# - https://github.com/ccxt/ccxt/wiki/Manual#unified-api
#
# In short, Binance's API is structured as follows and you should understand
# the meaning and the difference between ISOLATED vs CROSSED margin mode and
# the difference between Hedged positions vs One-way positions.
#
# - wapi: funding for withdrawals and deposits (wapi)
# - api: spot (api)
# - sapi: spot margin
# - CROSSED margin mode
# - Hedged positions
# - One-way positions
# - ISOLATED margin mode
# - Hedged positions
# - One-way positions
# - fapi: swap/perpetual futures margin
# - CROSSED margin mode
# - Hedged positions
# - One-way positions
# - ISOLATED margin mode
# - Hedged positions
# - One-way positions
# - dapi: classic delivery futures margin
# - CROSSED margin mode
# - Hedged positions
# - One-way positions
# - ISOLATED margin mode
# - Hedged positions
# - One-way positions
#
# You should pick the following:
#
# 1. which API you want to trade (fapi, i believe)
# 2. which specific margin mode you want (CROSSED or ISOLATED)
# 3. which specific position mode you want (Hedged or One-way)
#
# Differences in margin modes:
#
# - CROSSED margin mode = you have one futures-margin account for all your positions,
# if some position requires too much margin, your entire account is affected,
# leaving less margin for the other positions,
# thus you share the same margin _"across"_ all your positions
#
# - ISOLATED margin mode = you have separate futures-margin for each of your positions,
# if some position runs out of margin the other positions are not affected,
# thus your positions are _"isolated"_ from one another
#
# Difference in position modes:
#
# - One-way position mode - when you're in this mode
# there's no such things as LONG or SHORT positions.
# You just buy or sell a number of contracts, and
# if the price goes down, your PnL goes negative,
# if the price goes up, your PnL is positive.
# Thus, the position operates `BOTH` ways, both long and short at the same time,
# the notion of "long" and "short" is abstracted away from you,
# so there's only one way the position can go and that way is called "BOTH".
#
# - Hedge mode - you either enter a `LONG` position or a `SHORT` position and
# your PnL calculation rules depend on that
# so there's a number of ways a position can go
#
# Which specific mode of trading (margin mode + position mode) do you want?
def table(values):
first = values[0]
keys = list(first.keys()) if isinstance(first, dict) else range(0, len(first))
widths = [max([len(str(v[k])) for v in values]) for k in keys]
string = ' | '.join(['{:<' + str(w) + '}' for w in widths])
return "\n".join([string.format(*[str(v[k]) for k in keys]) for v in values])
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'options': {
'defaultType': 'future',
},
})
markets = exchange.load_markets()
symbol = 'BTC/USDT' # YOUR SYMBOL HERE
market = exchange.market(symbol)
exchange.verbose = True # UNCOMMENT THIS AFTER LOADING THE MARKETS FOR DEBUGGING
print('----------------------------------------------------------------------')
print('Fetching your balance:')
response = exchange.fetch_balance()
pprint(response['total']) # make sure you have enough futures margin...
# pprint(response['info']) # more details
print('----------------------------------------------------------------------')
# https://binance-docs.github.io/apidocs/futures/en/#position-information-v2-user_data
print('Getting your positions:')
response = exchange.fapiprivatev2_get_positionrisk()
print(table(response))
print('----------------------------------------------------------------------')
# https://binance-docs.github.io/apidocs/futures/en/#change-position-mode-trade
print('Getting your current position mode (One-way or Hedge Mode):')
response = exchange.fapiprivate_get_positionside_dual()
if response['dualSidePosition']:
print('You are in Hedge Mode')
else:
print('You are in One-way Mode')
print('----------------------------------------------------------------------')
# print('Setting your position mode to One-way:')
# response = exchange.fapiprivate_post_positionside_dual({
# 'dualSidePosition': False,
# })
# print(response)
# print('Setting your positions to Hedge mode:')
# response = exchange.fapiprivate_post_positionside_dual({
# 'dualSidePosition': True,
# })
# print(response)
# print('----------------------------------------------------------------------')
# # https://binance-docs.github.io/apidocs/futures/en/#change-margin-type-trade
# print('Changing your', symbol, 'position margin mode to CROSSED:')
# response = exchange.fapiprivate_post_margintype({
# 'symbol': market['id'],
# 'marginType': 'CROSSED',
# })
# print(response)
# print('Changing your', symbol, 'position margin mode to ISOLATED:')
# response = exchange.fapiprivate_post_margintype({
# 'symbol': market['id'],
# 'marginType': 'ISOLATED',
# })
# print(response)
# print('----------------------------------------------------------------------')
# # https://binance-docs.github.io/apidocs/spot/en/#new-future-account-transfer-futures
# code = 'USDT'
# amount = 123.45
# currency = exchange.currency(code)
# print('Moving', code, 'funds from your spot account to your futures account:')
# response = exchange.sapi_post_futures_transfer({
# 'asset': currency['id'],
# 'amount': exchange.currency_to_precision(code, amount),
# # 1: transfer from spot account to USDT-Ⓜ futures account.
# # 2: transfer from USDT-Ⓜ futures account to spot account.
# # 3: transfer from spot account to COIN-Ⓜ futures account.
# # 4: transfer from COIN-Ⓜ futures account to spot account.
# 'type': 1,
# })
# print('----------------------------------------------------------------------')
# # for ISOLATED positions only
# print('Modifying your ISOLATED', symbol, 'position margin:')
# response = exchange.fapiprivate_post_positionmargin({
# 'symbol': market['id'],
# 'amount': 123.45, # ←-------------- YOUR AMOUNT HERE
# 'positionSide': 'BOTH', # use BOTH for One-way positions, LONG or SHORT for Hedge Mode
# 'type': 1, # 1 = add position margin, 2 = reduce position margin
# })
# print('----------------------------------------------------------------------')
```
@@ -0,0 +1,32 @@
- [Binance Futures Positions](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binance({
'apiKey': 'YOUR_TESTNET_API_KEY',
'secret': 'YOUR_TESTNET_API_SECRET',
'options': {
'defaultType': 'future',
},
})
exchange.set_sandbox_mode(True) # comment if you're not using the testnet
markets = exchange.load_markets()
exchange.verbose = True # debug output
balance = exchange.fetch_balance()
positions = balance['info']['positions']
pprint(positions)
```
@@ -0,0 +1,35 @@
- [Binance Futures Set Leverage Implicit Api](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'options': {
'defaultType': 'future',
}
})
exchange.load_markets()
symbol = 'ADA/USDT'
market = exchange.market(symbol)
leverage = 10
response = exchange.fapiprivate_post_leverage({
'symbol': market['id'],
'leverage': leverage,
})
print(response)
```
@@ -0,0 +1,25 @@
- [Binance Futures Set Leverage](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binanceusdm({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
exchange.load_markets()
response = exchange.set_leverage(10, 'ADA/USDT')
print(response)
```
@@ -0,0 +1,58 @@
- [Binance Market Order Quote Usdt](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
symbol = 'ETH/USDT'
try:
print('--------------------------------------------------------------')
# option 1  specify price * amount
amount = 1
price = 4000
# cost = amount * price
# this line will use the amount * price to calculate the total cost-to-spend (4000)
order = exchange.create_order(symbol, 'market', 'buy', amount, price)
pprint(order)
print('--------------------------------------------------------------')
# option 2  specify
# this line does the same, but you override the cost via extra params
params = {
'quoteOrderQty': 4000, # binance-specific
}
amount = None
price = None
order = exchange.create_order(symbol, 'market', 'buy', amount, price, params)
pprint(order)
except Exception as e:
print(type(e).__name__, str(e))
```
@@ -0,0 +1,41 @@
- [Binance Poll Balance](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
previous_timestamp = exchange.milliseconds()
while True:
try:
balance = exchange.fetch_balance()
print('--------------------------------------------------------------')
current_timestamp = exchange.milliseconds()
print(exchange.iso8601(current_timestamp), 'balance:')
pprint(balance)
print('Fetched in', current_timestamp - previous_timestamp, 'milliseconds')
previous_timestamp = current_timestamp
except Exception as e:
print(type(e).__name__, str(e))
```
@@ -0,0 +1,34 @@
- [Binance Poll Positions](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binanceusdm({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
while True:
try:
positions = exchange.fetch_positions ()
print(exchange.iso8601(exchange.milliseconds()), len(positions), 'positions')
print([ [position['symbol'], position['contracts']] for position in positions ])
except Exception as e:
print(type(e).__name__, str(e))
```
@@ -0,0 +1,46 @@
- [Binance Savings Endpoints](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
from pprint import pprint
import ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = exchange.load_markets()
exchange.verbose = True # uncomment for debugging purposes
response = exchange.sapi_post_lending_customizedfixed_purchase({
# YOUR PARAMS HERE
# https://binance-docs.github.io/apidocs/spot/en/#purchase-fixed-activity-project-user_data
})
pprint(response)
response = exchange.sapi_post_lending_daily_purchase({
# YOUR PARAMS HERE
# https://binance-docs.github.io/apidocs/spot/en/#purchase-flexible-product-user_data
})
pprint(response)
response = exchange.sapi_post_lending_daily_redeem({
# YOUR PARAMS HERE
# https://binance-docs.github.io/apidocs/spot/en/#redeem-flexible-product-user_data
})
pprint(response)
```
@@ -0,0 +1,89 @@
- [Binance Spot Trailing](./examples/py/)
```python
# -*- coding: utf-8 -*-
import asyncio
import os
from random import randint
import sys
from pprint import pprint
import ccxt.async_support as ccxt # noqa: E402
print('CCXT Version:', ccxt.__version__)
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET_KEY',
})
exchange = ccxt.binance({
'apiKey': os.environ['BINANCE_APIKEY'],
'secret': os.environ['BINANCE_SECRET'],
})
# You can read more about spot trailing orders here:
# https://github.com/binance/binance-spot-api-docs/blob/master/faqs/trailing-stop-faq.md
# Example 1: Spot : trailing spot loss
async def example_1():
markets = await exchange.load_markets(True)
# create STOP_LOSS_LIMIT BUY with a trailing stop of 5%.
symbol = 'LTC/USDT'
type = 'STOP_LOSS_LIMIT'
side = 'buy'
amount = 0.4
price = 25
params = {
'trailingDelta': 500, # 5% in BIPS
}
exchange.verbose = True
create_order = await exchange.create_order(symbol, type, side, amount, price, params)
print('Create order id:', create_order['id'])
# cancel created order
canceled_order = await exchange.cancel_order(create_order['id'], symbol)
print(canceled_order)
await exchange.close()
# Example 2: Spot : TAKE_PROFIT_LIMIT BUY order
async def example_2():
markets = await exchange.load_markets(True)
# create TAKE_PROFIT_LIMIT BUY with a trailing stop of 5%.
symbol = 'LTC/USDT'
type = 'TAKE_PROFIT_LIMIT'
side = 'buy'
amount = 0.2
price = 70
params = {
'trailingDelta': 250 # 2.5% in BIPS
}
exchange.verbose = True
create_order = await exchange.create_order(symbol, type, side, amount, price, params)
print('Create order id:', create_order['id'])
# cancel created order
canceled_order = await exchange.cancel_order(create_order['id'], symbol)
print(canceled_order)
await exchange.close()
async def main():
try:
# await example_1()
await example_2()
except Exception as e:
print(e)
await exchange.close()
asyncio.run(main())
```
@@ -0,0 +1,46 @@
- [Binance Stop Loss Take Profit](./examples/py/)
```python
# -*- coding: utf-8 -*-
import os
import sys
import ccxt # noqa: E402
exchange = ccxt.binanceusdm({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes
symbol = 'BTC/USDT'
side = 'buy'
amount = 0.01
price = None
stopLossPrice = 25000
takeProfitPrice = 35000
try:
order = exchange.create_order(symbol, 'MARKET', side, amount)
print(order)
inverted_side = 'sell' if side == 'buy' else 'buy'
stopLossParams = {'stopPrice': stopLossPrice}
stopLossOrder = exchange.create_order(symbol, 'STOP_MARKET', inverted_side, amount, price, stopLossParams)
print(stopLossOrder)
takeProfitParams = {'stopPrice': takeProfitPrice}
takeProfitOrder = exchange.create_order(symbol, 'TAKE_PROFIT_MARKET', inverted_side, amount, price, takeProfitParams)
print(takeProfitOrder)
except Exception as e:
print(type(e).__name__, str(e))
```

Some files were not shown because too many files have changed in this diff Show More