Skip to main content

Crypto WS API connector for ASYNC requests

Project description

Crypto WS API connector for ASYNC requests

Full coverage of all methods provided by the interface

Provides of connection management, keepalive and rate limits control


PyPI version DeepSource DeepSource sonarcloud Downloads


For :heavy_check_mark:Binance, :heavy_check_mark:OKX, :heavy_check_mark:Bitfinex


Features

Lightweight and efficient solution to utilize of all available methods** provided through the:

** 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

pip install crypto_ws_api

For upgrade to latest versions use:

pip install -U crypto_ws_api

After first install create environment by run

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

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

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

await account_information(user_session, trade_id)

Stop user session and close aiohttp session

await user_session.stop()
await session.close()

Create limit order example

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

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 :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

BNB, BUSD, USDT (BEP20) 0x5b52c6ba862b11318616ee6cef64388618318b92

USDT (TRC20) TP1Y43dpY7rrRyTSLaSKDZmFirqvRcpopC

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

crypto-ws-api-2.0.5.post2.tar.gz (13.6 kB view details)

Uploaded Source

Built Distribution

crypto_ws_api-2.0.5.post2-py3-none-any.whl (12.6 kB view details)

Uploaded Python 3

File details

Details for the file crypto-ws-api-2.0.5.post2.tar.gz.

File metadata

  • Download URL: crypto-ws-api-2.0.5.post2.tar.gz
  • Upload date:
  • Size: 13.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.28.1

File hashes

Hashes for crypto-ws-api-2.0.5.post2.tar.gz
Algorithm Hash digest
SHA256 c8ebe398466a0c3efa83afe34f5210054494390da19b92d464712ce62cf74c1e
MD5 3c2f4039cb00d920ed7dad5dc71d7678
BLAKE2b-256 ae21cb789bb87b423cdf9968a35cd9ff32510a46196739f7b7120ea438448076

See more details on using hashes here.

File details

Details for the file crypto_ws_api-2.0.5.post2-py3-none-any.whl.

File metadata

File hashes

Hashes for crypto_ws_api-2.0.5.post2-py3-none-any.whl
Algorithm Hash digest
SHA256 29555e26d9c9af8d4b41ca3c7e2de47c1a2fc467fe786f48f4b388183bbc144f
MD5 132b160d073ff1c27cd34da4df03584e
BLAKE2b-256 bf57c0cf4a209402966067a55fd6c472da9ab8fbea88a0f3f6a15aadee4dd324

See more details on using hashes here.

Supported by

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