Bitfinex API Python Library

repository·master·Indexed 42 days ago

https://github.com/bitfinexcom/bitfinex-api-py

The official Python implementation of the Bitfinex API (V2) for Python 3.8+. It provides support for over 75 REST endpoints and includes a high-performance WebSocket client for real-time data streams and authenticated operations.

Tokens
2.1K
Snippets
11
Records
11
Agent score
3%

What's inside Bitfinex

  1. Handle WebSocket authentication events

    master

    When using an authenticated WebSocket connection, you must wait for the authenticated event before performing operations that require permissions. The data payload contains user information and capability flags (caps).

    @bfx.wss.on("authenticated")
    def on_authenticated(data: Dict[str, Any]):
        print(f"Successful login for user <{data['userId']}>.")
        
        # Check specific permissions
        if not data["caps"]["orders"]["read"]:
            raise Exception("This application requires read permissions on orders.")
  2. Install bitfinex-api-py and dependencies

    master

    To set up a Python 3.8+ environment for running the bitfinex-api-py source code, clone the repository and install the development dependencies.

    Note: It is recommended to install from dev-requirements.txt rather than requirements.txt to ensure all necessary development tools (like mypy, black, isort, flake8, and pre-commit) are available.

    git clone https://github.com/bitfinexcom/bitfinex-api-py.git
    python3 -m pip install -r dev-requirements.txt
  3. Authenticate REST client with environment variables

    master

    For security, it is recommended to store your api_key and api_secret in a local .env file and access them via environment variables rather than hardcoding them.

    import os
    
    bfx = Client(
        [...],
        api_key=os.getenv("BFX_API_KEY"),
        api_secret=os.getenv("BFX_API_SECRET")
    )
  4. Set up pre-commit hooks

    master

    If you intend to contribute to the project, you should set up the pre-commit hooks. This repository uses isort, black, and flake8 to ensure code quality and consistency. Installing the hooks will automatically run these tools on every git commit.

    To install the hooks:

    python3 -m pre-commit install

    To manually trigger all hooks across all files:

    python3 -m pre-commit run --all-files
  5. Install bitfinex-api-py

    master

    Install the official Bitfinex API (V2) implementation for Python 3.8+ using pip.

    To install the standard package:

    python3 -m pip install bitfinex-api-py

    If you want to use mypy type hints in your project, install the typing extra:

    python3 -m pip install bitfinex-api-py[typing]
  6. Quickstart: Submit an order via REST

    master

    Use the Client to interact with Bitfinex REST endpoints. This example demonstrates authenticating and submitting an exchange limit order.

    from bfxapi import Client, REST_HOST
    from bfxapi.types import Notification, Order
    
    bfx = Client(
        rest_host=REST_HOST,
        api_key="<YOUR BFX API-KEY>",
        api_secret="<YOUR BFX API-SECRET>"
    )
    
    notification: Notification[Order] = bfx.rest.auth.submit_order(
        type="EXCHANGE LIMIT", symbol="tBTCUSD", amount=0.165212, price=30264.0
    )
    
    order: Order = notification.data
    
    if notification.status == "SUCCESS":
        print(f"Successful new order for {order.symbol} at {order.price}$.")
    
    if notification.status == "ERROR":
        raise Exception(f"Something went wrong: {notification.text}")
  7. Subscribe and unsubscribe to public channels

    master

    Use bfx.wss.subscribe to listen to data streams. Each subscription generates a unique sub_id.

    • Subscribe: await bfx.wss.subscribe(channel, symbol=...)
    • Unsubscribe: await bfx.wss.unsubscribe(sub_id=...)
    • Custom sub_id: You can provide your own sub_id to ensure uniqueness or tracking.

    Successful subscriptions emit the subscribed event.

    # Subscribe to a ticker
    await bfx.wss.subscribe("ticker", symbol="tBTCUSD")
    
    # Subscribe with a custom sub_id
    await bfx.wss.subscribe("candles", key="trade:1m:tBTCUSD", sub_id="507f1f77bcf86cd799439011")
    
    # Unsubscribe using the sub_id
    await bfx.wss.unsubscribe(sub_id="f2757df2-7e11-4244-9bb7-a53b7343bef8")
  8. Send and receive custom notifications

    master

    Authenticated users can broadcast custom notifications to all their own open WebSocket connections using bfx.wss.notify. These are received by any client of the same user via the notification event.

    # Sending a notification (requires authentication)
    await bfx.wss.notify({ "foo": 1 })
    
    # Receiving a notification
    @bfx.wss.on("notification")
    def on_notification(notification: Notification[Any]):
        print(notification.data)  # Output: { "foo": 1 }
  9. Instantiate the WebSocket client

    master

    The Client object contains a wss attribute, which is an instance of BfxWebSocketClient. You can specify the wss_host during instantiation.

    Use the following constants to set the host:

    • WSS_HOST: wss://api.bitfinex.com/ws/2 (Supports authentication, suitable for all situations).
    • PUB_WSS_HOST: wss://api-pub.bitfinex.com/ws/2 (Public use only, does not support authentication. Recommended for non-authenticated apps).
    from bfxapi import Client, PUB_WSS_HOST
    
    bfx = Client(wss_host=PUB_WSS_HOST)
  10. Listen to WebSocket events

    master

    The WebSocket client emits events whenever data is received. You can register listeners using the @bfx.wss.on("event_name") decorator or by passing a callback to bfx.wss.on("event_name", callback=...). Listeners can be synchronous or asynchronous (coroutines).

    # Using a decorator
    @bfx.wss.on("candles_update")
    def on_candles_update(sub: subscriptions.Candles, candle: Candle):
        print(f"Candle update for key <{sub['key']}>: {candle}")
    
    # Using a callback function
    def my_callback(data):
        print(data)
    
    bfx.wss.on("candles_update", callback=my_callback)
  11. Run and manage the WebSocket client lifecycle

    master

    To start the WebSocket client, use run() for blocking execution or start() if an event loop is already running.

    • Start (Blocking): bfx.wss.run()
    • Start (Async): await bfx.wss.start()
    • Close: await bfx.wss.close(code=1001, reason="Going Away")

    Common lifecycle events:

    • open: Emitted when the connection is established. Use this for bootstrapping (e.g., subscribing to channels).
    • disconnected: Emitted after the connection closes.
    # Running the client
    bfx.wss.run()
    
    # Subscribing on open
    @bfx.wss.on("open")
    async def on_open():
        await bfx.wss.subscribe("ticker", symbol="tBTCUSD")
    
    # Closing the connection
    await bfx.wss.close(code=1001, reason="Going Away")