crypto-ws-api


Namecrypto-ws-api JSON
Version 2.0.15 PyPI version JSON
download
home_pageNone
SummaryCrypto WS API connector for ASYNC requests
upload_time2024-12-16 16:21:45
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords
VCS
bugtrack_url
requirements shortuuid platformdirs toml websockets ujson
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <h1 align="center"><img align="center" src="https://user-images.githubusercontent.com/77513676/250364389-cbedc171-a930-4467-a0cd-21627a6a41ed.svg" width="75">Crypto WS API connector for ASYNC requests</h1>

<h2 align="center">Full coverage of all methods provided by the interface</h2>

<h3 align="center">Provides of connection management, keepalive and rate limits control</h3>

***
<a href="https://pypi.org/project/crypto-ws-api/"><img src="https://img.shields.io/pypi/v/crypto-ws-api" alt="PyPI version"></a>
<a href="https://codeclimate.com/github/DogsTailFarmer/crypto-ws-api/maintainability"><img src="https://api.codeclimate.com/v1/badges/2d2a654ba393eb88d911/maintainability" /></a>
<a href="https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api/?ref=repository-badge}" target="_blank"><img alt="DeepSource" title="DeepSource" src="https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api.svg/?label=resolved+issues&token=TXghPzbi0YWhkCLU8Q1tmDyQ"/></a>
<a href="https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api/?ref=repository-badge}" target="_blank"><img alt="DeepSource" title="DeepSource" src="https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api.svg/?label=active+issues&token=TXghPzbi0YWhkCLU8Q1tmDyQ"/></a>
<a href="https://sonarcloud.io/summary/new_code?id=DogsTailFarmer_crypto-ws-api" target="_blank"><img alt="sonarcloud" title="sonarcloud" src="https://sonarcloud.io/api/project_badges/measure?project=DogsTailFarmer_crypto-ws-api&metric=alert_status"/></a>
<a href="https://pepy.tech/project/crypto-ws-api" target="_blank"><img alt="Downloads" title="Downloads" src="https://static.pepy.tech/badge/crypto-ws-api"/></a>
***
For :heavy_check_mark:Binance, :heavy_check_mark:OKX, :heavy_check_mark:Bitfinex, :heavy_check_mark:HTX
***

## Features
Lightweight and efficient solution to utilize of all available methods** provided through the:
* [Binance Websocket API v3](https://binance-docs.github.io/apidocs/websocket_api/en)
* [OKX Websocket API v5](https://www.okx.com/docs-v5/en/#overview-websocket)
* [Bitfinex Websocket Inputs](https://docs.bitfinex.com/reference/ws-auth-input)
* [HTX WS Trade](https://www.htx.com/en-us/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1928f079ab6)

** Not for channel by one-way subscription, for **_request <-> response_** mode only

### Session management layer for:
- Credentials
- Connection
- Keepalive
- Error handling
- Limits control
- Methods construction
  + Creating request on-the-fly from method name and params: {}
  + Generating signature if necessary
  + Response handling
- logging

### User interface layer
- Start session instance
- Send async request
- Get response or raised exception
- Reuse instance for different type requests
- Stop session instance

## Get started
### Install use PIP

```console
pip install crypto_ws_api
```
For upgrade to latest versions use:
```console
pip install -U crypto_ws_api
```

After first install create environment by run 
```console
crypto_ws_api_init
```
in terminal window.

The config directory will be created. You get path to config:

>ubuntu@ubuntu:~$ crypto_ws_api_init
> 
>Can't find config file! Creating it...
> 
>Before first run set account(s) API key into /home/ubuntu/.config/crypto_ws_api/ws_api.toml

### Prepare exchange account
* For test purpose log in at [Binance Spot Test Network](https://testnet.binance.vision/)

For OKX and Bitfinex, unlike Binance, a limited number of methods are implemented at the WS API level,
such as creating, modifying, and deleting orders.
There are no public get-time (), ping-pong, etc., so this demo script is limited to calling Binance
to demonstrate capabilities.

* Create API Key
* After install and create environment specify api_key and api_secret to the config file

### Start demo
* Run in terminal window
```
crypto_ws_api_demo
``` 

## Useful tips

_*`crypto_ws_api/demo.py` - complete and fully functional example*_

### Get credentials and create user session

```bazaar
from crypto_ws_api.ws_session import UserWSSession

# Get credentials and create user session
# Can be omitted if you have credentials from other source
exchange, _test_net, api_key, api_secret, passphrase, ws_api_endpoint = get_credentials(account_name)

session = aiohttp.ClientSession()

trade_id = shortuuid.uuid()

user_session = UserWSSession(
    session,
    exchange,
    ws_api_endpoint,
    api_key,
    api_secret,
    passphrase
)
```

### Method example
```bazaar
async def account_information(user_session: UserWSSession, _trade_id):
    # https://developers.binance.com/docs/binance-trading-api/websocket_api#account-information-user_data
    try:
        res = await user_session.handle_request(
            _trade_id,
            "account.status",
            _api_key=True,
            _signed=True
        )
        if res is None:
            logger.warning("Here handling state Out-of-Service")
    except asyncio.CancelledError:
        pass  # Task cancellation should not be logged as an error
    except Exception as _ex:
        logger.error(f"Handling exception: {_ex}")
    else:
        logger.info(f"Account information (USER_DATA) response: {res}")
```

### Demo method's calling
```bazaar
await account_information(user_session, trade_id)
```

### Stop user session and close aiohttp session
```bazaar
await user_session.stop()
await session.close()
```

### Create limit order example
```bazaar
if self.exchange == 'binance':
    params = {
        "symbol": "BTCUSDT",
        "side": "SELL",
        "type": "LIMIT",
        "timeInForce": "GTC",
        "price": "23416.10000000",
        "quantity": "0.00847000",
    }
    binance_res = await user_session.handle_request(trade_id, "order.place", params, _api_key=True, _signed=True)

elif self.exchange == 'bitfinex':
    params = {
        "type": "EXCHANGE LIMIT",
        "symbol": "tBTCUSDT",
        "price": "23416.10000000",
        "amount": ('' if side == 'BUY' else '-') + "0.00847000",
    }
    bitfnex_res = await user_session.handle_request(trade_id, "on", params)

elif self.exchange == 'okx':
    params = {
        "instId": "BTC-USDT",
        "tdMode": "cash",
        "clOrdId": "client_order_id",
        "side": "buy",
        "ordType": "limit",
        "sz": "0.00847000",
        "px": "23416.10000000",
    }
    okx_res = await user_session.handle_request(trade_id, "order", params)
```

### Logging setup
For configure logging in multi-module project use next snippet for yours `main()`:
```bazaar
import logging.handlers

logger = logging.getLogger(__name__)
formatter = logging.Formatter(fmt="[%(asctime)s: %(levelname)s] %(message)s")
#
sh = logging.StreamHandler()
sh.setFormatter(formatter)
sh.setLevel(logging.DEBUG)
#
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
root_logger.addHandler(sh)
```

## [Limits control](https://developers.binance.com/docs/binance-trading-api/websocket_api#general-information-on-rate-limits) :link:
Upon reaching the limit threshold of each type, the session switches to the Out-of-Service state.
If you send a request in this state, the answer will be `None`

*In any case, you are protected from exceeding limits and blocking for this reason*

## Donate
*USDT* (TRC20) TU3kagV9kxbjuUmEi6bUym5MTXjeM7Tm8K

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "crypto-ws-api",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "Jerry Fedorenko <jerry.fedorenko@yahoo.com>",
    "download_url": "https://files.pythonhosted.org/packages/76/17/eb8f0898102e4d8fd0207b49168580ffa8140fbd6e7c011a6c61192cedfb/crypto_ws_api-2.0.15.tar.gz",
    "platform": null,
    "description": "<h1 align=\"center\"><img align=\"center\" src=\"https://user-images.githubusercontent.com/77513676/250364389-cbedc171-a930-4467-a0cd-21627a6a41ed.svg\" width=\"75\">Crypto WS API connector for ASYNC requests</h1>\n\n<h2 align=\"center\">Full coverage of all methods provided by the interface</h2>\n\n<h3 align=\"center\">Provides of connection management, keepalive and rate limits control</h3>\n\n***\n<a href=\"https://pypi.org/project/crypto-ws-api/\"><img src=\"https://img.shields.io/pypi/v/crypto-ws-api\" alt=\"PyPI version\"></a>\n<a href=\"https://codeclimate.com/github/DogsTailFarmer/crypto-ws-api/maintainability\"><img src=\"https://api.codeclimate.com/v1/badges/2d2a654ba393eb88d911/maintainability\" /></a>\n<a href=\"https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api/?ref=repository-badge}\" target=\"_blank\"><img alt=\"DeepSource\" title=\"DeepSource\" src=\"https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api.svg/?label=resolved+issues&token=TXghPzbi0YWhkCLU8Q1tmDyQ\"/></a>\n<a href=\"https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api/?ref=repository-badge}\" target=\"_blank\"><img alt=\"DeepSource\" title=\"DeepSource\" src=\"https://app.deepsource.com/gh/DogsTailFarmer/crypto-ws-api.svg/?label=active+issues&token=TXghPzbi0YWhkCLU8Q1tmDyQ\"/></a>\n<a href=\"https://sonarcloud.io/summary/new_code?id=DogsTailFarmer_crypto-ws-api\" target=\"_blank\"><img alt=\"sonarcloud\" title=\"sonarcloud\" src=\"https://sonarcloud.io/api/project_badges/measure?project=DogsTailFarmer_crypto-ws-api&metric=alert_status\"/></a>\n<a href=\"https://pepy.tech/project/crypto-ws-api\" target=\"_blank\"><img alt=\"Downloads\" title=\"Downloads\" src=\"https://static.pepy.tech/badge/crypto-ws-api\"/></a>\n***\nFor :heavy_check_mark:Binance, :heavy_check_mark:OKX, :heavy_check_mark:Bitfinex, :heavy_check_mark:HTX\n***\n\n## Features\nLightweight and efficient solution to utilize of all available methods** provided through the:\n* [Binance Websocket API v3](https://binance-docs.github.io/apidocs/websocket_api/en)\n* [OKX Websocket API v5](https://www.okx.com/docs-v5/en/#overview-websocket)\n* [Bitfinex Websocket Inputs](https://docs.bitfinex.com/reference/ws-auth-input)\n* [HTX WS Trade](https://www.htx.com/en-us/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1928f079ab6)\n\n** Not for channel by one-way subscription, for **_request <-> response_** mode only\n\n### Session management layer for:\n- Credentials\n- Connection\n- Keepalive\n- Error handling\n- Limits control\n- Methods construction\n  + Creating request on-the-fly from method name and params: {}\n  + Generating signature if necessary\n  + Response handling\n- logging\n\n### User interface layer\n- Start session instance\n- Send async request\n- Get response or raised exception\n- Reuse instance for different type requests\n- Stop session instance\n\n## Get started\n### Install use PIP\n\n```console\npip install crypto_ws_api\n```\nFor upgrade to latest versions use:\n```console\npip install -U crypto_ws_api\n```\n\nAfter first install create environment by run \n```console\ncrypto_ws_api_init\n```\nin terminal window.\n\nThe config directory will be created. You get path to config:\n\n>ubuntu@ubuntu:~$ crypto_ws_api_init\n> \n>Can't find config file! Creating it...\n> \n>Before first run set account(s) API key into /home/ubuntu/.config/crypto_ws_api/ws_api.toml\n\n### Prepare exchange account\n* For test purpose log in at [Binance Spot Test Network](https://testnet.binance.vision/)\n\nFor OKX and Bitfinex, unlike Binance, a limited number of methods are implemented at the WS API level,\nsuch as creating, modifying, and deleting orders.\nThere are no public get-time (), ping-pong, etc., so this demo script is limited to calling Binance\nto demonstrate capabilities.\n\n* Create API Key\n* After install and create environment specify api_key and api_secret to the config file\n\n### Start demo\n* Run in terminal window\n```\ncrypto_ws_api_demo\n``` \n\n## Useful tips\n\n_*`crypto_ws_api/demo.py` - complete and fully functional example*_\n\n### Get credentials and create user session\n\n```bazaar\nfrom crypto_ws_api.ws_session import UserWSSession\n\n# Get credentials and create user session\n# Can be omitted if you have credentials from other source\nexchange, _test_net, api_key, api_secret, passphrase, ws_api_endpoint = get_credentials(account_name)\n\nsession = aiohttp.ClientSession()\n\ntrade_id = shortuuid.uuid()\n\nuser_session = UserWSSession(\n    session,\n    exchange,\n    ws_api_endpoint,\n    api_key,\n    api_secret,\n    passphrase\n)\n```\n\n### Method example\n```bazaar\nasync def account_information(user_session: UserWSSession, _trade_id):\n    # https://developers.binance.com/docs/binance-trading-api/websocket_api#account-information-user_data\n    try:\n        res = await user_session.handle_request(\n            _trade_id,\n            \"account.status\",\n            _api_key=True,\n            _signed=True\n        )\n        if res is None:\n            logger.warning(\"Here handling state Out-of-Service\")\n    except asyncio.CancelledError:\n        pass  # Task cancellation should not be logged as an error\n    except Exception as _ex:\n        logger.error(f\"Handling exception: {_ex}\")\n    else:\n        logger.info(f\"Account information (USER_DATA) response: {res}\")\n```\n\n### Demo method's calling\n```bazaar\nawait account_information(user_session, trade_id)\n```\n\n### Stop user session and close aiohttp session\n```bazaar\nawait user_session.stop()\nawait session.close()\n```\n\n### Create limit order example\n```bazaar\nif self.exchange == 'binance':\n    params = {\n        \"symbol\": \"BTCUSDT\",\n        \"side\": \"SELL\",\n        \"type\": \"LIMIT\",\n        \"timeInForce\": \"GTC\",\n        \"price\": \"23416.10000000\",\n        \"quantity\": \"0.00847000\",\n    }\n    binance_res = await user_session.handle_request(trade_id, \"order.place\", params, _api_key=True, _signed=True)\n\nelif self.exchange == 'bitfinex':\n    params = {\n        \"type\": \"EXCHANGE LIMIT\",\n        \"symbol\": \"tBTCUSDT\",\n        \"price\": \"23416.10000000\",\n        \"amount\": ('' if side == 'BUY' else '-') + \"0.00847000\",\n    }\n    bitfnex_res = await user_session.handle_request(trade_id, \"on\", params)\n\nelif self.exchange == 'okx':\n    params = {\n        \"instId\": \"BTC-USDT\",\n        \"tdMode\": \"cash\",\n        \"clOrdId\": \"client_order_id\",\n        \"side\": \"buy\",\n        \"ordType\": \"limit\",\n        \"sz\": \"0.00847000\",\n        \"px\": \"23416.10000000\",\n    }\n    okx_res = await user_session.handle_request(trade_id, \"order\", params)\n```\n\n### Logging setup\nFor configure logging in multi-module project use next snippet for yours `main()`:\n```bazaar\nimport logging.handlers\n\nlogger = logging.getLogger(__name__)\nformatter = logging.Formatter(fmt=\"[%(asctime)s: %(levelname)s] %(message)s\")\n#\nsh = logging.StreamHandler()\nsh.setFormatter(formatter)\nsh.setLevel(logging.DEBUG)\n#\nroot_logger = logging.getLogger()\nroot_logger.setLevel(logging.DEBUG)\nroot_logger.addHandler(sh)\n```\n\n## [Limits control](https://developers.binance.com/docs/binance-trading-api/websocket_api#general-information-on-rate-limits) :link:\nUpon reaching the limit threshold of each type, the session switches to the Out-of-Service state.\nIf you send a request in this state, the answer will be `None`\n\n*In any case, you are protected from exceeding limits and blocking for this reason*\n\n## Donate\n*USDT* (TRC20) TU3kagV9kxbjuUmEi6bUym5MTXjeM7Tm8K\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Crypto WS API connector for ASYNC requests",
    "version": "2.0.15",
    "project_urls": {
        "Source": "https://github.com/DogsTailFarmer/crypto-ws-api"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "27598830c7198a8b422873efc01399e984a973063647139c922918737afed928",
                "md5": "c78df086c9732d3ee5c9e9fc2f7faef6",
                "sha256": "79f8951a6c15031b5982a2a9bb74300a5dbe39b2ed3a1dba2bc01a3756c382b8"
            },
            "downloads": -1,
            "filename": "crypto_ws_api-2.0.15-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c78df086c9732d3ee5c9e9fc2f7faef6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 13405,
            "upload_time": "2024-12-16T16:21:42",
            "upload_time_iso_8601": "2024-12-16T16:21:42.457505Z",
            "url": "https://files.pythonhosted.org/packages/27/59/8830c7198a8b422873efc01399e984a973063647139c922918737afed928/crypto_ws_api-2.0.15-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7617eb8f0898102e4d8fd0207b49168580ffa8140fbd6e7c011a6c61192cedfb",
                "md5": "2c22a998597d9b1920475406c82e6126",
                "sha256": "fac77f58fceed0c60e369cbe41977e3771eba68d1599153028d50455346b1362"
            },
            "downloads": -1,
            "filename": "crypto_ws_api-2.0.15.tar.gz",
            "has_sig": false,
            "md5_digest": "2c22a998597d9b1920475406c82e6126",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 14864,
            "upload_time": "2024-12-16T16:21:45",
            "upload_time_iso_8601": "2024-12-16T16:21:45.875682Z",
            "url": "https://files.pythonhosted.org/packages/76/17/eb8f0898102e4d8fd0207b49168580ffa8140fbd6e7c011a6c61192cedfb/crypto_ws_api-2.0.15.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-16 16:21:45",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "DogsTailFarmer",
    "github_project": "crypto-ws-api",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "shortuuid",
            "specs": [
                [
                    "~=",
                    "1.0.13"
                ]
            ]
        },
        {
            "name": "platformdirs",
            "specs": [
                [
                    "==",
                    "3.11.0"
                ]
            ]
        },
        {
            "name": "toml",
            "specs": [
                [
                    "~=",
                    "0.10.2"
                ]
            ]
        },
        {
            "name": "websockets",
            "specs": [
                [
                    "==",
                    "14.1"
                ]
            ]
        },
        {
            "name": "ujson",
            "specs": [
                [
                    "~=",
                    "5.10.0"
                ]
            ]
        }
    ],
    "lcname": "crypto-ws-api"
}
        
Elapsed time: 0.40105s