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({ 'enableRateLimit': True, # this option enables the built-in rate limiter }) 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
async def main(asyncio_loop): exchange = ccxt.binance({ 'asyncio_loop': asyncio_loop, 'enableRateLimit': True, '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()
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()
async def print_ethbtc_ticker(): exchange = ccxt.binance({ 'enableRateLimit': True, }) await exchange.load_markets() # print(exchange.market (symbol)) print(await exchange.fetch_ticker(symbol)) await exchange.close()
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()
async def main(): exchange = ccxt.binance({ 'enableRateLimit': True, # required by the Manual }) 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()
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)
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
async def main(loop): # the exchange instance has to be reused # do not recreate the exchange before each call! exchange = ccxt.binance({ 'asyncio_loop': loop, 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_API_SECRET', # 'uid': 'YOUR_UID', # some exchanges require this # 'password': '******', # some exchanges require this # if you do not rate-limit your requests the exchange can ban you! # 'enableRateLimit': True, # 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()
def main(): # 实例化市场 exchanges = [ccxt.binance(), ccxt.bitfinex2(), ccxt.okex(), ccxt.gdax()] # 交易对 symbols = ['BTC/USDT', 'BTC/USD', 'BTC/USDT', 'BTC/USD'] tasks = [] for i in range(len(exchanges)): task = getData(exchanges[i], symbols[i]) tasks.append(asyncio.ensure_future(task)) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks))
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()
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({ 'enableRateLimit': True, # this option enables the built-in rate limiter }) 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)
async def test_bot_checker(): bfx = ccxt.bitfinex({ # # ↓ The "proxy" property setting below is for CORS-proxying only! # Do not use it if you don't know what a CORS proxy is. # https://github.com/ccxt/ccxt/wiki/Install#cors-access-control-allow-origin # You should only use the "proxy" setting if you're having a problem with Access-Control-Allow-Origin # In Python you rarely need to use it, if ever at all. # # 'proxy': 'https://cors-anywhere.herokuapp.com/', # # ↓ The "aiohttp_proxy" setting is for HTTP(S)-proxying (SOCKS, etc...) # It is a standard method of sending your requests through your proxies # This gets passed to the `asyncio` and `aiohttp` implementation directly # You can use this setting as documented here: # https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support # This is the setting you should be using with async version of ccxt in Python 3.5+ # # 'aiohttp_proxy': 'http://proxy.com', # 'aiohttp_proxy': 'http://*****:*****@some.proxy.com', # 'aiohttp_proxy': 'http://10.10.1.10:3128', 'enableRateLimit': False, }) binance = ccxt.binance({ 'enableRateLimit': False, }) try: # your code goes here... while True: ticker1 = await bfx.fetch_ticker('BTC/USD') ticker2 = await binance.fetch_ticker('BTC/USDT') if abs(ticker1["last"] - ticker2["last"]) / ( (ticker1["last"] + ticker2["last"]) / 2) > 0.01: print("Opportunity for arb: {} {} differ: {}%".format( ticker1["last"], ticker1["last"], (100 * abs(ticker1["last"] - ticker2["last"])) / ((ticker1["last"] + ticker2["last"]) / 2))) print("BFX: {} Binance: {}".format(ticker1["last"], ticker2["last"])) # await bfx.close() # await binance.close() await asyncio.sleep(1) except: # traceback.print_stack() pass finally: await bfx.close() await binance.close()
def get_async_client(exchange_id: "exchange id"): assert (config.SUPPORT_EXCHANGE) if exchange_id == "binance": return ccxt.binance({'enableRateLimit': True}) elif exchange_id == "bitfinex2": return ccxt.bitfinex2({'enableRateLimit': True}) elif exchange_id == "coinbasepro": return ccxt.coinbasepro({'enableRateLimit': True}) elif exchange_id == "huobipro": return ccxt.huobipro({'enableRateLimit': True}) elif exchange_id == "okex": return ccxt.okex({'enableRateLimit': True}) return None
async def run(): exchange = ccxt.binance({ 'apiKey': os.getenv('BINANCE_API_KEY'), 'secret': os.getenv('BINANCE_API_SECRET'), 'enableRateLimit': True }) symbol = 'BTC/USDT' everything = { 'margin': await load(exchange, symbol, 'margin') # 'spot': await load(exchange, symbol, 'spot'), # 'future': await load(exchange, symbol, 'future'), } await exchange.close() import pdb pdb.set_trace() return everything
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()
async def main(symbols): exchange = ccxt.binance({'enableRateLimit': True}) pg_pool = await asyncpg.create_pool(host=database_host, port=database_port, user=database_user, password=database_pass, database=database_name, command_timeout=60) async with pg_pool.acquire() as connection: async with connection.transaction(): print(f'Initalizing tables for {symbols}') for symbol in symbols: sql_value, sql_info = build_tables(symbol) await connection.execute(sql_value) await connection.execute(sql_info) while True: print(exchange.iso8601(exchange.milliseconds()), 'fetching', symbols, 'ticker from', exchange.name) for symbol in symbols: await handle_symbol(symbol, exchange, pg_pool)
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()
""" A ticker proxy seems like a good idea but not that important yet """ import asyncio import os import sys from pprint import pprint root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async_support as ccxt # noqa: E402 pprint(asyncio.get_event_loop().run_until_complete( ccxt.binance().fetch_ticker('ETH/BTC')))
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()
async def test_binance(): exchange = ccxt.binance() markets = await exchange.load_markets() await exchange.close() return markets
"event": "ob", "symbol": sys.argv[i], "params": { 'limit': limit } }) exchange = binance2({ # getattr(ccxt, exchange_id)({ "enableRateLimit": True, 'verbose': False, 'timeout': 5 * 1000, # 'wsproxy': 'http://185.93.3.123:8080/', }) print("simulating multiple endpoints to each symbol....") sys.stdout.flush() loop.run_until_complete(main(exchange, symbols, eventSymbols)) exchange = ccxt.binance({ # getattr(ccxt, exchange_id)({ "enableRateLimit": True, 'verbose': False, 'timeout': 5 * 1000, # 'wsproxy': 'http://185.93.3.123:8080/', }) print("simulating one endpoint to all symbols....") sys.stdout.flush() loop.run_until_complete(main(exchange, symbols, eventSymbols)) # loop.run_forever() # loop.stop() # loop.close() print("after complete")
async def test_binance(): binance = ccxt.binance() markets = await binance.load_markets() await binance.close() return markets
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({#ACTUAL exchange = ccxt.binance({ 'enableRateLimit': True, # this option enables the built-in rate limiter 'rateLimit': 1, # once every 3 seconds, 20 times per minute – will work #check # 'verbose': True }) count = 0 print('fileName of CSV is:', fname5) while True: if count == 0: # while count<5: tic = time.time() print( '______________________________count {}_______________________________________' .format(count)) print( '--------------------------------------------------------------' ) datetime_unix = exchange.milliseconds() # changed datetime_read = datetime.datetime.utcfromtimestamp( int(datetime_unix) / 1000) # 2020-06-19 04:11:24.165000 datetime_read_2 = datetime_read.strftime( '%H:%M:%S.%f') # 04:11:24.165000 ticker = await exchange.fetch_ticker(symbol) # 0actual toc = time.time() tocketty = toc - tic print('time taken is:', tocketty) count += 1 else: # while count<5: tic = time.time() print( '______________________________count {}_______________________________________' .format(count)) print( '--------------------------------------------------------------' ) datetime_unix = exchange.milliseconds() # changed datetime_read = datetime.datetime.utcfromtimestamp( int(datetime_unix) / 1000) #2020-06-19 04:11:24.165000 datetime_read_2 = datetime_read.strftime( '%H:%M:%S.%f') #04:11:24.165000 # this can be any call really ticker = await exchange.fetch_ticker(symbol) # 0actual print('ticker:', ticker) #ccxt1 # print(ticker['bids'][99], ticker['asks'][99]) #ccxt5 print('bid ask:', ticker['bid'], ticker['ask']) # ccxt5 print('bid ask:', ticker['bid'], ticker['ask']) # ccxt5 # print('tickertest:', ticker['ticker']) # working symbols_ = ticker['symbol'] timestamp = ticker['timestamp'] datetime_exchng = ticker['datetime'] high = ticker['high'] low = ticker['low'] bid = ticker['bid'] bidVolume = ticker['bidVolume'] ask = ticker['ask'] askVolume = ticker['askVolume'] vwap = ticker['vwap'] opened = ticker['open'] #cannot close = ticker['close'] last = ticker['last'] previousClose = ticker['previousClose'] change = ticker['change'] percentage = ticker['percentage'] baseVolume = ticker['baseVolume'] quoteVolume = ticker['quoteVolume'] info = ticker['info'] # 'info': {...........} # priceChange = info['priceChange'] # cannot priceChangePercent = info['priceChangePercent'] weightedAvgPrice = info['weightedAvgPrice'] prevClosePrice = info['prevClosePrice'] lastPrice = info['lastPrice'] lastQty = info['lastQty'] askPrice = info['askPrice'] askQty = info['askQty'] openPrice = info['openPrice'] highPrice = info['highPrice'] lowPrice = info['lowPrice'] volume = info['volume'] quoteVolume = info['quoteVolume'] openTime = info['openTime'] closeTime = info['closeTime'] firstId = info['firstId'] lastId = info['lastId'] count_info = info['count'] bid1 = ticker['bid'] ask1 = ticker['ask'] bid1_vol = ticker['bid'] ask1_vol = ticker['ask'] print(datetime_read_2, bid1, bid1_vol, ask1, ask1_vol) toc = time.time() toe = toc - tic tocketty = tocketty + toe avg_tocky = tocketty / count print(' Average time taken:', avg_tocky) print(' TOTAL Time Run (Since Inception):', tocketty) # print(' Time Unable to print:', unable_print) print('time taken is:', toe) with open(fname5, 'a+', newline='') as csv: csvwriter = writer(csv) csvwriter.writerow([ symbols_, timestamp, datetime_exchng, high, low, bid, bidVolume, ask, askVolume, vwap, opened, close, last, previousClose, change, percentage, baseVolume, quoteVolume, priceChange, priceChangePercent, weightedAvgPrice, prevClosePrice, lastPrice, lastQty, askPrice, askQty, openPrice, highPrice, lowPrice, volume, quoteVolume, openTime, closeTime, firstId, lastId, count_info ]) count += 1
def __init__(self, loop, config): self.ob_constant = OD_TICK_TIMER self.bl_constant = BALANCE_TICK_TIMER self.trade_constant = TRADE_TICK_TIMER self.stop_tick_time = datetime.datetime.now() + datetime.timedelta( seconds=TICK_TIMER) self.orderbook_tick_time = datetime.datetime.now( ) + datetime.timedelta(seconds=self.ob_constant) self.balance_tick_time = datetime.datetime.now() + datetime.timedelta( seconds=self.bl_constant) self.trade_tick_time = datetime.datetime.now() + datetime.timedelta( seconds=self.trade_constant) self.info_tick_time = datetime.datetime.now() + datetime.timedelta( seconds=INFO_TIMER) self.config = config self.orderbook_count = 0 self.pair_info = dict() self.logger = None if 'logger' in self.config.keys(): self.logger = self.config['logger'] self.exhange = config['exchange'] self.is_auth = False self.name = '[ccxt %s]' % self.exhange self.pair_list = set() if self.exhange == 'liqui': self.ob_constant = 30 self.bl_constant = 60 self.ccxt_it_queue = self.config['ccxt_in_queue'] self.ccxt_out_queue = self.config['ccxt_out_queue'] self.pair_list = self.config['pairs'] # for i in self.config['pairs']: # i['balance_tick'] = True # self.pair_list.add( i['name'] ) auth = {} if 'auth' in self.config.keys(): auth = self.config['auth'] self.is_auth = True self.name = '[ccxt %s %s*]' % (self.exhange, auth['apiKey'][:4]) asyncio.set_event_loop(loop) if self.exhange == 'hitbtc': loop.create_task(self.run_loop(ccxt.hitbtc(auth))) elif self.exhange == 'coinmarketcap': loop.create_task(self.run_loop(ccxt.coinmarketcap())) elif self.exhange == 'binance': loop.create_task(self.run_loop(ccxt.binance(auth))) elif self.exhange == 'bitmex': loop.create_task(self.run_loop(ccxt.bitmex(auth))) elif self.exhange == 'huobipro': loop.create_task(self.run_loop(ccxt.huobipro())) elif self.exhange == 'liqui': loop.create_task(self.run_loop(ccxt.liqui(auth))) elif self.exhange == 'bitfinex2': loop.create_task(self.run_loop(ccxt.bitfinex2(auth))) elif self.exhange == 'bitfinex': loop.create_task(self.run_loop(ccxt.bitfinex(auth))) elif self.exhange == 'okex': loop.create_task(self.run_loop(ccxt.okex(auth))) elif self.exhange == 'kucoin': loop.create_task(self.run_loop(ccxt.kucoin(auth))) elif self.exhange == 'bittrex': loop.create_task(self.run_loop(ccxt.bittrex(auth))) elif self.exhange == 'qryptos': loop.create_task(self.run_loop(ccxt.qryptos(auth))) elif self.exhange == 'kraken': loop.create_task(self.run_loop(ccxt.kraken(auth))) loop.run_forever()
async def test_binance(): exchange = ccxt.binance({'enableRateLimit': True}) markets = await exchange.load_markets() await exchange.close() return markets
# -*- coding: utf-8 -*- import asyncio import os import sys from pprint import pprint root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async_support as ccxt # noqa: E402 pprint(asyncio.get_event_loop().run_until_complete(ccxt.binance().fetch_ticker('ETH/BTC')))
# -*- coding: utf-8 -*- import asyncio import os import sys from pprint import pprint root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async_support as ccxt # noqa: E402 pprint(asyncio.run(ccxt.binance().fetch_ticker('ETH/BTC')))
inicio = round(time.time() * 1000) # INICIO EN ms root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async_support as ccxt # noqa: E402 # CLAVES A BINANCE usuario = claves.api_key clave = claves.secret exchange = ccxt.binance({ 'apiKey': usuario, 'secret': clave, 'enableRateLimit': True, # this is required, as documented in the Manual! }) async def test(): response = None try: await exchange.load_markets('ADA/ETH') await exchange.load_markets('ETH/BTC') # force-preload markets first exchange.verbose = True # this is for debugging
} RESOLUTION_PD2CCXT = { "trades": None, "1min": "1m", "5min": "5m", "15min": "15m", "1h": "1h", "4h": "4h", "1d": "1d" } SUPPORT_EXCHANGE = { "binance": ccxt.binance({ 'enableRateLimit': True, # this option enables the built-in rate limiter }), "coinbasepro": ccxt.coinbasepro({ 'enableRateLimit': True, # this option enables the built-in rate limiter }), "bitfinex2": ccxt.bitfinex2({ 'enableRateLimit': True, # this option enables the built-in rate limiter }), "huobipro": ccxt.huobipro({ 'enableRateLimit': True, # this option enables the built-in rate limiter