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
@@ -0,0 +1,34 @@
import ccxt.pro
from pprint import pprint
from asyncio import run
print('CCXT Version:', ccxt.__version__)
async def main():
exchange = ccxt.pro.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
symbol = 'ETH/BTC'
type = 'limit' # or 'market'
side = 'sell' # or 'buy'
amount = 1.0
price = 0.060154 # or None
order = await exchange.create_order(symbol, type, side, amount, price)
canceled = await exchange.cancel_order(order['id'], order['symbol'])
pprint(canceled)
await exchange.close()
run(main())
@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import run
print('CCXT Version:', ccxt.__version__)
# This example will run silent and will return your balance only when the balance is updated.
#
# 1. launch the example with your keys and keep it running
# 2. go to the trading section on the website
# 3. place a order on a spot market
# 4. see your balance updated in the example
#
# Warning! This example might produce a lot of output to your screen
async def watch_balance(exchange):
await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
balance = await exchange.fetch_balance()
print('---------------------------------------------------------')
print(exchange.iso8601(exchange.milliseconds()))
print(balance)
print('')
while True:
try:
update = await exchange.watch_balance()
balance = exchange.deep_extend(balance, update)
# it will print the balance update when the balance changes
# if the balance remains unchanged the exchange will not send it
print('---------------------------------------------------------')
print(exchange.iso8601(exchange.milliseconds()))
print(balance)
print('')
except Exception as e:
print('watch_balance() failed')
print(type(e).__name__, str(e))
break
async def main():
exchange = ccxt.pro.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
await watch_balance(exchange)
await exchange.close()
run(main())
@@ -0,0 +1,39 @@
import ccxt
import ccxt.pro
import asyncio
from pprint import pprint
loop = asyncio.get_event_loop()
async def print_balance(exchange, market_type):
while True:
try:
balance = await exchange.watch_balance({'type': market_type})
pprint(balance)
print('balance of ' + market_type, balance)
print(exchange.options[market_type])
except ccxt.BaseError as e:
print(type(e), e)
except Exception as e:
print(type(e), e)
async def main():
exchange = ccxt.pro.binance({
"apiKey": "",
"secret": "",
'enableRateLimit': True,
'newUpdates': True,
})
# you must make an order a transfer first to the websocket to send updates
asyncio.ensure_future(print_balance(exchange, 'future'))
asyncio.ensure_future(print_balance(exchange, 'delivery')) # inverse futures settled in BTC
asyncio.ensure_future(print_balance(exchange, 'spot'))
asyncio.run(main())
asyncio.ensure_future(main())
loop.run_forever()
@@ -0,0 +1,22 @@
import ccxt.pro
from asyncio import run
async def main():
exchange = ccxt.pro.binance({
'options': {
'defaultType': 'future',
},
})
symbol = 'BTC/USDT'
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
print(orderbook['bids'][0], orderbook['asks'][0])
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
run(main())
@@ -0,0 +1,27 @@
import ccxt.pro as ccxt
from asyncio import run
print('CCXT Version:', ccxt.__version__)
async def main():
exchange = ccxt.pro.binance({
'options': {
'defaultType': 'future', # spot, margin, future, delivery
},
})
# or
# exchange = ccxt.pro.binanceusdm()
# or
# exchange = ccxt.pro.binancecoinm()
symbol = 'BTC/USDT'
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
print(exchange.iso8601(exchange.milliseconds()), exchange.id, symbol, 'ask:', orderbook['asks'][0], 'bid:', orderbook['bids'][0])
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
run(main())
@@ -0,0 +1,42 @@
import ccxt.pro
from asyncio import run, gather
print('CCXT Pro version', ccxt.pro.__version__)
async def watch_order_book(exchange, symbol):
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
datetime = exchange.iso8601(exchange.milliseconds())
print(datetime, orderbook['nonce'], symbol, orderbook['asks'][0], orderbook['bids'][0])
except Exception as e:
print(type(e).__name__, str(e))
break
async def reload_markets(exchange, delay):
while True:
try:
await exchange.sleep(delay)
markets = await exchange.load_markets(True)
datetime = exchange.iso8601(exchange.milliseconds())
print(datetime, 'Markets reloaded')
except Exception as e:
print(type(e).__name__, str(e))
break
async def main():
exchange = ccxt.pro.binance()
await exchange.load_markets()
# exchange.verbose = True
symbol = 'BTC/USDT'
delay = 60000 # every minute = 60 seconds = 60000 milliseconds
loops = [watch_order_book(exchange, symbol), reload_markets(exchange, delay)]
await gather(*loops)
await exchange.close()
run(main())
@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import gather, run
orderbooks = {}
def handle_all_orderbooks(orderbooks):
print('We have the following orderbooks:')
for id, orderbooks_by_symbol in orderbooks.items():
for symbol in orderbooks_by_symbol.keys():
orderbook = orderbooks_by_symbol[symbol]
print(ccxt.pro.Exchange.iso8601(orderbook['timestamp']), id, symbol, orderbook['asks'][0], orderbook['bids'][0])
async def symbol_loop(exchange, id, symbol):
print('Starting', id, symbol)
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
orderbooks[id] = orderbooks.get(id, {})
orderbooks[id][symbol] = orderbook
print('===========================================================')
#
# here you can do what you want
# with the most recent versions of each orderbook you have so far
#
# you can also wait until all of them are available
# by just looking into all the orderbooks and counting them
#
# we just print them here to keep this example simple
#
handle_all_orderbooks(orderbooks)
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(id, config):
print('Starting', id)
exchange = getattr(ccxt.pro, config['id'])({
'options': config['options'],
})
loops = [symbol_loop(exchange, id, symbol) for symbol in config['symbols']]
await gather(*loops)
await exchange.close()
async def main():
configs = {
'Exchange A (Binance spot)': {
'id': 'binance',
'symbols': ['BTC/USDT', 'ETH/BTC','ETH/USDT'],
'options': {
'defaultType': 'spot',
},
},
'Exchange B (Binance futures)': {
'id': 'binance',
'symbols': ['BTC/USDT', 'ETH/USDT'],
'options': {
'defaultType': 'future',
},
},
}
loops = [exchange_loop(id, config) for id, config in configs.items()]
await gather(*loops)
run(main())
@@ -0,0 +1,51 @@
import ccxt.pro as ccxt
import asyncio
orderbooks = {}
def when_orderbook_changed(exchange_spot, symbol, orderbook):
# this is a common handler function
# it is called when any of the orderbook is updated
# it has access to both the orderbook that was updated
# as well as the rest of the orderbooks
# ...................................................................
print('-------------------------------------------------------------')
print('Last updated:', exchange_spot.iso8601(exchange_spot.milliseconds()))
# ...................................................................
# print just one orderbook here
# print(orderbook['datetime'], symbol, orderbook['asks'][0], orderbook['bids'][0])
# ...................................................................
# or print all orderbooks that have been already subscribed-to
for symbol, orderbook in orderbooks.items():
print(orderbook['datetime'], symbol, orderbook['asks'][0], orderbook['bids'][0])
async def watch_one_orderbook(exchange_spot, symbol):
# a call cost of 1 in the queue of subscriptions
# means one subscription per exchange.rateLimit milliseconds
your_delay = 1
await exchange_spot.throttle(your_delay)
while True:
try:
orderbook = await exchange_spot.watch_order_book(symbol)
orderbooks[symbol] = orderbook
when_orderbook_changed(exchange_spot, symbol, orderbook)
except Exception as e:
print(type(e).__name__, str(e))
async def watch_some_orderbooks(exchange_spot, symbol_list):
loops = [watch_one_orderbook(exchange_spot, symbol) for symbol in symbol_list]
# let them run, don't for all tasks cause they execute asynchronously
# don't print here
await asyncio.gather(*loops)
async def main():
exchange_spot = ccxt.binance()
await exchange_spot.load_markets()
await watch_some_orderbooks(exchange_spot, ['ZEN/USDT', 'RUNE/USDT', 'AAVE/USDT', 'SNX/USDT'])
await exchange_spot.close()
asyncio.run(main())
@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
from asyncio import run
import ccxt.pro as ccxt
from pprint import pprint
# This example will run silent and will return your balance only when the balance is updated.
# 1. launch the example with your keys and keep it running
# 2. go to the margin trading on the website
# 3. place a margin order on a spot market
# 4. see your balance updated in the example
async def main():
exchange = ccxt.pro.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'options': {
'defaultType': 'margin',
},
# comment it out if you don't want debug output
# this is for the demo purpose only (to show the communication)
'verbose': True,
})
while True:
try:
balance = await exchange.watch_balance()
# it will print the balance update when the balance changes
# if the balance remains unchanged the exchange will not send it
pprint(balance)
except Exception as e:
print('watch_balance() failed')
print(e)
break
await exchange.close()
run(main())
@@ -0,0 +1,43 @@
import ccxt.pro
from asyncio import run
print('CCXT Pro version', ccxt.pro.__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.pro.binance({
# 'options': {
# 'OHLCVLimit': 1000, # how many candles to store in memory by default
# },
})
symbol = 'ETH/USDT' # or BNB/USDT, etc...
timeframe = '1m' # 5m, 1h, 1d
limit = 10 # how many candles to return max
method = 'watchOHLCV'
if (method in exchange.has) and exchange.has[method]:
max_iterations = 100000 # how many times to repeat the loop before exiting
for i in range(0, max_iterations):
try:
ohlcvs = await exchange.watch_ohlcv(symbol, timeframe, None, limit)
now = exchange.milliseconds()
print('\n===============================================================================')
print('Loop iteration:', i, 'current time:', exchange.iso8601(now), symbol, timeframe)
print('-------------------------------------------------------------------------------')
print(table([[exchange.iso8601(o[0])] + o[1:] for o in ohlcvs]))
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
else:
print(exchange.id, method, 'is not supported or not implemented yet')
run(main())
@@ -0,0 +1,34 @@
# -*- coding: utf-8 -*-
from asyncio import run
import ccxt.pro as ccxt
class MyBinance(ccxt.binance):
def handle_order_book_message(self, client, message, orderbook):
asks = self.safe_value(message, 'a', [])
bids = self.safe_value(message, 'b', [])
# printing high-frequency updates is a resource-heavy task
# this print statement is here just to demonstrate the work of it
# replace it with you logic for processing individual updates
print('Updates:', {
'asks': asks,
'bids': bids,
})
return super(MyBinance, self).handle_order_book_message(client, message, orderbook);
async def main():
exchange = MyBinance()
symbol = 'BTC/USDT'
print('Watching', exchange.id, symbol)
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
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 also break just this one loop if it fails
await exchange.close()
run(main())
@@ -0,0 +1,63 @@
import ccxt.pro
from asyncio import run, gather
data = {
'orderbook': None,
'balance': None,
}
def common_handler(exchange, symbol):
market = exchange.market(symbol)
base = market['base']
quote = market['quote']
balance = data['balance']
orderbook = data['orderbook']
if balance and orderbook:
total = balance['total']
tip = [ orderbook['asks'][0], orderbook['bids'][0] ]
print(exchange.iso8601(exchange.milliseconds()), symbol, 'orderbook:', tip, 'balance:', total)
async def watch_order_book(exchange, symbol):
while True:
try:
data['orderbook'] = await exchange.watch_order_book(symbol)
common_handler(exchange, symbol)
except Exception as e:
print(type(e).__name__, str(e))
break # break this loop
async def watch_balance(exchange, symbol):
while True:
try:
data['balance'] = await exchange.watch_balance()
common_handler(exchange, symbol)
except Exception as e:
print(type(e).__name__, str(e))
break # break this loop
async def main():
exchange = ccxt.pro.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
await exchange.load_markets()
symbol = 'BTC/USDT'
while True:
try:
loops = [
watch_order_book(exchange, symbol),
watch_balance(exchange, symbol)
]
await gather(*loops)
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
run(main())
@@ -0,0 +1,59 @@
# Python
import ccxt.pro
from asyncio import run, gather
from pprint import pprint
async def place_delayed_order(exchange, symbol, amount, price):
try:
await exchange.sleep(5000) # wait a bit
order = await exchange.create_limit_buy_order(symbol, amount, price)
print(exchange.iso8601(exchange.milliseconds()), 'place_delayed_order')
pprint(order)
print('---------------------------------------------------------------')
except Exception as e:
# break
print(e)
async def watch_orders_loop(exchange, symbol):
while True:
try:
orders = await exchange.watch_orders(symbol)
print(exchange.iso8601(exchange.milliseconds()), 'watch_orders_loop', len(orders), ' last orders cached')
print('---------------------------------------------------------------')
except Exception as e:
# break
print(e)
async def watch_balance_loop(exchange):
while True:
try:
balance = await exchange.watch_balance()
print(exchange.iso8601(exchange.milliseconds()), 'watch_balance_loop')
pprint(balance)
print('---------------------------------------------------------------')
except Exception as e:
# break
print(e)
async def main():
exchange = ccxt.pro.binanceusdm({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
symbol = 'BTC/USDT'
amount = 0.001
price = 11111
loops = [
watch_orders_loop(exchange, symbol),
watch_balance_loop(exchange),
place_delayed_order(exchange, symbol, amount, price)
]
await gather(*loops)
await exchange.close()
run(main())
@@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-
from asyncio import run, gather
import os
import sys
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root + '/python')
import ccxt.pro # noqa: E402
print('CCXT Version:', ccxt.__version__)
async def print_balance_continuously(exchange):
while True:
try:
print('-----------------------------------------------------------')
await exchange.load_markets()
balance = await exchange.watch_balance()
print(exchange.iso8601(exchange.milliseconds()), exchange.id)
for currency, value in balance['total'].items():
print(value, currency)
except Exception as e:
print('-----------------------------------------------------------')
print(exchange.iso8601(exchange.milliseconds()), exchange.id, type(e), e)
await exchange.sleep(300000) # sleep 5 minutes and retry
async def main():
config = {
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
}
exchange_ids = [
'binance',
'binanceusdm',
'binancecoinm',
]
exchanges = [getattr(ccxt.pro, exchange_id)(config) for exchange_id in exchange_ids]
printing_loops = [print_balance_continuously(exchange) for exchange in exchanges]
await gather(*printing_loops)
closing_tasks = [exchange.close() for exchange in exchanges]
await gather(*closing_tasks)
run(main())
@@ -0,0 +1,41 @@
import ccxt.pro
from asyncio import run
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.pro.bitmex({
# 'options': {
# 'OHLCVLimit': 1000, # how many candles to store in memory by default
# },
})
symbol = 'BTC/USD'
timeframe = '1m' # 5m, 1h, 1d
limit = 10 # how many candles to return max
method = 'watchOHLCV'
if (method in exchange.has) and exchange.has[method]:
max_iterations = 100 # how many times to repeat the loop before exiting
for i in range(0, max_iterations):
try:
ohlcvs = await exchange.watch_ohlcv(symbol, timeframe, None, limit)
now = exchange.milliseconds()
print('\n===============================================================================')
print('Loop iteration:', i, 'current time:', exchange.iso8601(now), symbol, timeframe)
print('-------------------------------------------------------------------------------')
print(table([[exchange.iso8601(o[0])] + o[1:] for o in ohlcvs]))
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
else:
print(exchange.id, method, 'is not supported or not implemented yet')
run(main())
@@ -0,0 +1,73 @@
import ccxt.pro
from asyncio import run, gather
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 watch_ticker(color, duration, exchange, symbol):
method = 'watchTicker'
if (method in exchange.has) and exchange.has[method]:
start = exchange.milliseconds()
i = 1
while True:
ticker = await exchange.watch_ticker(symbol)
now = exchange.milliseconds()
# start color code
print(color, 'Ticker ========================================================================')
print(exchange.iso8601(now), symbol, 'iteration:', i, 'last price:', ticker['last'])
print('-------------------------------------------------------------------------------')
# pprint.pprint(ticker) # uncomment for a lengthy complete printout
print('\x1b[0m') # stop color code
i += 1
if (start + duration) < now:
break
else:
raise Exception(exchange.id + ' ' + method + ' is not supported or not implemented yet')
async def watch_ohlcv(color, duration, exchange, symbol, timeframe, limit):
method = 'watchOHLCV'
if (method in exchange.has) and exchange.has[method]:
start = exchange.milliseconds()
i = 1
while True:
ohlcvs = await exchange.watch_ohlcv(symbol, timeframe, None, limit)
now = exchange.milliseconds()
# start color code
print(color, 'OHLCV =========================================================================')
print(exchange.iso8601(now), symbol, timeframe, 'iteration:', i)
print('-------------------------------------------------------------------------------')
print(table([[exchange.iso8601(o[0])] + o[1:] for o in ohlcvs]))
print('\x1b[0m') # stop color code
i += 1
if (start + duration) < now:
break
else:
raise Exception(exchange.id + ' ' + method + ' is not supported or not implemented yet')
# =============================================================================
async def main():
exchange = ccxt.pro.bitmex()
await exchange.load_markets()
duration = 1200000 # run 20 minutes = 1200000 milliseconds
symbol = 'BTC/USD'
limit = 10
loops = [
watch_ticker('\033[35m', duration, exchange, symbol), # magenta
watch_ohlcv('\x1b[33m', duration, exchange, symbol, '1m', limit), # yellow
watch_ohlcv('\x1b[32m', duration, exchange, symbol, '5m', limit), # green
]
await gather(*loops)
await exchange.close()
run(main())
@@ -0,0 +1,23 @@
import ccxt.pro
from asyncio import run
print('CCXT Pro version', ccxt.pro.__version__)
async def main():
exchange = ccxt.pro.bitvavo()
await exchange.load_markets()
exchange.verbose = True
symbol = 'BTC/EUR'
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
print(orderbook['nonce'], symbol, orderbook['asks'][0], orderbook['bids'][0])
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
run(main())
@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro
print('CCXT Version:', ccxt.__version__)
async def loop(exchange, symbol, timeframe, complete_candles_only=False):
duration_in_seconds = exchange.parse_timeframe(timeframe)
duration_in_ms = duration_in_seconds * 1000
while True:
try:
trades = await exchange.watch_trades(symbol)
if len(trades) > 0:
current_minute = int(exchange.milliseconds() / duration_in_ms)
ohlcvc = exchange.build_ohlcvc(trades, timeframe)
if complete_candles_only:
ohlcvc = [candle for candle in ohlcvc if int(candle[0] / duration_in_ms) < current_minute]
if len(ohlcvc) > 0:
print('-----------------------------------------------------------')
print("Symbol:", symbol, "timeframe:", timeframe)
print(ohlcvc)
except Exception as e:
print(f"{type(e).__name__}: {(str(e))}")
# raise type(e)(str(e)) # uncomment to break all loops in case of an error in any one of them
# break # you can also break just this one loop if it fails
async def main():
# select the exchange
exchange = ccxt.pro.binance()
if exchange.has['watchTrades']:
markets = await exchange.load_markets()
# Change this value accordingly
timeframe = '1m'
limit = 5
selected_symbols = list(markets.values())[:limit]
# you can also specify the symbols manually
# selected_symbols = ['BTC/USDT', 'ETH/USDT']
# Use this variable to choose if only complete candles
# should be considered
complete_candles_only = True
await asyncio.gather(*[loop(exchange, symbol['symbol'], timeframe, complete_candles_only)
for symbol in selected_symbols])
await exchange.close()
else:
print(exchange.id, 'does not support watchTrades yet')
asyncio.run(main())
@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import run
async def main():
exchange = ccxt.pro.coinbase()
method = 'watchTrades'
print('CCXT Pro version', ccxt.pro.__version__)
if exchange.has[method]:
last_id = ''
while True:
try:
trades = await exchange.watch_trades('BTC/USD')
for trade in trades:
if trade['id'] > last_id:
print(exchange.iso8601(exchange.milliseconds()), trade['symbol'], trade['datetime'], trade['price'], trade['amount'])
last_id = trade['id']
except Exception as e:
# stop
await exchange.close()
raise e
# or retry
# pass
else:
raise Exception(exchange.id + ' ' + method + ' is not supported or not implemented yet')
run(main())
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import run
async def main():
exchange = ccxt.pro.coinbase()
method = 'watchTrades'
print('CCXT Pro version', ccxt.pro.__version__)
if exchange.has[method]:
while True:
try:
trades = await exchange.watch_trades('BTC/USD')
num_trades = len(trades)
trade = trades[-1]
print(exchange.iso8601(exchange.milliseconds()), trade['symbol'], trade['datetime'], trade['price'], trade['amount'], 'stored', num_trades, 'trades in cache')
except Exception as e:
# stop
await exchange.close()
raise e
# or retry
# pass
else:
raise Exception(exchange.id + ' ' + method + ' is not supported or not implemented yet')
run(main())
@@ -0,0 +1,22 @@
import ccxt.pro
from asyncio import run
async def consume_all_trades(exchange, symbol):
await exchange.load_markets()
while True:
try:
trades = await exchange.watch_trades(symbol)
print('----------------------------------------------------------------------')
print(exchange.iso8601(exchange.milliseconds()), 'received', len(trades), 'new', symbol, 'trades:')
for trade in trades:
print(exchange.id, symbol, trade['id'], trade['datetime'], trade['amount'], trade['price'])
exchange.trades[symbol].clear()
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
exchange = ccxt.pro.bitmex()
symbol = 'BTC/USD'
run(consume_all_trades(exchange, symbol))
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro
from datetime import datetime
async def loop(exchange, symbol):
since = datetime.utcnow()
timestamp = int(since.timestamp() * 1000)
while True:
trades = await exchange.watch_trades(symbol, since=timestamp)
print('--------------------------------------------------------------')
print('Received', len(trades), 'after', exchange.iso8601 (timestamp))
print('waiting for next update...')
async def main():
exchange = ccxt.pro.gateio()
await loop(exchange, 'BTC/USDT')
await exchange.close()
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
from asyncio import run
import ccxt.pro
from pprint import pprint
class MyBinance(ccxt.pro.binance):
def handle_ohlcv(self, client, message):
# add your handling of the original message here
print('intercepted', message)
return super(MyBinance, self).handle_ohlcv(client, message)
async def main():
exchange = MyBinance()
symbol = 'BTC/USDT'
print('Watching', exchange.id, symbol)
while True:
try:
ohlcv = await exchange.watch_ohlcv(symbol, '1m')
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 also break just this one loop if it fails
await exchange.close()
if __name__ == "__main__":
print('CCXT Version:', ccxt.__version__)
run(main())
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import gather, run
async def symbol_loop(exchange, symbol):
print('Starting the', exchange.id, 'symbol loop with', symbol)
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
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 main():
exchange = ccxt.pro.kucoin({
"apiKey": "YOUR_API_KEY",
"secret": "YOUR_API_SECRET",
"password": "YOUR_API_PASSWORD",
})
symbols = ['KDA/USDT', 'KDA/BTC', 'BTC/USDT']
loops = [symbol_loop(exchange, symbol) for symbol in symbols]
await gather(*loops)
await exchange.close()
run(main())
@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import gather, run
async def symbol_loop(exchange, method, symbol):
print('Starting', exchange.id, method, symbol)
while True:
try:
response = await getattr(exchange, method)(symbol)
now = exchange.milliseconds()
iso8601 = exchange.iso8601(now)
if method == 'watchOrderBook':
print(iso8601, exchange.id, method, symbol, response['asks'][0], response['bids'][0])
elif method == 'watchTicker':
print(iso8601, exchange.id, method, symbol, response['high'], response['low'], response['bid'], response['ask'])
elif method == 'watchTrades':
print(iso8601, exchange.id, method, symbol, len(response), 'trades')
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 method_loop(exchange, method, symbols):
print('Starting', exchange.id, method, symbols)
loops = [symbol_loop(exchange, method, symbol) for symbol in symbols]
await gather(*loops)
async def exchange_loop(exchange_id, methods):
print('Starting', exchange_id, methods)
exchange = getattr(ccxt.pro, exchange_id)()
loops = [method_loop(exchange, method, symbols) for method, symbols in methods.items()]
await gather(*loops)
await exchange.close()
async def main():
exchanges = {
'okex': {
'watchOrderBook': ['BTC/USDT', 'ETH/BTC', 'ETH/USDT'],
'watchTicker': ['BTC/USDT'],
},
'binance': {
'watchOrderBook': ['BTC/USDT', 'ETH/BTC'],
'watchTrades': [ 'ETH/BTC' ],
},
}
loops = [exchange_loop(exchange_id, methods) for exchange_id, methods in exchanges.items()]
await gather(*loops)
run(main())
@@ -0,0 +1,59 @@
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro
orderbooks = {}
def handle_all_orderbooks(orderbooks):
print('We have the following orderbooks:')
for exchange_id, orderbooks_by_symbol in orderbooks.items():
for symbol in orderbooks_by_symbol.keys():
orderbook = orderbooks_by_symbol[symbol]
print(ccxt.pro.Exchange.iso8601(orderbook['timestamp']), exchange_id, symbol, orderbook['asks'][0], orderbook['bids'][0])
async def symbol_loop(exchange, symbol):
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
orderbooks[exchange.id] = orderbooks.get(exchange.id, {})
orderbooks[exchange.id][symbol] = orderbook
print('===========================================================')
#
# here you can do what you want
# with the most recent versions of each orderbook you have so far
#
# you can also wait until all of them are available
# by just looking into all the orderbooks and counting them
#
# we just print them here to keep this example simple
#
handle_all_orderbooks(orderbooks)
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):
exchange = getattr(ccxt.pro, exchange_id)()
loops = [symbol_loop(exchange, symbol) for symbol in symbols]
await asyncio.gather(*loops)
await exchange.close()
async def main():
symbols = ['BTC/USDT', 'ETH/BTC']
# symbols = []
exchanges = {
'okex': symbols + ['ETH/USDT'],
'binance': symbols,
}
loops = [exchange_loop(exchange_id, symbols) for exchange_id, symbols in exchanges.items()]
await asyncio.gather(*loops)
asyncio.run(main())
@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import run, gather, sleep
orderbooks = {}
def handle_all_orderbooks(orderbooks):
print('We have the following orderbooks:')
for exchange_id, orderbooks_by_symbol in orderbooks.items():
for symbol in orderbooks_by_symbol.keys():
orderbook = orderbooks_by_symbol[symbol]
print(ccxt.pro.Exchange.iso8601(orderbook['timestamp']), exchange_id, symbol, orderbook['asks'][0], orderbook['bids'][0])
async def handling_loop(orderbooks):
delay = 5
while True:
await sleep(delay)
handle_all_orderbooks(orderbooks)
async def symbol_loop(exchange, symbol):
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
orderbooks[exchange.id] = orderbooks.get(exchange.id, {})
orderbooks[exchange.id][symbol] = orderbook
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):
exchange = getattr(ccxt.pro, exchange_id)()
loops = [symbol_loop(exchange, symbol) for symbol in symbols]
await gather(*loops)
await exchange.close()
async def main():
symbols = ['BTC/USDT', 'ETH/BTC']
# symbols = []
exchanges = {
'okex': symbols + ['ETH/USDT'],
'binance': symbols,
}
loops = [exchange_loop(exchange_id, symbols) for exchange_id, symbols in exchanges.items()]
loops += [handling_loop(orderbooks)]
await gather(*loops)
run(main())
@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import gather, run
async def symbol_loop(exchange, method, symbol):
print('Starting', exchange.id, method, symbol)
while True:
try:
response = await getattr(exchange, method)(symbol)
now = exchange.milliseconds()
iso8601 = exchange.iso8601(now)
if method == 'watchOrderBook':
print(iso8601, exchange.id, method, symbol, response['asks'][0], response['bids'][0])
elif method == 'watchTicker':
print(iso8601, exchange.id, method, symbol, response['high'], response['low'], response['bid'], response['ask'])
elif method == 'watchTrades':
print(iso8601, exchange.id, method, symbol, len(response), 'trades')
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 symbols_method_loop(exchange, method, symbols):
print('Starting', exchange.id, method, symbols)
loops = [symbol_loop(exchange, method, symbol) for symbol in symbols]
await gather(*loops)
async def method_loop(exchange, method):
print('Starting', exchange.id, method)
while True:
try:
response = await getattr(exchange, method)()
now = exchange.milliseconds()
iso8601 = exchange.iso8601(now)
print(iso8601, exchange.id, method, response)
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, methods, config={}):
print('Starting', exchange_id, methods)
exchange = getattr(ccxt.pro, exchange_id)()
for attr, value in config.items():
setattr(exchange, attr, value)
loops = [symbols_method_loop(exchange, method, symbols) if len(symbols) else method_loop(exchange, method) for method, symbols in methods.items()]
await gather(*loops)
await exchange.close()
async def main():
keys = {
'okex': {
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
},
'binance': {
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
},
}
exchanges = {
'okex': {
'watchOrderBook': ['BTC/USDT', 'ETH/BTC', 'ETH/USDT'],
'watchTicker': ['BTC/USDT'],
'watchBalance': [],
},
'binance': {
'watchOrderBook': ['BTC/USDT', 'ETH/BTC'],
'watchTrades': [ 'ETH/BTC' ],
'watchBalance': [],
},
}
loops = [exchange_loop(exchange_id, methods, keys.get(exchange_id, {})) for exchange_id, methods in exchanges.items()]
await gather(*loops)
run(main())
@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import gather, run
async def symbol_loop(exchange, symbol):
print('Starting the', exchange.id, 'symbol loop with', symbol)
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
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.pro, 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'],
}
loops = [exchange_loop(exchange_id, symbols) for exchange_id, symbols in exchanges.items()]
await gather(*loops)
run(main())
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
import ccxt.pro
from asyncio import gather, run
async def symbol_loop(exchange, symbol):
print('Starting the', exchange.id, 'symbol loop with', symbol)
while True:
try:
trades = await exchange.watch_trades(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), exchange.id, symbol, len(trades), trades[-1]['price'])
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.pro, exchange_id)({
'newUpdates': True, # https://github.com/ccxt/ccxt/wiki/ccxt.pro.manual#incremental-data-structures
})
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'],
}
loops = [exchange_loop(exchange_id, symbols) for exchange_id, symbols in exchanges.items()]
await gather(*loops)
run(main())
@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro
async def loop(exchange_id, symbol):
exchange = getattr(ccxt.pro, exchange_id)()
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
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
await exchange.close()
async def main():
symbols = {
'kraken': 'BTC/USDT',
'binance': 'BTC/USDT',
'bitmex': 'XBT_USDT',
}
await asyncio.gather(*[loop(exchange_id, symbol) for exchange_id, symbol in symbols.items()])
asyncio.run(main())
@@ -0,0 +1,34 @@
import ccxt.pro
import asyncio
import time
async def watch_book(exchange, ticker):
last = None
while True:
try:
orderbook = await exchange.watch_order_book(ticker)
# TODO add timeout within a minute
# TODO add last
top_bid = orderbook['bids'][0][0]
if last != top_bid:
print(f'{int(time.time() * 1000)} top bid for celo on {exchange.name} is {top_bid}')
last = top_bid
except Exception as e:
print(f'{exchange.name} failed {type(e)} {e}')
async def main():
exchange_ids = ['coinbasepro', 'okcoin', 'bittrex']
exchanges = [getattr(ccxt.pro, exchange_id)() for exchange_id in exchange_ids]
try:
done, pending = await asyncio.wait({watch_book(exchange, 'CELO/USD') for exchange in exchanges}, return_when=asyncio.FIRST_EXCEPTION)
for completed in done:
# trigger the exception here
completed.result()
except Exception as e:
print(f'closing all exchanges because of exception {type(e)} {e}')
await asyncio.gather(*[exchange.close() for exchange in exchanges])
asyncio.run(main())
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
from asyncio import run
import ccxt.pro
print('CCXT Pro Version: ', ccxt.pro.__version__)
exchange = ccxt.pro.okex({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_API_SECRET',
'password': 'YOUR_API_PASSWORD',
'options': { 'defaultType': 'swap' },
})
async def main():
await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging
# https://github.com/ccxt/ccxt/wiki/Manual#overriding-unified-params
# https://www.okex.com/docs/en/#swap-swap---orders
symbol = 'BTC/USDT:USDT'
amount = 1 # how may contracts
price = None # or your limit price
side = 'buy' # or 'sell'
future_type = '1' # 1 open long, 2 open short, 3 close long, 4 close short for futures
order_type = '4' # 0 = limit order, 4 = market order
try:
# open long market price order
order = await exchange.create_order(symbol, 'market', side, amount, price, {'type': future_type})
# --------------------------------------------------------------------
# open long market price order
# const order = await exchange.create_order(symbol, type, side, amount, price, {'order_type': order_type})
# --------------------------------------------------------------------
# close short market price order
# const order = await exchange.create_order(symbol, 'market', side, amount, price, {'type': future_type, 'order_type': order_type})
# --------------------------------------------------------------------
# close short market price order
# const order = await exchange.create_order(symbol, '4', side, amount, price, {'order_type': order_type})
# ...
print(order)
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
run(main())
@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro as ccxt
from pprint import pprint
async def main():
exchange = ccxt.pro.okex({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# okex requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication
'password': 'YOUR_API_PASSWORD',
# comment it out if you don't want debug output
# this is for the demo purpose only (to show the communication)
'verbose': True,
})
while True:
try:
balance = await exchange.watch_balance({
# okex watch_balance requires a symbol or an instrument_id
'symbol': 'BTC/USDT',
'type': 'margin',
})
# it will print the balance update when the balance changes
# if the balance remains unchanged the exchange will not send it
pprint(balance)
except Exception as e:
print('watch_balance() failed')
print(e)
break
await exchange.close()
asyncio.run(main())
@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro as ccxt
from pprint import pprint
async def main():
exchange = ccxt.pro.okex({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
# okex requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication
'password': 'YOUR_API_PASSWORD',
'options': {
'watchBalance': 'margin',
},
# comment it out if you don't want debug output
# this is for the demo purpose only (to show the communication)
'verbose': True,
})
while True:
try:
balance = await exchange.watch_balance({
# okex watch_balance requires a symbol or an instrument_id
'symbol': 'BTC/USDT',
})
# it will print the balance update when the balance changes
# if the balance remains unchanged the exchange will not send it
pprint(balance)
except Exception as e:
print('watch_balance() failed')
print(e)
break
await exchange.close()
asyncio.run(main())
@@ -0,0 +1,36 @@
import ccxt.pro
from asyncio import run
print('CCXT Pro version', ccxt.pro.__version__)
async def main():
exchange = ccxt.pro.okx({
'options': {
'watchOrderBook': {
'depth': 'bbo-tbt', # tick-by-tick best bidask
},
},
})
markets = await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
symbol = 'BTC/USDT'
while True:
try:
# -----------------------------------------------------------------
# use this:
# orderbook = await exchange.watch_order_book(symbol)
# print(orderbook['datetime'], symbol, orderbook['asks'][0], orderbook['bids'][0])
# -----------------------------------------------------------------
# or this:
ticker = await exchange.watch_ticker(symbol)
print(ticker['datetime'], symbol, [ticker['ask'], ticker['askVolume']], [ticker['bid'], ticker['bidVolume']])
# -----------------------------------------------------------------
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
run(main())
@@ -0,0 +1,55 @@
import ccxt.pro
from asyncio import run, ensure_future
from pprint import pprint
print('CCXT Version:', ccxt.__version__)
# on_connected() is called when a client connection is established
# note that the exchange will reuse the same client connection
# some exchanges might require two or more public/private connections
# therefore on_connected() may be called more than once
class MyBinance(ccxt.pro.binance):
def on_connected(self, client, message=None):
print('Connected to', client.url)
ensure_future(create_order(self))
async def create_order(exchange):
symbol = 'BTC/USDT'
type = 'limit'
side = 'buy'
amount = 123.45 # change for your values
price = 54.321 # change for your values
params = {}
try:
order = await exchange.create_order(symbol, type, side, amount, price, params)
print('--------------------------------------------------------------')
print('create_order():')
pprint(order)
except Exception as e:
print(type(e).__name__, str(e))
async def watch_orders(exchange):
while True:
try:
orders = await exchange.watch_orders()
print('--------------------------------------------------------------')
print('watch_orders():')
pprint(orders)
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
exchange = MyBinance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
run(watch_orders(exchange))
@@ -0,0 +1,35 @@
import ccxt.pro
import asyncio
async def watch_order_book(exchange, symbol):
while True:
orderbook = await exchange.watch_order_book(symbol)
print(orderbook['datetime'], symbol, orderbook['asks'][0], orderbook['bids'][0])
async def watch_trades(exchange, symbol):
while True:
trades = await exchange.watch_trades(symbol)
last = trades[-1]
print(last['datetime'], last['price'], last['amount'])
async def main():
exchange = ccxt.pro.bitstamp()
await exchange.load_markets()
symbol = 'BTC/USD'
while True:
try:
loops = [
watch_order_book(exchange, symbol),
watch_trades(exchange, symbol)
]
await asyncio.gather(*loops)
except Exception as e:
print(type(e).__name__, str(e))
break
await exchange.close()
asyncio.run(main())
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
from asyncio import run
import ccxt.pro
async def loop(exchange, symbol):
await exchange.throttle(10)
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), symbol, orderbook['asks'][0], orderbook['bids'][0])
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 also break just this one loop if it fails
async def main():
exchange = ccxt.pro.ftx()
symbols = ['BTC/USDT', 'ETH/USDT', 'ETH/BTC']
await asyncio.gather(*[loop(exchange, symbol) for symbol in symbols])
await exchange.close()
run(main())
@@ -0,0 +1,23 @@
import ccxt.pro
from asyncio import run
from pprint import pprint
print('CCXT Version:', ccxt.__version__)
async def main():
exchange = ccxt.pro.phemex({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
markets = await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes if necessary
try:
symbol = 'UNI/USDT'
response = await exchange.cancel_all_orders(symbol)
pprint(response)
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
run(main())
@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
import asyncio
import sys
import os
# ------------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(root + '/python')
# ------------------------------------------------------------------------------
import ccxt.pro
print('CCXT Version:', ccxt.pro.__version__)
orderbooks = {}
def handle_all_orderbooks(exchange, orderbooks, spot, future):
if spot in orderbooks and future in orderbooks:
spot_order_book = orderbooks[spot]
future_order_book = orderbooks[future]
timestamp = exchange.milliseconds()
spot_lag = abs(timestamp - spot_order_book['timestamp']) if spot_order_book['timestamp'] else 10000
future_lag = abs(timestamp - future_order_book['timestamp']) if future_order_book['timestamp'] else 10000
if spot_lag >= 10000 or future_lag >= 10000:
print('Lag > 10 seconds')
async def symbol_loop(exchange, symbol, spot, future):
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
orderbooks[symbol] = orderbook
print(exchange.id, '{:13s}'.format(symbol), orderbook['datetime'], orderbook['asks'][0], orderbook['bids'][0])
#
# here you can do what you want
# with the most recent versions of each orderbook you have so far
#
# you can also wait until all of them are available
# by just looking into all the orderbooks and counting them
#
# we just print them here to keep this example simple
#
handle_all_orderbooks(exchange, orderbooks, spot, future)
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 main():
spot = 'BTC/USDT'
future = 'BTC/USDT:USDT'
symbols = [ spot, future ]
exchange = ccxt.pro.bitmart()
loops = [
symbol_loop(exchange, spot, spot, future),
symbol_loop(exchange, future, spot, future),
]
await asyncio.gather(*loops)
await exchange.close()
asyncio.run(main())
@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
import asyncio
import ccxt.pro
async def loop(exchange, symbol, n):
i = 0
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
# print every 100th bidask to avoid wasting CPU cycles on printing
if not i % 100:
# i = how many updates there were in total
# n = the number of the pair to count subscriptions
now = exchange.milliseconds()
print(exchange.iso8601(now), n, symbol, i, orderbook['asks'][0], orderbook['bids'][0])
i += 1
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 also break just this one loop if it fails
async def main():
exchange = ccxt.pro.kraken()
await exchange.load_markets()
markets = list(exchange.markets.values())
symbols = [market['symbol'] for market in markets if not market['darkpool']]
await asyncio.gather(*[loop(exchange, symbol, n) for n, symbol in enumerate(symbols)])
await exchange.close()
asyncio.run(main())
@@ -0,0 +1,45 @@
import asyncio
import ccxt.pro
class MyBinance(ccxt.pro.binance):
def handle_mini_ticker(self, client, message):
market_id = self.safe_string_lower(message, 's')
message_hash = market_id + '@miniTicker'
client.resolve(message, message_hash)
def handle_message(self, client, message):
handlers = {
'24hrMiniTicker': self.handle_mini_ticker,
# add other custom handlers here
}
e = self.safe_string(message, 'e')
method = self.safe_value(handlers, e)
if method:
return method(client, message)
else:
return super(MyBinance, self).handle_message(client, message)
async def main():
exchange = MyBinance({
'enableRateLimit': False,
'options': {
'defaultType': 'future'
}
})
await exchange.load_markets()
# exchange.verbose = True # uncomment for debugging purposes
market = exchange.market('BTC/USDT')
message_hash = market['lowercaseId'] + '@miniTicker'
while True:
try:
print(await exchange.watch_public(message_hash))
except Exception as e:
print(type(e).__name__, str(e))
await exchange.close()
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
from asyncio import run, gather
import ccxt.pro
print('CCXT Version:', ccxt.__version__)
async def exchange_loop(exchange_id, symbols):
exchange = getattr(ccxt.pro, exchange_id)()
markets = await exchange.load_markets()
await gather(*[watch_ticker_loop(exchange, symbol) for symbol in symbols])
await exchange.close()
async def watch_ticker_loop(exchange, symbol):
# exchange.verbose = True # uncomment for debugging purposes if necessary
while True:
try:
ticker = await exchange.watch_ticker(symbol)
now = exchange.milliseconds()
print(exchange.iso8601(now), exchange.id, symbol, 'bid:', ticker['bid'], 'ask:', ticker['ask'], 'last:', ticker['last'], 'on', ticker['datetime'])
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 main():
exchanges = {
'binance': [ 'BTC/USDT', 'ETH/USDT' ],
'ftx': [ 'BTC/USD', 'ETH/USD' ],
}
loops = [exchange_loop(exchange_id, symbols) for exchange_id, symbols in exchanges.items()]
await gather(*loops)
run(main())
@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
from asyncio import gather, run
import ccxt.pro
from pprint import pprint
async def watch_ticker_continuously(exchange, symbol):
filename = exchange.id + '-' + symbol.replace('/', '-') + '.csv'
print('Watching', exchange.id, symbol, filename)
keys = ['index', 'exchange', 'symbol', 'timestamp', 'open', 'high', 'low', 'close', 'baseVolume']
with open(filename, 'w') as file:
file.write(','.join(keys) + "\n")
index = 0
while True:
try:
ticker = await exchange.watch_ticker(symbol)
values = [str(index), exchange.id] + [str(ticker[key]) for key in keys[2:]]
print(*values)
with open(filename, 'a') as file:
file.write(','.join(values) + "\n")
index += 1
except Exception as e:
print(e)
async def watch_tickers_continuously(exchange_id, overrides, symbols):
exchange_class = getattr(ccxt.pro, exchange_id)
exchange = exchange_class(overrides)
coroutines = [watch_ticker_continuously(exchange, symbol) for symbol in symbols]
await gather(*coroutines)
await exchange.close()
async def main():
exchanges = {
'binance': {'options': {'defaultType': 'future'}},
'huobipro': {}
}
symbols = ['BTC/USDT', 'ETH/USDT', 'LTC/USDT', 'XRP/USDT', 'BCH/USDT']
coroutines = [watch_tickers_continuously(exchange_id, exchanges[exchange_id], symbols) for exchange_id in exchanges.keys()]
return await gather(*coroutines)
run(main())