async def main(): exchange = ccxt.okex({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', # okex requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication '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_trading': '2', }) 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 main(): exchange = ccxt.okex({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', # okex requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication 'password': '******', # 'verbose': True, # for debug output }) await exchange.load_markets() symbol = 'BTC/USDT' # okex requires a symbol for borrowing code = 'BTC' amount = 1 currency = exchange.currency(code) market = exchange.market(symbol) try: response = await exchange.margin_post_accounts_borrow({ # uncomment to set a user-defined order id for this borrow # this may be handy if you're going to repay it later by this id # 'client_oid': exchange.uuid(), # can be any unique string 'instrument_id': market['id'], 'currency': currency['id'], 'amount': exchange.currency_to_precision(code, amount) }) pprint(response) except ccxt.InsufficientFunds as e: print('margin_post_accounts_borrow() failed – not enough funds') print(e) except Exception as e: print('margin_post_accounts_borrow() failed') print(e) await exchange.close()
async def main(): exchange = ccxt.okex({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', # okex requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication 'password': '******' }) await loop(exchange) await exchange.close()
async def main(): exchange = ccxt.okex({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', # okex requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication 'password': '******', # to always default to 'margin' balance type 'options': { 'fetchBalance': 'margin', }, }) await loop(exchange) 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 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
async def private_test(cl): okex = ccxt.okex(get_okex_params()) proxy = await aclient.client() await asyncio.sleep(5) await account(okex, cl, proxy) # close await okex.close() await asyncio.sleep(5) await proxy.close() cl.close() await asyncio.sleep(1)
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 client(): api = ccxt.okex(get_okex_params()) await asyncio.sleep(2) okex = await okws.client() await okex.redis_clear() ret = await okex.open_ws('tests', get_okex_params()) logger.info(ret) assert ret['errorCode'] == 80000 # 等待 tests 服务开启 await asyncio.sleep(10) ret = await okex.servers() logger.info(f"servers:{ret}") assert ret['errorCode'] == 80000 assert ret['message'] == ['tests'] # 开始测试 -------------------------------------------------------------------------------------------- await ticker(okex) await position(okex, api) await instruments(okex) await candle(okex) # 结束测试 --------------------------------------------------------------------------------------------- ret = await okex.close_ws('tests') logger.info(ret) ret = await okex.close_ws('tests--------') logger.info(ret) assert ret['errorCode'] == 80011 ret = await okex.servers() logger.info(f"servers:{ret}") assert ret['errorCode'] == 80000 assert ret['message'] == [] await okex.server_quit() await okex.close() await asyncio.sleep(1) await api.close()
async def main(): exchange = ccxt.okex({ 'apiKey': 'YOUR_API_KEY', # https://github.com/ccxt/ccxt/wiki/Manual#authentication 'secret': 'YOUR_API_SECRET', 'password': '******', 'options': { 'defaultType': 'futures', }, }) 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['futures']]) 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()
async def main(asyncio_loop): exchange = ccxt.okex({ 'asyncio_loop': asyncio_loop, 'enableRateLimit': True, 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', # okex requires this: https://github.com/ccxt/ccxt/wiki/Manual#authentication 'password': '******', # 'verbose': True, # for debug output }) await exchange.load_markets() symbol = 'BTC/USDT' # okex requires a symbol for borrowing code = 'BTC' amount = 1 currency = exchange.currency(code) market = exchange.market(symbol) try: response = await exchange.margin_post_accounts_repayment({ # https://github.com/ccxt/ccxt/blob/master/examples/py/async-okex-margin-borrow.py # uncomment to repay a particular borrow by id # 'borrow_id': 'YOUR_BORROW_ID_RECEIVED_FROM_BORROWING', # uncomment to set a user-defined order id for this repayment # 'client_oid': 'YOUR_CLIENT_ORDER_ID_FROM_BORROWING', # one of borrow_id or client_oid is required! 'instrument_id': market['id'], 'currency': currency['id'], 'amount': exchange.currency_to_precision(code, amount) }) pprint(response) except ccxt.InsufficientFunds as e: print('margin_post_accounts_repayment() failed – not enough funds') print(e) except Exception as e: print('margin_post_accounts_repayment() failed') print(e) await exchange.close()
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() print('CCXT Version:', ccxt.__version__) loop = get_event_loop() exchange = ccxt.okex({ 'asyncio_loop': loop, 'enableRateLimit': True, # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit 'apiKey': 'YOUR_API_KEY', # https://github.com/ccxt/ccxt/wiki/Manual#authentication 'secret': 'YOUR_API_SECRET', 'password': '******', 'options': { 'defaultType': 'futures', }, }) loop.run_until_complete(main(exchange))
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 }), "okex": ccxt.okex({ 'enableRateLimit': True, # this option enables the built-in rate limiter }), "kraken": ccxt.kraken({ 'enableRateLimit': True, # this option enables the built-in rate limiter }), "bitmex": ccxt.bitmex({ 'enableRateLimit': True, # this option enables the built-in rate limiter }) }
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()