async def run(): api_key = os.environ['BITPANDAAPIKEY'] client = CryptoXLib.create_bitpanda_client(api_key) # Bundle several subscriptions into a single websocket client.compose_subscriptions([ AccountSubscription(callbacks = [account_update]), PricesSubscription([Pair("BTC", "EUR")]), OrderbookSubscription([Pair("BTC", "EUR")], "50", callbacks = [order_book_update]), CandlesticksSubscription([CandlesticksSubscriptionParams(Pair("BTC", "EUR"), TimeUnit.MINUTES, 1)]), MarketTickerSubscription([Pair("BTC", "EUR")]) ]) # Bundle another subscriptions into a separate websocket client.compose_subscriptions([ OrderbookSubscription([Pair("ETH", "EUR")], "3", callbacks = [order_book_update]), ]) # Bundle another subscriptions into a separate websocket client.compose_subscriptions([ TradingSubscription(callbacks = [trading_update]), OrdersSubscription(callbacks = [orders_update]), ]) # Execute all websockets asynchronously await client.start_websockets()
async def run(): api_key = os.environ['BITVAVOAPIKEY'] sec_key = os.environ['BITVAVOSECKEY'] client = CryptoXLib.create_bitvavo_client(api_key, sec_key) print("Time:") await client.get_time() print("Exchange info:") await client.get_exchange_info() print("Assets:") await client.get_assets() print("Open orders:") await client.get_open_orders() print("Create order:") try: await client.create_order(pair = Pair("BTC", "EUR"), side = enums.OrderSide.BUY, type = enums.OrderType.LIMIT, amount = "10000", price = "1") except BitvavoException as e: print(e) print("Cancel order:") try: await client.cancel_order(pair = Pair("BTC", "EUR"), order_id = "1") except BitvavoException as e: print(e) print("Balance:") await client.get_balance() await client.close()
async def run(): api_key = os.environ['APIKEY'] sec_key = os.environ['SECKEY'] client = CryptoXLib.create_binance_usds_m_futures_client(api_key, sec_key) # Bundle several subscriptions into a single websocket client.compose_subscriptions([ OrderBookTickerSubscription(callbacks=[orderbook_ticker_update]), OrderBookSymbolTickerSubscription(symbol=Pair("BTC", "USDT"), callbacks=[orderbook_ticker_update]), CandlestickSubscription(interval=Interval.I_1MIN, symbol=Pair('BTC', 'USDT'), callbacks=[candlestick_update]) ]) # Bundle another subscriptions into a separate websocket client.compose_subscriptions([ AccountSubscription(callbacks=[account_update]), CompositeIndexSubscription(pair=Pair('DEFI', 'USDT')) ]) # Execute all websockets asynchronously await client.start_websockets() await client.close()
async def run(): # to retrieve your API/SEC key go to your bitforex account, create the keys and store them in # BITFOREXAPIKEY/BITFOREXSECKEY environment variables api_key = os.environ['BITFOREXAPIKEY'] sec_key = os.environ['BITFOREXSECKEY'] bitforex = CryptoXLib.create_bitforex_client(api_key, sec_key) # Bundle several subscriptions into a single websocket bitforex.compose_subscriptions([ OrderBookSubscription(pair=Pair('ETH', 'BTC'), depth="0", callbacks=[order_book_update]), OrderBookSubscription(pair=Pair('ETH', 'USDT'), depth="0", callbacks=[order_book_update2]), TradeSubscription(pair=Pair('ETH', 'BTC'), size="2", callbacks=[trade_update]), ]) # Bundle subscriptions into a separate websocket bitforex.compose_subscriptions([ TickerSubscription(pair=Pair('BTC', 'USDT'), size="2", interval=enums.CandlestickInterval.I_1MIN, callbacks=[ticker_update]), Ticker24hSubscription(pair=Pair('BTC', 'USDT'), callbacks=[ticker24_update]) ]) # Execute all websockets asynchronously await bitforex.start_websockets() await bitforex.close()
async def test_multiple_subscription(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ MarketTickerSubscription([Pair("BTC", "EUR")], callbacks = [message_counter.generate_callback(2, name = "MarketTicker")]), OrderbookSubscription([Pair("BTC", "EUR")], "1", callbacks = [message_counter.generate_callback(1, name = "Orderbook")]) ]) await self.assertWsMessageCount(message_counter)
async def test_isolated_listen_key(self): response = await self.client.get_isolated_margin_listen_key( pair=Pair('BTC', 'USDT')) self.assertTrue(self.check_positive_response(response)) response = await self.client.keep_alive_isolated_margin_listen_key( pair=Pair('BTC', 'USDT'), listen_key=response['response']['listenKey']) self.assertTrue(self.check_positive_response(response))
async def test_change_margin_type(self): position = await self.client.get_position(pair = Pair('ETH', 'USDT')) margin_type = position['response'][0]['marginType'] if margin_type == 'cross': new_margin_type = enums.MarginType.ISOLATED else: new_margin_type = enums.MarginType.CROSSED response = await self.client.change_margin_type(pair = Pair('ETH', 'USDT'), margin_type = new_margin_type) self.assertTrue(self.check_positive_response(response))
async def run(): api_key = os.environ['APIKEY'] sec_key = os.environ['SECKEY'] client = CryptoXLib.create_binance_coin_m_futures_client(api_key, sec_key) print("Ping:") await client.ping() print("Server time:") await client.get_time() print("Exchange info:") await client.get_exchange_info() print("Order book:") await client.get_orderbook(symbol='BTCUSD_PERP', limit=enums.DepthLimit.L_5) print("Trades:") await client.get_trades(symbol='BTCUSD_PERP', limit=5) print("Historical trades:") await client.get_historical_trades(symbol='BTCUSD_PERP', limit=5) print("Aggregate trades:") await client.get_aggregate_trades(symbol='BTCUSD_PERP', limit=5) print("Index price candlesticks:") await client.get_index_price_candlesticks(pair=Pair('BTC', 'USD'), interval=enums.Interval.I_1MIN) print("24hour price ticker:") await client.get_24h_price_ticker(pair=Pair('BTC', 'USD')) print("Price ticker:") await client.get_price_ticker(pair=Pair('BTC', 'USD')) print("Best order book ticker:") await client.get_orderbook_ticker(pair=Pair('BTC', 'USD')) print("Create limit order:") try: await client.create_order( symbol='BTCUSD_PERP', side=enums.OrderSide.BUY, type=enums.OrderType.LIMIT, quantity="1", price="0", time_in_force=enums.TimeInForce.GOOD_TILL_CANCELLED, new_order_response_type=enums.OrderResponseType.FULL) except BinanceException as e: print(e) await client.close()
async def main_loop(client: BinanceClient) -> None: i = 0 sleep_sec = 1 while True: if i == 3: print("Unsubscribing BTC/USDT") await client.unsubscribe_subscriptions([sub.subscriptions[0][0]]) if i == 6: print("Unsubscribing BNB/USDT") await client.unsubscribe_subscriptions([sub.subscriptions[1][0]]) if i == 9: print("Unsubscribing ADA/USDT and DOT/USDT") await client.unsubscribe_subscription_set( sub.subscription_set_ids[2]) if i == 12: print("Unsubscribing all") await client.unsubscribe_all() if i == 15: print("Subscribe BNB/BTC") await client.add_subscriptions(sub.subscription_set_ids[0], [ OrderBookSymbolTickerSubscription(Pair("BNB", "BTC"), callbacks=[sub.call1]) ]) if i == 18: print("Subscribe ETH/USDT again") await client.add_subscriptions(sub.subscription_set_ids[0], [ OrderBookSymbolTickerSubscription(Pair("ETH", "USDT"), callbacks=[sub.call1]) ]) if i == 21: print("Subscribe ADA/USDT and XRP/USDT again") await client.add_subscriptions(sub.subscription_set_ids[1], [ OrderBookSymbolTickerSubscription(Pair("ADA", "USDT"), callbacks=[sub.call2]), OrderBookSymbolTickerSubscription(Pair("XRP", "USDT"), callbacks=[sub.call2]) ]) if i == 24: print("Shutting down websockets.") await client.shutdown_websockets() if i == 27: print("Quitting the main loop.") break i += 1 await asyncio.sleep(sleep_sec)
async def test_update_isolated_position_margin(self): position = await self.client.get_position(pair = Pair('BNB', 'USDT')) margin_type = position['response'][0]['marginType'] if margin_type == 'cross': await self.client.change_margin_type(pair = Pair('BNB', 'USDT'), margin_type = enums.MarginType.ISOLATED) await self.client.create_order(pair = Pair('BNB', 'USDT'), side = enums.OrderSide.BUY, type = enums.OrderType.MARKET, quantity = '0.1') response = await self.client.update_isolated_position_margin(pair = Pair('BNB', 'USDT'), quantity = '0.001', type = 2) self.assertTrue(self.check_positive_response(response))
async def test_price_subscription(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ PricesSubscription([Pair("BTC", "EUR")], callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_get_price_ticks2(self): response = await self.client.get_price_tick( Pair('ETH', 'EUR'), from_timestamp=datetime.datetime.now() - datetime.timedelta(hours=2), to_timestamp=datetime.datetime.now()) self.assertTrue(self.check_positive_response(response))
async def orders_update(response: dict, websocket: ClientWebsocketHandle) -> None: print(f"Callback orders_update: [{response}]") # as soon as ORDERS channel subscription is confirmed, fire testing orders if response['type'] == 'SUBSCRIPTIONS': await websocket.send( CreateOrderMessage(pair=Pair('BTC', 'EUR'), type=OrderType.LIMIT, side=OrderSide.BUY, amount="0.0001", price="10")) await websocket.send( CancelOrderMessage(order_id="d44cf37a-335d-4936-9336-4c7944cd00ec") ) await websocket.send( CancelAllOrdersMessage( order_ids=["d44cf37a-335d-4936-9336-4c7944cd00ec"])) await websocket.send( UpdateOrderMessage(amount="1", order_id="d44cf37a-335d-4936-9336-4c7944cd00ec") )
async def test_detph2(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ DepthSubscription(Pair('BTC', 'USDT'), 0, callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_blvt(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ BlvtSubscription(Pair('BTC', 'UP'), callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_order_book_L2_subscription(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ OrderbookL2Subscription([Pair('BTSE', 'BTC')], depth = 1, callbacks = [message_counter.generate_callback(2)]), ]) await self.assertWsMessageCount(message_counter)
async def liquidation_orders(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ LiquidationOrdersSubscription(Pair('BTC', 'USDT'), callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_candlestick(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ CandlestickSubscription(Pair("BTC", "USDT"), enums.Interval.I_1MIN, callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_mini_ticker(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ MiniTickerSubscription(Pair('BTC', 'USDT'), callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_order_book_subscription(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ OrderbookSubscription([Pair("BTC", "EUR")], "1", [message_counter.generate_callback(1)]), ]) await self.assertWsMessageCount(message_counter)
async def test_mark_price(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ MarkPriceSubscription(Pair("BTC", "USDT"), True, callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_market_ticker_subscription(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ MarketTickerSubscription([Pair("BTC", "EUR")], callbacks = [message_counter.generate_callback(2)]) ]) await self.assertWsMessageCount(message_counter)
async def test_get_open_order(self): with self.assertRaises(BinanceRestException) as cm: await self.client.get_open_order(symbol=Pair('BTC', 'USDT'), order_id=1) e = cm.exception self.assertTrue(self.check_error_code(e, '400', '-2013'))
async def test_trade_subscription(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ TradeSubscription([Pair('BTC', 'USDT')], callbacks = [message_counter.generate_callback(1)]), ]) await self.assertWsMessageCount(message_counter)
async def run(): api_key = os.environ['BIBOXAPIKEY'] sec_key = os.environ['BIBOXSECKEY'] bibox = CryptoXLib.create_bibox_client(api_key, sec_key) print("Ping:") await bibox.get_ping() print("Pair list:") await bibox.get_pairs() print("Exchange info:") await bibox.get_exchange_info() print("User assets:") await bibox.get_spot_assets(full=True) print("Create order:") try: await bibox.create_order(pair=Pair('ETH', 'BTC'), order_type=enums.OrderType.LIMIT, order_side=enums.OrderSide.BUY, price="1", quantity="1") except BiboxException as e: print(e) print("Cancel order:") await bibox.cancel_order(order_id="1234567890") await bibox.close()
async def test_best_orderbook_symbol_ticker(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ OrderBookSymbolTickerSubscription(Pair('BTC', 'USDT'), callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_aggregate_trade(self): message_counter = WsMessageCounter() self.client.compose_subscriptions([ AggregateTradeSubscription(Pair("BTC", "USDT"), callbacks = [message_counter.generate_callback(1)]) ]) await self.assertWsMessageCount(message_counter)
async def test_create_order(self): response = await self.client.create_order(pair=Pair('BTC', 'USD'), type=enums.OrderType.LIMIT, side=enums.OrderSide.BUY, amount="10000", price="1") self.assertTrue(self.check_positive_response(response))
async def test_bswap_swap(self): with self.assertRaises(BinanceRestException) as cm: await self.client.bswap_swap(Pair('BTC', 'USDT'), '100000000000') e = cm.exception self.assertEqual(e.status_code, 400) self.assertEqual(e.body['code'], -12000)
async def test_create_stop_limit_order(self): with self.assertRaises(BitpandaRestException) as cm: await self.client.create_stop_limit_order(Pair("BTC", "EUR"), enums.OrderSide.BUY, "10000", "1", "1") e = cm.exception self.assertEqual(e.status_code, 422)