diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 1a1c2570..587be153 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -43,7 +43,7 @@ jobs: flake8 . --statistics - name: Test with pytest run: | - pytest + pytest tests/ - name: Test document build run: | python -m pip install sphinx sphinx-rtd-theme diff --git a/CHANGELOG.md b/CHANGELOG.md index bc7dee47..efbc8312 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog + +## 3.0.0rc1 - 2023-02-10 + +### Changed +- Redesign of Websocket part. Please consult `README.md` for details on its new usage. + +### Added +- Add Websocket API + ## 2.0.0 - 2023-01-18 ### Added - New endpoints for wallet diff --git a/README.md b/README.md index fc4ae091..11376156 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ This is a lightweight library that works as a connector to [Binance public API]( - `/sapi/*` - Spot Websocket Market Stream - Spot User Data Stream + - Spot WebSocket API - Inclusion of test cases and examples - Customizable base URL, request timeout and HTTP proxy - Response metadata can be displayed @@ -219,6 +220,65 @@ There are 2 types of error returned from the library: ## Websocket +### Connector v3 + +WebSocket can be established through either of the following types of connections: +- WebSocket API (`https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md`) +- WebSocket Stream (`https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md`) + +```python + +# WebSocket API Client +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +def message_handler(_, message): + logging.info(message) + +my_client = SpotWebsocketAPIClient(on_message=message_handler) + +my_client.ticker(symbol="BNBBUSD", type="FULL") + +time.sleep(5) +logging.info("closing ws connection") +my_client.stop() +``` + +```python + +# WebSocket Stream Client +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +def message_handler(_, message): + logging.info(message) + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + +# Subscribe to a single symbol stream +my_client.agg_trade(symbol="bnbusdt") +time.sleep(5) +logging.info("closing ws connection") +my_client.stop() +``` + +#### Request Id + +Client can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided. + +```python +# id provided by client +my_client.ping_connectivity(id="my_request_id") + +# library will generate a random uuid string +my_client.ping_connectivity() +``` + +More websocket examples are available in the `examples` folder. + +Example file "examples/websocket_api/app_demo.py" demonstrates how Websocket API and Websocket Stream can be used together. + + +### Connector v1 and v2 + ```python from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient @@ -242,7 +302,6 @@ ws_client.instant_subscribe( ws_client.stop() ``` -More websocket examples are available in the `examples` folder ### Heartbeat diff --git a/binance/__version__.py b/binance/__version__.py index 8c0d5d5b..451cd1fa 100644 --- a/binance/__version__.py +++ b/binance/__version__.py @@ -1 +1 @@ -__version__ = "2.0.0" +__version__ = "3.0.0rc1" diff --git a/binance/error.py b/binance/error.py index 4d83edca..8dd33f4c 100644 --- a/binance/error.py +++ b/binance/error.py @@ -52,3 +52,11 @@ def __init__(self, error_message): def __str__(self): return self.error_message + + +class WebsocketClientError(Error): + def __init__(self, error_message): + self.error_message = error_message + + def __str__(self): + return self.error_message diff --git a/binance/lib/utils.py b/binance/lib/utils.py index 98fd1a5a..8ea02943 100644 --- a/binance/lib/utils.py +++ b/binance/lib/utils.py @@ -1,11 +1,14 @@ import json import time - +import uuid +from collections import OrderedDict from urllib.parse import urlencode +from binance.lib.authentication import hmac_hashing from binance.error import ( ParameterRequiredError, ParameterValueError, ParameterTypeError, + WebsocketClientError, ) @@ -78,3 +81,34 @@ def config_logging(logging, logging_level, log_file: str = None): format="%(asctime)s.%(msecs)03d UTC %(levelname)s %(name)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) + + +def get_uuid(): + return str(uuid.uuid4()) + + +def purge_map(map: map): + """Remove None values from map""" + return {k: v for k, v in map.items() if v is not None and v != "" and v != 0} + + +def websocket_api_signature(api_key: str, api_secret: str, parameters: dict): + """Generate signature for websocket API + Args: + api_key (str): API key. + api_secret (str): API secret. + params (dict): Parameters. + """ + + if not api_key or not api_secret: + raise WebsocketClientError( + "api_key and api_secret are required for websocket API signature" + ) + + parameters["timestamp"] = get_timestamp() + parameters["apiKey"] = api_key + + parameters = OrderedDict(sorted(parameters.items())) + parameters["signature"] = hmac_hashing(api_secret, urlencode(parameters)) + + return parameters diff --git a/binance/spot/__init__.py b/binance/spot/__init__.py index e6e123a7..d50ffe1b 100644 --- a/binance/spot/__init__.py +++ b/binance/spot/__init__.py @@ -8,287 +8,287 @@ def __init__(self, api_key=None, api_secret=None, **kwargs): super().__init__(api_key, api_secret, **kwargs) # MARKETS - from binance.spot.market import ping - from binance.spot.market import time - from binance.spot.market import exchange_info - from binance.spot.market import depth - from binance.spot.market import trades - from binance.spot.market import historical_trades - from binance.spot.market import agg_trades - from binance.spot.market import klines - from binance.spot.market import ui_klines - from binance.spot.market import avg_price - from binance.spot.market import ticker_24hr - from binance.spot.market import ticker_price - from binance.spot.market import book_ticker - from binance.spot.market import rolling_window_ticker + from binance.spot._market import ping + from binance.spot._market import time + from binance.spot._market import exchange_info + from binance.spot._market import depth + from binance.spot._market import trades + from binance.spot._market import historical_trades + from binance.spot._market import agg_trades + from binance.spot._market import klines + from binance.spot._market import ui_klines + from binance.spot._market import avg_price + from binance.spot._market import ticker_24hr + from binance.spot._market import ticker_price + from binance.spot._market import book_ticker + from binance.spot._market import rolling_window_ticker # ACCOUNT (including orders and trades) - from binance.spot.trade import new_order_test - from binance.spot.trade import new_order - from binance.spot.trade import cancel_order - from binance.spot.trade import cancel_open_orders - from binance.spot.trade import get_order - from binance.spot.trade import cancel_and_replace - from binance.spot.trade import get_open_orders - from binance.spot.trade import get_orders - from binance.spot.trade import new_oco_order - from binance.spot.trade import cancel_oco_order - from binance.spot.trade import get_oco_order - from binance.spot.trade import get_oco_orders - from binance.spot.trade import get_oco_open_orders - from binance.spot.trade import account - from binance.spot.trade import my_trades - from binance.spot.trade import get_order_rate_limit + from binance.spot._trade import new_order_test + from binance.spot._trade import new_order + from binance.spot._trade import cancel_order + from binance.spot._trade import cancel_open_orders + from binance.spot._trade import get_order + from binance.spot._trade import cancel_and_replace + from binance.spot._trade import get_open_orders + from binance.spot._trade import get_orders + from binance.spot._trade import new_oco_order + from binance.spot._trade import cancel_oco_order + from binance.spot._trade import get_oco_order + from binance.spot._trade import get_oco_orders + from binance.spot._trade import get_oco_open_orders + from binance.spot._trade import account + from binance.spot._trade import my_trades + from binance.spot._trade import get_order_rate_limit # STREAMS - from binance.spot.data_stream import new_listen_key - from binance.spot.data_stream import renew_listen_key - from binance.spot.data_stream import close_listen_key - from binance.spot.data_stream import new_margin_listen_key - from binance.spot.data_stream import renew_margin_listen_key - from binance.spot.data_stream import close_margin_listen_key - from binance.spot.data_stream import new_isolated_margin_listen_key - from binance.spot.data_stream import renew_isolated_margin_listen_key - from binance.spot.data_stream import close_isolated_margin_listen_key + from binance.spot._data_stream import new_listen_key + from binance.spot._data_stream import renew_listen_key + from binance.spot._data_stream import close_listen_key + from binance.spot._data_stream import new_margin_listen_key + from binance.spot._data_stream import renew_margin_listen_key + from binance.spot._data_stream import close_margin_listen_key + from binance.spot._data_stream import new_isolated_margin_listen_key + from binance.spot._data_stream import renew_isolated_margin_listen_key + from binance.spot._data_stream import close_isolated_margin_listen_key # MARGIN - from binance.spot.margin import margin_transfer - from binance.spot.margin import margin_borrow - from binance.spot.margin import margin_repay - from binance.spot.margin import margin_asset - from binance.spot.margin import margin_pair - from binance.spot.margin import margin_all_assets - from binance.spot.margin import margin_all_pairs - from binance.spot.margin import margin_pair_index - from binance.spot.margin import new_margin_order - from binance.spot.margin import cancel_margin_order - from binance.spot.margin import margin_transfer_history - from binance.spot.margin import margin_load_record - from binance.spot.margin import margin_repay_record - from binance.spot.margin import margin_interest_history - from binance.spot.margin import margin_force_liquidation_record - from binance.spot.margin import margin_account - from binance.spot.margin import margin_order - from binance.spot.margin import margin_open_orders - from binance.spot.margin import margin_open_orders_cancellation - from binance.spot.margin import margin_all_orders - from binance.spot.margin import margin_my_trades - from binance.spot.margin import margin_max_borrowable - from binance.spot.margin import margin_max_transferable - from binance.spot.margin import isolated_margin_transfer - from binance.spot.margin import isolated_margin_transfer_history - from binance.spot.margin import isolated_margin_account - from binance.spot.margin import isolated_margin_pair - from binance.spot.margin import isolated_margin_all_pairs - from binance.spot.margin import toggle_bnbBurn - from binance.spot.margin import bnbBurn_status - from binance.spot.margin import margin_interest_rate_history - from binance.spot.margin import new_margin_oco_order - from binance.spot.margin import cancel_margin_oco_order - from binance.spot.margin import get_margin_oco_order - from binance.spot.margin import get_margin_oco_orders - from binance.spot.margin import get_margin_open_oco_orders - from binance.spot.margin import cancel_isolated_margin_account - from binance.spot.margin import enable_isolated_margin_account - from binance.spot.margin import isolated_margin_account_limit - from binance.spot.margin import margin_fee - from binance.spot.margin import isolated_margin_fee - from binance.spot.margin import isolated_margin_tier - from binance.spot.margin import margin_order_usage - from binance.spot.margin import margin_dust_log - from binance.spot.margin import summary_of_margin_account + from binance.spot._margin import margin_transfer + from binance.spot._margin import margin_borrow + from binance.spot._margin import margin_repay + from binance.spot._margin import margin_asset + from binance.spot._margin import margin_pair + from binance.spot._margin import margin_all_assets + from binance.spot._margin import margin_all_pairs + from binance.spot._margin import margin_pair_index + from binance.spot._margin import new_margin_order + from binance.spot._margin import cancel_margin_order + from binance.spot._margin import margin_transfer_history + from binance.spot._margin import margin_load_record + from binance.spot._margin import margin_repay_record + from binance.spot._margin import margin_interest_history + from binance.spot._margin import margin_force_liquidation_record + from binance.spot._margin import margin_account + from binance.spot._margin import margin_order + from binance.spot._margin import margin_open_orders + from binance.spot._margin import margin_open_orders_cancellation + from binance.spot._margin import margin_all_orders + from binance.spot._margin import margin_my_trades + from binance.spot._margin import margin_max_borrowable + from binance.spot._margin import margin_max_transferable + from binance.spot._margin import isolated_margin_transfer + from binance.spot._margin import isolated_margin_transfer_history + from binance.spot._margin import isolated_margin_account + from binance.spot._margin import isolated_margin_pair + from binance.spot._margin import isolated_margin_all_pairs + from binance.spot._margin import toggle_bnbBurn + from binance.spot._margin import bnbBurn_status + from binance.spot._margin import margin_interest_rate_history + from binance.spot._margin import new_margin_oco_order + from binance.spot._margin import cancel_margin_oco_order + from binance.spot._margin import get_margin_oco_order + from binance.spot._margin import get_margin_oco_orders + from binance.spot._margin import get_margin_open_oco_orders + from binance.spot._margin import cancel_isolated_margin_account + from binance.spot._margin import enable_isolated_margin_account + from binance.spot._margin import isolated_margin_account_limit + from binance.spot._margin import margin_fee + from binance.spot._margin import isolated_margin_fee + from binance.spot._margin import isolated_margin_tier + from binance.spot._margin import margin_order_usage + from binance.spot._margin import margin_dust_log + from binance.spot._margin import summary_of_margin_account # SAVINGS - from binance.spot.savings import savings_flexible_products - from binance.spot.savings import savings_flexible_user_left_quota - from binance.spot.savings import savings_purchase_flexible_product - from binance.spot.savings import savings_flexible_user_redemption_quota - from binance.spot.savings import savings_flexible_redeem - from binance.spot.savings import savings_flexible_product_position - from binance.spot.savings import savings_project_list - from binance.spot.savings import savings_purchase_project - from binance.spot.savings import savings_project_position - from binance.spot.savings import savings_account - from binance.spot.savings import savings_purchase_record - from binance.spot.savings import savings_redemption_record - from binance.spot.savings import savings_interest_history - from binance.spot.savings import savings_change_position + from binance.spot._savings import savings_flexible_products + from binance.spot._savings import savings_flexible_user_left_quota + from binance.spot._savings import savings_purchase_flexible_product + from binance.spot._savings import savings_flexible_user_redemption_quota + from binance.spot._savings import savings_flexible_redeem + from binance.spot._savings import savings_flexible_product_position + from binance.spot._savings import savings_project_list + from binance.spot._savings import savings_purchase_project + from binance.spot._savings import savings_project_position + from binance.spot._savings import savings_account + from binance.spot._savings import savings_purchase_record + from binance.spot._savings import savings_redemption_record + from binance.spot._savings import savings_interest_history + from binance.spot._savings import savings_change_position # Staking - from binance.spot.staking import staking_product_list - from binance.spot.staking import staking_purchase_product - from binance.spot.staking import staking_redeem_product - from binance.spot.staking import staking_product_position - from binance.spot.staking import staking_history - from binance.spot.staking import staking_set_auto_staking - from binance.spot.staking import staking_product_quota + from binance.spot._staking import staking_product_list + from binance.spot._staking import staking_purchase_product + from binance.spot._staking import staking_redeem_product + from binance.spot._staking import staking_product_position + from binance.spot._staking import staking_history + from binance.spot._staking import staking_set_auto_staking + from binance.spot._staking import staking_product_quota # WALLET - from binance.spot.wallet import system_status - from binance.spot.wallet import coin_info - from binance.spot.wallet import account_snapshot - from binance.spot.wallet import disable_fast_withdraw - from binance.spot.wallet import enable_fast_withdraw - from binance.spot.wallet import withdraw - from binance.spot.wallet import deposit_history - from binance.spot.wallet import withdraw_history - from binance.spot.wallet import deposit_address - from binance.spot.wallet import account_status - from binance.spot.wallet import api_trading_status - from binance.spot.wallet import dust_log - from binance.spot.wallet import user_universal_transfer - from binance.spot.wallet import user_universal_transfer_history - from binance.spot.wallet import transfer_dust - from binance.spot.wallet import asset_dividend_record - from binance.spot.wallet import asset_detail - from binance.spot.wallet import trade_fee - from binance.spot.wallet import funding_wallet - from binance.spot.wallet import user_asset - from binance.spot.wallet import api_key_permissions - from binance.spot.wallet import bnb_convertible_assets - from binance.spot.wallet import convertible_coins - from binance.spot.wallet import toggle_auto_convertion - from binance.spot.wallet import cloud_mining_trans_history - from binance.spot.wallet import convert_transfer - from binance.spot.wallet import convert_history + from binance.spot._wallet import system_status + from binance.spot._wallet import coin_info + from binance.spot._wallet import account_snapshot + from binance.spot._wallet import disable_fast_withdraw + from binance.spot._wallet import enable_fast_withdraw + from binance.spot._wallet import withdraw + from binance.spot._wallet import deposit_history + from binance.spot._wallet import withdraw_history + from binance.spot._wallet import deposit_address + from binance.spot._wallet import account_status + from binance.spot._wallet import api_trading_status + from binance.spot._wallet import dust_log + from binance.spot._wallet import user_universal_transfer + from binance.spot._wallet import user_universal_transfer_history + from binance.spot._wallet import transfer_dust + from binance.spot._wallet import asset_dividend_record + from binance.spot._wallet import asset_detail + from binance.spot._wallet import trade_fee + from binance.spot._wallet import funding_wallet + from binance.spot._wallet import user_asset + from binance.spot._wallet import api_key_permissions + from binance.spot._wallet import bnb_convertible_assets + from binance.spot._wallet import convertible_coins + from binance.spot._wallet import toggle_auto_convertion + from binance.spot._wallet import cloud_mining_trans_history + from binance.spot._wallet import convert_transfer + from binance.spot._wallet import convert_history # MINING - from binance.spot.mining import mining_algo_list - from binance.spot.mining import mining_coin_list - from binance.spot.mining import mining_worker - from binance.spot.mining import mining_worker_list - from binance.spot.mining import mining_earnings_list - from binance.spot.mining import mining_bonus_list - from binance.spot.mining import mining_statistics_list - from binance.spot.mining import mining_account_list - from binance.spot.mining import mining_hashrate_resale_request - from binance.spot.mining import mining_hashrate_resale_cancellation - from binance.spot.mining import mining_hashrate_resale_list - from binance.spot.mining import mining_hashrate_resale_details - from binance.spot.mining import mining_account_earning + from binance.spot._mining import mining_algo_list + from binance.spot._mining import mining_coin_list + from binance.spot._mining import mining_worker + from binance.spot._mining import mining_worker_list + from binance.spot._mining import mining_earnings_list + from binance.spot._mining import mining_bonus_list + from binance.spot._mining import mining_statistics_list + from binance.spot._mining import mining_account_list + from binance.spot._mining import mining_hashrate_resale_request + from binance.spot._mining import mining_hashrate_resale_cancellation + from binance.spot._mining import mining_hashrate_resale_list + from binance.spot._mining import mining_hashrate_resale_details + from binance.spot._mining import mining_account_earning # SUB-ACCOUNT - from binance.spot.sub_account import sub_account_create - from binance.spot.sub_account import sub_account_list - from binance.spot.sub_account import sub_account_assets - from binance.spot.sub_account import sub_account_deposit_address - from binance.spot.sub_account import sub_account_deposit_history - from binance.spot.sub_account import sub_account_status - from binance.spot.sub_account import sub_account_enable_margin - from binance.spot.sub_account import sub_account_margin_account - from binance.spot.sub_account import sub_account_margin_account_summary - from binance.spot.sub_account import sub_account_enable_futures - from binance.spot.sub_account import sub_account_futures_transfer - from binance.spot.sub_account import sub_account_margin_transfer - from binance.spot.sub_account import sub_account_transfer_to_sub - from binance.spot.sub_account import sub_account_transfer_to_master - from binance.spot.sub_account import sub_account_transfer_sub_account_history - from binance.spot.sub_account import sub_account_futures_asset_transfer_history - from binance.spot.sub_account import sub_account_futures_asset_transfer - from binance.spot.sub_account import sub_account_spot_summary - from binance.spot.sub_account import sub_account_universal_transfer - from binance.spot.sub_account import sub_account_universal_transfer_history - from binance.spot.sub_account import sub_account_futures_account - from binance.spot.sub_account import sub_account_futures_account_summary - from binance.spot.sub_account import sub_account_futures_position_risk - from binance.spot.sub_account import sub_account_spot_transfer_history - from binance.spot.sub_account import sub_account_enable_leverage_token - from binance.spot.sub_account import managed_sub_account_deposit - from binance.spot.sub_account import managed_sub_account_assets - from binance.spot.sub_account import managed_sub_account_withdraw - from binance.spot.sub_account import sub_account_api_toggle_ip_restriction - from binance.spot.sub_account import sub_account_api_add_ip - from binance.spot.sub_account import sub_account_api_get_ip_restriction - from binance.spot.sub_account import sub_account_api_delete_ip - from binance.spot.sub_account import managed_sub_account_get_snapshot - from binance.spot.sub_account import managed_sub_account_investor_trans_log - from binance.spot.sub_account import managed_sub_account_trading_trans_log + from binance.spot._sub_account import sub_account_create + from binance.spot._sub_account import sub_account_list + from binance.spot._sub_account import sub_account_assets + from binance.spot._sub_account import sub_account_deposit_address + from binance.spot._sub_account import sub_account_deposit_history + from binance.spot._sub_account import sub_account_status + from binance.spot._sub_account import sub_account_enable_margin + from binance.spot._sub_account import sub_account_margin_account + from binance.spot._sub_account import sub_account_margin_account_summary + from binance.spot._sub_account import sub_account_enable_futures + from binance.spot._sub_account import sub_account_futures_transfer + from binance.spot._sub_account import sub_account_margin_transfer + from binance.spot._sub_account import sub_account_transfer_to_sub + from binance.spot._sub_account import sub_account_transfer_to_master + from binance.spot._sub_account import sub_account_transfer_sub_account_history + from binance.spot._sub_account import sub_account_futures_asset_transfer_history + from binance.spot._sub_account import sub_account_futures_asset_transfer + from binance.spot._sub_account import sub_account_spot_summary + from binance.spot._sub_account import sub_account_universal_transfer + from binance.spot._sub_account import sub_account_universal_transfer_history + from binance.spot._sub_account import sub_account_futures_account + from binance.spot._sub_account import sub_account_futures_account_summary + from binance.spot._sub_account import sub_account_futures_position_risk + from binance.spot._sub_account import sub_account_spot_transfer_history + from binance.spot._sub_account import sub_account_enable_leverage_token + from binance.spot._sub_account import managed_sub_account_deposit + from binance.spot._sub_account import managed_sub_account_assets + from binance.spot._sub_account import managed_sub_account_withdraw + from binance.spot._sub_account import sub_account_api_toggle_ip_restriction + from binance.spot._sub_account import sub_account_api_add_ip + from binance.spot._sub_account import sub_account_api_get_ip_restriction + from binance.spot._sub_account import sub_account_api_delete_ip + from binance.spot._sub_account import managed_sub_account_get_snapshot + from binance.spot._sub_account import managed_sub_account_investor_trans_log + from binance.spot._sub_account import managed_sub_account_trading_trans_log # FUTURES - from binance.spot.futures import futures_transfer - from binance.spot.futures import futures_transfer_history - from binance.spot.futures import futures_loan_borrow_history - from binance.spot.futures import futures_loan_repay_history - from binance.spot.futures import futures_loan_wallet - from binance.spot.futures import futures_loan_adjust_collateral_history - from binance.spot.futures import futures_loan_liquidation_history - from binance.spot.futures import futures_loan_interest_history + from binance.spot._futures import futures_transfer + from binance.spot._futures import futures_transfer_history + from binance.spot._futures import futures_loan_borrow_history + from binance.spot._futures import futures_loan_repay_history + from binance.spot._futures import futures_loan_wallet + from binance.spot._futures import futures_loan_adjust_collateral_history + from binance.spot._futures import futures_loan_liquidation_history + from binance.spot._futures import futures_loan_interest_history # BLVTs - from binance.spot.blvt import blvt_info - from binance.spot.blvt import subscribe_blvt - from binance.spot.blvt import subscription_record - from binance.spot.blvt import redeem_blvt - from binance.spot.blvt import redemption_record - from binance.spot.blvt import user_limit_info + from binance.spot._blvt import blvt_info + from binance.spot._blvt import subscribe_blvt + from binance.spot._blvt import subscription_record + from binance.spot._blvt import redeem_blvt + from binance.spot._blvt import redemption_record + from binance.spot._blvt import user_limit_info # BSwap - from binance.spot.bswap import bswap_pools - from binance.spot.bswap import bswap_liquidity - from binance.spot.bswap import bswap_liquidity_add - from binance.spot.bswap import bswap_liquidity_remove - from binance.spot.bswap import bswap_liquidity_operation_record - from binance.spot.bswap import bswap_request_quote - from binance.spot.bswap import bswap_swap - from binance.spot.bswap import bswap_swap_history - from binance.spot.bswap import bswap_pool_configure - from binance.spot.bswap import bswap_add_liquidity_preview - from binance.spot.bswap import bswap_remove_liquidity_preview - from binance.spot.bswap import bswap_unclaimed_rewards - from binance.spot.bswap import bswap_claim_rewards - from binance.spot.bswap import bswap_claimed_rewards + from binance.spot._bswap import bswap_pools + from binance.spot._bswap import bswap_liquidity + from binance.spot._bswap import bswap_liquidity_add + from binance.spot._bswap import bswap_liquidity_remove + from binance.spot._bswap import bswap_liquidity_operation_record + from binance.spot._bswap import bswap_request_quote + from binance.spot._bswap import bswap_swap + from binance.spot._bswap import bswap_swap_history + from binance.spot._bswap import bswap_pool_configure + from binance.spot._bswap import bswap_add_liquidity_preview + from binance.spot._bswap import bswap_remove_liquidity_preview + from binance.spot._bswap import bswap_unclaimed_rewards + from binance.spot._bswap import bswap_claim_rewards + from binance.spot._bswap import bswap_claimed_rewards # FIAT - from binance.spot.fiat import fiat_order_history - from binance.spot.fiat import fiat_payment_history + from binance.spot._fiat import fiat_order_history + from binance.spot._fiat import fiat_payment_history # C2C - from binance.spot.c2c import c2c_trade_history + from binance.spot._c2c import c2c_trade_history # LOANS - from binance.spot.loan import loan_history - from binance.spot.loan import loan_borrow - from binance.spot.loan import loan_borrow_history - from binance.spot.loan import loan_ongoing_orders - from binance.spot.loan import loan_repay - from binance.spot.loan import loan_repay_history - from binance.spot.loan import loan_adjust_ltv - from binance.spot.loan import loan_adjust_ltv_history - from binance.spot.loan import loan_vip_ongoing_orders - from binance.spot.loan import loan_vip_repay - from binance.spot.loan import loan_vip_repay_history - from binance.spot.loan import loan_vip_collateral_account - from binance.spot.loan import loan_loanable_data - from binance.spot.loan import loan_collateral_data - from binance.spot.loan import loan_collateral_rate - from binance.spot.loan import loan_customize_margin_call + from binance.spot._loan import loan_history + from binance.spot._loan import loan_borrow + from binance.spot._loan import loan_borrow_history + from binance.spot._loan import loan_ongoing_orders + from binance.spot._loan import loan_repay + from binance.spot._loan import loan_repay_history + from binance.spot._loan import loan_adjust_ltv + from binance.spot._loan import loan_adjust_ltv_history + from binance.spot._loan import loan_vip_ongoing_orders + from binance.spot._loan import loan_vip_repay + from binance.spot._loan import loan_vip_repay_history + from binance.spot._loan import loan_vip_collateral_account + from binance.spot._loan import loan_loanable_data + from binance.spot._loan import loan_collateral_data + from binance.spot._loan import loan_collateral_rate + from binance.spot._loan import loan_customize_margin_call # PAY - from binance.spot.pay import pay_history + from binance.spot._pay import pay_history # CONVERT - from binance.spot.convert import convert_trade_history + from binance.spot._convert import convert_trade_history # REBATE - from binance.spot.rebate import rebate_spot_history + from binance.spot._rebate import rebate_spot_history # NFT - from binance.spot.nft import nft_transaction_history - from binance.spot.nft import nft_deposit_history - from binance.spot.nft import nft_withdraw_history - from binance.spot.nft import nft_asset + from binance.spot._nft import nft_transaction_history + from binance.spot._nft import nft_deposit_history + from binance.spot._nft import nft_withdraw_history + from binance.spot._nft import nft_asset # Gift Card (Binance Code in the API documentation) - from binance.spot.gift_card import gift_card_create_code - from binance.spot.gift_card import gift_card_redeem_code - from binance.spot.gift_card import gift_card_verify_code - from binance.spot.gift_card import gift_card_rsa_public_key - from binance.spot.gift_card import gift_card_buy_code - from binance.spot.gift_card import gift_card_token_limit + from binance.spot._gift_card import gift_card_create_code + from binance.spot._gift_card import gift_card_redeem_code + from binance.spot._gift_card import gift_card_verify_code + from binance.spot._gift_card import gift_card_rsa_public_key + from binance.spot._gift_card import gift_card_buy_code + from binance.spot._gift_card import gift_card_token_limit # Portfolio Margin - from binance.spot.portfolio_margin import portfolio_margin_account - from binance.spot.portfolio_margin import portfolio_margin_collateral_rate - from binance.spot.portfolio_margin import portfolio_margin_bankruptcy_loan_amount - from binance.spot.portfolio_margin import portfolio_margin_bankruptcy_loan_repay + from binance.spot._portfolio_margin import portfolio_margin_account + from binance.spot._portfolio_margin import portfolio_margin_collateral_rate + from binance.spot._portfolio_margin import portfolio_margin_bankruptcy_loan_amount + from binance.spot._portfolio_margin import portfolio_margin_bankruptcy_loan_repay diff --git a/binance/spot/blvt.py b/binance/spot/_blvt.py similarity index 100% rename from binance/spot/blvt.py rename to binance/spot/_blvt.py diff --git a/binance/spot/bswap.py b/binance/spot/_bswap.py similarity index 100% rename from binance/spot/bswap.py rename to binance/spot/_bswap.py diff --git a/binance/spot/c2c.py b/binance/spot/_c2c.py similarity index 100% rename from binance/spot/c2c.py rename to binance/spot/_c2c.py diff --git a/binance/spot/convert.py b/binance/spot/_convert.py similarity index 100% rename from binance/spot/convert.py rename to binance/spot/_convert.py diff --git a/binance/spot/data_stream.py b/binance/spot/_data_stream.py similarity index 100% rename from binance/spot/data_stream.py rename to binance/spot/_data_stream.py diff --git a/binance/spot/fiat.py b/binance/spot/_fiat.py similarity index 100% rename from binance/spot/fiat.py rename to binance/spot/_fiat.py diff --git a/binance/spot/futures.py b/binance/spot/_futures.py similarity index 100% rename from binance/spot/futures.py rename to binance/spot/_futures.py diff --git a/binance/spot/gift_card.py b/binance/spot/_gift_card.py similarity index 100% rename from binance/spot/gift_card.py rename to binance/spot/_gift_card.py diff --git a/binance/spot/loan.py b/binance/spot/_loan.py similarity index 100% rename from binance/spot/loan.py rename to binance/spot/_loan.py diff --git a/binance/spot/margin.py b/binance/spot/_margin.py similarity index 100% rename from binance/spot/margin.py rename to binance/spot/_margin.py diff --git a/binance/spot/market.py b/binance/spot/_market.py similarity index 100% rename from binance/spot/market.py rename to binance/spot/_market.py diff --git a/binance/spot/mining.py b/binance/spot/_mining.py similarity index 100% rename from binance/spot/mining.py rename to binance/spot/_mining.py diff --git a/binance/spot/nft.py b/binance/spot/_nft.py similarity index 100% rename from binance/spot/nft.py rename to binance/spot/_nft.py diff --git a/binance/spot/pay.py b/binance/spot/_pay.py similarity index 100% rename from binance/spot/pay.py rename to binance/spot/_pay.py diff --git a/binance/spot/portfolio_margin.py b/binance/spot/_portfolio_margin.py similarity index 100% rename from binance/spot/portfolio_margin.py rename to binance/spot/_portfolio_margin.py diff --git a/binance/spot/rebate.py b/binance/spot/_rebate.py similarity index 100% rename from binance/spot/rebate.py rename to binance/spot/_rebate.py diff --git a/binance/spot/savings.py b/binance/spot/_savings.py similarity index 100% rename from binance/spot/savings.py rename to binance/spot/_savings.py diff --git a/binance/spot/staking.py b/binance/spot/_staking.py similarity index 100% rename from binance/spot/staking.py rename to binance/spot/_staking.py diff --git a/binance/spot/sub_account.py b/binance/spot/_sub_account.py similarity index 100% rename from binance/spot/sub_account.py rename to binance/spot/_sub_account.py diff --git a/binance/spot/trade.py b/binance/spot/_trade.py similarity index 100% rename from binance/spot/trade.py rename to binance/spot/_trade.py diff --git a/binance/spot/wallet.py b/binance/spot/_wallet.py similarity index 100% rename from binance/spot/wallet.py rename to binance/spot/_wallet.py diff --git a/binance/websocket/binance_client_factory.py b/binance/websocket/binance_client_factory.py deleted file mode 100644 index 8bada1b7..00000000 --- a/binance/websocket/binance_client_factory.py +++ /dev/null @@ -1,48 +0,0 @@ -import logging -from autobahn.twisted.websocket import WebSocketClientFactory -from twisted.internet.protocol import ReconnectingClientFactory -from binance.websocket.binance_client_protocol import BinanceClientProtocol - - -class BinanceReconnectingClientFactory(ReconnectingClientFactory): - - initialDelay = 0.1 - maxDelay = 10 - maxRetries = 10 - - -class BinanceClientFactory(WebSocketClientFactory, BinanceReconnectingClientFactory): - def __init__(self, *args, payload=None, **kwargs): - WebSocketClientFactory.__init__(self, *args, **kwargs) - self.protocol_instance = None - self.base_client = None - self.payload = payload - self._logger = logging.getLogger(__name__) - - _reconnect_error_payload = {"e": "error", "m": "Max reconnect retries reached"} - - def startedConnecting(self, connector): - self._logger.info("Start to connect....") - - def clientConnectionFailed(self, connector, reason): - self._logger.error( - "Can't connect to server. Reason: {}. Retrying: {}".format( - reason, self.retries + 1 - ) - ) - self.retry(connector) - if self.retries > self.maxRetries: - self.callback(self._reconnect_error_payload) - - def clientConnectionLost(self, connector, reason): - self._logger.error( - "Lost connection to Server. Reason: {}. Retrying: {}".format( - reason, self.retries + 1 - ) - ) - self.retry(connector) - if self.retries > self.maxRetries: - self.callback(self._reconnect_error_payload) - - def buildProtocol(self, addr): - return BinanceClientProtocol(self, payload=self.payload) diff --git a/binance/websocket/binance_client_protocol.py b/binance/websocket/binance_client_protocol.py deleted file mode 100644 index f100442f..00000000 --- a/binance/websocket/binance_client_protocol.py +++ /dev/null @@ -1,46 +0,0 @@ -import json -import logging -from autobahn.twisted.websocket import WebSocketClientProtocol - - -class BinanceClientProtocol(WebSocketClientProtocol): - def __init__(self, factory, payload=None): - super().__init__() - self.factory = factory - self.payload = payload - self._logger = logging.getLogger(__name__) - - def onOpen(self): - self.factory.protocol_instance = self - - def onConnect(self, response): - self._logger.info("Server connected") - if self.payload: - self._logger.info("Sending message to Server: {}".format(self.payload)) - self.sendMessage(self.payload, isBinary=False) - # reset the delay after reconnecting - self.factory.resetDelay() - - def onMessage(self, payload, isBinary): - if not isBinary: - try: - payload_obj = json.loads(payload.decode("utf8")) - except ValueError: - pass - else: - self.factory.callback(payload_obj) - - def onClose(self, wasClean, code, reason): - self._logger.warning( - "WebSocket connection closed: {0}, code: {1}, clean: {2}, reason: {0}".format( - reason, code, wasClean - ) - ) - - def onPing(self, payload): - self._logger.info("Received Ping from server") - self.sendPong() - self._logger.info("Responded Pong to server") - - def onPong(self, payload): - self._logger.info("Received Pong from server") diff --git a/binance/websocket/binance_socket_manager.py b/binance/websocket/binance_socket_manager.py index 3f6a6a18..858bd1f2 100644 --- a/binance/websocket/binance_socket_manager.py +++ b/binance/websocket/binance_socket_manager.py @@ -1,83 +1,104 @@ -import json import logging import threading -from urllib.parse import urlparse -from twisted.internet import reactor, ssl -from twisted.internet.error import ReactorAlreadyRunning -from autobahn.twisted.websocket import WebSocketClientFactory, connectWS -from binance.websocket.binance_client_protocol import BinanceClientProtocol -from binance.websocket.binance_client_factory import BinanceClientFactory +from websocket import ( + ABNF, + create_connection, + WebSocketException, + WebSocketConnectionClosedException, +) class BinanceSocketManager(threading.Thread): - def __init__(self, stream_url): + def __init__( + self, + stream_url, + on_message=None, + on_open=None, + on_close=None, + on_error=None, + on_ping=None, + on_pong=None, + logger=None, + ): threading.Thread.__init__(self) - - self.factories = {} - self._connected_event = threading.Event() + if not logger: + logger = logging.getLogger(__name__) + self.logger = logger self.stream_url = stream_url - self._conns = {} - self._user_callback = None - self._logger = logging.getLogger(__name__) - - def _start_socket( - self, stream_name, payload, callback, is_combined=False, is_live=True - ): - if stream_name in self._conns: - return False - - if is_combined: - factory_url = self.stream_url + "/stream" - else: - factory_url = self.stream_url + "/ws" - - if not is_live: - payload_obj = json.loads(payload.decode("utf8")) - - if is_combined: - factory_url = factory_url + "?streams=" + payload_obj["params"] - else: - factory_url = factory_url + "/" + payload_obj["params"] - payload = None - - self._logger.info("Connection with URL: {}".format(factory_url)) + self.on_message = on_message + self.on_open = on_open + self.on_close = on_close + self.on_ping = on_ping + self.on_pong = on_pong + self.on_error = on_error + self.create_ws_connection() - factory = BinanceClientFactory(factory_url, payload=payload) - factory.base_client = self - factory.protocol = BinanceClientProtocol - factory.setProtocolOptions( - openHandshakeTimeout=5, autoPingInterval=300, autoPingTimeout=5 + def create_ws_connection(self): + self.logger.debug( + "Creating connection with WebSocket Server: %s", self.stream_url ) - factory.callback = callback - self.factories[stream_name] = factory - reactor.callFromThread(self.add_connection, stream_name, self.stream_url) + self.ws = create_connection(self.stream_url) + self.logger.debug( + "WebSocket connection has been established: %s", self.stream_url + ) + self._callback(self.on_open) - def add_connection(self, stream_name, url): - if not url.startswith("wss://"): - raise ValueError("expected wss:// URL prefix") + def run(self): + self.read_data() - factory = self.factories[stream_name] - options = ssl.optionsForClientTLS(hostname=urlparse(url).hostname) - self._conns[stream_name] = connectWS(factory, options) + def send_message(self, message): + self.logger.debug("Sending message to Binance WebSocket Server: %s", message) + self.ws.send(message) - def stop_socket(self, conn_key): - if conn_key not in self._conns: - return + def ping(self): + self.ws.ping() - # disable reconnecting if we are closing - self._conns[conn_key].factory = WebSocketClientFactory(self.stream_url) - self._conns[conn_key].disconnect() - del self._conns[conn_key] + def read_data(self): + data = "" + while True: + try: + op_code, frame = self.ws.recv_data_frame(True) + except WebSocketException as e: + if isinstance(e, WebSocketConnectionClosedException): + self.logger.error("Lost websocket connection") + else: + self.logger.error("Websocket exception: {}".format(e)) + raise e + except Exception as e: + self.logger.error("Exception in read_data: {}".format(e)) + raise e - def run(self): - try: - reactor.run(installSignalHandlers=False) - except ReactorAlreadyRunning: - # Ignore error about reactor already running - pass + if op_code == ABNF.OPCODE_CLOSE: + self.logger.warning( + "CLOSE frame received, closing websocket connection" + ) + self._callback(self.on_close) + break + elif op_code == ABNF.OPCODE_PING: + self._callback(self.on_ping, frame.data) + self.ws.pong("") + self.logger.debug("Received Ping; PONG frame sent back") + elif op_code == ABNF.OPCODE_PONG: + self.logger.debug("Received PONG frame") + self._callback(self.on_pong) + else: + data = frame.data + if op_code == ABNF.OPCODE_TEXT: + data = data.decode("utf-8") + self._callback(self.on_message, data) def close(self): - keys = set(self._conns.keys()) - for key in keys: - self.stop_socket(key) - self._conns = {} + if not self.ws.connected: + self.logger.warn("Websocket already closed") + else: + self.ws.send_close() + return + + def _callback(self, callback, *args): + if callback: + try: + callback(self, *args) + except Exception as e: + self.logger.error("Error from callback {}: {}".format(callback, e)) + if self.on_error: + self.on_error(self, e) diff --git a/binance/websocket/spot/websocket_api/__init__.py b/binance/websocket/spot/websocket_api/__init__.py new file mode 100644 index 00000000..1df3f297 --- /dev/null +++ b/binance/websocket/spot/websocket_api/__init__.py @@ -0,0 +1,70 @@ +from binance.websocket.websocket_client import BinanceWebsocketClient + + +class SpotWebsocketAPIClient(BinanceWebsocketClient): + def __init__( + self, + stream_url="wss://ws-api.binance.com/ws-api/v3", + api_key=None, + api_secret=None, + on_message=None, + on_open=None, + on_close=None, + on_error=None, + on_ping=None, + on_pong=None, + ): + self.api_key = api_key + self.api_secret = api_secret + + super().__init__( + stream_url, + on_message=on_message, + on_open=on_open, + on_close=on_close, + on_error=on_error, + on_ping=on_ping, + on_pong=on_pong, + ) + + # Market + from binance.websocket.spot.websocket_api._market import ping_connectivity + from binance.websocket.spot.websocket_api._market import server_time + from binance.websocket.spot.websocket_api._market import exchange_info + from binance.websocket.spot.websocket_api._market import order_book + from binance.websocket.spot.websocket_api._market import recent_trades + from binance.websocket.spot.websocket_api._market import historical_trades + from binance.websocket.spot.websocket_api._market import aggregate_trades + from binance.websocket.spot.websocket_api._market import klines + from binance.websocket.spot.websocket_api._market import ui_klines + from binance.websocket.spot.websocket_api._market import avg_price + from binance.websocket.spot.websocket_api._market import ticker_24hr + from binance.websocket.spot.websocket_api._market import ticker + from binance.websocket.spot.websocket_api._market import ticker_price + from binance.websocket.spot.websocket_api._market import ticker_book + + # Account + from binance.websocket.spot.websocket_api._account import account + from binance.websocket.spot.websocket_api._account import order_rate_limit + from binance.websocket.spot.websocket_api._account import order_history + from binance.websocket.spot.websocket_api._account import oco_history + from binance.websocket.spot.websocket_api._account import my_trades + from binance.websocket.spot.websocket_api._account import prevented_matches + + # Trade + from binance.websocket.spot.websocket_api._trade import new_order + from binance.websocket.spot.websocket_api._trade import new_order_test + from binance.websocket.spot.websocket_api._trade import get_order + from binance.websocket.spot.websocket_api._trade import cancel_order + from binance.websocket.spot.websocket_api._trade import cancel_replace_order + from binance.websocket.spot.websocket_api._trade import get_open_orders + from binance.websocket.spot.websocket_api._trade import cancel_open_orders + from binance.websocket.spot.websocket_api._trade import new_oco_order + from binance.websocket.spot.websocket_api._trade import get_oco_order + from binance.websocket.spot.websocket_api._trade import cancel_oco_order + from binance.websocket.spot.websocket_api._trade import get_open_oco_orders + + # User Data Stream + from binance.websocket.spot.websocket_api._user_data import user_data_start + from binance.websocket.spot.websocket_api._user_data import user_data_ping + from binance.websocket.spot.websocket_api._user_data import user_data_stop diff --git a/binance/websocket/spot/websocket_api/_account.py b/binance/websocket/spot/websocket_api/_account.py new file mode 100644 index 00000000..ff570e51 --- /dev/null +++ b/binance/websocket/spot/websocket_api/_account.py @@ -0,0 +1,469 @@ +from binance.lib.utils import get_uuid, purge_map, websocket_api_signature + + +def account(self, **kwargs): + """Account information (USER_DATA) + + Keyword Args: + id (str, optional): Client generated ID. + recvWindow (int, optional): The value cannot be greater than 60000 + + Message sent: + + .. code-block:: json + + { + "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba", + "method": "account.status", + "params": { + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "83303b4a136ac1371795f465808367242685a9e3a42b22edb4d977d0696eb45c", + "timestamp": 1660801839480 + } + } + + + Response: + + .. code-block:: json + + { + "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba", + "status": 200, + "result": { + "makerCommission": 15, + "takerCommission": 15, + "buyerCommission": 0, + "sellerCommission": 0, + "canTrade": true, + "canWithdraw": true, + "canDeposit": true, + "commissionRates": { + "maker": "0.00150000", + "taker": "0.00150000", + "buyer": "0.00000000", + "seller":"0.00000000" + }, + "brokered": false, + "requireSelfTradePrevention": false, + "updateTime": 1660801833000, + "accountType": "SPOT", + "balances": [ + { + "asset": "BNB", + "free": "0.00000000", + "locked": "0.00000000" + }, + { + "asset": "BTC", + "free": "1.3447112", + "locked": "0.08600000" + }, + { + "asset": "USDT", + "free": "1021.21000000", + "locked": "0.00000000" + } + ], + "permissions": [ + "SPOT" + ] + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 10 + } + ] + } + + """ + + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "account.status", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def order_rate_limit(self, **kwargs): + """Account order rate limits (USER_DATA) + + Keyword Args: + id (str, optional): Client generated ID. + recvWindow (int, optional): The value cannot be greater than 60000 + + Message sent: + + .. code-block:: json + + { + "id": "d3783d8d-f8d1-4d2c-b8a0-b7596af5a664", + "method": "account.rateLimits.orders", + "params": { + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "76289424d6e288f4dc47d167ac824e859dabf78736f4348abbbac848d719eb94", + "timestamp": 1660801839500 + } + } + + + Response: + + .. code-block:: json + + { + "id": "d3783d8d-f8d1-4d2c-b8a0-b7596af5a664", + "status": 200, + "result": [{ + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 1, + "limit": 200 + }, + { + "rateLimitType": "ORDERS", + "interval": "DAY", + "intervalNum": 1, + "limit": 100000 + }], + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 10 + }] + } + + """ + + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "account.rateLimits.orders", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def order_history(self, **kwargs): + """Account order history (USER_DATA) + + Keyword Args: + id (str, optional): Client generated ID. + symbol (str, optional): Symbol + orderId (int, optional): Order ID + startTime (int, optional): Timestamp in ms + endTime (int, optional): Timestamp in ms + limit (int, optional): Default 500; max 1000. + recvWindow (int, optional): The value cannot be greater than 60000 + + Message sent: + + .. code-block:: json + + { + "id": "734235c2-13d2-4574-be68-723e818c08f3", + "method": "allOrders", + "params": { + "symbol": "BTCUSDT", + "startTime": 1660780800000, + "endTime": 1660867200000, + "limit": 5, + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "f50a972ba7fad92842187643f6b930802d4e20bce1ba1e788e856e811577bd42", + "timestamp": 1661955123341 + } + } + + + Response + + .. code-block:: json + + { + "id": "734235c2-13d2-4574-be68-723e818c08f3", + "status": 200, + "result": [{ + "symbol": "BTCUSDT", + "orderId": 12569099453, + "orderListId": -1, + "clientOrderId": "4d96324ff9d44481926157", + "price": "23416.10000000", + "origQty": "0.00847000", + "executedQty": "0.00847000", + "cummulativeQuoteQty": "198.33521500", + "status": "FILLED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "stopPrice": "0.00000000", + "icebergQty": "0.00000000", + "time": 1660801715639, + "updateTime": 1660801717945, + "isWorking": true, + "workingTime": 1660801715639, + "origQuoteOrderQty": "0.00000000", + "selfTradePreventionMode": "NONE", + "preventedMatchId": 0, + "preventedQuantity": "1.200000" + }], + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 10 + }] + } + + """ + + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "allOrders", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def oco_history(self, **kwargs): + """Account OCO history (USER_DATA) + + Keyword Args: + id (str, optional): Client generated ID. + fromId (int, optional): OCO ID + startTime (int, optional): Timestamp in ms + endTime (int, optional): Timestamp in ms + limit (int, optional): Default 500; max 1000. + recvWindow (int, optional): The value cannot be greater than 60000 + + Message sent: + + .. code-block:: json + + { + "id": "8617b7b3-1b3d-4dec-94cd-eefd929b8ceb", + "method": "allOrderLists", + "params": { + "startTime": 1660780800000, + "endTime": 1660867200000, + "limit": 5, + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "c8e1484db4a4a02d0e84dfa627eb9b8298f07ebf12fcc4eaf86e4a565b2712c2", + "timestamp": 1661955123341 + } + } + + + Response + + .. code-block:: json + + { + "id": "8617b7b3-1b3d-4dec-94cd-eefd929b8ceb", + "status": 200, + "result": [{ + "orderListId": 1274512, + "contingencyType": "OCO", + "listStatusType": "EXEC_STARTED", + "listOrderStatus": "EXECUTING", + "listClientOrderId": "08985fedd9ea2cf6b28996", + "transactionTime": 1660801713793, + "symbol": "BTCUSDT", + "orders": [{ + "symbol": "BTCUSDT", + "orderId": 12569138901, + "clientOrderId": "BqtFCj5odMoWtSqGk2X9tU" + }, + { + "symbol": "BTCUSDT", + "orderId": 12569138902, + "clientOrderId": "jLnZpj5enfMXTuhKB1d0us" + }] + }], + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 10 + }] + } + + """ + + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "allOrderLists", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def my_trades(self, **kwargs): + """Account trade history (USER_DATA) + + Keyword Args: + id (str, optional): Client generated ID. + symbol (str, optional): Symbol + orderId (int, optional): order id + startTime (int, optional): Timestamp in ms + endTime (int, optional): Timestamp in ms + fromId (int, optional): Trade id to fetch from. Default gets most recent trades. + limit (int, optional): Default 500; max 1000. + recvWindow (int, optional): The value cannot be greater than 60000 + + Message sent: + + .. code-block:: json + + { + "id": "f4ce6a53-a29d-4f70-823b-4ab59391d6e8", + "method": "myTrades", + "params": { + "symbol": "BTCUSDT", + "startTime": 1660780800000, + "endTime": 1660867200000, + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "c5a5ffb79fd4f2e10a92f895d488943a57954edf5933bde3338dfb6ea6d6eefc", + "timestamp": 1661955125250 + } + } + + + Response: + + .. code-block:: json + + { + "id": "f4ce6a53-a29d-4f70-823b-4ab59391d6e8", + "status": 200, + "result": [ + { + "symbol": "BTCUSDT", + "id": 12569138901, + "orderId": 12569138901, + "price": "0.00000000", + "qty": "0.00000000", + "commission": "0.00000000", + "commissionAsset": "BTC", + "time": 1660801715639, + "isBuyer": true, + "isMaker": false, + "isBestMatch": true + } + ], + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 10 + }] + } + + """ + + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "myTrades", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def prevented_matches(self, symbol: str, **kwargs): + """Account prevented matches (USER_DATA) + + Keyword Args: + id (str, optional): Client generated ID. + symbol (str, optional): Symbol + preventedMatchId (int, optional): Prevented match id + orderId (int, optional): order id + fromPrevMatchId (int, optional): Prevented match id to fetch from. + limit (int, optional): Default 500; max 1000. + recvWindow (int, optional): The value cannot be greater than 60000 + + + Combinations supported:: + - symbol + preventedMatchId + - symbol + orderId + - symbol + orderId + fromPreventedMatchId (limit will default to 500) + - symbol + orderId + fromPreventedMatchId + limit + + + Message sent: + + .. code-block:: json + + { + "id": "g4ce6a53-a39d-4f71-823b-4ab5r391d6y8", + "method": "myPreventedMatches", + "params": { + "symbol": "BTCUSDT", + "orderId": 35, + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "c5a5ffb79fd4f2e10a92f895d488943a57954edf5933bde3338dfb6ea6d6eefc", + "timestamp": 1673923281052 + } + } + + + Response + + .. code-block:: json + + { + "id": "g4ce6a53-a39d-4f71-823b-4ab5r391d6y8", + "status": 200, + "result": [{ + "symbol": "BTCUSDT", + "preventedMatchId": 1, + "takerOrderId": 5, + "makerOrderId": 3, + "tradeGroupId": 1, + "selfTradePreventionMode": "EXPIRE_MAKER", + "price": "1.100000", + "makerPreventedQuantity": "1.300000", + "transactTime": 1669101687094 + }], + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 10 + }] + } + + """ + parameters = {"symbol": symbol, **kwargs} + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "myPreventedMatches", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) diff --git a/binance/websocket/spot/websocket_api/_market.py b/binance/websocket/spot/websocket_api/_market.py new file mode 100644 index 00000000..a3b05c23 --- /dev/null +++ b/binance/websocket/spot/websocket_api/_market.py @@ -0,0 +1,1000 @@ +from binance.lib.utils import get_uuid, purge_map +from binance.error import ParameterArgumentError + + +def ping_connectivity(self, id=None): + """Test connectivity to the WebSocket API. + + Args: + id (str): request id + + Message sent: + + .. code-block:: json + + { + "id": "922bcc6e-9de8-440d-9e84-7c80933a8d0d", + "method": "ping" + } + + + Response: + + .. code-block:: json + + { + "id": "922bcc6e-9de8-440d-9e84-7c80933a8d0d", + "status": 200, + "result": {}, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + }] + } + + + Note: You can use regular WebSocket ping frames to test connectivity as well, + WebSocket API will respond with pong frames as soon as possible. + + """ + + if not id: + id = get_uuid() + + payload = {"id": id, "method": "ping"} + + self.send(payload) + + +def server_time(self, id=None): + """Check server time + + Args: + id (str): request id + + Message sent: + + .. code-block:: json + + { + "id": "187d3cb2-942d-484c-8271-4e2141bbadb1", + "method": "time" + } + + + Response: + + .. code-block:: json + + { + "id": "187d3cb2-942d-484c-8271-4e2141bbadb1", + "status": 200, + "result": { + "serverTime": 1656400526260 + }, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + }] + } + + + Test connectivity to the WebSocket API and get the current server time. + + """ + + if not id: + id = get_uuid() + + payload = {"id": id, "method": "time"} + + self.send(payload) + + +def exchange_info(self, **kwargs): + """Exchange information + + Query current exchange trading rules, rate limits, and symbol information. + + Note: For symbol, Upper case is required. + + Keyword Args: + symbols (list): symbols to get info + symbol (str): symbol to get info + permissons (list): permissions to get info + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "exchangeInfo", + "params": { + "symbols": [ + "BNBBTC" + ] + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": { + "timezone": "UTC", + "serverTime": 1655969291181, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 50 + }, + { + "rateLimitType": "ORDERS", + "interval": "DAY", + "intervalNum": 1, + "limit": 160000 + }, + { + "rateLimitType": "RAW_REQUESTS", + "interval": "MINUTE", + "intervalNum": 5, + "limit": 6100 + }], + "exchangeFilters": [], + "symbols": [{ + "symbol": "BNBBTC", + "status": "TRADING", + "baseAsset": "BNB", + "baseAssetPrecision": 8, + "quoteAsset": "BTC", + "quotePrecision": 8, + "quoteAssetPrecision": 8, + "baseCommissionPrecision": 8, + "quoteCommissionPrecision": 8, + "orderTypes": [ + "LIMIT", + "LIMIT_MAKER", + "MARKET", + "STOP_LOSS_LIMIT", + "TAKE_PROFIT_LIMIT" + ], + "icebergAllowed": true, + "ocoAllowed": true, + "quoteOrderQtyMarketAllowed": true, + "allowTrailingStop": true, + "cancelReplaceAllowed": true, + "isSpotTradingAllowed": true, + "isMarginTradingAllowed": true, + "filters": [{ + "filterType": "PRICE_FILTER", + "minPrice": "0.00000100", + "maxPrice": "100000.00000000", + "tickSize": "0.00000100" + }, + { + "filterType": "LOT_SIZE", + "minQty": "0.00100000", + "maxQty": "100000.00000000", + "stepSize": "0.00100000" + }], + "permissions": [ + "SPOT", + "MARGIN", + "TRD_GRP_004" + ], + "defaultSelfTradePreventionMode": "NONE", + "allowedSelfTradePreventionModes": [ + "NONE" + ] + }]}, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 10 + }] + } + """ + parameters = {**kwargs} + + parameters = purge_map(parameters) + + if len(parameters) > 1: + raise ParameterArgumentError( + "Only one of symbol, symbols or permissions is required." + ) + + payload = {"id": parameters.pop("id", get_uuid()), "method": "exchangeInfo"} + + self.send(payload) + + +def order_book(self, symbol: str, **kwargs): + """Order book + + Args: + symbol (str): symbol to get order book + + Keyword Args: + limit (int): limit of order book + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "depth", + "params": { + "symbol": "BNBBTC", + "limit": 10 + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": { + "lastUpdateId": 2731179239, + "bids": [ + [ + "0.01379900", + "3.43200000" + ], + [ + "0.01379800", + "3.24300000" + ], + [ + "0.01379700", + "10.45500000" + ], + [ + "0.01379600", + "3.82100000" + ], + [ + "0.01379500", + "10.26200000" + ] + ], + "asks": [ + [ + "0.01380000", + "5.91700000" + ], + [ + "0.01380100", + "6.01400000" + ], + [ + "0.01380200", + "0.26800000" + ], + [ + "0.01380300", + "0.33800000" + ], + [ + "0.01380400", + "0.26800000" + ] + ] + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + """ + parameters = {"symbol": symbol.upper(), **kwargs} + + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "depth", + "params": parameters, + } + + self.send(payload) + + +def recent_trades(self, symbol: str, **kwargs): + """Recent trades + + Args: + symbol (str): symbol to get recent trades + + Keyword Args: + limit (int): limit of recent trades + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "trades.recent", + "params": { + "symbol": "BNBBTC", + "limit": 10 + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": [ + { + "id": 194686783, + "price": "0.01361000", + "qty": "0.01400000", + "quoteQty": "0.00019054", + "time": 1660009530807, + "isBuyerMaker": true, + "isBestMatch": true + } + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + """ + + parameters = {"symbol": symbol.upper(), **kwargs} + + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "trades.recent", + "params": parameters, + } + + self.send(payload) + + +def historical_trades(self, symbol: str, apiKey: str, **kwargs): + """Historical trades + + Args: + symbol (str): symbol to get historical trades + + Keyword Args: + symbol (str): symbol to get historical trades + fromId (int): trade id to fetch from + limit (int): limit of historical trades + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "trades.historical", + "params": { + "symbol": "BNBBTC", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "fromId": 0, + "limit": 1 + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": [ + { + "id": 0, + "price": "0.01361000", + "qty": "0.01400000", + "quoteQty": "0.00019054", + "time": 1660009530807, + "isBuyerMaker": true, + "isBestMatch": true + } + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + """ + parameters = {"symbol": symbol.upper(), "apiKey": apiKey, **kwargs} + + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "trades.historical", + "params": parameters, + } + + self.send(payload) + + +def aggregate_trades(self, symbol: str, **kwargs): + """Aggregate trades + + Args: + symbol (str): symbol to get aggregate trades + + Keyword Args: + symbol (str): symbol to get aggregate trades + fromId (int): trade id to fetch from + limit (int): limit of aggregate trades + startTime (int): start time to fetch from + endTime (int): end time to fetch from + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "trades.aggregate", + "params": { + "symbol": "BNBBTC", + "fromId": 0, + "limit": 1 + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": [ + { + "a": 0, + "p": "0.01361000", + "q": "0.01400000", + "f": 0, + "l": 0, + "T": 1660009530807, + "m": true, + "M": true + } + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + parameters = {"symbol": symbol.upper(), **kwargs} + + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "trades.aggregate", + "params": parameters, + } + + self.send(payload) + + +def klines(self, symbol: str, interval: str, **kwargs): + """Klines/candlesticks + + Args: + symbol (str): symbol to get klines + interval (str): interval of klines + + Keyword Args: + startTime (int): start time to fetch from + endTime (int): end time to fetch from + limit (int): limit of klines + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "klines", + "params": { + "symbol": "BNBBTC", + "interval": "1m", + "startTime": 1655969280000, + "limit": 1 + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": [ + [ + 1660009530807, + "0.01361000", + "0.01361000", + "0.01361000", + "0.01361000", + "0.01400000", + 1660009530807, + "0.00019054", + 0, + "0.00000000", + "0.00000000", + "0" + ] + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + parameters = {"symbol": symbol.upper(), "interval": interval, **kwargs} + + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "klines", + "params": parameters, + } + + self.send(payload) + + +def ui_klines(self, symbol: str, interval: str, **kwargs): + """Klines/candlesticks for UI + + Args: + symbol (str): symbol to get klines + interval (str): interval of klines + + Keyword Args: + startTime (int): start time to fetch from + endTime (int): end time to fetch from + limit (int): limit of klines + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "uiKlines", + "params": { + "symbol": "BNBBTC", + "interval": "1m", + "startTime": 1655969280000, + "limit": 1 + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": [ + [ + 1660009530807, + "0.01361000", + "0.01361000", + "0.01361000", + "0.01361000", + "0.01400000", + 1660009530807, + "0.00019054", + 0, + "0.00000000", + "0.00000000", + "0" + ] + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + parameters = {"symbol": symbol.upper(), "interval": interval, **kwargs} + + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "uiKlines", + "params": parameters, + } + + self.send(payload) + + +def avg_price(self, symbol: str, **kwargs): + """Current average price for a symbol + + Args: + symbol (str): symbol to get average price + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "avgPrice", + "params": { + "symbol": "BNBBTC" + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": { + "mins": 5, + "price": "0.01361000" + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + parameters = {"symbol": symbol.upper(), **kwargs} + + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "avgPrice", + "params": parameters, + } + + self.send(payload) + + +def ticker_24hr(self, **kwargs): + """24 hour rolling window price change statistics + + Keyword Args: + symbol (str): symbol to get ticker 24hr + symbols (list): symbols to get ticker 24hr + type (str): type of ticker 24hr + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "ticker.24hr", + "params": { + "symbol": "BNBBTC" + } + } + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": { + "symbol": "BNBBTC", + "priceChange": "-94.99999800", + "priceChangePercent": "-95.960", + "weightedAvgPrice": "0.29628482", + "prevClosePrice": "0.10002000", + "lastPrice": "4.00000200", + "lastQty": "200.00000000", + "bidPrice": "4.00000000", + "bidQty": "10.00000000", + "askPrice": "4.00000200", + "askQty": "10.00000000", + "openPrice": "99.00000000", + "highPrice": "100.00000000", + "lowPrice": "0.10000000", + "volume": "8913.30000000", + "quoteVolume": "15.30000000", + "openTime": 1499783499040, + "closeTime": 1499869899040, + "firstId": 28385, + "lastId": 28460, + "count": 76 + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "ticker.24hr", + "params": parameters, + } + + self.send(payload) + + +def ticker(self, **kwargs): + """Rolling window price change statistics + + Keyword Args: + symbol (str): symbol to get ticker + symbols (list): symbols to get ticker + type (str): type of ticker + windowSize (str): window size of ticker + + Message sent: + + .. code-block:: json + + { + "id": "f4b3b507-c8f2-442a-81a6-b2f12daa030f", + "method": "ticker", + "params": { + "symbols": [ + "BNBBTC", + "BTCUSDT" + ], + "windowSize": "7d" + } + } + + + Response + + .. code-block:: json + + { + "id": "f4b3b507-c8f2-442a-81a6-b2f12daa030f", + "status": 200, + "result": { + "symbol": "BNBBTC", + "priceChange": "0.00061500", + "priceChangePercent": "4.735", + "weightedAvgPrice": "0.01368242", + "openPrice": "0.01298900", + "highPrice": "0.01418800", + "lowPrice": "0.01296000", + "lastPrice": "0.01360400", + "volume": "587179.23900000", + "quoteVolume": "8034.03382165", + "openTime": 1659580020000, + "closeTime": 1660184865291, + "firstId": 192977765, + "lastId": 195365758, + "count": 2387994 + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 2 + } + ] + } + + """ + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "ticker", + "params": parameters, + } + + self.send(payload) + + +def ticker_price(self, **kwargs): + """Symbol price ticker + + Keyword Args: + symbol (str): symbol to get ticker price + symbols (list): symbols to get ticker price + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "ticker.price", + "params": { + "symbol": "BNBBTC" + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": { + "symbol": "BNBBTC", + "price": "4.00000200" + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "ticker.price", + "params": parameters, + } + + self.send(payload) + + +def ticker_book(self, **kwargs): + """Symbol order book ticker + + Keyword Args: + symbol (str): symbol to get ticker book + symbols (list): symbols to get ticker book + + Message sent: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "method": "ticker.book", + "params": { + "symbol": "BNBBTC" + } + } + + + Response: + + .. code-block:: json + + { + "id": "5494febb-d167-46a2-996d-70533eb4d976", + "status": 200, + "result": { + "symbol": "BNBBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + parameters = purge_map(kwargs) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "ticker.book", + "params": parameters, + } + + self.send(payload) diff --git a/binance/websocket/spot/websocket_api/_trade.py b/binance/websocket/spot/websocket_api/_trade.py new file mode 100644 index 00000000..316604f8 --- /dev/null +++ b/binance/websocket/spot/websocket_api/_trade.py @@ -0,0 +1,1157 @@ +from binance.lib.utils import get_uuid, purge_map, websocket_api_signature + + +def new_order(self, symbol: str, side: str, type: str, **kwargs): + """Create a new order. + + Args: + symbol (str): Symbol to trade. + side (str): Side of the trade. + type (str): Type of the trade. + Keyword Args: + timeInForce (str): Time in force. + quantity (float): Quantity of the trade. + quoteOrderQty (float): Quote order quantity. + price (float): Price of the trade. + newClientOrderId (str): New client order id. + stopPrice (float): Stop price. + trailingDelta (int): Trailing delta. + icebergQty (float): Iceberg quantity. + strategyId (int): Strategy id. + strategyType (int): Strategy type. + selfTradePreventionMode (str): Self trade prevention. + newOrderRespType (str): New order response type. + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "56374a46-3061-486b-a311-99ee972eb648", + "method": "order.place", + "params": { + "symbol": "BTCUSDT", + "side": "SELL", + "type": "LIMIT", + "timeInForce": "GTC", + "price": "23416.10000000", + "quantity": "0.00847000", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "15af09e41c36f3cc61378c2fbe2c33719a03dd5eba8d0f9206fbda44de717c88", + "timestamp": 1660801715431 + } + } + + + + Response + + .. code-block:: json + + { + "id": "56374a46-3061-486b-a311-99ee972eb648", + "status": 200, + "result": { + "symbol": "BTCUSDT", + "orderId": 12569099453, + "orderListId": -1, + "clientOrderId": "4d96324ff9d44481926157ec08158a40", + "transactTime": 1660801715639 + }, + "rateLimits": [ + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 50, + "count": 1 + }, + { + "rateLimitType": "ORDERS", + "interval": "DAY", + "intervalNum": 1, + "limit": 160000, + "count": 1 + }, + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + parameters = {"symbol": symbol, "side": side, "type": type, **kwargs} + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "order.place", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def new_order_test(self, symbol: str, side: str, type: str, **kwargs): + """Test new order (TRADE) + + Args: + symbol (str): Symbol to trade. + side (str): Side of the trade. + type (str): Type of the trade. + Keyword Args: + timeInForce (str): Time in force. + quantity (float): Quantity of the trade. + quoteOrderQty (float): Quote order quantity. + price (float): Price of the trade. + newClientOrderId (str): New client order id. + stopPrice (float): Stop price. + trailingDelta (int): Trailing delta. + icebergQty (float): Iceberg quantity. + strategyId (int): Strategy id. + strategyType (int): Strategy type. + selfTradePreventionMode (str): Self trade prevention. + newOrderRespType (str): New order response type. + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "56374a46-3061-486b-a311-99ee972eb648", + "method": "order.test", + "params": { + "symbol": "BTCUSDT", + "side": "SELL", + "type": "LIMIT", + "timeInForce": "GTC", + "price": "23416.10000000", + "quantity": "0.00847000", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "15af09e41c36f3cc61378c2fbe2c33719a03dd5eba8d0f9206fbda44de717c88", + "timestamp": 1660801715431 + } + } + + + + Response + + .. code-block:: json + + { + "id": "6ffebe91-01d9-43ac-be99-57cf062e0e30", + "status": 200, + "result": {}, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + parameters = {"symbol": symbol, "side": side, "type": type, **kwargs} + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "order.test", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def get_order(self, symbol: str, **kwargs): + """Get order (USER_DATA) + + Args: + symbol (str): Symbol to trade. + Keyword Args: + orderId (int): Order id. + origClientOrderId (str): Original client order id. + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "aa62318a-5a97-4f3b-bdc7-640bbe33b291", + "method": "order.status", + "params": { + "symbol": "BTCUSDT", + "orderId": 12569099453, + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "2c3aab5a078ee4ea465ecd95523b77289f61476c2f238ec10c55ea6cb11a6f35", + "timestamp": 1660801720951 + } + } + + Response: + + .. code-block:: json + + { + "id": "aa62318a-5a97-4f3b-bdc7-640bbe33b291", + "status": 200, + "result": { + "symbol": "BTCUSDT", + "orderId": 12569099453, + "orderListId": -1, + "clientOrderId": "4d96324ff9d44481926157", + "price": "23416.10000000", + "origQty": "0.00847000", + "executedQty": "0.00847000", + "cummulativeQuoteQty": "198.33521500", + "status": "FILLED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "stopPrice": "0.00000000", + "trailingDelta": 10, + "trailingTime": -1, + "icebergQty": "0.00000000", + "time": 1660801715639, + "updateTime": 1660801717945, + "isWorking": true, + "workingTime": 1660801715639, + "origQuoteOrderQty": "0.00000000", + "strategyId": 37463720, + "strategyType": 1000000, + "selfTradePreventionMode": "NONE", + "preventedMatchId": 0, + "preventedQuantity": "1.200000" + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 2 + } + ] + } + + """ + + parameters = {"symbol": symbol, **kwargs} + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "order.status", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def cancel_order(self, symbol: str, **kwargs): + """Cancel order (USER_DATA) + Args: + symbol (str): Symbol to trade. + Keyword Args: + orderId (int): Order id. + origClientOrderId (str): Original client order id. + newClientOrderId (str): New client order id. + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd", + "method": "order.cancel", + "params": { + "symbol": "BTCUSDT", + "origClientOrderId": "4d96324ff9d44481926157", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "33d5b721f278ae17a52f004a82a6f68a70c68e7dd6776ed0be77a455ab855282", + "timestamp": 1660801715830 + } + } + + + Response: + + .. code-block:: json + + { + "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd", + "status": 200, + "result": { + "symbol": "BTCUSDT", + "origClientOrderId": "4d96324ff9d44481926157", + "orderId": 12569099453, + "orderListId": -1, + "clientOrderId": "91fe37ce9e69c90d6358c0", + "price": "23416.10000000", + "origQty": "0.00847000", + "executedQty": "0.00001000", + "cummulativeQuoteQty": "0.23416100", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "stopPrice": "0.00000000", + "trailingDelta": 0, + "trailingTime": -1, + "icebergQty": "0.00000000", + "strategyId": 37463720, + "strategyType": 1000000, + "selfTradePreventionMode": "NONE" + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + parameters = {"symbol": symbol, **kwargs} + parameters = purge_map(parameters) + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "order.cancel", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + + self.send(payload) + + +def cancel_replace_order( + self, symbol: str, cancelReplaceMode: str, side: str, type: str, **kwargs +): + """Cancel and replace order + Args: + symbol (str): Symbol to trade. + cancelReplaceMode (str): + side (str): SIDE + type (str): ORDER_TYPE + Keyword Args: + cancelOrderId (int): Cancel order by orderId + cancelOrigClientOrderId (int): Cancel order by clientOrderId. + cancelNewClientOrderId (str): New ID for the canceled order. Automatically generated if not sent + timeInForce (str): Time in force. + price (float): Price. + quantity (float): Quantity. + quoteOrderQty (float): Quote order quantity. + newClientOrderId (str): New client order id. + newOrderRespType (str): New order response type. + stopPrice (float): Stop price. + trailingDelta (float): Trailing delta. + icebergQty (float): Iceberg quantity. + strategyId (int): Strategy id. + strategyType (int): Strategy type. + selfTradePreventionMode (str): Self trade prevention mode. + recvWindow (int): Recv window. + + Message Sent: + + .. code-block:: json + + { + "id": "99de1036-b5e2-4e0f-9b5c-13d751c93a1a", + "method": "order.cancelReplace", + "params": { + "symbol": "BTCUSDT", + "cancelReplaceMode": "ALLOW_FAILURE", + "cancelOrigClientOrderId": "4d96324ff9d44481926157", + "side": "SELL", + "type": "LIMIT", + "timeInForce": "GTC", + "price": "23416.10000000", + "quantity": "0.00847000", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "7028fdc187868754d25e42c37ccfa5ba2bab1d180ad55d4c3a7e2de643943dc5", + "timestamp": 1660813156900 + } + } + + + Response: + + .. code-block:: json + + { + "id": "b220edfe-f3c4-4a3a-9d13-b35473783a25", + "status": 409, + "error": { + "code": -2021, + "msg": "Order cancel-replace partially failed.", + "data": { + "cancelResult": "SUCCESS", + "newOrderResult": "FAILURE", + "cancelResponse": { + "symbol": "BTCUSDT", + "origClientOrderId": "4d96324ff9d44481926157", + "orderId": 125690984230, + "orderListId": -1, + "clientOrderId": "91fe37ce9e69c90d6358c0", + "price": "23450.00000000", + "origQty": "0.00847000", + "executedQty": "0.00001000", + "cummulativeQuoteQty": "0.23450000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "selfTradePreventionMode": "NONE" + }, + "newOrderResponse": { + "code": -2010, + "msg": "Order would immediately match and take." + } + } + }, + "rateLimits": [ + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 50, + "count": 1 + }, + { + "rateLimitType": "ORDERS", + "interval": "DAY", + "intervalNum": 1, + "limit": 160000, + "count": 1 + }, + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + { + "id": "ce641763-ff74-41ac-b9f7-db7cbe5e93b1", + "status": 409, + "error": { + "code": -2021, + "msg": "Order cancel-replace partially failed.", + "data": { + "cancelResult": "FAILURE", + "newOrderResult": "SUCCESS", + "cancelResponse": { + "code": -2011, + "msg": "Unknown order sent." + }, + "newOrderResponse": { + "symbol": "BTCUSDT", + "orderId": 12569099453, + "orderListId": -1, + "clientOrderId": "bX5wROblo6YeDwa9iTLeyY", + "transactTime": 1660813156959, + "price": "23416.10000000", + "origQty": "0.00847000", + "executedQty": "0.00000000", + "cummulativeQuoteQty": "0.00000000", + "status": "NEW", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "workingTime": 1669693344508, + "fills": [], + "selfTradePreventionMode": "NONE" + } + } + }, + "rateLimits": [ + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 50, + "count": 1 + }, + { + "rateLimitType": "ORDERS", + "interval": "DAY", + "intervalNum": 1, + "limit": 160000, + "count": 1 + }, + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + parameters = { + "symbol": symbol, + "cancelReplaceMode": cancelReplaceMode, + "side": side, + "type": type, + **kwargs, + } + parameters = purge_map(parameters) + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "order.cancelReplace", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + self.send(payload) + + +def get_open_orders(self, **kwargs): + """Current open orders (USER_DATA) + + Keyword Arguments: + symbol (str): Symbol. + recvWindow (int): Recv window. + + Message Sent: + + .. code-block:: json + + { + "id": "55f07876-4f6f-4c47-87dc-43e5fff3f2e7", + "method": "openOrders.status", + "params": { + "symbol": "BTCUSDT", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "d632b3fdb8a81dd44f82c7c901833309dd714fe508772a89b0a35b0ee0c48b89", + "timestamp": 1660813156812 + } + } + + + Response: + + .. code-block:: json + + { + "id": "55f07876-4f6f-4c47-87dc-43e5fff3f2e7", + "status": 200, + "result": [ + { + "symbol": "BTCUSDT", + "orderId": 12569099453, + "orderListId": -1, + "clientOrderId": "4d96324ff9d44481926157", + "price": "23416.10000000", + "origQty": "0.00847000", + "executedQty": "0.00720000", + "cummulativeQuoteQty": "172.43931000", + "status": "PARTIALLY_FILLED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "stopPrice": "0.00000000", + "icebergQty": "0.00000000", + "time": 1660801715639, + "updateTime": 1660801717945, + "isWorking": true, + "workingTime": 1660801715639, + "origQuoteOrderQty": "0.00000000", + "selfTradePreventionMode": "NONE" + } + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 3 + } + ] + } + + """ + + parameters = purge_map(kwargs) + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "openOrders.status", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + self.send(payload) + + +def cancel_open_orders(self, symbol: str, **kwargs): + """Cancel all open orders on a symbol (USER_DATA) + + Arguments: + symbol (str): Symbol. + Keyword Arguments: + recvWindow (int): Recv window. + + Message Sent: + + .. code-block:: json + + { + "id": "778f938f-9041-4b88-9914-efbf64eeacc8", + "method": "openOrders.cancelAll" + "params": { + "symbol": "BTCUSDT", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "773f01b6e3c2c9e0c1d217bc043ce383c1ddd6f0e25f8d6070f2b66a6ceaf3a5", + "timestamp": 1660805557200 + } + } + + + Response: + + .. code-block:: json + + { + "id": "778f938f-9041-4b88-9914-efbf64eeacc8", + "status": 200, + "result": [ + { + "symbol": "BTCUSDT", + "origClientOrderId": "4d96324ff9d44481926157", + "orderId": 12569099453, + "orderListId": -1, + "clientOrderId": "91fe37ce9e69c90d6358c0", + "price": "23416.10000000", + "origQty": "0.00847000", + "executedQty": "0.00001000", + "cummulativeQuoteQty": "0.23416100", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "SELL", + "stopPrice": "0.00000000", + "trailingDelta": 0, + "trailingTime": -1, + "icebergQty": "0.00000000", + "strategyId": 37463720, + "strategyType": 1000000, + "selfTradePreventionMode": "NONE" + }, + { + "orderListId": 19431, + "contingencyType": "OCO", + "listStatusType": "ALL_DONE", + "listOrderStatus": "ALL_DONE", + "listClientOrderId": "iuVNVJYYrByz6C4yGOPPK0", + "transactionTime": 1660803702431, + "symbol": "BTCUSDT", + "orders": [ + { + "symbol": "BTCUSDT", + "orderId": 12569099453, + "clientOrderId": "bX5wROblo6YeDwa9iTLeyY" + }, + { + "symbol": "BTCUSDT", + "orderId": 12569099454, + "clientOrderId": "Tnu2IP0J5Y4mxw3IATBfmW" + } + ], + "orderReports": [ + { + "symbol": "BTCUSDT", + "origClientOrderId": "bX5wROblo6YeDwa9iTLeyY", + "orderId": 12569099453, + "orderListId": 19431, + "clientOrderId": "OFFXQtxVFZ6Nbcg4PgE2DA", + "price": "23450.50000000", + "origQty": "0.00850000", + "executedQty": "0.00000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "STOP_LOSS_LIMIT", + "side": "BUY", + "stopPrice": "23430.00000000", + "selfTradePreventionMode": "NONE" + }, + { + "symbol": "BTCUSDT", + "origClientOrderId": "Tnu2IP0J5Y4mxw3IATBfmW", + "orderId": 12569099454, + "orderListId": 19431, + "clientOrderId": "OFFXQtxVFZ6Nbcg4PgE2DA", + "price": "23400.00000000", + "origQty": "0.00850000", + "executedQty": "0.00000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT_MAKER", + "side": "BUY", + "selfTradePreventionMode": "NONE" + } + ] + } + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + parameters = purge_map({"symbol": symbol, **kwargs}) + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "openOrders.cancelAll", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + self.send(payload) + + +def new_oco_order(self, symbol: str, side: str, price, quantity, **kwargs): + """Place a new OCO Order (TRADE) + Args: + symbol (str): Symbol. + side (str): BUY or SELL. + price (float): Price. + quantity (float): Quantity. + Keyword Arguments: + listClientOrderId (str): A unique id for the entire order list. + limitClientOrderId (str): A unique id for the limit order. + limitIcebergQty (float): Iceberg quantity. + limitStrategyId (int): Strategy id. + limitStrategyType (int): Strategy type. + stopPrice (float): Stop price. + trailingDelta (float): Trailing delta. + stopClientOrderId (str): A unique id for the stop loss order. + stopLimitPrice (float): Stop limit price. + stopLimitTimeInForce (str): GTC or FOK. + stopIcebergQty (float): Iceberg quantity. + stopStrategyId (int): Strategy id. + stopStrategyType (int): Strategy type. + newOrderRespType (str): ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK. + selfTradePreventionMode (str): NONE, EXPIRE_TAKER, EXPIRE_MAKER or EXPIRE_BOTH. + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "56374a46-3061-486b-a311-99ee972eb648", + "method": "orderList.place", + "params": { + "symbol": "BTCUSDT", + "side": "SELL", + "price": "23420.00000000", + "quantity": "0.00650000", + "stopPrice": "23410.00000000", + "stopLimitPrice": "23405.00000000", + "stopLimitTimeInForce": "GTC", + "newOrderRespType": "RESULT", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "6689c2a36a639ff3915c2904871709990ab65f3c7a9ff13857558fd350315c35", + "timestamp": 1660801713767 + } + } + + + Response: + + .. code-block:: json + + { + "id": "57833dc0-e3f2-43fb-ba20-46480973b0aa", + "status": 200, + "result": { + "orderListId": 1274512, + "contingencyType": "OCO", + "listStatusType": "EXEC_STARTED", + "listOrderStatus": "EXECUTING", + "listClientOrderId": "08985fedd9ea2cf6b28996", + "transactionTime": 1660801713793, + "symbol": "BTCUSDT", + "orders": [ + { + "symbol": "BTCUSDT", + "orderId": 12569138901, + "clientOrderId": "BqtFCj5odMoWtSqGk2X9tU" + }, + { + "symbol": "BTCUSDT", + "orderId": 12569138902, + "clientOrderId": "jLnZpj5enfMXTuhKB1d0us" + } + ], + "orderReports": [ + { + "symbol": "BTCUSDT", + "orderId": 12569138901, + "orderListId": 1274512, + "clientOrderId": "BqtFCj5odMoWtSqGk2X9tU", + "transactTime": 1660801713793, + "price": "23410.00000000", + "origQty": "0.00650000", + "executedQty": "0.00000000", + "cummulativeQuoteQty": "0.00000000", + "status": "NEW", + "timeInForce": "GTC", + "type": "STOP_LOSS_LIMIT", + "side": "SELL", + "stopPrice": "23405.00000000", + "workingTime": -1, + "selfTradePreventionMode": "NONE" + }, + { + "symbol": "BTCUSDT", + "orderId": 12569138902, + "orderListId": 1274512, + "clientOrderId": "jLnZpj5enfMXTuhKB1d0us", + "transactTime": 1660801713793, + "price": "23420.00000000", + "origQty": "0.00650000", + "executedQty": "0.00000000", + "cummulativeQuoteQty": "0.00000000", + "status": "NEW", + "timeInForce": "GTC", + "type": "LIMIT_MAKER", + "side": "SELL", + "workingTime": 1660801713793, + "selfTradePreventionMode": "NONE" + } + ] + }, + "rateLimits": [ + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 50, + "count": 2 + }, + { + "rateLimitType": "ORDERS", + "interval": "DAY", + "intervalNum": 1, + "limit": 160000, + "count": 2 + }, + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + parameters = { + "symbol": symbol, + "side": side, + "price": price, + "quantity": quantity, + **kwargs, + } + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "orderList.place", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + self.send(payload) + + +def get_oco_order(self, **kwargs): + """Get OCO order + + Keyword Args: + orderListId (int): Order list id. + origClientOrderId (str): Original client order id. + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "b53fd5ff-82c7-4a04-bd64-5f9dc42c2100", + "method": "orderList.status", + "params": { + "symbol": "BTCUSDT", + "origClientOrderId": "08985fedd9ea2cf6b28996" + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "d12f4e8892d46c0ddfbd43d556ff6d818581b3be22a02810c2c20cb719aed6a4", + "timestamp": 1660801713965 + } + } + + + Response: + + .. code-block:: json + + { + "id": "b53fd5ff-82c7-4a04-bd64-5f9dc42c2100", + "status": 200, + "result": { + "orderListId": 1274512, + "contingencyType": "OCO", + "listStatusType": "EXEC_STARTED", + "listOrderStatus": "EXECUTING", + "listClientOrderId": "08985fedd9ea2cf6b28996", + "transactionTime": 1660801713793, + "symbol": "BTCUSDT", + "orders": [ + { + "symbol": "BTCUSDT", + "orderId": 12569138901, + "clientOrderId": "BqtFCj5odMoWtSqGk2X9tU" + }, + { + "symbol": "BTCUSDT", + "orderId": 12569138902, + "clientOrderId": "jLnZpj5enfMXTuhKB1d0us" + } + ] + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 2 + } + ] + } + + """ + + parameters = {**kwargs} + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "orderList.status", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + self.send(payload) + + +def cancel_oco_order(self, symbol: str, **kwargs): + """Cancel OCO order + + Args: + symbol (str): Symbol to place the order on. + Keyword Args: + orderListId (int): Order list id. + listClientOrderId (str): List client order id. + newClientOrderId (str): New client order id. + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "c5899911-d3f4-47ae-8835-97da553d27d0", + "method": "orderList.cancel", + "params": { + "symbol": "BTCUSDT", + "orderListId": 1274512, + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "4973f4b2fee30bf6d45e4a973e941cc60fdd53c8dd5a25edeac96f5733c0ccee", + "timestamp": 1660801720210 + } + } + + + Response: + + .. code-block:: json + + { + "id": "c5899911-d3f4-47ae-8835-97da553d27d0", + "status": 200, + "result": { + "orderListId": 1274512, + "contingencyType": "OCO", + "listStatusType": "ALL_DONE", + "listOrderStatus": "ALL_DONE", + "listClientOrderId": "6023531d7edaad348f5aff", + "transactionTime": 1660801720215, + "symbol": "BTCUSDT", + "orders": [ + { + "symbol": "BTCUSDT", + "orderId": 12569138901, + "clientOrderId": "BqtFCj5odMoWtSqGk2X9tU" + }, + { + "symbol": "BTCUSDT", + "orderId": 12569138902, + "clientOrderId": "jLnZpj5enfMXTuhKB1d0us" + } + ], + "orderReports": [ + { + "symbol": "BTCUSDT", + "orderId": 12569138901, + "orderListId": 1274512, + "clientOrderId": "BqtFCj5odMoWtSqGk2X9tU", + "transactTime": 1660801720215, + "price": "23410.00000000", + "origQty": "0.00650000", + "executedQty": "0.00000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "STOP_LOSS_LIMIT", + "side": "SELL", + "stopPrice": "23405.00000000", + "selfTradePreventionMode": "NONE" + }, + { + "symbol": "BTCUSDT", + "orderId": 12569138902, + "orderListId": 1274512, + "clientOrderId": "jLnZpj5enfMXTuhKB1d0us", + "transactTime": 1660801720215, + "price": "23420.00000000", + "origQty": "0.00650000", + "executedQty": "0.00000000", + "cummulativeQuoteQty": "0.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "type": "LIMIT_MAKER", + "side": "SELL", + "selfTradePreventionMode": "NONE" + } + ] + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + parameters = {"symbol": symbol, **kwargs} + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "orderList.cancel", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + self.send(payload) + + +def get_open_oco_orders(self, **kwargs): + """Get open OCO orders + + Keyword Args: + recvWindow (int): Recv window. + + Message sent: + + .. code-block:: json + + { + "id": "3a4437e2-41a3-4c19-897c-9cadc5dce8b6", + "method": "openOrderLists.status", + "params": { + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", + "signature": "1bea8b157dd78c3da30359bddcd999e4049749fe50b828e620e12f64e8b433c9", + "timestamp": 1660801713831 + } + } + + + Response: + + .. code-block:: json + + { + "id": "3a4437e2-41a3-4c19-897c-9cadc5dce8b6", + "status": 200, + "result": [ + { + "orderListId": 0, + "contingencyType": "OCO", + "listStatusType": "EXEC_STARTED", + "listOrderStatus": "EXECUTING", + "listClientOrderId": "08985fedd9ea2cf6b28996", + "transactionTime": 1660801713793, + "symbol": "BTCUSDT", + "orders": [ + { + "symbol": "BTCUSDT", + "orderId": 4, + "clientOrderId": "CUhLgTXnX5n2c0gWiLpV4d" + }, + { + "symbol": "BTCUSDT", + "orderId": 5, + "clientOrderId": "1ZqG7bBuYwaF4SU8CwnwHm" + } + ] + } + ], + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 3 + } + ] + } + + """ + + parameters = {**kwargs} + + payload = { + "id": parameters.pop("id", get_uuid()), + "method": "openOrderLists.status", + "params": websocket_api_signature(self.api_key, self.api_secret, parameters), + } + self.send(payload) diff --git a/binance/websocket/spot/websocket_api/_user_data.py b/binance/websocket/spot/websocket_api/_user_data.py new file mode 100644 index 00000000..a5cb04b3 --- /dev/null +++ b/binance/websocket/spot/websocket_api/_user_data.py @@ -0,0 +1,163 @@ +from binance.lib.utils import get_uuid + + +def user_data_start(self, id=None): + """Start user data stream (USER_STREAM) + + Args: + id (str): A unique id for the request + + Message sent: + + .. code-block:: json + + { + "id": "d3df8a61-98ea-4fe0-8f4e-0fcea5d418b0", + "method": "userDataStream.start", + "params": { + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" + } + } + + Response: + + .. code-block:: json + + { + "id": "d3df8a61-98ea-4fe0-8f4e-0fcea5d418b0", + "status": 200, + "result": { + "listenKey": "xs0mRXdAKlIPDRFrlPcw0qI41Eh3ixNntmymGyhrhgqo7L6FuLaWArTD7RLP" + }, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + + """ + + if not id: + id = get_uuid() + + payload = { + "id": id, + "method": "userDataStream.start", + "params": {"apiKey": self.api_key}, + } + + self.send(payload) + + +def user_data_ping(self, listenKey: str, id=None): + """Keepalive a user data stream to prevent a time out. + + Args: + listenKey (str): The listen key from the user data stream + id (str): A unique id for the request + + Message sent: + + .. code-block:: json + + { + "id": "815d5fce-0880-4287-a567-80badf004c74", + "method": "userDataStream.ping", + "params": { + "listenKey": "xs0mRXdAKlIPDRFrlPcw0qI41Eh3ixNntmymGyhrhgqo7L6FuLaWArTD7RLP", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" + } + } + + + Response: + + .. code-block:: json + + { + "id": "815d5fce-0880-4287-a567-80badf004c74", + "status": 200, + "response": {}, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + + """ + + if not id: + id = get_uuid() + + payload = { + "id": id, + "method": "userDataStream.ping", + "params": {"apiKey": self.api_key, "listenKey": listenKey}, + } + + self.send(payload) + + +def user_data_stop(self, listenKey: str, id=None): + """Stop user data stream + + Args: + listenKey (str): The listen key from the user data stream + id (str): A unique id for the request + + Message sent: + + .. code-block:: json + + { + "id": "819e1b1b-8c06-485b-a13e-131326c69599", + "method": "userDataStream.stop", + "params": { + "listenKey": "xs0mRXdAKlIPDRFrlPcw0qI41Eh3ixNntmymGyhrhgqo7L6FuLaWArTD7RLP", + "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" + } + } + + Response: + + .. code-block:: json + + { + "id": "819e1b1b-8c06-485b-a13e-131326c69599", + "status": 200, + "response": {}, + "rateLimits": [ + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "count": 1 + } + ] + } + + """ + + if not id: + id = get_uuid() + + payload = { + "id": id, + "method": "userDataStream.stop", + "params": {"apiKey": self.api_key, "listenKey": listenKey}, + } + + self.send(payload) diff --git a/binance/websocket/spot/websocket_client.py b/binance/websocket/spot/websocket_client.py deleted file mode 100644 index e8e98c64..00000000 --- a/binance/websocket/spot/websocket_client.py +++ /dev/null @@ -1,213 +0,0 @@ -from binance.websocket.websocket_client import BinanceWebsocketClient -from binance.error import ParameterRequiredError - - -class SpotWebsocketClient(BinanceWebsocketClient): - def __init__(self, stream_url="wss://stream.binance.com:9443"): - super().__init__(stream_url) - - def agg_trade(self, symbol: str, id: int, callback, **kwargs): - """Aggregate Trade Streams - - The Aggregate Trade Streams push trade information that is aggregated for a single taker order. - - Stream Name: @aggTrade - - Update Speed: Real-time - """ - if isinstance(symbol, list): - symbol = ["{}@aggTrade".format(x.lower()) for x in symbol] - else: - symbol = "{}@aggTrade".format(symbol.lower()) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def trade(self, symbol: str, id: int, callback, **kwargs): - """Trade Streams - - The Trade Streams push raw trade information; each trade has a unique buyer and seller. - - Stream Name: @trade - - Update Speed: Real-time - """ - if isinstance(symbol, list): - symbol = ["{}@trade".format(x.lower()) for x in symbol] - else: - symbol = "{}@trade".format(symbol.lower()) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def kline(self, symbol: str, id: int, interval: str, callback, **kwargs): - """Kline/Candlestick Streams - - The Kline/Candlestick Stream push updates to the current klines/candlestick every second. - - Stream Name: @kline_ - - interval: - m -> minutes; h -> hours; d -> days; w -> weeks; M -> months - - - 1m - - 3m - - 5m - - 15m - - 30m - - 1h - - 2h - - 4h - - 6h - - 8h - - 12h - - 1d - - 3d - - 1w - - 1M - - Update Speed: 2000ms - """ - if isinstance(symbol, list): - symbol = ["{}@kline_{}".format(x.lower(), interval) for x in symbol] - else: - symbol = "{}@kline_{}".format(symbol.lower(), interval) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def mini_ticker(self, id: int, callback, symbol=None, **kwargs): - """Individual symbol or all symbols mini ticker - - 24hr rolling window mini-ticker statistics. - These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs - - Stream Name: @miniTicker or - Stream Name: !miniTicker@arr - - Update Speed: 1000ms - """ - - if symbol is None: - self.live_subscribe("!miniTicker@arr", id, callback, **kwargs) - else: - if isinstance(symbol, list): - symbol = ["{}@miniTicker".format(x.lower()) for x in symbol] - else: - symbol = "{}@miniTicker".format(symbol.lower()) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def ticker(self, id: int, callback, symbol=None, **kwargs): - """Individual symbol or all symbols ticker - - 24hr rolling window ticker statistics for a single symbol. - These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. - - Stream Name: @ticker or - Stream Name: !ticker@arr - - Update Speed: 1000ms - """ - - if symbol is None: - self.live_subscribe("!ticker@arr", id, callback, **kwargs) - else: - if isinstance(symbol, list): - symbol = ["{}@ticker".format(x.lower()) for x in symbol] - else: - symbol = "{}@ticker".format(symbol.lower()) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def book_ticker(self, id: int, callback, symbol=None, **kwargs): - """Individual symbol book ticker - - Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. - - Stream Name: @bookTicker - - Update Speed: realtime - """ - - if symbol is None: - raise ParameterRequiredError(["symbol"]) - - if isinstance(symbol, list): - symbol = ["{}@bookTicker".format(x.lower()) for x in symbol] - else: - symbol = "{}@bookTicker".format(symbol.lower()) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def partial_book_depth( - self, symbol: str, id: int, level, speed, callback, **kwargs - ): - """Partial Book Depth Streams - - Top bids and asks, Valid are 5, 10, or 20. - - Stream Names: @depth OR @depth@100ms. - - Update Speed: 1000ms or 100ms - """ - - if isinstance(symbol, list): - symbol = ["{}@depth{}@{}ms".format(x.lower(), level, speed) for x in symbol] - else: - symbol = "{}@depth{}@{}ms".format(symbol.lower(), level, speed) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def rolling_window_ticker( - self, symbol: str, windowSize: str, id: int, callback, **kwargs - ): - """Rolling window ticker statistics for a single symbol, computed over multiple windows. - - Stream Name: @ticker_ - - Window Sizes: 1h,4h - - Update Speed: 1000ms - - Note: This stream is different from the @ticker stream. The open time "O" always starts on a minute, while the closing time "C" is the current time of the update. As such, the effective window might be up to 59999ms wider that . - """ - - if isinstance(symbol, list): - symbol = ["{}@ticker_{}".format(x.lower(), windowSize) for x in symbol] - else: - symbol = "{}@ticker_{}".format(symbol.lower(), windowSize) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def rolling_window_ticker_all_symbols( - self, windowSize: str, id: int, callback, **kwargs - ): - """All Market Rolling Window Statistics Streams - - Rolling window ticker statistics for all market symbols, computed over multiple windows. Note that only tickers that have changed will be present in the array. - - Stream Name: !ticker_@arr - - Window Size: 1h,4h - - Update Speed: 1000ms - """ - self.live_subscribe("!ticker_{}@arr".format(windowSize), id, callback, **kwargs) - - def diff_book_depth(self, symbol: str, id: int, speed, callback, **kwargs): - """Diff. Depth Stream - - Stream Name: @depth OR @depth@100ms - - Update Speed: 1000ms or 100ms - - Order book price and quantity depth updates used to locally manage an order book. - """ - if isinstance(symbol, list): - symbol = ["{}@depth@{}ms".format(x.lower(), speed) for x in symbol] - else: - symbol = "{}@depth@{}ms".format(symbol.lower(), speed) - - self.live_subscribe(symbol, id, callback, **kwargs) - - def user_data(self, listen_key: str, id: int, callback, **kwargs): - """Listen to user data by using the provided listen_key""" - self.live_subscribe(listen_key, id, callback, **kwargs) diff --git a/binance/websocket/spot/websocket_stream.py b/binance/websocket/spot/websocket_stream.py new file mode 100644 index 00000000..330df5ce --- /dev/null +++ b/binance/websocket/spot/websocket_stream.py @@ -0,0 +1,204 @@ +from binance.websocket.websocket_client import BinanceWebsocketClient + + +class SpotWebsocketStreamClient(BinanceWebsocketClient): + ACTION_SUBSCRIBE = "SUBSCRIBE" + ACTION_UNSUBSCRIBE = "UNSUBSCRIBE" + + def __init__( + self, + stream_url="wss://stream.binance.com:9443", + on_message=None, + on_open=None, + on_close=None, + on_error=None, + on_ping=None, + on_pong=None, + is_combined=False, + ): + if is_combined: + stream_url = stream_url + "/stream" + else: + stream_url = stream_url + "/ws" + super().__init__( + stream_url, + on_message=on_message, + on_open=on_open, + on_close=on_close, + on_error=on_error, + on_ping=on_ping, + on_pong=on_pong, + ) + + def agg_trade(self, symbol: str, id=None, action=None, **kwargs): + """Aggregate Trade Streams + + The Aggregate Trade Streams push trade information that is aggregated for a single taker order. + + Stream Name: @aggTrade + + Update Speed: Real-time + """ + stream_name = "{}@aggTrade".format(symbol.lower()) + + self.send_message_to_server(stream_name, action=action, id=id) + + def trade(self, symbol: str, id=None, action=None, **kwargs): + """Trade Streams + + The Trade Streams push raw trade information; each trade has a unique buyer and seller. + + Stream Name: @trade + + Update Speed: Real-time + """ + + stream_name = "{}@trade".format(symbol.lower()) + + self.send_message_to_server(stream_name, action=action, id=id) + + def kline(self, symbol: str, interval: str, id=None, action=None): + """Kline/Candlestick Streams + + The Kline/Candlestick Stream push updates to the current klines/candlestick every second. + + Stream Name: @kline_ + + interval: + m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + + - 1m + - 3m + - 5m + - 15m + - 30m + - 1h + - 2h + - 4h + - 6h + - 8h + - 12h + - 1d + - 3d + - 1w + - 1M + + Update Speed: 2000ms + """ + stream_name = "{}@kline_{}".format(symbol.lower(), interval) + + self.send_message_to_server(stream_name, action=action, id=id) + + def mini_ticker(self, symbol=None, id=None, action=None, **kwargs): + """Individual symbol or all symbols mini ticker + + 24hr rolling window mini-ticker statistics. + These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs + + Stream Name: @miniTicker or + Stream Name: !miniTicker@arr + + Update Speed: 1000ms + """ + + if symbol is None: + stream_name = "!miniTicker@arr" + else: + stream_name = "{}@miniTicker".format(symbol.lower()) + + self.send_message_to_server(stream_name, action=action, id=id) + + def ticker(self, symbol=None, id=None, action=None, **kwargs): + """Individual symbol or all symbols ticker + + 24hr rolling window ticker statistics for a single symbol. + These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. + + Stream Name: @ticker or + Stream Name: !ticker@arr + + Update Speed: 1000ms + """ + + if symbol is None: + stream_name = "!ticker@arr" + else: + stream_name = "{}@ticker".format(symbol.lower()) + self.send_message_to_server(stream_name, action=action, id=id) + + def book_ticker(self, symbol, id=None, action=None, **kwargs): + """Individual symbol book ticker + + Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. + + Stream Name: @bookTicker + + Update Speed: realtime + """ + + self.send_message_to_server( + "{}@bookTicker".format(symbol.lower()), action=action, id=id + ) + + def partial_book_depth( + self, symbol: str, level=5, speed=1000, id=None, action=None, **kwargs + ): + """Partial Book Depth Streams + + Top bids and asks, Valid are 5, 10, or 20. + + Stream Names: @depth OR @depth@100ms. + + Update Speed: 1000ms or 100ms + """ + self.send_message_to_server( + "{}@depth{}@{}ms".format(symbol.lower(), level, speed), id=id, action=action + ) + + def rolling_window_ticker(self, symbol: str, windowSize: str, id=None, action=None): + """Rolling window ticker statistics for a single symbol, computed over multiple windows. + + Stream Name: @ticker_ + + Window Sizes: 1h, 4h, 1d + + Update Speed: 1000ms + + Note: This stream is different from the @ticker stream. The open time "O" always starts on a minute, while the closing time "C" is the current time of the update. As such, the effective window might be up to 59999ms wider that . + """ + self.send_message_to_server( + "{}@ticker_{}".format(symbol.lower(), windowSize), id=id, action=action + ) + + def rolling_window_ticker_all_symbols(self, windowSize: str, id=None, action=None): + """All Market Rolling Window Statistics Streams + + Rolling window ticker statistics for all market symbols, computed over multiple windows. Note that only tickers that have changed will be present in the array. + + Stream Name: !ticker_@arr + + Window Size: 1h, 4h, 1d + + Update Speed: 1000ms + """ + self.send_message_to_server( + "!ticker_{}@arr".format(windowSize), id=id, action=action + ) + + def diff_book_depth(self, symbol: str, speed=1000, id=None, action=None, **kwargs): + """Diff. Depth Stream + + Stream Name: @depth OR @depth@100ms + + Update Speed: 1000ms or 100ms + + Order book price and quantity depth updates used to locally manage an order book. + """ + + self.send_message_to_server( + "{}@depth@{}ms".format(symbol.lower(), speed), action=action, id=id + ) + + def user_data(self, listen_key: str, id=None, action=None, **kwargs): + """Listen to user data by using the provided listen_key""" + self.send_message_to_server(listen_key, action=action, id=id) diff --git a/binance/websocket/websocket_client.py b/binance/websocket/websocket_client.py index 51dba550..cba6d44d 100644 --- a/binance/websocket/websocket_client.py +++ b/binance/websocket/websocket_client.py @@ -1,68 +1,117 @@ import json -from twisted.internet import reactor +import logging +from binance.lib.utils import get_timestamp from binance.websocket.binance_socket_manager import BinanceSocketManager -class BinanceWebsocketClient(BinanceSocketManager): - def __init__(self, stream_url): - super().__init__(stream_url) +class BinanceWebsocketClient: + def __init__( + self, + stream_url, + on_message=None, + on_open=None, + on_close=None, + on_error=None, + on_ping=None, + on_pong=None, + logger=None, + ): + if not logger: + logger = logging.getLogger(__name__) + self.logger = logger + self.socket_manager = self._initialize_socket( + stream_url, + on_message, + on_open, + on_close, + on_error, + on_ping, + on_pong, + logger, + ) - def stop(self): - try: - self.close() - finally: - reactor.callFromThread(reactor.stop) + # start the thread + self.socket_manager.start() + self.logger.debug("Binance WebSocket Client started.") - def _single_stream(self, stream): - if isinstance(stream, str): - return True - elif isinstance(stream, list): - return False - else: - raise ValueError("Invalid stream name, expect string or array") + def _initialize_socket( + self, + stream_url, + on_message, + on_open, + on_close, + on_error, + on_ping, + on_pong, + logger, + ): + return BinanceSocketManager( + stream_url, + on_message=on_message, + on_open=on_open, + on_close=on_close, + on_error=on_error, + on_ping=on_ping, + on_pong=on_pong, + logger=logger, + ) - def live_subscribe(self, stream, id, callback, **kwargs): - """live subscribe websocket - Connect to the server - - SPOT: wss://stream.binance.com:9443/ws - - SPOT testnet : wss://testnet.binance.vision/ws + def send(self, message: dict): + self.socket_manager.send_message(json.dumps(message)) - and sending the subscribe message, e.g. + def send_message_to_server(self, message, action=None, id=None): + if not id: + id = get_timestamp() - {"method": "SUBSCRIBE","params":["btcusdt@miniTicker"],"id": 100} + if action != self.ACTION_UNSUBSCRIBE: + return self.subscribe(message, id=id) + return self.unsubscribe(message, id=id) - """ - combined = False + def subscribe(self, stream, id=None): + if not id: + id = get_timestamp() if self._single_stream(stream): stream = [stream] - else: - combined = True + json_msg = json.dumps({"method": "SUBSCRIBE", "params": stream, "id": id}) + self.socket_manager.send_message(json_msg) + + def unsubscribe(self, stream: str, id=None): + if not id: + id = get_timestamp() - data = {"method": "SUBSCRIBE", "params": stream, "id": id} + if not self._single_stream(stream): + raise ValueError("Invalid stream name, expect a string") - data.update(**kwargs) - payload = json.dumps(data, ensure_ascii=False).encode("utf8") - stream_name = "-".join(stream) - return self._start_socket( - stream_name, payload, callback, is_combined=combined, is_live=True + stream = [stream] + self.socket_manager.send_message( + json.dumps({"method": "UNSUBSCRIBE", "params": stream, "id": id}) ) - def instant_subscribe(self, stream, callback, **kwargs): - """Instant subscribe, e.g. - wss://stream.binance.com:9443/ws/btcusdt@bookTicker - wss://stream.binance.com:9443/stream?streams=btcusdt@bookTicker/bnbusdt@bookTicker + def ping(self): + self.logger.debug("Sending ping to Binance WebSocket Server") + self.socket_manager.ping() - """ - combined = False - if not self._single_stream(stream): - combined = True - stream = "/".join(stream) + def stop(self, id=None): + self.socket_manager.close() + self.socket_manager.join() - data = {"method": "SUBSCRIBE", "params": stream} + def list_subscribe(self, id=None): + """sending the list subscription message, e.g. - data.update(**kwargs) - payload = json.dumps(data, ensure_ascii=False).encode("utf8") - stream_name = "-".join(stream) - return self._start_socket( - stream_name, payload, callback, is_combined=combined, is_live=False + {"method": "LIST_SUBSCRIPTIONS","id": 100} + + """ + + if not id: + id = get_timestamp() + self.socket_manager.send_message( + json.dumps({"method": "LIST_SUBSCRIPTIONS", "id": id}) ) + + def _single_stream(self, stream): + if isinstance(stream, str): + return True + elif isinstance(stream, list): + return False + else: + raise ValueError("Invalid stream name, expect string or array") diff --git a/docs/source/CHANGELOG.rst b/docs/source/CHANGELOG.rst index bf7012a9..6ce1aecb 100644 --- a/docs/source/CHANGELOG.rst +++ b/docs/source/CHANGELOG.rst @@ -2,6 +2,54 @@ Changelog ========= +3.0.0rc1 - 2023-02-10 +--------------------- + +Changed +^^^^^^^ + +* Redesign of Websocket part. Please consult ``README.md`` for details on its new usage. + +Added +^^^^^ + +* Add Websocket API + +2.0.0 - 2023-01-18 +------------------ + +Added +^^^^^ + +* New endpoints for wallet + + * ``GET /sapi/v1/capital/contract/convertible-coins``` Get a user's auto-conversion settings in deposit/withdrawal + * ``POST /sapi/v1/capital/contract/convertible-coins`` User can use it to turn on or turn off the BUSD auto-conversion from/to a specific stable coin. +* New endpoints for Sub-Account + + * ``GET /v1/managed-subaccount/queryTransLogForInvestor`` Investor can use this api to query managed sub account transfer log + * ``GET /v1/managed-subaccount/queryTransLogForTradeParent`` Trading team can use this api to query managed sub account transfer log +* New endpoints for Loan + + * ``GET /sapi/v1/loan/vip/ongoing/orders`` Get VIP Loan Ongoing Orders + * ``POST /sapi/v1/loan/vip/repay`` VIP Loan Repay + * ``GET /sapi/v1/loan/vip/repay/history`` Get VIP Loan Repayment History + * ``GET /sapi/v1/loan/vip/collateral/account`` Check Locked Value of VIP Collateral Account + * ``GET /sapi/v1/loan/loanable/data`` Get Loanable Assets Data + * ``GET /sapi/v1/loan/collateral/data`` Get Collateral Assets Data + * ``GET /sapi/v1/loan/repay/collateral/rate`` Check Collateral Repay Rate + * ``POST /sapi/v1/loan/customize/margin_call`` Customize margin call for ongoing orders only. +* New endpoints for Wallet + + * ``GET /sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage`` Get Cloud-Mining payment and refund history + * ``POST /sapi/v1/asset/convert-transfer`` BUSD Convert + * ``GET /sapi/v1/asset/convert-transfer/queryByPage`` BUSD Convert History +* New endpoint for gift card + + * ``POST /sapi/v1/giftcard/buyCode`` Create a dual-token gift card + * ``GET /sapi/v1/giftcard/buyCode/token-limit`` Fetch Token Limit + + 2.0.0rc2 - 2022-11-29 --------------------- diff --git a/docs/source/binance.spot.blvt.rst b/docs/source/binance.spot.blvt.rst index 4cd669f6..e19dbfdf 100644 --- a/docs/source/binance.spot.blvt.rst +++ b/docs/source/binance.spot.blvt.rst @@ -3,24 +3,24 @@ Blvt Endpoints Get BLVT Info (MARKET_DATA) --------------------------- -.. autofunction:: binance.spot.blvt.blvt_info +.. autofunction:: binance.spot.Spot.blvt_info Subscribe BLVT (USER_DATA) -------------------------- -.. autofunction:: binance.spot.blvt.subscribe_blvt +.. autofunction:: binance.spot.Spot.subscribe_blvt Query Subscription Record (USER_DATA) ------------------------------------- -.. autofunction:: binance.spot.blvt.subscription_record +.. autofunction:: binance.spot.Spot.subscription_record Redeem BLVT (USER_DATA) ----------------------- -.. autofunction:: binance.spot.blvt.redeem_blvt +.. autofunction:: binance.spot.Spot.redeem_blvt Query Redemption Record (USER_DATA) ----------------------------------- -.. autofunction:: binance.spot.blvt.redemption_record +.. autofunction:: binance.spot.Spot.redemption_record Get BLVT User Limit Info --------------------------- -.. autofunction:: binance.spot.blvt.user_limit_info +.. autofunction:: binance.spot.Spot.user_limit_info diff --git a/docs/source/binance.spot.bswap.rst b/docs/source/binance.spot.bswap.rst index 0dc4e8d3..62a53640 100644 --- a/docs/source/binance.spot.bswap.rst +++ b/docs/source/binance.spot.bswap.rst @@ -3,56 +3,56 @@ Bswap Endpoints List All Swap Pools (MARKET_DATA) --------------------------------- -.. autofunction:: binance.spot.bswap.bswap_pools +.. autofunction:: binance.spot.Spot.bswap_pools Get liquidity information of a pool (USER_DATA) ----------------------------------------------- -.. autofunction:: binance.spot.bswap.bswap_liquidity +.. autofunction:: binance.spot.Spot.bswap_liquidity Add Liquidity (TRADE) --------------------- -.. autofunction:: binance.spot.bswap.bswap_liquidity_add +.. autofunction:: binance.spot.Spot.bswap_liquidity_add Remove Liquidity (TRADE) ------------------------ -.. autofunction:: binance.spot.bswap.bswap_liquidity_remove +.. autofunction:: binance.spot.Spot.bswap_liquidity_remove Get Liquidity Operation Record (USER_DATA) ------------------------------------------ -.. autofunction:: binance.spot.bswap.bswap_liquidity_operation_record +.. autofunction:: binance.spot.Spot.bswap_liquidity_operation_record Request Quote (USER_DATA) ------------------------- -.. autofunction:: binance.spot.bswap.bswap_request_quote +.. autofunction:: binance.spot.Spot.bswap_request_quote Swap (TRADE) ------------ -.. autofunction:: binance.spot.bswap.bswap_swap +.. autofunction:: binance.spot.Spot.bswap_swap Get Swap History (USER_DATA) ---------------------------- -.. autofunction:: binance.spot.bswap.bswap_swap_history +.. autofunction:: binance.spot.Spot.bswap_swap_history Get Pool Configure (USER_DATA) ------------------------------ -.. autofunction:: binance.spot.bswap.bswap_pool_configure +.. autofunction:: binance.spot.Spot.bswap_pool_configure Add Liquidity Preview (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.bswap.bswap_add_liquidity_preview +.. autofunction:: binance.spot.Spot.bswap_add_liquidity_preview Remove Liquidity Preview (USER_DATA) ------------------------------------ -.. autofunction:: binance.spot.bswap.bswap_remove_liquidity_preview +.. autofunction:: binance.spot.Spot.bswap_remove_liquidity_preview Get Unclaimed Rewards Record (USER_DATA) ---------------------------------------- -.. autofunction:: binance.spot.bswap.bswap_unclaimed_rewards +.. autofunction:: binance.spot.Spot.bswap_unclaimed_rewards Claim rewards (TRADE) --------------------- -.. autofunction:: binance.spot.bswap.bswap_claim_rewards +.. autofunction:: binance.spot.Spot.bswap_claim_rewards Get Claimed History (USER_DATA) ------------------------------- -.. autofunction:: binance.spot.bswap.bswap_claimed_rewards \ No newline at end of file +.. autofunction:: binance.spot.Spot.bswap_claimed_rewards diff --git a/docs/source/binance.spot.c2c.rst b/docs/source/binance.spot.c2c.rst index 5464080e..0301c491 100644 --- a/docs/source/binance.spot.c2c.rst +++ b/docs/source/binance.spot.c2c.rst @@ -3,4 +3,4 @@ C2C Endpoints Get C2C Trade History (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.c2c.c2c_trade_history +.. autofunction:: binance.spot.Spot.c2c_trade_history diff --git a/docs/source/binance.spot.convert.rst b/docs/source/binance.spot.convert.rst index 266c8dea..b30ad0ce 100644 --- a/docs/source/binance.spot.convert.rst +++ b/docs/source/binance.spot.convert.rst @@ -4,4 +4,4 @@ Convert Endpoints Get Convert Trade History (USER_DATA) ------------------------------------- -.. autofunction:: binance.spot.convert.convert_trade_history +.. autofunction:: binance.spot.Spot.convert_trade_history diff --git a/docs/source/binance.spot.data_stream.rst b/docs/source/binance.spot.data_stream.rst index 9f130113..1358928d 100644 --- a/docs/source/binance.spot.data_stream.rst +++ b/docs/source/binance.spot.data_stream.rst @@ -3,36 +3,36 @@ Data Stream Endpoints Create a ListenKey (USER_STREAM) -------------------------------- -.. autofunction:: binance.spot.data_stream.new_listen_key +.. autofunction:: binance.spot.Spot.new_listen_key Ping/Keep-alive a ListenKey (USER_STREAM) ----------------------------------------- -.. autofunction:: binance.spot.data_stream.renew_listen_key +.. autofunction:: binance.spot.Spot.renew_listen_key Close a ListenKey (USER_STREAM) ------------------------------- -.. autofunction:: binance.spot.data_stream.close_listen_key +.. autofunction:: binance.spot.Spot.close_listen_key Create a margin ListenKey (USER_STREAM) --------------------------------------- -.. autofunction:: binance.spot.data_stream.new_margin_listen_key +.. autofunction:: binance.spot.Spot.new_margin_listen_key Renew a margin ListenKey (USER_STREAM) -------------------------------------- -.. autofunction:: binance.spot.data_stream.renew_margin_listen_key +.. autofunction:: binance.spot.Spot.renew_margin_listen_key Close a margin ListenKey (USER_STREAM) -------------------------------------- -.. autofunction:: binance.spot.data_stream.close_margin_listen_key +.. autofunction:: binance.spot.Spot.close_margin_listen_key Create an isolated margin ListenKey (USER_STREAM) ------------------------------------------------- -.. autofunction:: binance.spot.data_stream.new_isolated_margin_listen_key +.. autofunction:: binance.spot.Spot.new_isolated_margin_listen_key Renew an isolated ListenKey (USER_STREAM) ----------------------------------------- -.. autofunction:: binance.spot.data_stream.renew_isolated_margin_listen_key +.. autofunction:: binance.spot.Spot.renew_isolated_margin_listen_key Close an isolated margin ListenKey (USER_STREAM) ------------------------------------------------ -.. autofunction:: binance.spot.data_stream.close_isolated_margin_listen_key +.. autofunction:: binance.spot.Spot.close_isolated_margin_listen_key diff --git a/docs/source/binance.spot.fiat.rst b/docs/source/binance.spot.fiat.rst index 7a26aa5e..c4641563 100644 --- a/docs/source/binance.spot.fiat.rst +++ b/docs/source/binance.spot.fiat.rst @@ -3,8 +3,8 @@ Fiat Endpoints Get Fiat Order History (USER_DATA) --------------------------------------------- -.. autofunction:: binance.spot.fiat.fiat_order_history +.. autofunction:: binance.spot.Spot.fiat_order_history Get Fiat Payments History (USER_DATA) --------------------------------------------- -.. autofunction:: binance.spot.fiat.fiat_payment_history +.. autofunction:: binance.spot.Spot.fiat_payment_history diff --git a/docs/source/binance.spot.futures.rst b/docs/source/binance.spot.futures.rst index bd9ebbaa..292d2c9c 100644 --- a/docs/source/binance.spot.futures.rst +++ b/docs/source/binance.spot.futures.rst @@ -3,32 +3,32 @@ Futures Endpoints New Future Account Transfer (USER_DATA) --------------------------------------- -.. autofunction:: binance.spot.futures.futures_transfer +.. autofunction:: binance.spot.Spot.futures_transfer Get Future Account Transaction History List (USER_DATA) ------------------------------------------------------- -.. autofunction:: binance.spot.futures.futures_transfer_history +.. autofunction:: binance.spot.Spot.futures_transfer_history Cross-Collateral Borrow History (USER_DATA) ------------------------------------------- -.. autofunction:: binance.spot.futures.futures_loan_borrow_history +.. autofunction:: binance.spot.Spot.futures_loan_borrow_history Cross-Collateral Repayment History (USER_DATA) ---------------------------------------------- -.. autofunction:: binance.spot.futures.futures_loan_repay_history +.. autofunction:: binance.spot.Spot.futures_loan_repay_history Cross-Collateral Wallet (USER_DATA) ----------------------------------- -.. autofunction:: binance.spot.futures.futures_loan_wallet +.. autofunction:: binance.spot.Spot.futures_loan_wallet Adjust Cross-Collateral LTV History (USER_DATA) ----------------------------------------------- -.. autofunction:: binance.spot.futures.futures_loan_adjust_collateral_history +.. autofunction:: binance.spot.Spot.futures_loan_adjust_collateral_history Cross-Collateral Liquidation History (USER_DATA) ------------------------------------------------ -.. autofunction:: binance.spot.futures.futures_loan_liquidation_history +.. autofunction:: binance.spot.Spot.futures_loan_liquidation_history Cross-Collateral Interest History (USER_DATA) --------------------------------------------- -.. autofunction:: binance.spot.futures.futures_loan_interest_history +.. autofunction:: binance.spot.Spot.futures_loan_interest_history diff --git a/docs/source/binance.spot.gift_card.rst b/docs/source/binance.spot.gift_card.rst index 80f34fca..49bda9b2 100644 --- a/docs/source/binance.spot.gift_card.rst +++ b/docs/source/binance.spot.gift_card.rst @@ -3,24 +3,24 @@ Card Gift Endpoints Create a Binance Code (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.gift_card.gift_card_create_code +.. autofunction:: binance.spot.Spot.gift_card_create_code Redeem a Binance Code (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.gift_card.gift_card_redeem_code +.. autofunction:: binance.spot.Spot.gift_card_redeem_code Verify a Binance Code (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.gift_card.gift_card_verify_code +.. autofunction:: binance.spot.Spot.gift_card_verify_code Gift Card RSA Public Key (USER_DATA) ------------------------------------ -.. autofunction:: binance.spot.gift_card.gift_card_rsa_public_key +.. autofunction:: binance.spot.Spot.gift_card_rsa_public_key Create a dual-token gift card (USER_DATA) ----------------------------------------- -.. autofunction:: binance.spot.gift_card.gift_card_buy_code +.. autofunction:: binance.spot.Spot.gift_card_buy_code Fetch Token Limit (USER_DATA) ----------------------------- -.. autofunction:: binance.spot.gift_card.gift_card_token_limit +.. autofunction:: binance.spot.Spot.gift_card_token_limit diff --git a/docs/source/binance.spot.loan.rst b/docs/source/binance.spot.loan.rst index 19408d37..c7f57594 100644 --- a/docs/source/binance.spot.loan.rst +++ b/docs/source/binance.spot.loan.rst @@ -3,64 +3,64 @@ Crypto Loans Endpoints Get Crypto Loans Income History (USER_DATA) ------------------------------------------- -.. autofunction:: binance.spot.loan.loan_history +.. autofunction:: binance.spot.Spot.loan_history Crypto Loan Borrow (TRADE) -------------------------- -.. autofunction:: binance.spot.loan.loan_borrow +.. autofunction:: binance.spot.Spot.loan_borrow Get Loan Borrow History (USER_DATA) ----------------------------------- -.. autofunction:: binance.spot.loan.loan_borrow_history +.. autofunction:: binance.spot.Spot.loan_borrow_history Get Loan Ongoing Orders (USER_DATA) ----------------------------------- -.. autofunction:: binance.spot.loan.loan_ongoing_orders +.. autofunction:: binance.spot.Spot.loan_ongoing_orders Crypto Loan Repay (TRADE) ------------------------- -.. autofunction:: binance.spot.loan.loan_repay +.. autofunction:: binance.spot.Spot.loan_repay Get Loan Repayment History (USER_DATA) -------------------------------------- -.. autofunction:: binance.spot.loan.loan_repay_history +.. autofunction:: binance.spot.Spot.loan_repay_history Crypto Loan Adjust LTV (TRADE) ------------------------------ -.. autofunction:: binance.spot.loan.loan_adjust_ltv +.. autofunction:: binance.spot.Spot.loan_adjust_ltv Get Loan LTV Adjustment History (USER_DATA) ------------------------------------------- -.. autofunction:: binance.spot.loan.loan_adjust_ltv_history +.. autofunction:: binance.spot.Spot.loan_adjust_ltv_history Get VIP Loan Ongoing Orders (USER_DATA) --------------------------------------- -.. autofunction:: binance.spot.loan.loan_vip_ongoing_orders +.. autofunction:: binance.spot.Spot.loan_vip_ongoing_orders VIP Loan Repay (TRADE) ---------------------- -.. autofunction:: binance.spot.loan.loan_vip_repay +.. autofunction:: binance.spot.Spot.loan_vip_repay Get VIP Loan Repayment History (USER_DATA) ------------------------------------------ -.. autofunction:: binance.spot.loan.loan_vip_repay_history +.. autofunction:: binance.spot.Spot.loan_vip_repay_history Check Locked Value of VIP Collateral Account (USER_DATA) -------------------------------------------------------- -.. autofunction:: binance.spot.loan.loan_vip_collateral_account +.. autofunction:: binance.spot.Spot.loan_vip_collateral_account Get Loanable Assets Data (USER_DATA) ------------------------------------ -.. autofunction:: binance.spot.loan.loan_loanable_data +.. autofunction:: binance.spot.Spot.loan_loanable_data Get Collateral Assets Data (USER_DATA) -------------------------------------- -.. autofunction:: binance.spot.loan.loan_collateral_data +.. autofunction:: binance.spot.Spot.loan_collateral_data Check Collateral Repay Rate (USER_DATA) --------------------------------------- -.. autofunction:: binance.spot.loan.loan_collateral_rate +.. autofunction:: binance.spot.Spot.loan_collateral_rate Customize margin call for ongoing orders only. (USER_DATA) ---------------------------------------------------------- -.. autofunction:: binance.spot.loan.loan_customize_margin_call +.. autofunction:: binance.spot.Spot.loan_customize_margin_call diff --git a/docs/source/binance.spot.margin.rst b/docs/source/binance.spot.margin.rst index 0b9eaae4..9012b83c 100644 --- a/docs/source/binance.spot.margin.rst +++ b/docs/source/binance.spot.margin.rst @@ -3,180 +3,180 @@ Margin Endpoints Margin Account Transfer (MARGIN) -------------------------------- -.. autofunction:: binance.spot.margin.margin_transfer +.. autofunction:: binance.spot.Spot.margin_transfer Margin Account Borrow (MARGIN) ------------------------------ -.. autofunction:: binance.spot.margin.margin_borrow +.. autofunction:: binance.spot.Spot.margin_borrow Margin Account Repay(MARGIN) ---------------------------- -.. autofunction:: binance.spot.margin.margin_repay +.. autofunction:: binance.spot.Spot.margin_repay Query Margin Asset (MARKET_DATA) -------------------------------- -.. autofunction:: binance.spot.margin.margin_asset +.. autofunction:: binance.spot.Spot.margin_asset Query Margin Pair (MARKET_DATA) ------------------------------- -.. autofunction:: binance.spot.margin.margin_pair +.. autofunction:: binance.spot.Spot.margin_pair Get All Margin Assets (MARKET_DATA) ----------------------------------- -.. autofunction:: binance.spot.margin.margin_all_assets +.. autofunction:: binance.spot.Spot.margin_all_assets Get All Margin Pairs (MARKET_DATA) ---------------------------------- -.. autofunction:: binance.spot.margin.margin_all_pairs +.. autofunction:: binance.spot.Spot.margin_all_pairs Query Margin PriceIndex (MARKET_DATA) ------------------------------------- -.. autofunction:: binance.spot.margin.margin_pair_index +.. autofunction:: binance.spot.Spot.margin_pair_index Margin Account New Order (TRADE) -------------------------------- -.. autofunction:: binance.spot.margin.new_margin_order +.. autofunction:: binance.spot.Spot.new_margin_order Margin Account Cancel Order (TRADE) ----------------------------------- -.. autofunction:: binance.spot.margin.cancel_margin_order +.. autofunction:: binance.spot.Spot.cancel_margin_order Get Transfer History (USER_DATA) -------------------------------- -.. autofunction:: binance.spot.margin.margin_transfer_history +.. autofunction:: binance.spot.Spot.margin_transfer_history Query Loan Record (USER_DATA) ----------------------------- -.. autofunction:: binance.spot.margin.margin_load_record +.. autofunction:: binance.spot.Spot.margin_load_record Query Repay Record (USER_DATA) -------------------------------- -.. autofunction:: binance.spot.margin.margin_repay_record +.. autofunction:: binance.spot.Spot.margin_repay_record Get Interest History (USER_DATA) -------------------------------- -.. autofunction:: binance.spot.margin.margin_interest_history +.. autofunction:: binance.spot.Spot.margin_interest_history Get Force Liquidation Record (USER_DATA) ---------------------------------------- -.. autofunction:: binance.spot.margin.margin_force_liquidation_record +.. autofunction:: binance.spot.Spot.margin_force_liquidation_record Query Cross Margin Account Details (USER_DATA) ---------------------------------------------- -.. autofunction:: binance.spot.margin.margin_account +.. autofunction:: binance.spot.Spot.margin_account Query Margin Account's Order (USER_DATA) ---------------------------------------- -.. autofunction:: binance.spot.margin.margin_order +.. autofunction:: binance.spot.Spot.margin_order Query Margin Account's Open Order (USER_DATA) --------------------------------------------- -.. autofunction:: binance.spot.margin.margin_open_orders +.. autofunction:: binance.spot.Spot.margin_open_orders Margin Account Cancel all Open Orders on a Symbol (USER_DATA) ------------------------------------------------------------- -.. autofunction:: binance.spot.margin.margin_open_orders_cancellation +.. autofunction:: binance.spot.Spot.margin_open_orders_cancellation Query Margin Account's All Orders (USER_DATA) --------------------------------------------- -.. autofunction:: binance.spot.margin.margin_all_orders +.. autofunction:: binance.spot.Spot.margin_all_orders Query Margin Account's Trade List (USER_DATA) --------------------------------------------- -.. autofunction:: binance.spot.margin.margin_my_trades +.. autofunction:: binance.spot.Spot.margin_my_trades Query Max Borrow (USER_DATA) ---------------------------- -.. autofunction:: binance.spot.margin.margin_max_borrowable +.. autofunction:: binance.spot.Spot.margin_max_borrowable Query Max Transfer-Out Amount (USER_DATA) ----------------------------------------- -.. autofunction:: binance.spot.margin.margin_max_transferable +.. autofunction:: binance.spot.Spot.margin_max_transferable Isolated Margin Account Transfer (MARGIN) ----------------------------------------- -.. autofunction:: binance.spot.margin.isolated_margin_transfer +.. autofunction:: binance.spot.Spot.isolated_margin_transfer Get Isolated Margin Transfer History (USER_DATA) ------------------------------------------------ -.. autofunction:: binance.spot.margin.isolated_margin_transfer_history +.. autofunction:: binance.spot.Spot.isolated_margin_transfer_history Query Isolated Margin Account Info (USER_DATA) ---------------------------------------------- -.. autofunction:: binance.spot.margin.isolated_margin_account +.. autofunction:: binance.spot.Spot.isolated_margin_account Query Isolated Margin Symbol (USER_DATA) ---------------------------------------- -.. autofunction:: binance.spot.margin.isolated_margin_pair +.. autofunction:: binance.spot.Spot.isolated_margin_pair Get All Isolated Margin Symbol(USER_DATA) ----------------------------------------- -.. autofunction:: binance.spot.margin.isolated_margin_all_pairs +.. autofunction:: binance.spot.Spot.isolated_margin_all_pairs Toggle BNB Burn On Spot Trade And Margin Interest (USER_DATA) ------------------------------------------------------------- -.. autofunction:: binance.spot.margin.toggle_bnbBurn +.. autofunction:: binance.spot.Spot.toggle_bnbBurn Get BNB Burn Status (USER_DATA) ------------------------------- -.. autofunction:: binance.spot.margin.bnbBurn_status +.. autofunction:: binance.spot.Spot.bnbBurn_status Get Margin Interest Rate History (USER_DATA) -------------------------------------------- -.. autofunction:: binance.spot.margin.margin_interest_rate_history +.. autofunction:: binance.spot.Spot.margin_interest_rate_history Margin Account New OCO (TRADE) ------------------------------ -.. autofunction:: binance.spot.margin.new_margin_oco_order +.. autofunction:: binance.spot.Spot.new_margin_oco_order Margin Account Cancel OCO (TRADE) --------------------------------- -.. autofunction:: binance.spot.margin.cancel_margin_oco_order +.. autofunction:: binance.spot.Spot.cancel_margin_oco_order Query Margin Account's OCO (USER_DATA) -------------------------------------- -.. autofunction:: binance.spot.margin.get_margin_oco_order +.. autofunction:: binance.spot.Spot.get_margin_oco_order Query Margin Account's all OCO (USER_DATA) ------------------------------------------ -.. autofunction:: binance.spot.margin.get_margin_oco_orders +.. autofunction:: binance.spot.Spot.get_margin_oco_orders Query Margin Account's Open OCO (USER_DATA) ------------------------------------------- -.. autofunction:: binance.spot.margin.get_margin_open_oco_orders +.. autofunction:: binance.spot.Spot.get_margin_open_oco_orders Disable Isolated Margin Account (TRADE) --------------------------------------- -.. autofunction:: binance.spot.margin.cancel_isolated_margin_account +.. autofunction:: binance.spot.Spot.cancel_isolated_margin_account Enable Isolated Margin Account (TRADE) -------------------------------------- -.. autofunction:: binance.spot.margin.enable_isolated_margin_account +.. autofunction:: binance.spot.Spot.enable_isolated_margin_account Query Enabled Isolated Margin Account Limit (USER_DATA) ------------------------------------------------------- -.. autofunction:: binance.spot.margin.isolated_margin_account_limit +.. autofunction:: binance.spot.Spot.isolated_margin_account_limit Query Cross Margin Fee Data (USER_DATA) --------------------------------------- -.. autofunction:: binance.spot.margin.margin_fee +.. autofunction:: binance.spot.Spot.margin_fee Query Isolated Margin Fee Data (USER_DATA) ------------------------------------------ -.. autofunction:: binance.spot.margin.isolated_margin_fee +.. autofunction:: binance.spot.Spot.isolated_margin_fee Query Isolated Margin Tier Data (USER_DATA) ------------------------------------------- -.. autofunction:: binance.spot.margin.isolated_margin_tier +.. autofunction:: binance.spot.Spot.isolated_margin_tier Query Current Margin Order Count Usage (TRADE) ---------------------------------------------- -.. autofunction:: binance.spot.margin.margin_order_usage +.. autofunction:: binance.spot.Spot.margin_order_usage Margin Dust Log (USER_DATA) --------------------------- -.. autofunction:: binance.spot.margin.margin_dust_log +.. autofunction:: binance.spot.Spot.margin_dust_log Get Summary of Margin account (USER_DATA) ----------------------------------------- -.. autofunction:: binance.spot.margin.summary_of_margin_account \ No newline at end of file +.. autofunction:: binance.spot.Spot.summary_of_margin_account diff --git a/docs/source/binance.spot.market.rst b/docs/source/binance.spot.market.rst index 971daed6..4ff7a180 100644 --- a/docs/source/binance.spot.market.rst +++ b/docs/source/binance.spot.market.rst @@ -3,56 +3,56 @@ Market Endpoints Test Connectivity ----------------- -.. autofunction:: binance.spot.market.ping +.. autofunction:: binance.spot.Spot.ping Check Server Time ----------------- -.. autofunction:: binance.spot.market.time +.. autofunction:: binance.spot.Spot.time Exchange Information -------------------- -.. autofunction:: binance.spot.market.exchange_info +.. autofunction:: binance.spot.Spot.exchange_info Get orderbook ------------- -.. autofunction:: binance.spot.market.depth +.. autofunction:: binance.spot.Spot.depth Recent Trades List ------------------ -.. autofunction:: binance.spot.market.trades +.. autofunction:: binance.spot.Spot.trades Old Trade Lookup ---------------- -.. autofunction:: binance.spot.market.historical_trades +.. autofunction:: binance.spot.Spot.historical_trades Compressed/Aggregate Trades List -------------------------------- -.. autofunction:: binance.spot.market.agg_trades +.. autofunction:: binance.spot.Spot.agg_trades Kline/Candlestick Data ---------------------- -.. autofunction:: binance.spot.market.klines +.. autofunction:: binance.spot.Spot.klines UIKlines -------- -.. autofunction:: binance.spot.market.ui_klines +.. autofunction:: binance.spot.Spot.ui_klines Current Average Price --------------------- -.. autofunction:: binance.spot.market.avg_price +.. autofunction:: binance.spot.Spot.avg_price 24hr Ticker Price Change Statistics ----------------------------------- -.. autofunction:: binance.spot.market.ticker_24hr +.. autofunction:: binance.spot.Spot.ticker_24hr Symbol Price Ticker ------------------- -.. autofunction:: binance.spot.market.ticker_price +.. autofunction:: binance.spot.Spot.ticker_price Symbol Order Book Ticker ------------------------ -.. autofunction:: binance.spot.market.book_ticker +.. autofunction:: binance.spot.Spot.book_ticker Rolling window price change statistics -------------------------------------- -.. autofunction:: binance.spot.market.rolling_window_ticker \ No newline at end of file +.. autofunction:: binance.spot.Spot.rolling_window_ticker diff --git a/docs/source/binance.spot.mining.rst b/docs/source/binance.spot.mining.rst index bc99dc64..046d3f1d 100644 --- a/docs/source/binance.spot.mining.rst +++ b/docs/source/binance.spot.mining.rst @@ -3,52 +3,52 @@ Mining Endpoints Acquiring Algorithm (MARKET_DATA) --------------------------------- -.. autofunction:: binance.spot.mining.mining_algo_list +.. autofunction:: binance.spot.Spot.mining_algo_list Acquiring CoinName (MARKET_DATA) -------------------------------- -.. autofunction:: binance.spot.mining.mining_coin_list +.. autofunction:: binance.spot.Spot.mining_coin_list Request for Detail Miner List (USER_DATA) ----------------------------------------- -.. autofunction:: binance.spot.mining.mining_worker +.. autofunction:: binance.spot.Spot.mining_worker Request for Miner List (USER_DATA) ---------------------------------- -.. autofunction:: binance.spot.mining.mining_worker_list +.. autofunction:: binance.spot.Spot.mining_worker_list Revenue List (USER_DATA) ------------------------ -.. autofunction:: binance.spot.mining.mining_earnings_list +.. autofunction:: binance.spot.Spot.mining_earnings_list Extra Bonus List (USER_DATA) ---------------------------- -.. autofunction:: binance.spot.mining.mining_bonus_list +.. autofunction:: binance.spot.Spot.mining_bonus_list Statistic List (USER_DATA) -------------------------- -.. autofunction:: binance.spot.mining.mining_statistics_list +.. autofunction:: binance.spot.Spot.mining_statistics_list Account List (USER_DATA) ------------------------ -.. autofunction:: binance.spot.mining.mining_account_list +.. autofunction:: binance.spot.Spot.mining_account_list Hashrate Resale Request (USER_DATA) ----------------------------------- -.. autofunction:: binance.spot.mining.mining_hashrate_resale_request +.. autofunction:: binance.spot.Spot.mining_hashrate_resale_request Cancel hashrate resale configuration(USER_DATA) ----------------------------------------------- -.. autofunction:: binance.spot.mining.mining_hashrate_resale_cancellation +.. autofunction:: binance.spot.Spot.mining_hashrate_resale_cancellation Hashrate Resale List (USER_DATA) -------------------------------- -.. autofunction:: binance.spot.mining.mining_hashrate_resale_list +.. autofunction:: binance.spot.Spot.mining_hashrate_resale_list Hashrate Resale Detail (USER_DATA) ---------------------------------- -.. autofunction:: binance.spot.mining.mining_hashrate_resale_details +.. autofunction:: binance.spot.Spot.mining_hashrate_resale_details Mining Account Earning (USER_DATA) ---------------------------------- -.. autofunction:: binance.spot.mining.mining_account_earning \ No newline at end of file +.. autofunction:: binance.spot.Spot.mining_account_earning diff --git a/docs/source/binance.spot.nft.rst b/docs/source/binance.spot.nft.rst index 11c454ed..ac4896ff 100644 --- a/docs/source/binance.spot.nft.rst +++ b/docs/source/binance.spot.nft.rst @@ -3,16 +3,16 @@ NFT Endpoints Get NFT Transaction History (USER_DATA) --------------------------------------- -.. autofunction:: binance.spot.nft.nft_transaction_history +.. autofunction:: binance.spot.Spot.nft_transaction_history Get NFT Deposit History(USER_DATA) ---------------------------------- -.. autofunction:: binance.spot.nft.nft_deposit_history +.. autofunction:: binance.spot.Spot.nft_deposit_history Get NFT Withdraw History (USER_DATA) ------------------------------------ -.. autofunction:: binance.spot.nft.nft_withdraw_history +.. autofunction:: binance.spot.Spot.nft_withdraw_history Get NFT Asset (USER_DATA) ------------------------- -.. autofunction:: binance.spot.nft.nft_asset \ No newline at end of file +.. autofunction:: binance.spot.Spot.nft_asset diff --git a/docs/source/binance.spot.pay.rst b/docs/source/binance.spot.pay.rst index db326f04..43ec6fd6 100644 --- a/docs/source/binance.spot.pay.rst +++ b/docs/source/binance.spot.pay.rst @@ -3,4 +3,4 @@ Pay Endpoints Get Pay Trade History (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.pay.pay_history +.. autofunction:: binance.spot.Spot.pay_history diff --git a/docs/source/binance.spot.portfolio_margin.rst b/docs/source/binance.spot.portfolio_margin.rst index 24dbaf81..03dde79e 100644 --- a/docs/source/binance.spot.portfolio_margin.rst +++ b/docs/source/binance.spot.portfolio_margin.rst @@ -4,12 +4,12 @@ Portfolio Margin Endpoints Get Portfolio Margin Account Info (USER_DATA) --------------------------------------------- -.. autofunction:: binance.spot.portfolio_margin.portfolio_margin_account +.. autofunction:: binance.spot.Spot.portfolio_margin_account Query Portfolio Margin Bankruptcy Loan Amount (USER_DATA) --------------------------------------------------------- -.. autofunction:: binance.spot.portfolio_margin.portfolio_margin_bankruptcy_loan_amount +.. autofunction:: binance.spot.Spot.portfolio_margin_bankruptcy_loan_amount Portfolio Margin Bankruptcy Loan Repay (USER_DATA) -------------------------------------------------- -.. autofunction:: binance.spot.portfolio_margin.portfolio_margin_bankruptcy_loan_repay \ No newline at end of file +.. autofunction:: binance.spot.Spot.portfolio_margin_bankruptcy_loan_repay diff --git a/docs/source/binance.spot.rebate.rst b/docs/source/binance.spot.rebate.rst index 057c5df9..98d077a9 100644 --- a/docs/source/binance.spot.rebate.rst +++ b/docs/source/binance.spot.rebate.rst @@ -3,4 +3,4 @@ Rebate Endpoints Get Spot Rebate History Records (USER_DATA) ------------------------------------------- -.. autofunction:: binance.spot.rebate.rebate_spot_history +.. autofunction:: binance.spot.Spot.rebate_spot_history diff --git a/docs/source/binance.spot.savings.rst b/docs/source/binance.spot.savings.rst index 62582b9b..b962101f 100644 --- a/docs/source/binance.spot.savings.rst +++ b/docs/source/binance.spot.savings.rst @@ -3,56 +3,56 @@ Savings Endpoints Get Flexible Product List (USER_DATA) ------------------------------------- -.. autofunction:: binance.spot.savings.savings_flexible_products +.. autofunction:: binance.spot.Spot.savings_flexible_products Get Left Daily Purchase Quota of Flexible Product (USER_DATA) ------------------------------------------------------------- -.. autofunction:: binance.spot.savings.savings_flexible_user_left_quota +.. autofunction:: binance.spot.Spot.savings_flexible_user_left_quota POST Purchase Flexible Product (USER_DATA) ------------------------------------------ -.. autofunction:: binance.spot.savings.savings_purchase_flexible_product +.. autofunction:: binance.spot.Spot.savings_purchase_flexible_product Get Left Daily Redemption Quota of Flexible Product (USER_DATA) --------------------------------------------------------------- -.. autofunction:: binance.spot.savings.savings_flexible_user_redemption_quota +.. autofunction:: binance.spot.Spot.savings_flexible_user_redemption_quota Redeem Flexible Product (USER_DATA) ----------------------------------- -.. autofunction:: binance.spot.savings.savings_flexible_redeem +.. autofunction:: binance.spot.Spot.savings_flexible_redeem Get Flexible Product Position (USER_DATA) ----------------------------------------- -.. autofunction:: binance.spot.savings.savings_flexible_product_position +.. autofunction:: binance.spot.Spot.savings_flexible_product_position Get Fixed and Activity Project List(USER_DATA) ---------------------------------------------- -.. autofunction:: binance.spot.savings.savings_project_list +.. autofunction:: binance.spot.Spot.savings_project_list Purchase Fixed/Activity Project (USER_DATA) ------------------------------------------- -.. autofunction:: binance.spot.savings.savings_purchase_project +.. autofunction:: binance.spot.Spot.savings_purchase_project Get Fixed/Activity Project Position (USER_DATA) ------------------------------------------------ -.. autofunction:: binance.spot.savings.savings_project_position +.. autofunction:: binance.spot.Spot.savings_project_position Lending Account (USER_DATA) --------------------------- -.. autofunction:: binance.spot.savings.savings_account +.. autofunction:: binance.spot.Spot.savings_account Get Purchase Record (USER_DATA) ------------------------------- -.. autofunction:: binance.spot.savings.savings_purchase_record +.. autofunction:: binance.spot.Spot.savings_purchase_record Get Redemption Record (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.savings.savings_redemption_record +.. autofunction:: binance.spot.Spot.savings_redemption_record Get Interest History (USER_DATA) -------------------------------- -.. autofunction:: binance.spot.savings.savings_interest_history +.. autofunction:: binance.spot.Spot.savings_interest_history Change Fixed/Activity Position to Daily Position(USER_DATA) ----------------------------------------------------------- -.. autofunction:: binance.spot.savings.savings_change_position +.. autofunction:: binance.spot.Spot.savings_change_position diff --git a/docs/source/binance.spot.staking.rst b/docs/source/binance.spot.staking.rst index 05dea172..18910b9f 100644 --- a/docs/source/binance.spot.staking.rst +++ b/docs/source/binance.spot.staking.rst @@ -3,28 +3,28 @@ Staking Endpoints Get Staking Product List (USER_DATA) ------------------------------------ -.. autofunction:: binance.spot.staking.staking_product_list +.. autofunction:: binance.spot.Spot.staking_product_list Purchase Staking Product (USER_DATA) ------------------------------------ -.. autofunction:: binance.spot.staking.staking_purchase_product +.. autofunction:: binance.spot.Spot.staking_purchase_product Redeem Staking Product (USER_DATA) ---------------------------------- -.. autofunction:: binance.spot.staking.staking_redeem_product +.. autofunction:: binance.spot.Spot.staking_redeem_product Get Staking Product Position (USER_DATA) ---------------------------------------- -.. autofunction:: binance.spot.staking.staking_product_position +.. autofunction:: binance.spot.Spot.staking_product_position Get Staking History (USER_DATA) ------------------------------- -.. autofunction:: binance.spot.staking.staking_history +.. autofunction:: binance.spot.Spot.staking_history Set Auto Staking (USER_DATA) ---------------------------- -.. autofunction:: binance.spot.staking.staking_set_auto_staking +.. autofunction:: binance.spot.Spot.staking_set_auto_staking Get Personal Left Quota of Staking Product (USER_DATA) ------------------------------------------------------ -.. autofunction:: binance.spot.staking.staking_product_quota \ No newline at end of file +.. autofunction:: binance.spot.Spot.staking_product_quota diff --git a/docs/source/binance.spot.sub_account.rst b/docs/source/binance.spot.sub_account.rst index 88970371..f7ce46eb 100644 --- a/docs/source/binance.spot.sub_account.rst +++ b/docs/source/binance.spot.sub_account.rst @@ -3,140 +3,140 @@ Sub Account Endpoints Create a Virtual Sub-account(For Master Account) ------------------------------------------------ -.. autofunction:: binance.spot.sub_account.sub_account_create +.. autofunction:: binance.spot.Spot.sub_account_create Query Sub-account List(For Master Account) ------------------------------------------ -.. autofunction:: binance.spot.sub_account.sub_account_list +.. autofunction:: binance.spot.Spot.sub_account_list Query Sub-account Assets(For Master Account) -------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_assets +.. autofunction:: binance.spot.Spot.sub_account_assets Get Sub-account Deposit Address (For Master Account) ---------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_deposit_address +.. autofunction:: binance.spot.Spot.sub_account_deposit_address Get Sub-account Deposit History (For Master Account) ---------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_deposit_history +.. autofunction:: binance.spot.Spot.sub_account_deposit_history Get Sub-account's Status on Margin/Futures(For Master Account) -------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_status +.. autofunction:: binance.spot.Spot.sub_account_status Enable Margin for Sub-account (For Master Account) -------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_enable_margin +.. autofunction:: binance.spot.Spot.sub_account_enable_margin Get Detail on Sub-account's Margin Account (For Master Account) --------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_margin_account +.. autofunction:: binance.spot.Spot.sub_account_margin_account Get Summary of Sub-account's Margin Account (For Master Account) ---------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_margin_account_summary +.. autofunction:: binance.spot.Spot.sub_account_margin_account_summary Enable Futures for Sub-account (For Master Account) --------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_enable_futures +.. autofunction:: binance.spot.Spot.sub_account_enable_futures Futures Transfer for Sub-account(For Master Account) ------------------------------------------------------ -.. autofunction:: binance.spot.sub_account.sub_account_futures_transfer +.. autofunction:: binance.spot.Spot.sub_account_futures_transfer Margin Transfer for Sub-account(For Master Account) ---------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_margin_transfer +.. autofunction:: binance.spot.Spot.sub_account_margin_transfer Transfer to Sub-account of Same Master(For Sub-account) --------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_transfer_to_sub +.. autofunction:: binance.spot.Spot.sub_account_transfer_to_sub Transfer to Master(For Sub-account) ------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_transfer_to_master +.. autofunction:: binance.spot.Spot.sub_account_transfer_to_master Sub-account Transfer History (For Sub-account) ---------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_transfer_sub_account_history +.. autofunction:: binance.spot.Spot.sub_account_transfer_sub_account_history Query Sub-account Futures Asset Transfer History(For Master Account) -------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_futures_asset_transfer_history +.. autofunction:: binance.spot.Spot.sub_account_futures_asset_transfer_history Query Sub-account Futures Asset Transfer History(For Master Account) -------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_futures_asset_transfer +.. autofunction:: binance.spot.Spot.sub_account_futures_asset_transfer Query Sub-account Spot Assets Summary (For Master Account) ---------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_spot_summary +.. autofunction:: binance.spot.Spot.sub_account_spot_summary Universal Transfer (For Master Account) --------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_universal_transfer +.. autofunction:: binance.spot.Spot.sub_account_universal_transfer Query Universal Transfer History (For Master Account) ----------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_universal_transfer_history +.. autofunction:: binance.spot.Spot.sub_account_universal_transfer_history Get Detail on Sub-account's Futures Account V2 (For Master Account) ------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_futures_account +.. autofunction:: binance.spot.Spot.sub_account_futures_account Get Summary of Sub-account's Futures Account V2 (For Master Account) -------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_futures_account_summary +.. autofunction:: binance.spot.Spot.sub_account_futures_account_summary Get Futures Position-Risk of Sub-account V2 (For Master Account) ---------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_futures_position_risk +.. autofunction:: binance.spot.Spot.sub_account_futures_position_risk Query Sub-account Spot Asset Transfer History (SAPI For Master Account) ----------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_spot_transfer_history +.. autofunction:: binance.spot.Spot.sub_account_spot_transfer_history Enable Leverage Token for Sub-account(For Master Account) --------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_enable_leverage_token +.. autofunction:: binance.spot.Spot.sub_account_enable_leverage_token Deposit assets into the managed sub-account (For Investor Master Account) ------------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.managed_sub_account_deposit +.. autofunction:: binance.spot.Spot.managed_sub_account_deposit Query managed sub-account asset details (For Investor Master Account) --------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.managed_sub_account_assets +.. autofunction:: binance.spot.Spot.managed_sub_account_assets Withdrawl assets from the managed sub-account (For Investor Master Account) --------------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.managed_sub_account_withdraw +.. autofunction:: binance.spot.Spot.managed_sub_account_withdraw Enable or Disable IP Restriction for a Sub-account API Key (For Master Account) ------------------------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_api_toggle_ip_restriction +.. autofunction:: binance.spot.Spot.sub_account_api_toggle_ip_restriction Add IP List for a Sub-account API Key (For Master Account) ---------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_api_add_ip +.. autofunction:: binance.spot.Spot.sub_account_api_add_ip Get IP Restriction for a Sub-account API Key (For Master Account) ----------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_api_get_ip_restriction +.. autofunction:: binance.spot.Spot.sub_account_api_get_ip_restriction Delete IP List for a Sub-account API Key (For Master Account) ------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.sub_account_api_delete_ip +.. autofunction:: binance.spot.Spot.sub_account_api_delete_ip Query Managed Sub-account Snapshot (For Investor Master Account) ---------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.managed_sub_account_get_snapshot +.. autofunction:: binance.spot.Spot.managed_sub_account_get_snapshot Query Managed Sub Account Transfer Log (Investor) (USER_DATA) ------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.managed_sub_account_investor_trans_log +.. autofunction:: binance.spot.Spot.managed_sub_account_investor_trans_log Query Managed Sub Account Transfer Log (Trading Team) (USER_DATA) ----------------------------------------------------------------- -.. autofunction:: binance.spot.sub_account.managed_sub_account_trading_trans_log +.. autofunction:: binance.spot.Spot.managed_sub_account_trading_trans_log diff --git a/docs/source/binance.spot.trade.rst b/docs/source/binance.spot.trade.rst index e9b5fbc4..3b203aca 100644 --- a/docs/source/binance.spot.trade.rst +++ b/docs/source/binance.spot.trade.rst @@ -4,64 +4,64 @@ Account / Trade Endpoints Test New Order (TRADE) ---------------------- -.. autofunction:: binance.spot.trade.new_order_test +.. autofunction:: binance.spot.Spot.new_order_test New Order (TRADE) ----------------- -.. autofunction:: binance.spot.trade.new_order +.. autofunction:: binance.spot.Spot.new_order Cancel Order (TRADE) -------------------- -.. autofunction:: binance.spot.trade.cancel_order +.. autofunction:: binance.spot.Spot.cancel_order Cancel all Open Orders on a Symbol (TRADE) ------------------------------------------ -.. autofunction:: binance.spot.trade.cancel_open_orders +.. autofunction:: binance.spot.Spot.cancel_open_orders Query Order (USER_DATA) ----------------------- -.. autofunction:: binance.spot.trade.get_order +.. autofunction:: binance.spot.Spot.get_order Cancel an Existing Order and Send a New Order (USER_DATA) --------------------------------------------------------- -.. autofunction:: binance.spot.trade.cancel_and_replace +.. autofunction:: binance.spot.Spot.cancel_and_replace Current Open Orders (USER_DATA) ------------------------------- -.. autofunction:: binance.spot.trade.get_open_orders +.. autofunction:: binance.spot.Spot.get_open_orders All Orders (USER_DATA) ---------------------- -.. autofunction:: binance.spot.trade.get_orders +.. autofunction:: binance.spot.Spot.get_orders New OCO (TRADE) --------------- -.. autofunction:: binance.spot.trade.new_oco_order +.. autofunction:: binance.spot.Spot.new_oco_order Cancel OCO (TRADE) ------------------ -.. autofunction:: binance.spot.trade.cancel_oco_order +.. autofunction:: binance.spot.Spot.cancel_oco_order Query OCO (USER_DATA) --------------------- -.. autofunction:: binance.spot.trade.get_oco_order +.. autofunction:: binance.spot.Spot.get_oco_order Query all OCO (USER_DATA) ------------------------- -.. autofunction:: binance.spot.trade.get_oco_orders +.. autofunction:: binance.spot.Spot.get_oco_orders Query Open OCO (USER_DATA) -------------------------- -.. autofunction:: binance.spot.trade.get_oco_open_orders +.. autofunction:: binance.spot.Spot.get_oco_open_orders Account Information (USER_DATA) ------------------------------- -.. autofunction:: binance.spot.trade.account +.. autofunction:: binance.spot.Spot.account Account Trade List (USER_DATA) ------------------------------ -.. autofunction:: binance.spot.trade.my_trades +.. autofunction:: binance.spot.Spot.my_trades Query Current Order Count Usage (TRADE) --------------------------------------- -.. autofunction:: binance.spot.trade.get_order_rate_limit +.. autofunction:: binance.spot.Spot.get_order_rate_limit diff --git a/docs/source/binance.spot.wallet.rst b/docs/source/binance.spot.wallet.rst index 364bcb25..1c3619be 100644 --- a/docs/source/binance.spot.wallet.rst +++ b/docs/source/binance.spot.wallet.rst @@ -3,108 +3,108 @@ Wallet Endpoints System Status (System) ---------------------- -.. autofunction:: binance.spot.wallet.system_status +.. autofunction:: binance.spot.Spot.system_status All Coins' Information (USER_DATA) ---------------------------------- -.. autofunction:: binance.spot.wallet.coin_info +.. autofunction:: binance.spot.Spot.coin_info Daily Account Snapshot (USER_DATA) ---------------------------------- -.. autofunction:: binance.spot.wallet.account_snapshot +.. autofunction:: binance.spot.Spot.account_snapshot Disable Fast Withdraw Switch (USER_DATA) ---------------------------------------- -.. autofunction:: binance.spot.wallet.disable_fast_withdraw +.. autofunction:: binance.spot.Spot.disable_fast_withdraw Enable Fast Withdraw Switch (USER_DATA) --------------------------------------- -.. autofunction:: binance.spot.wallet.enable_fast_withdraw +.. autofunction:: binance.spot.Spot.enable_fast_withdraw Withdraw (USER_DATA) -------------------- -.. autofunction:: binance.spot.wallet.withdraw +.. autofunction:: binance.spot.Spot.withdraw Deposit History(supporting network) (USER_DATA) ------------------------------------------------- -.. autofunction:: binance.spot.wallet.deposit_history +.. autofunction:: binance.spot.Spot.deposit_history Withdraw History (supporting network) (USER_DATA) ------------------------------------------------- -.. autofunction:: binance.spot.wallet.withdraw_history +.. autofunction:: binance.spot.Spot.withdraw_history Deposit Address (supporting network) (USER_DATA) ------------------------------------------------ -.. autofunction:: binance.spot.wallet.deposit_address +.. autofunction:: binance.spot.Spot.deposit_address Account Status (USER_DATA) -------------------------- -.. autofunction:: binance.spot.wallet.account_status +.. autofunction:: binance.spot.Spot.account_status Account API Trading Status (USER_DATA) -------------------------------------- -.. autofunction:: binance.spot.wallet.api_trading_status +.. autofunction:: binance.spot.Spot.api_trading_status DustLog (USER_DATA) ------------------- -.. autofunction:: binance.spot.wallet.dust_log +.. autofunction:: binance.spot.Spot.dust_log User Universal Transfer ----------------------- -.. autofunction:: binance.spot.wallet.user_universal_transfer +.. autofunction:: binance.spot.Spot.user_universal_transfer Query User Universal Transfer History ------------------------------------- -.. autofunction:: binance.spot.wallet.user_universal_transfer_history +.. autofunction:: binance.spot.Spot.user_universal_transfer_history Dust Transfer (USER_DATA) ------------------------- -.. autofunction:: binance.spot.wallet.transfer_dust +.. autofunction:: binance.spot.Spot.transfer_dust Asset Dividend Record (USER_DATA) --------------------------------- -.. autofunction:: binance.spot.wallet.asset_dividend_record +.. autofunction:: binance.spot.Spot.asset_dividend_record Asset Detail (USER_DATA) ------------------------ -.. autofunction:: binance.spot.wallet.asset_detail +.. autofunction:: binance.spot.Spot.asset_detail Trade Fee (USER_DATA) --------------------- -.. autofunction:: binance.spot.wallet.trade_fee +.. autofunction:: binance.spot.Spot.trade_fee Funding Wallet (USER_DATA) -------------------------- -.. autofunction:: binance.spot.wallet.funding_wallet +.. autofunction:: binance.spot.Spot.funding_wallet User Asset (USER_DATA) ---------------------- -.. autofunction:: binance.spot.wallet.user_asset +.. autofunction:: binance.spot.Spot.user_asset API Key Permission (USER_DATA) ------------------------------ -.. autofunction:: binance.spot.wallet.api_key_permissions +.. autofunction:: binance.spot.Spot.api_key_permissions Get Assets That Can Be Converted Into BNB (USER_DATA) ----------------------------------------------------- -.. autofunction:: binance.spot.wallet.bnb_convertible_assets +.. autofunction:: binance.spot.Spot.bnb_convertible_assets Query auto-converting stable coins (USER_DATA) ---------------------------------------------- -.. autofunction:: binance.spot.wallet.convertible_coins +.. autofunction:: binance.spot.Spot.convertible_coins Switch on/off BUSD and stable coins conversion (USER_DATA) ---------------------------------------------------------- -.. autofunction:: binance.spot.wallet.toggle_auto_convertion +.. autofunction:: binance.spot.Spot.toggle_auto_convertion Get Cloud-Mining payment and refund history (USER_DATA) ------------------------------------------------------- -.. autofunction:: binance.spot.wallet.cloud_mining_trans_history +.. autofunction:: binance.spot.Spot.cloud_mining_trans_history BUSD Convert (USER_DATA) ------------------------ -.. autofunction:: binance.spot.wallet.convert_transfer +.. autofunction:: binance.spot.Spot.convert_transfer BUSD Convert History (USER_DATA) -------------------------------- -.. autofunction:: binance.spot.wallet.convert_history +.. autofunction:: binance.spot.Spot.convert_history diff --git a/docs/source/binance.websocket.spot.rst b/docs/source/binance.websocket.spot.rst deleted file mode 100644 index d276be1c..00000000 --- a/docs/source/binance.websocket.spot.rst +++ /dev/null @@ -1,47 +0,0 @@ -Spot Websocket Streams -====================== - - -Aggregate Trade Streams ------------------------ -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.agg_trade - -Trade Streams -------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.trade - -Kline/Candlestick Streams -------------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.kline - -Individual symbol or all symbols mini ticker --------------------------------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.mini_ticker - -Individual symbol or all symbols ticker ---------------------------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.ticker - -Individual symbol or all book ticker ------------------------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.book_ticker - -Individual Symbol Rolling Window Statistics Streams ---------------------------------------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.rolling_window_ticker - -All Market Rolling Window Statistics Streams --------------------------------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.rolling_window_ticker_all_symbols - -Partial Book Depth Streams --------------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.partial_book_depth - -Diff. Depth Stream ------------------- -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.diff_book_depth - -Listen to user data by provided listenkey ------------------------------------------ -.. autofunction:: binance.websocket.spot.websocket_client.SpotWebsocketClient.user_data diff --git a/docs/source/binance.websocket_api.rst b/docs/source/binance.websocket_api.rst new file mode 100644 index 00000000..dd0e3ac8 --- /dev/null +++ b/docs/source/binance.websocket_api.rst @@ -0,0 +1,135 @@ +Spot Websocket API +====================== + +Test connectivity to the WebSocket API +-------------------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.ping_connectivity + +Check server time +----------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.server_time + +Get exchange information +------------------------ +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.exchange_info + +Get order book +-------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.order_book + +Get historical trades +--------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.historical_trades + +Get compressed, aggregate trades +-------------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.aggregate_trades + +klines +------ +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.klines + +Klines/candlesticks for UI +-------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.ui_klines + +Current average price for a symbol +---------------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.avg_price + +24hr ticker price change statistics +----------------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.ticker_24hr + +Rolling window price change statistics +-------------------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.ticker + +Symbol price ticker +------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.ticker_price + +Symbol order book ticker +------------------------ +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.ticker_book + +Account information +------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.account + +Account order rate limits +------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.order_rate_limit + +Account order history +--------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.order_history + +Account OCO history +------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.oco_history + +Account trade history +--------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.my_trades + +Account prevented matches +------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.prevented_matches + +Create a new order +------------------ +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.new_order + +Test new order +-------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.new_order_test + +Get order +--------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.get_order + +Cancel order +------------ +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.cancel_order + +Cancel and replace order +------------------------ +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.cancel_replace_order + + +Current open orders +------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.get_open_orders + +Cancel all open orders on a symbol +---------------------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.cancel_open_orders + +Place a new OCO Order +--------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.new_oco_order + +Get OCO order +------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.get_oco_order + +Cancel OCO order +---------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.cancel_oco_order + +Get all OCO orders +------------------ +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.get_open_oco_orders + +Start user data stream +---------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.user_data_start + +Ping user data stream +--------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.user_data_ping + +Stop user data stream +--------------------- +.. autofunction:: binance.websocket.spot.websocket_api.SpotWebsocketAPIClient.user_data_stop diff --git a/docs/source/binance.websocket_stream.spot.rst b/docs/source/binance.websocket_stream.spot.rst new file mode 100644 index 00000000..71bec4b8 --- /dev/null +++ b/docs/source/binance.websocket_stream.spot.rst @@ -0,0 +1,47 @@ +Spot Websocket Streams +====================== + + +Aggregate Trade Streams +----------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.agg_trade + +Trade Streams +------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.trade + +Kline/Candlestick Streams +------------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.kline + +Individual symbol or all symbols mini ticker +-------------------------------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.mini_ticker + +Individual symbol or all symbols ticker +--------------------------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.ticker + +Individual symbol or all book ticker +------------------------------------ +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.book_ticker + +Individual Symbol Rolling Window Statistics Streams +--------------------------------------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.rolling_window_ticker + +All Market Rolling Window Statistics Streams +-------------------------------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.rolling_window_ticker_all_symbols + +Partial Book Depth Streams +-------------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.partial_book_depth + +Diff. Depth Stream +------------------ +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.diff_book_depth + +Listen to user data by provided listenkey +----------------------------------------- +.. autofunction:: binance.websocket.spot.websocket_stream.SpotWebsocketStreamClient.user_data diff --git a/docs/source/index.rst b/docs/source/index.rst index 19991eaa..10c1f364 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -13,7 +13,8 @@ Contents CHANGELOG getting_started binance.spot - binance.websocket.spot + binance.websocket_stream.spot + binance.websocket_api Indices and tables ================== diff --git a/examples/config.ini.example b/examples/config.ini.example index 004b1df7..67a725aa 100644 --- a/examples/config.ini.example +++ b/examples/config.ini.example @@ -1,6 +1,10 @@ # Make a copy of this file, and save to `config.ini` -# Enter your API and Secret Key for use in the example files +# Enter your API and Secret Key for use in the example files; No need to add double quote or single quote. For example: +# api_key=vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A +# api_secret=NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j +# It's a demo key, doesn't work on production :) + [keys] api_key= api_secret= diff --git a/examples/websocket/spot/agg_trade.py b/examples/websocket/spot/agg_trade.py deleted file mode 100644 index 98d41246..00000000 --- a/examples/websocket/spot/agg_trade.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -# Subscribe to a single symbol stream -my_client.agg_trade( - symbol="btcusdt", - id=1, - callback=message_handler, -) - -time.sleep(2) - -# Subscribe to a new stream for each symbol in the list -my_client.agg_trade( - symbol=["bnbusdt", "ethusdt", "ltcusdt"], - id=2, - callback=message_handler, -) - -time.sleep(5) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/all_symbols_ticker.py b/examples/websocket/spot/all_symbols_ticker.py deleted file mode 100644 index b251e27c..00000000 --- a/examples/websocket/spot/all_symbols_ticker.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - - -my_client.ticker( - id=1, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/book_ticker.py b/examples/websocket/spot/book_ticker.py deleted file mode 100644 index d40c308a..00000000 --- a/examples/websocket/spot/book_ticker.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - - -my_client.book_ticker( - id=1, - callback=message_handler, - symbol="btcusdt", -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/combined_streams.py b/examples/websocket/spot/combined_streams.py deleted file mode 100644 index 764c1155..00000000 --- a/examples/websocket/spot/combined_streams.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - logging.info(message) - - -my_client = Client() -my_client.start() - - -# subscribe one stream -my_client.instant_subscribe( - stream="bnbusdt@bookTicker", - callback=message_handler, -) - -time.sleep(3) - -# subscribe multiple streams -my_client.instant_subscribe( - stream=["bnbusdt@bookTicker", "ethusdt@bookTicker"], - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/diff_book_depth.py b/examples/websocket/spot/diff_book_depth.py deleted file mode 100644 index 00f642dc..00000000 --- a/examples/websocket/spot/diff_book_depth.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -my_client.diff_book_depth( - symbol="bnbusdt", - speed=100, - id=1, - callback=message_handler, -) - -time.sleep(2) - -# Subscribe to a new stream for each symbol in the list -my_client.diff_book_depth( - symbol=["ethusdt", "ltcusdt"], - speed=100, - id=1, - callback=message_handler, -) - -time.sleep(2) - -my_client.diff_book_depth( - symbol="btcusdt", - speed=1000, - id=2, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/partial_book_depth.py b/examples/websocket/spot/partial_book_depth.py deleted file mode 100644 index 910d312c..00000000 --- a/examples/websocket/spot/partial_book_depth.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -my_client.partial_book_depth( - symbol="bnbusdt", - level=10, - speed=100, - id=1, - callback=message_handler, -) - -time.sleep(2) - -my_client.partial_book_depth( - symbol=["btcusdt", "ltcusdt"], - level=10, - speed=100, - id=2, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/rolling_window_ticker.py b/examples/websocket/spot/rolling_window_ticker.py deleted file mode 100644 index 7e3866b4..00000000 --- a/examples/websocket/spot/rolling_window_ticker.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - - -my_client.rolling_window_ticker( - "BNBUSDT", - "1h", - id=1, - callback=message_handler, -) - -my_client.rolling_window_ticker( - ["LTCUSDT", "ETHUSDT"], - "1h", - id=1, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/rolling_window_ticker_all_symbols.py b/examples/websocket/spot/rolling_window_ticker_all_symbols.py deleted file mode 100644 index e030a36f..00000000 --- a/examples/websocket/spot/rolling_window_ticker_all_symbols.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - - -my_client.rolling_window_ticker_all_symbols( - "1h", - id=1, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/symbol_book_ticker.py b/examples/websocket/spot/symbol_book_ticker.py deleted file mode 100644 index 90f6951c..00000000 --- a/examples/websocket/spot/symbol_book_ticker.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -my_client.book_ticker( - symbol="bnbusdt", - id=1, - callback=message_handler, -) - -time.sleep(2) - -my_client.book_ticker( - symbol=["btcusdt", "ethusdt"], - id=2, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/symbol_kline.py b/examples/websocket/spot/symbol_kline.py deleted file mode 100644 index ecd0aa5e..00000000 --- a/examples/websocket/spot/symbol_kline.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -my_client.kline(symbol="btcusdt", id=1, interval="1m", callback=message_handler) - -time.sleep(5) - -my_client.kline( - symbol=["bnbusdt", "ethusdt"], id=2, interval="3m", callback=message_handler -) - -time.sleep(10) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/symbol_mini_ticker.py b/examples/websocket/spot/symbol_mini_ticker.py deleted file mode 100644 index 4facb451..00000000 --- a/examples/websocket/spot/symbol_mini_ticker.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -my_client.mini_ticker( - symbol="bnbusdt", - id=1, - callback=message_handler, -) - -time.sleep(2) - -my_client.mini_ticker( - symbol=["btcusdt", "ethusdt"], - id=2, - callback=message_handler, -) - -time.sleep(3000) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/symbol_ticker.py b/examples/websocket/spot/symbol_ticker.py deleted file mode 100644 index 58d62d69..00000000 --- a/examples/websocket/spot/symbol_ticker.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - logging.info(message) - - -my_client = Client(stream_url="wss://testnet.binance.vision") -my_client.start() - -# Live subscription -my_client.ticker( - symbol="bnbusdt", - id=1, - callback=message_handler, -) - -# Combined subscription -my_client.instant_subscribe( - ["bnbusdt@ticker", "ethusdt@ticker"], callback=message_handler -) - -time.sleep(2000) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/test.py b/examples/websocket/spot/test.py deleted file mode 100644 index f453d9a5..00000000 --- a/examples/websocket/spot/test.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -my_client.agg_trade( - symbol="btcusdt", - id=1, - callback=message_handler, -) - -time.sleep(1) - -my_client.agg_trade( - symbol=["bnbusdt", "ethusdt"], - id=2, - callback=message_handler, -) - -time.sleep(10) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/trade.py b/examples/websocket/spot/trade.py deleted file mode 100644 index 2eefba7c..00000000 --- a/examples/websocket/spot/trade.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -my_client = Client() -my_client.start() - -my_client.trade( - symbol="bnbusdt", - interval="1m", - id=1, - callback=message_handler, -) - -time.sleep(2) - -my_client.trade( - symbol=["eosusdt", "ltcusdt"], - interval="1m", - id=2, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -my_client.stop() diff --git a/examples/websocket/spot/user_data.py b/examples/websocket/spot/user_data.py deleted file mode 100644 index d15e7495..00000000 --- a/examples/websocket/spot/user_data.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python - -import time -import logging -from binance.lib.utils import config_logging -from binance.spot import Spot as Client -from binance.websocket.spot.websocket_client import SpotWebsocketClient -from configparser import ConfigParser - -config = ConfigParser() -config.read("../../config.ini") - -config_logging(logging, logging.DEBUG) - - -def message_handler(message): - print(message) - - -api_key = config["keys"]["api_key"] -client = Client(api_key, base_url="https://testnet.binance.vision") -response = client.new_listen_key() - -logging.info("Receving listen key : {}".format(response["listenKey"])) - -ws_client = SpotWebsocketClient(stream_url="wss://testnet.binance.vision") -ws_client.start() - -ws_client.user_data( - listen_key=response["listenKey"], - id=1, - callback=message_handler, -) - -time.sleep(30) - -logging.debug("closing ws connection") -ws_client.stop() diff --git a/examples/websocket/spot/websocket_api/account/account.py b/examples/websocket/spot/websocket_api/account/account.py new file mode 100644 index 00000000..1ef55dc2 --- /dev/null +++ b/examples/websocket/spot/websocket_api/account/account.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.account() + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/account/my_trades.py b/examples/websocket/spot/websocket_api/account/my_trades.py new file mode 100644 index 00000000..98443c4b --- /dev/null +++ b/examples/websocket/spot/websocket_api/account/my_trades.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.order_history(symbol="BNBUSDT", limit=10) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/account/oco_history.py b/examples/websocket/spot/websocket_api/account/oco_history.py new file mode 100644 index 00000000..1cc591da --- /dev/null +++ b/examples/websocket/spot/websocket_api/account/oco_history.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.oco_history(fromId=1, limit=10) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/account/order_history.py b/examples/websocket/spot/websocket_api/account/order_history.py new file mode 100644 index 00000000..e8a247c5 --- /dev/null +++ b/examples/websocket/spot/websocket_api/account/order_history.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.order_history(id="123", symbol="BNBUSDT", limit=10) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/account/order_rate_limit.py b/examples/websocket/spot/websocket_api/account/order_rate_limit.py new file mode 100644 index 00000000..15ab1631 --- /dev/null +++ b/examples/websocket/spot/websocket_api/account/order_rate_limit.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.order_rate_limit() + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/account/prevented_matches.py b/examples/websocket/spot/websocket_api/account/prevented_matches.py new file mode 100644 index 00000000..82df3b4c --- /dev/null +++ b/examples/websocket/spot/websocket_api/account/prevented_matches.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.prevented_matches(symbol="BNBUSDT", preventedMatchId=1) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/app_demo.py b/examples/websocket/spot/websocket_api/app_demo.py new file mode 100644 index 00000000..2e856ee1 --- /dev/null +++ b/examples/websocket/spot/websocket_api/app_demo.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python + +""" + A simple demo for how to: + - Create a connection to the websocket api + - Create a connection to the websocket stream + - Subscribe to the user data stream from websocket stream + - Create a new order from websocket api +""" + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient +from binance.spot import Spot as SpotAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def websocket_api_message_handler(_, message): + logging.info("message from websocket API") + logging.info(message) + + +def websocket_stream_message_handler(_, message): + logging.info("message from websocket stream") + logging.info(message) + + +# make a connection to the websocket api +ws_api_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=websocket_api_message_handler, + on_close=on_close, +) + +# make a connection to the websocket stream +ws_stream_client = SpotWebsocketStreamClient( + stream_url="wss://testnet.binance.vision", + on_message=websocket_stream_message_handler, +) + +# spot api client to call all restful api endpoints +spot_api_client = SpotAPIClient(api_key, base_url="https://testnet.binance.vision") +response = spot_api_client.new_listen_key() + +# You can subscribe to the user data stream from websocket stream, it will broadcast all the events +# related to your account, including order updates, balance updates, etc. +ws_stream_client.user_data(listen_key=response["listenKey"]) + +time.sleep(5) + +# You can create a new order from websocket api +ws_api_client.new_order( + symbol="BNBUSDT", + side="BUY", + type="LIMIT", + timeInForce="GTC", + quantity=1, + price=200, + newOrderRespType="RESULT", +) + +time.sleep(10) + +logging.info("closing ws connection") +ws_api_client.stop() +ws_stream_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/aggregate_trades.py b/examples/websocket/spot/websocket_api/market/aggregate_trades.py new file mode 100644 index 00000000..ab3ce8e9 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/aggregate_trades.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.aggregate_trades(symbol="BNBBUSD", limit=1, fromId=0) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/all.py b/examples/websocket/spot/websocket_api/market/all.py new file mode 100644 index 00000000..375e22fa --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/all.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.ping_connectivity() +time.sleep(2) + +my_client.server_time() +time.sleep(2) + +my_client.exchange_info() +time.sleep(2) + +my_client.order_book(symbol="BNBBUSD", limit=1) +time.sleep(2) + +my_client.recent_trades(symbol="BNBBUSD", limit=1) +time.sleep(2) + +my_client.historical_trades( + symbol="BNBBUSD", + apiKey="HX0gpRCAJHiAZBCaPfkDMXAN2uXj3BrNNwjBRjlFhn3E4jtZthu4SijD31rkLqr2", + limit=1, +) +time.sleep(2) + +my_client.aggregate_trades(symbol="BNBBUSD", limit=1, fromId=0) +time.sleep(2) + +my_client.ticker_24hr(symbol="BNBBUSD") +time.sleep(2) + +my_client.ticker(symbol="BNBBUSD", type="FULL") +time.sleep(2) + +my_client.ticker_price(symbol="BNBBUSD") +time.sleep(2) + +my_client.ticker_book(symbol="BNBBUSD") +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/avg_price.py b/examples/websocket/spot/websocket_api/market/avg_price.py new file mode 100644 index 00000000..1a0466b1 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/avg_price.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.avg_price(symbol="BNBBUSD") + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/exchange_info.py b/examples/websocket/spot/websocket_api/market/exchange_info.py new file mode 100644 index 00000000..63e39af0 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/exchange_info.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.exchange_info(symbol="BNBBUSD") + +time.sleep(2) + +my_client.exchange_info(symbols=["BNBUSDT", "BTCUSDT"]) + +time.sleep(2) + +my_client.exchange_info(permissions=["SPOT", "MARGIN"]) + +time.sleep(2) + +my_client.exchange_info() + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/historical_trades.py b/examples/websocket/spot/websocket_api/market/historical_trades.py new file mode 100644 index 00000000..fde4f298 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/historical_trades.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.historical_trades(symbol="BNBBUSD", apiKey="", limit=1) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/klines.py b/examples/websocket/spot/websocket_api/market/klines.py new file mode 100644 index 00000000..16ea116e --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/klines.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.klines(symbol="BNBBUSD", interval="1m", limit=2) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/order_book.py b/examples/websocket/spot/websocket_api/market/order_book.py new file mode 100644 index 00000000..f4266fa7 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/order_book.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.order_book(symbol="BNBBUSD") + +time.sleep(2) + +my_client.order_book(symbol="BNBBUSD", limit=5) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/ping_connectivity.py b/examples/websocket/spot/websocket_api/market/ping_connectivity.py new file mode 100644 index 00000000..4414f19d --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/ping_connectivity.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + +# send a message to the server to ping connectivity +my_client.ping_connectivity(id="my_request_id") + +time.sleep(10) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/recent_trades.py b/examples/websocket/spot/websocket_api/market/recent_trades.py new file mode 100644 index 00000000..abdc3fdf --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/recent_trades.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.recent_trades(symbol="BNBBUSD") + +time.sleep(2) + +my_client.recent_trades(symbol="BNBBUSD", limit=5) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/server_time.py b/examples/websocket/spot/websocket_api/market/server_time.py new file mode 100644 index 00000000..0915d4ff --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/server_time.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.server_time() + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/ticker.py b/examples/websocket/spot/websocket_api/market/ticker.py new file mode 100644 index 00000000..6c67bbe0 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/ticker.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.ticker(symbol="BNBBUSD", type="FULL") + +time.sleep(2) + +my_client.ticker(symbols=["BNBBUSD", "BTCUSDT"], type="MINI", windowSize="2h") + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/ticker_24hr.py b/examples/websocket/spot/websocket_api/market/ticker_24hr.py new file mode 100644 index 00000000..e63c5dfd --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/ticker_24hr.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.ticker_24hr(symbol="BNBBUSD", type="FULL") + +time.sleep(2) + +my_client.ticker_24hr(symbols=["BNBBUSD", "BTCUSDT"], type="FULL") + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/ticker_book.py b/examples/websocket/spot/websocket_api/market/ticker_book.py new file mode 100644 index 00000000..91c2c448 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/ticker_book.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.ticker_book(symbol="BNBBUSD") + +time.sleep(2) + +my_client.ticker_book(symbols=["BNBBUSD", "BTCUSDT"]) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/ticker_price.py b/examples/websocket/spot/websocket_api/market/ticker_price.py new file mode 100644 index 00000000..2c02b102 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/ticker_price.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.ticker_price(symbol="BNBBUSD") + +time.sleep(2) + +my_client.ticker_price(symbols=["BNBBUSD", "BTCUSDT"]) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/market/ui_klines.py b/examples/websocket/spot/websocket_api/market/ui_klines.py new file mode 100644 index 00000000..559f7696 --- /dev/null +++ b/examples/websocket/spot/websocket_api/market/ui_klines.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient(on_message=message_handler, on_close=on_close) + + +my_client.ui_klines(symbol="BNBBUSD", interval="1m", limit=2) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/cancel_oco_order.py b/examples/websocket/spot/websocket_api/trade/cancel_oco_order.py new file mode 100644 index 00000000..e171a824 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/cancel_oco_order.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.cancel_oco_order(symbol="BNBUSDT", orderListId=15558) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/cancel_open_orders.py b/examples/websocket/spot/websocket_api/trade/cancel_open_orders.py new file mode 100644 index 00000000..5d9c8290 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/cancel_open_orders.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.cancel_open_orders(symbol="BNBUSDT") + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/cancel_order.py b/examples/websocket/spot/websocket_api/trade/cancel_order.py new file mode 100644 index 00000000..16402e85 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/cancel_order.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.cancel_order(symbol="BNBUSDT", orderId=1) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/cancel_replace_order.py b/examples/websocket/spot/websocket_api/trade/cancel_replace_order.py new file mode 100644 index 00000000..d171357e --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/cancel_replace_order.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.cancel_replace_order( + symbol="BNBUSDT", + cancelReplaceMode="STOP_ON_FAILURE", + cancelOrderId=1, + newClientOrderId="new_client_order_id", + side="BUY", + type="LIMIT", + timeInForce="GTC", + price=200, + quantity=1, +) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/get_oco_order.py b/examples/websocket/spot/websocket_api/trade/get_oco_order.py new file mode 100644 index 00000000..63e6e5ee --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/get_oco_order.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.get_oco_order(orderListId=15558) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/get_open_oco_orders.py b/examples/websocket/spot/websocket_api/trade/get_open_oco_orders.py new file mode 100644 index 00000000..a6bf2070 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/get_open_oco_orders.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.get_open_oco_orders() + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/get_open_orders.py b/examples/websocket/spot/websocket_api/trade/get_open_orders.py new file mode 100644 index 00000000..b0f62ab5 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/get_open_orders.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.get_open_orders(symbol="BNBUSDT") + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/get_order.py b/examples/websocket/spot/websocket_api/trade/get_order.py new file mode 100644 index 00000000..3ea43f6b --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/get_order.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.get_order(symbol="BNBUSDT", orderId=1) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/new_oco_order.py b/examples/websocket/spot/websocket_api/trade/new_oco_order.py new file mode 100644 index 00000000..27d39d34 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/new_oco_order.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.new_oco_order( + symbol="BNBUSDT", + side="BUY", + price=200, + quantity=1, + listClientOrderId="123", + limitClientOrderId="456", + stopPrice=350, + stopLimitPrice=400, + stopLimitTimeInForce="GTC", + newOrderRespType="RESULT", +) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/new_order.py b/examples/websocket/spot/websocket_api/trade/new_order.py new file mode 100644 index 00000000..79f96998 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/new_order.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.new_order( + id=12345678, + symbol="BNBUSDT", + side="BUY", + type="LIMIT", + timeInForce="GTC", + quantity=1, + price=200, + newClientOrderId="my_order_id_1", + newOrderRespType="RESULT", +) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/trade/new_order_test.py b/examples/websocket/spot/websocket_api/trade/new_order_test.py new file mode 100644 index 00000000..d390e130 --- /dev/null +++ b/examples/websocket/spot/websocket_api/trade/new_order_test.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.new_order_test( + symbol="BNBUSDT", + side="BUY", + type="LIMIT", + timeInForce="GTC", + quantity=1, + price=200, + newClientOrderId="my_order_id_1", + newOrderRespType="RESULT", +) + +time.sleep(2) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/user_data/user_data_ping.py b/examples/websocket/spot/websocket_api/user_data/user_data_ping.py new file mode 100644 index 00000000..08ea1fec --- /dev/null +++ b/examples/websocket/spot/websocket_api/user_data/user_data_ping.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.user_data_ping(listen_key="your_listen_key") + +time.sleep(10) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/user_data/user_data_start.py b/examples/websocket/spot/websocket_api/user_data/user_data_start.py new file mode 100644 index 00000000..b8f7f65d --- /dev/null +++ b/examples/websocket/spot/websocket_api/user_data/user_data_start.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.user_data_start() + +time.sleep(100) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_api/user_data/user_data_stop.py b/examples/websocket/spot/websocket_api/user_data/user_data_stop.py new file mode 100644 index 00000000..c3c5248a --- /dev/null +++ b/examples/websocket/spot/websocket_api/user_data/user_data_stop.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def on_close(_): + logging.info("Do custom stuff when connection is closed") + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketAPIClient( + stream_url="wss://testnet.binance.vision/ws-api/v3", + api_key=api_key, + api_secret=api_secret, + on_message=message_handler, + on_close=on_close, +) + + +my_client.user_data_stop(listenKey="your_listen_key") + +time.sleep(100) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/agg_trade.py b/examples/websocket/spot/websocket_stream/agg_trade.py new file mode 100644 index 00000000..51b6636c --- /dev/null +++ b/examples/websocket/spot/websocket_stream/agg_trade.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python + +import logging +import time +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler, is_combined=True) + +# Subscribe to a single symbol stream +my_client.agg_trade(symbol="bnbusdt") + +time.sleep(5) + +# Unsubscribe +my_client.agg_trade( + symbol="bnbusdt", action=SpotWebsocketStreamClient.ACTION_UNSUBSCRIBE +) + +time.sleep(5) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/all_symbols_mini_ticker.py b/examples/websocket/spot/websocket_stream/all_symbols_mini_ticker.py new file mode 100644 index 00000000..b0aaafe7 --- /dev/null +++ b/examples/websocket/spot/websocket_stream/all_symbols_mini_ticker.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +# subscribe to all symbols mini ticker stream +my_client.mini_ticker(symbol="bnbusdt") + +time.sleep(10) + +# unsubscribe +my_client.mini_ticker( + symbol="bnbusdt", action=SpotWebsocketStreamClient.ACTION_UNSUBSCRIBE +) + +time.sleep(10) + +logging.info("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/all_symbols_ticker.py b/examples/websocket/spot/websocket_stream/all_symbols_ticker.py new file mode 100644 index 00000000..46e55119 --- /dev/null +++ b/examples/websocket/spot/websocket_stream/all_symbols_ticker.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + print(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +# subscribe to all symbols ticker stream +my_client.ticker() + +time.sleep(5) + +# unsubscribe +my_client.ticker(action=SpotWebsocketStreamClient.ACTION_UNSUBSCRIBE) + +time.sleep(5) + +# subscribe to single symbol ticker stream +my_client.ticker(symbol="bnbusdt") + +time.sleep(5) + +# unsubscribe +my_client.ticker(symbol="bnbusdt", action=SpotWebsocketStreamClient.ACTION_UNSUBSCRIBE) + +time.sleep(5) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/book_ticker.py b/examples/websocket/spot/websocket_stream/book_ticker.py new file mode 100644 index 00000000..049e0c7e --- /dev/null +++ b/examples/websocket/spot/websocket_stream/book_ticker.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + print(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +my_client.book_ticker(symbol="btcusdt") + +time.sleep(10) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/combined_streams.py b/examples/websocket/spot/websocket_stream/combined_streams.py new file mode 100644 index 00000000..676b768f --- /dev/null +++ b/examples/websocket/spot/websocket_stream/combined_streams.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +import logging +import time + +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) +counter = 1 + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler, is_combined=True) + + +# subscribe one stream +my_client.kline(symbol="bnbusdt", interval="1m") + +time.sleep(4) + +# subscribe another +my_client.ticker(symbol="ethusdt") + +time.sleep(10) +my_client.stop() diff --git a/examples/websocket/spot/all_symbols_mini_ticker.py b/examples/websocket/spot/websocket_stream/diff_book_depth.py similarity index 50% rename from examples/websocket/spot/all_symbols_mini_ticker.py rename to examples/websocket/spot/websocket_stream/diff_book_depth.py index 7aef2240..c78f7658 100644 --- a/examples/websocket/spot/all_symbols_mini_ticker.py +++ b/examples/websocket/spot/websocket_stream/diff_book_depth.py @@ -3,23 +3,19 @@ import time import logging from binance.lib.utils import config_logging -from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient config_logging(logging, logging.DEBUG) -def message_handler(message): +def message_handler(_, message): print(message) -my_client = Client() -my_client.start() +my_client = SpotWebsocketStreamClient(on_message=message_handler) -my_client.mini_ticker( - id=2, - callback=message_handler, -) +my_client.diff_book_depth(symbol="bnbusdt", speed=1000) time.sleep(30) diff --git a/examples/websocket/spot/websocket_stream/partial_book_depth.py b/examples/websocket/spot/websocket_stream/partial_book_depth.py new file mode 100644 index 00000000..943a657d --- /dev/null +++ b/examples/websocket/spot/websocket_stream/partial_book_depth.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + print(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +my_client.partial_book_depth(symbol="bnbusdt", level=10, speed=1000) + +time.sleep(10) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/rolling_window_ticker.py b/examples/websocket/spot/websocket_stream/rolling_window_ticker.py new file mode 100644 index 00000000..5df06bec --- /dev/null +++ b/examples/websocket/spot/websocket_stream/rolling_window_ticker.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +my_client.rolling_window_ticker("BNBUSDT", "1h") + +time.sleep(10) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/rolling_window_ticker_all_symbols.py b/examples/websocket/spot/websocket_stream/rolling_window_ticker_all_symbols.py new file mode 100644 index 00000000..36c84d64 --- /dev/null +++ b/examples/websocket/spot/websocket_stream/rolling_window_ticker_all_symbols.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +my_client.rolling_window_ticker_all_symbols(windowSize="1h") + +time.sleep(10) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/symbol_kline.py b/examples/websocket/spot/websocket_stream/symbol_kline.py new file mode 100644 index 00000000..6a4256fe --- /dev/null +++ b/examples/websocket/spot/websocket_stream/symbol_kline.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler, is_combined=True) + + +# subscribe btcusdt 1m kline +my_client.kline(symbol="btcusdt", interval="1m") + +time.sleep(5) + +# subscribe ethusdt 3m kline +my_client.kline(symbol="ethusdt", interval="3m") + +time.sleep(10) + +# unsubscribe btcusdt 1m kline +my_client.kline( + symbol="btcusdt", interval="1m", action=SpotWebsocketStreamClient.ACTION_UNSUBSCRIBE +) + +time.sleep(5) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/symbol_mini_ticker.py b/examples/websocket/spot/websocket_stream/symbol_mini_ticker.py new file mode 100644 index 00000000..ebca7c81 --- /dev/null +++ b/examples/websocket/spot/websocket_stream/symbol_mini_ticker.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +my_client.mini_ticker(symbol="bnbusdt") + +time.sleep(30) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/symbol_ticker.py b/examples/websocket/spot/websocket_stream/symbol_ticker.py new file mode 100644 index 00000000..de6d33fb --- /dev/null +++ b/examples/websocket/spot/websocket_stream/symbol_ticker.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient as Client + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = Client(on_message=message_handler) + + +my_client.ticker(symbol="bnbusdt") + +time.sleep(30) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/test.py b/examples/websocket/spot/websocket_stream/test.py new file mode 100644 index 00000000..69da7777 --- /dev/null +++ b/examples/websocket/spot/websocket_stream/test.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient as Client + +config_logging(logging, logging.DEBUG) + + +def message_handler(socketMangar, message): + logging.info(message) + + +def on_ping(socketMangar): + logging.info("received ping from server") + + +def on_pong(socketMangar): + logging.info("received pong from server") + + +def on_open(socketMangar): + logging.info("opened connection") + + +def on_close(socketMangar): + logging.info("Closing connection received") + + +my_client = Client( + on_open=on_open, + on_message=message_handler, + on_ping=on_ping, + on_pong=on_pong, + on_close=on_close, + is_combined=True, +) + + +my_client.kline(symbol="bnbusdt", interval="1m") + +time.sleep(5) + +my_client.ping() + +time.sleep(10) + +my_client.list_subscribe() + +time.sleep(10) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/trade.py b/examples/websocket/spot/websocket_stream/trade.py new file mode 100644 index 00000000..b20b4bec --- /dev/null +++ b/examples/websocket/spot/websocket_stream/trade.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +my_client = SpotWebsocketStreamClient(on_message=message_handler) + + +my_client.trade(symbol="bnbusdt") + +time.sleep(10) + +logging.debug("closing ws connection") +my_client.stop() diff --git a/examples/websocket/spot/websocket_stream/user_data.py b/examples/websocket/spot/websocket_stream/user_data.py new file mode 100644 index 00000000..765d82eb --- /dev/null +++ b/examples/websocket/spot/websocket_stream/user_data.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +import time +import logging +from binance.lib.utils import config_logging +from binance.spot import Spot as Client +from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient +from examples.utils.prepare_env import get_api_key + +api_key, api_secret = get_api_key() + +config_logging(logging, logging.DEBUG) + + +def message_handler(_, message): + logging.info(message) + + +# get listen key from testnet, make sure you are using testnet api key +client = Client(api_key, base_url="https://testnet.binance.vision") +response = client.new_listen_key() + +logging.info("Receving listen key : {}".format(response["listenKey"])) + +# create the websocket connection to testnet as well +ws_client = SpotWebsocketStreamClient( + stream_url="wss://testnet.binance.vision", on_message=message_handler +) + +ws_client.user_data(listen_key=response["listenKey"]) + +time.sleep(30) + +# You don't have to, but just in case you want to unsubscribe +logging.info("unsubscribe user data") +ws_client.user_data( + response["listenKey"], action=SpotWebsocketStreamClient.ACTION_UNSUBSCRIBE +) + +time.sleep(300) + +logging.debug("closing ws connection") +ws_client.stop() diff --git a/requirements/common.txt b/requirements/common.txt index 63040458..3df274d3 100644 --- a/requirements/common.txt +++ b/requirements/common.txt @@ -1,6 +1,3 @@ -autobahn>=21.2.1 -Twisted>=21.2.0 requests>=2.25.1 -pyOpenSSL>=19.0.0 -service-identity>=21.1.0 +websocket-client>=1.5.0 pycryptodome>=3.15.0 diff --git a/tests/lib/test_utils.py b/tests/lib/test_utils.py index 65205d81..511fd743 100644 --- a/tests/lib/test_utils.py +++ b/tests/lib/test_utils.py @@ -7,6 +7,7 @@ check_required_parameter, check_type_parameter, convert_list_to_json_array, + purge_map, ) from binance.lib.utils import check_required_parameters from binance.lib.utils import check_enum_parameter @@ -108,3 +109,11 @@ def test_encode_query_without_email_symbol(): def test_convert_list_to_json_array(): convert_list_to_json_array(["symbol"]).should.equal('["symbol"]') + + +def test_remove_empty_parameter(): + purge_map({"foo": "bar", "foo2": None}).should.equal({"foo": "bar"}) + purge_map({"foo": "bar", "foo2": ""}).should.equal({"foo": "bar"}) + purge_map({"foo": "bar", "foo2": 0}).should.equal({"foo": "bar"}) + purge_map({"foo": "bar", "foo2": []}).should.equal({"foo": "bar", "foo2": []}) + purge_map({"foo": "bar", "foo2": {}}).should.equal({"foo": "bar", "foo2": {}})