repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
msp1974/ViewAssist_Companion_App | https://github.com/msp1974/ViewAssist_Companion_App/blob/5f4533c753120a8b59087b19fda2b26c42284aa7/custom_components/vaca/config_flow.py | custom_components/vaca/config_flow.py | """Config flow for Wyoming integration."""
from __future__ import annotations
import logging
# pylint: disable-next=hass-component-root-import
from homeassistant.components.wyoming.config_flow import WyomingConfigFlow
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
class VAWyomingConfigFlow(WyomingConfigFlow, domain=DOMAIN):
"""Handle a config flow for Wyoming integration."""
| python | Apache-2.0 | 5f4533c753120a8b59087b19fda2b26c42284aa7 | 2026-01-05T07:13:44.720990Z | false |
msp1974/ViewAssist_Companion_App | https://github.com/msp1974/ViewAssist_Companion_App/blob/5f4533c753120a8b59087b19fda2b26c42284aa7/custom_components/vaca/stt.py | custom_components/vaca/stt.py | """Support for Wyoming speech-to-text services."""
from collections.abc import AsyncIterable
import logging
from wyoming.asr import Transcribe, Transcript
from wyoming.audio import AudioChunk, AudioStart, AudioStop
from wyoming.client import AsyncTcpClient
from homeassistant.components import stt
from homeassistant.components.wyoming import DomainDataItem, WyomingService
# pylint: disable-next=hass-component-root-import
from homeassistant.components.wyoming.error import WyomingError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN, SAMPLE_CHANNELS, SAMPLE_RATE, SAMPLE_WIDTH
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Wyoming speech-to-text."""
item: DomainDataItem = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[
WyomingSttProvider(config_entry, item.service),
]
)
class WyomingSttProvider(stt.SpeechToTextEntity):
"""Wyoming speech-to-text provider."""
def __init__(
self,
config_entry: ConfigEntry,
service: WyomingService,
) -> None:
"""Set up provider."""
self.service = service
asr_service = service.info.asr[0]
model_languages: set[str] = set()
for asr_model in asr_service.models:
if asr_model.installed:
model_languages.update(asr_model.languages)
self._supported_languages = list(model_languages)
self._attr_name = asr_service.name
self._attr_unique_id = f"{config_entry.entry_id}-stt"
@property
def supported_languages(self) -> list[str]:
"""Return a list of supported languages."""
return self._supported_languages
@property
def supported_formats(self) -> list[stt.AudioFormats]:
"""Return a list of supported formats."""
return [stt.AudioFormats.WAV]
@property
def supported_codecs(self) -> list[stt.AudioCodecs]:
"""Return a list of supported codecs."""
return [stt.AudioCodecs.PCM]
@property
def supported_bit_rates(self) -> list[stt.AudioBitRates]:
"""Return a list of supported bitrates."""
return [stt.AudioBitRates.BITRATE_16]
@property
def supported_sample_rates(self) -> list[stt.AudioSampleRates]:
"""Return a list of supported samplerates."""
return [stt.AudioSampleRates.SAMPLERATE_16000]
@property
def supported_channels(self) -> list[stt.AudioChannels]:
"""Return a list of supported channels."""
return [stt.AudioChannels.CHANNEL_MONO]
async def async_process_audio_stream(
self, metadata: stt.SpeechMetadata, stream: AsyncIterable[bytes]
) -> stt.SpeechResult:
"""Process an audio stream to STT service."""
try:
async with AsyncTcpClient(self.service.host, self.service.port) as client:
# Set transcription language
await client.write_event(Transcribe(language=metadata.language).event())
# Begin audio stream
await client.write_event(
AudioStart(
rate=SAMPLE_RATE,
width=SAMPLE_WIDTH,
channels=SAMPLE_CHANNELS,
).event(),
)
async for audio_bytes in stream:
chunk = AudioChunk(
rate=SAMPLE_RATE,
width=SAMPLE_WIDTH,
channels=SAMPLE_CHANNELS,
audio=audio_bytes,
)
await client.write_event(chunk.event())
# End audio stream
await client.write_event(AudioStop().event())
while True:
event = await client.read_event()
if event is None:
_LOGGER.debug("Connection lost")
return stt.SpeechResult(None, stt.SpeechResultState.ERROR)
if Transcript.is_type(event.type):
transcript = Transcript.from_event(event)
text = transcript.text
break
except (OSError, WyomingError):
_LOGGER.exception("Error processing audio stream")
return stt.SpeechResult(None, stt.SpeechResultState.ERROR)
return stt.SpeechResult(
text,
stt.SpeechResultState.SUCCESS,
)
| python | Apache-2.0 | 5f4533c753120a8b59087b19fda2b26c42284aa7 | 2026-01-05T07:13:44.720990Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/setup.py | setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open("requirements.txt", "r") as fh:
requirements = fh.readlines()
requirements = [line.strip() for line in requirements]
setuptools.setup(
name="cryptoxlib-aio",
version="5.3.0",
author="nardew",
author_email="cryptoxlib.aio@gmail.com",
description="Cryptoexchange asynchronous python client",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/nardew/cryptoxlib-aio",
packages=setuptools.find_packages(),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Framework :: AsyncIO",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
"Typing :: Typed",
],
install_requires=requirements,
python_requires='>=3.6.1',
)
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/binance_coin_m_futures.py | tests/e2e/binance_coin_m_futures.py | import unittest
import os
import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.BinanceFuturesWebsocket import AggregateTradeSubscription, MarkPriceSubscription, \
MarkPriceAllSubscription, AllMarketLiquidationOrdersSubscription, AllMarketMiniTickersSubscription, \
AllMarketTickersSubscription, MiniTickerSubscription, OrderBookTickerSubscription, \
OrderBookSymbolTickerSubscription, LiquidationOrdersSubscription, BlvtCandlestickSubscription, \
BlvtSubscription, CompositeIndexSubscription, DepthSubscription, CandlestickSubscription, \
ContContractCandlestickSubscription, TickerSubscription
from cryptoxlib.clients.binance.exceptions import BinanceRestException
from cryptoxlib.Pair import Pair
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['BINANCEAPIKEY']
sec_key = os.environ['BINANCESECKEY']
test_api_key = os.environ['BINANCEFUTURESTESTAPIKEY']
test_sec_key = os.environ['BINANCEFUTURESTESTSECKEY']
class BinanceCOINMFuturesMarketRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_coin_m_futures_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def test_get_ping(self):
response = await self.client.ping()
self.assertTrue(self.check_positive_response(response))
async def test_get_time(self):
response = await self.client.get_time()
self.assertTrue(self.check_positive_response(response))
async def test_get_exchange_info(self):
response = await self.client.get_exchange_info()
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book(self):
response = await self.client.get_orderbook(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_trades(self):
response = await self.client.get_trades(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_historical_trades(self):
response = await self.client.get_historical_trades(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_aggregate_trades(self):
response = await self.client.get_aggregate_trades(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_candlesticks(self):
response = await self.client.get_candlesticks(symbol = 'BTCUSD_PERP', interval = enums.Interval.I_1MIN)
self.assertTrue(self.check_positive_response(response))
async def test_get_cont_contract_candlesticks(self):
response = await self.client.get_cont_contract_candlesticks(pair = Pair('BTC', 'USD'),
interval = enums.Interval.I_1MIN,
contract_type = enums.ContractType.PERPETUAL)
self.assertTrue(self.check_positive_response(response))
async def test_get_index_price_candlesticks(self):
response = await self.client.get_index_price_candlesticks(pair = Pair('BTC', 'USD'), interval = enums.Interval.I_1MIN)
self.assertTrue(self.check_positive_response(response))
async def test_get_mark_price_candlesticks(self):
response = await self.client.get_mark_price_candlesticks(symbol = 'BTCUSD_PERP', interval = enums.Interval.I_1MIN)
self.assertTrue(self.check_positive_response(response))
async def test_get_mark_price(self):
response = await self.client.get_mark_index_price(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_fund_rate_history(self):
response = await self.client.get_fund_rate_history(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_24h_price_ticker(self):
response = await self.client.get_24h_price_ticker(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_price_ticker(self):
response = await self.client.get_price_ticker(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_best_orderbook_ticker(self):
response = await self.client.get_orderbook_ticker(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_open_interest(self):
response = await self.client.get_open_interest(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_open_interest_hist(self):
response = await self.client.get_open_interest_hist(pair = Pair('BTC', 'USD'), interval = enums.Interval.I_1D,
contract_type = enums.ContractType.PERPETUAL)
self.assertTrue(self.check_positive_response(response))
async def test_get_top_long_short_account_ratio(self):
response = await self.client.get_top_long_short_account_ratio(pair = Pair('BTC', 'USD'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
async def test_get_top_long_short_position_ratio(self):
response = await self.client.get_top_long_short_position_ratio(pair = Pair('BTC', 'USD'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
class BinanceCOINMFuturesAccountRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_coin_m_futures_testnet_client(test_api_key, test_sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
def check_error_code(self, e: BinanceRestException, status: str, code: str):
return str(e.status_code) == status and str(e.body['code']) == code
async def test_change_position_type(self):
# make sure some position exists in order for the change of position to fail
await self.client.create_order(symbol = "BTCUSD_PERP", side = enums.OrderSide.BUY,
type = enums.OrderType.MARKET, quantity = '10')
with self.assertRaises(BinanceRestException) as cm:
current_type = await self.client.get_position_type()
response = await self.client.change_position_type(not current_type['response']['dualSidePosition'])
self.assertTrue(self.check_positive_response(response))
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-4068'))
async def test_get_position_type(self):
response = await self.client.get_position_type()
self.assertTrue(self.check_positive_response(response))
async def test_get_all_orders(self):
response = await self.client.get_all_orders(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
# market order
async def test_create_order1(self):
current_position_type = await self.client.get_position_type()
if current_position_type['response']['dualSidePosition']:
await self.client.change_position_type(False)
response = await self.client.create_order(symbol = 'BTCUSD_PERP', side = enums.OrderSide.BUY,
type = enums.OrderType.MARKET, quantity = '1')
self.assertTrue(self.check_positive_response(response))
# limit order
async def test_create_order2(self):
current_position_type = await self.client.get_position_type()
if current_position_type['response']['dualSidePosition']:
await self.client.change_position_type(False)
response = await self.client.create_order(symbol = 'BTCUSD_PERP', side = enums.OrderSide.BUY,
type = enums.OrderType.LIMIT, quantity = '1', price = '2000',
time_in_force = enums.TimeInForce.GOOD_TILL_CANCELLED)
self.assertTrue(self.check_positive_response(response))
async def test_get_order(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.get_order(symbol = 'BTCUSD_PERP', order_id = 1)
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2013'))
async def test_cancel_order(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.cancel_order(symbol = "BTCUSD_PERP", order_id = 1)
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2011'))
async def test_cancel_all_orders(self):
response = await self.client.cancel_all_orders(symbol = "BTCUSD_PERP")
self.assertTrue(self.check_positive_response(response))
@unittest.expectedFailure
# not supported for testnet
async def test_auto_cancel_orders(self):
response = await self.client.auto_cancel_orders(symbol = Pair('BTC', 'USDT'), countdown_time_ms = 0)
self.assertTrue(self.check_positive_response(response))
async def test_get_open_order(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.get_open_order(symbol = 'BTCUSD_PERP', order_id = 1)
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2013'))
async def test_get_all_open_orders(self):
response = await self.client.get_all_open_orders(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_balance(self):
response = await self.client.get_balance()
self.assertTrue(self.check_positive_response(response))
async def test_get_account(self):
response = await self.client.get_account()
self.assertTrue(self.check_positive_response(response))
async def test_change_init_leverage(self):
response = await self.client.change_init_leverage(symbol = "BTCUSD_PERP", leverage = 1)
self.assertTrue(self.check_positive_response(response))
async def test_change_margin_type(self):
position = await self.client.get_position(pair = Pair('BTC', '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(symbol = Pair('BTC', 'USDT'), margin_type = new_margin_type)
self.assertTrue(self.check_positive_response(response))
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(symbol = Pair('BNB', 'USDT'), margin_type = enums.MarginType.ISOLATED)
await self.client.create_order(symbol = Pair('BNB', 'USDT'), side = enums.OrderSide.BUY,
type = enums.OrderType.MARKET, quantity = '0.1')
response = await self.client.update_isolated_position_margin(symbol = Pair('BNB', 'USDT'), quantity = '0.001',
type = 2)
self.assertTrue(self.check_positive_response(response))
async def test_get_position_margin_change_history(self):
response = await self.client.get_position_margin_change_history(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_position(self):
response = await self.client.get_position()
self.assertTrue(self.check_positive_response(response))
async def test_get_position2(self):
response = await self.client.get_position(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_account_trades(self):
response = await self.client.get_account_trades(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_income_history(self):
response = await self.client.get_income_history(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_notional_and_leverage_brackets_for_pair(self):
response = await self.client.get_notional_and_leverage_brackets_for_pair(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_adl_quantile(self):
response = await self.client.get_adl_quantile(symbol = "BTCUSD_PERP")
self.assertTrue(self.check_positive_response(response))
async def test_get_force_orders(self):
response = await self.client.get_force_orders(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
async def test_get_commission_rate(self):
response = await self.client.get_commission_rate(symbol = 'BTCUSD_PERP')
self.assertTrue(self.check_positive_response(response))
class BinanceCOINMFuturesMarketWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_coin_m_futures_client(api_key, sec_key)
async def test_aggregate_trade(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AggregateTradeSubscription(symbol = "BTCUSD_PERP", callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_mark_price(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
MarkPriceSubscription(symbol = "BTCUSD_PERP", frequency1sec = True, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_mark_price_all(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
MarkPriceAllSubscription(True, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_candlestick(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
CandlestickSubscription(symbol = "BTCUSD_PERP", interval = enums.Interval.I_1MIN, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_cont_contract_candlestick(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
ContContractCandlestickSubscription(Pair("BTC", "USD"), enums.Interval.I_1MIN, enums.ContractType.PERPETUAL,
callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_all_market_mini_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AllMarketMiniTickersSubscription(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(symbol = "BTCUSD_PERP", callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_all_market_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AllMarketTickersSubscription(callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
TickerSubscription(symbol = "BTCUSD_PERP", callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_best_orderbook_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
OrderBookTickerSubscription(callbacks = [message_counter.generate_callback(10)])
])
await self.assertWsMessageCount(message_counter)
async def test_best_orderbook_symbol_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
OrderBookSymbolTickerSubscription(symbol = "BTCUSD_PERP", callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
# fails since normally there are no liquidation orders
async def test_liquidation_orders(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
LiquidationOrdersSubscription(symbol = "BTCUSD_PERP", callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
# fails since normally there are no liquidation orders
async def test_all_liquidation_orders(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AllMarketLiquidationOrdersSubscription(callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_partial_detph(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = "BTCUSD_PERP", level = 5, frequency = 100, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_partial_detph2(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = "BTCUSD_PERP", level = 5, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_detph(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = "BTCUSD_PERP", level = 0, frequency = 100, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_detph2(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = "BTCUSD_PERP", level = 0, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/btse.py | tests/e2e/btse.py | import unittest
import os
import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.btse import enums
from cryptoxlib.clients.btse.exceptions import BtseRestException
from cryptoxlib.clients.btse.BtseWebsocket import OrderbookSubscription, OrderbookL2Subscription, TradeSubscription
from cryptoxlib.Pair import Pair
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['BTSEAPIKEY']
sec_key = os.environ['BTSESECKEY']
class BtseRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_btse_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def test_get_time(self):
response = await self.client.get_time()
self.assertTrue(self.check_positive_response(response))
async def test_get_exchange_info(self):
response = await self.client.get_exchange_info(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book(self):
response = await self.client.get_order_book(pair = Pair('BTC', 'USD'), depth = 3)
self.assertTrue(self.check_positive_response(response))
async def test_get_price(self):
response = await self.client.get_price(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_funds(self):
response = await self.client.get_funds()
self.assertTrue(self.check_positive_response(response))
async def test_get_open_orders(self):
response = await self.client.get_open_orders(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_get_fees(self):
response = await self.client.get_fees(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
async def test_create_order(self):
with self.assertRaises(BtseRestException) as cm:
await self.client.create_order(pair = Pair('BTC', 'USD'), type = enums.OrderType.LIMIT,
side = enums.OrderSide.BUY,
amount = "1000", price = "1")
e = cm.exception
self.assertEqual(e.status_code, 400)
self.assertTrue(str(e.body['errorCode']) == '51523')
async def test_cancel_order(self):
response = await self.client.cancel_order(pair = Pair('BTC', 'USD'))
self.assertTrue(self.check_positive_response(response))
class BtseWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_btse_client(api_key, sec_key)
async def test_order_book_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
OrderbookSubscription([Pair('BTSE', 'BTC')], callbacks = [message_counter.generate_callback(2)]),
])
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 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)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/binance_margin.py | tests/e2e/binance_margin.py | import unittest
import os
import logging
import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.exceptions import BinanceRestException
from cryptoxlib.clients.binance.BinanceWebsocket import CandlestickSubscription, DepthSubscription
from cryptoxlib.Pair import Pair
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['BINANCEAPIKEY']
sec_key = os.environ['BINANCESECKEY']
class BinanceMarginRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
def check_error_code(self, e: BinanceRestException, status: str, code: str):
return str(e.status_code) == status and str(e.body['code']) == code
async def test_create_order1(self):
with self.assertRaises(BinanceRestException) as cm:
response = await self.client.create_margin_order(pair = Pair('BTC', 'USDT'), side = enums.OrderSide.BUY,
order_type = enums.OrderType.MARKET, quantity = '100')
self.assertTrue(self.check_positive_response(response))
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2010')) # insufficient funds
async def test_create_order2(self):
with self.assertRaises(BinanceRestException) as cm:
response = await self.client.create_margin_order(pair = Pair('BTC', 'USDT'), side = enums.OrderSide.BUY,
order_type = enums.OrderType.LIMIT, quantity = '100', price = "10000")
self.assertTrue(self.check_positive_response(response))
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2010')) # insufficient funds
async def test_create_order3(self):
with self.assertRaises(BinanceRestException) as cm:
response = await self.client.create_margin_order(pair = Pair('BTC', 'USDT'), side = enums.OrderSide.BUY,
order_type = enums.OrderType.LIMIT, quantity = '100', price = "10000",
time_in_force = enums.TimeInForce.FILL_OR_KILL)
self.assertTrue(self.check_positive_response(response))
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2010')) # insufficient funds
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_cross_listen_key(self):
response = await self.client.get_cross_margin_listen_key()
self.assertTrue(self.check_positive_response(response))
response = await self.client.keep_alive_cross_margin_listen_key(response['response']['listenKey'])
self.assertTrue(self.check_positive_response(response))
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/binance.py | tests/e2e/binance.py | import unittest
import os
import logging
import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.BinanceWebsocket import CandlestickSubscription, DepthSubscription
from cryptoxlib.Pair import Pair
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['BINANCEAPIKEY']
sec_key = os.environ['BINANCESECKEY']
class BinanceRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def test_listen_key(self):
response = await self.client.get_spot_listen_key()
self.assertTrue(self.check_positive_response(response))
response = await self.client.keep_alive_spot_listen_key(response['response']['listenKey'])
self.assertTrue(self.check_positive_response(response))
async def test_get_exchange_info1(self):
response = await self.client.get_exchange_info()
self.assertTrue(self.check_positive_response(response))
async def test_get_exchange_info2(self):
response = await self.client.get_exchange_info(pairs = [Pair('BTC', 'USDT')])
self.assertTrue(self.check_positive_response(response))
async def test_get_exchange_info3(self):
response = await self.client.get_exchange_info(pairs = [Pair('BTC', 'USDT'), Pair('BNB', 'USDT')])
self.assertTrue(self.check_positive_response(response))
class BinanceWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_client(api_key, sec_key)
#@unittest.expectedFailure
async def test_candlesticks_subscription(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, 15.0)
async def test_partial_detph(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(Pair('BTC', 'USDT'), 5, 100, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_partial_detph2(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(Pair('BTC', 'USDT'), 5, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_detph(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(Pair('BTC', 'USDT'), 0, 1000, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
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)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/aax.py | tests/e2e/aax.py | import unittest
import os
import logging
import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.aax import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.aax.exceptions import AAXRestException
from CryptoXLibTest import CryptoXLibTest
api_key = os.environ['AAXAPIKEY']
sec_key = os.environ['AAXSECKEY']
class AAXRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_aax_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_response(self, response, code = 1):
return str(response['status_code'])[0] == '2' and response['response']['code'] == code
async def test_get_exchange_info(self):
response = await self.client.get_exchange_info()
self.assertTrue(self.check_response(response))
async def test_get_funds(self):
response = await self.client.get_funds()
self.assertTrue(self.check_response(response))
async def test_get_user_info(self):
response = await self.client.get_user_info()
self.assertTrue(self.check_response(response))
async def test_create_spot_order(self):
response = await self.client.create_spot_order(pair = Pair('BTC', 'USDT'), type = enums.OrderType.LIMIT,
side = enums.OrderSide.BUY, amount = "10000", price = "1")
self.assertTrue(self.check_response(response))
async def test_update_spot_order(self):
response = await self.client.update_spot_order(order_id = "abcd", amount = "20000")
self.assertTrue(self.check_response(response, 30000))
async def test_cancel_spot_order(self):
response = await self.client.cancel_spot_order(order_id = "abcd")
self.assertTrue(self.check_response(response, 30000))
async def test_cancel_batch_spot_order(self):
response = await self.client.cancel_batch_spot_order(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_response(response, 30000))
async def test_cancel_all_spot_order(self):
response = await self.client.cancel_all_spot_order(timeout_ms = 0)
self.assertTrue(self.check_response(response))
if __name__ == '__main__':
unittest.main()
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/binance_usds_m_futures.py | tests/e2e/binance_usds_m_futures.py | import unittest
import os
import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.BinanceFuturesWebsocket import AggregateTradeSubscription, MarkPriceSubscription, \
MarkPriceAllSubscription, AllMarketLiquidationOrdersSubscription, AllMarketMiniTickersSubscription, \
AllMarketTickersSubscription, MiniTickerSubscription, OrderBookTickerSubscription, \
OrderBookSymbolTickerSubscription, LiquidationOrdersSubscription, BlvtCandlestickSubscription, \
BlvtSubscription, CompositeIndexSubscription, DepthSubscription, CandlestickSubscription, \
ContContractCandlestickSubscription, TickerSubscription, AccountSubscription
from cryptoxlib.clients.binance.exceptions import BinanceRestException
from cryptoxlib.Pair import Pair
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['BINANCEAPIKEY']
sec_key = os.environ['BINANCESECKEY']
test_api_key = os.environ['BINANCEFUTURESTESTAPIKEY']
test_sec_key = os.environ['BINANCEFUTURESTESTSECKEY']
class BinanceUSDSMFuturesMarketRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_usds_m_futures_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def test_get_ping(self):
response = await self.client.ping()
self.assertTrue(self.check_positive_response(response))
async def test_get_time(self):
response = await self.client.get_time()
self.assertTrue(self.check_positive_response(response))
async def test_get_exchange_info(self):
response = await self.client.get_exchange_info()
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book(self):
response = await self.client.get_orderbook(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_trades(self):
response = await self.client.get_trades(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_historical_trades(self):
response = await self.client.get_historical_trades(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_aggregate_trades(self):
response = await self.client.get_aggregate_trades(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_candlesticks(self):
response = await self.client.get_candlesticks(symbol = Pair('BTC', 'USDT'), interval = enums.Interval.I_1MIN)
self.assertTrue(self.check_positive_response(response))
async def test_get_cont_contract_candlesticks(self):
response = await self.client.get_cont_contract_candlesticks(pair = Pair('BTC', 'USDT'),
interval = enums.Interval.I_1MIN,
contract_type = enums.ContractType.PERPETUAL)
self.assertTrue(self.check_positive_response(response))
async def test_get_index_price_candlesticks(self):
response = await self.client.get_index_price_candlesticks(pair = Pair('BTC', 'USDT'), interval = enums.Interval.I_1MIN)
self.assertTrue(self.check_positive_response(response))
async def test_get_mark_price_candlesticks(self):
response = await self.client.get_mark_price_candlesticks(symbol = Pair('BTC', 'USDT'), interval = enums.Interval.I_1MIN)
self.assertTrue(self.check_positive_response(response))
async def test_get_mark_price(self):
response = await self.client.get_mark_price(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_fund_rate_history(self):
response = await self.client.get_fund_rate_history(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_24h_price_ticker(self):
response = await self.client.get_24h_price_ticker(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_price_ticker(self):
response = await self.client.get_price_ticker(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_best_orderbook_ticker(self):
response = await self.client.get_orderbook_ticker(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_open_interest(self):
response = await self.client.get_open_interest(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_open_interest_hist(self):
response = await self.client.get_open_interest_hist(pair = Pair('BTC', 'USDT'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
async def test_get_top_long_short_account_ratio(self):
response = await self.client.get_top_long_short_account_ratio(pair = Pair('BTC', 'USDT'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
async def test_get_top_long_short_position_ratio(self):
response = await self.client.get_top_long_short_position_ratio(pair = Pair('BTC', 'UP'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
async def test_get_global_long_short_account_ratio(self):
response = await self.client.get_global_long_short_account_ratio(pair = Pair('BTC', 'USDT'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
async def test_get_taker_long_short_ratio(self):
response = await self.client.get_taker_long_short_ratio(pair = Pair('BTC', 'USDT'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
async def test_get_blvt_candlesticks(self):
response = await self.client.get_blvt_candlesticks(pair = Pair('BTC', 'UP'), interval = enums.Interval.I_1D)
self.assertTrue(self.check_positive_response(response))
async def test_get_index_info(self):
response = await self.client.get_index_info(pair = Pair('DEFI', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_listen_key(self):
response = await self.client.get_listen_key()
self.assertTrue(self.check_positive_response(response))
response = await self.client.keep_alive_listen_key(response['response']['listenKey'])
self.assertTrue(self.check_positive_response(response))
class BinanceUSDSMFuturesAccountRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_usds_m_futures_testnet_client(test_api_key, test_sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
def check_error_code(self, e: BinanceRestException, status: str, code: str):
return str(e.status_code) == status and str(e.body['code']) == code
async def test_get_ping(self):
response = await self.client.ping()
self.assertTrue(self.check_positive_response(response))
async def test_change_position_type(self):
# make sure some position exists in order for the change of position to fail
await self.client.create_order(symbol = Pair('XRP', 'USDT'), side = enums.OrderSide.BUY,
type = enums.OrderType.MARKET, quantity = '10')
with self.assertRaises(BinanceRestException) as cm:
current_type = await self.client.get_position_type()
response = await self.client.change_position_type(not current_type['response']['dualSidePosition'])
self.assertTrue(self.check_positive_response(response))
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-4068'))
async def test_get_position_type(self):
response = await self.client.get_position_type()
self.assertTrue(self.check_positive_response(response))
async def test_get_all_orders(self):
response = await self.client.get_all_orders(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
# market order
async def test_create_order1(self):
current_position_type = await self.client.get_position_type()
if current_position_type['response']['dualSidePosition']:
await self.client.change_position_type(False)
response = await self.client.create_order(symbol = Pair('BTC', 'USDT'), side = enums.OrderSide.BUY,
type = enums.OrderType.MARKET, quantity = '0.001')
self.assertTrue(self.check_positive_response(response))
# limit order
async def test_create_order2(self):
current_position_type = await self.client.get_position_type()
if current_position_type['response']['dualSidePosition']:
await self.client.change_position_type(False)
response = await self.client.create_order(symbol = Pair('BTC', 'USDT'), side = enums.OrderSide.BUY,
type = enums.OrderType.LIMIT, quantity = '0.1', price = '2000',
time_in_force = enums.TimeInForce.GOOD_TILL_CANCELLED)
self.assertTrue(self.check_positive_response(response))
async def test_get_order(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.get_order(symbol = Pair('BTC', 'USDT'), order_id = 1)
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2013'))
async def test_cancel_order(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.cancel_order(symbol = Pair('BTC', 'USDT'), order_id = 1)
e = cm.exception
self.assertTrue(self.check_error_code(e, '400', '-2011'))
async def test_cancel_all_orders(self):
response = await self.client.cancel_all_orders(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
@unittest.expectedFailure
# not supported for testnet
async def test_auto_cancel_orders(self):
response = await self.client.auto_cancel_orders(symbol = Pair('BTC', 'USDT'), countdown_time_ms = 0)
self.assertTrue(self.check_positive_response(response))
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_get_all_open_orders(self):
response = await self.client.get_all_open_orders(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_balance(self):
response = await self.client.get_balance()
self.assertTrue(self.check_positive_response(response))
async def test_get_account(self):
response = await self.client.get_account()
self.assertTrue(self.check_positive_response(response))
async def test_change_init_leverage(self):
response = await self.client.change_init_leverage(symbol = Pair('BTC', 'USDT'), leverage = 1)
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(symbol = Pair('ETH', 'USDT'), margin_type = new_margin_type)
self.assertTrue(self.check_positive_response(response))
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(symbol = Pair('BNB', 'USDT'), margin_type = enums.MarginType.ISOLATED)
await self.client.create_order(symbol = Pair('BNB', 'USDT'), side = enums.OrderSide.BUY,
type = enums.OrderType.MARKET, quantity = '0.1')
response = await self.client.update_isolated_position_margin(symbol = Pair('BNB', 'USDT'), quantity = '0.001',
type = 2)
self.assertTrue(self.check_positive_response(response))
async def test_get_position_margin_change_history(self):
response = await self.client.get_position_margin_change_history(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_position(self):
response = await self.client.get_position()
self.assertTrue(self.check_positive_response(response))
async def test_get_position2(self):
response = await self.client.get_position(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_account_trades(self):
response = await self.client.get_account_trades(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_income_history(self):
response = await self.client.get_income_history(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_notional_and_leverage_brackets(self):
response = await self.client.get_notional_and_leverage_brackets(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_adl_quantile(self):
response = await self.client.get_adl_quantile(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_force_orders(self):
response = await self.client.get_force_orders(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_api_trading_status(self):
response = await self.client.get_api_trading_status(pair = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
async def test_get_commission_rate(self):
response = await self.client.get_commission_rate(symbol = Pair('BTC', 'USDT'))
self.assertTrue(self.check_positive_response(response))
class BinanceUSDSMFuturesMarketWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_usds_m_futures_client(api_key, sec_key)
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_mark_price(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
MarkPriceSubscription(symbol = Pair("BTC", "USDT"), frequency1sec = True, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_mark_price_all(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
MarkPriceAllSubscription(True, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_candlestick(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
CandlestickSubscription(symbol = Pair("BTC", "USDT"), interval = enums.Interval.I_1MIN, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_cont_contract_candlestick(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
ContContractCandlestickSubscription(Pair("BTC", "USDT"), enums.Interval.I_1MIN, enums.ContractType.PERPETUAL,
callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_all_market_mini_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AllMarketMiniTickersSubscription(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_all_market_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AllMarketTickersSubscription(callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
TickerSubscription(Pair('BTC', 'USDT'), callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_best_orderbook_ticker(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
OrderBookTickerSubscription(callbacks = [message_counter.generate_callback(10)])
])
await self.assertWsMessageCount(message_counter)
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)
# fails since normally there are no liquidation orders
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_all_liquidation_orders(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AllMarketLiquidationOrdersSubscription(callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_partial_detph(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = Pair('BTC', 'USDT'), level = 5, frequency = 100, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_partial_detph2(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = Pair('BTC', 'USDT'), level = 5, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_detph(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = Pair('BTC', 'USDT'), level = 0, frequency = 100, callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
async def test_detph2(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
DepthSubscription(symbol = Pair('BTC', 'USDT'), level = 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)
# typically no data are received
async def blvt_candlesticks(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
BlvtCandlestickSubscription(Pair('BTC', 'UP'), enums.Interval.I_1MIN,
callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter, timeout = 60)
async def test_composite_index(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
CompositeIndexSubscription(Pair('DEFI', 'USDT'),
callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/hitbtc.py | tests/e2e/hitbtc.py | import unittest
import os
import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.hitbtc import enums
from cryptoxlib.clients.hitbtc.HitbtcWebsocket import OrderbookSubscription, TickerSubscription, TradesSubscription, \
AccountSubscription
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.hitbtc.exceptions import HitbtcRestException
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['HITBTCAPIKEY']
sec_key = os.environ['HITBTCSECKEY']
class HitbtcRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def init_test(self):
self.client = CryptoXLib.create_hitbtc_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
async def test_get_currencies(self):
response = await self.client.get_currencies()
#for x in sorted(response['response'], key = lambda x: x['id']):
# print(x)
self.assertTrue(self.check_positive_response(response))
async def test_get_currencies2(self):
response = await self.client.get_currencies(['BTC', 'ETH'])
self.assertTrue(self.check_positive_response(response))
async def test_get_currency(self):
response = await self.client.get_currency('BTC')
self.assertTrue(self.check_positive_response(response))
async def test_get_symbols(self):
response = await self.client.get_symbols()
self.assertTrue(self.check_positive_response(response))
async def test_get_symbols2(self):
response = await self.client.get_symbols([Pair('ETH', 'BTC'), Pair('XRP', 'BTC')])
self.assertTrue(self.check_positive_response(response))
async def test_get_symbol(self):
response = await self.client.get_symbol(Pair('ETH', 'BTC'))
self.assertTrue(self.check_positive_response(response))
async def test_get_tickers(self):
response = await self.client.get_tickers()
self.assertTrue(self.check_positive_response(response))
async def test_get_tickers2(self):
response = await self.client.get_tickers([Pair('ETH', 'BTC'), Pair('XRP', 'BTC')])
self.assertTrue(self.check_positive_response(response))
async def test_get_ticker(self):
response = await self.client.get_ticker(Pair('ETH', 'BTC'))
self.assertTrue(self.check_positive_response(response))
async def test_get_order_books(self):
response = await self.client.get_order_books(limit = 1, pairs = [Pair('ETH', 'BTC')])
self.assertTrue(self.check_positive_response(response))
async def test_get_order_books2(self):
response = await self.client.get_order_books(pairs = [Pair('ETH', 'BTC')])
self.assertTrue(self.check_positive_response(response))
async def test_get_order_books3(self):
response = await self.client.get_order_books()
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book(self):
response = await self.client.get_order_book(pair = Pair('ETH', 'BTC'), limit = 1)
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book2(self):
response = await self.client.get_order_book(pair = Pair('ETH', 'BTC'), limit = 1, volume = 100)
self.assertTrue(self.check_positive_response(response))
async def test_get_balance(self):
response = await self.client.get_balance()
self.assertTrue(self.check_positive_response(response))
async def test_create_order(self):
with self.assertRaises(HitbtcRestException) as cm:
await self.client.create_order(pair = Pair("BTC", "USD"), side = enums.OrderSide.BUY,
type = enums.OrderType.LIMIT, amount = "100000", price = "1",
time_in_force = enums.TimeInForce.GOOD_TILL_CANCELLED)
e = cm.exception
self.assertEqual(e.status_code, 400)
self.assertEqual(e.body['error']['code'], 20001)
async def test_cancel_orders(self):
response = await self.client.cancel_orders(pair = Pair("BTC", "USD"))
self.assertTrue(self.check_positive_response(response))
async def test_cancel_order(self):
with self.assertRaises(HitbtcRestException) as cm:
await self.client.cancel_order(client_id = "12345678")
e = cm.exception
self.assertEqual(e.status_code, 400)
self.assertEqual(e.body['error']['code'], 20002)
class HitbtcWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_hitbtc_client(api_key, sec_key)
#@unittest.skip
async def test_order_book_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
OrderbookSubscription(Pair('BTC', 'USD'), callbacks = [message_counter.generate_callback(2)]),
])
await self.assertWsMessageCount(message_counter)
#@unittest.skip
async def test_ticker_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
TickerSubscription(Pair('BTC', 'USD'), callbacks = [message_counter.generate_callback(2)]),
])
await self.assertWsMessageCount(message_counter)
#@unittest.skip
async def test_trades_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
TradesSubscription(Pair('ETH', 'BTC'), callbacks = [message_counter.generate_callback(1)]),
])
await self.assertWsMessageCount(message_counter)
async def test_account_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AccountSubscription(callbacks = [message_counter.generate_callback(1)]),
])
await self.assertWsMessageCount(message_counter)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/CryptoXLibTest.py | tests/e2e/CryptoXLibTest.py | import logging
import sys
import asyncio
from typing import Any, List
import aiounittest
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
class CryptoXLibWsSuccessException(Exception):
pass
class WsMessageCounterCallback(object):
message_counts = {}
def __init__(self, ws_message_counter: 'WsMessageCounter', target_count: int, name: str = None):
self.ws_message_counter = ws_message_counter
self.name = name
self.current_count = 0
self.target_count = target_count
async def process_message(self, message):
self.current_count += 1
if self.current_count == self.target_count:
LOG.info(f"Message count reached [counter = {self.name}].")
self.ws_message_counter.check_target_reached()
def __call__(self, *args, **kwargs) -> Any:
return self.process_message(args[0])
class WsMessageCounter(object):
def __init__(self):
self.callbacks: List[WsMessageCounterCallback] = []
def generate_callback(self, target_count: int, name: str = None) -> WsMessageCounterCallback:
callback = WsMessageCounterCallback(self, target_count, name)
self.callbacks.append(callback)
return callback
def check_target_reached(self):
target_reached = True
for callback in self.callbacks:
if callback.current_count < callback.target_count:
target_reached = False
break
if target_reached:
raise CryptoXLibWsSuccessException("Websocket message count reached successfully.")
class CryptoXLibTest(aiounittest.AsyncTestCase):
print_logs: bool = True
log_level: int = logging.DEBUG
def __init__(self, methodName = None):
super().__init__(methodName)
@classmethod
def initialize(cls) -> None:
pass
@classmethod
def setUpClass(cls) -> None:
cls.initialize()
LOG.setLevel(cls.log_level)
if cls.print_logs:
LOG.addHandler(logging.StreamHandler())
@classmethod
def tearDownClass(cls) -> None:
pass
async def init_test(self):
pass
async def clean_test(self):
pass
def setUp(self) -> None:
return async_run(self.init_test())
def tearDown(self) -> None:
return async_run(self.clean_test())
def get_event_loop(self):
if not hasattr(self, 'loop'):
self.loop = asyncio.new_event_loop()
return self.loop
else:
return self.loop
async def assertWsMessageCount(self, ws_message_counter: WsMessageCounter, timeout: float = 25.0):
try:
await asyncio.wait_for(self.client.start_websockets(), timeout = timeout)
except CryptoXLibWsSuccessException as e:
LOG.info(f"SUCCESS exception: {e}")
return True
except asyncio.TimeoutError:
msg_string = ''
for counter in ws_message_counter.callbacks:
name = counter.name if counter.name is not None else 'counter'
current_count = counter.current_count
target_count = counter.target_count
msg_string += f"{name} {current_count}/{target_count}, "
self.fail(f"Websocket message count timeout ({timeout} secs). Processed messages: {msg_string[:-2]}.") | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/bitforex.py | tests/e2e/bitforex.py | import unittest
import os
import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.bitforex import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitforex.exceptions import BitforexRestException
from CryptoXLibTest import CryptoXLibTest
api_key = os.environ['BITFOREXAPIKEY']
sec_key = os.environ['BITFOREXSECKEY']
class BitforexRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_bitforex_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return response['response']['success'] is True
async def test_get_exchange_info(self):
response = await self.client.get_exchange_info()
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book(self):
response = await self.client.get_order_book(pair = Pair('ETH', 'BTC'), depth = "1")
self.assertTrue(self.check_positive_response(response))
async def test_get_ticker(self):
response = await self.client.get_ticker(pair = Pair('ETH', 'BTC'))
self.assertTrue(self.check_positive_response(response))
async def test_get_single_fund(self):
response = await self.client.get_single_fund(currency = "NOBS")
self.assertTrue(self.check_positive_response(response))
async def test_get_funds(self):
response = await self.client.get_funds()
self.assertTrue(self.check_positive_response(response))
async def test_get_trades(self):
response = await self.client.get_trades(pair = Pair('ETH', 'BTC'), size = "1")
self.assertTrue(self.check_positive_response(response))
async def test_get_candlesticks(self):
response = await self.client.get_candlesticks(pair = Pair('ETH', 'BTC'), interval = enums.CandlestickInterval.I_1W, size = "5")
self.assertTrue(self.check_positive_response(response))
async def test_create_order(self):
with self.assertRaises(BitforexRestException) as cm:
await self.client.create_order(Pair("ETH", "BTC"), side = enums.OrderSide.SELL, quantity = "1", price = "1")
e = cm.exception
self.assertEqual(e.body['code'], '3002')
async def test_create_multi_order(self):
response = await self.client.create_multi_order(Pair("ETH", "BTC"),
orders = [("1", "1", enums.OrderSide.SELL), ("2", "1", enums.OrderSide.SELL)])
self.assertTrue(self.check_positive_response(response))
async def test_cancel_order(self):
response = await self.client.cancel_order(pair = Pair('ETH', 'BTC'), order_id = "10")
self.assertTrue(self.check_positive_response(response))
async def test_cancel_multi_order(self):
response = await self.client.cancel_multi_order(pair = Pair('ETH', 'BTC'), order_ids = ["10", "20"])
self.assertTrue(self.check_positive_response(response))
async def test_cancel_all_orders(self):
response = await self.client.cancel_all_orders(pair = Pair('ETH', 'BTC'))
self.assertTrue(self.check_positive_response(response))
async def test_get_order(self):
with self.assertRaises(BitforexRestException) as cm:
await self.client.get_order(pair = Pair('ETH', 'BTC'), order_id = "1")
e = cm.exception
self.assertEqual(e.body['code'], '4004')
async def test_get_orders(self):
response = await self.client.get_orders(pair = Pair('ETH', 'BTC'), order_ids = ["1", "2"])
self.assertTrue(self.check_positive_response(response))
async def test_find_order(self):
response = await self.client.find_order(pair = Pair('ETH', 'BTC'), state = enums.OrderState.PENDING)
self.assertTrue(self.check_positive_response(response))
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/binance_bswap.py | tests/e2e/binance_bswap.py | import unittest
import os
import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.exceptions import BinanceRestException
from cryptoxlib.Pair import Pair
from CryptoXLibTest import CryptoXLibTest
api_key = os.environ['BINANCEAPIKEY']
sec_key = os.environ['BINANCESECKEY']
class BinanceBSwapRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def test_get_bswap_pools(self):
response = await self.client.get_bswap_pools()
self.assertTrue(self.check_positive_response(response))
async def test_get_bswap_liquidity(self):
response = await self.client.get_bswap_liquidity()
self.assertTrue(self.check_positive_response(response))
async def test_get_bswap_liquidity_operations(self):
response = await self.client.get_bswap_liquidity_operations()
self.assertTrue(self.check_positive_response(response))
async def test_get_bswap_quote(self):
response = await self.client.get_bswap_quote(Pair('BTC', 'USDT'), '1000')
self.assertTrue(self.check_positive_response(response))
async def test_get_bswap_swap_history(self):
response = await self.client.get_bswap_swap_history()
self.assertTrue(self.check_positive_response(response))
async def test_bswap_add_liquidity(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.bswap_add_liquidity(0, 'BTC', '10000000')
e = cm.exception
self.assertEqual(e.status_code, 400)
self.assertEqual(e.body['code'], -12017)
async def test_bswap_remove_liquidity(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.bswap_remove_liquidity(0, 'BTC', '10000000', type = enums.LiquidityRemovalType.COMBINATION)
e = cm.exception
self.assertEqual(e.status_code, 400)
self.assertEqual(e.body['code'], -9000)
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)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/onetrading.py | tests/e2e/onetrading.py | import datetime
import logging
import os
import unittest
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.onetrading import enums
from cryptoxlib.clients.onetrading.OneTradingWebsocket import PricesSubscription, AccountSubscription, \
OrderbookSubscription, \
CandlesticksSubscription, CandlesticksSubscriptionParams, MarketTickerSubscription
from cryptoxlib.clients.onetrading.exceptions import OneTradingRestException
api_key = os.environ['BITPANDAAPIKEY']
class OneTradingRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def init_test(self):
self.client = CryptoXLib.create_onetrading_client(api_key)
async def clean_test(self):
await self.client.close()
async def test_get_time(self):
response = await self.client.get_time()
self.assertTrue(self.check_positive_response(response))
async def test_get_account_balances(self):
response = await self.client.get_account_balances()
self.assertTrue(self.check_positive_response(response))
async def test_get_account_orders(self):
response = await self.client.get_account_orders()
self.assertTrue(self.check_positive_response(response))
async def test_get_account_order(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.get_account_order("1")
e = cm.exception
self.assertEqual(e.status_code, 400)
async def test_create_market_order(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.create_market_order(Pair("BTC", "EUR"), enums.OrderSide.BUY, "100000")
e = cm.exception
self.assertEqual(e.status_code, 422)
async def test_create_limit_order(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.create_limit_order(Pair("BTC", "EUR"), enums.OrderSide.BUY, "10000", "1")
e = cm.exception
self.assertEqual(e.status_code, 422)
async def test_create_stop_limit_order(self):
with self.assertRaises(OneTradingRestException) 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)
async def test_get_account_order_trades(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.get_account_order_trades("1")
e = cm.exception
self.assertEqual(e.status_code, 400)
async def test_get_account_trades(self):
response = await self.client.get_account_trades()
self.assertTrue(self.check_positive_response(response))
async def test_get_account_trade(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.get_account_trade("1")
e = cm.exception
self.assertEqual(e.status_code, 400)
async def test_get_account_trading_volume(self):
response = await self.client.get_account_trading_volume()
self.assertTrue(self.check_positive_response(response))
async def test_get_currencies(self):
response = await self.client.get_currencies()
self.assertTrue(self.check_positive_response(response))
async def test_find_order(self):
response = await self.client.get_candlesticks(Pair("BTC", "EUR"), enums.TimeUnit.DAYS, "1",
datetime.datetime.now() - datetime.timedelta(days = 7),
datetime.datetime.now())
self.assertTrue(self.check_positive_response(response))
async def test_get_account_fees(self):
response = await self.client.get_account_fees()
self.assertTrue(self.check_positive_response(response))
async def test_get_instruments(self):
response = await self.client.get_instruments()
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book(self):
response = await self.client.get_order_book(Pair("BTC", "EUR"))
self.assertTrue(self.check_positive_response(response))
async def test_get_fee_groups(self):
response = await self.client.get_fee_groups()
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book2(self):
response = await self.client.get_order_book(Pair("BTC", "EUR"), level = "3", depth = "1")
self.assertTrue(self.check_positive_response(response))
async def test_get_market_tickers(self):
response = await self.client.get_market_tickers()
self.assertTrue(self.check_positive_response(response))
async def test_get_market_ticker(self):
response = await self.client.get_market_ticker(Pair('ETH', 'EUR'))
self.assertTrue(self.check_positive_response(response))
async def test_get_price_ticks(self):
response = await self.client.get_price_tick(Pair('ETH', 'EUR'))
self.assertTrue(self.check_positive_response(response))
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 test_create_deposit_crypto_address(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.create_deposit_crypto_address("ABC")
e = cm.exception
self.assertEqual(e.status_code, 404)
self.assertTrue(e.body['error'] == 'CURRENCY_NOT_FOUND')
async def test_get_deposit_crypto_address(self):
response = await self.client.get_deposit_crypto_address("BTC")
self.assertTrue(self.check_positive_response(response))
async def test_get_fiat_deposit_info(self):
response = await self.client.get_fiat_deposit_info()
self.assertTrue(self.check_positive_response(response))
async def test_withdraw_crypto(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.withdraw_crypto('ABC', '1.0', 'ABC')
e = cm.exception
self.assertEqual(e.status_code, 404)
self.assertTrue(e.body['error'] == 'CURRENCY_NOT_FOUND')
async def test_delete_auto_cancel_all_orders(self):
response = await self.client.delete_auto_cancel_all_orders()
self.assertTrue(self.check_positive_response(response))
@unittest.skip
# SERVICE_UNAVAILABLE
async def test_withdraw_fiat(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.withdraw_fiat('ABC', '1.0', 'ABC')
e = cm.exception
self.assertEqual(e.status_code, 404)
async def test_get_deposits(self):
response = await self.client.get_deposits()
self.assertTrue(self.check_positive_response(response))
async def test_get_deposits2(self):
response = await self.client.get_deposits(currency = 'CHF')
self.assertTrue(self.check_positive_response(response))
async def test_get_onetrading_deposits(self):
response = await self.client.get_onetrading_deposits()
self.assertTrue(self.check_positive_response(response))
async def test_get_onetrading_deposits2(self):
response = await self.client.get_onetrading_deposits(currency ='CHF')
self.assertTrue(self.check_positive_response(response))
async def test_get_withdrawals(self):
response = await self.client.get_withdrawals()
self.assertTrue(self.check_positive_response(response))
async def test_get_withdrawals2(self):
response = await self.client.get_withdrawals(currency = 'CHF')
self.assertTrue(self.check_positive_response(response))
async def test_get_onetrading_withdrawals(self):
response = await self.client.get_onetrading_withdrawals()
self.assertTrue(self.check_positive_response(response))
async def test_get_onetrading_withdrawals2(self):
response = await self.client.get_onetrading_withdrawals(currency ='CHF')
self.assertTrue(self.check_positive_response(response))
@unittest.skip
# updates account settings
async def test_toggle_best_fee_collection(self):
response = await self.client.toggle_best_fee_collection(True)
self.assertTrue(self.check_positive_response(response))
async def test_delete_account_order(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.delete_account_order(order_id = "1")
e = cm.exception
self.assertEqual(e.status_code, 404)
async def test_delete_account_order2(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.delete_account_order(client_id = "1")
e = cm.exception
self.assertEqual(e.status_code, 404)
async def test_order_update_order_id(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.update_order(amount = "10", order_id = "1")
e = cm.exception
self.assertEqual(e.status_code, 404)
async def test_order_update_client_id(self):
with self.assertRaises(OneTradingRestException) as cm:
await self.client.update_order(amount = "10", client_id = "1")
e = cm.exception
self.assertEqual(e.status_code, 404)
class OneTradingWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_onetrading_client(api_key)
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_account_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
AccountSubscription(callbacks = [message_counter.generate_callback(3)])
])
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)
@unittest.skip
async def test_candlesticks_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
CandlesticksSubscription([CandlesticksSubscriptionParams(Pair("BTC", "EUR"), enums.TimeUnit.MINUTES, 1)],
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_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)
if __name__ == '__main__':
unittest.main()
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/eterbase.py | tests/e2e/eterbase.py | import unittest
import os
import logging
import uuid
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.eterbase import enums
from cryptoxlib.clients.eterbase.exceptions import EterbaseRestException
from cryptoxlib.clients.eterbase.EterbaseWebsocket import OrderbookSubscription
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['ETERBASEAPIKEY']
sec_key = os.environ['ETERBASESECKEY']
acct_key = os.environ['ETERBASEACCTKEY']
class EterbaseRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def get_market_id(self, symbol: str) -> str:
markets = await self.client.get_markets()
return next(filter(lambda x: x['symbol'] == symbol, markets['response']))['id']
async def init_test(self):
self.client = CryptoXLib.create_eterbase_client(acct_key, api_key, sec_key)
async def clean_test(self):
await self.client.close()
async def test_get_ping(self):
response = await self.client.get_ping()
self.assertTrue(self.check_positive_response(response))
async def test_get_currencies(self):
response = await self.client.get_currencies()
self.assertTrue(self.check_positive_response(response))
async def test_get_markets(self):
response = await self.client.get_markets()
self.assertTrue(self.check_positive_response(response))
async def test_get_balances(self):
response = await self.client.get_balances()
self.assertTrue(self.check_positive_response(response))
async def test_get_token(self):
response = await self.client.get_token()
self.assertTrue(self.check_positive_response(response))
async def test_create_order(self):
ethusdt_id = await self.get_market_id('ETHUSDT')
print(f'ETHUSDT: {ethusdt_id}')
with self.assertRaises(EterbaseRestException) as cm:
await self.client.create_order(pair_id = ethusdt_id, side = enums.OrderSide.BUY,
type = enums.OrderType.LIMIT, amount = "100000", price = "1",
time_in_force = enums.TimeInForce.GOOD_TILL_CANCELLED)
e = cm.exception
self.assertEqual(e.status_code, 400)
async def test_cancel_order(self):
with self.assertRaises(EterbaseRestException) as cm:
await self.client.cancel_order(order_id = str(uuid.uuid4()))
e = cm.exception
self.assertEqual(e.status_code, 400)
class EterbaseWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_eterbase_client(acct_key, api_key, sec_key)
async def clean_test(self):
await self.client.close()
async def get_market_id(self, symbol: str) -> str:
markets = await self.client.get_markets()
return next(filter(lambda x: x['symbol'] == symbol, markets['response']))['id']
async def test_order_book_subscription(self):
ethusdt_id = await self.get_market_id('ETHUSDT')
print(f'ETHUSDT: {ethusdt_id}')
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
OrderbookSubscription(market_ids = [ethusdt_id], callbacks = [message_counter.generate_callback(1)]),
])
await self.assertWsMessageCount(message_counter)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/binance_blvt.py | tests/e2e/binance_blvt.py | import unittest
import os
import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance.exceptions import BinanceRestException
from CryptoXLibTest import CryptoXLibTest
api_key = os.environ['BINANCEAPIKEY']
sec_key = os.environ['BINANCESECKEY']
class BinanceBLVTRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_binance_client(api_key, sec_key)
async def clean_test(self):
await self.client.close()
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def test_get_blvt_info(self):
response = await self.client.get_blvt_info()
self.assertTrue(self.check_positive_response(response))
async def test_get_blvt_subscribtion_record(self):
response = await self.client.get_blvt_subscribtion_record()
self.assertTrue(self.check_positive_response(response))
async def test_get_blvt_redemption_record(self):
response = await self.client.get_blvt_redemption_record()
self.assertTrue(self.check_positive_response(response))
async def test_get_blvt_user_info(self):
response = await self.client.get_blvt_user_info()
self.assertTrue(self.check_positive_response(response))
async def test_blvt_subscribe(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.blvt_subscribe("BTCUP", "50000000000")
e = cm.exception
self.assertEqual(e.status_code, 400)
self.assertEqual(e.body['code'], -5002)
async def test_blvt_redeem(self):
with self.assertRaises(BinanceRestException) as cm:
await self.client.blvt_redeem("BTCUP", "50000000000")
e = cm.exception
self.assertEqual(e.status_code, 400)
self.assertEqual(e.body['code'], -5002)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/tests/e2e/coinmate.py | tests/e2e/coinmate.py | import unittest
import os
import logging
import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.coinmate.exceptions import CoinmateRestException
from cryptoxlib.clients.coinmate.CoinmateWebsocket import OrderbookSubscription
from cryptoxlib.clients.coinmate import enums
from CryptoXLibTest import CryptoXLibTest, WsMessageCounter
api_key = os.environ['COINMATEAPIKEY']
sec_key = os.environ['COINMATESECKEY']
user_id = os.environ['COINMATEUSERID']
class CoinmateRestApi(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
def check_positive_response(self, response):
return str(response['status_code'])[0] == '2'
async def init_test(self):
self.client = CryptoXLib.create_coinmate_client(user_id, api_key, sec_key)
async def clean_test(self):
await self.client.close()
async def test_get_pairs(self):
response = await self.client.get_exchange_info()
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book(self):
response = await self.client.get_order_book(pair = Pair("BTC", "EUR"))
self.assertTrue(self.check_positive_response(response))
async def test_get_order_book2(self):
response = await self.client.get_order_book(pair = Pair("BTC", "EUR"), group = True)
self.assertTrue(self.check_positive_response(response))
async def test_get_ticker(self):
response = await self.client.get_ticker(pair = Pair("BTC", "EUR"))
self.assertTrue(self.check_positive_response(response))
async def test_get_currency_pairs(self):
response = await self.client.get_currency_pairs()
self.assertTrue(self.check_positive_response(response))
async def test_get_transactions(self):
response = await self.client.get_transactions(minutes_history = 10)
self.assertTrue(self.check_positive_response(response))
async def test_get_transactions2(self):
response = await self.client.get_transactions(minutes_history = 10, currency_pair = Pair("BTC", "EUR"))
self.assertTrue(self.check_positive_response(response))
async def test_get_balances(self):
response = await self.client.get_balances()
self.assertTrue(self.check_positive_response(response))
async def test_get_fees(self):
response = await self.client.get_fees()
self.assertTrue(self.check_positive_response(response))
async def test_get_fees2(self):
response = await self.client.get_fees(pair = Pair('BTC', 'EUR'))
self.assertTrue(self.check_positive_response(response))
async def test_get_transaction_history(self):
response = await self.client.get_transaction_history()
self.assertTrue(self.check_positive_response(response))
async def test_get_trade_history(self):
response = await self.client.get_trade_history()
self.assertTrue(self.check_positive_response(response))
async def test_get_trade_history2(self):
response = await self.client.get_trade_history(pair = Pair('BTC', 'EUR'))
self.assertTrue(self.check_positive_response(response))
async def test_get_transfer(self):
with self.assertRaises(CoinmateRestException) as cm:
await self.client.get_transfer(transaction_id = "0")
e = cm.exception
self.assertEqual(e.status_code, 200)
self.assertTrue(e.body['errorMessage'] == 'No transfer with given ID')
async def test_get_transfer_history(self):
response = await self.client.get_transfer_history()
self.assertTrue(self.check_positive_response(response))
async def test_get_transfer_history2(self):
response = await self.client.get_transfer_history(currency = 'EUR')
self.assertTrue(self.check_positive_response(response))
async def test_get_order_history(self):
response = await self.client.get_order_history(pair = Pair('BTC', 'EUR'))
self.assertTrue(self.check_positive_response(response))
async def test_get_open_orders(self):
response = await self.client.get_open_orders()
self.assertTrue(self.check_positive_response(response))
async def test_get_open_orders2(self):
response = await self.client.get_open_orders(pair = Pair('BTC', 'EUR'))
self.assertTrue(self.check_positive_response(response))
async def test_get_order(self):
with self.assertRaises(CoinmateRestException) as cm:
await self.client.get_order(order_id = "0")
e = cm.exception
self.assertEqual(e.status_code, 200)
self.assertTrue(e.body['errorMessage'] == 'No order with given ID')
async def test_get_order2(self):
response = await self.client.get_order(client_id = "0")
self.assertTrue(self.check_positive_response(response))
async def test_cancel_order(self):
response = await self.client.cancel_order(order_id = "0")
self.assertTrue(self.check_positive_response(response))
async def test_cancel_all_orders(self):
response = await self.client.cancel_all_orders()
self.assertTrue(self.check_positive_response(response))
async def test_cancel_all_orders2(self):
response = await self.client.cancel_all_orders(pair = Pair('BTC', 'EUR'))
self.assertTrue(self.check_positive_response(response))
async def test_create_order(self):
with self.assertRaises(CoinmateRestException) as cm:
await self.client.create_order(type = enums.OrderType.MARKET, side = enums.OrderSide.BUY, amount = "100",
pair = Pair('BTC', 'EUR'))
e = cm.exception
self.assertEqual(e.status_code, 200)
async def test_create_order2(self):
with self.assertRaises(CoinmateRestException) as cm:
await self.client.create_order(type = enums.OrderType.MARKET, side = enums.OrderSide.SELL, amount = "100",
pair = Pair('BTC', 'EUR'))
e = cm.exception
self.assertEqual(e.status_code, 200)
async def test_create_order3(self):
with self.assertRaises(CoinmateRestException) as cm:
await self.client.create_order(type = enums.OrderType.LIMIT, side = enums.OrderSide.BUY, price = "1",
amount = "100",
pair = Pair('BTC', 'EUR'))
e = cm.exception
self.assertEqual(e.status_code, 200)
async def test_create_order4(self):
with self.assertRaises(CoinmateRestException) as cm:
await self.client.create_order(type = enums.OrderType.LIMIT, side = enums.OrderSide.SELL, price = "1000000",
amount = "0.001",
pair = Pair('BTC', 'EUR'))
e = cm.exception
self.assertEqual(e.status_code, 200)
class CoinmateWs(CryptoXLibTest):
@classmethod
def initialize(cls) -> None:
cls.print_logs = True
cls.log_level = logging.DEBUG
async def init_test(self):
self.client = CryptoXLib.create_coinmate_client(user_id, api_key, sec_key)
async def test_order_book_subscription(self):
message_counter = WsMessageCounter()
self.client.compose_subscriptions([
OrderbookSubscription(Pair("BTC", "EUR"), callbacks = [message_counter.generate_callback(1)])
])
await self.assertWsMessageCount(message_counter)
if __name__ == '__main__':
unittest.main() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bitvavo_ws.py | examples/bitvavo_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitvavo import enums
from cryptoxlib.clients.bitvavo.BitvavoWebsocket import AccountSubscription, \
OrderbookSubscription, CandlesticksSubscription, TickerSubscription, Ticker24Subscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
LOG = logging.getLogger("websockets")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def ticker_update(response: dict) -> None:
print(f"Callback ticker_update: [{response}]")
async def ticker24_update(response: dict) -> None:
print(f"Callback ticker24_update: [{response}]")
async def run():
api_key = os.environ['BITVAVOAPIKEY']
sec_key = os.environ['BITVAVOSECKEY']
client = CryptoXLib.create_bitvavo_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
AccountSubscription(pairs = [Pair("BTC", "EUR")]),
TickerSubscription([Pair("BTC", "EUR")], callbacks = [ticker_update]),
Ticker24Subscription([Pair("BTC", "EUR")], callbacks = [ticker24_update]),
OrderbookSubscription([Pair("BTC", "EUR")], callbacks = [order_book_update]),
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
CandlesticksSubscription(pairs = [Pair("BTC", "EUR")], intervals = [enums.CandlestickInterval.I_1MIN])
])
# Execute all websockets asynchronously
await client.start_websockets()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/hitbtc_rest_apy.py | examples/hitbtc_rest_apy.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def run():
api_key = os.environ['HITBTCAPIKEY']
sec_key = os.environ['HITBTCSECKEY']
client = CryptoXLib.create_hitbtc_client(api_key, sec_key)
print("Account balance:")
await client.get_balance()
print("Symbols:")
await client.get_symbols()
print("Orderbook:")
await client.get_order_book(pair = Pair("ETH", "BTC"), limit = 2)
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bitvavo_rest_api.py | examples/bitvavo_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitvavo import enums
from cryptoxlib.clients.bitvavo.exceptions import BitvavoException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
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()
print("Ticker 24h:")
await client.get_24h_price_ticker()
print("Ticker 24h BTC-EUR:")
await client.get_24h_price_ticker(Pair("BTC", "EUR"))
print("Ticker price")
await client.get_price_ticker()
print("Ticker price BTC-EUR:")
await client.get_price_ticker(Pair("BTC", "EUR"))
print("Ticker book")
await client.get_best_orderbook_ticker()
print("Ticker book BTC-EUR:")
await client.get_best_orderbook_ticker(Pair("BTC", "EUR"))
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/ws_subscriptions.py | examples/ws_subscriptions.py | import logging
import os
import asyncio
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.PeriodicChecker import PeriodicChecker
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.BinanceClient import BinanceClient
from cryptoxlib.clients.binance.BinanceWebsocket import OrderBookSymbolTickerSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.INFO)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def order_book_update(response: dict) -> None:
pass
class Subscriptions:
def __init__(self):
self.subscriptions = [
[
OrderBookSymbolTickerSubscription(Pair("BTC", "USDT"), callbacks = [self.call1]),
OrderBookSymbolTickerSubscription(Pair("ETH", "USDT"), callbacks = [self.call1])
],
[
OrderBookSymbolTickerSubscription(Pair("BNB", "USDT"), callbacks = [self.call2]),
OrderBookSymbolTickerSubscription(Pair("XRP", "USDT"), callbacks = [self.call2])
],
[
OrderBookSymbolTickerSubscription(Pair("ADA", "USDT"), callbacks = [self.call3]),
OrderBookSymbolTickerSubscription(Pair("DOT", "USDT"), callbacks = [self.call3])
]
]
self.subscription_set_ids = []
self.timers = [
PeriodicChecker(100),
PeriodicChecker(100),
PeriodicChecker(100)
]
async def call1(self, response : dict):
if self.timers[0].check():
print(response)
async def call2(self, response : dict):
if self.timers[1].check():
print(response)
async def call3(self, response : dict):
if self.timers[2].check():
print(response)
# global container for various subscription compositions
sub = Subscriptions()
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 run():
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = CryptoXLib.create_binance_client(api_key, sec_key)
# initialize three independent websockets
sub.subscription_set_ids.append(client.compose_subscriptions(sub.subscriptions[0]))
sub.subscription_set_ids.append(client.compose_subscriptions(sub.subscriptions[1]))
sub.subscription_set_ids.append(client.compose_subscriptions(sub.subscriptions[2]))
try:
await asyncio.gather(*[
client.start_websockets(),
main_loop(client)
])
except Exception as e:
print(f"Out: {e}")
await client.close()
print("Exiting.")
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_usds_m_futures_rest_api.py | examples/binance_usds_m_futures_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
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)
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 = Pair('BTC', 'USDT'), limit = enums.DepthLimit.L_5)
print("Trades:")
await client.get_trades(symbol=Pair('BTC', 'USDT'), limit = 5)
print("Historical trades:")
await client.get_historical_trades(symbol=Pair('BTC', 'USDT'), limit = 5)
print("Aggregate trades:")
await client.get_aggregate_trades(symbol=Pair('BTC', 'USDT'), limit = 5)
print("Index price candlesticks:")
await client.get_index_price_candlesticks(pair = Pair('BTC', 'USDT'), interval = enums.Interval.I_1MIN)
print("Index info:")
await client.get_index_info(pair = Pair('DEFI', 'USDT'))
print("24hour price ticker:")
await client.get_24h_price_ticker(pair = Pair('BTC', 'USDT'))
print("Price ticker:")
await client.get_price_ticker(pair = Pair('BTC', 'USDT'))
print("Best order book ticker:")
await client.get_orderbook_ticker(pair = Pair('BTC', 'USDT'))
print("Create limit order:")
try:
await client.create_order(Pair("BTC", "USDT"), 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)
print("Account:")
await client.get_account(recv_window_ms = 5000)
print("Account trades:")
await client.get_account_trades(pair = Pair('BTC', 'USDT'))
print("All Open Orders:")
await client.get_all_open_orders()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/coinmate_rest_api.py | examples/coinmate_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def run():
api_key = os.environ['COINMATEAPIKEY']
client = CryptoXLib.create_coinmate_client(api_key, "", "")
print("Trading pairs:")
await client.get_exchange_info()
print("Currency pairs:")
await client.get_currency_pairs()
print("Ticker:")
await client.get_ticker(pair = Pair('BTC', 'EUR'))
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bibox_rest_api.py | examples/bibox_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bibox import enums
from cryptoxlib.clients.bibox.exceptions import BiboxException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
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()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_ws.py | examples/binance_ws.py | import logging
import os
from datetime import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance.BinanceWebsocket import AccountSubscription, OrderBookTickerSubscription, \
TradeSubscription, OrderBookSymbolTickerSubscription, CandlestickSubscription
from cryptoxlib.clients.binance.enums import Interval
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def account_update(response : dict) -> None:
print(f"Callback account_update: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def candlestick_update(response : dict) -> None:
print(f"Callback candlestick_update: [{response}]")
async def trade_update(response : dict) -> None:
local_timestamp_ms = int(datetime.now().timestamp() * 1000)
server_timestamp_ms = response['data']['E']
print(f"Callback trade_update: trade update timestamp diff [ms]:"
f" {local_timestamp_ms - server_timestamp_ms}")
async def orderbook_ticker_update(response : dict) -> None:
print(f"Callback orderbook_ticker_update: [{response}]")
async def run():
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = CryptoXLib.create_binance_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
OrderBookTickerSubscription(callbacks = [orderbook_ticker_update]),
OrderBookSymbolTickerSubscription(pair = Pair("BTC", "USDT"), callbacks = [orderbook_ticker_update]),
TradeSubscription(pair = Pair('ETH', 'BTC'), callbacks = [trade_update]),
CandlestickSubscription(Pair('BTC', 'USDT'), Interval.I_1MIN, callbacks = [candlestick_update])
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
AccountSubscription(callbacks = [account_update])
])
# Execute all websockets asynchronously
await client.start_websockets()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/aax_rest_api.py | examples/aax_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['AAXAPIKEY']
sec_key = os.environ['AAXSECKEY']
aax = CryptoXLib.create_bitforex_client(api_key, sec_key)
print("Exchange info:")
await aax.get_exchange_info()
await aax.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_coin_m_futures_ws.py | examples/binance_coin_m_futures_ws.py | import logging
import os
from datetime import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance.BinanceFuturesWebsocket import AccountSubscription, OrderBookTickerSubscription, \
OrderBookSymbolTickerSubscription, CandlestickSubscription, CompositeIndexSubscription
from cryptoxlib.clients.binance.enums import Interval
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def account_update(response : dict) -> None:
print(f"Callback account_update: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def candlestick_update(response : dict) -> None:
print(f"Callback candlestick_update: [{response}]")
async def trade_update(response : dict) -> None:
local_timestamp_ms = int(datetime.now().timestamp() * 1000)
server_timestamp_ms = response['data']['E']
print(f"Callback trade_update: trade update timestamp diff [ms]:"
f" {local_timestamp_ms - server_timestamp_ms}")
async def orderbook_ticker_update(response : dict) -> None:
print(f"Callback orderbook_ticker_update: [{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)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
OrderBookTickerSubscription(callbacks = [orderbook_ticker_update]),
OrderBookSymbolTickerSubscription(symbol = "BTCUSD_PERP", callbacks = [orderbook_ticker_update]),
CandlestickSubscription(interval = Interval.I_1MIN, symbol = "BTCUSD_PERP", callbacks = [candlestick_update])
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
AccountSubscription(callbacks = [account_update]),
])
# Execute all websockets asynchronously
await client.start_websockets()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_rest_api.py | examples/binance_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = CryptoXLib.create_binance_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(pair = Pair('ETH', 'BTC'), limit = enums.DepthLimit.L_5)
print("Trades:")
await client.get_trades(pair=Pair('ETH', 'BTC'), limit = 5)
print("Historical trades:")
await client.get_historical_trades(pair=Pair('ETH', 'BTC'), limit = 5)
print("Aggregate trades:")
await client.get_aggregate_trades(pair=Pair('ETH', 'BTC'), limit = 5)
print("Candlesticks:")
await client.get_candlesticks(pair=Pair('ETH', 'BTC'), interval = enums.Interval.I_1D, limit=5)
print("Average price:")
await client.get_average_price(pair = Pair('ETH', 'BTC'))
print("24hour price ticker:")
await client.get_24h_price_ticker(pair = Pair('ETH', 'BTC'))
print("Price ticker:")
await client.get_price_ticker(pair = Pair('ETH', 'BTC'))
print("Best order book ticker:")
await client.get_orderbook_ticker(pair = Pair('ETH', 'BTC'))
print("Create test market order:")
await client.create_test_order(Pair("ETH", "BTC"), side = enums.OrderSide.BUY, type = enums.OrderType.MARKET,
quantity = "1",
new_order_response_type = enums.OrderResponseType.FULL)
print("Create limit order:")
try:
await client.create_order(Pair("ETH", "BTC"), 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)
print("Cancel order:")
try:
await client.cancel_order(pair = Pair('ETH', 'BTC'), order_id = "1")
except BinanceException as e:
print(e)
print("Get order:")
try:
await client.get_order(pair = Pair('ETH', 'BTC'), order_id = 1)
except BinanceException as e:
print(e)
print("Get open orders:")
await client.get_open_orders(pair = Pair('ETH', 'BTC'))
print("Get all orders:")
await client.get_all_orders(pair = Pair('ETH', 'BTC'))
print("Create OCO order:")
try:
await client.create_oco_order(Pair("ETH", "BTC"), side = enums.OrderSide.BUY,
quantity = "1",
price = "0",
stop_price = "0",
new_order_response_type = enums.OrderResponseType.FULL)
except BinanceException as e:
print(e)
print("Cancel OCO order:")
try:
await client.cancel_oco_order(pair = Pair('ETH', 'BTC'), order_list_id = "1")
except BinanceException as e:
print(e)
print("Get OCO order:")
try:
await client.get_oco_order(order_list_id = 1)
except BinanceException as e:
print(e)
print("Get open OCO orders:")
await client.get_open_oco_orders()
print("Get all OCO orders:")
await client.get_all_oco_orders()
print("Account:")
await client.get_account(recv_window_ms = 5000)
print("Account trades:")
await client.get_account_trades(pair = Pair('ETH', 'BTC'))
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/liquid_rest_api.py | examples/liquid_rest_api.py | import logging
import os
import json
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.liquid import enums
from cryptoxlib.clients.liquid.exceptions import LiquidException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['LIQUIDAPIKEY']
sec_key = os.environ['LIQUIDSECKEY']
liquid = CryptoXLib.create_liquid_client(api_key, sec_key)
print("Products:")
products = await liquid.get_products()
for product in products['response']:
if product['currency_pair_code'] == 'ETHBTC':
print(json.dumps(product, indent = 4, sort_keys = True))
print("Product:")
product = await liquid.get_product(product_id = "1")
print(json.dumps(product['response'], indent = 4, sort_keys = True))
print("Orderbook:")
await liquid.get_order_book("1")
print("Order:")
try:
await liquid.get_order("1")
except LiquidException as e:
print(e)
print("Create order:")
try:
await liquid.create_order(product_id = "1", order_side = enums.OrderSide.BUY, order_type = enums.OrderType.LIMIT, quantity = "0",
price = "1")
except LiquidException as e:
print(e)
print("Cancel order:")
try:
await liquid.cancel_order(order_id = "1")
except LiquidException as e:
print(e)
print("Crypto accounts:")
await liquid.get_crypto_accounts()
print("Fiat accounts:")
await liquid.get_fiat_accounts()
print("Account details:")
await liquid.get_account_details(currency = "BTC")
print("Currencies:")
currencies = await liquid.get_currencies()
for currency in currencies['response']:
if currency['currency'] in ['BTC', 'ETH', 'USD', 'QASH']:
print(json.dumps(currency, indent = 4))
await liquid.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/eterbase_ws.py | examples/eterbase_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.eterbase.EterbaseWebsocket import OrderbookSubscription, TradesSubscription, OHLCVSubscription, \
AccountSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def trades_update(response: dict) -> None:
print(f"Callback trades_update: [{response}]")
async def ohlcv_update(response: dict) -> None:
print(f"Callback ohlcv_update: [{response}]")
async def account_update(response: dict) -> None:
print(f"Callback account_update: [{response}]")
def get_market_id(markets: dict, symbol: str) -> str:
return next(filter(lambda x: x['symbol'] == symbol, markets['response']))['id']
async def run():
api_key = os.environ['ETERBASEAPIKEY']
sec_key = os.environ['ETERBASESECKEY']
acct_key = os.environ['ETERBASEACCTKEY']
client = CryptoXLib.create_eterbase_client(acct_key, api_key, sec_key)
markets = await client.get_markets()
ethusdt_id = get_market_id(markets, 'ETHUSDT')
xbaseebase_id = get_market_id(markets, 'XBASEEBASE')
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
OrderbookSubscription([ethusdt_id, xbaseebase_id], callbacks = [order_book_update]),
TradesSubscription([ethusdt_id, xbaseebase_id], callbacks = [trades_update]),
OHLCVSubscription([ethusdt_id, xbaseebase_id], callbacks = [ohlcv_update]),
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
AccountSubscription([ethusdt_id, xbaseebase_id], callbacks = [account_update]),
])
# Execute all websockets asynchronously
await client.start_websockets()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bitforex_ws.py | examples/bitforex_ws.py | import logging
import os
from cryptoxlib.version_conversions import async_run
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.bitforex import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitforex.BitforexWebsocket import OrderBookSubscription, TradeSubscription, TickerSubscription, \
Ticker24hSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def trade_update(response : dict) -> None:
print(f"Callback trade_update: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def order_book_update2(response : dict) -> None:
print(f"Callback order_book_update2: [{response}]")
async def ticker_update(response : dict) -> None:
print(f"Callback ticker_update: [{response}]")
async def ticker24_update(response : dict) -> None:
print(f"Callback ticker24_update: [{response}]")
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()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_usds_m_futures_ws.py | examples/binance_usds_m_futures_ws.py | import logging
import os
from datetime import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance.BinanceFuturesWebsocket import AccountSubscription, OrderBookTickerSubscription, \
OrderBookSymbolTickerSubscription, CandlestickSubscription, CompositeIndexSubscription
from cryptoxlib.clients.binance.enums import Interval
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def account_update(response : dict) -> None:
print(f"Callback account_update: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def candlestick_update(response : dict) -> None:
print(f"Callback candlestick_update: [{response}]")
async def trade_update(response : dict) -> None:
local_timestamp_ms = int(datetime.now().timestamp() * 1000)
server_timestamp_ms = response['data']['E']
print(f"Callback trade_update: trade update timestamp diff [ms]:"
f" {local_timestamp_ms - server_timestamp_ms}")
async def orderbook_ticker_update(response : dict) -> None:
print(f"Callback orderbook_ticker_update: [{response}]")
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()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bibox_europe_ws.py | examples/bibox_europe_ws.py | import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bibox_europe.BiboxEuropeWebsocket import OrderBookSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def order_book_update2(response : dict) -> None:
print(f"Callback order_book_update2: [{response}]")
async def order_book_update3(response : dict) -> None:
print(f"Callback order_book_update3: [{response}]")
async def user_data_update(response : dict) -> None:
print(f"Callback user_data_update: [{response}]")
async def run():
#api_key = os.environ['BIBOXEUROPEAPIKEY']
#sec_key = os.environ['BIBOXEUROPESECKEY']
api_key = ""
sec_key = ""
bibox = CryptoXLib.create_bibox_europe_client(api_key, sec_key)
bibox.compose_subscriptions([
OrderBookSubscription(pair = Pair('ETH', 'BTC'), callbacks = [order_book_update]),
OrderBookSubscription(pair = Pair('BTC', 'EUR'), callbacks = [order_book_update]),
])
# Execute all websockets asynchronously
await bibox.start_websockets()
await bibox.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bibox_ws.py | examples/bibox_ws.py | import logging
import os
import datetime
from decimal import Decimal
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bibox.BiboxWebsocket import OrderBookSubscription, TradeSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.INFO)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def order_book_update(response : dict) -> None:
print(f"Order_book_update: [{response['data']['asks'][0]}] [{response['data']['bids'][0]}]")
data = response['data']
server_timestamp = int(Decimal(data['update_time']))
local_tmstmp_ms = int(datetime.datetime.now(tz = datetime.timezone.utc).timestamp() * 1000)
print(f"Timestamp diff: {local_tmstmp_ms - server_timestamp} ms")
async def trade_update(response : dict) -> None:
print(f"Trade_update: {response['data'][0]}")
async def order_book_update3(response : dict) -> None:
print(f"Callback order_book_update3: [{response}]")
async def user_data_update(response : dict) -> None:
print(f"Callback user_data_update: [{response}]")
async def run():
api_key = os.environ['BIBOXAPIKEY']
sec_key = os.environ['BIBOXSECKEY']
bibox = CryptoXLib.create_bibox_client(api_key, sec_key)
bibox.compose_subscriptions([
OrderBookSubscription(pair = Pair('BTC', 'USDT'), callbacks = [order_book_update]),
])
bibox.compose_subscriptions([
TradeSubscription(pair = Pair('BTC', 'USDT'), callbacks = [trade_update]),
])
# Execute all websockets asynchronously
await bibox.start_websockets()
await bibox.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_coin_m_futures_rest_api.py | examples/binance_coin_m_futures_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
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()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_testnet_ws.py | examples/binance_testnet_ws.py | import logging
import os
from datetime import datetime
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance.BinanceWebsocket import AccountSubscription, OrderBookTickerSubscription, \
TradeSubscription, OrderBookSymbolTickerSubscription, CandlestickSubscription
from cryptoxlib.clients.binance.enums import Interval
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def account_update(response : dict) -> None:
print(f"Callback account_update: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def candlestick_update(response : dict) -> None:
print(f"Callback candlestick_update: [{response}]")
async def trade_update(response : dict) -> None:
local_timestamp_ms = int(datetime.now().timestamp() * 1000)
server_timestamp_ms = response['data']['E']
print(f"Callback trade_update: trade update timestamp diff [ms]:"
f" {local_timestamp_ms - server_timestamp_ms}")
async def orderbook_ticker_update(response : dict) -> None:
print(f"Callback orderbook_ticker_update: [{response}]")
async def run():
api_key = os.environ['BINANCETESTAPIKEY']
sec_key = os.environ['BINANCETESTSECKEY']
client = CryptoXLib.create_binance_testnet_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
OrderBookTickerSubscription(callbacks = [orderbook_ticker_update]),
OrderBookSymbolTickerSubscription(pair = Pair("BTC", "USDT"), callbacks = [orderbook_ticker_update]),
TradeSubscription(pair = Pair('ETH', 'BTC'), callbacks = [trade_update]),
CandlestickSubscription(Pair('BTC', 'USDT'), Interval.I_1MIN, callbacks = [candlestick_update])
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
AccountSubscription(callbacks = [account_update])
])
# Execute all websockets asynchronously
await client.start_websockets()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_bswap_rest_api.py | examples/binance_bswap_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = CryptoXLib.create_binance_client(api_key, sec_key)
print('Swap pools:')
await client.get_bswap_pools()
print('Swap liquidity:')
await client.get_bswap_liquidity()
print('Add liquidity:')
try:
await client.bswap_add_liquidity(0, 'BTC', '10000000')
except Exception as e:
print(e)
print('Remove liquidity:')
try:
await client.bswap_remove_liquidity(0, 'BTC', '10000000', type = enums.LiquidityRemovalType.COMBINATION)
except Exception as e:
print(e)
print('Liquidity history:')
await client.get_bswap_liquidity_operations()
print('Request quote:')
await client.get_bswap_quote(Pair('BTC', 'USDT'), '1000')
print('Swap:')
try:
await client.bswap_swap(Pair('BTC', 'USDT'), '100000000000')
except Exception as e:
print(e)
print('Swap hisotry:')
await client.get_bswap_swap_history()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_testnet_rest_api.py | examples/binance_testnet_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['BINANCETESTAPIKEY']
sec_key = os.environ['BINANCETESTSECKEY']
client = CryptoXLib.create_binance_testnet_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(pair = Pair('ETH', 'BTC'), limit = enums.DepthLimit.L_5)
print("Trades:")
await client.get_trades(pair=Pair('ETH', 'BTC'), limit = 5)
print("Historical trades:")
await client.get_historical_trades(pair=Pair('ETH', 'BTC'), limit = 5)
print("Aggregate trades:")
await client.get_aggregate_trades(pair=Pair('ETH', 'BTC'), limit = 5)
print("Candlesticks:")
await client.get_candlesticks(pair=Pair('ETH', 'BTC'), interval = enums.Interval.I_1D, limit=5)
print("Average price:")
await client.get_average_price(pair = Pair('ETH', 'BTC'))
print("24hour price ticker:")
await client.get_24h_price_ticker(pair = Pair('ETH', 'BTC'))
print("Price ticker:")
await client.get_price_ticker(pair = Pair('ETH', 'BTC'))
print("Best order book ticker:")
await client.get_orderbook_ticker(pair = Pair('ETH', 'BTC'))
print("Create market order:")
await client.create_order(Pair("ETH", "BTC"), side = enums.OrderSide.BUY, type = enums.OrderType.MARKET,
quantity = "1",
new_order_response_type = enums.OrderResponseType.FULL)
print("Cancel order:")
try:
await client.cancel_order(pair = Pair('ETH', 'BTC'), order_id = "1")
except BinanceException as e:
print(e)
print("Get order:")
try:
await client.get_order(pair = Pair('ETH', 'BTC'), order_id = 1)
except BinanceException as e:
print(e)
print("Get open orders:")
await client.get_open_orders(pair = Pair('ETH', 'BTC'))
print("Get all orders:")
await client.get_all_orders(pair = Pair('ETH', 'BTC'))
print("Create OCO order:")
try:
await client.create_oco_order(Pair("ETH", "BTC"), side = enums.OrderSide.BUY,
quantity = "1",
price = "0",
stop_price = "0",
new_order_response_type = enums.OrderResponseType.FULL)
except BinanceException as e:
print(e)
print("Cancel OCO order:")
try:
await client.cancel_oco_order(pair = Pair('ETH', 'BTC'), order_list_id = "1")
except BinanceException as e:
print(e)
print("Get OCO order:")
try:
await client.get_oco_order(order_list_id = 1)
except BinanceException as e:
print(e)
print("Get open OCO orders:")
await client.get_open_oco_orders()
print("Get all OCO orders:")
await client.get_all_oco_orders()
print("Account:")
await client.get_account(recv_window_ms = 5000)
print("Account trades:")
await client.get_account_trades(pair = Pair('ETH', 'BTC'))
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/eterbase_rest_api.py | examples/eterbase_rest_api.py | import logging
import uuid
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.eterbase.exceptions import EterbaseException
from cryptoxlib.clients.eterbase import enums
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
def get_market_id(markets: dict, symbol: str) -> str:
return next(filter(lambda x: x['symbol'] == symbol, markets['response']))['id']
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def run():
api_key = os.environ['ETERBASEAPIKEY']
sec_key = os.environ['ETERBASESECKEY']
acct_key = os.environ['ETERBASEACCTKEY']
client = CryptoXLib.create_eterbase_client(acct_key, api_key, sec_key)
print("Time:")
response = await client.get_ping()
print(f"Headers: {response['headers']}")
print("Currencies:")
await client.get_currencies()
print("Markets:")
markets = await client.get_markets()
print("Balances:")
try:
await client.get_balances()
except EterbaseException as e:
print(e)
print("Create market order:")
try:
await client.create_order(pair_id = get_market_id(markets, 'ETHUSDT'), side = enums.OrderSide.BUY,
type = enums.OrderType.LIMIT, amount = "100000", price = "1",
time_in_force = enums.TimeInForce.GOOD_TILL_CANCELLED)
except EterbaseException as e:
print(e)
print("Cancel order:")
try:
await client.cancel_order(order_id = str(uuid.uuid4()))
except EterbaseException as e:
print(e)
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bibox_europe_rest_api.py | examples/bibox_europe_rest_api.py | import logging
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bibox_europe import enums
from cryptoxlib.clients.bibox_europe.exceptions import BiboxEuropeException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
#api_key = os.environ['BIBOXEUROPEAPIKEY']
#sec_key = os.environ['BIBOXEUROPESECKEY']
api_key = ""
sec_key = ""
bibox_europe = CryptoXLib.create_bibox_europe_client(api_key, sec_key)
print("Ping:")
await bibox_europe.get_ping()
print("Pair list:")
await bibox_europe.get_pairs()
print("Exchange info:")
await bibox_europe.get_exchange_info()
print("User assets:")
await bibox_europe.get_spot_assets(full = True)
print("Create order:")
try:
await bibox_europe.create_order(pair = Pair('ETH', 'BTC'), order_type = enums.OrderType.LIMIT,
order_side = enums.OrderSide.BUY, price = "1", quantity = "1")
except BiboxEuropeException as e:
print(e)
print("Cancel order:")
await bibox_europe.cancel_order(order_id = "1234567890")
await bibox_europe.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_blvt_rest_api.py | examples/binance_blvt_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = CryptoXLib.create_binance_client(api_key, sec_key)
print("BLVT symbol info:")
await client.get_blvt_info()
print("Subscribe BTCUP:")
try:
await client.blvt_subscribe("BTCUP", "500000000")
except Exception as e:
print(e)
print("Subscription history:")
await client.get_blvt_subscribtion_record()
print("Redeem BTCUP:")
try:
await client.blvt_redeem("BTCUP", "500000000")
except Exception as e:
print(e)
print("Redemption history:")
await client.get_blvt_redemption_record()
print("BLVT user limits:")
await client.get_blvt_user_info()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/aax_ws.py | examples/aax_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.aax.AAXWebsocket import OrderBookSubscription, AccountSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def trade_update(response : dict) -> None:
print(f"Callback trade_update: [{response}]")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def order_book_update2(response : dict) -> None:
print(f"Callback order_book_update2: [{response}]")
async def ticker_update(response : dict) -> None:
print(f"Callback ticker_update: [{response}]")
async def ticker24_update(response : dict) -> None:
print(f"Callback ticker24_update: [{response}]")
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['AAXAPIKEY']
sec_key = os.environ['AAXSECKEY']
user_id = os.environ['AAXUSERID']
aax = CryptoXLib.create_aax_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
aax.compose_subscriptions([
OrderBookSubscription(pair = Pair('BTC', 'USDT'), depth = 20, callbacks = [order_book_update]),
OrderBookSubscription(pair = Pair('ETH', 'USDT'), depth = 20, callbacks = [order_book_update2]),
])
# Bundle subscriptions into a separate websocket
aax.compose_subscriptions([
AccountSubscription(user_id)
])
# Execute all websockets asynchronously
await aax.start_websockets()
await aax.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_margin_rest_api.py | examples/binance_margin_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = CryptoXLib.create_binance_client(api_key, sec_key)
print("All margin assets:")
await client.get_margin_all_assets()
print("Margin pair:")
await client.get_margin_pair(Pair('BTC', 'USDT'))
print("Margin price index:")
await client.get_margin_price_index(Pair('BTC', 'USDT'))
print("Margin account balance:")
await client.get_margin_account()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bitpanda_ws.py | examples/bitpanda_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.onetrading.enums import TimeUnit, OrderSide, OrderType
from cryptoxlib.clients.onetrading.OneTradingWebsocket import AccountSubscription, PricesSubscription, \
OrderbookSubscription, CandlesticksSubscription, CandlesticksSubscriptionParams, MarketTickerSubscription, \
TradingSubscription, OrdersSubscription, ClientWebsocketHandle, CreateOrderMessage, CancelOrderMessage, \
UpdateOrderMessage, CancelAllOrdersMessage
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def trading_update(response: dict) -> None:
print(f"Callback trading_update: [{response}]")
async def account_update(response: dict) -> None:
print(f"Callback account_update: [{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 run():
api_key = os.environ['BITPANDAAPIKEY']
client = CryptoXLib.create_onetrading_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()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/coinmate_ws.py | examples/coinmate_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.coinmate.CoinmateWebsocket import OrderbookSubscription, TradesSubscription, \
UserOrdersSubscription, BalancesSubscription, UserTradesSubscription, UserTransfersSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def trades_update(response: dict) -> None:
print(f"Callback trades_update: [{response}]")
async def account_update(response: dict) -> None:
print(f"Callback account_update: [{response}]")
async def run():
api_key = os.environ['COINMATEAPIKEY']
sec_key = os.environ['COINMATESECKEY']
user_id = os.environ['COINMATEUSERID']
client = CryptoXLib.create_coinmate_client(user_id, api_key, sec_key)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
OrderbookSubscription(Pair("BTC", "EUR"), callbacks = [order_book_update]),
TradesSubscription(Pair("BTC", "EUR"), callbacks = [trades_update])
])
# Bundle private subscriptions into a separate websocket
client.compose_subscriptions([
UserOrdersSubscription(callbacks = [account_update]),
UserTradesSubscription(callbacks = [account_update]),
UserTransfersSubscription(callbacks = [account_update]),
BalancesSubscription(callbacks = [account_update])
])
# Execute all websockets asynchronously
await client.start_websockets()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/liquid_ws.py | examples/liquid_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.liquid import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.liquid.LiquidWebsocket import OrderBookSideSubscription, OrderBookSubscription, OrderSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def order_book_update(response : dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def order_book_update2(response : dict) -> None:
print(f"Callback order_book_update2: [{response}]")
async def order_book_update3(response : dict) -> None:
print(f"Callback order_book_update3: [{response}]")
async def order_update(response : dict) -> None:
print(f"Callback order_update: [{response}]")
async def run():
api_key = os.environ['LIQUIDAPIKEY']
sec_key = os.environ['LIQUIDSECKEY']
liquid = CryptoXLib.create_liquid_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
liquid.compose_subscriptions([
OrderBookSideSubscription(pair = Pair('BTC', 'USD'), order_side = enums.OrderSide.BUY, callbacks = [order_book_update]),
OrderBookSubscription(pair = Pair('ETH', 'USD'), callbacks = [order_book_update2]),
OrderBookSubscription(pair = Pair('XRP', 'USD'), callbacks = [order_book_update3]),
OrderSubscription(quote = "USD", callbacks = [order_update])
])
# Execute all websockets asynchronously
await liquid.start_websockets()
await liquid.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/btse_ws.py | examples/btse_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.btse.BtseWebsocket import AccountSubscription, OrderbookL2Subscription, OrderbookSubscription, \
TradeSubscription
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def run():
api_key = os.environ['BTSEAPIKEY']
sec_key = os.environ['BTSESECKEY']
client = CryptoXLib.create_btse_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
AccountSubscription(),
OrderbookL2Subscription([Pair("BTC", "USD"), Pair('ETH', 'BTC')], depth = 1)
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
OrderbookSubscription([Pair('BTSE', 'BTC')], callbacks = [order_book_update]),
TradeSubscription([Pair('BTSE', 'BTC')])
])
# Execute all websockets asynchronously
await client.start_websockets()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bitpanda_rest_api.py | examples/bitpanda_rest_api.py | import logging
import datetime
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.onetrading.exceptions import OneTradingException
from cryptoxlib.clients.onetrading.enums import OrderSide, TimeUnit
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def run():
api_key = os.environ['BITPANDAAPIKEY']
client = CryptoXLib.create_onetrading_client(api_key)
print("Time:")
response = await client.get_time()
print(f"Headers: {response['headers']}")
print("Account balance:")
await client.get_account_balances()
print("Account orders:")
await client.get_account_orders()
print("Account order:")
try:
await client.get_account_order("1")
except OneTradingException as e:
print(e)
print("Create market order:")
try:
await client.create_market_order(Pair("BTC", "EUR"), OrderSide.BUY, "10000")
except OneTradingException as e:
print(e)
print("Create limit order:")
try:
await client.create_limit_order(Pair("BTC", "EUR"), OrderSide.BUY, "10000", "1")
except OneTradingException as e:
print(e)
print("Create stop loss order:")
try:
await client.create_stop_limit_order(Pair("BTC", "EUR"), OrderSide.BUY, "10000", "1", "1")
except OneTradingException as e:
print(e)
print("Delete order:")
try:
await client.delete_account_order("1")
except OneTradingException as e:
print(e)
print("Order trades:")
try:
await client.get_account_order_trades("1")
except OneTradingException as e:
print(e)
print("Trades:")
await client.get_account_trades()
print("Trade:")
try:
await client.get_account_trade("1")
except OneTradingException as e:
print(e)
print("Trading volume:")
await client.get_account_trading_volume()
print("Currencies:")
await client.get_currencies()
print("Candlesticks:")
await client.get_candlesticks(Pair("BTC", "EUR"), TimeUnit.DAYS, "1",
datetime.datetime.now() - datetime.timedelta(days = 7), datetime.datetime.now())
print("Fees:")
await client.get_account_fees()
print("Instruments:")
await client.get_instruments()
print("Order book:")
await client.get_order_book(Pair("BTC", "EUR"))
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/hitbtc_ws.py | examples/hitbtc_ws.py | import logging
import os
import uuid
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.hitbtc.HitbtcWebsocket import TickerSubscription, OrderbookSubscription, TradesSubscription, \
AccountSubscription, ClientWebsocketHandle, CreateOrderMessage, CancelOrderMessage
from cryptoxlib.clients.hitbtc import enums
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def order_book_update(response: dict) -> None:
print(f"Callback order_book_update: [{response}]")
async def ticker_update(response: dict) -> None:
print(f"Callback ticker_update: [{response}]")
async def trade_update(response: dict) -> None:
print(f"Callback trade_update: [{response}]")
async def account_update(response: dict, websocket: ClientWebsocketHandle) -> None:
print(f"Callback account_update: [{response}]")
# as soon as account channel subscription is confirmed, fire testing orders
if 'id' in response and 'result' in response and response['result'] == True:
await websocket.send(CreateOrderMessage(
pair = Pair('ETH', 'BTC'),
type = enums.OrderType.LIMIT,
side = enums.OrderSide.BUY,
amount = "1000000000",
price = "0.000001",
client_id = str(uuid.uuid4())[:32]
))
await websocket.send(CancelOrderMessage(
client_id = "client_id"
))
async def run():
api_key = os.environ['HITBTCAPIKEY']
sec_key = os.environ['HITBTCSECKEY']
client = CryptoXLib.create_hitbtc_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
AccountSubscription(callbacks = [account_update]),
OrderbookSubscription(pair = Pair("ETH", "BTC"), callbacks = [order_book_update]),
TickerSubscription(pair = Pair("BTC", "USD"), callbacks = [ticker_update])
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
TradesSubscription(pair = Pair("ETH", "BTC"), limit = 5,callbacks = [trade_update])
])
# Execute all websockets asynchronously
await client.start_websockets()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/binance_margin_ws.py | examples/binance_margin_ws.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.binance.BinanceWebsocket import AccountCrossMarginSubscription, AccountIsolatedMarginSubscription,\
CandlestickSubscription
from cryptoxlib.clients.binance.enums import Interval
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}\n")
async def account_update(response : dict) -> None:
print(f"Callback account_update: [{response}]")
async def candlestick_update(response : dict) -> None:
print(f"Callback candlestick_update: [{response}]")
async def run():
api_key = os.environ['APIKEY']
sec_key = os.environ['SECKEY']
client = CryptoXLib.create_binance_client(api_key, sec_key)
# Bundle several subscriptions into a single websocket
client.compose_subscriptions([
CandlestickSubscription(Pair('BTC', 'USDT'), Interval.I_1MIN, callbacks = [candlestick_update])
])
# Bundle another subscriptions into a separate websocket
client.compose_subscriptions([
# uncomment if isolated margin account is setup
#AccountIsolatedMarginSubscription(pair = Pair('BTC', 'USDT'), callbacks = [account_update]),
AccountCrossMarginSubscription(callbacks = [account_update])
])
# Execute all websockets asynchronously
await client.start_websockets()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/btse_rest_api.py | examples/btse_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.Pair import Pair
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
async def run():
api_key = os.environ['BTSEAPIKEY']
sec_key = os.environ['BTSESECKEY']
client = CryptoXLib.create_btse_client(api_key, sec_key)
print("Exchange details:")
await client.get_exchange_info(pair = Pair('BTC', 'USD'))
print("Account funds:")
await client.get_funds()
await client.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/examples/bitforex_rest_api.py | examples/bitforex_rest_api.py | import logging
import os
from cryptoxlib.CryptoXLib import CryptoXLib
from cryptoxlib.clients.bitforex import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitforex.exceptions import BitforexException
from cryptoxlib.version_conversions import async_run
LOG = logging.getLogger("cryptoxlib")
LOG.setLevel(logging.DEBUG)
LOG.addHandler(logging.StreamHandler())
print(f"Available loggers: {[name for name in logging.root.manager.loggerDict]}")
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)
print("Exchange info:")
await bitforex.get_exchange_info()
print("Order book:")
await bitforex.get_order_book(pair = Pair('ETH', 'BTC'), depth = "1")
print("Ticker:")
await bitforex.get_ticker(pair = Pair('ETH', 'BTC'))
print("Single fund:")
await bitforex.get_single_fund(currency = "NOBS")
print("Funds:")
await bitforex.get_funds()
print("Trades:")
await bitforex.get_trades(pair = Pair('ETH', 'BTC'), size = "1")
print("Candlesticks:")
await bitforex.get_candlesticks(pair = Pair('ETH', 'BTC'), interval = enums.CandlestickInterval.I_1W, size = "5")
print("Create order:")
try:
await bitforex.create_order(Pair("ETH", "BTC"), side = enums.OrderSide.SELL, quantity = "1", price = "1")
except BitforexException as e:
print(e)
print("Create multiple orders:")
await bitforex.create_multi_order(Pair("ETH", "BTC"),
orders = [("1", "1", enums.OrderSide.SELL), ("2", "1", enums.OrderSide.SELL)])
print("Cancel order:")
await bitforex.cancel_order(pair = Pair('ETH', 'BTC'), order_id = "10")
print("Cancel multiple orders:")
await bitforex.cancel_multi_order(pair = Pair('ETH', 'BTC'), order_ids = ["10", "20"])
print("Cancel all orders:")
await bitforex.cancel_all_orders(pair = Pair('ETH', 'BTC'))
print("Get order:")
try:
await bitforex.get_order(pair = Pair('ETH', 'BTC'), order_id = "1")
except BitforexException as e:
print(e)
print("Get orders:")
await bitforex.get_orders(pair = Pair('ETH', 'BTC'), order_ids = ["1", "2"])
print("Find orders:")
await bitforex.find_order(pair = Pair('ETH', 'BTC'), state = enums.OrderState.PENDING)
await bitforex.close()
if __name__ == "__main__":
async_run(run())
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/PeriodicChecker.py | cryptoxlib/PeriodicChecker.py | import logging
import datetime
LOG = logging.getLogger(__name__)
class PeriodicChecker(object):
def __init__(self, period_ms):
self.period_ms = period_ms
self.last_exec_tmstmp_ms = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp() * 1000)
def check(self) -> bool:
now_tmstmp_ms = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp() * 1000)
if self.last_exec_tmstmp_ms + self.period_ms < now_tmstmp_ms:
self.last_exec_tmstmp_ms = now_tmstmp_ms
return True
else:
return False | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/CryptoXLibClient.py | cryptoxlib/CryptoXLibClient.py | import asyncio
import aiohttp
import ssl
import logging
import datetime
import json
import enum
import time
from abc import ABC, abstractmethod
from multidict import CIMultiDictProxy
from typing import List, Optional, Dict
from cryptoxlib.version_conversions import async_create_task
from cryptoxlib.Timer import Timer
from cryptoxlib.exceptions import CryptoXLibException
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr
LOG = logging.getLogger(__name__)
class RestCallType(enum.Enum):
GET = "GET"
POST = "POST"
DELETE = "DELETE"
PUT = "PUT"
class SubscriptionSet(object):
SUBSCRIPTION_SET_ID_SEQ = 0
def __init__(self, subscriptions: List[Subscription]):
self.subscription_set_id = SubscriptionSet.SUBSCRIPTION_SET_ID_SEQ
SubscriptionSet.SUBSCRIPTION_SET_ID_SEQ += 1
self.subscriptions: List[Subscription] = subscriptions
self.websocket_mgr: Optional[WebsocketMgr] = None
def find_subscription(self, subscription: Subscription) -> Optional[Subscription]:
for s in self.subscriptions:
if s.internal_subscription_id == subscription.internal_subscription_id:
return s
return None
class CryptoXLibClient(ABC):
def __init__(self, api_trace_log: bool = False, ssl_context: ssl.SSLContext = None) -> None:
self.api_trace_log = api_trace_log
self.rest_session = None
self.subscription_sets: Dict[int, SubscriptionSet] = {}
if ssl_context is not None:
self.ssl_context = ssl_context
else:
self.ssl_context = ssl.create_default_context()
@abstractmethod
def _get_rest_api_uri(self) -> str:
pass
@abstractmethod
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
pass
@abstractmethod
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
pass
@abstractmethod
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
pass
async def close(self) -> None:
session = self._get_rest_session()
if session is not None:
await session.close()
async def _create_get(self, resource: str, params: dict = None, headers: dict = None, signed: bool = False,
api_variable_path: str = None) -> dict:
return await self._create_rest_call(RestCallType.GET, resource, None, params, headers, signed, api_variable_path)
async def _create_post(self, resource: str, data: dict = None, params: dict = None, headers: dict = None, signed: bool = False,
api_variable_path: str = None) -> dict:
return await self._create_rest_call(RestCallType.POST, resource, data, params, headers, signed, api_variable_path)
async def _create_delete(self, resource: str, data:dict = None, params: dict = None, headers: dict = None, signed: bool = False,
api_variable_path: str = None) -> dict:
return await self._create_rest_call(RestCallType.DELETE, resource, data, params, headers, signed, api_variable_path)
async def _create_put(self, resource: str, data: dict = None, params: dict = None, headers: dict = None, signed: bool = False,
api_variable_path: str = None) -> dict:
return await self._create_rest_call(RestCallType.PUT, resource, data, params, headers, signed, api_variable_path)
async def _create_rest_call(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None, signed: bool = False,
api_variable_path: str = None) -> dict:
with Timer('RestCall'):
# ensure headers & params are always valid objects
if headers is None:
headers = {}
if params is None:
params = {}
# add signature into the parameters
if signed:
self._sign_payload(rest_call_type, resource, data, params, headers)
resource_uri = self._get_rest_api_uri()
if api_variable_path is not None:
resource_uri += api_variable_path
resource_uri += resource
if rest_call_type == RestCallType.GET:
rest_call = self._get_rest_session().get(resource_uri, json = data, params = params, headers = headers, ssl = self.ssl_context)
elif rest_call_type == RestCallType.POST:
rest_call = self._get_rest_session().post(resource_uri, json = data, params = params, headers = headers, ssl = self.ssl_context)
elif rest_call_type == RestCallType.DELETE:
rest_call = self._get_rest_session().delete(resource_uri, json = data, params = params, headers = headers, ssl = self.ssl_context)
elif rest_call_type == RestCallType.PUT:
rest_call = self._get_rest_session().put(resource_uri, json = data, params = params, headers = headers, ssl = self.ssl_context)
else:
raise Exception(f"Unsupported REST call type {rest_call_type}.")
LOG.debug(f"> rest type [{rest_call_type.name}], uri [{resource_uri}], params [{params}], headers [{headers}], data [{data}]")
async with rest_call as response:
status_code = response.status
headers = response.headers
body = await response.text()
LOG.debug(f"<: status [{status_code}], response [{body}]")
if len(body) > 0:
try:
body = json.loads(body)
except json.JSONDecodeError:
body = {
"raw": body
}
self._preprocess_rest_response(status_code, headers, body)
return {
"status_code": status_code,
"headers": headers,
"response": body
}
def _get_rest_session(self) -> aiohttp.ClientSession:
if self.rest_session is not None:
return self.rest_session
if self.api_trace_log:
trace_config = aiohttp.TraceConfig()
trace_config.on_request_start.append(CryptoXLibClient._on_request_start)
trace_config.on_request_end.append(CryptoXLibClient._on_request_end)
trace_configs = [trace_config]
else:
trace_configs = None
self.rest_session = aiohttp.ClientSession(trace_configs=trace_configs)
return self.rest_session
@staticmethod
def _clean_request_params(params: dict) -> dict:
clean_params = {}
for key, value in params.items():
if value is not None:
clean_params[key] = str(value)
return clean_params
@staticmethod
async def _on_request_start(session, trace_config_ctx, params) -> None:
LOG.debug(f"> Context: {trace_config_ctx}")
LOG.debug(f"> Params: {params}")
@staticmethod
async def _on_request_end(session, trace_config_ctx, params) -> None:
LOG.debug(f"< Context: {trace_config_ctx}")
LOG.debug(f"< Params: {params}")
@staticmethod
def _get_current_timestamp_ms() -> int:
return int(datetime.datetime.now(tz = datetime.timezone.utc).timestamp() * 1000)
@staticmethod
def _get_unix_timestamp_ns() -> int:
return int(time.time_ns() * 10**9)
def compose_subscriptions(self, subscriptions: List[Subscription]) -> int:
subscription_set = SubscriptionSet(subscriptions = subscriptions)
self.subscription_sets[subscription_set.subscription_set_id] = subscription_set
return subscription_set.subscription_set_id
async def add_subscriptions(self, subscription_set_id: int, subscriptions: List[Subscription]) -> None:
await self.subscription_sets[subscription_set_id].websocket_mgr.subscribe(subscriptions)
async def unsubscribe_subscriptions(self, subscriptions: List[Subscription]) -> None:
for subscription in subscriptions:
subscription_found = False
for id, subscription_set in self.subscription_sets.items():
if subscription_set.find_subscription(subscription) is not None:
subscription_found = True
await subscription_set.websocket_mgr.unsubscribe(subscriptions)
if not subscription_found:
raise CryptoXLibException(f"No active subscription {subscription.subscription_id} found.")
async def unsubscribe_subscription_set(self, subscription_set_id: int) -> None:
return await self.unsubscribe_subscriptions(self.subscription_sets[subscription_set_id].subscriptions)
async def unsubscribe_all(self) -> None:
for id, _ in self.subscription_sets.items():
await self.unsubscribe_subscription_set(id)
async def start_websockets(self, websocket_start_time_interval_ms: int = 0) -> None:
if len(self.subscription_sets) < 1:
raise CryptoXLibException("ERROR: There are no subscriptions to be started.")
tasks = []
startup_delay_ms = 0
for id, subscription_set in self.subscription_sets.items():
subscription_set.websocket_mgr = self._get_websocket_mgr(subscription_set.subscriptions, startup_delay_ms, self.ssl_context)
tasks.append(async_create_task(
subscription_set.websocket_mgr.run())
)
startup_delay_ms += websocket_start_time_interval_ms
done, pending = await asyncio.wait(tasks, return_when = asyncio.FIRST_EXCEPTION)
for task in done:
try:
task.result()
except Exception as e:
LOG.error(f"Unrecoverable exception occurred while processing messages: {e}")
LOG.info(f"Remaining websocket managers scheduled for shutdown.")
await self.shutdown_websockets()
if len(pending) > 0:
await asyncio.wait(pending, return_when = asyncio.ALL_COMPLETED)
LOG.info("All websocket managers shut down.")
raise
async def shutdown_websockets(self):
for id, subscription_set in self.subscription_sets.items():
await subscription_set.websocket_mgr.shutdown()
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/exceptions.py | cryptoxlib/exceptions.py | class CryptoXLibException(Exception):
pass
class WebsocketReconnectionException(CryptoXLibException):
pass
class WebsocketError(CryptoXLibException):
pass
class WebsocketClosed(CryptoXLibException):
pass | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/CryptoXLib.py | cryptoxlib/CryptoXLib.py | from cryptoxlib.clients.bitforex.BitforexClient import BitforexClient
from cryptoxlib.clients.liquid.LiquidClient import LiquidClient
from cryptoxlib.clients.bibox.BiboxClient import BiboxClient
from cryptoxlib.clients.bibox_europe.BiboxEuropeClient import BiboxEuropeClient
from cryptoxlib.clients.onetrading.OneTradingClient import OneTradingClient
from cryptoxlib.clients.binance.BinanceClient import BinanceClient, BinanceTestnetClient
from cryptoxlib.clients.binance.BinanceFuturesClient import BinanceUSDSMFuturesClient, BinanceUSDSMFuturesTestnetClient, \
BinanceCOINMFuturesClient, BinanceCOINMFuturesTestnetClient
from cryptoxlib.clients.binance import enums as binance_enums
from cryptoxlib.clients.bitvavo.BitvavoClient import BitvavoClient
from cryptoxlib.clients.btse.BtseClient import BtseClient
from cryptoxlib.clients.aax.AAXClient import AAXClient
from cryptoxlib.clients.hitbtc.HitbtcClient import HitbtcClient
from cryptoxlib.clients.eterbase.EterbaseClient import EterbaseClient
from cryptoxlib.clients.coinmate.CoinmateClient import CoinmateClient
class CryptoXLib(object):
@staticmethod
def create_bitforex_client(api_key: str, sec_key: str) -> BitforexClient:
return BitforexClient(api_key, sec_key)
@staticmethod
def create_liquid_client(api_key: str, sec_key: str) -> LiquidClient:
return LiquidClient(api_key, sec_key)
@staticmethod
def create_bibox_client(api_key: str, sec_key: str) -> BiboxClient:
return BiboxClient(api_key, sec_key)
@staticmethod
def create_bibox_europe_client(api_key: str, sec_key: str) -> BiboxEuropeClient:
return BiboxEuropeClient(api_key, sec_key)
@staticmethod
def create_onetrading_client(api_key: str) -> OneTradingClient:
return OneTradingClient(api_key)
@staticmethod
def create_binance_client(api_key: str, sec_key: str,
api_cluster: binance_enums.APICluster = binance_enums.APICluster.CLUSTER_DEFAULT) -> BinanceClient:
return BinanceClient(api_key, sec_key, api_cluster = api_cluster)
@staticmethod
def create_binance_testnet_client(api_key: str, sec_key: str) -> BinanceTestnetClient:
return BinanceTestnetClient(api_key, sec_key)
@staticmethod
def create_binance_usds_m_futures_client(api_key: str, sec_key: str) -> BinanceUSDSMFuturesClient:
return BinanceUSDSMFuturesClient(api_key, sec_key)
@staticmethod
def create_binance_usds_m_futures_testnet_client(api_key: str, sec_key: str) -> BinanceUSDSMFuturesTestnetClient:
return BinanceUSDSMFuturesTestnetClient(api_key, sec_key)
@staticmethod
def create_binance_coin_m_futures_client(api_key: str, sec_key: str) -> BinanceCOINMFuturesClient:
return BinanceCOINMFuturesClient(api_key, sec_key)
@staticmethod
def create_binance_coin_m_futures_testnet_client(api_key: str, sec_key: str) -> BinanceCOINMFuturesTestnetClient:
return BinanceCOINMFuturesTestnetClient(api_key, sec_key)
@staticmethod
def create_bitvavo_client(api_key: str, sec_key: str) -> BitvavoClient:
return BitvavoClient(api_key, sec_key)
@staticmethod
def create_btse_client(api_key: str, sec_key: str) -> BtseClient:
return BtseClient(api_key, sec_key)
@staticmethod
def create_aax_client(api_key: str, sec_key: str) -> AAXClient:
return AAXClient(api_key, sec_key)
@staticmethod
def create_hitbtc_client(api_key: str, sec_key: str) -> HitbtcClient:
return HitbtcClient(api_key, sec_key)
@staticmethod
def create_eterbase_client(account_id: str, api_key: str, sec_key: str) -> EterbaseClient:
return EterbaseClient(account_id, api_key, sec_key)
@staticmethod
def create_coinmate_client(user_id: str, api_key: str, sec_key: str) -> CoinmateClient:
return CoinmateClient(user_id, api_key, sec_key)
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/WebsocketMgr.py | cryptoxlib/WebsocketMgr.py | import websockets
import json
import logging
import asyncio
import ssl
import aiohttp
import enum
from abc import ABC, abstractmethod
from typing import List, Callable, Any, Optional, Union
from cryptoxlib.version_conversions import async_create_task
from cryptoxlib.exceptions import CryptoXLibException, WebsocketReconnectionException, WebsocketClosed, WebsocketError
LOG = logging.getLogger(__name__)
CallbacksType = List[Callable[..., Any]]
class WebsocketMgrMode(enum.Enum):
STOPPED = enum.auto()
RUNNING = enum.auto()
CLOSING = enum.auto()
class Websocket(ABC):
def __init__(self):
pass
@abstractmethod
async def connect(self):
pass
@abstractmethod
async def is_open(self):
pass
@abstractmethod
async def close(self):
pass
@abstractmethod
async def receive(self):
pass
@abstractmethod
async def send(self, message: str):
pass
class FullWebsocket(Websocket):
def __init__(self, websocket_uri: str, builtin_ping_interval: Optional[float] = 20,
max_message_size: int = 2**20, ssl_context: ssl.SSLContext = None):
super().__init__()
self.websocket_uri = websocket_uri
self.builtin_ping_interval = builtin_ping_interval
self.max_message_size = max_message_size
self.ssl_context = ssl_context
self.ws = None
async def connect(self):
if self.ws is not None:
raise CryptoXLibException("Websocket reattempted to make connection while previous one is still active.")
LOG.debug(f"Connecting to websocket {self.websocket_uri}")
self.ws = await websockets.connect(self.websocket_uri,
ping_interval = self.builtin_ping_interval,
max_size = self.max_message_size,
ssl = self.ssl_context)
async def is_open(self):
return self.ws is not None
async def close(self):
if self.ws is None:
raise CryptoXLibException("Websocket attempted to close connection while connection not open.")
await self.ws.close()
self.ws = None
async def receive(self):
if self.ws is None:
raise CryptoXLibException("Websocket attempted to read data while connection not open.")
return await self.ws.recv()
async def send(self, message: str):
if self.ws is None:
raise CryptoXLibException("Websocket attempted to send data while connection not open.")
return await self.ws.send(message)
class AiohttpWebsocket(Websocket):
def __init__(self, websocket_uri: str, builtin_ping_interval: Optional[float] = 20,
max_message_size: int = 2 ** 20, ssl_context: ssl.SSLContext = None):
super().__init__()
self.websocket_uri = websocket_uri
self.builtin_ping_interval = builtin_ping_interval
self.max_message_size = max_message_size
self.ssl_context = ssl_context
self.ws = None
async def connect(self):
if self.ws is not None:
raise CryptoXLibException("Websocket reattempted to make connection while previous one is still active.")
self.session = aiohttp.ClientSession()
self.ws = await self.session.ws_connect(url = self.websocket_uri,
max_msg_size = self.max_message_size,
autoping = True,
heartbeat = self.builtin_ping_interval,
ssl = self.ssl_context)
async def is_open(self):
return self.ws is not None
async def close(self):
if self.ws is None:
raise CryptoXLibException("Websocket attempted to close connection while connection not open.")
await self.ws.close()
await self.session.close()
self.ws = None
self.session = None
async def receive(self):
if self.ws is None:
raise CryptoXLibException("Websocket attempted to read data while connection not open.")
message = await self.ws.receive()
if message.type == aiohttp.WSMsgType.TEXT:
if message.data == 'close cmd':
raise WebsocketClosed(f'Websocket was closed: {message.data}')
else:
return message.data
elif message.type == aiohttp.WSMsgType.CLOSED:
raise WebsocketClosed(f'Websocket was closed: {message.data}')
elif message.type == aiohttp.WSMsgType.ERROR:
raise WebsocketError(f'Websocket error: {message.data}')
async def send(self, message: str):
if self.ws is None:
raise CryptoXLibException("Websocket attempted to send data while connection not open.")
return await self.ws.send_str(message)
class WebsocketOutboundMessage(ABC):
@abstractmethod
def to_json(self):
pass
class ClientWebsocketHandle(object):
def __init__(self, websocket: Websocket):
self.websocket = websocket
async def send(self, message: Union[str, dict, WebsocketOutboundMessage]):
if isinstance(message, str):
pass
elif isinstance(message, dict):
message = json.dumps(message)
elif isinstance(message, WebsocketOutboundMessage):
message = json.dumps(message.to_json())
else:
raise CryptoXLibException("Only string or JSON serializable objects can be sent over the websocket.")
LOG.debug(f"> {message}")
return await self.websocket.send(message)
async def receive(self):
return await self.websocket.receive()
class WebsocketMessage(object):
def __init__(self, subscription_id: Any, message: dict, websocket: ClientWebsocketHandle = None) -> None:
self.subscription_id = subscription_id
self.message = message
self.websocket = websocket
class Subscription(ABC):
INTERNAL_SUBSCRIPTION_ID_SEQ = 0
def __init__(self, callbacks: CallbacksType = None):
self.callbacks = callbacks
self.subscription_id = None
self.internal_subscription_id = Subscription.INTERNAL_SUBSCRIPTION_ID_SEQ
Subscription.INTERNAL_SUBSCRIPTION_ID_SEQ += 1
@abstractmethod
def construct_subscription_id(self) -> Any:
pass
@abstractmethod
def get_subscription_message(self, **kwargs) -> dict:
pass
def get_internal_subscription_id(self) -> int:
return self.internal_subscription_id
def get_subscription_id(self) -> Any:
if self.subscription_id is None:
self.subscription_id = self.construct_subscription_id()
LOG.debug(f"New subscription id constructed: {self.subscription_id}")
return self.subscription_id
async def initialize(self, **kwargs) -> None:
pass
async def process_message(self, message: WebsocketMessage) -> None:
await self.process_callbacks(message)
async def process_callbacks(self, message: WebsocketMessage) -> None:
if self.callbacks is not None:
tasks = []
for cb in self.callbacks:
# If message contains a websocket, then the websocket handle will be passed to the callbacks.
# This is useful for duplex websockets
if message.websocket is not None:
tasks.append(async_create_task(cb(message.message, message.websocket)))
else:
tasks.append(async_create_task(cb(message.message)))
await asyncio.gather(*tasks)
def __eq__(self, other):
return self.internal_subscription_id == other.internal_subscription_id
class WebsocketMgr(ABC):
WEBSOCKET_MGR_ID_SEQ = 0
def __init__(self, websocket_uri: str, subscriptions: List[Subscription], builtin_ping_interval: Optional[float] = 20,
max_message_size: int = 2**20, periodic_timeout_sec: int = None, ssl_context = None,
auto_reconnect: bool = False, startup_delay_ms: int = 0) -> None:
self.websocket_uri = websocket_uri
self.subscriptions = subscriptions
self.builtin_ping_interval = builtin_ping_interval
self.max_message_size = max_message_size
self.periodic_timeout_sec = periodic_timeout_sec
self.ssl_context = ssl_context
self.auto_reconnect = auto_reconnect
self.startup_delay_ms = startup_delay_ms
self.id = WebsocketMgr.WEBSOCKET_MGR_ID_SEQ
WebsocketMgr.WEBSOCKET_MGR_ID_SEQ += 1
self.websocket = None
self.mode: WebsocketMgrMode = WebsocketMgrMode.STOPPED
@abstractmethod
async def _process_message(self, websocket: Websocket, response: str) -> None:
pass
async def _process_periodic(self, websocket: Websocket) -> None:
pass
def get_websocket_uri_variable_part(self):
return ""
def get_websocket(self) -> Websocket:
return self.get_full_websocket()
def get_full_websocket(self) -> Websocket:
uri = self.websocket_uri + self.get_websocket_uri_variable_part()
LOG.debug(f"Websocket URI: {uri}")
return FullWebsocket(websocket_uri = uri,
builtin_ping_interval = self.builtin_ping_interval,
max_message_size = self.max_message_size,
ssl_context = self.ssl_context)
def get_aiohttp_websocket(self) -> Websocket:
uri = self.websocket_uri + self.get_websocket_uri_variable_part()
LOG.debug(f"Websocket URI: {uri}")
return AiohttpWebsocket(websocket_uri = uri,
builtin_ping_interval = self.builtin_ping_interval,
max_message_size = self.max_message_size,
ssl_context = self.ssl_context)
async def validate_subscriptions(self, subscriptions: List[Subscription]) -> None:
pass
async def initialize_subscriptions(self, subscriptions: List[Subscription]) -> None:
for subscription in subscriptions:
await subscription.initialize()
async def subscribe(self, new_subscriptions: List[Subscription]):
await self.validate_subscriptions(new_subscriptions)
await self.initialize_subscriptions(new_subscriptions)
self.subscriptions += new_subscriptions
await self.send_subscription_message(new_subscriptions)
async def send_subscription_message(self, subscriptions: List[Subscription]):
subscription_messages = []
for subscription in subscriptions:
subscription_messages.append(subscription.get_subscription_message())
LOG.debug(f"> {subscription_messages}")
await self.websocket.send(json.dumps(subscription_messages))
async def unsubscribe(self, subscriptions: List[Subscription]):
self.subscriptions = [subscription for subscription in self.subscriptions if subscription not in subscriptions]
await self.send_unsubscription_message(subscriptions)
async def send_unsubscription_message(self, subscriptions: List[Subscription]):
raise CryptoXLibException("The client does not support unsubscription messages.")
async def send_authentication_message(self):
pass
async def main_loop(self):
await self.send_authentication_message()
await self.send_subscription_message(self.subscriptions)
# start processing incoming messages
while True:
message = await self.websocket.receive()
LOG.debug(f"< {message}")
await self._process_message(self.websocket, message)
async def periodic_loop(self):
if self.periodic_timeout_sec is not None:
while True:
await self._process_periodic(self.websocket)
await asyncio.sleep(self.periodic_timeout_sec)
async def run(self) -> None:
self.mode = WebsocketMgrMode.RUNNING
await self.validate_subscriptions(self.subscriptions)
await self.initialize_subscriptions(self.subscriptions)
try:
# main loop ensuring proper reconnection if required
while True:
LOG.debug(f"[{self.id}] Initiating websocket connection.")
self.websocket = None
try:
# sleep for the requested period before initiating the connection. This is useful when client
# opens many connections at the same time and server cannot handle the load
await asyncio.sleep(self.startup_delay_ms / 1000.0)
LOG.debug(f"[{self.id}] Websocket initiation delayed by {self.startup_delay_ms}ms.")
self.websocket = self.get_websocket()
await self.websocket.connect()
done, pending = await asyncio.wait(
[async_create_task(self.main_loop()),
async_create_task(self.periodic_loop())],
return_when = asyncio.FIRST_EXCEPTION
)
for task in done:
try:
task.result()
except Exception as e:
LOG.debug(f"[{self.id}] Websocket processing has led to an exception, all pending tasks are going to be cancelled.")
for task in pending:
if not task.cancelled():
task.cancel()
if len(pending) > 0:
try:
await asyncio.wait(pending, return_when = asyncio.ALL_COMPLETED)
except asyncio.CancelledError:
await asyncio.wait(pending, return_when = asyncio.ALL_COMPLETED)
raise
finally:
LOG.debug(f"[{self.id}] All pending tasks cancelled successfully.")
raise
# recoverable exceptions
except (websockets.ConnectionClosedError,
websockets.ConnectionClosedOK,
websockets.InvalidStatusCode,
ConnectionResetError,
WebsocketClosed,
WebsocketError,
WebsocketReconnectionException) as e:
LOG.info(f"[{self.id}] Exception [{type(e)}]: {e}")
if self.mode == WebsocketMgrMode.CLOSING:
LOG.debug(f"[{self.id}] Websocket is going to be shut down.")
# exit the main infinite loop
break
elif self.auto_reconnect:
LOG.info(f"[{self.id}] A recoverable exception has occurred, the websocket will be restarted automatically.")
self._print_subscriptions()
else:
raise
finally:
if self.websocket is not None:
if await self.websocket.is_open():
LOG.debug(f"[{self.id}] Closing websocket connection.")
await self.websocket.close()
except asyncio.CancelledError:
LOG.warning(f"[{self.id}] The websocket was requested to be cancelled.")
except Exception as e:
LOG.error(f"[{self.id}] An exception [{e}] occurred. The websocket manager will be closed.")
self._print_subscriptions()
raise
async def publish_message(self, message: WebsocketMessage) -> None:
for subscription in self.subscriptions:
if subscription.get_subscription_id() == message.subscription_id:
await subscription.process_message(message)
return
LOG.warning(f"[{self.id}] Websocket message with subscription id {message.subscription_id} did not identify any subscription!")
def _print_subscriptions(self):
subscription_messages = []
for subscription in self.subscriptions:
subscription_messages.append(subscription.get_subscription_id())
LOG.info(f"[{self.id}] Subscriptions: {subscription_messages}")
async def shutdown(self):
if self.mode == WebsocketMgrMode.CLOSING:
LOG.debug(f"[{self.id}] Websocket manager already being shut down.")
return
self.mode = WebsocketMgrMode.CLOSING
if self.websocket is not None:
LOG.debug(f"[{self.id}] Manually closing websocket connection.")
if await self.websocket.is_open():
await self.websocket.close() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/version_conversions.py | cryptoxlib/version_conversions.py | import sys
import asyncio
import time
def is_python_version(major: int, minor: int, micro: int = None):
python_version = sys.version_info
if python_version.major == major and python_version.minor == minor:
if micro is not None:
return python_version.micro == micro
else:
return True
else:
return False
IS_PYTHON36 = is_python_version(3, 6)
IS_PYTHON37 = is_python_version(3, 7)
IS_PYTHON38 = is_python_version(3, 8)
IS_PYTHON39 = is_python_version(3, 9)
IS_PYTHON310 = is_python_version(3, 10)
def async_run(f):
if IS_PYTHON36:
loop = asyncio.get_event_loop()
return loop.run_until_complete(f)
elif IS_PYTHON37 or IS_PYTHON38 or IS_PYTHON39 or IS_PYTHON310:
return asyncio.run(f)
raise Exception(f'Unsupported Python version! Only versions 3.6.x, 3.7.x, 3.8.x, 3.9.x and 3.10.x are supported.')
def async_create_task(f):
if IS_PYTHON36:
loop = asyncio.get_event_loop()
return loop.create_task(f)
elif IS_PYTHON37 or IS_PYTHON38 or IS_PYTHON39 or IS_PYTHON310:
return asyncio.create_task(f)
raise Exception(f'Unsupported Python version! Only versions 3.6.x, 3.8.x, 3.9.x and 3.10.x are supported.')
def get_current_time_ms():
if IS_PYTHON36:
return time.time() * 1000.0
else:
return time.time_ns() / 1000000.0 | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/__init__.py | cryptoxlib/__init__.py | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false | |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/Pair.py | cryptoxlib/Pair.py | class Pair(object):
def __init__(self, base: str, quote: str) -> None:
self.base = base
self.quote = quote
def __str__(self):
return self.base + '/' + self.quote
def __repr__(self):
return self.__str__()
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/Timer.py | cryptoxlib/Timer.py | import logging
from cryptoxlib.version_conversions import get_current_time_ms
LOG = logging.getLogger(__name__)
class Timer(object):
def __init__(self, name: str, active: bool = True) -> None:
self.name = name
self.active = active
self.start_tmstmp_ms = None
def __enter__(self) -> None:
if self.active:
self.start_tmstmp_ms = get_current_time_ms()
def __exit__(self, type, value, traceback) -> None:
if self.active:
LOG.debug(f'Timer {self.name} finished. Took {round((get_current_time_ms() - self.start_tmstmp_ms), 3)} ms.') | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/__init__.py | cryptoxlib/clients/__init__.py | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false | |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitforex/enums.py | cryptoxlib/clients/bitforex/enums.py | import enum
class OrderSide(enum.Enum):
BUY = "1"
SELL = "2"
class OrderState(enum.Enum):
PENDING = "0"
COMPLETE = "1"
class CandlestickInterval(enum.Enum):
I_1MIN = '1min'
I_5MIN = '5min'
I_15MIN = '15min'
I_30MIN = '30min'
I_1H = '1hour'
I_2H = '2hour'
I_4H = '4hour'
I_12H = '12hour'
I_1D = '1day'
I_1W = '1week'
I_1MONTH = '1month' | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitforex/BitforexWebsocket.py | cryptoxlib/clients/bitforex/BitforexWebsocket.py | import json
import logging
import websockets
from abc import abstractmethod
from typing import List, Callable, Any, Union, Optional
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitforex import enums
from cryptoxlib.clients.bitforex.exceptions import BitforexException
from cryptoxlib.clients.bitforex.functions import map_pair
from cryptoxlib.PeriodicChecker import PeriodicChecker
LOG = logging.getLogger(__name__)
class BitforexWebsocket(WebsocketMgr):
WEBSOCKET_URI = "wss://www.bitforex.com/mkapi/coinGroup1/ws"
PING_MSG = 'ping_p'
PONG_MSG = 'pong_p'
def __init__(self, subscriptions: List[Subscription], ssl_context = None) -> None:
super().__init__(websocket_uri = BitforexWebsocket.WEBSOCKET_URI, subscriptions = subscriptions,
builtin_ping_interval = None, periodic_timeout_sec = 10, ssl_context = ssl_context)
self.ping_checker = PeriodicChecker(period_ms = 30 * 1000)
async def _process_periodic(self, websocket: Websocket) -> None:
if self.ping_checker.check():
LOG.debug(f"> {BitforexWebsocket.PING_MSG}")
await websocket.send(BitforexWebsocket.PING_MSG)
async def _process_message(self, websocket: Websocket, message: str) -> None:
if message != BitforexWebsocket.PONG_MSG:
message = json.loads(message)
subscription_id = BitforexSubscription.make_subscription_id(message['event'], message['param'])
await self.publish_message(WebsocketMessage(subscription_id = subscription_id, message = message))
class BitforexSubscription(Subscription):
def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
@staticmethod
def get_channel_name() -> str:
pass
@abstractmethod
def get_params(self) -> dict:
pass
@staticmethod
def make_subscription_id(channel: str, params: dict) -> dict:
subscription_id = {'channel': channel}
if channel == OrderBookSubscription.get_channel_name():
subscription_id.update(params)
elif channel == TradeSubscription.get_channel_name():
subscription_id['businessType'] = params['businessType']
elif channel == TickerSubscription.get_channel_name():
subscription_id['businessType'] = params['businessType']
subscription_id['kType'] = params['kType']
elif channel == Ticker24hSubscription.get_channel_name():
subscription_id.update(params)
else:
raise BitforexException(f'Unknown channel name {channel}')
return subscription_id
def construct_subscription_id(self) -> Any:
return BitforexSubscription.make_subscription_id(self.get_channel_name(), self.get_params())
def get_subscription_message(self, **kwargs) -> dict:
return {
"type": "subHq",
"event": self.get_channel_name(),
"param": self.get_params(),
}
class OrderBookSubscription(BitforexSubscription):
def __init__(self, pair: Pair, depth: str, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
self.depth = depth
@staticmethod
def get_channel_name():
return "depth10"
def get_params(self):
return {
"businessType": map_pair(self.pair),
"dType": int(self.depth)
}
class Ticker24hSubscription(BitforexSubscription):
def __init__(self, pair: Pair, callbacks: List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pair = pair
@staticmethod
def get_channel_name():
return "ticker"
def get_params(self):
return {
"businessType": map_pair(self.pair)
}
class TickerSubscription(BitforexSubscription):
def __init__(self, pair: Pair, size: str, interval: enums.CandlestickInterval, callbacks: List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pair = pair
self.size = size
self.interval = interval
@staticmethod
def get_channel_name():
return "kline"
def get_params(self):
return {
"businessType": map_pair(self.pair),
"size": int(self.size),
"kType": self.interval.value
}
class TradeSubscription(BitforexSubscription):
def __init__(self, pair: Pair, size: str, callbacks: List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pair = pair
self.size = size
@staticmethod
def get_channel_name():
return "trade"
def get_params(self):
return {
"businessType": map_pair(self.pair),
"size": int(self.size)
}
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitforex/BitforexClient.py | cryptoxlib/clients/bitforex/BitforexClient.py | import ssl
import logging
import hmac
import hashlib
from multidict import CIMultiDictProxy
from typing import List, Tuple, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bitforex import enums
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitforex.exceptions import BitforexRestException
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
from cryptoxlib.clients.bitforex.BitforexWebsocket import BitforexWebsocket
from cryptoxlib.clients.bitforex.functions import map_pair
LOG = logging.getLogger(__name__)
class BitforexClient(CryptoXLibClient):
REST_API_VERSION_URI = "/api/v1/"
REST_API_URI = "https://api.bitforex.com" + REST_API_VERSION_URI
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_trace_log, ssl_context)
self.api_key = api_key
self.sec_key = sec_key
def _get_rest_api_uri(self) -> str:
return BitforexClient.REST_API_URI
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
params['accessKey'] = self.api_key
params_string = ""
data_string = ""
if params is not None:
params_string = BitforexClient.REST_API_VERSION_URI + resource + '?'
params_string += '&'.join([f"{key}={val}" for key, val in sorted(params.items())])
if data is not None:
data_string = '&'.join(["{}={}".format(param[0], param[1]) for param in data])
m = hmac.new(self.sec_key.encode('utf-8'), (params_string + data_string).encode('utf-8'), hashlib.sha256)
params['signData'] = m.hexdigest()
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
if body['success'] is False:
raise BitforexRestException(status_code, body)
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BitforexWebsocket(subscriptions, ssl_context)
async def get_exchange_info(self) -> dict:
return await self._create_get("market/symbols")
async def get_order_book(self, pair: Pair, depth: str = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"size": depth,
})
return await self._create_get("market/depth", params = params)
async def get_ticker(self, pair: Pair) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair)
})
return await self._create_get("market/ticker", params = params, signed = True)
async def get_candlesticks(self, pair: Pair, interval: enums.CandlestickInterval, size: str = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"ktype": interval.value,
"size": size
})
return await self._create_get("market/kline", params = params, signed = True)
async def get_trades(self, pair: Pair, size: str = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"size": size
})
return await self._create_get("market/trades", params = params, signed = True)
async def get_single_fund(self, currency: str) -> dict:
params = CryptoXLibClient._clean_request_params({
"currency": currency.lower(),
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("fund/mainAccount", params = params, signed = True)
async def get_funds(self) -> dict:
params = CryptoXLibClient._clean_request_params({
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("fund/allAccount", params = params, signed = True)
async def create_order(self, pair: Pair, price: str, quantity: str, side: enums.OrderSide) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"price": price,
"amount": quantity,
"tradeType": side.value,
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("trade/placeOrder", params = params, signed = True)
# orders is a list of tuples where each tuple represents an order. Members of the tuple represent following attributes:
# (price, quantity, side)
async def create_multi_order(self, pair: Pair, orders: List[Tuple[str, str, enums.OrderSide]]) -> dict:
orders_data = []
for order in orders:
orders_data.append({
"price": order[0],
"amount": order[1],
"tradeType": order[2].value,
})
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"ordersData": orders_data,
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("trade/placeMultiOrder", params = params, signed = True)
async def cancel_order(self, pair: Pair, order_id: str) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderId": order_id,
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("trade/cancelOrder", params = params, signed = True)
async def cancel_multi_order(self, pair: Pair, order_ids: List[str]) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderIds": ",".join(order_ids),
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("trade/cancelMultiOrder", params = params, signed = True)
async def cancel_all_orders(self, pair: Pair) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("trade/cancelAllOrder", params = params, signed = True)
async def get_order(self, pair: Pair, order_id: str) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderId": order_id,
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("trade/orderInfo", params = params, signed = True)
async def find_order(self, pair: Pair, state: enums.OrderState, side: enums.OrderSide = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"state": state.value,
"nonce": self._get_current_timestamp_ms()
})
if side:
params["tradeType"] = side.value
return await self._create_post("trade/orderInfos", params = params, signed = True)
async def get_orders(self, pair: Pair, order_ids: List[str]) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderIds": ",".join(order_ids),
"nonce": self._get_current_timestamp_ms()
})
return await self._create_post("trade/multiOrderInfo", params = params, signed = True) | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitforex/exceptions.py | cryptoxlib/clients/bitforex/exceptions.py | from typing import Optional
from cryptoxlib.exceptions import CryptoXLibException
class BitforexException(CryptoXLibException):
pass
class BitforexRestException(BitforexException):
def __init__(self, status_code: int, body: Optional[dict]):
super().__init__(f"Rest API exception: status [{status_code}], response [{body}]")
self.status_code = status_code
self.body = body | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitforex/__init__.py | cryptoxlib/clients/bitforex/__init__.py | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false | |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitforex/functions.py | cryptoxlib/clients/bitforex/functions.py | from cryptoxlib.Pair import Pair
def map_pair(pair: Pair) -> str:
return f"coin-{pair.quote.lower()}-{pair.base.lower()}"
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/coinmate/enums.py | cryptoxlib/clients/coinmate/enums.py | import enum
class OrderType(enum.Enum):
MARKET = enum.auto()
LIMIT = enum.auto()
class OrderSide(enum.Enum):
BUY = enum.auto()
SELL = enum.auto()
class TimeInForce(enum.Enum):
GOOD_TILL_CANCELLED = enum.auto()
IMMEDIATE_OR_CANCELLED = enum.auto() | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/coinmate/exceptions.py | cryptoxlib/clients/coinmate/exceptions.py | from typing import Optional
from cryptoxlib.exceptions import CryptoXLibException
class CoinmateException(CryptoXLibException):
pass
class CoinmateRestException(CoinmateException):
def __init__(self, status_code: int, body: Optional[dict]):
super().__init__(f"Rest API exception: status [{status_code}], response [{body}]")
self.status_code = status_code
self.body = body | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/coinmate/CoinmateClient.py | cryptoxlib/clients/coinmate/CoinmateClient.py | import ssl
import logging
import datetime
import hmac
import hashlib
import pytz
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.coinmate.functions import map_pair
from cryptoxlib.clients.coinmate.exceptions import CoinmateRestException, CoinmateException
from cryptoxlib.clients.coinmate import enums
from cryptoxlib.clients.coinmate.CoinmateWebsocket import CoinmateWebsocket
from cryptoxlib.Pair import Pair
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
LOG = logging.getLogger(__name__)
class CoinmateClient(CryptoXLibClient):
REST_API_URI = "https://coinmate.io/api/"
def __init__(self, user_id: str = None, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_trace_log, ssl_context)
self.user_id = user_id
self.api_key = api_key
self.sec_key = sec_key
def _get_rest_api_uri(self) -> str:
return self.REST_API_URI
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
nonce = self._get_current_timestamp_ms()
input_message = str(nonce) + str(self.user_id) + self.api_key
m = hmac.new(self.sec_key.encode('utf-8'), input_message.encode('utf-8'), hashlib.sha256)
params['signature'] = m.hexdigest().upper()
params['clientId'] = self.user_id
params['publicKey'] = self.api_key
params['nonce'] = nonce
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
if str(status_code)[0] != '2':
raise CoinmateRestException(status_code, body)
else:
if "error" in body and body['error'] is True:
raise CoinmateRestException(status_code, body)
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return CoinmateWebsocket(subscriptions = subscriptions,
user_id = self.user_id, api_key = self.api_key, sec_key = self.sec_key,
ssl_context = ssl_context,
startup_delay_ms = startup_delay_ms)
async def get_exchange_info(self) -> dict:
return await self._create_get("tradingPairs")
async def get_currency_pairs(self) -> dict:
return await self._create_get("products")
async def get_order_book(self, pair: Pair, group: bool = False) -> dict:
params = CoinmateClient._clean_request_params({
"currencyPair": map_pair(pair),
"groupByPriceLimit": group
})
return await self._create_get("orderBook", params = params)
async def get_ticker(self, pair: Pair) -> dict:
params = CoinmateClient._clean_request_params({
"currencyPair": map_pair(pair)
})
return await self._create_get("ticker", params = params)
async def get_transactions(self, minutes_history: int, currency_pair: Pair = None) -> dict:
params = CoinmateClient._clean_request_params({
"minutesIntoHistory": minutes_history
})
if currency_pair is not None:
params['currencyPair'] = map_pair(currency_pair)
return await self._create_get("transactions", params = params)
async def get_balances(self) -> dict:
return await self._create_post("balances", signed = True)
async def get_fees(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['currencyPair'] = map_pair(pair)
return await self._create_post("traderFees", params = params, signed = True)
async def get_transaction_history(self, offset: int = None, limit: int = None, ascending = False, order_id: str = None,
from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None) -> dict:
params = CoinmateClient._clean_request_params({
"offset": offset,
"limit": limit,
"orderId": order_id
})
if ascending is True:
params['sort'] = 'ASC'
else:
params['sort'] = 'DESC'
if from_timestamp is not None:
params["timestampFrom"] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params["timestampTo"] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_post("transactionHistory", params = params, signed = True)
async def get_trade_history(self, limit: int = None, ascending = False, order_id: str = None, last_id: str = None,
from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None,
pair: Pair = None) -> dict:
params = CoinmateClient._clean_request_params({
"limit": limit,
"orderId": order_id,
"lastId": last_id
})
if pair is not None:
params['currencyPair'] = map_pair(pair)
if ascending is True:
params['sort'] = 'ASC'
else:
params['sort'] = 'DESC'
if from_timestamp is not None:
params["timestampFrom"] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params["timestampTo"] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_post("tradeHistory", params = params, signed = True)
async def get_transfer(self, transaction_id: str) -> dict:
params = CoinmateClient._clean_request_params({
"transactionId": transaction_id
})
return await self._create_post("transfer", params = params, signed = True)
async def get_transfer_history(self, limit: int = None, ascending = False, last_id: str = None,
from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None,
currency: str = None) -> dict:
params = CoinmateClient._clean_request_params({
"limit": limit,
"lastId": last_id,
"currency": currency
})
if ascending is True:
params['sort'] = 'ASC'
else:
params['sort'] = 'DESC'
if from_timestamp is not None:
params["timestampFrom"] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params["timestampTo"] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_post("transferHistory", params = params, signed = True)
async def get_order_history(self, pair: Pair, limit: int = None) -> dict:
params = CoinmateClient._clean_request_params({
"currencyPair": map_pair(pair),
"limit": limit
})
return await self._create_post("orderHistory", params = params, signed = True)
async def get_open_orders(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params["currencyPair"] = map_pair(pair)
return await self._create_post("openOrders", params = params, signed = True)
async def get_order(self, order_id: str = None, client_id: str = None) -> dict:
if not (bool(order_id) ^ bool(client_id)):
raise CoinmateException("One and only one of order_id and client_id can be provided.")
params = {}
if order_id is not None:
endpoint = "orderById"
params["orderId"] = order_id
else:
endpoint = "order"
params["clientOrderId"] = client_id
return await self._create_post(endpoint, params = params, signed = True)
async def cancel_order(self, order_id: str) -> dict:
params = {
"orderId": order_id
}
return await self._create_post("cancelOrder", params = params, signed = True)
async def cancel_all_orders(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params["currencyPair"] = map_pair(pair)
return await self._create_post("cancelAllOpenOrders", params = params, signed = True)
async def create_order(self, type: enums.OrderType,
pair: Pair,
side: enums.OrderSide,
amount: str,
price: str = None,
stop_price: str = None,
trailing: bool = None,
hidden: bool = None,
time_in_force: enums.TimeInForce = None,
post_only: bool = None,
client_id: str = None) -> dict:
params = CoinmateClient._clean_request_params({
"currencyPair": map_pair(pair),
"price": price,
"stopPrice": stop_price,
"clientOrderId": client_id
})
if type == enums.OrderType.MARKET:
if side == enums.OrderSide.BUY:
endpoint = "buyInstant"
params["total"] = amount
else:
endpoint = "sellInstant"
params["amount"] = amount
else:
if side == enums.OrderSide.BUY:
endpoint = "buyLimit"
else:
endpoint = "sellLimit"
params["amount"] = amount
if trailing is True:
params["trailing"] = "1"
if hidden is True:
params["hidden"] = "1"
if post_only is True:
params["postOnly"] = "1"
if time_in_force == enums.TimeInForce.IMMEDIATE_OR_CANCELLED:
params["immediateOrCancel"] = "1"
return await self._create_post(endpoint, params = params, signed = True) | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/coinmate/__init__.py | cryptoxlib/clients/coinmate/__init__.py | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false | |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/coinmate/functions.py | cryptoxlib/clients/coinmate/functions.py | from cryptoxlib.Pair import Pair
def map_pair(pair: Pair) -> str:
return f"{pair.base}_{pair.quote}"
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/coinmate/CoinmateWebsocket.py | cryptoxlib/clients/coinmate/CoinmateWebsocket.py | import json
import logging
import datetime
import hmac
import hashlib
from typing import List, Any
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.coinmate.functions import map_pair
from cryptoxlib.clients.coinmate.exceptions import CoinmateException
LOG = logging.getLogger(__name__)
class CoinmateWebsocket(WebsocketMgr):
WEBSOCKET_URI = "wss://coinmate.io/api/websocket"
MAX_MESSAGE_SIZE = 3 * 1024 * 1024 # 3MB
def __init__(self, subscriptions: List[Subscription],
user_id: str = None, api_key: str = None, sec_key: str = None,
ssl_context = None,
startup_delay_ms: int = 0) -> None:
super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions,
max_message_size = CoinmateWebsocket.MAX_MESSAGE_SIZE,
ssl_context = ssl_context,
auto_reconnect = True,
builtin_ping_interval = None,
startup_delay_ms = startup_delay_ms)
self.user_id = user_id
self.api_key = api_key
self.sec_key = sec_key
def get_websocket(self) -> Websocket:
return self.get_aiohttp_websocket()
async def initialize_subscriptions(self, subscriptions: List[Subscription]) -> None:
for subscription in subscriptions:
await subscription.initialize(user_id = self.user_id)
async def send_subscription_message(self, subscriptions: List[Subscription]):
for subscription in subscriptions:
subscription_message = {
"event": "subscribe",
"data": {
"channel": subscription.get_subscription_message()
}
}
if subscription.requires_authentication():
nonce = int(datetime.datetime.now(tz = datetime.timezone.utc).timestamp() * 1000) # timestamp ms
input_message = str(nonce) + str(self.user_id) + self.api_key
m = hmac.new(self.sec_key.encode('utf-8'), input_message.encode('utf-8'), hashlib.sha256)
subscription_message['data']['signature'] = m.hexdigest().upper()
subscription_message['data']['clientId'] = self.user_id
subscription_message['data']['publicKey'] = self.api_key
subscription_message['data']['nonce'] = nonce
LOG.debug(f"> {subscription_message}")
await self.websocket.send(json.dumps(subscription_message))
message = await self.websocket.receive()
LOG.debug(f"< {message}")
message = json.loads(message)
if message['event'] == 'subscribe_success':
LOG.info(f"Channel {subscription.get_subscription_message()} subscribed successfully.")
else:
raise CoinmateException(f"Subscription failed for channel {subscription.get_subscription_message()}. Response [{message}]")
async def send_unsubscription_message(self, subscriptions: List[Subscription]):
unsubscription_message = self._get_unsubscription_message(subscriptions)
LOG.debug(f"> {unsubscription_message}")
await self.websocket.send(json.dumps(unsubscription_message))
async def _process_message(self, websocket: Websocket, message: str) -> None:
message = json.loads(message)
# data message
if "event" in message and message['event'] == "data":
await self.publish_message(WebsocketMessage(
subscription_id = message['channel'],
message = message
))
class CoinmateSubscription(Subscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.user_id = None
def construct_subscription_id(self) -> Any:
return self.get_subscription_message()
def requires_authentication(self) -> bool:
return False
async def initialize(self, **kwargs):
self.user_id = kwargs['user_id']
class UserOrdersSubscription(CoinmateSubscription):
def __init__(self, pair: Pair = None, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_subscription_message(self, **kwargs) -> dict:
msg = f"private-open_orders-{self.user_id}"
if self.pair is not None:
msg += f"-{map_pair(self.pair)}"
return msg
def requires_authentication(self) -> bool:
return True
class UserTradesSubscription(CoinmateSubscription):
def __init__(self, pair: Pair = None, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_subscription_message(self, **kwargs) -> dict:
msg = f"private-user-trades-{self.user_id}"
if self.pair is not None:
msg += f"-{map_pair(self.pair)}"
return msg
def requires_authentication(self) -> bool:
return True
class UserTransfersSubscription(CoinmateSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_subscription_message(self, **kwargs) -> dict:
return f"private-user-transfers-{self.user_id}"
def requires_authentication(self) -> bool:
return True
class BalancesSubscription(CoinmateSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_subscription_message(self, **kwargs) -> dict:
return f"private-user_balances-{self.user_id}"
def requires_authentication(self) -> bool:
return True
class OrderbookSubscription(CoinmateSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_subscription_message(self, **kwargs) -> dict:
return f"order_book-{map_pair(self.pair)}"
class TradesSubscription(CoinmateSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_subscription_message(self, **kwargs) -> dict:
return f"trades-{map_pair(self.pair)}"
class TradeStatsSubscription(CoinmateSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_subscription_message(self, **kwargs) -> dict:
return f"statistics-{map_pair(self.pair)}" | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox/enums.py | cryptoxlib/clients/bibox/enums.py | import enum
class OrderType(enum.Enum):
LIMIT = 2
class OrderSide(enum.Enum):
BUY = 1
SELL = 2 | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox/BiboxWebsocket.py | cryptoxlib/clients/bibox/BiboxWebsocket.py | import json
import jwt
import time
import logging
import hmac
import zlib
import hashlib
import base64
import websockets
from abc import abstractmethod
from typing import List, Callable, Any, Optional
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bibox.functions import map_pair
from cryptoxlib.clients.bibox import enums
from cryptoxlib.clients.bibox.exceptions import BiboxException
LOG = logging.getLogger(__name__)
class BiboxWebsocket(WebsocketMgr):
WEBSOCKET_URI = "wss://push.bibox.com/"
def __init__(self, subscriptions: List[Subscription], api_key: str = None, sec_key: str = None, ssl_context = None) -> None:
super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions,
builtin_ping_interval = None, periodic_timeout_sec = 10, ssl_context = ssl_context,
auto_reconnect = True)
self.api_key = api_key
self.sec_key = sec_key
async def send_subscription_message(self, subscriptions: List[Subscription]):
for subscription in subscriptions:
subscription_message = json.dumps(
subscription.get_subscription_message(api_key = self.api_key, sec_key = self.sec_key))
LOG.debug(f"> {subscription_message}")
await self.websocket.send(subscription_message)
async def _process_message(self, websocket: Websocket, message: str) -> None:
messages = json.loads(message)
if "ping" in messages:
pong_message = {
"pong": messages['ping']
}
LOG.debug(f"> {pong_message}")
await websocket.send(json.dumps(pong_message))
elif 'error' in messages:
raise BiboxException(f"BiboxException: Bibox error received: {message}")
else:
for message in messages:
if 'data' in message:
data = message['data']
if 'binary' in message and message['binary'] == '1':
data = zlib.decompress(base64.b64decode(data), zlib.MAX_WBITS | 32)
message['data'] = json.loads(data.decode("utf-8"))
await self.publish_message(WebsocketMessage(subscription_id = message['channel'], message = message))
else:
LOG.warning(f"No data element received: {message}")
class BiboxSubscription(Subscription):
def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
@abstractmethod
def get_channel_name(self) -> str:
pass
def construct_subscription_id(self) -> Any:
return self.get_channel_name()
def get_subscription_message(self, **kwargs) -> dict:
return {
"binary": 0,
"channel": self.get_channel_name(),
"event": "addChannel",
}
class OrderBookSubscription(BiboxSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"bibox_sub_spot_{map_pair(self.pair)}_depth"
class TickerSubscription(BiboxSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"bibox_sub_spot_{map_pair(self.pair)}_ticker"
class MarketSubscription(BiboxSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return "bibox_sub_spot_ALL_ALL_market"
class TradeSubscription(BiboxSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"bibox_sub_spot_{map_pair(self.pair)}_deals"
class UserDataSubscription(BiboxSubscription):
def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
def get_channel_name(self):
return "bibox_sub_spot_ALL_ALL_login"
def get_subscription_message(self, **kwargs) -> dict:
subscription = {
"apikey": kwargs['api_key'],
'binary': 0,
"channel": self.get_channel_name(),
"event": "addChannel",
}
signature = hmac.new(kwargs['sec_key'].encode('utf-8'),
json.dumps(subscription, sort_keys=True).replace("\'", "\"").replace(" ", "").encode('utf-8'),
hashlib.md5).hexdigest()
subscription['sign'] = signature
return subscription | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox/exceptions.py | cryptoxlib/clients/bibox/exceptions.py | from cryptoxlib.exceptions import CryptoXLibException
class BiboxException(CryptoXLibException):
pass | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox/BiboxClient.py | cryptoxlib/clients/bibox/BiboxClient.py | import ssl
import logging
import json
import hmac
import hashlib
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bibox import enums
from cryptoxlib.clients.bibox.exceptions import BiboxException
from cryptoxlib.clients.bibox.functions import map_pair
from cryptoxlib.Pair import Pair
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
from cryptoxlib.clients.bibox.BiboxWebsocket import BiboxWebsocket
LOG = logging.getLogger(__name__)
class BiboxClient(CryptoXLibClient):
REST_API_URI = "https://api.bibox.com/v1/"
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_trace_log, ssl_context)
self.api_key = api_key
self.sec_key = sec_key
def _get_rest_api_uri(self) -> str:
return self.REST_API_URI
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
cmds = data['cmds']
signature = hmac.new(self.sec_key.encode('utf-8'), cmds.encode('utf-8'), hashlib.md5).hexdigest()
data['apikey'] = self.api_key
data['sign'] = signature
LOG.debug(f"Signed data: {data}")
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
if body is not None and 'error' in body:
raise BiboxException(f"BiboxException: status [{status_code}], response [{body}]")
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BiboxWebsocket(subscriptions, self.api_key, self.sec_key, ssl_context)
async def get_ping(self) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "ping",
"body": {}
}])
}
return await self._create_post("mdata", data = data)
async def get_pairs(self) -> dict:
return await self._create_get("mdata?cmd=pairList")
async def get_exchange_info(self) -> dict:
params = {
"cmd": "tradeLimit"
}
return await self._create_get("orderpending", params = params)
async def get_spot_assets(self, full: bool = False) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "transfer/assets",
"body": {
"select": 1 if full else 0
}
}])
}
return await self._create_post("transfer", data = data, signed = True)
async def create_order(self, pair: Pair, price: str, quantity: str, order_type: enums.OrderType,
order_side: enums.OrderSide) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "orderpending/trade",
"index": self._get_current_timestamp_ms(),
"body": {
"pair": map_pair(pair),
"account_type": 0, # spot account
"order_type": order_type.value,
"order_side": order_side.value,
"price": price,
"amount": quantity
}
}])
}
return await self._create_post("orderpending", data = data, signed = True)
async def cancel_order(self, order_id: str) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "orderpending/cancelTrade",
"index": self._get_current_timestamp_ms(),
"body": {
"orders_id": order_id
}
}])
}
return await self._create_post("orderpending", data = data, signed = True)
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox/__init__.py | cryptoxlib/clients/bibox/__init__.py | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false | |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox/functions.py | cryptoxlib/clients/bibox/functions.py | from cryptoxlib.Pair import Pair
def map_pair(pair: Pair) -> str:
return f"{pair.base}_{pair.quote}"
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/enums.py | cryptoxlib/clients/binance/enums.py | import enum
class OrderSide(enum.Enum):
BUY = "BUY"
SELL = "SELL"
class OrderType(enum.Enum):
LIMIT = 'LIMIT'
MARKET = 'MARKET'
STOP_LOSS = 'STOP_LOSS'
STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'
TAKE_PROFIT = 'TAKE_PROFIT'
TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'
LIMIT_MAKER = 'LIMIT_MAKER'
STOP = 'STOP'
STOP_MARKET = 'STOP_MARKET'
TAKE_PROFIT_MARKET = 'TAKE_PROFIT_MARKET'
TRAILING_STOP_MARKET = 'TRAILING_STOP_MARKET'
class PositionSide(enum.Enum):
BOTH = 'BOTH'
LONG = 'LONG'
SHORT = 'SHORT'
class WorkingType(enum.Enum):
MARK_PRICE = 'MARK_PRICE'
CONTRACT_PRICE = 'CONTRACT_PRICE'
class MarginType(enum.Enum):
ISOLATED = 'ISOLATED'
CROSSED = 'CROSSED'
class IncomeType(enum.Enum):
TRANSFER = "TRANSFER"
WELCOME_BONUS = "WELCOME_BONUS"
REALIZED_PNL = "REALIZED_PNL"
FUNDING_FEE = "FUNDING_FEE"
COMMISSION = "COMMISSION"
INSURANCE_CLEAR = "INSURANCE_CLEAR"
class AutoCloseType(enum.Enum):
LIQUIDATION = 'LIQUIDATION'
ADL = 'ADL'
class DepthLimit(enum.Enum):
L_5 = '5'
L_10 = '10'
L_20 = '20'
L_50 = '50'
L_100 = '100'
L_500 = '500'
L_1000 = '1000'
L_5000 = '5000'
class Interval(enum.Enum):
I_1MIN = '1m'
I_3MIN = '3m'
I_5MIN = '5m'
I_15MIN = '15m'
I_30MIN = '30m'
I_1H = '1h'
I_2H = '2h'
I_4H = '4h'
I_6H = '6h'
I_8H = '8h'
I_12H = '12h'
I_1D = '1d'
I_3D = '3d'
I_1W = '1w'
I_1MONTH = '1M'
class ContractType(enum.Enum):
PERPETUAL = 'PERPETUAL'
CURRENT_MONTH = 'CURRENT_MONTH'
NEXT_MONTH = 'NEXT_MONTH'
CURRENT_QUARTER = 'CURRENT_QUARTER'
NEXT_QUARTER = 'NEXT_QUARTER'
class OrderResponseType(enum.Enum):
ACT = "ACK"
RESULT = "RESULT"
FULL = "FULL"
class TimeInForce(enum.Enum):
GOOD_TILL_CANCELLED = "GTC"
IMMEDIATE_OR_CANCELLED = "IOC"
FILL_OR_KILL = "FOK"
GOOD_TILL_CROSSING = 'GTX'
class APICluster(enum.Enum):
CLUSTER_DEFAULT = "api"
CLUSTER_1 = "api1"
CLUSTER_2 = "api2"
CLUSTER_3 = "api3"
class CrossMarginTransferType(enum.Enum):
TO_CROSS_MARGIN_ACCOUNT = 1
TO_MAIN_ACCOUNT = 2
class SideEffectType(enum.Enum):
NO_SIDE_EFFECT = "NO_SIDE_EFFECT"
MARGIN_BUY = "MARGIN_BUY"
AUTO_REPAY = "AUTO_REPAY"
class TransferType(enum.Enum):
ROLL_IN = "ROLL_IN"
ROLL_OUT = "ROLL_OUT"
class AccountType(enum.Enum):
ISOLATED_MARGIN = "ISOLATED_MARGIN"
SPOT = "SPOT"
class LiquidityRemovalType(enum.Enum):
SINGLE = "SINGLE"
COMBINATION = "COMBINATION"
class LiquidityOperationType(enum.Enum):
ADD = "ADD"
REMOVE = "REMOVE"
class SwapStatusType(enum.Enum):
PENDING = 0
SUCCESS = 1
FAILED = 2
class DepositHistoryStatusType(enum.Enum):
PENDING = 0
CREDITED_CANNOT_WITHDRAW = 6
SUCCESS = 1 | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/BinanceCommonWebsocket.py | cryptoxlib/clients/binance/BinanceCommonWebsocket.py | import json
import logging
from typing import List, Any
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType
LOG = logging.getLogger(__name__)
class BinanceCommonWebsocket(WebsocketMgr):
SUBSCRIPTION_ID = 0
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
websocket_uri: str = None, builtin_ping_interval: float = 20, periodic_timeout_sec: int = None,
ssl_context = None) -> None:
super().__init__(websocket_uri = websocket_uri,
subscriptions = subscriptions,
builtin_ping_interval = builtin_ping_interval,
periodic_timeout_sec = periodic_timeout_sec,
ssl_context = ssl_context,
auto_reconnect = True)
self.api_key = api_key
self.sec_key = sec_key
self.binance_client = binance_client
def get_websocket_uri_variable_part(self):
return "stream?streams=" + "/".join([subscription.get_channel_name() for subscription in self.subscriptions])
def get_websocket(self) -> Websocket:
return self.get_aiohttp_websocket()
async def initialize_subscriptions(self, subscriptions: List[Subscription]) -> None:
for subscription in subscriptions:
await subscription.initialize(binance_client = self.binance_client)
async def send_subscription_message(self, subscriptions: List[Subscription]):
BinanceCommonWebsocket.SUBSCRIPTION_ID += 1
subscription_message = {
"method": "SUBSCRIBE",
"params": [
subscription.get_channel_name() for subscription in subscriptions
],
"id": BinanceCommonWebsocket.SUBSCRIPTION_ID
}
LOG.debug(f"> {subscription_message}")
await self.websocket.send(json.dumps(subscription_message))
async def send_unsubscription_message(self, subscriptions: List[Subscription]):
BinanceCommonWebsocket.SUBSCRIPTION_ID += 1
subscription_message = {
"method": "UNSUBSCRIBE",
"params": [
subscription.get_channel_name() for subscription in subscriptions
],
"id": BinanceCommonWebsocket.SUBSCRIPTION_ID
}
LOG.debug(f"> {subscription_message}")
await self.websocket.send(json.dumps(subscription_message))
@staticmethod
def _is_subscription_confirmation(response):
if 'result' in response and response['result'] is None:
return True
else:
return False
async def _process_message(self, websocket: Websocket, message: str) -> None:
if message is None:
return
message = json.loads(message)
if self._is_subscription_confirmation(message):
LOG.info(f"Subscription updated for id: {message['id']}")
else:
# regular message
await self.publish_message(WebsocketMessage(subscription_id = message['stream'], message = message))
class BinanceSubscription(Subscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
@staticmethod
def get_channel_name():
pass
def get_subscription_message(self, **kwargs) -> dict:
pass
def construct_subscription_id(self) -> Any:
return self.get_channel_name()
def is_authenticated(self) -> bool:
return False
def is_isolated_margin_authenticated(self) -> bool:
return False
def is_cross_margin_authenticated(self) -> bool:
return False | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/BinanceWebsocket.py | cryptoxlib/clients/binance/BinanceWebsocket.py | import logging
from typing import List
from cryptoxlib.WebsocketMgr import Subscription, CallbacksType, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.BinanceCommonWebsocket import BinanceCommonWebsocket
from cryptoxlib.clients.binance.BinanceCommonWebsocket import BinanceSubscription
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.clients.binance.functions import map_ws_pair
from cryptoxlib.clients.binance.enums import Interval
LOG = logging.getLogger(__name__)
class BinanceWebsocket(BinanceCommonWebsocket):
WEBSOCKET_URI = "wss://stream.binance.com:9443/"
LISTEN_KEY_REFRESH_INTERVAL_SEC = 1800
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
ssl_context = None) -> None:
super().__init__(subscriptions = subscriptions, binance_client = binance_client, api_key = api_key,
sec_key = sec_key, websocket_uri = BinanceWebsocket.WEBSOCKET_URI,
periodic_timeout_sec = BinanceWebsocket.LISTEN_KEY_REFRESH_INTERVAL_SEC,
ssl_context = ssl_context)
async def _process_periodic(self, websocket: Websocket) -> None:
for subscription in self.subscriptions:
if subscription.is_authenticated():
LOG.info(f"[{self.id}] Refreshing listen key.")
await self.binance_client.keep_alive_spot_listen_key(listen_key = subscription.listen_key)
if subscription.is_cross_margin_authenticated():
LOG.info(f"[{self.id}] Refreshing cross margin listen key.")
await self.binance_client.keep_alive_cross_margin_listen_key(listen_key = subscription.listen_key)
if subscription.is_isolated_margin_authenticated():
LOG.info(f"[{self.id}] Refreshing isolated margin listen key.")
await self.binance_client.keep_alive_isolated_margin_listen_key(listen_key = subscription.listen_key,
pair = subscription.pair)
class BinanceTestnetWebsocket(BinanceCommonWebsocket):
WEBSOCKET_URI = "wss://testnet.binance.vision/"
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
ssl_context = None) -> None:
super().__init__(subscriptions = subscriptions, binance_client = binance_client, api_key = api_key,
sec_key = sec_key, websocket_uri = BinanceTestnetWebsocket.WEBSOCKET_URI,
ssl_context = ssl_context)
class AllMarketTickersSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_channel_name(self):
return "!ticker@arr"
class OrderBookTickerSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_channel_name(self):
return "!bookTicker"
class OrderBookSymbolTickerSubscription(BinanceSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"{map_ws_pair(self.pair)}@bookTicker"
class TradeSubscription(BinanceSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return map_ws_pair(self.pair) + "@trade"
class AggregateTradeSubscription(BinanceSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return map_ws_pair(self.pair) + "@aggTrade"
class CandlestickSubscription(BinanceSubscription):
def __init__(self, pair: Pair, interval: Interval, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
self.interval = interval
def get_channel_name(self):
return f"{map_ws_pair(self.pair)}@kline_{self.interval.value}"
class AccountSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.listen_key = None
async def initialize(self, **kwargs):
binance_client = kwargs['binance_client']
listen_key_response = await binance_client.get_spot_listen_key()
self.listen_key = listen_key_response["response"]["listenKey"]
LOG.debug(f'Listen key: {self.listen_key}')
def get_channel_name(self):
return self.listen_key
def is_authenticated(self) -> bool:
return True
class AccountIsolatedMarginSubscription(BinanceSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
self.listen_key = None
async def initialize(self, **kwargs):
binance_client = kwargs['binance_client']
listen_key_response = await binance_client.get_isolated_margin_listen_key(self.pair)
self.listen_key = listen_key_response["response"]["listenKey"]
LOG.debug(f'Listen key: {self.listen_key}')
def get_channel_name(self):
return self.listen_key
def is_isolated_margin_authenticated(self) -> bool:
return True
class AccountCrossMarginSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.listen_key = None
async def initialize(self, **kwargs):
binance_client = kwargs['binance_client']
listen_key_response = await binance_client.get_cross_margin_listen_key()
self.listen_key = listen_key_response["response"]["listenKey"]
LOG.debug(f'Listen key: {self.listen_key}')
def get_channel_name(self):
return self.listen_key
def is_cross_margin_authenticated(self) -> bool:
return True
class DepthSubscription(BinanceSubscription):
DEFAULT_FREQUENCY = 1000
DEFAULT_LEVEL = 0
def __init__(self, pair: Pair, level: int = DEFAULT_LEVEL, frequency: int = DEFAULT_FREQUENCY,
callbacks: CallbacksType = None):
super().__init__(callbacks)
if level not in [0, 5, 10, 20]:
raise BinanceException(f"Level [{level}] must be one of 0, 5, 10 or 20.")
if frequency not in [100, 1000]:
raise BinanceException(f"Frequency [{frequency}] must be one of 100 or 1000.")
self.pair = pair
self.level = level
self.frequency = frequency
def get_channel_name(self):
if self.level == DepthSubscription.DEFAULT_LEVEL:
level_str = ""
else:
level_str = f"{self.level}"
if self.frequency == DepthSubscription.DEFAULT_FREQUENCY:
frequency_str = ""
else:
frequency_str = f"@{self.frequency}ms"
return f"{map_ws_pair(self.pair)}@depth{level_str}{frequency_str}" | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/exceptions.py | cryptoxlib/clients/binance/exceptions.py | from typing import Optional
from cryptoxlib.exceptions import CryptoXLibException
class BinanceException(CryptoXLibException):
pass
class BinanceRestException(BinanceException):
def __init__(self, status_code: int, body: Optional[dict]):
super().__init__(f"Rest API exception: status [{status_code}], response [{body}]")
self.status_code = status_code
self.body = body | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/BinanceClient.py | cryptoxlib/clients/binance/BinanceClient.py | import ssl
import logging
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient
from cryptoxlib.clients.binance.BinanceCommonClient import BinanceCommonClient
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.functions import map_pair
from cryptoxlib.Pair import Pair
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
from cryptoxlib.clients.binance.BinanceWebsocket import BinanceWebsocket, BinanceTestnetWebsocket
LOG = logging.getLogger(__name__)
class BinanceClient(BinanceCommonClient):
API_V3 = "api/v3/"
SAPI_V1 = "sapi/v1/"
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
api_cluster: enums.APICluster = enums.APICluster.CLUSTER_DEFAULT,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_key = api_key, sec_key = sec_key, api_trace_log = api_trace_log, ssl_context = ssl_context)
self.rest_api_uri = f"https://{api_cluster.value}.binance.com/"
def _get_rest_api_uri(self) -> str:
return self.rest_api_uri
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BinanceWebsocket(subscriptions = subscriptions, binance_client = self, api_key = self.api_key,
sec_key = self.sec_key, ssl_context = ssl_context)
async def ping(self) -> dict:
return await self._create_get("ping", api_variable_path = BinanceClient.API_V3)
async def get_exchange_info(self, pairs: List[Pair] = None) -> dict:
resource_path = "exchangeInfo"
if pairs is not None:
if len(pairs) == 1:
symbols = [map_pair(p) for p in pairs]
symbols_str = ",".join(symbols)
resource_path += "?symbol=" + symbols_str
else:
wrapped_symbols = ["\"" + map_pair(p) + "\"" for p in pairs]
symbols_str = ",".join(wrapped_symbols)
resource_path += "?symbols=" + "[" + symbols_str + "]"
return await self._create_get(resource_path, api_variable_path = BinanceClient.API_V3)
async def get_time(self) -> dict:
return await self._create_get("time", api_variable_path = BinanceClient.API_V3)
async def get_orderbook(self, pair: Pair, limit: enums.DepthLimit = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
})
if limit:
params['limit'] = limit.value
return await self._create_get("depth", params = params, api_variable_path = BinanceClient.API_V3)
async def get_trades(self, pair: Pair, limit: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"limit": limit
})
return await self._create_get("trades", params = params, api_variable_path = BinanceClient.API_V3)
async def get_historical_trades(self, pair: Pair, limit: int = None, from_id: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"limit": limit,
"fromId": from_id
})
return await self._create_get("historicalTrades", params = params, headers = self._get_header(), api_variable_path = BinanceClient.API_V3)
async def get_aggregate_trades(self, pair: Pair, limit: int = None, from_id: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"limit": limit,
"fromId": from_id,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("aggTrades", params = params, api_variable_path = BinanceClient.API_V3)
async def get_candlesticks(self, pair: Pair, limit: int = None, interval: enums.Interval = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
if interval:
params['interval'] = interval.value
return await self._create_get("klines", params = params, api_variable_path = BinanceClient.API_V3)
async def get_average_price(self, pair: Pair) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair)
})
return await self._create_get("avgPrice", params = params, api_variable_path = BinanceClient.API_V3)
async def get_24h_price_ticker(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("ticker/24hr", params = params, api_variable_path = BinanceClient.API_V3)
async def get_price_ticker(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("ticker/price", params = params, api_variable_path = BinanceClient.API_V3)
async def get_orderbook_ticker(self, pair: Optional[Pair] = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("ticker/bookTicker", headers = self._get_header(), params = params, api_variable_path = BinanceClient.API_V3)
async def create_order(self, pair: Pair, side: enums.OrderSide, type: enums.OrderType,
quantity: str,
price: str = None,
stop_price: str = None,
quote_order_quantity: str = None,
time_in_force: enums.TimeInForce = None,
new_client_order_id: str = None,
iceberg_quantity: str = None,
new_order_response_type: enums.OrderResponseType = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"side": side.value,
"type": type.value,
"quantity": quantity,
"quoteOrderQty": quote_order_quantity,
"price": price,
"stopPrice": stop_price,
"newClientOrderId": new_client_order_id,
"icebergQty": iceberg_quantity,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if time_in_force:
params['timeInForce'] = time_in_force.value
if new_order_response_type:
params['newOrderRespType'] = new_order_response_type.value
return await self._create_post("order", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceClient.API_V3)
async def create_test_order(self, pair: Pair, side: enums.OrderSide, type: enums.OrderType,
quantity: str,
price: str = None,
stop_price: str = None,
quote_order_quantity: str = None,
time_in_force: enums.TimeInForce = None,
new_client_order_id: str = None,
iceberg_quantity: str = None,
new_order_response_type: enums.OrderResponseType = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"side": side.value,
"type": type.value,
"quantity": quantity,
"quoteOrderQty": quote_order_quantity,
"price": price,
"stopPrice": stop_price,
"newClientOrderId": new_client_order_id,
"icebergQty": iceberg_quantity,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if time_in_force:
params['timeInForce'] = time_in_force.value
if new_order_response_type:
params['newOrderRespType'] = new_order_response_type.value
return await self._create_post("order/test", params = params, headers = self._get_header(),
signed = True, api_variable_path = BinanceClient.API_V3)
async def get_order(self, pair: Pair, order_id: int = None, orig_client_order_id: int = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderId": order_id,
"origClientOrderId": orig_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("order", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceClient.API_V3)
async def cancel_order(self, pair: Pair, order_id: str = None, orig_client_order_id: str = None,
new_client_order_id: str = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderId": order_id,
"origClientOrderId": orig_client_order_id,
"newClientOrderId": new_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_delete("order", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceClient.API_V3)
async def cancel_all_open_orders(self, pair: Pair, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
'symbol': map_pair(pair),
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_delete("openOrders", params = params, headers = self._get_header(),
signed = True, api_variable_path = BinanceClient.API_V3)
async def get_open_orders(self, pair: Pair = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("openOrders", params = params, headers = self._get_header(),
signed = True, api_variable_path = BinanceClient.API_V3)
async def get_all_orders(self, pair: Pair, order_id: int = None, limit: int = None, start_tmstmp_ms: int = None,
end_tmstmp_ms: int = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderId": order_id,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"limit": limit,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("allOrders", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceClient.API_V3)
async def create_oco_order(self, pair: Pair, side: enums.OrderSide,
quantity: str,
price: str,
stop_price: str,
limit_client_order_id: str = None,
list_client_order_id: str = None,
limit_iceberg_quantity: str = None,
stop_client_order_id: str = None,
stop_limit_price: str = None,
stop_iceberg_quantity: str = None,
stop_limit_time_in_force: enums.TimeInForce = None,
new_order_response_type: enums.OrderResponseType = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"side": side.value,
"quantity": quantity,
"listClientOrderId": list_client_order_id,
"limitClientOrderId": limit_client_order_id,
"price": price,
"stopClientOrderId": stop_client_order_id,
"stopPrice": stop_price,
"stopLimitPrice": stop_limit_price,
"stopIcebergQty": stop_iceberg_quantity,
"limitIcebergQty": limit_iceberg_quantity,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if stop_limit_time_in_force:
params['stopLimitTimeInForce'] = stop_limit_time_in_force.value
if new_order_response_type:
params['newOrderRespType'] = new_order_response_type.value
return await self._create_post("order/oco", params = params, headers = self._get_header(),
signed = True, api_variable_path = BinanceClient.API_V3)
async def cancel_oco_order(self, pair: Pair, order_list_id: str = None, list_client_order_id: str = None,
new_client_order_id: str = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderListId": order_list_id,
"listClientOrderId": list_client_order_id,
"newClientOrderId": new_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_delete("orderList", params = params, headers = self._get_header(),
signed = True, api_variable_path = BinanceClient.API_V3)
async def get_oco_order(self, order_list_id: int = None, orig_client_order_id: int = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"orderListId": order_list_id,
"origClientOrderId": orig_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("orderList", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceClient.API_V3)
async def get_all_oco_orders(self, from_id: int = None, limit: int = None, start_tmstmp_ms: int = None,
end_tmstmp_ms: int = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"fromId": from_id,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"limit": limit,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("allOrderList", params = params, headers = self._get_header(),
signed = True, api_variable_path = BinanceClient.API_V3)
async def get_open_oco_orders(self, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("openOrderList", params = params, headers = self._get_header(),
signed = True, api_variable_path = BinanceClient.API_V3)
async def get_account(self, recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("account", headers = self._get_header(), params = params, signed = True, api_variable_path = BinanceClient.API_V3)
async def get_account_trades(self, pair: Pair, limit: int = None, from_id: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"limit": limit,
"fromId": from_id,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("myTrades", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceClient.API_V3)
async def get_spot_listen_key(self):
return await self._create_post("userDataStream", headers = self._get_header(), api_variable_path = BinanceClient.API_V3)
async def keep_alive_spot_listen_key(self, listen_key: str):
params = {
"listenKey": listen_key
}
return await self._create_put("userDataStream", headers = self._get_header(), params = params, api_variable_path = BinanceClient.API_V3)
async def get_isolated_margin_listen_key(self, pair: Pair):
params = {
"symbol": map_pair(pair)
}
return await self._create_post("userDataStream/isolated", headers = self._get_header(), params = params, api_variable_path = BinanceClient.SAPI_V1)
async def keep_alive_isolated_margin_listen_key(self, listen_key: str, pair: Pair):
params = {
"listenKey": listen_key,
"symbol": map_pair(pair)
}
return await self._create_put("userDataStream/isolated", headers = self._get_header(), params = params, api_variable_path = BinanceClient.SAPI_V1)
async def get_cross_margin_listen_key(self):
return await self._create_post("userDataStream", headers = self._get_header(), api_variable_path = BinanceClient.SAPI_V1)
async def keep_alive_cross_margin_listen_key(self, listen_key: str):
params = {
"listenKey": listen_key
}
return await self._create_put("userDataStream", headers = self._get_header(), params = params, api_variable_path = BinanceClient.SAPI_V1)
## MARGIN ENDPOINTS
async def margin_transfer(
self,
asset: str,
amount: str,
transfer_type: enums.CrossMarginTransferType,
recv_window_ms: Optional[int] = None) -> dict:
"""
Cross Margin Account Transfer (MARGIN)
From the official original Binance REST API documentation:
POST /sapi/v1/margin/transfer (HMAC SHA256)
asset STRING YES The asset being transferred, e.g., BTC
amount DECIMAL YES The amount to be transferred
type INT YES 1: transfer from main account to cross margin account
2: transfer from cross margin account to main account
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
"""
params = {
"asset": asset,
"amount": amount,
"type": transfer_type.value,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
}
params = BinanceClient._clean_request_params(params)
return await self._create_post(
"margin/transfer",
headers = self._get_header(),
params = params,
signed = True,
api_variable_path = BinanceClient.SAPI_V1)
async def margin_borrow(
self,
asset: str,
amount: str,
pair: Optional[Pair] = None,
recv_window_ms: Optional[int] = None) -> dict:
"""
Margin Account Borrow (MARGIN)
From the official original Binance REST API documentation:
POST /sapi/v1/margin/loan (HMAC SHA256)
asset STRING YES
isIsolated STRING NO for isolated margin or not, "TRUE", "FALSE",default "FALSE"
symbol STRING NO isolated symbol
amount DECIMAL YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
If isIsolated = TRUE, symbol must be sent
isIsolated = FALSE for crossed margin loan
"""
params = {
"asset": asset,
"amount": amount,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
}
if pair is None:
params["isIsolated"] = "FALSE"
else:
params["isIsolated"] = "TRUE"
params["symbol"] = map_pair(pair)
params = BinanceClient._clean_request_params(params)
return await self._create_post(
"margin/loan",
headers = self._get_header(),
params = params,
signed = True,
api_variable_path = BinanceClient.SAPI_V1)
async def margin_repay(
self,
asset: str,
amount: str,
pair: Optional[Pair] = None,
recv_window_ms: Optional[int] = None) -> dict:
"""
Margin Account Repay (MARGIN)
From the official original Binance REST API documentation:
POST /sapi/v1/margin/repay (HMAC SHA256)
Repay loan for margin account.
asset STRING YES
isIsolated STRING NO for isolated margin or not, "TRUE", "FALSE",default "FALSE"
symbol STRING NO isolated symbol
amount DECIMAL YES
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
If "isIsolated" = "TRUE", "symbol" must be sent
"isIsolated" = "FALSE" for crossed margin repay
"""
params = {
"asset": asset,
"amount": amount,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
}
if pair is None:
params["isIsolated"] = "FALSE"
else:
params["isIsolated"] = "TRUE"
params["symbol"] = map_pair(pair)
params = BinanceClient._clean_request_params(params)
return await self._create_post(
"margin/repay",
headers = self._get_header(),
params = params,
signed = True,
api_variable_path = BinanceClient.SAPI_V1)
async def get_margin_asset(self, asset: str) -> dict:
"""
Query Margin Asset (MARKET_DATA)
From the official original Binance REST API documentation:
GET /sapi/v1/margin/asset
asset STRING YES
"""
params = {
"asset": asset,
}
params = BinanceClient._clean_request_params(params)
return await self._create_get(
"margin/asset",
headers = self._get_header(),
params = params,
api_variable_path = BinanceClient.SAPI_V1)
async def get_margin_pair(self, pair: Pair) -> dict:
"""
Query Cross Margin Pair (MARKET_DATA)
From the official original Binance REST API documentation:
GET /sapi/v1/margin/pair
symbol STRING YES
"""
params = {
"symbol": map_pair(pair),
}
params = BinanceClient._clean_request_params(params)
return await self._create_get(
"margin/pair",
headers = self._get_header(),
params = params,
api_variable_path = BinanceClient.SAPI_V1)
async def get_margin_all_assets(self) -> dict:
"""
Get All Margin Assets (MARKET_DATA)
From the official original Binance REST API documentation:
GET /sapi/v1/margin/allAssets
Parameters: None
"""
return await self._create_get(
"margin/allAssets",
headers = self._get_header(),
api_variable_path = BinanceClient.SAPI_V1)
async def get_margin_all_pairs(self) -> dict:
"""
Get All Cross Margin Pairs (MARKET_DATA)
From the official original Binance REST API documentation:
GET /sapi/v1/margin/allPairs
Parameters: None
"""
return await self._create_get(
"margin/allPairs",
headers = self._get_header(),
api_variable_path = BinanceClient.SAPI_V1)
async def get_margin_price_index(self, pair: Pair) -> dict:
"""
Query Margin PriceIndex (MARKET_DATA)
From the official original Binance REST API documentation:
GET /sapi/v1/margin/priceIndex
Weight: 1
Official Binance REST API documentation:
Parameters:
Name Type Mandatory
symbol STRING YES
"""
params = {
"symbol": map_pair(pair),
}
params = BinanceClient._clean_request_params(params)
return await self._create_get(
"margin/priceIndex",
headers = self._get_header(),
params = params,
api_variable_path = BinanceClient.SAPI_V1)
async def create_margin_order(self,
pair: Pair,
side: enums.OrderSide,
order_type: enums.OrderType,
quantity: str = None,
is_isolated: Optional[bool] = False,
quote_order_quantity: Optional[str] = None,
price: Optional[str] = None,
stop_price: Optional[str] = None,
new_client_order_id: Optional[str] = None,
iceberg_quantity: Optional[str] = None,
new_order_response_type: Optional[enums.OrderResponseType] = None,
side_effect_type: Optional[enums.SideEffectType] = None,
time_in_force: Optional[enums.TimeInForce] = None,
recv_window_ms: Optional[int] = None) -> dict:
"""
Margin Account New Order (TRADE)
From the official original Binance REST API documentation:
POST /sapi/v1/margin/order (HMAC SHA256)
Post a new order for margin account.
Official Binance REST API documentation:
Parameters:
Name Type Mandatory Description
symbol STRING YES
side ENUM YES BUY SELL
type ENUM YES
quantity DECIMAL NO
isIsolated STRING NO for isolated margin or not, "TRUE", "FALSE",default "FALSE"
quoteOrderQty DECIMAL NO
price DECIMAL NO
stopPrice DECIMAL NO Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT orders.
newClientOrderId STRING NO A unique id among open orders. Automatically generated if not sent.
icebergQty DECIMAL NO Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create
an iceberg order.
newOrderRespType ENUM NO Set the response JSON. ACK, RESULT, or FULL;
MARKET and LIMIT order types default to FULL, all other orders
default to ACK.
sideEffectType ENUM NO NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY; default NO_SIDE_EFFECT.
timeInForce ENUM NO GTC,IOC,FOK
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
"""
params = {
"symbol": map_pair(pair),
"side": side.value,
"type": order_type.value,
"quantity": quantity,
"quoteOrderQty": quote_order_quantity,
"price": price,
"stopPrice": stop_price,
"isIsolated": ("TRUE" if is_isolated else "FALSE"),
"newClientOrderId": new_client_order_id,
"icebergQty": iceberg_quantity,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
}
if time_in_force is not None:
params['timeInForce'] = time_in_force.value
elif order_type in [enums.OrderType.LIMIT, enums.OrderType.STOP_LOSS_LIMIT, enums.OrderType.TAKE_PROFIT_LIMIT]:
# default time_in_force for LIMIT orders
params['timeInForce'] = enums.TimeInForce.GOOD_TILL_CANCELLED.value
if new_order_response_type is not None:
params['newOrderRespType'] = new_order_response_type.value
if side_effect_type is not None:
params["sideEffectType"] = side_effect_type.value
params = BinanceClient._clean_request_params(params)
return await self._create_post(
"margin/order",
headers = self._get_header(),
params = params,
signed = True,
api_variable_path = BinanceClient.SAPI_V1)
async def cancel_margin_order(self,
pair: Pair,
is_isolated: Optional[bool] = False,
order_id: Optional[str] = None,
orig_client_order_id: Optional[str] = None,
new_client_order_id: Optional[str] = None,
recv_window_ms: Optional[int] = None) -> dict:
"""
Margin Account Cancel Order (TRADE)
From the official original Binance REST API documentation:
DELETE /sapi/v1/margin/order (HMAC SHA256)
Cancel an active order for margin account.
Weight: 1
Official Binance REST API documentation:
Parameters:
Name Type Mandatory Description
symbol STRING YES
isIsolated STRING NO for isolated margin or not, "TRUE", "FALSE",default "FALSE"
orderId LONG NO
origClientOrderId STRING NO
newClientOrderId STRING NO Used to uniquely identify this cancel. Automatically generated by default.
recvWindow LONG NO The value cannot be greater than 60000
timestamp LONG YES
Either orderId or origClientOrderId must be sent.
"""
params = {
"symbol": map_pair(pair),
"isIsolated": ("TRUE" if is_isolated else "FALSE"),
"orderId": order_id,
"origClientOrderId": orig_client_order_id,
"newClientOrderId": new_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
}
params = BinanceClient._clean_request_params(params)
return await self._create_delete(
"margin/order",
headers = self._get_header(),
params = params,
signed = True,
api_variable_path = BinanceClient.SAPI_V1)
async def cancel_margin_open_orders(self, pair: Pair, is_isolated: Optional[bool] = False,
recv_window_ms: Optional[int] = None) -> dict:
"""
Margin Account Cancel all Open Orders on a Symbol (TRADE)
From the official original Binance REST API documentation:
DELETE /sapi/v1/margin/openOrders (HMAC SHA256)
Cancels all active orders on a symbol for margin account.
This includes OCO orders.
Weight: 1
Official Binance REST API documentation:
Parameters
Name Type Mandatory Description
symbol STRING YES
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | true |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/BinanceCommonClient.py | cryptoxlib/clients/binance/BinanceCommonClient.py | import ssl
import logging
import hmac
import hashlib
from multidict import CIMultiDictProxy
from typing import Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.binance.exceptions import BinanceRestException
LOG = logging.getLogger(__name__)
class BinanceCommonClient(CryptoXLibClient):
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_trace_log, ssl_context)
self.api_key = api_key
self.sec_key = sec_key
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
params_string = ""
data_string = ""
if params is not None and len(params) > 0:
params_string = '&'.join([f"{key}={val}" for key, val in params.items()])
if data is not None and len(data) > 0:
data_string = '&'.join(["{}={}".format(param[0], param[1]) for param in data])
m = hmac.new(self.sec_key.encode('utf-8'), (params_string + data_string).encode('utf-8'), hashlib.sha256)
params['signature'] = m.hexdigest()
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
if str(status_code)[0] != '2':
raise BinanceRestException(status_code, body)
def _get_header(self):
header = {
'Accept': 'application/json',
"X-MBX-APIKEY": self.api_key
}
return header | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/BinanceFuturesClient.py | cryptoxlib/clients/binance/BinanceFuturesClient.py | import ssl
import logging
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient
from cryptoxlib.clients.binance.BinanceCommonClient import BinanceCommonClient
from cryptoxlib.clients.binance.BinanceFuturesWebsocket import BinanceUSDSMFuturesWebsocket, \
BinanceUSDSMFuturesTestnetWebsocket, BinanceCOINMFuturesWebsocket, BinanceCOINMFuturesTestnetWebsocket
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.functions import map_pair, extract_symbol
from cryptoxlib.clients.binance.types import PairSymbolType
from cryptoxlib.Pair import Pair
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
LOG = logging.getLogger(__name__)
class BinanceFuturesClient(BinanceCommonClient):
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_key = api_key, sec_key = sec_key, api_trace_log = api_trace_log, ssl_context = ssl_context)
def get_api_v1(self) -> str:
pass
def get_api_v2(self) -> str:
pass
def get_api_futures(self) -> str:
pass
async def ping(self) -> dict:
return await self._create_get("ping", api_variable_path = self.get_api_v1())
async def get_exchange_info(self) -> dict:
return await self._create_get("exchangeInfo", api_variable_path = self.get_api_v1())
async def get_time(self) -> dict:
return await self._create_get("time", api_variable_path = self.get_api_v1())
async def get_orderbook(self, symbol: PairSymbolType, limit: enums.DepthLimit = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
})
if limit is not None:
params['limit'] = limit.value
return await self._create_get("depth", params = params, api_variable_path = self.get_api_v1())
async def get_trades(self, symbol: PairSymbolType, limit: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"limit": limit
})
return await self._create_get("trades", params = params, api_variable_path = self.get_api_v1())
async def get_historical_trades(self, symbol: PairSymbolType, limit: int = None, from_id: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"limit": limit,
"fromId": from_id
})
return await self._create_get("historicalTrades", params = params, headers = self._get_header(),
api_variable_path = self.get_api_v1())
async def get_aggregate_trades(self, symbol: PairSymbolType, limit: int = None, from_id: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"limit": limit,
"fromId": from_id,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("aggTrades", params = params, api_variable_path = self.get_api_v1())
async def get_candlesticks(self, symbol: PairSymbolType, interval: enums.Interval, limit: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
if interval:
params['interval'] = interval.value
return await self._create_get("klines", params = params, api_variable_path = self.get_api_v1())
async def get_cont_contract_candlesticks(self, pair: Pair, interval: enums.Interval,
contract_type: enums.ContractType, limit: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"pair": map_pair(pair),
"contractType": contract_type.value,
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
if interval:
params['interval'] = interval.value
return await self._create_get("continuousKlines", params = params, api_variable_path = self.get_api_v1())
async def get_index_price_candlesticks(self, pair: Pair, interval: enums.Interval,
limit: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"pair": map_pair(pair),
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
if interval:
params['interval'] = interval.value
return await self._create_get("indexPriceKlines", params = params, api_variable_path = self.get_api_v1())
async def get_mark_price_candlesticks(self, symbol: PairSymbolType, interval: enums.Interval,
limit: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
if interval:
params['interval'] = interval.value
return await self._create_get("markPriceKlines", params = params, api_variable_path = self.get_api_v1())
async def get_open_interest(self, symbol: PairSymbolType) -> dict:
params = {
"symbol": extract_symbol(symbol)
}
return await self._create_get("openInterest", headers = self._get_header(), params = params, api_variable_path = self.get_api_v1())
async def change_position_type(self, dual_side_position: bool, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"dualSidePosition": "true" if dual_side_position else "false",
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_post("positionSide/dual", headers = self._get_header(), params = params, signed = True,
api_variable_path = self.get_api_v1())
async def get_position_type(self, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("positionSide/dual", headers = self._get_header(), params = params, signed = True,
api_variable_path = self.get_api_v1())
async def create_order(self, symbol: PairSymbolType, side: enums.OrderSide, type: enums.OrderType,
position_side: enums.PositionSide = None,
quantity: str = None,
price: str = None,
stop_price: str = None,
time_in_force: enums.TimeInForce = None,
new_client_order_id: str = None,
reduce_only: bool = None,
close_position: bool = None,
activation_price: str = None,
callback_rate: str = None,
working_type: enums.WorkingType = None,
price_protect: bool = None,
new_order_response_type: enums.OrderResponseType = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"side": side.value,
"type": type.value,
"quantity": quantity,
"price": price,
"stopPrice": stop_price,
"newClientOrderId": new_client_order_id,
"activationPrice": activation_price,
"callbackRate": callback_rate,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if price_protect is not None:
params['priceProtect'] = "true" if price_protect else "false"
if working_type is not None:
params['workingType'] = working_type.value
if position_side is not None:
params['positionSide'] = position_side.value
if reduce_only is not None:
params['reduceOnly'] = "true" if reduce_only else "false"
if close_position is not None:
params['closePosition'] = "true" if close_position else "false"
if time_in_force is not None:
params['timeInForce'] = time_in_force.value
if new_order_response_type is not None:
params['newOrderRespType'] = new_order_response_type.value
return await self._create_post("order", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_order(self, symbol: PairSymbolType, order_id: int = None, orig_client_order_id: int = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"orderId": order_id,
"origClientOrderId": orig_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("order", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def cancel_order(self, symbol: PairSymbolType,
order_id: int = None, orig_client_order_id: str = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"orderId": order_id,
"origClientOrderId": orig_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_delete("order", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def cancel_all_orders(self, symbol: PairSymbolType, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_delete("allOpenOrders", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def auto_cancel_orders(self, symbol: PairSymbolType, countdown_time_ms: int,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"countdownTime": countdown_time_ms,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_delete("countdownCancelAll", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_open_order(self, symbol: PairSymbolType, order_id: int = None, orig_client_order_id: int = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"orderId": order_id,
"origClientOrderId": orig_client_order_id,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("openOrder", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def change_init_leverage(self, symbol: PairSymbolType, leverage: int, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"leverage": leverage,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_post("leverage", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def change_margin_type(self, symbol: PairSymbolType, margin_type: enums.MarginType, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"marginType": margin_type.value,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_post("marginType", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def update_isolated_position_margin(self, symbol: PairSymbolType, quantity: str, type: int,
position_side: enums.PositionSide = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"amount": quantity,
"type": type,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if position_side is not None:
params['positionSide'] = position_side.value
return await self._create_post("positionMargin", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_position_margin_change_history(self, symbol: PairSymbolType, limit: int = None, type: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None,
recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"limit": limit,
"type": type,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("positionMargin/history", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_income_history(self, symbol: PairSymbolType = None, limit: int = None,
income_type: enums.IncomeType = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None,
recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"timestamp": self._get_current_timestamp_ms(),
"recvWindow": recv_window_ms
})
if symbol is not None:
params['symbol'] = extract_symbol(symbol)
if income_type is not None:
params['incomeType'] = income_type.value
return await self._create_get("income", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_force_orders(self, symbol: PairSymbolType = None, limit: int = None, auto_close_type: enums.AutoCloseType = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None,
recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"timestamp": self._get_current_timestamp_ms(),
"recvWindow": recv_window_ms
})
if auto_close_type is not None:
params['autoCloseType'] = auto_close_type.value
if symbol is not None:
params['symbol'] = extract_symbol(symbol)
return await self._create_get("forceOrders", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_adl_quantile(self, symbol: PairSymbolType = None, recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"timestamp": self._get_current_timestamp_ms(),
"recvWindow": recv_window_ms
})
if symbol is not None:
params['symbol'] = extract_symbol(symbol)
return await self._create_get("adlQuantile", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_commission_rate(self, symbol: PairSymbolType, recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": extract_symbol(symbol),
"timestamp": self._get_current_timestamp_ms(),
"recvWindow": recv_window_ms
})
return await self._create_get("commissionRate", params = params, headers = self._get_header(), signed = True,
api_variable_path = self.get_api_v1())
async def get_listen_key(self):
return await self._create_post("listenKey", headers = self._get_header(), api_variable_path = self.get_api_v1())
async def keep_alive_listen_key(self):
return await self._create_put("listenKey", headers = self._get_header(), api_variable_path = self.get_api_v1())
class BinanceUSDSMFuturesClient(BinanceFuturesClient):
REST_API_URI = "https://fapi.binance.com/"
FAPI_V1 = "fapi/v1/"
FAPI_V2 = "fapi/v2/"
FUTURES_DATA = "futures/data/"
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_key = api_key, sec_key = sec_key, api_trace_log = api_trace_log, ssl_context = ssl_context)
def _get_rest_api_uri(self) -> str:
return BinanceUSDSMFuturesClient.REST_API_URI
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BinanceUSDSMFuturesWebsocket(subscriptions = subscriptions, binance_client = self, api_key = self.api_key,
sec_key = self.sec_key, ssl_context = ssl_context)
def get_api_v1(self) -> str:
return BinanceUSDSMFuturesClient.FAPI_V1
def get_api_v2(self) -> str:
return BinanceUSDSMFuturesClient.FAPI_V2
def get_api_futures(self) -> str:
return BinanceUSDSMFuturesClient.FUTURES_DATA
async def get_mark_price(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("premiumIndex", params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_fund_rate_history(self, pair: Pair = None, limit: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("fundingRate", params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_24h_price_ticker(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("ticker/24hr", params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_price_ticker(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("ticker/price", params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_orderbook_ticker(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("ticker/bookTicker", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
# Not maintained by binance, will be removed in the future
async def get_all_liquidation_orders(self, pair: Pair = None, limit: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("allForceOrders", params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_open_interest_hist(self, pair: Pair, interval: enums.Interval,
limit: int = None, start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"period": interval.value,
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("openInterestHist", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FUTURES_DATA)
async def get_top_long_short_account_ratio(self, pair: Pair, interval: enums.Interval,
limit: int = None, start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"period": interval.value,
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("topLongShortAccountRatio", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FUTURES_DATA)
async def get_top_long_short_position_ratio(self, pair: Pair, interval: enums.Interval,
limit: int = None, start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"period": interval.value,
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("topLongShortPositionRatio", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FUTURES_DATA)
async def get_global_long_short_account_ratio(self, pair: Pair, interval: enums.Interval,
limit: int = None, start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"period": interval.value,
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("globalLongShortAccountRatio", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FUTURES_DATA)
async def get_taker_long_short_ratio(self, pair: Pair, interval: enums.Interval,
limit: int = None, start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"period": interval.value,
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("takerlongshortRatio", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FUTURES_DATA)
async def get_blvt_candlesticks(self, pair: Pair, interval: enums.Interval,
limit: int = None, start_tmstmp_ms: int = None, end_tmstmp_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"interval": interval.value,
"limit": limit,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms
})
return await self._create_get("lvtKlines", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_index_info(self, pair: Pair = None) -> dict:
params = {}
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("indexInfo", headers = self._get_header(), params = params, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_all_orders(self, pair: Pair, order_id: int = None, limit: int = None, start_tmstmp_ms: int = None,
end_tmstmp_ms: int = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"orderId": order_id,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"limit": limit,
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("allOrders", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_all_open_orders(self, pair: Pair = None, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("openOrders", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_balance(self, recv_window_ms: int = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("balance", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V2)
async def get_account(self, recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
return await self._create_get("account", headers = self._get_header(), params = params, signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V2)
async def get_position(self, pair: Pair = None, recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"recvWindow": recv_window_ms,
"timestamp": self._get_current_timestamp_ms()
})
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("positionRisk", headers = self._get_header(), params = params, signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V2)
async def get_account_trades(self, pair: Pair, limit: int = None, from_id: int = None,
start_tmstmp_ms: int = None, end_tmstmp_ms: int = None,
recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"symbol": map_pair(pair),
"limit": limit,
"fromId": from_id,
"startTime": start_tmstmp_ms,
"endTime": end_tmstmp_ms,
"timestamp": self._get_current_timestamp_ms(),
"recvWindow": recv_window_ms
})
return await self._create_get("userTrades", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_notional_and_leverage_brackets(self, pair: Pair = None, recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"timestamp": self._get_current_timestamp_ms(),
"recvWindow": recv_window_ms
})
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("leverageBracket", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
async def get_api_trading_status(self, pair: Pair = None, recv_window_ms: Optional[int] = None) -> dict:
params = CryptoXLibClient._clean_request_params({
"timestamp": self._get_current_timestamp_ms(),
"recvWindow": recv_window_ms
})
if pair is not None:
params['symbol'] = map_pair(pair)
return await self._create_get("apiTradingStatus", params = params, headers = self._get_header(), signed = True, api_variable_path = BinanceUSDSMFuturesClient.FAPI_V1)
class BinanceUSDSMFuturesTestnetClient(BinanceUSDSMFuturesClient):
REST_API_URI = "https://testnet.binancefuture.com/"
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_key = api_key, sec_key = sec_key, api_trace_log = api_trace_log, ssl_context = ssl_context)
def _get_rest_api_uri(self) -> str:
return BinanceUSDSMFuturesTestnetClient.REST_API_URI
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BinanceUSDSMFuturesTestnetWebsocket(subscriptions = subscriptions, binance_client = self,
api_key = self.api_key,
sec_key = self.sec_key, ssl_context = ssl_context)
class BinanceCOINMFuturesClient(BinanceFuturesClient):
REST_API_URI = "https://dapi.binance.com/"
DAPI_V1 = "dapi/v1/"
DAPI_V2 = "dapi/v2/"
FUTURES_DATA = "futures/data/"
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_key = api_key, sec_key = sec_key, api_trace_log = api_trace_log, ssl_context = ssl_context)
def _get_rest_api_uri(self) -> str:
return BinanceCOINMFuturesClient.REST_API_URI
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | true |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/__init__.py | cryptoxlib/clients/binance/__init__.py | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false | |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/types.py | cryptoxlib/clients/binance/types.py | from typing import Union
from cryptoxlib.Pair import Pair
PairSymbolType = Union[Pair, str]
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/functions.py | cryptoxlib/clients/binance/functions.py | from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.types import PairSymbolType
from cryptoxlib.clients.binance.exceptions import BinanceException
def map_pair(pair: Pair) -> str:
return f"{pair.base}{pair.quote}"
def map_ws_pair(pair: Pair) -> str:
return map_pair(pair).lower()
def extract_symbol(symbol: PairSymbolType) -> str:
if isinstance(symbol, str):
return symbol
elif isinstance(symbol, Pair):
return map_pair(symbol)
raise BinanceException(f"Symbol [{symbol}] is neither string not Pair.")
def extract_ws_symbol(symbol: PairSymbolType) -> str:
return extract_symbol(symbol).lower()
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/binance/BinanceFuturesWebsocket.py | cryptoxlib/clients/binance/BinanceFuturesWebsocket.py | import logging
from typing import List
from cryptoxlib.WebsocketMgr import Subscription, CallbacksType, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.clients.binance.functions import map_ws_pair, extract_ws_symbol
from cryptoxlib.clients.binance.BinanceCommonWebsocket import BinanceCommonWebsocket, BinanceSubscription
from cryptoxlib.clients.binance import enums
from cryptoxlib.clients.binance.types import PairSymbolType
LOG = logging.getLogger(__name__)
class BinanceFuturesWebsocket(BinanceCommonWebsocket):
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
websocket_uri: str = None, builtin_ping_interval: float = None, periodic_timeout_sec: int = None,
ssl_context = None) -> None:
super().__init__(subscriptions = subscriptions, binance_client = binance_client, api_key = api_key,
sec_key = sec_key,
websocket_uri = websocket_uri,
builtin_ping_interval = builtin_ping_interval,
periodic_timeout_sec = periodic_timeout_sec,
ssl_context = ssl_context)
def is_authenticated(self) -> bool:
for subscription in self.subscriptions:
if subscription.is_authenticated():
return True
return False
async def _process_periodic(self, websocket: Websocket) -> None:
if self.is_authenticated() is True:
LOG.info(f"[{self.id}] Refreshing listen key.")
await self.binance_client.keep_alive_listen_key()
class BinanceUSDSMFuturesWebsocket(BinanceFuturesWebsocket):
WEBSOCKET_URI = "wss://fstream.binance.com/"
BULTIN_PING_INTERVAL_SEC = 30
LISTEN_KEY_REFRESH_INTERVAL_SEC = 1800
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
ssl_context = None) -> None:
super().__init__(subscriptions = subscriptions, binance_client = binance_client, api_key = api_key,
sec_key = sec_key, websocket_uri = BinanceUSDSMFuturesWebsocket.WEBSOCKET_URI,
builtin_ping_interval = BinanceUSDSMFuturesWebsocket.BULTIN_PING_INTERVAL_SEC,
periodic_timeout_sec = BinanceUSDSMFuturesWebsocket.LISTEN_KEY_REFRESH_INTERVAL_SEC,
ssl_context = ssl_context)
class BinanceUSDSMFuturesTestnetWebsocket(BinanceFuturesWebsocket):
WEBSOCKET_URI = "wss://stream.binancefuture.com/"
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
ssl_context = None) -> None:
super().__init__(subscriptions = subscriptions, binance_client = binance_client, api_key = api_key,
sec_key = sec_key, websocket_uri = BinanceUSDSMFuturesTestnetWebsocket.WEBSOCKET_URI,
ssl_context = ssl_context)
class BinanceCOINMFuturesWebsocket(BinanceFuturesWebsocket):
WEBSOCKET_URI = "https://dstream.binance.com/"
BULTIN_PING_INTERVAL_SEC = 30
LISTEN_KEY_REFRESH_INTERVAL_SEC = 1800
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
ssl_context = None) -> None:
super().__init__(subscriptions = subscriptions, binance_client = binance_client, api_key = api_key,
sec_key = sec_key, websocket_uri = BinanceCOINMFuturesWebsocket.WEBSOCKET_URI,
builtin_ping_interval = BinanceCOINMFuturesWebsocket.BULTIN_PING_INTERVAL_SEC,
periodic_timeout_sec = BinanceCOINMFuturesWebsocket.LISTEN_KEY_REFRESH_INTERVAL_SEC,
ssl_context = ssl_context)
class BinanceCOINMFuturesTestnetWebsocket(BinanceFuturesWebsocket):
WEBSOCKET_URI = "wss://dstream.binancefuture.com/"
def __init__(self, subscriptions: List[Subscription], binance_client, api_key: str = None, sec_key: str = None,
ssl_context = None) -> None:
super().__init__(subscriptions = subscriptions, binance_client = binance_client, api_key = api_key,
sec_key = sec_key, websocket_uri = BinanceCOINMFuturesTestnetWebsocket.WEBSOCKET_URI,
ssl_context = ssl_context)
class AggregateTradeSubscription(BinanceSubscription):
def __init__(self, symbol: PairSymbolType, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.symbol = extract_ws_symbol(symbol)
def get_channel_name(self):
return f"{self.symbol}@aggTrade"
class IndexPriceSubscription(BinanceSubscription):
def __init__(self, pair: Pair, frequency1sec: bool = False, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
self.frequency1sec = frequency1sec
def get_channel_name(self):
return map_ws_pair(self.pair) + "@indexPrice" + ("@1s" if self.frequency1sec else "")
class MarkPriceSubscription(BinanceSubscription):
def __init__(self, symbol: PairSymbolType, frequency1sec: bool = False, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.symbol = extract_ws_symbol(symbol)
self.frequency1sec = frequency1sec
def get_channel_name(self):
return f"{self.symbol}@markPrice" + ("@1s" if self.frequency1sec else "")
class MarkPriceAllSubscription(BinanceSubscription):
def __init__(self, frequency1sec: bool = False, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.frequency1sec = frequency1sec
def get_channel_name(self):
return "!markPrice@arr" + ("@1s" if self.frequency1sec else "")
class CandlestickSubscription(BinanceSubscription):
def __init__(self, symbol: PairSymbolType, interval: enums.Interval, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.interval = interval
self.symbol = extract_ws_symbol(symbol)
def get_channel_name(self):
return f"{self.symbol}@kline_{self.interval.value}"
class ContContractCandlestickSubscription(BinanceSubscription):
def __init__(self, pair: Pair, interval: enums.Interval, contract_type: enums.ContractType, callbacks: CallbacksType = None):
super().__init__(callbacks)
if contract_type not in [enums.ContractType.PERPETUAL, enums.ContractType.CURRENT_QUARTER, enums.ContractType.NEXT_QUARTER]:
raise BinanceException(f"Level [{contract_type.value}] must be one of {enums.ContractType.PERPETUAL.value}, "
f"{enums.ContractType.CURRENT_QUARTER.value} or {enums.ContractType.NEXT_QUARTER.value}.")
self.pair = pair
self.interval = interval
self.contract_type = contract_type
def get_channel_name(self):
return f"{map_ws_pair(self.pair)}_{self.contract_type.value.lower()}@continuousKline_{self.interval.value}"
class IndexPriceCandlestickSubscription(BinanceSubscription):
def __init__(self, pair: Pair, interval: enums.Interval, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
self.interval = interval
def get_channel_name(self):
return f"{map_ws_pair(self.pair)}@indexPriceKline_{self.interval.value}"
class MarkPriceCandlestickSubscription(BinanceSubscription):
def __init__(self, symbol: str, interval: enums.Interval, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.symbol = symbol
self.interval = interval
def get_channel_name(self):
return f"{self.symbol}@markPriceKline_{self.interval.value}"
class AllMarketMiniTickersSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_channel_name(self):
return "!miniTicker@arr"
class MiniTickerSubscription(BinanceSubscription):
def __init__(self, symbol: PairSymbolType, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.symbol = extract_ws_symbol(symbol)
def get_channel_name(self):
return f"{self.symbol}@miniTicker"
class AllMarketTickersSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_channel_name(self):
return "!ticker@arr"
class TickerSubscription(BinanceSubscription):
def __init__(self, symbol: PairSymbolType, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.symbol = extract_ws_symbol(symbol)
def get_channel_name(self):
return f"{self.symbol}@ticker"
class OrderBookTickerSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_channel_name(self):
return "!bookTicker"
class OrderBookSymbolTickerSubscription(BinanceSubscription):
def __init__(self, symbol: PairSymbolType, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.symbol = extract_ws_symbol(symbol)
def get_channel_name(self):
return f"{self.symbol}@bookTicker"
class LiquidationOrdersSubscription(BinanceSubscription):
def __init__(self, symbol: PairSymbolType, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.symbol = extract_ws_symbol(symbol)
def get_channel_name(self):
return f"{self.symbol}@forceOrder"
class AllMarketLiquidationOrdersSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
def get_channel_name(self):
return "!forceOrder@arr"
class DepthSubscription(BinanceSubscription):
DEFAULT_FREQUENCY = 250
DEFAULT_LEVEL = 0
def __init__(self, symbol: PairSymbolType, level: int = DEFAULT_LEVEL, frequency: int = DEFAULT_FREQUENCY,
callbacks: CallbacksType = None):
super().__init__(callbacks)
if level not in [0, 5, 10, 20]:
raise BinanceException(f"Level [{level}] must be one of 0, 5, 10 or 20.")
if frequency not in [100, 250, 500]:
raise BinanceException(f"Frequency [{frequency}] must be one of 100, 250 or 500.")
self.symbol = extract_ws_symbol(symbol)
self.level = level
self.frequency = frequency
def get_channel_name(self):
if self.level == DepthSubscription.DEFAULT_LEVEL:
level_str = ""
else:
level_str = f"{self.level}"
if self.frequency == DepthSubscription.DEFAULT_FREQUENCY:
frequency_str = ""
else:
frequency_str = f"@{self.frequency}ms"
return f"{self.symbol}@depth{level_str}{frequency_str}"
class BlvtSubscription(BinanceSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"{map_ws_pair(self.pair).upper()}@tokenNav"
class BlvtCandlestickSubscription(BinanceSubscription):
def __init__(self, pair: Pair, interval: enums.Interval, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
self.interval = interval
def get_channel_name(self):
return f"{map_ws_pair(self.pair).upper()}@nav_Kline_{self.interval.value}"
class CompositeIndexSubscription(BinanceSubscription):
def __init__(self, pair: Pair, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"{map_ws_pair(self.pair)}@compositeIndex"
class AccountSubscription(BinanceSubscription):
def __init__(self, callbacks: CallbacksType = None):
super().__init__(callbacks)
self.listen_key = None
async def initialize(self, **kwargs):
binance_client = kwargs['binance_client']
listen_key_response = await binance_client.get_listen_key()
self.listen_key = listen_key_response["response"]["listenKey"]
LOG.debug(f'Listen key: {self.listen_key}')
def get_channel_name(self):
return self.listen_key
def is_authenticated(self) -> bool:
return True | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox_europe/enums.py | cryptoxlib/clients/bibox_europe/enums.py | import enum
class OrderType(enum.Enum):
LIMIT = 2
class OrderSide(enum.Enum):
BUY = 1
SELL = 2 | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox_europe/BiboxEuropeClient.py | cryptoxlib/clients/bibox_europe/BiboxEuropeClient.py | import ssl
import logging
import json
import hmac
import hashlib
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bibox_europe import enums
from cryptoxlib.clients.bibox_europe.exceptions import BiboxEuropeException
from cryptoxlib.clients.bibox_europe.functions import map_pair
from cryptoxlib.Pair import Pair
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
from cryptoxlib.clients.bibox_europe.BiboxEuropeWebsocket import BiboxEuropeWebsocket
LOG = logging.getLogger(__name__)
class BiboxEuropeClient(CryptoXLibClient):
REST_API_URI = "https://api.bibox.cc/v1/"
def __init__(self, api_key: str = None, sec_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_trace_log, ssl_context)
self.api_key = api_key
self.sec_key = sec_key
def _get_rest_api_uri(self) -> str:
return self.REST_API_URI
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
cmds = data['cmds']
signature = hmac.new(self.sec_key.encode('utf-8'), cmds.encode('utf-8'), hashlib.md5).hexdigest()
data['apikey'] = self.api_key
data['sign'] = signature
LOG.debug(f"Signed data: {data}")
@staticmethod
def _get_headers():
return {
'X-Ca-Nonce': str(CryptoXLibClient._get_current_timestamp_ms()),
'Content-Type': 'application/json'
}
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
if str(status_code)[0] != "2":
raise BiboxEuropeException(f"BiboxEuropeException: status [{status_code}], response [{body}]")
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BiboxEuropeWebsocket(subscriptions, self.api_key, self.sec_key, ssl_context)
async def get_ping(self) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "ping",
"body": {}
}])
}
return await self._create_post("api", data = data, headers = self._get_headers())
async def get_pairs(self) -> dict:
return await self._create_get("api?cmd=pairList", headers = self._get_headers())
async def get_exchange_info(self) -> dict:
return await self._create_get("orderpending?cmd=tradeLimit", headers = self._get_headers())
async def get_spot_assets(self, full: bool = False) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "transfer/assets",
"body": {
"select": 1 if full else 0
}
}])
}
return await self._create_post("transfer", data = data, headers = self._get_headers(), signed = True)
async def create_order(self, pair: Pair, price: str, quantity: str, order_type: enums.OrderType,
order_side: enums.OrderSide) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "orderpending/trade",
"index": self._get_current_timestamp_ms(),
"body": {
"pair": map_pair(pair),
"account_type": 0, # spot account
"order_type": order_type.value,
"order_side": order_side.value,
"price": price,
"amount": quantity
}
}])
}
return await self._create_post("orderpending", data = data, headers = self._get_headers(), signed = True)
async def cancel_order(self, order_id: str) -> dict:
data = {
"cmds": json.dumps([{
"cmd": "orderpending/cancelTrade",
"index": self._get_current_timestamp_ms(),
"body": {
"orders_id": order_id
}
}])
}
return await self._create_post("orderpending", data = data, headers = self._get_headers(), signed = True)
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox_europe/BiboxEuropeWebsocket.py | cryptoxlib/clients/bibox_europe/BiboxEuropeWebsocket.py | import json
import jwt
import time
import logging
import hmac
import zlib
import hashlib
import base64
import websockets
from abc import abstractmethod
from typing import List, Callable, Any, Optional
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bibox.functions import map_pair
from cryptoxlib.clients.bibox import enums
from cryptoxlib.clients.bibox.exceptions import BiboxException
LOG = logging.getLogger(__name__)
class BiboxEuropeWebsocket(WebsocketMgr):
WEBSOCKET_URI = "wss://push.bibox.cc/"
def __init__(self, subscriptions: List[Subscription], api_key: str = None, sec_key: str = None, ssl_context = None) -> None:
super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions,
builtin_ping_interval = None, ssl_context = ssl_context,
auto_reconnect = True)
self.api_key = api_key
self.sec_key = sec_key
async def send_subscription_message(self, subscriptions: List[Subscription]):
for subscription in subscriptions:
subscription_message = json.dumps(subscription.get_subscription_message(api_key = self.api_key, sec_key = self.sec_key))
LOG.debug(f"> {subscription_message}")
await self.websocket.send(subscription_message)
async def _process_message(self, websocket: Websocket, message: str) -> None:
messages = json.loads(message)
if "ping" in messages:
pong_message = {
"pong": messages['ping']
}
LOG.debug(f"> {pong_message}")
await websocket.send(json.dumps(pong_message))
elif 'error' in messages:
raise BiboxException(f"BiboxException: Bibox error received: {message}")
else:
for message in messages:
if 'data' in message:
data = message['data']
if 'binary' in message and message['binary'] == '1':
data = zlib.decompress(base64.b64decode(data), zlib.MAX_WBITS | 32)
message['data'] = json.loads(data.decode("utf-8"))
await self.publish_message(WebsocketMessage(subscription_id = message['channel'], message = message))
else:
LOG.warning(f"No data element received: {message}")
class BiboxEuropeSubscription(Subscription):
def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
@abstractmethod
def get_channel_name(self) -> str:
pass
def construct_subscription_id(self) -> Any:
return self.get_channel_name()
def get_subscription_message(self, **kwargs) -> dict:
return {
"binary": 0,
"channel": self.get_channel_name(),
"event": "addChannel",
}
class OrderBookSubscription(BiboxEuropeSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"bibox_sub_spot_{map_pair(self.pair)}_depth"
class TickerSubscription(BiboxEuropeSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"bibox_sub_spot_{map_pair(self.pair)}_ticker"
class MarketSubscription(BiboxEuropeSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return "bibox_sub_spot_ALL_ALL_market"
class TradeSubscription(BiboxEuropeSubscription):
def __init__(self, pair: Pair, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
self.pair = pair
def get_channel_name(self):
return f"bibox_sub_spot_{map_pair(self.pair)}_deals"
class UserDataSubscription(BiboxEuropeSubscription):
def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
def get_channel_name(self):
return "bibox_sub_spot_ALL_ALL_login"
def get_subscription_message(self, **kwargs) -> dict:
subscription = {
"apikey": kwargs['api_key'],
'binary': 0,
"channel": self.get_channel_name(),
"event": "addChannel",
}
signature = hmac.new(kwargs['sec_key'].encode('utf-8'),
json.dumps(subscription, sort_keys=True).replace("\'", "\"").replace(" ", "").encode('utf-8'),
hashlib.md5).hexdigest()
subscription['sign'] = signature
return subscription | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox_europe/exceptions.py | cryptoxlib/clients/bibox_europe/exceptions.py | from cryptoxlib.exceptions import CryptoXLibException
class BiboxEuropeException(CryptoXLibException):
pass | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox_europe/__init__.py | cryptoxlib/clients/bibox_europe/__init__.py | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false | |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bibox_europe/functions.py | cryptoxlib/clients/bibox_europe/functions.py | from cryptoxlib.Pair import Pair
def map_pair(pair: Pair) -> str:
return f"{pair.base}_{pair.quote}"
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitvavo/enums.py | cryptoxlib/clients/bitvavo/enums.py | import enum
class OrderType(enum.Enum):
MARKET = "market"
LIMIT = "limit"
class OrderSide(enum.Enum):
BUY = "buy"
SELL = "sell"
class TimeInForce(enum.Enum):
GOOD_TILL_CANCELLED = "GTC"
IMMEDIATE_OR_CANCELLED = "IOC"
FILL_OR_KILL = "FOK"
class SelfTradePrevention(enum.Enum):
DECREMENT_AND_CANCEL = "decrementAndCancel"
CANCEL_OLDEST = "cancelOldest"
CANCEL_NEWEST = "cancelNewest"
CANCEL_BOTH = "cancelBoth"
class CandlestickInterval(enum.Enum):
I_1MIN = '1m'
I_5MIN = '5m'
I_15MIN = '15m'
I_30MIN = '30m'
I_1H = '1h'
I_2H = '2h'
I_4H = '4h'
I_6H = '6h'
I_8H = '8h'
I_12H = '12h'
I_1D = '1d'
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitvavo/BitvavoWebsocket.py | cryptoxlib/clients/bitvavo/BitvavoWebsocket.py | import json
import logging
import websockets
import hmac
import hashlib
import datetime
from typing import List, Callable, Any, Optional
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.bitvavo.functions import map_pair
from cryptoxlib.clients.bitvavo import enums
from cryptoxlib.clients.bitvavo.exceptions import BitvavoException
LOG = logging.getLogger(__name__)
class BitvavoWebsocket(WebsocketMgr):
WEBSOCKET_URI = "wss://ws.bitvavo.com/v2/"
def __init__(self, subscriptions: List[Subscription], api_key: str = None, sec_key: str = None,
ssl_context = None) -> None:
super().__init__(websocket_uri = self.WEBSOCKET_URI, subscriptions = subscriptions,
ssl_context = ssl_context,
auto_reconnect = True)
self.api_key = api_key
self.sec_key = sec_key
async def send_authentication_message(self):
requires_authentication = False
for subscription in self.subscriptions:
if subscription.requires_authentication():
requires_authentication = True
break
if requires_authentication:
timestamp = int(datetime.datetime.now(tz = datetime.timezone.utc).timestamp() * 1000)
signature_string = str(timestamp) + 'GET/v2/websocket'
signature = hmac.new(self.sec_key.encode('utf-8'), signature_string.encode('utf-8'),
hashlib.sha256).hexdigest()
authentication_message = {
"action": "authenticate",
"key": self.api_key,
"signature": signature,
"timestamp": timestamp
}
LOG.debug(f"> {authentication_message}")
await self.websocket.send(json.dumps(authentication_message))
message = await self.websocket.receive()
LOG.debug(f"< {message}")
message = json.loads(message)
if 'event' in message and message['event'] == 'authenticate' and \
'authenticated' in message and message['authenticated'] is True:
LOG.info(f"Websocket authenticated successfully.")
else:
raise BitvavoException(f"Authentication error. Response [{json.dumps(message)}]")
async def send_subscription_message(self, subscriptions: List[Subscription]):
subscription_message = {
"action": "subscribe",
"channels": [
subscription.get_subscription_message() for subscription in subscriptions
]
}
LOG.debug(f"> {subscription_message}")
await self.websocket.send(json.dumps(subscription_message))
async def _process_message(self, websocket: websockets.WebSocketClientProtocol, message: str) -> None:
message = json.loads(message)
# subscription negative response
if 'action' in message and message['action'] == 'subscribe' and "error" in message:
raise BitvavoException(f"Subscription error. Response [{json.dumps(message)}]")
# subscription positive response
if 'event' in message and message['event'] == 'subscribed':
if len(message['subscriptions']) > 0:
LOG.info(f"Subscription confirmed for channels [{message['subscriptions']}]")
else:
raise BitvavoException(f"Subscription error. No subscription confirmed. Response [{json.dumps(message)}]")
# regular message
else:
await self.publish_message(WebsocketMessage(subscription_id = self._map_event_id_to_subscription_id(message['event']),
message = message))
@staticmethod
def _map_event_id_to_subscription_id(event_typ: str):
if event_typ in ['order', 'fill']:
return AccountSubscription.get_channel_name()
elif event_typ == 'trade':
return TradesSubscription.get_channel_name()
elif event_typ == 'candle':
return CandlesticksSubscription.get_channel_name()
else:
return event_typ
class BitvavoSubscription(Subscription):
def __init__(self, callbacks: Optional[List[Callable[[dict], Any]]] = None):
super().__init__(callbacks)
@staticmethod
def get_channel_name():
pass
def construct_subscription_id(self) -> Any:
return self.get_channel_name()
def requires_authentication(self) -> bool:
return False
class AccountSubscription(BitvavoSubscription):
def __init__(self, pairs: List[Pair], callbacks : List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pairs = pairs
def requires_authentication(self) -> bool:
return True
@staticmethod
def get_channel_name():
return "account"
def get_subscription_message(self, **kwargs) -> dict:
return {
"name": self.get_channel_name(),
"markets": [
map_pair(pair) for pair in self.pairs
]
}
class TickerSubscription(BitvavoSubscription):
def __init__(self, pairs : List[Pair], callbacks : List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pairs = pairs
@staticmethod
def get_channel_name():
return "ticker"
def get_subscription_message(self, **kwargs) -> dict:
return {
"name": self.get_channel_name(),
"markets": [
map_pair(pair) for pair in self.pairs
]
}
class Ticker24Subscription(BitvavoSubscription):
def __init__(self, pairs : List[Pair], callbacks : List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pairs = pairs
@staticmethod
def get_channel_name():
return "ticker24h"
def get_subscription_message(self, **kwargs) -> dict:
return {
"name": self.get_channel_name(),
"markets": [
map_pair(pair) for pair in self.pairs
]
}
class TradesSubscription(BitvavoSubscription):
def __init__(self, pairs : List[Pair], callbacks : List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pairs = pairs
@staticmethod
def get_channel_name():
return "trades"
def get_subscription_message(self, **kwargs) -> dict:
return {
"name": self.get_channel_name(),
"markets": [
map_pair(pair) for pair in self.pairs
]
}
class OrderbookSubscription(BitvavoSubscription):
def __init__(self, pairs : List[Pair], callbacks : List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pairs = pairs
@staticmethod
def get_channel_name():
return "book"
def get_subscription_message(self, **kwargs) -> dict:
return {
"name": self.get_channel_name(),
"markets": [
map_pair(pair) for pair in self.pairs
]
}
class CandlesticksSubscription(BitvavoSubscription):
def __init__(self, pairs : List[Pair], intervals: List[enums.CandlestickInterval], callbacks : List[Callable[[dict], Any]] = None):
super().__init__(callbacks)
self.pairs = pairs
self.intervals = intervals
@staticmethod
def get_channel_name():
return "candles"
def get_subscription_message(self, **kwargs) -> dict:
return {
"name": self.get_channel_name(),
"markets": [
map_pair(pair) for pair in self.pairs
],
"interval": [
interval.value for interval in self.intervals
]
}
| python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
nardew/cryptoxlib-aio | https://github.com/nardew/cryptoxlib-aio/blob/3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8/cryptoxlib/clients/bitvavo/exceptions.py | cryptoxlib/clients/bitvavo/exceptions.py | from cryptoxlib.exceptions import CryptoXLibException
class BitvavoException(CryptoXLibException):
pass | python | MIT | 3fb114e2e4d5ad87aaf7fdbc24dd9a9d2bdc6ee8 | 2026-01-05T07:14:19.536370Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.