### Install BitMart Python SDK Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Use pip to install the BitMart Python SDK. This command installs the latest version of the library. ```bash pip install bitmart-python-sdk-api ``` -------------------------------- ### Spot Public API Examples Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Examples demonstrating how to use the APISpot class to fetch public market data. Requires instantiation of APISpot without API keys. ```python from bitmart.api_spot import APISpot if __name__ == '__main__': spotAPI = APISpot(timeout=(2, 10)) # Get a list of all cryptocurrencies on the platform response = spotAPI.get_currencies() print("response:", response[0]) # Querying aggregated tickers of a particular trading pair response = spotAPI.get_v3_ticker(symbol='BTC_USDT') print("response:", response[0]) # Get the quotations of all trading pairs response = spotAPI.get_v3_tickers() print("response:", response[0]) # Get full depth of trading pairs response = spotAPI.get_v3_depth(symbol='BTC_USDT') print("response:", response[0]) # Get the latest trade records of the specified trading pair response = spotAPI.get_v3_trades(symbol='BTC_USDT', limit=10) print("response:", response[0]) ``` -------------------------------- ### Spot WebSocket Private Channel Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Example demonstrating how to connect to the Spot private WebSocket stream to receive user-specific data like balance updates. ```APIDOC ## Spot WebSocket Private Channel ### Description Connects to the private WebSocket stream for Spot trading to receive real-time user balance updates. ### Usage Instantiate `SpotSocketClient` with your API credentials and a message handler. Then, log in and subscribe to the desired streams. ### Code Example ```python import logging from bitmart.lib.cloud_consts import SPOT_PRIVATE_WS_URL from bitmart.lib.cloud_utils import config_logging from bitmart.websocket.spot_socket_client import SpotSocketClient def message_handler(message): logging.info(f"message_handler: {message}") if __name__ == '__main__': config_logging(logging, logging.INFO) my_client = SpotSocketClient(stream_url=SPOT_PRIVATE_WS_URL, on_message=message_handler, api_key="your_api_key", api_secret_key="your_secret_key", api_memo="your_api_memo") # Login my_client.login() # Subscribe to a single symbol stream my_client.subscribe(args="spot/user/balance:BALANCE_UPDATE") # Stop # my_client.stop() ``` ### Further Examples Refer to the [examples/websocket/spot/websocket_stream](https://github.com/bitmartexchange/bitmart-python-sdk-api/tree/master/examples/websocket/spot/websocket_stream) folder for more endpoints. ``` -------------------------------- ### Futures Trade API Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Example demonstrating how to submit a limit order for Futures trading using the API. ```APIDOC ## Futures Trade API - Submit Order ### Description Submits a limit order for Futures trading. Handles potential API exceptions. ### Method `post_submit_order(contract_symbol, client_order_id, side, mode, type, leverage, open_type, size, price)` ### Parameters - `contract_symbol` (string) - Required - The symbol of the contract (e.g., 'BTCUSDT'). - `client_order_id` (string) - Required - A unique client-generated order ID. - `side` (integer) - Required - Order side: 1 for buy, 4 for sell. - `mode` (integer) - Required - Trading mode: 1 for cross margin, 2 for isolated margin. - `type` (string) - Required - Order type: 'limit', 'market', etc. - `leverage` (string) - Required - Leverage amount. - `open_type` (string) - Required - Position opening type: 'isolated' or 'cross'. - `size` (integer) - Required - The quantity of the order. - `price` (string) - Required - The price for a limit order. ### Request Example ```python from bitmart.api_contract import APIContract from bitmart.lib import cloud_exceptions if __name__ == '__main__': api_key = "Your API KEY" secret_key = "Your Secret KEY" memo = "Your Memo" contractAPI = APIContract(api_key, secret_key, memo, timeout=(3, 10)) try: response = contractAPI.post_submit_order(contract_symbol='BTCUSDT', client_order_id="BM1234", side=4, # Sell mode=1, # Cross Margin type='limit', leverage='1', open_type='isolated', size=10, price='20000') except cloud_exceptions.APIException as apiException: print("Error[HTTP<>200]:", apiException.response) except Exception as exception: print("Error[Exception]:", exception) else: if response[0]['code'] == 1000: print('Call Success:', response[0]) else: print('Call Failed:', response[0]['message']) ``` ### Further Examples Refer to the [examples/futures](https://github.com/bitmartexchange/bitmart-python-sdk-api/tree/master/examples/futures) folder for more endpoints. ``` -------------------------------- ### Spot WebSocket Public Channel Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Demonstrates subscribing and unsubscribing to public spot market data streams using SpotSocketClient. Requires configuration of logging and the WebSocket URL. ```python import logging import time from bitmart.lib.cloud_consts import SPOT_PUBLIC_WS_URL from bitmart.lib.cloud_utils import config_logging from bitmart.websocket.spot_socket_client import SpotSocketClient def message_handler(message): logging.info(f"message_handler: {message}") if __name__ == '__main__': config_logging(logging, logging.INFO) my_client = SpotSocketClient(stream_url=SPOT_PUBLIC_WS_URL, on_message=message_handler) # Subscribe to a single symbol stream my_client.subscribe(args="spot/ticker:BMX_USDT") # Subscribe to multiple symbol streams my_client.subscribe(args=["spot/ticker:BMX_USDT", "spot/ticker:BTC_USDT"]) # Send the original subscription message my_client.send({"op": "subscribe", "args": ["spot/ticker:ETH_USDT"]}) time.sleep(5) # Unsubscribe my_client.unsubscribe(args="spot/ticker:BMX_USDT") my_client.send({"op": "unsubscribe", "args": ["spot/ticker:BMX_USDT"]}) ``` -------------------------------- ### Spot Trade API Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Example of submitting a limit order using the APISpot class. Requires API key, secret key, and memo. Includes error handling for API exceptions. ```python from bitmart.api_spot import APISpot from bitmart.lib import cloud_exceptions if __name__ == '__main__': api_key = "Your API KEY" secret_key = "Your Secret KEY" memo = "Your Memo" try: spotAPI = APISpot(api_key, secret_key, memo, timeout=(3, 10)) response = spotAPI.post_submit_order( symbol='BTC_USDT', side='sell', type='limit', size='10000', price='1000000' ) except cloud_exceptions.APIException as apiException: print("Error[HTTP<>200]:", apiException.response) except Exception as exception: print("Error[Exception]:", exception) else: if response[0]['code'] == 1000: print('Call Success:', response[0]) else: print('Call Failed:', response[0]['message']) ``` -------------------------------- ### Futures WebSocket Public Channel Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Example demonstrating how to connect to the Futures public WebSocket stream to subscribe to ticker data. ```APIDOC ## Futures WebSocket Public Channel ### Description Connects to the public WebSocket stream for Futures to receive real-time market data like ticker updates. ### Usage Instantiate `FuturesSocketClient` with the stream URL and a message handler. You can then use `subscribe` or `send` methods to manage subscriptions. ### Code Example ```python import logging import time from bitmart.lib.cloud_consts import FUTURES_PUBLIC_WS_URL from bitmart.lib.cloud_utils import config_logging from bitmart.websocket.futures_socket_client import FuturesSocketClient def message_handler(message): logging.info(f"message_handler: {message}") if __name__ == '__main__': config_logging(logging, logging.INFO) my_client = FuturesSocketClient(stream_url=FUTURES_PUBLIC_WS_URL, on_message=message_handler) # Example 1: Subscribe to a single symbol stream my_client.subscribe(args="futures/ticker:BTCUSDT") time.sleep(2) # Unsubscribe my_client.unsubscribe(args="futures/ticker:BTCUSDT") time.sleep(5) # Example 2: Send the original subscription message my_client.send({"action": "subscribe", "args": ["futures/ticker:BTCUSDT"]}) time.sleep(2) # Unsubscribe my_client.send({"action": "unsubscribe", "args": ["futures/ticker:BTCUSDT"]}) # Stop # my_client.stop() ``` ``` -------------------------------- ### Futures Public API Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Examples of how to use the Futures API to query contract details, depth, open interest, funding rates, and K-line data. ```APIDOC ## Futures Public API ### Description Provides access to public data for BitMart Futures, including market data and contract information. ### Methods - `get_details(contract_symbol)`: Query contract details. - `get_depth(contract_symbol)`: Get full depth of trading pairs. - `get_open_interest(contract_symbol)`: Query open interest and open interest value. - `get_funding_rate(contract_symbol)`: Check the current funding rate. - `get_kline(contract_symbol, step, start_time, end_time)`: Query K-line (candlestick) data. ### Code Example ```python import time from bitmart.api_contract import APIContract if __name__ == '__main__': contractAPI = APIContract(timeout=(2, 10)) # query contract details response = contractAPI.get_details(contract_symbol='ETHUSDT') print("response:", response[0]) # Get full depth of trading pairs. response = contractAPI.get_depth(contract_symbol='ETHUSDT') print("response:", response[0]) # Querying the open interest and open interest value data of the specified contract response = contractAPI.get_open_interest(contract_symbol='ETHUSDT') print("response:", response[0]) # Applicable for checking the current funding rate of a specified contract response = contractAPI.get_funding_rate(contract_symbol='ETHUSDT') print("response:", response[0]) # querying K-line data end_time = int(time.time()) start_time = end_time - 3600 response = contractAPI.get_kline(contract_symbol='ETHUSDT', step=5, start_time=start_time, end_time=end_time) print("response:", response[0]) ``` ``` -------------------------------- ### Futures Trade API Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Shows how to submit a limit order for futures trading using the APIContract class. Requires API key, secret key, and memo for authentication. Includes error handling for API exceptions and general exceptions. ```python from bitmart.api_contract import APIContract from bitmart.lib import cloud_exceptions if __name__ == '__main__': api_key = "Your API KEY" secret_key = "Your Secret KEY" memo = "Your Memo" contractAPI = APIContract(api_key, secret_key, memo, timeout=(3, 10)) try: response = contractAPI.post_submit_order(contract_symbol='BTCUSDT', client_order_id="BM1234", side=4, mode=1, type='limit', leverage='1', open_type='isolated', size=10, price='20000') except cloud_exceptions.APIException as apiException: print("Error[HTTP<>200]:", apiException.response) except Exception as exception: print("Error[Exception]:", exception) else: if response[0]['code'] == 1000: print('Call Success:', response[0]) else: print('Call Failed:', response[0]['message']) ``` -------------------------------- ### Spot WebSocket Private Channel Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Connects to the spot private WebSocket stream to receive user-specific data like balance updates. Requires API key, secret key, and memo for authentication. Ensure logging is configured. ```python import logging from bitmart.lib.cloud_consts import SPOT_PRIVATE_WS_URL from bitmart.lib.cloud_utils import config_logging from bitmart.websocket.spot_socket_client import SpotSocketClient def message_handler(message): logging.info(f"message_handler: {message}") if __name__ == '__main__': config_logging(logging, logging.INFO) my_client = SpotSocketClient(stream_url=SPOT_PRIVATE_WS_URL, on_message=message_handler, api_key="your_api_key", api_secret_key="your_secret_key", api_memo="your_api_memo") # Login my_client.login() # Subscribe to a single symbol stream my_client.subscribe(args="spot/user/balance:BALANCE_UPDATE") # Stop # my_client.stop() ``` -------------------------------- ### Futures WebSocket Public Channel Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Connects to the futures public WebSocket stream for real-time market data like tickers. Demonstrates subscribing, unsubscribing, and sending raw messages. Logging must be configured. ```python import logging import time from bitmart.lib.cloud_consts import FUTURES_PUBLIC_WS_URL from bitmart.lib.cloud_utils import config_logging from bitmart.websocket.futures_socket_client import FuturesSocketClient def message_handler(message): logging.info(f"message_handler: {message}") if __name__ == '__main__': config_logging(logging, logging.INFO) my_client = FuturesSocketClient(stream_url=FUTURES_PUBLIC_WS_URL, on_message=message_handler) # Example 1: # Subscribe to a single symbol stream my_client.subscribe(args="futures/ticker:BTCUSDT") time.sleep(2) # Unsubscribe my_client.unsubscribe(args="futures/ticker:BTCUSDT") time.sleep(5) # Example 2: # Send the original subscription message my_client.send({"action": "subscribe", "args": ["futures/ticker:BTCUSDT"]}) time.sleep(2) # Unsubscribe my_client.send({"action": "unsubscribe", "args": ["futures/ticker:BTCUSDT"]}) # Stop # my_client.stop() ``` -------------------------------- ### Futures WebSocket Private Channel Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Connects to the futures private WebSocket stream, logs in, and subscribes to asset streams for single and multiple symbols. Ensure your API key, secret key, and memo are correctly configured. ```python import logging from bitmart.lib.cloud_consts import FUTURES_PRIVATE_WS_URL from bitmart.lib.cloud_utils import config_logging from bitmart.websocket.futures_socket_client import FuturesSocketClient def message_handler(message): logging.info(f"message_handler: {message}") if __name__ == '__main__': config_logging(logging, logging.INFO) my_client = FuturesSocketClient(stream_url=FUTURES_PRIVATE_WS_URL, on_message=message_handler, api_key="your_api_key", api_secret_key="your_secret_key", api_memo="your_api_memo") # Login my_client.login() # Subscribe to a single symbol stream my_client.subscribe(args="futures/asset:USDT") # Subscribe to multiple symbol streams my_client.subscribe(args=["futures/asset:BTC", "futures/asset:ETH"]) # Stop # my_client.stop() ``` -------------------------------- ### Futures Public API Example Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Demonstrates how to query various public endpoints for futures trading using the APIContract class. Includes fetching contract details, depth, open interest, funding rates, and K-line data. Set a timeout for API requests. ```python import time from bitmart.api_contract import APIContract if __name__ == '__main__': contractAPI = APIContract(timeout=(2, 10)) # query contract details response = contractAPI.get_details(contract_symbol='ETHUSDT') print("response:", response[0]) # Get full depth of trading pairs. response = contractAPI.get_depth(contract_symbol='ETHUSDT') print("response:", response[0]) # Querying the open interest and open interest value data of the specified contract response = contractAPI.get_open_interest(contract_symbol='ETHUSDT') print("response:", response[0]) # Applicable for checking the current funding rate of a specified contract response = contractAPI.get_funding_rate(contract_symbol='ETHUSDT') print("response:", response[0]) # querying K-line data end_time = int(time.time()) start_time = end_time - 3600 response = contractAPI.get_kline(contract_symbol='ETHUSDT', step=5, start_time=start_time, end_time=end_time) print("response:", response[0]) ``` -------------------------------- ### Set API Key for Spot and Contract Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Initializes the Spot and Contract API clients with your API access key, secret key, and memo. These credentials are required for authenticated requests. ```python from bitmart.api_spot import APISpot from bitmart.api_contract import APIContract spotAPI = APISpot(api_key="your api access key", secret_key="your api secret key", memo="your api memo") contractAPI = APIContract(api_key="your api access key", secret_key="your api secret key", memo="your api memo") ``` -------------------------------- ### Set Custom API Domain Name Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Specifies a custom API domain name for the Spot and Contract clients. If not provided, the default domain `https://api-cloud.bitmart.com` is used. ```python from bitmart.api_spot import APISpot from bitmart.api_contract import APIContract spotAPI = APISpot(url='https://api-cloud.bitmart.com') contractAPI = APIContract(url='https://api-cloud-v2.bitmart.com') ``` -------------------------------- ### Set HTTP Connection and Read Timeouts Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Configures the connection and read timeouts for HTTP requests. The `timeout` parameter accepts a tuple where the first element is the connection timeout and the second is the read timeout. ```python from bitmart.api_spot import APISpot from bitmart.api_contract import APIContract spotAPI = APISpot(timeout=(2, 10)) contractAPI = APIContract(timeout=(2, 10)) ``` -------------------------------- ### Access Response Rate Limit Metadata Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Retrieves currency information and extracts rate limit details from the response headers. This includes remaining calls, limit per window, reset time, and mode. ```python import logging from bitmart.api_spot import APISpot logger = logging.getLogger(__name__) spotAPI = APISpot() response = spotAPI.get_currencies()[0] limit = spotAPI.get_currencies()[1] logger.info(f"x-bm-ratelimit-remaining={limit['Remaining']}," f"x-bm-ratelimit-limit={limit['Limit']}," f"x-bm-ratelimit-reset={limit['Reset']}," f"x-bm-ratelimit-mode={limit['Mode']}") ``` -------------------------------- ### Enable API Debug Logging Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Configures the logging level to DEBUG to capture detailed information about API requests and responses. A logger instance is created and passed to the API client. ```python import logging from bitmart.api_spot import APISpot from bitmart.lib.cloud_utils import config_logging config_logging(logging, logging.DEBUG) logger = logging.getLogger(__name__) spotAPI = APISpot(logger=logger) ``` -------------------------------- ### Add Custom Request Headers Source: https://github.com/bitmartexchange/bitmart-python-sdk-api/blob/master/README.md Allows adding custom headers to API requests. Note that sensitive headers like `X-BM-KEY`, `X-BM-SIGN`, and `X-BM-TIMESTAMP` should not be included. ```python from bitmart.api_spot import APISpot spotAPI = APISpot(headers={'Your-Custom-Header': 'xxxxxxx'}) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.