binance-futures-connector


Namebinance-futures-connector JSON
Version 4.0.0 PyPI version JSON
download
home_pagehttps://github.com/binance/binance-futures-connector-python
SummaryThis is a lightweight library that works as a connector to Binance Futures public API.
upload_time2023-08-08 17:53:31
maintainer
docs_urlNone
author
requires_python>=3.7
licenseMIT
keywords binance futures public api
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Binance Futures Public API Connector Python
[![Python version](https://img.shields.io/pypi/pyversions/binance-futures-connector)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

This is a lightweight library that works as a connector to [Binance Futures public API](https://binance-docs.github.io/apidocs/futures/en/)

- Supported APIs:
    - USDT-M Futures `/fapi/*`
    - COIN-M Delivery `/dapi/*`
    - Futures/Delivery Websocket Market Stream
    - Futures/Delivery User Data Stream
- Inclusion of examples
- Customizable base URL, request timeout
- Response metadata can be displayed

## Installation

```bash
pip install binance-futures-connector
```


## RESTful APIs

Usage examples:
```python

from binance.cm_futures import CMFutures

cm_futures_client = CMFutures()

# get server time
print(cm_futures_client.time())

cm_futures_client = CMFutures(key='<api_key>', secret='<api_secret>')

# Get account information
print(cm_futures_client.account())

# Post a new order
params = {
    'symbol': 'BTCUSDT',
    'side': 'SELL',
    'type': 'LIMIT',
    'timeInForce': 'GTC',
    'quantity': 0.002,
    'price': 59808
}

response = cm_futures_client.new_order(**params)
print(response)
```
Please find `examples` folder to check for more endpoints.

## Authentication
Binance supports HMAC and RSA API authentication.

```python
# HMAC Authentication
client = Client(api_key, api_secret)
print(client.account())

# RSA Authentication
key = ""
with open("/Users/john/private_key.pem", "r") as f: # Location of private key file
    private_key = f.read()
private_key_passphrase = "" # Optional: only used for encrypted RSA key

client = Client(key=key, private_key=private_key, private_key_passphrase=private_key_passphrase)
print(client.account())
```
Please see `examples/um_futures/trade/get_account.py` or `examples/cm_futures/trade/get_account.py` for more details.

### Base URL

For USDT-M Futures, if `base_url` is not provided, it defaults to `fapi.binance.com`.<br/>
For COIN-M Delivery, if `base_url` is not provided, it defaults to `dapi.binance.com`.<br/>
It's recommended to pass in the `base_url` parameter, even in production as Binance provides alternative URLs

### Optional parameters

PEP8 suggests _lowercase with words separated by underscores_, but for this connector,
the methods' optional parameters should follow their exact naming as in the API documentation.

```python
# Recognised parameter name
response = client.query_order('BTCUSDT', orderListId=1)

# Unrecognised parameter name
response = client.query_order('BTCUSDT', order_list_id=1)
```

### RecvWindow parameter

Additional parameter `recvWindow` is available for endpoints requiring signature.<br/>
It defaults to `5000` (milliseconds) and can be any value lower than `60000`(milliseconds).
Anything beyond the limit will result in an error response from Binance server.

```python
from binance.cm_futures import CMFutures

cm_futures_client = CMFutures(key='<api_key>', secret='<api_secret>')
response = cm_futures_client.query_order('BTCUSDT', orderId=11, recvWindow=10000)
```

### Timeout

`timeout` is available to be assigned with the number of seconds you find most appropriate to wait for a server response.<br/>
Please remember the value as it won't be shown in error message _no bytes have been received on the underlying socket for timeout seconds_.<br/>
By default, `timeout` is None. Hence, requests do not time out.

```python
from binance.cm_futures import CMFutures

client= CMFutures(timeout=1)
```

### Proxy
proxy is supported

```python
from binance.cm_futures import CMFutures

proxies = { 'https': 'http://1.2.3.4:8080' }

client= CMFutures(proxies=proxies)
```

### Response Metadata

The Binance API server provides weight usages in the headers of each response.
You can display them by initializing the client with `show_limit_usage=True`:

```python
from binance.cm_futures import CMFutures

client = CMFutures(show_limit_usage=True)
print(client.time())
```
returns:

```python
{'limit_usage': {'x-mbx-used-weight-1m': '1'}, 'data': {'serverTime': 1653563092778}}
```
You can also display full response metadata to help in debugging:

```python
client = Client(show_header=True)
print(client.time())
```

returns:

```python
{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}
```

If `ClientError` is received, it'll display full response meta information.

### Display logs

Setting the log level to `DEBUG` will log the request URL, payload and response text.

### Error

There are 2 types of error returned from the library:
- `binance.error.ClientError`
    - This is thrown when server returns `4XX`, it's an issue from client side.
    - It has 4 properties:
        - `status_code` - HTTP status code
        - `error_code` - Server's error code, e.g. `-1102`
        - `error_message` - Server's error message, e.g. `Unknown order sent.`
        - `header` - Full response header.
- `binance.error.ServerError`
    - This is thrown when server returns `5XX`, it's an issue from server side.

## Websocket

### Connector v4

WebSocket can be established through the following connections:
- USD-M WebSocket Stream (`https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams`)
- COIN-M WebSocket Stream (`https://binance-docs.github.io/apidocs/delivery/en/#websocket-market-streams`)

```python
# WebSocket Stream Client
import time
from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient

def message_handler(_, message):
    logging.info(message)

my_client = UMFuturesWebsocketClient(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.agg_trade(symbol="bnbusdt", id="my_request_id")

# library will generate a random uuid string
my_client.agg_trade(symbol="bnbusdt")
```
#### Proxy

Proxy is supported for both WebSocket CM futures and UM futures.

To use it, pass in the `proxies` parameter when initializing the client.

The format of the `proxies` parameter is the same as the one used in the Spot RESTful API.

It consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL:

For websockets, the proxy type is `http`.

```python
proxies = { 'http': 'http://1.2.3.4:8080' }
```

You can also use authentication for the proxy by adding the `username` and `password` parameters to the proxy URL:

```python
proxies = { 'http': 'http://username:password@host:port' }
```

```python
# WebSocket Stream Client
import time
from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient

proxies = {'http': 'http://1.2.3.4:8080'}

def message_handler(_, message):
    logging.info(message)

my_client = UMFuturesWebsocketClient(on_message=message_handler, proxies=proxies)

# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
```


#### Combined Streams
- If you set `is_combined` to `True`, `"/stream/"` will be appended to the `baseURL` to allow for Combining streams.
- `is_combined` defaults to `False` and `"/ws/"` (raw streams) will be appended to the `baseURL`.

More websocket examples are available in the `examples` folder

## Websocket < v4

```python
import time
from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient

def message_handler(message):
    print(message)

my_client = UMFuturesWebsocketClient(on_message=message_handler)

# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
print("closing ws connection")
my_client.stop()

```

### Heartbeat

Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within
a 10 minutes period. This package handles the pong responses automatically.

## License
MIT

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/binance/binance-futures-connector-python",
    "name": "binance-futures-connector",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "Binance futures,Public API",
    "author": "",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/46/7d/f708df1b97761d28071323040ae7ed713af7b43a836e60152edcdf5cced5/binance-futures-connector-4.0.0.tar.gz",
    "platform": null,
    "description": "# Binance Futures Public API Connector Python\n[![Python version](https://img.shields.io/pypi/pyversions/binance-futures-connector)](https://www.python.org/downloads/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nThis is a lightweight library that works as a connector to [Binance Futures public API](https://binance-docs.github.io/apidocs/futures/en/)\n\n- Supported APIs:\n    - USDT-M Futures `/fapi/*`\n    - COIN-M Delivery `/dapi/*`\n    - Futures/Delivery Websocket Market Stream\n    - Futures/Delivery User Data Stream\n- Inclusion of examples\n- Customizable base URL, request timeout\n- Response metadata can be displayed\n\n## Installation\n\n```bash\npip install binance-futures-connector\n```\n\n\n## RESTful APIs\n\nUsage examples:\n```python\n\nfrom binance.cm_futures import CMFutures\n\ncm_futures_client = CMFutures()\n\n# get server time\nprint(cm_futures_client.time())\n\ncm_futures_client = CMFutures(key='<api_key>', secret='<api_secret>')\n\n# Get account information\nprint(cm_futures_client.account())\n\n# Post a new order\nparams = {\n    'symbol': 'BTCUSDT',\n    'side': 'SELL',\n    'type': 'LIMIT',\n    'timeInForce': 'GTC',\n    'quantity': 0.002,\n    'price': 59808\n}\n\nresponse = cm_futures_client.new_order(**params)\nprint(response)\n```\nPlease find `examples` folder to check for more endpoints.\n\n## Authentication\nBinance supports HMAC and RSA API authentication.\n\n```python\n# HMAC Authentication\nclient = Client(api_key, api_secret)\nprint(client.account())\n\n# RSA Authentication\nkey = \"\"\nwith open(\"/Users/john/private_key.pem\", \"r\") as f: # Location of private key file\n    private_key = f.read()\nprivate_key_passphrase = \"\" # Optional: only used for encrypted RSA key\n\nclient = Client(key=key, private_key=private_key, private_key_passphrase=private_key_passphrase)\nprint(client.account())\n```\nPlease see `examples/um_futures/trade/get_account.py` or `examples/cm_futures/trade/get_account.py` for more details.\n\n### Base URL\n\nFor USDT-M Futures, if `base_url` is not provided, it defaults to `fapi.binance.com`.<br/>\nFor COIN-M Delivery, if `base_url` is not provided, it defaults to `dapi.binance.com`.<br/>\nIt's recommended to pass in the `base_url` parameter, even in production as Binance provides alternative URLs\n\n### Optional parameters\n\nPEP8 suggests _lowercase with words separated by underscores_, but for this connector,\nthe methods' optional parameters should follow their exact naming as in the API documentation.\n\n```python\n# Recognised parameter name\nresponse = client.query_order('BTCUSDT', orderListId=1)\n\n# Unrecognised parameter name\nresponse = client.query_order('BTCUSDT', order_list_id=1)\n```\n\n### RecvWindow parameter\n\nAdditional parameter `recvWindow` is available for endpoints requiring signature.<br/>\nIt defaults to `5000` (milliseconds) and can be any value lower than `60000`(milliseconds).\nAnything beyond the limit will result in an error response from Binance server.\n\n```python\nfrom binance.cm_futures import CMFutures\n\ncm_futures_client = CMFutures(key='<api_key>', secret='<api_secret>')\nresponse = cm_futures_client.query_order('BTCUSDT', orderId=11, recvWindow=10000)\n```\n\n### Timeout\n\n`timeout` is available to be assigned with the number of seconds you find most appropriate to wait for a server response.<br/>\nPlease remember the value as it won't be shown in error message _no bytes have been received on the underlying socket for timeout seconds_.<br/>\nBy default, `timeout` is None. Hence, requests do not time out.\n\n```python\nfrom binance.cm_futures import CMFutures\n\nclient= CMFutures(timeout=1)\n```\n\n### Proxy\nproxy is supported\n\n```python\nfrom binance.cm_futures import CMFutures\n\nproxies = { 'https': 'http://1.2.3.4:8080' }\n\nclient= CMFutures(proxies=proxies)\n```\n\n### Response Metadata\n\nThe Binance API server provides weight usages in the headers of each response.\nYou can display them by initializing the client with `show_limit_usage=True`:\n\n```python\nfrom binance.cm_futures import CMFutures\n\nclient = CMFutures(show_limit_usage=True)\nprint(client.time())\n```\nreturns:\n\n```python\n{'limit_usage': {'x-mbx-used-weight-1m': '1'}, 'data': {'serverTime': 1653563092778}}\n```\nYou can also display full response metadata to help in debugging:\n\n```python\nclient = Client(show_header=True)\nprint(client.time())\n```\n\nreturns:\n\n```python\n{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}\n```\n\nIf `ClientError` is received, it'll display full response meta information.\n\n### Display logs\n\nSetting the log level to `DEBUG` will log the request URL, payload and response text.\n\n### Error\n\nThere are 2 types of error returned from the library:\n- `binance.error.ClientError`\n    - This is thrown when server returns `4XX`, it's an issue from client side.\n    - It has 4 properties:\n        - `status_code` - HTTP status code\n        - `error_code` - Server's error code, e.g. `-1102`\n        - `error_message` - Server's error message, e.g. `Unknown order sent.`\n        - `header` - Full response header.\n- `binance.error.ServerError`\n    - This is thrown when server returns `5XX`, it's an issue from server side.\n\n## Websocket\n\n### Connector v4\n\nWebSocket can be established through the following connections:\n- USD-M WebSocket Stream (`https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams`)\n- COIN-M WebSocket Stream (`https://binance-docs.github.io/apidocs/delivery/en/#websocket-market-streams`)\n\n```python\n# WebSocket Stream Client\nimport time\nfrom binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient\n\ndef message_handler(_, message):\n    logging.info(message)\n\nmy_client = UMFuturesWebsocketClient(on_message=message_handler)\n\n# Subscribe to a single symbol stream\nmy_client.agg_trade(symbol=\"bnbusdt\")\ntime.sleep(5)\nlogging.info(\"closing ws connection\")\nmy_client.stop()\n```\n\n#### Request Id\n\nClient 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.\n\n```python\n# id provided by client\nmy_client.agg_trade(symbol=\"bnbusdt\", id=\"my_request_id\")\n\n# library will generate a random uuid string\nmy_client.agg_trade(symbol=\"bnbusdt\")\n```\n#### Proxy\n\nProxy is supported for both WebSocket CM futures and UM futures.\n\nTo use it, pass in the `proxies` parameter when initializing the client.\n\nThe format of the `proxies` parameter is the same as the one used in the Spot RESTful API.\n\nIt consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL:\n\nFor websockets, the proxy type is `http`.\n\n```python\nproxies = { 'http': 'http://1.2.3.4:8080' }\n```\n\nYou can also use authentication for the proxy by adding the `username` and `password` parameters to the proxy URL:\n\n```python\nproxies = { 'http': 'http://username:password@host:port' }\n```\n\n```python\n# WebSocket Stream Client\nimport time\nfrom binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient\n\nproxies = {'http': 'http://1.2.3.4:8080'}\n\ndef message_handler(_, message):\n    logging.info(message)\n\nmy_client = UMFuturesWebsocketClient(on_message=message_handler, proxies=proxies)\n\n# Subscribe to a single symbol stream\nmy_client.agg_trade(symbol=\"bnbusdt\")\ntime.sleep(5)\nlogging.info(\"closing ws connection\")\nmy_client.stop()\n```\n\n\n#### Combined Streams\n- If you set `is_combined` to `True`, `\"/stream/\"` will be appended to the `baseURL` to allow for Combining streams.\n- `is_combined` defaults to `False` and `\"/ws/\"` (raw streams) will be appended to the `baseURL`.\n\nMore websocket examples are available in the `examples` folder\n\n## Websocket < v4\n\n```python\nimport time\nfrom binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient\n\ndef message_handler(message):\n    print(message)\n\nmy_client = UMFuturesWebsocketClient(on_message=message_handler)\n\n# Subscribe to a single symbol stream\nmy_client.agg_trade(symbol=\"bnbusdt\")\ntime.sleep(5)\nprint(\"closing ws connection\")\nmy_client.stop()\n\n```\n\n### Heartbeat\n\nOnce connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within\na 10 minutes period. This package handles the pong responses automatically.\n\n## License\nMIT\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "This is a lightweight library that works as a connector to Binance Futures public API.",
    "version": "4.0.0",
    "project_urls": {
        "Homepage": "https://github.com/binance/binance-futures-connector-python"
    },
    "split_keywords": [
        "binance futures",
        "public api"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "52b1b9b40899370ab508d731d199245d96636d0de684e14210879c7d3924c829",
                "md5": "38fa5eea636d89e5817ef70d05525a30",
                "sha256": "e61fd1eb61180b055d650377f70e1f219f443876ea57efe9fdb2bfa4e2137738"
            },
            "downloads": -1,
            "filename": "binance_futures_connector-4.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "38fa5eea636d89e5817ef70d05525a30",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 36195,
            "upload_time": "2023-08-08T17:53:29",
            "upload_time_iso_8601": "2023-08-08T17:53:29.267767Z",
            "url": "https://files.pythonhosted.org/packages/52/b1/b9b40899370ab508d731d199245d96636d0de684e14210879c7d3924c829/binance_futures_connector-4.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "467df708df1b97761d28071323040ae7ed713af7b43a836e60152edcdf5cced5",
                "md5": "01c974a885b23a67079421f404cdd917",
                "sha256": "8c6bd44d071c563a0329f37d192bcae160c6f614bc25a04c9cc6abc97e43606b"
            },
            "downloads": -1,
            "filename": "binance-futures-connector-4.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "01c974a885b23a67079421f404cdd917",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 31184,
            "upload_time": "2023-08-08T17:53:31",
            "upload_time_iso_8601": "2023-08-08T17:53:31.024901Z",
            "url": "https://files.pythonhosted.org/packages/46/7d/f708df1b97761d28071323040ae7ed713af7b43a836e60152edcdf5cced5/binance-futures-connector-4.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-08 17:53:31",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "binance",
    "github_project": "binance-futures-connector-python",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "binance-futures-connector"
}
        
Elapsed time: 0.10380s