V2 Websockets

The code bellow is documented with complete examples of how to use the methods.

You should use a shared client object that is maintaned in your application while it is running.

Quickstart example

def my_candle_handler(message):
    # Here you can do stuff with the candle bar messages
    print(message)

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate(print)

my_client.subscribe_to_candles(
    symbol="BTCUSD",
    timeframe="1m",
    callback=my_candle_handler
)
my_client.subscribe_to_candles(
    symbol="ETHUSD",
    timeframe="5m",
    callback=my_candle_handler
)
my_client.start()

# Wait a bit for the connection to go live
import time
time.sleep(5)

# Then create a new order
order_client_id = my_client.new_order(
    order_type="LIMIT",
    symbol="BTCUSD",
    amount=0.004,
    price=1000.0
)

WssClient - With Examples

class WssClient(key=None, secret=None, nonce_multiplier=1.0)[source]

Websocket client for bitfinex.

Parameters:
  • key (str) – Your API key.
  • secret (str) – Your API secret

Hint

Do not store your key or secret directly in the code. Use environment variables. and fetch them with os.environ.get("BITFINEX_KEY")

stop()[source]

Tries to close all connections and finally stops the reactor. Properly stops the program.

authenticate(callback, filters=None)[source]

Method used to create an authenticated channel that both recieves account spesific messages and is used to send account spesific messages. So in order to be able to use the new_order method, you have to create a authenticated channel before starting the connection.

Parameters:
  • callback (func) – A function to use to handle incomming messages. This channel wil be handling all messages returned from operations like new_order or cancel_order, so make sure you handle all these messages.
  • filters (List[str]) – A list of filter strings. See more information here: https://docs.bitfinex.com/v2/docs/ws-auth#section-channel-filters

Example

def handle_account_messages(message):
    print(message)

 # You should only need to create and authenticate a client once.
 # Then simply reuse it later
 my_client = WssClient(key, secret)
 my_client.authenticate(
    callback=handle_account_messages
 )
 my_client.start()
subscribe_to_ticker(symbol, callback)[source]

Subscribe to the passed symbol ticks data channel.

Parameters:
  • symbol (str) – Symbol to request data for.
  • callback (func) – A function to use to handle incomming messages

Example

def my_handler(message):
    # Here you can do stuff with the messages
    print(message)

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate(print)
my_client.subscribe_to_ticker(
    symbol="BTCUSD",
    callback=my_handler
)
my_client.start()
subscribe_to_trades(symbol, callback)[source]

Subscribe to the passed symbol trades data channel.

Parameters:
  • symbol (str) – Symbol to request data for.
  • callback (func) – A function to use to handle incomming messages

Example

def my_handler(message):
    # Here you can do stuff with the messages
    print(message)

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate(print)
my_client.subscribe_to_trades(
    symbol="BTCUSD",
    callback=my_handler
)
my_client.start()
subscribe_to_orderbook(symbol, precision, callback)[source]

Subscribe to the orderbook of a given symbol.

Parameters:
  • symbol (str) – Symbol to request data for.
  • precision (str) – Accepted values as strings {R0, P0, P1, P2, P3}
  • callback (func) – A function to use to handle incomming messages

Example

def my_handler(message):
    # Here you can do stuff with the messages
    print(message)

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)

my_client.subscribe_to_orderbook(
    symbol="BTCUSD",
    precision="P1",
    callback=my_handler
)
my_client.start()
subscribe_to_candles(symbol, timeframe, callback)[source]

Subscribe to the passed symbol’s OHLC data channel.

Parameters:
  • symbol (str) – Symbol to request data for
  • timeframe (str) – Accepted values as strings {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M}
  • callback (func) – A function to use to handle incomming messages
Returns:

The socket identifier.

Return type:

str

Example

def my_candle_handler(message):
    # Here you can do stuff with the candle bar messages
    print(message)

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)

my_client.subscribe_to_candles(
    symbol="BTCUSD",
    timeframe="1m",
    callback=my_candle_handler
)
my_client.subscribe_to_candles(
    symbol="ETHUSD",
    timeframe="5m",
    callback=my_candle_handler
)
my_client.start()
ping(channel='auth')[source]

Ping bitfinex.

Parameters:channel (str) – What channel id that should be pinged. Default “auth”. To get channel id’s use ´client._conns.keys()´.
new_order_op(order_type, symbol, amount, price, price_trailing=None, price_aux_limit=None, price_oco_stop=None, hidden=0, flags=None, tif=None, set_cid=True)[source]

Create new order operation

Parameters:
  • order_type (str) – Order type. Must be one of: “LIMIT”, “STOP”, “MARKET”, “TRAILING STOP”, “FOK”, “STOP LIMIT” or equivelent with “EXCHANGE” prepended to it. All orders starting with EXCHANGE are made on the exchange wallet. Orders without it is made on the margin wallet and will start or change a position.
  • symbol (str) – The currency symbol to be traded. e.g. BTCUSD
  • amount (decimal str) – The amount to be traided.
  • price (decimal str) – The price to buy at. Will be ignored for market orders.
  • price_trailing (decimal string) – The trailing price
  • price_aux_limit (decimal string) – Auxiliary Limit price (for STOP LIMIT)
  • price_oco_stop (decimal string) – OCO stop price
  • hidden (bool) – Whether or not to use the hidden order type.
  • flags (list) – A list of integers for the different flags. Will be added together into a unique integer.
  • tif (datetime string) –
  • set_cid (bool) – wheter or not to set a cid.
Returns:

A dict containing the order detials. Used in new_order and for creating multiorders.

Return type:

dict

Example

Note if you only want to create a new order, use the ´´new_order´´ method bellow. However if you want to submitt multiple order and cancel orders at the same time use this method to create order operations and send them with the multi_order method:

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate()
my_client.start()

order_operation = my_client.new_order_op(
    order_type="LIMIT",
    symbol="BTCUSD",
    amount=0.004,
    price=1000.0
)

# Usefull to keep track of an order by its client id, for later
# operations (like cancel order).
clinet_id = order_operation["cid"]

my_client.multi_order(
    operations=[order_operation]
)
new_order(order_type, symbol, amount, price, price_trailing=None, price_aux_limit=None, price_oco_stop=None, hidden=0, flags=None, tif=None, set_cid=True)[source]

Create new order.

Parameters:
  • order_type (str) – Order type. Must be one of: “LIMIT”, “STOP”, “MARKET”, “TRAILING STOP”, “FOK”, “STOP LIMIT” or equivelent with “EXCHANGE” prepended to it. All orders starting with EXCHANGE are made on the exchange wallet. Orders without it is made on the margin wallet and will start or change a position.
  • symbol (str) – The currency symbol to be traded. e.g. BTCUSD
  • amount (decimal string) – The amount to be traided.
  • price (decimal string) – The price to buy at. Will be ignored for market orders.
  • price_trailing (decimal string) – The trailing price
  • price_aux_limit (decimal string) – Auxiliary Limit price (for STOP LIMIT)
  • price_oco_stop (decimal string) – OCO stop price
  • hidden (bool) – Whether or not to use the hidden order type.
  • flags (list) – A list of integers for the different flags. Will be added together into a unique integer.
  • tif (datetime string) –
  • set_cid (bool) – wheter or not to set a cid.
Returns:

Order client id (cid). The CID is also a mts date stamp of when the order was created.

Return type:

int

Example

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate()
my_client.start()

order_client_id = my_client.new_order(
    order_type="LIMIT",
    symbol="BTCUSD",
    amount=0.004,
    price=1000.0
)
multi_order(operations)[source]

Multi order operation.

Parameters:operations (list) – a list of operations. Read more here: https://bitfinex.readme.io/v2/reference#ws-input-order-multi-op Hint. you can use the self.new_order_op() for easy new order operation creation.
Returns:A list of all the client ids created for each order. Returned in the order they are given to the method.
Return type:list

Example

# You should only need to create and authenticate a client once.
# Then simply reuse it later
from bitfinex import utils
my_client = WssClient(key, secret)
my_client.authenticate()
my_client.start()

example_order_cid_to_cancel = 153925861909296

# docs: http://bit.ly/2BVqwW6
cancel_order_operation = {
    'cid': example_order_cid_to_cancel,
    'cid_date': utils.cid_to_date(example_order_cid_to_cancel)
}

new_order_operation = my_client.new_order_op(
    order_type="LIMIT",
    symbol="BTCUSD",
    amount="0.004",
    price="1000.0"
)

order_client_id = my_client.multi_order([
    cancel_order_operation,
    new_order_operation
])
cancel_order(order_id)[source]

Cancel order

Parameters:order_id (int, str) – Order id created by Bitfinex

Example

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate()
my_client.start()

my_client.cancel_order(
    order_id=1234
)
cancel_order_cid(order_cid, order_date)[source]

Cancel order using the client id and the date of the cid. Both are returned from the new_order command from this library.

Parameters:
  • order_cid (str) – cid string. e.g. “1234154”
  • order_date (str) – Iso formated order date. e.g. “2012-01-23”

Example

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate()
my_client.start()

# order_cid created by this library is always a milliseconds
# time stamp. So you can just divide it by 1000 to get the timestamp.
my_client.cancel_order(
    order_cid=1538911910035,
    order_date=(
        datetime.utcfromtimestamp(
            1538911910035/1000.0
        ).strftime("%Y-%m-%d")
    )
)
update_order(**order_settings)[source]

Update order using the order id

Parameters:
  • id (int64) – Order ID
  • gid (int32) – Group Order ID
  • price (decimal string) – Price
  • amount (decimal string) – Amount
  • delta (decimal string) – Change of amount
  • price_aux_limit (decimal string) – Auxiliary limit price
  • price_trailing (decimal string) – Trailing price delta
  • tif (datetime string) – Time-In-Force: datetime for automatic order cancellation (ie. 2020-01-01 10:45:23)
calc(*calculations)[source]

This message will be used by clients to trigger specific calculations, so we don’t end up in calculating data that is not usually needed.

You can request calculations to the websocket server that sends you the same message, with the required fields.

List items must be one of the following:

  • margin_sym_SYMBOL (e.g. margin_sym_tBTCUSD)
  • funding_sym_SYMBOL
  • position_SYMBOL
  • wallet_WALLET-TYPE_CURRENCY
Parameters:*calculations (list) – list of calculations wanted
Returns:Data is returned over the auth channel. See the abbreviation glossary: https://docs.bitfinex.com/v2/docs/abbreviations-glossary
Return type:None

Examples

# You should only need to create and authenticate a client once.
# Then simply reuse it later
my_client = WssClient(key, secret)
my_client.authenticate(print)
my_client.start()

my_client.calc(["margin_sym_tBTCUSD", "funding_sym_fUSD"])
my_client.calc(["margin_sym_tBTCUSD"])
my_client.calc(["position_tBTCUSD"])
my_client.calc(["wallet_exachange_USD"])

Note

Calculations are on demand, so no more streaming of unnecessary data. Websocket server allows up to 30 calculations per batch. If the client sends too many concurrent requests (or tries to spam) requests, it will receive an error and potentially a disconnection. The Websocket server performs a maximum of 8 calculations per second per client.