• Stars
    star
    200
  • Rank 195,295 (Top 4 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created almost 6 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

bitfinex-api-py (v3-beta)

Official implementation of the Bitfinex APIs (V2) for Python 3.8+.

DISCLAIMER:
Production use of v3.0.0b1 (and all future beta versions) is HIGHLY discouraged.
Beta versions should not be used in applications which require user authentication.
Provide your API-KEY/API-SECRET, and manage your account and funds at your own risk.

Features

  • Support for 75+ REST endpoints (a list of available endpoints can be found here)
  • New WebSocket client to ensure fast, secure and persistent connections
  • Full support for Bitfinex notifications (including custom notifications)
  • Native support for type hinting and type checking with mypy

Installation

python3 -m pip install --pre bitfinex-api-py

Selecting and installing a specific beta version

It's also possible to select and install a specific beta version:

python3 -m pip install bitfinex-api-py==3.0.0b1

Quickstart

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}")

Authenticating in your account

To authenticate in your account, you must provide a valid API-KEY and API-SECRET:

bfx = Client(
    [...],
    api_key=os.getenv("BFX_API_KEY"),
    api_secret=os.getenv("BFX_API_SECRET")
)

Warning

Remember to not share your API-KEYs and API-SECRETs with anyone.
Everyone who owns one of your API-KEYs and API-SECRETs will have full access to your account.
We suggest saving your credentials in a local .env file and accessing them as environment variables.

Revoke your API-KEYs and API-SECRETs immediately if you think they might have been stolen.

NOTE: A guide on how to create, edit and revoke API-KEYs and API-SECRETs can be found here.

Next


WebSocket client documentation

  1. Instantiating the client
  2. Running the client
  3. Subscribing to public channels
  4. Listening to events

Advanced features

Examples

Instantiating the client

bfx = Client(wss_host=PUB_WSS_HOST)

Client::wss contains an instance of BfxWebSocketClient (core implementation of the WebSocket client).
The wss_host argument is used to indicate the URL to which the WebSocket client should connect.
The bfxapi package exports 2 constants to quickly set this URL:

Constant URL When to use
WSS_HOST wss://api.bitfinex.com/ws/2 Suitable for all situations, supports authentication.
PUB_WSS_HOST wss://api-pub.bitfinex.com/ws/2 For public uses only, doesn't support authentication.

PUB_WSS_HOST is recommended over WSS_HOST for applications that don't require authentication.

NOTE: The wss_host parameter is optional, and the default value is WSS_HOST.

Authentication

To learn how to authenticate in your account, have a look at Authenticating in your account.

If authentication is successful, the client will emit the authenticated event.
All operations that require authentication will fail if run before the emission of this event.
The data argument contains information about the authentication, such as the userId, the auth_id, etc...

@bfx.wss.on("authenticated")
def on_authenticated(data: Dict[str, Any]):
    print(f"Successful login for user <{data['userId']}>.")

data can also be useful for checking if an API-KEY has certain permissions:

@bfx.wss.on("authenticated")
def on_authenticated(data: Dict[str, Any]):
    if not data["caps"]["orders"]["read"]:
        raise Exception("This application requires read permissions on orders.")

    if not data["caps"]["positions"]["write"]:
        raise Exception("This application requires write permissions on positions.")

Running the client

The client can be run using BfxWebSocketClient::run:

bfx.wss.run()

If an event loop is already running, users can start the client with BfxWebSocketClient::start:

await bfx.wss.start()

If the client succeeds in connecting to the server, it will emit the open event.
This is the right place for all bootstrap activities, such as subscribing to public channels.
To learn more about events and public channels, see Listening to events and Subscribing to public channels.

@bfx.wss.on("open")
async def on_open():
    await bfx.wss.subscribe("ticker", symbol="tBTCUSD")

Closing the connection

Users can close the connection with the WebSocket server using BfxWebSocketClient::close:

await bfx.wss.close()

A custom close code number, along with a verbose reason, can be given as parameters:

await bfx.wss.close(code=1001, reason="Going Away")

After closing the connection, the client will emit the disconnection event:

@bfx.wss.on("disconnection")
def on_disconnection(code: int, reason: str):
    if code == 1000 or code == 1001:
        print("Closing the connection without errors!")

Subscribing to public channels

Users can subscribe to public channels using BfxWebSocketClient::subscribe:

await bfx.wss.subscribe("ticker", symbol="tBTCUSD")

On each successful subscription, the client will emit the subscribed event:

@bfx.wss.on("subscribed")
def on_subscribed(subscription: subscriptions.Subscription):
    if subscription["channel"] == "ticker":
        print(f"{subscription['symbol']}: {subscription['subId']}") # tBTCUSD: f2757df2-7e11-4244-9bb7-a53b7343bef8

Unsubscribing from a public channel

It is possible to unsubscribe from a public channel at any time.
Unsubscribing from a public channel prevents the client from receiving any more data from it.
This can be done using BfxWebSocketClient::unsubscribe, and passing the sub_id of the public channel you want to unsubscribe from:

await bfx.wss.unsubscribe(sub_id="f2757df2-7e11-4244-9bb7-a53b7343bef8")

Setting a custom sub_id

The client generates a random sub_id for each subscription.
These values must be unique, as the client uses them to identify subscriptions.
However, it is possible to force this value by passing a custom sub_id to BfxWebSocketClient::subscribe:

await bfx.wss.subscribe("candles", key="trade:1m:tBTCUSD", sub_id="507f1f77bcf86cd799439011")

Listening to events

Whenever the WebSocket client receives data, it will emit a specific event.
Users can either ignore those events or listen for them by registering callback functions.
These callback functions can also be asynchronous; in fact the client fully supports coroutines (asyncio).

To add a listener for a specific event, users can use the decorator BfxWebSocketClient::on:

@bfx.wss.on("candles_update")
def on_candles_update(sub: subscriptions.Candles, candle: Candle):
    print(f"Candle update for key <{sub['key']}>: {candle}")

The same can be done without using decorators:

bfx.wss.on("candles_update", callback=on_candles_update)

You can pass any number of events to register for the same callback function:

bfx.wss.on("t_ticker_update", "f_ticker_update", callback=on_ticker_update)

Advanced features

Using custom notifications

Using custom notifications requires user authentication.

Users can send custom notifications using BfxWebSocketClient::notify:

await bfx.wss.notify({ "foo": 1 })

Any data can be sent along with a custom notification.

Custom notifications are broadcast by the server on all user's open connections.
So, each custom notification will be sent to every online client of the current user.
Whenever a client receives a custom notification, it will emit the notification event:

@bfx.wss.on("notification")
def on_notification(notification: Notification[Any]):
    print(notification.data) # { "foo": 1 }

Setting up connection multiplexing

BfxWebSocketClient::run and BfxWebSocketClient::start accept a connections argument:

bfx.wss.run(connections=3)

connections indicates the number of connections to run concurrently (through connection multiplexing).

Each of these connections can handle up to 25 subscriptions to public channels.
So, using N connections will allow the client to handle at most N * 25 subscriptions.
You should always use the minimum number of connections necessary to handle all the subscriptions that will be made.

For example, if you know that your application will subscribe to 75 public channels, 75 / 25 = 3 connections will be enough to handle all the subscriptions.

The default number of connections is 5; therefore, if the connections argument is not given, the client will be able to handle a maximum of 25 * 5 = 125 subscriptions.

Keep in mind that using a large number of connections could slow down the client performance.

The use of more than 20 connections is not recommended.

Examples

Creating a new order

import os

from bfxapi import Client, WSS_HOST

from bfxapi.types import Notification, Order

bfx = Client(
    wss_host=WSS_HOST,
    api_key=os.getenv("BFX_API_KEY"),
    api_secret=os.getenv("BFX_API_SECRET")
)

@bfx.wss.on("authenticated")
async def on_authenticated(_):
    await bfx.wss.inputs.submit_order(
        type="EXCHANGE LIMIT", symbol="tBTCUSD", amount=0.165212, price=30264.0)

@bfx.wss.on("order_new")
def on_order_new(order: Order):
    print(f"Successful new order for {order.symbol} at {order.price}$.")

@bfx.wss.on("on-req-notification")
def on_notification(notification: Notification[Order]):
    if notification.status == "ERROR":
        raise Exception(f"Something went wrong: {notification.text}")

bfx.wss.run()

How to contribute

All contributions are welcome! :D

A guide on how to install and set up bitfinex-api-py's source code can be found here.
Before opening any pull requests, please have a look at Before Opening a PR.
Contributors must uphold the Contributor Covenant code of conduct.

Index

  1. Installation and setup
  2. Before opening a PR
  3. License

Installation and setup

A brief guide on how to install and set up the project in your Python 3.8+ environment.

Cloning the repository

The following command will only clone the v3-beta branch (excluding all others):

git clone --branch v3-beta --single-branch https://github.com/bitfinexcom/bitfinex-api-py.git

Installing the dependencies

python3 -m pip install -r dev-requirements.txt

Make sure to install dev-requirements.txt instead of requirements.txt.
dev-requirements.txt will install all dependencies in requirements.txt plus any development dependencies.
This will also install the versions in use of pylint and mypy, which you should both use before opening your PRs.

All done, your Python 3.8+ environment should now be able to run bitfinex-api-py's source code.

Before opening a PR

We won't accept your PR or we will request changes if the following requirements aren't met.

Wheter you're submitting a bug fix, a new feature or a documentation change, you should first discuss it in an issue.

All PRs must follow this PULL_REQUEST_TEMPLATE and include an exhaustive description.

Before opening a pull request, you should also make sure that:

  • all unit tests pass (see Running the unit tests).
  • pylint returns a score of 10.00/10.00 when run against your code.
  • mypy doesn't throw any error code when run on the project (excluding notes).

Running the unit tests

bitfinex-api-py comes with a set of unit tests (written using the unittest unit testing framework).
Contributors must ensure that each unit test passes before opening a pull request.
You can run all project's unit tests by calling unittest on bfxapi.tests:

python3 -m unittest -v bfxapi.tests

A single unit test can be run as follows:

python3 -m unittest -v bfxapi.tests.test_notification

License

Copyright 2023 Bitfinex

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

bitfinex-api-node

BITFINEX NodeJS trading API - Bitcoin, Litecoin, and Ether exchange
JavaScript
459
star
2

bitfinex-api-go

BITFINEX Go trading API - Bitcoin, Litecoin, and Ether exchange
Go
296
star
3

bfx-hf-ui

JavaScript
212
star
4

grenache

DHT based high-performance microservices framework, by Bitfinex
206
star
5

bfx-hf-algo

JavaScript
90
star
6

bitfinex-api-rb

BITFINEX Ruby trading API - Bitcoin, Litecoin, and Ether exchange
Ruby
80
star
7

bitfinex-terminal

JavaScript
69
star
8

bfx-hf-indicators

JavaScript
58
star
9

grenache-grape

Grenache Grape implementation
JavaScript
53
star
10

sunbeam

JavaScript
47
star
11

bfxfixgw

Bitfinex FIX Gateway
Go
45
star
12

dazaar

JavaScript
45
star
13

bfx-hf-algo-server

JavaScript
44
star
14

smidgen

JavaScript
43
star
15

bfx-hf-strategy-py

Python
40
star
16

bfx-hf-indicators-py

Python
31
star
17

bfx-hf-strategy

JavaScript
25
star
18

bfx-report-electron

JavaScript
23
star
19

hypertele

A swiss-knife proxy powered by Hyperswarm DHT
JavaScript
20
star
20

grenache-nodejs-ws

Grenache Node.JS WebSocket implementation
JavaScript
19
star
21

dazaar-vision

JavaScript
18
star
22

eosfinex-custody-contract

C++
18
star
23

antani

Proof of Liabilities and Vote Delegation
JavaScript
16
star
24

bfx-hf-backtest

JavaScript
15
star
25

bfx-pay-woocommerce

PHP
14
star
26

pub

14
star
27

bfx-hf-chart

JavaScript
14
star
28

bfx-hf-data-server

JavaScript
13
star
29

bfx-stuff-ui

Bitfinex UI Goodies
JavaScript
13
star
30

grenache-nodejs-http

Grenache Node.JS WebSocket implementation
JavaScript
13
star
31

bfx-api-node-models

JavaScript
12
star
32

bfx-api-node-rest

JavaScript
12
star
33

bfx-reports-framework

JavaScript
10
star
34

bfx-report-ui

JavaScript
10
star
35

grenache-cli

The Grenache Command Line Interface.
M4
8
star
36

svc-js-cli

JavaScript
8
star
37

bfx-api-excel-demo

Visual Basic 6.0
7
star
38

bfx-report

JavaScript
7
star
39

bfx-hf-server

JavaScript
7
star
40

grenache-nodejs-utp

JavaScript
7
star
41

caron

Atomic Job enqueuer from Redis lists to popular Job Queues (Sidekiq, Resque, Bull, ...)
JavaScript
7
star
42

ufx-ui

JavaScript
7
star
43

hypercore-benchmark

JavaScript
6
star
44

grenache-rust

Rust
6
star
45

grenache-ruby-http

Ruby
6
star
46

mobile-pub

6
star
47

dazaar-payment

JavaScript
6
star
48

bip

6
star
49

hypercore-bisect

JavaScript
6
star
50

bfx-api-node-core

JavaScript
5
star
51

bfx-api-mock-srv

JavaScript
5
star
52

bfx-util-net-js

JavaScript
5
star
53

bfx-hf-models

JavaScript
5
star
54

ulisse

MySQL table snapshots and real time updates to Redis ordered queue
JavaScript
5
star
55

bfx-hf-util

JavaScript
5
star
56

bfx-ost-streamer

The Bitfinex osTicket Streamer Plugin.
PHP
5
star
57

dazaar-payment-lightning

JavaScript
5
star
58

lokue

LokiJS Job Queue
JavaScript
4
star
59

grenache-nodejs-zmq

Grenache Node.JS ZeroMQ implementation, by Bitfinex
JavaScript
4
star
60

bfx-svc-js

Shell
4
star
61

wasteland

JavaScript
4
star
62

bfx-api-node-util

JavaScript
3
star
63

bfx-hf-models-adapter-template

JavaScript
3
star
64

bfx-report-express

JavaScript
3
star
65

pesto-rb

Redis based distributed lock for ruby
Ruby
3
star
66

mutail

Simple and fast file(s) tail. Works with wildcards.
JavaScript
3
star
67

bfx-cli

3
star
68

dazaar-cli

JavaScript
3
star
69

bfx-api-node-plugin-example

JavaScript
3
star
70

cheesebox

JavaScript
3
star
71

grenache-ruby-ws

Ruby
3
star
72

bfx-hf-strategy-exec

JavaScript
3
star
73

grenache-nodejs-base

JavaScript
3
star
74

moonbeam

JavaScript
3
star
75

dazaar-guild

JavaScript
3
star
76

bitfinex-api-php

PHP
3
star
77

bfx-ext-eos-multisig

JavaScript
3
star
78

bfx-hf-ext-plugin-dummy

JavaScript
3
star
79

grenache-nodejs-link

JavaScript
3
star
80

bfx-facs-auth-google

JavaScript
2
star
81

bfx-api-node-plugin-managed-ob

JavaScript
2
star
82

moonbeam-history

JavaScript
2
star
83

bfx-lib-server-js

JavaScript
2
star
84

eos-block-stream

JavaScript
2
star
85

grenache-nodejs-ws-tls

JavaScript
2
star
86

affiliates-nicknames

JavaScript
2
star
87

bitfinex-terminal-order-book

JavaScript
2
star
88

bfx-api-node-plugin-managed-candles

JavaScript
2
star
89

dazaar-www

CSS
2
star
90

hypercore-tutorial

2
star
91

lib-js-util-schema

2
star
92

bfx-api-node-plugin-ob-checksum

JavaScript
2
star
93

bfx-hf-strategy-dazaar

JavaScript
2
star
94

bfx-hf-ui-config

JavaScript
2
star
95

bfx-api-node-plugin-wd

JavaScript
2
star
96

bfx-util-js

Shell
2
star
97

bfx-api-node-plugin-seq-audit

JavaScript
2
star
98

dazaar-scatter-pay

JavaScript
2
star
99

bfx-api-node-mock-data

2
star
100

lib-js-util-math

JavaScript
2
star