{"id":22608962,"url":"https://github.com/bitfinexcom/bitfinex-api-py","last_synced_at":"2025-05-15T07:07:18.224Z","repository":{"id":39707150,"uuid":"157535962","full_name":"bitfinexcom/bitfinex-api-py","owner":"bitfinexcom","description":null,"archived":false,"fork":false,"pushed_at":"2024-11-14T08:58:41.000Z","size":903,"stargazers_count":204,"open_issues_count":1,"forks_count":125,"subscribers_count":23,"default_branch":"master","last_synced_at":"2025-04-14T22:16:12.292Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bitfinexcom.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-11-14T11:03:37.000Z","updated_at":"2025-03-31T16:06:44.000Z","dependencies_parsed_at":"2023-12-14T19:54:17.823Z","dependency_job_id":"ffda9356-a8c7-49ef-8ce8-4b94ad362f3f","html_url":"https://github.com/bitfinexcom/bitfinex-api-py","commit_stats":{"total_commits":312,"total_committers":21,"mean_commits":"14.857142857142858","dds":0.6057692307692308,"last_synced_commit":"0079580180bac6179c8e447f34518f26603ce730"},"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bitfinexcom%2Fbitfinex-api-py","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bitfinexcom%2Fbitfinex-api-py/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bitfinexcom%2Fbitfinex-api-py/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bitfinexcom%2Fbitfinex-api-py/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bitfinexcom","download_url":"https://codeload.github.com/bitfinexcom/bitfinex-api-py/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254292042,"owners_count":22046426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-08T15:10:23.246Z","updated_at":"2025-05-15T07:07:13.188Z","avatar_url":"https://github.com/bitfinexcom.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# bitfinex-api-py\n\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/bitfinex-api-py)](https://pypi.org/project/bitfinex-api-py/)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n![GitHub Action](https://github.com/bitfinexcom/bitfinex-api-py/actions/workflows/build.yml/badge.svg)\n\nOfficial implementation of the [Bitfinex APIs (V2)](https://docs.bitfinex.com/docs) for `Python 3.8+`.\n\n### Features\n\n* Support for 75+ REST endpoints (a list of available endpoints can be found [here](https://docs.bitfinex.com/reference))\n* New WebSocket client to ensure fast, secure and persistent connections\n* Full support for Bitfinex notifications (including custom notifications)\n* Native support for type hinting and type checking with [`mypy`](https://github.com/python/mypy)\n\n## Installation\n\n```console\npython3 -m pip install bitfinex-api-py\n```\n\nIf you intend to use mypy type hints in your project, use:\n```console\npython3 -m pip install bitfinex-api-py[typing]\n```\n\n---\n\n# Quickstart\n\n```python\nfrom bfxapi import Client, REST_HOST\n\nfrom bfxapi.types import Notification, Order\n\nbfx = Client(\n    rest_host=REST_HOST,\n    api_key=\"\u003cYOUR BFX API-KEY\u003e\",\n    api_secret=\"\u003cYOUR BFX API-SECRET\u003e\"\n)\n\nnotification: Notification[Order] = bfx.rest.auth.submit_order(\n    type=\"EXCHANGE LIMIT\", symbol=\"tBTCUSD\", amount=0.165212, price=30264.0)\n\norder: Order = notification.data\n\nif notification.status == \"SUCCESS\":\n    print(f\"Successful new order for {order.symbol} at {order.price}$.\")\n\nif notification.status == \"ERROR\":\n    raise Exception(f\"Something went wrong: {notification.text}\")\n```\n\n## Authenticating in your account\n\nTo authenticate in your account, you must provide a valid API-KEY and API-SECRET:\n```python\nbfx = Client(\n    [...],\n    api_key=os.getenv(\"BFX_API_KEY\"),\n    api_secret=os.getenv(\"BFX_API_SECRET\")\n)\n```\n\n### Warning\n\nRemember to not share your API-KEYs and API-SECRETs with anyone. \\\nEveryone who owns one of your API-KEYs and API-SECRETs will have full access to your account. \\\nWe suggest saving your credentials in a local `.env` file and accessing them as environment variables.\n\n_Revoke your API-KEYs and API-SECRETs immediately if you think they might have been stolen._\n\n\u003e **NOTE:** A guide on how to create, edit and revoke API-KEYs and API-SECRETs can be found [here](https://support.bitfinex.com/hc/en-us/articles/115003363429-How-to-create-and-revoke-a-Bitfinex-API-Key).\n\n## Next\n\n* [WebSocket client documentation](#websocket-client-documentation)\n    - [Advanced features](#advanced-features)\n    - [Examples](#examples)\n* [How to contribute](#how-to-contribute)\n\n---\n\n# WebSocket client documentation\n\n1. [Instantiating the client](#instantiating-the-client)\n    * [Authentication](#authentication)\n2. [Running the client](#running-the-client)\n    * [Closing the connection](#closing-the-connection)\n3. [Subscribing to public channels](#subscribing-to-public-channels)\n    * [Unsubscribing from a public channel](#unsubscribing-from-a-public-channel)\n    * [Setting a custom `sub_id`](#setting-a-custom-sub_id)\n4. [Listening to events](#listening-to-events)\n\n### Advanced features\n* [Using custom notifications](#using-custom-notifications)\n\n### Examples\n* [Creating a new order](#creating-a-new-order)\n\n## Instantiating the client\n\n```python\nbfx = Client(wss_host=PUB_WSS_HOST)\n```\n\n`Client::wss` contains an instance of `BfxWebSocketClient` (core implementation of the WebSocket client). \\\nThe `wss_host` argument is used to indicate the URL to which the WebSocket client should connect. \\\nThe `bfxapi` package exports 2 constants to quickly set this URL:\n\nConstant | URL | When to use\n:--- | :--- | :---\nWSS_HOST | wss://api.bitfinex.com/ws/2 | Suitable for all situations, supports authentication.\nPUB_WSS_HOST | wss://api-pub.bitfinex.com/ws/2 | For public uses only, doesn't support authentication.\n\nPUB_WSS_HOST is recommended over WSS_HOST for applications that don't require authentication.\n\n\u003e **NOTE:** The `wss_host` parameter is optional, and the default value is WSS_HOST.\n\n### Authentication\n\nTo learn how to authenticate in your account, have a look at [Authenticating in your account](#authenticating-in-your-account).\n\nIf authentication is successful, the client will emit the `authenticated` event. \\\nAll operations that require authentication will fail if run before the emission of this event. \\\nThe `data` argument contains information about the authentication, such as the `userId`, the `auth_id`, etc...\n\n```python\n@bfx.wss.on(\"authenticated\")\ndef on_authenticated(data: Dict[str, Any]):\n    print(f\"Successful login for user \u003c{data['userId']}\u003e.\")\n```\n\n`data` can also be useful for checking if an API-KEY has certain permissions:\n\n```python\n@bfx.wss.on(\"authenticated\")\ndef on_authenticated(data: Dict[str, Any]):\n    if not data[\"caps\"][\"orders\"][\"read\"]:\n        raise Exception(\"This application requires read permissions on orders.\")\n\n    if not data[\"caps\"][\"positions\"][\"write\"]:\n        raise Exception(\"This application requires write permissions on positions.\")\n```\n\n## Running the client\n\nThe client can be run using `BfxWebSocketClient::run`:\n```python\nbfx.wss.run()\n```\n\nIf an event loop is already running, users can start the client with `BfxWebSocketClient::start`:\n```python\nawait bfx.wss.start()\n```\n\nIf the client succeeds in connecting to the server, it will emit the `open` event. \\\nThis is the right place for all bootstrap activities, such as subscribing to public channels. \\\nTo learn more about events and public channels, see [Listening to events](#listening-to-events) and [Subscribing to public channels](#subscribing-to-public-channels).\n\n```python\n@bfx.wss.on(\"open\")\nasync def on_open():\n    await bfx.wss.subscribe(\"ticker\", symbol=\"tBTCUSD\")\n```\n\n### Closing the connection\n\nUsers can close the connection with the WebSocket server using `BfxWebSocketClient::close`:\n```python\nawait bfx.wss.close()\n```\n\nA custom [close code number](https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number), along with a verbose reason, can be given as parameters:\n```python\nawait bfx.wss.close(code=1001, reason=\"Going Away\")\n```\n\nAfter closing the connection, the client will emit the `disconnected` event:\n```python\n@bfx.wss.on(\"disconnected\")\ndef on_disconnected(code: int, reason: str):\n    if code == 1000 or code == 1001:\n        print(\"Closing the connection without errors!\")\n```\n\n## Subscribing to public channels\n\nUsers can subscribe to public channels using `BfxWebSocketClient::subscribe`:\n```python\nawait bfx.wss.subscribe(\"ticker\", symbol=\"tBTCUSD\")\n```\n\nOn each successful subscription, the client will emit the `subscribed` event:\n```python\n@bfx.wss.on(\"subscribed\")\ndef on_subscribed(subscription: subscriptions.Subscription):\n    if subscription[\"channel\"] == \"ticker\":\n        print(f\"{subscription['symbol']}: {subscription['sub_id']}\") # tBTCUSD: f2757df2-7e11-4244-9bb7-a53b7343bef8\n```\n\n### Unsubscribing from a public channel\n\nIt is possible to unsubscribe from a public channel at any time. \\\nUnsubscribing from a public channel prevents the client from receiving any more data from it. \\\nThis can be done using `BfxWebSocketClient::unsubscribe`, and passing the `sub_id` of the public channel you want to unsubscribe from:\n\n```python\nawait bfx.wss.unsubscribe(sub_id=\"f2757df2-7e11-4244-9bb7-a53b7343bef8\")\n```\n\n### Setting a custom `sub_id`\n\nThe client generates a random `sub_id` for each subscription. \\\nThese values must be unique, as the client uses them to identify subscriptions. \\\nHowever, it is possible to force this value by passing a custom `sub_id` to `BfxWebSocketClient::subscribe`:\n\n```python\nawait bfx.wss.subscribe(\"candles\", key=\"trade:1m:tBTCUSD\", sub_id=\"507f1f77bcf86cd799439011\")\n```\n\n## Listening to events\n\nWhenever the WebSocket client receives data, it will emit a specific event. \\\nUsers can either ignore those events or listen for them by registering callback functions. \\\nThese callback functions can also be asynchronous; in fact the client fully supports coroutines ([`asyncio`](https://docs.python.org/3/library/asyncio.html)).\n\nTo add a listener for a specific event, users can use the decorator `BfxWebSocketClient::on`:\n```python\n@bfx.wss.on(\"candles_update\")\ndef on_candles_update(sub: subscriptions.Candles, candle: Candle):\n    print(f\"Candle update for key \u003c{sub['key']}\u003e: {candle}\")\n```\n\nThe same can be done without using decorators:\n```python\nbfx.wss.on(\"candles_update\", callback=on_candles_update)\n```\n\n# Advanced features\n\n## Using custom notifications\n\n**Using custom notifications requires user authentication.**\n\nUsers can send custom notifications using `BfxWebSocketClient::notify`:\n```python\nawait bfx.wss.notify({ \"foo\": 1 })\n```\n\nAny data can be sent along with a custom notification.\n\nCustom notifications are broadcast by the server on all user's open connections. \\\nSo, each custom notification will be sent to every online client of the current user. \\\nWhenever a client receives a custom notification, it will emit the `notification` event:\n```python\n@bfx.wss.on(\"notification\")\ndef on_notification(notification: Notification[Any]):\n    print(notification.data) # { \"foo\": 1 }\n```\n\n# Examples\n\n## Creating a new order\n\n```python\nimport os\n\nfrom bfxapi import Client, WSS_HOST\n\nfrom bfxapi.types import Notification, Order\n\nbfx = Client(\n    wss_host=WSS_HOST,\n    api_key=os.getenv(\"BFX_API_KEY\"),\n    api_secret=os.getenv(\"BFX_API_SECRET\")\n)\n\n@bfx.wss.on(\"authenticated\")\nasync def on_authenticated(_):\n    await bfx.wss.inputs.submit_order(\n        type=\"EXCHANGE LIMIT\", symbol=\"tBTCUSD\", amount=0.165212, price=30264.0)\n\n@bfx.wss.on(\"order_new\")\ndef on_order_new(order: Order):\n    print(f\"Successful new order for {order.symbol} at {order.price}$.\")\n\n@bfx.wss.on(\"on-req-notification\")\ndef on_notification(notification: Notification[Order]):\n    if notification.status == \"ERROR\":\n        raise Exception(f\"Something went wrong: {notification.text}\")\n\nbfx.wss.run()\n```\n\n---\n\n# How to contribute\n\nAll contributions are welcome! :D\n\nA guide on how to install and set up `bitfinex-api-py`'s source code can be found [here](#installation-and-setup). \\\nBefore opening any pull requests, please have a look at [Before Opening a PR](#before-opening-a-pr). \\\nContributors must uphold the [Contributor Covenant code of conduct](https://github.com/bitfinexcom/bitfinex-api-py/blob/master/CODE_OF_CONDUCT.md).\n\n### Index\n\n1. [Installation and setup](#installation-and-setup)\n    * [Cloning the repository](#cloning-the-repository)\n    * [Installing the dependencies](#installing-the-dependencies)\n    * [Set up the pre-commit hooks (optional)](#set-up-the-pre-commit-hooks-optional)\n2. [Before opening a PR](#before-opening-a-pr)\n    * [Tip](#tip)\n3. [License](#license)\n\n## Installation and setup\n\nA brief guide on how to install and set up the project in your Python 3.8+ environment.\n\n### Cloning the repository\n\n```console\ngit clone https://github.com/bitfinexcom/bitfinex-api-py.git\n```\n\n### Installing the dependencies\n\n```console\npython3 -m pip install -r dev-requirements.txt\n```\n\nMake sure to install `dev-requirements.txt` (and not `requirements.txt`!). \\\n`dev-requirements.txt` will install all dependencies in `requirements.txt` plus any development dependency. \\\ndev-requirements includes [mypy](https://github.com/python/mypy), [black](https://github.com/psf/black), [isort](https://github.com/PyCQA/isort), [flake8](https://github.com/PyCQA/flake8), and [pre-commit](https://github.com/pre-commit/pre-commit) (more on these tools in later chapters).\n\nAll done, your Python 3.8+ environment should now be able to run `bitfinex-api-py`'s source code.\n\n### Set up the pre-commit hooks (optional)\n\n**Do not skip this paragraph if you intend to contribute to the project.**\n\nThis repository includes a pre-commit configuration file that defines the following hooks:\n1. [isort](https://github.com/PyCQA/isort)\n2. [black](https://github.com/psf/black)\n3. [flake8](https://github.com/PyCQA/flake8)\n\nTo set up pre-commit use:\n```console\npython3 -m pre-commit install\n```\n\nThese will ensure that isort, black and flake8 are run on each git commit.\n\n[Visit this page to learn more about git hooks and pre-commit.](https://pre-commit.com/#introduction)\n\n#### Manually triggering the pre-commit hooks\n\nYou can also manually trigger the execution of all hooks with:\n```console\npython3 -m pre-commit run --all-files\n```\n\n## Before opening a PR\n\n**We won't accept your PR or we'll request changes if the following requirements aren't met.**\n\nWheter you're submitting a bug fix, a new feature or a documentation change, you should first discuss it in an issue.\n\nYou must be able to check off all tasks listed in [PULL_REQUEST_TEMPLATE](https://raw.githubusercontent.com/bitfinexcom/bitfinex-api-py/master/.github/PULL_REQUEST_TEMPLATE.md) before opening a pull request.\n\n### Tip\n\nSetting up the project's pre-commit hooks will help automate this process ([more](#set-up-the-pre-commit-hooks-optional)).\n\n## License\n\n```\nCopyright 2023 Bitfinex\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbitfinexcom%2Fbitfinex-api-py","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbitfinexcom%2Fbitfinex-api-py","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbitfinexcom%2Fbitfinex-api-py/lists"}