Skip to main content

BitMart Exchange official(https://bitmart.com) Python client for the BitMart Cloud API

Project description

Logo

BitMart-Python-SDK-API

PyPI version Python version License: MIT Telegram

BitMart Exchange official Python client for the BitMart Cloud API.

Feature

  • Provides exchange quick trading API
  • Easier withdrawal
  • Efficiency, higher speeds, and lower latencies
  • Priority in development and maintenance
  • Dedicated and responsive technical support
  • Supported APIs:
    • /spot/*
    • /contract/*
    • /account/*
  • Supported websockets:
    • Spot WebSocket Market Stream
    • Spot User Data Stream
    • futures User Data Stream
    • futures WebSocket Market Stream
  • Test cases and examples

Installation

pip install bitmart-python-sdk-api

Documentation

API Documentation

Example

Spot Public API Example

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 Trade API Example

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'])
    

Please find examples/spot folder to check for more endpoints.

Spot WebSocket Public Channel Example

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 WebSocket Private Channel Example

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()

Please find examples/websocket/spot/websocket_stream folder to check for more endpoints.

Futures Public API Example

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

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'])

Please find examples/futures folder to check for more endpoints.

Futures WebSocket Public Channel Example

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

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()

Please find examples/websocket/futures/websocket_stream folder to check for more endpoints.

Extra Options

Authentication

How to set API KEY?

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")

Timeout

Set HTTP connection timeout and read timeout.

from bitmart.api_spot import APISpot
from bitmart.api_contract import APIContract
spotAPI = APISpot(timeout=(2, 10))
contractAPI = APIContract(timeout=(2, 10))

Logging

If you want to debug the data requested by the API and the corresponding data returned by the API, you can set it like this:

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)

Domain

How to set API domain name? The domain name parameter is optional, the default domain name is https://api-cloud.bitmart.com.

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')

Custom request headers

You can add your own request header information here, but please do not fill in X-BM-KEY, X-BM-SIGN, X-BM-TIMESTAMP

from bitmart.api_spot import APISpot
spotAPI = APISpot(headers={'Your-Custom-Header': 'xxxxxxx'})

Response Metadata

The bitmart API server provides the endpoint rate limit usage in the header of each response. This information can be obtained from the headers property. x-bm-ratelimit-remaining indicates the number of times the current window has been used, x-bm-ratelimit-limit indicates the maximum number of times the current window can be used, and x-bm-ratelimit-reset indicates the current window time.

Example:
x-bm-ratelimit-mode: IP
x-bm-ratelimit-remaining: 10
x-bm-ratelimit-limit: 600
x-bm-ratelimit-reset: 60

This means that this IP can call the endpoint 600 times within 60 seconds, and has called 10 times so far.

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']}")

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bitmart_python_sdk_api-2.5.0.tar.gz (29.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bitmart_python_sdk_api-2.5.0-py3-none-any.whl (29.5 kB view details)

Uploaded Python 3

File details

Details for the file bitmart_python_sdk_api-2.5.0.tar.gz.

File metadata

  • Download URL: bitmart_python_sdk_api-2.5.0.tar.gz
  • Upload date:
  • Size: 29.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for bitmart_python_sdk_api-2.5.0.tar.gz
Algorithm Hash digest
SHA256 b792d63e3c34be1295d4e00093fdf6202c20fecda631c0ac7e0d5eaf991ed68e
MD5 60b29ab4444d1bc65f2f1522e07b73bc
BLAKE2b-256 150b28a496107970843de1f9420cb30e687a6438aca490b3e627d5b2926b2c9c

See more details on using hashes here.

Provenance

The following attestation bundles were made for bitmart_python_sdk_api-2.5.0.tar.gz:

Publisher: release.yml on bitmartexchange/bitmart-python-sdk-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file bitmart_python_sdk_api-2.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for bitmart_python_sdk_api-2.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f965c8c721a777b4222959583d32ef1d39159a0c2989604bfac7042d1aee310d
MD5 9cbb267bcf492be269d9ed793527d1e4
BLAKE2b-256 a5dae35f46f1d2e9c5720394c41a9712bf38eaf18a5148971414dc3fffb0bc30

See more details on using hashes here.

Provenance

The following attestation bundles were made for bitmart_python_sdk_api-2.5.0-py3-none-any.whl:

Publisher: release.yml on bitmartexchange/bitmart-python-sdk-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page