### Quickstart: Subscribe to Candles and Place Order with WssClient Source: https://bitfinex.readthedocs.io/en/latest/websocket.html This example demonstrates the quickstart usage of the WssClient for Bitfinex websockets. It shows how to initialize and authenticate a client, subscribe to candle data for multiple symbols and timeframes, start the client, and place a new order. It emphasizes reusing a single client instance. ```python 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 ) ``` -------------------------------- ### Subscribe to Orderbook Data with WssClient Source: https://bitfinex.readthedocs.io/en/latest/websocket.html This example shows how to subscribe to the orderbook data for a given symbol and precision level using the WssClient. It includes a placeholder for a message handler function and outlines the necessary steps for client setup and subscription. ```python 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. ``` -------------------------------- ### Subscribe to Ticker Data with WssClient Source: https://bitfinex.readthedocs.io/en/latest/websocket.html This example demonstrates how to subscribe to real-time ticker data for a given symbol using the WssClient. It includes setting up a callback function to process the incoming ticker messages and shows the typical pattern of initializing, authenticating, subscribing, and starting the client. ```python 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() ``` -------------------------------- ### Authenticate and Start WebSocket Client Source: https://bitfinex.readthedocs.io/en/latest/websocket.html Initializes and authenticates the WebSocket client using provided API keys. The client must be authenticated before performing any operations. The start() method initiates the connection. ```python from bitfinex import WssClient # Assuming key and secret are defined elsewhere my_client = WssClient(key, secret) my_client.authenticate() my_client.start() ``` -------------------------------- ### Subscribe to Trades Data with WssClient Source: https://bitfinex.readthedocs.io/en/latest/websocket.html This example illustrates how to subscribe to real-time trade data for a specified symbol using the WssClient. It defines a handler function for processing trade messages and follows the standard procedure of client initialization, authentication, subscription, and starting the connection. ```python 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() ``` -------------------------------- ### GET /configs Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Fetch currency and symbol site configuration data. Supports multiple actions like map, list, info, and fees. ```APIDOC ## GET /configs ### Description Fetch currency and symbol site configuration data. Multiple sets of parameters may be passed in a single request. ### Method GET ### Endpoint /configs ### Parameters #### Query Parameters - **action** (str) - Required - Valid values: 'map', 'list', 'info', 'fees' - **obj** (str) - Optional - Object type based on action - **detail** (str) - Optional - Specific detail required for certain action:object combinations ### Request Example { "action": "map", "obj": "currency", "detail": "sym" } ### Response #### Success Response (200) - **data** (list) - List of configuration objects #### Response Example [] ``` -------------------------------- ### GET /key_permissions Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Checks the permissions associated with the current API key. ```APIDOC ## GET /key_permissions ### Description Returns the read/write permissions for the API key used in the request. ### Response #### Success Response (200) - **permissions** (dict) - Mapping of account modules to read/write boolean status. ### Response Example { "account": {"read": true, "write": false}, "withdraw": {"read": false, "write": false} } ``` -------------------------------- ### GET /ledgers Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Views past ledger entries for account balance changes. ```APIDOC ## GET /ledgers ### Description Retrieves account ledger entries, showing balance changes over time. ### Method GET ### Parameters #### Query Parameters - **currency** (str) - Optional - The currency code (e.g., BTC) - **start** (int) - Optional - Millisecond start time - **end** (int) - Optional - Millisecond end time - **limit** (int) - Optional - Number of records ### Response #### Success Response (200) - **ledgers** (list) - List of ledger entries including ID, CURRENCY, AMOUNT, and BALANCE. ### Response Example [ [1001, "BTC", 1573482478000, 0.5, 10.5, "Deposit"] ] ``` -------------------------------- ### Offer Status Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Get the status of a specific offer. ```APIDOC ## GET /offers/{offer_id} ### Description Get the status of a specific offer, including whether it is active, cancelled, or executed. ### Method GET ### Endpoint /offers/{offer_id} ### Parameters #### Path Parameters - **offer_id** (integer) - Required - The offer ID to query. ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the offer. - **currency** (string) - The currency of the offer. - **rate** (string) - The rate of the offer. - **period** (integer) - The period of the offer in days. - **direction** (string) - The direction of the offer ('lend' or 'loan'). - **timestamp** (string) - The timestamp of the offer. - **is_live** (boolean) - Indicates if the offer is currently live. - **is_cancelled** (boolean) - Indicates if the offer has been cancelled. - **original_amount** (string) - The original amount of the offer. - **remaining_amount** (string) - The remaining amount of the offer. - **executed_amount** (string) - The executed amount of the offer. #### Response Example ```json { "id": 13800585, "currency": "USD", "rate": "20.0", "period": 2, "direction": "lend", "timestamp": "1444279698.0", "is_live": false, "is_cancelled": true, "original_amount": "50.0", "remaining_amount": "50.0", "executed_amount": "0.0" } ``` ``` -------------------------------- ### GET /symbols Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Retrieves a list of all available trading symbols. ```APIDOC ## GET /symbols ### Description Returns a list of valid symbol names supported by the exchange. ### Response #### Success Response (200) - **symbols** (list) - A list of strings representing symbol names. ### Response Example [ "btcusd", "ltcusd", "ltcbtc" ] ``` -------------------------------- ### Get Funding Offers Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Retrieves active funding offers for a specified symbol. ```APIDOC ## GET /v2/auth/r/funding/offers ### Description Retrieves active funding offers for a specified symbol. ### Method POST ### Endpoint /v2/auth/r/funding/offers ### Parameters #### Query Parameters - **symbol** (string) - The trading symbol you want information about. #### Request Body None ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **ID** (int) - The unique identifier for the funding offer. - **SYMBOL** (string) - The trading symbol. - **MTS_CREATED** (int) - Millisecond timestamp of offer creation. - **MTS_UPDATED** (int) - Millisecond timestamp of last offer update. - **AMOUNT** (float) - The amount of the funding offer. - **AMOUNT_ORIG** (float) - The original amount of the funding offer. - **TYPE** (string) - The type of funding offer (e.g., "FRR", "LIM"). - **FLAGS** (int) - Flags associated with the offer. - **STATUS** (string) - The status of the funding offer. - **RATE** (float) - The interest rate for the funding. - **PERIOD** (int) - The period for the funding in days. #### Response Example ```json { "example": [ [ 12345, "tBTCUSD", 1678886400000, 1678886400000, 1000.0, 1000.0, "FRR", 0, 0, 0, "ACTIVE", 0, 0, 0, 0.05, 30 ] ] } ``` ``` -------------------------------- ### Place a New Order using WebSocket Client Source: https://bitfinex.readthedocs.io/en/latest/websocket.html Places a new limit order for a specified symbol and amount. This function returns a client-generated ID for the order. Ensure the client is authenticated and started. ```python # Assuming my_client is an authenticated WssClient instance order_client_id = my_client.new_order( order_type="LIMIT", symbol="BTCUSD", amount=0.004, price=1000.0 ) ``` -------------------------------- ### Get Funding Offers (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Fetches active funding offers, optionally filtered by a specific symbol. The returned data includes offer ID, symbol, creation/update times, amount, rate, period, and status. ```python bfx_client.funding_offers() bfx_client.funding_offers("fIOT") ``` -------------------------------- ### Initialize and Use Bitfinex WssClient Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/websockets/client.html Demonstrates the initialization, authentication, and usage of the WssClient to perform specific data calculations. ```python 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"]) ``` -------------------------------- ### Get Status Information Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Retrieves status information for a given status type and keys. Supports filtering by start and end timestamps and other query parameters. ```python bfx_client.status("deriv", "tBTCF0:USTF0", start="1580020000000", end="1580058375000") ``` -------------------------------- ### Get Funding Trades History Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves Bitfinex funding trades history. This function allows fetching records of funding trades with optional parameters for symbol, start time, end time, and limit. ```python bfx_client.funding_trades('fUSD') ``` -------------------------------- ### Initialize Bitfinex API Client Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Demonstrates how to instantiate the Client class using API keys and an optional nonce multiplier for request security. ```python bfx_client = Client(key, secret) bfx_client = Client(key, secret, 2.0) ``` -------------------------------- ### Get Funding Credits History Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves the history of inactive funding credits used in positions, limited to the last 3 days. It accepts optional parameters for start time, end time, and limit. ```python bfx_client.funding_credits_history('fUSD') ``` -------------------------------- ### Initialize Bitfinex Websocket Client Dependencies Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/websockets/client.html This snippet demonstrates the necessary imports and module setup for the Bitfinex WebSocket client. It includes threading, cryptographic utilities for authentication, and the Twisted/Autobahn infrastructure required for asynchronous WebSocket communication. ```python # coding=utf-8 import threading import json import hmac import hashlib from autobahn.twisted.websocket import WebSocketClientFactory, \ WebSocketClientProtocol, \ connectWS from twisted.internet import reactor, ssl from twisted.internet.protocol import ReconnectingClientFactory from twisted.internet.error import ReactorAlreadyRunning from bitfinex import utils from . import abbreviations ``` -------------------------------- ### Get Account Movements (Python) Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Retrieves historical account movements for a specified currency. It accepts optional start and end times, and a limit for the number of records. The response is a list of movement records. ```python def movements(self, currency=None, start=None, end=None, limit=None): """`Bitfinex movements reference `_ Currency (BTC, ...) start : Optional int Millisecond start time end : Optional int Millisecond end time limit : Optional int Number of records, default & max: 25 Returns ------- list :: [ [ ID, CURRENCY, CURRENCY_NAME, null, null, MTS_STARTED, MTS_UPDATED, null, null, STATUS, null, null, AMOUNT, FEES, null, null, DESTINATION_ADDRESS, null, null, null, TRANSACTION_ID, null ], ... ] Example ------- :: bfx_client.movements() bfx_client.movements("BTC") """ body = kwargs raw_body = json.dumps(body) add_currency = "{}/".format(currency.upper()) if currency else "" path = "v2/auth/r/movements/{}hist".format(add_currency) response = self._post(path, raw_body, verify=True) return response ``` -------------------------------- ### Create and Execute Orders with Bitfinex WssClient Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/websockets/client.html Demonstrates how to initialize the WssClient, authenticate, and execute both single orders and multi-order operations. The process involves creating an order operation dictionary and submitting it to the exchange. ```python # 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() # Creating a single order operation order_operation = my_client.new_order_op( order_type="LIMIT", symbol="BTCUSD", amount=0.004, price=1000.0 ) # Submitting multiple orders my_client.multi_order( operations=[order_operation] ) # Creating a new order directly order_client_id = my_client.new_order( order_type="LIMIT", symbol="BTCUSD", amount=0.004, price=1000.0 ) ``` -------------------------------- ### Get Leaderboard Standings Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Fetches leaderboard standings for various metrics like profit and volume. Requires specifying a key, timeframe, and symbol. Supports filtering by start and end timestamps, limit, and sort order. ```python bfx_client.leaderboards(key="plu_diff", timeframe="1w", symbol="tBTCUSD", start="1580020000000", end="1580058375000") ``` -------------------------------- ### Initialize Bitfinex API Client Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Demonstrates how to create an instance of the `Client` class for the Bitfinex API. It requires an API key and secret, with an optional nonce multiplier for advanced usage. The nonce multiplier must be a float. ```python from bitfinex.client import Client key = "YOUR_API_KEY" secret = "YOUR_API_SECRET" # Initialize with key and secret bfx_client = Client(key, secret) # Initialize with key, secret, and nonce multiplier bfx_client_with_multiplier = Client(key, secret, 2.0) ``` -------------------------------- ### Get Positions Audit (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Returns an audit of user positions corresponding to provided IDs. This function allows filtering by position IDs, start and end times, and limiting the results. The output includes detailed position information and metadata. ```python positions = bfx_client.positions_audit([1, 2, 3]) for position in positions: print(position) ``` -------------------------------- ### Get Positions History (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves the historical positions of a user between specified dates. It supports filtering by start and end times, and limiting the number of records returned. Each record includes details like symbol, status, amount, and price. ```python positions = bfx_client.positions_history(limit=10) for position in positions: print(position) ``` -------------------------------- ### Place Offer Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Submit a new offer to lend or borrow on Bitfinex. ```APIDOC ## POST /offers ### Description Submit a new offer to lend or borrow on Bitfinex. ### Method POST ### Endpoint /offers ### Parameters #### Query Parameters - **currency** (string) - Required - The name of the currency. - **amount** (float) - Required - Order size: how much to lend or borrow. - **rate** (float) - Required - Rate to lend or borrow at. In percentage per 365 days. (Set to 0 for FRR). - **period** (integer) - Required - Number of days of the funding contract. - **direction** (string) - Required - Either "lend" or "loan". ### Request Example ```json { "currency": "USD", "amount": 50.0, "rate": 20.0, "period": 2, "direction": "lend" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the offer. - **currency** (string) - The currency of the offer. - **rate** (string) - The rate of the offer. - **period** (integer) - The period of the offer in days. - **direction** (string) - The direction of the offer ('lend' or 'loan'). - **timestamp** (string) - The timestamp of the offer. - **is_live** (boolean) - Indicates if the offer is currently live. - **is_cancelled** (boolean) - Indicates if the offer has been cancelled. - **original_amount** (string) - The original amount of the offer. - **remaining_amount** (string) - The remaining amount of the offer. - **executed_amount** (string) - The executed amount of the offer. - **offer_id** (integer) - The offer ID. #### Response Example ```json { "id": 13800585, "currency": "USD", "rate": "20.0", "period": 2, "direction": "lend", "timestamp": "1444279698.21175971", "is_live": true, "is_cancelled": false, "original_amount": "50.0", "remaining_amount": "50.0", "executed_amount": "0.0", "offer_id": 13800585 } ``` ``` -------------------------------- ### POST /v2/conf/{cfg_params} Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Fetches multiple configurations in a single request by providing a list of configuration dictionaries. This is more efficient than making individual requests for each configuration item. ```APIDOC ## POST /v2/conf/{cfg_params} ### Description Fetches multiple configurations in a single request by providing a list of configuration dictionaries. This is more efficient than making individual requests for each configuration item. ### Method POST ### Endpoint /v2/conf/{cfg_params} ### Parameters #### Request Body - **cfg_list** (list) - Required - Contains a list of dictionaries, where each dictionary specifies a configuration to fetch. Each dictionary must have an 'action' key and can optionally include 'obj' and 'detail' keys. - Example dictionary: `{"action": "fees"}` - Example dictionary: `{"action": "map", "obj": "currency", "detail": "sym"}` ### Request Example ```json { "example": "cfgs = [\n {\"action\": \"fees\"},\n {\"action\": \"map\", \"obj\": \"currency\", \"detail\": \"sym\"}\n]\nbfx_client.configs_list(cfgs)" } ``` ### Response #### Success Response (200) - **list** - A list containing the requested configuration data for all specified items. #### Response Example ```json { "example": "[]" } ``` ``` -------------------------------- ### Get Funding Loans History (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Fetches historical inactive funds not used in positions, limited to the last 3 days. This function supports filtering by symbol, start and end times, and limiting the results. The output details are similar to active funding loans. ```python bfx_client.funding_loans_history() bfx_client.funding_loans_history('fOMG') ``` -------------------------------- ### Get Funding Offers History (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves past inactive funding offers, limited to the last 3 days. This function allows filtering by symbol, start and end times, and limiting the number of records. The output structure is similar to active funding offers. ```python bfx_client.funding_offers_history() bfx_client.funding_offers_history('fOMG') ``` -------------------------------- ### Initialize Bitfinex V2 REST API Client (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Demonstrates how to initialize the Bitfinex V2 REST API client using API keys and secrets. It also shows an optional parameter for nonce multiplier. ```python bfx_client = Client(key,secret) bfx_client = Client(key,secret,2.0) ``` -------------------------------- ### Get Bitfinex Configurations (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Fetches currency and symbol site configuration data from Bitfinex. Supports various actions like 'map', 'list', 'info', and 'fees', with specific object and detail parameters for each action. Requires a Bitfinex client instance. ```python bfx_client.configs("fees") bfx_client.configs("map","currency","sym") ``` -------------------------------- ### Get Positions History - Python Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Retrieves historical positions for a user within a specified date range from the Bitfinex API. This function accepts optional 'start', 'end', and 'limit' parameters. It returns a list of position records, including creation and update timestamps. ```python def positions_history(self, **kwargs): ""`Bitfinex positions history reference `_ Return the positions of a user between two dates Parameters ---------- start : Optional int Millisecond start time end : Optional int Millisecond end time limit : Optional int Number of records Returns ------- list :: [ [ SYMBOL, STATUS, AMOUNT, BASE_PRICE, MARGIN_FUNDING, MARGIN_FUNDING_TYPE, PL, PL_PERC, PRICE_LIQ, LEVERAGE, ID, MTS_CREATE, MTS_UPDATE ], ... ] Examples -------- :: positions = bfx_client.positions_history(limit=10) for position in positions: print(position) """ body = kwargs raw_body = json.dumps(body) path = "v2/auth/r/positions/hist" response = self._post(path, raw_body, verify=True) return response ``` -------------------------------- ### Get Candle Data (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves candle data from the Bitfinex API. Supports 'hist' for historical candles and 'last' for the most recent candle. Requires specifying the time frame, symbol, and section. Optional parameters include limit, start, and end timestamps, and sort order. ```python bfx_client.candles("1m", "tBTCUSD", "hist") bfx_client.candles("1h", "tBTCUSD", "hist", limit='1') bfx_client.candles("1h", "tBTCUSD", "last") ``` -------------------------------- ### GET /v2/conf/{action}:{obj}:{detail} Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Fetches various types of configuration data by constructing a path with Action, Object, and optionally a Detail value. This endpoint allows fetching specific configuration details for currencies, transactions, or pairs. ```APIDOC ## GET /v2/conf/{action}:{obj}:{detail} ### Description Fetches various types of configuration data by constructing a path with Action, Object, and optionally a Detail value. This endpoint allows fetching specific configuration details for currencies, transactions, or pairs. ### Method GET ### Endpoint /v2/conf/{action}:{obj}:{detail} ### Parameters #### Path Parameters - **action** (str) - Required - Valid action values: 'map', 'list', 'info', 'fees' - **obj** (str) - Optional - Valid object values depend on the action: - For 'map' action: 'currency', 'tx' - For 'list' action: 'currency', 'pair', 'competitions' - For 'info' action: 'pair' - For 'fees' action: none - **detail** (str) - Optional - Required for specific action-object combinations: - For map:currency: 'sym', 'label', 'unit', 'undl', 'pool', 'explorer' - For map:tx: 'method' - For list:pair: 'exchange', 'margin' ### Request Example ```json { "example": "bfx_client.configs(\"fees\")" } ``` ```json { "example": "bfx_client.configs(\"map\",\"currency\",\"sym\")" } ``` ### Response #### Success Response (200) - **list** - A list containing the requested configuration data. The structure of the list varies based on the requested configuration. #### Response Example ```json { "example": "[]" } ``` ``` -------------------------------- ### Handle HTTP GET Requests Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv1.html Performs an HTTP GET request to a specified URL with a timeout. It parses the JSON response if successful or raises a BitfinexException with details if an error occurs. ```python def _get(self, url): response = requests.get(url, timeout=TIMEOUT) if response.status_code == 200: return response.json() else: try: content = response.json() except JSONDecodeError: content = response.text raise BitfinexException(response.status_code, response.reason, content) ``` -------------------------------- ### POST /v2/auth/r/settings Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Reads specific user settings based on the provided key. ```APIDOC ## POST v2/auth/r/settings ### Description Retrieves user settings associated with a specific key. ### Method POST ### Endpoint v2/auth/r/settings ### Parameters #### Request Body - **keys** (array) - Required - List of keys to retrieve, formatted as ['api:key_name'] ### Request Example { "keys": ["api:pkey"] } ### Response #### Success Response (200) - **data** (array) - A list of key-value pairs. #### Response Example [ [ "api:pkey", "value" ] ] ``` -------------------------------- ### GET /order_trades Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves all trades generated by a specific order. ```APIDOC ## GET /order_trades ### Description Fetches individual trade executions associated with a specific order ID. ### Method GET ### Parameters #### Query Parameters - **symbol** (str) - Required - The trading symbol - **orderid** (int) - Required - The ID of the order ### Response #### Success Response (200) - **trades** (list) - List of trade objects including ID, EXEC_AMOUNT, and EXEC_PRICE. ### Response Example [ [12345, "tIOTUSD", 1573482478000, 14395751815, 0.001, 15.5] ] ``` -------------------------------- ### Authenticate WssClient for Account Messages Source: https://bitfinex.readthedocs.io/en/latest/websocket.html This example shows how to authenticate a WssClient to receive account-specific messages and send authenticated messages. It highlights the importance of creating and authenticating the client once and reusing it. The provided callback function handles incoming messages from authenticated channels. ```python 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() ``` -------------------------------- ### POST /order/new Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Submit a new order to the Bitfinex exchange. ```APIDOC ## POST /order/new ### Description Submit a new order to the Bitfinex exchange. This endpoint supports both margin and exchange-specific order types. ### Method POST ### Endpoint /order/new ### Parameters #### Request Body - **amount** (float) - Required - Order size: how much you want to buy or sell - **price** (float) - Required - Price to buy or sell at - **side** (string) - Required - Either "buy" or "sell" - **ord_type** (string) - Required - Order type (e.g., "market", "limit", "exchange limit") - **symbol** (string) - Optional - The trading symbol (default: "btcusd") - **exchange** (string) - Optional - The exchange name (default: "bitfinex") ### Request Example { "amount": 0.01, "price": 0.01, "side": "buy", "ord_type": "exchange limit", "symbol": "btcusd" } ### Response #### Success Response (200) - **id** (int) - The unique order ID - **symbol** (string) - The trading symbol - **price** (string) - The price of the order - **side** (string) - The side of the order #### Response Example { "id": 448364249, "symbol": "btcusd", "exchange": "bitfinex", "price": "0.01", "side": "buy", "type": "exchange limit" } ``` -------------------------------- ### GET /liquidations Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieve recent liquidation data for positions. ```APIDOC ## GET /liquidations ### Description Retrieve liquidation records. By default, returns the most recent liquidations. ### Method GET ### Endpoint /liquidations ### Parameters #### Query Parameters - **start** (int) - Optional - Millisecond start time - **end** (int) - Optional - Millisecond end time - **limit** (int) - Optional - Max 10000 ### Response #### Success Response (200) - **data** (list) - List of liquidation position arrays #### Response Example [ ["pos", 12345, 1580020000000, null, "tBTCUSD", -0.5, 9000.0, null, 1, 1, null, 9005.0] ] ``` -------------------------------- ### Bitfinex Configs API Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Fetches currency and symbol site configuration data. ```APIDOC ## Bitfinex Configs API ### Description Fetches currency and symbol site configuration data. ### Method GET ### Endpoint /v2/conf ### Parameters #### Path Parameters None #### Query Parameters - **action** (str) - Required - Specifies the action to perform (e.g., 'get_currency', 'get_symbol'). - **obj** (str) - Optional - Specifies the object for the action (e.g., a currency name or symbol). - **detail** (str) - Optional - Specifies the detail level for the action. ### Request Example ```json { "example": "bfx_client.configs('get_currency')" } ``` ### Response #### Success Response (200) - **list** - A list containing configuration data. #### Response Example ```json { "example": "[ [ CURRENCY, PRECISION_SET, START, MIN_ORDER, MAX_ORDER, AMOUNT, MIN_ORDER_VALUE, MAX_ORDER_VALUE, MARGIN, FEES ] ]" } ``` ``` -------------------------------- ### GET /movements Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Retrieves the history of deposits and withdrawals. ```APIDOC ## GET /movements ### Description Retrieve a list of deposit and withdrawal movements. ### Parameters #### Query Parameters - **limit** (int) - Optional - Limit the number of entries to return. - **method** (str) - Optional - The method of the deposit/withdrawal (e.g., "bitcoin", "litecoin", "iota", "wire"). ### Response #### Success Response (200) - **movements** (list) - A list of movement objects containing id, txid, currency, method, type, amount, description, address, status, timestamps, and fee. ### Response Example [{ "id": 581183, "txid": 123456, "currency": "BTC", "method": "BITCOIN", "type": "WITHDRAWAL", "amount": ".01", "status": "COMPLETED" }] ``` -------------------------------- ### Configure Bitfinex Logging Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/utils.html Initializes a standardized logger for Bitfinex modules. It sets the logging level to INFO and attaches a console handler with a specific format if no handlers are already present. ```python def get_bitfinex_logger(name): logger = logging.getLogger(name) logger.setLevel(logging.INFO) if not logger.handlers: console = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(levelname) -10s %(name) -10s %(funcName) -10s %(lineno) -5d %(message)s') console.setFormatter(formatter) logger.addHandler(console) return logger ``` -------------------------------- ### Batch Fetch Bitfinex Configurations Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Fetches multiple configuration items in a single request to optimize performance. It accepts a list of dictionaries containing action, object, and detail keys, joins them into a single path, and returns the combined response. ```python cfg_params = [] for cfg in cfg_list: request = f"pub:{cfg['action']}" if 'obj' in cfg: request = f"{request}:{cfg['obj']}" if 'detail' in cfg: request = f"{request}:{cfg['detail']}" cfg_params.append(request) path = f"v2/conf/{','.join(cfg_params)}" response = self._get(path) return response ``` -------------------------------- ### Execute Orders and Operations Source: https://bitfinex.readthedocs.io/en/latest/websocket.html Shows how to create single orders using new_order or prepare multiple order operations for batch processing via multi_order. These methods support various order types like LIMIT and MARKET. ```python my_client = WssClient(key, secret) my_client.authenticate() my_client.start() # Create a single order operation order_operation = my_client.new_order_op( order_type="LIMIT", symbol="BTCUSD", amount=0.004, price=1000.0 ) # Submit multiple orders my_client.multi_order( operations=[order_operation] ) ``` -------------------------------- ### Fetch Bitfinex Configuration Data Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Retrieves configuration data by constructing a path with action, object, and detail parameters. It supports single configuration requests and returns a list of data based on the specified parameters. ```python path = f"v2/conf/pub:{action}" if obj: path = f'{path}:{obj}' if detail: path = f'{path}:{detail}' response = self._get(path) return response ``` -------------------------------- ### GET /order_book Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Retrieves the full order book for a specific symbol. ```APIDOC ## GET /order_book ### Description Returns the full order book containing bids and asks for the specified symbol. ### Parameters #### Query Parameters - **symbol** (str) - Required - The symbol to retrieve the order book for. ### Response #### Success Response (200) - **bids** (list) - List of bid objects. - **asks** (list) - List of ask objects. ### Response Example { "bids": [{"price": "574.61", "amount": "0.1439327"}], "asks": [{"price": "574.62", "amount": "19.1334"}] } ``` -------------------------------- ### Subscribe to Market Data Channels Source: https://bitfinex.readthedocs.io/en/latest/websocket.html Demonstrates how to subscribe to orderbook and candle data streams using the WssClient. Requires a valid API key and secret for authentication, and a callback function to process incoming data. ```python my_client = WssClient(key, secret) # Subscribe to orderbook my_client.subscribe_to_orderbook( symbol="BTCUSD", precision="P1", callback=my_handler ) # Subscribe to candles def my_candle_handler(message): print(message) my_client.subscribe_to_candles( symbol="BTCUSD", timeframe="1m", callback=my_candle_handler ) my_client.start() ``` -------------------------------- ### Place Multiple Orders Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Demonstrates how to construct a list of order payloads and submit them to the Bitfinex client using the place_multiple_orders method. ```python orders = [] for price in range(3, 6): payload = { "symbol": 'IOTUSD', "amount": '100', "price": str(price), "exchange": 'bitfinex', "side": 'buy', "type": 'limit' } orders.append(payload) response = bfx_client.place_multiple_orders(orders) ``` -------------------------------- ### GET /ticker Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Retrieves high-level market state for a specific symbol. ```APIDOC ## GET /ticker ### Description Provides a high-level overview of the market state including bid, ask, last price, volume, and daily movement. ### Parameters #### Query Parameters - **symbol** (str) - Required - The symbol to retrieve information for. ### Response #### Success Response (200) - **ticker** (dict) - Contains mid, bid, ask, last_price, low, high, volume, and timestamp. ### Response Example { "mid": "244.755", "bid": "244.75", "ask": "244.76", "last_price": "244.82", "volume": "7842.11542563" } ``` -------------------------------- ### GET /trades_history Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves a historical list of trades for a specific symbol or the entire account. ```APIDOC ## GET /trades_history ### Description Returns a list of past trades. Can be filtered by symbol, time range, or sorted. ### Method GET ### Parameters #### Query Parameters - **trade_pair** (str) - Optional - The symbol to filter by - **start** (int) - Optional - Millisecond start time - **end** (int) - Optional - Millisecond end time - **limit** (int) - Optional - Number of records - **sort** (int) - Optional - 1 for ascending order ### Response #### Success Response (200) - **trades** (list) - List of trade records. ### Response Example [ [554433, "tIOTUSD", 1573482478000, 14395751815, 0.001, 15.5] ] ``` -------------------------------- ### Fetch Multiple Configurations in One Request (Python) Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves multiple Bitfinex configuration items in a single API request, improving efficiency. The `cfg_list` parameter accepts a list of dictionaries, each specifying the 'action', 'obj', and 'detail' for a configuration item. Requires a configured Bitfinex client instance. ```python bfx_client = Client("key", "secret") cfgs = [ { "action": "fees" }, { "action": "map", "obj": "currency", "detail": "sym" } ] bfx_client.configs_list(cfgs) ``` -------------------------------- ### Retrieve Funding Book Source: https://bitfinex.readthedocs.io/en/latest/restv1.html Fetches the full margin funding book for a specific currency, showing current bids and asks for lending. ```python bfx_client.lendbook("USD") ``` -------------------------------- ### GET /orders_history Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieves the history of closed or canceled orders for a specific symbol or by ID. ```APIDOC ## GET /orders_history ### Description Returns the most recent closed or canceled orders up to approximately two weeks ago. ### Method GET ### Parameters #### Query Parameters - **symbol** (str) - Optional - The trading symbol (e.g., tBTCUSD) - **start** (int) - Optional - Millisecond start time - **end** (int) - Optional - Millisecond end time - **limit** (int) - Optional - Number of records - **id** (list) - Optional - List of specific order IDs ### Response #### Success Response (200) - **orders** (list) - List of order objects containing ID, SYMBOL, AMOUNT, PRICE, and STATUS. ### Response Example [ [33961681942, "1227", 1337, "tBTCUSD", 1573482478000, "CANCELED", 15] ] ``` -------------------------------- ### GET /v1/symbols Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv1.html Retrieves a list of all available trading symbols on Bitfinex. ```APIDOC ## GET /v1/symbols ### Description Retrieves a list of all available trading symbols on Bitfinex. ### Method GET ### Endpoint /v1/symbols ### Parameters No parameters are required for this endpoint. ### Request Example ```json (No request body or parameters needed) ``` ### Response #### Success Response (200) - A list of strings, where each string is a trading symbol (e.g., "btcusd"). #### Response Example ```json [ "btcusd", "ltcusd", "ltcbtc" ] ``` ``` -------------------------------- ### POST /v2/auth/r/info/margin/:key Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Retrieves account margin information. ```APIDOC ## POST /v2/auth/r/info/margin/:key ### Description Get account margin information for the base account or a specific symbol. ### Method POST ### Endpoint v2/auth/r/info/margin/{key} ### Parameters #### Path Parameters - **key** (string) - Required - Use "base" for account summary or a specific SYMBOL for pair-specific margin info. ### Response #### Success Response (200) - **margin_info** (array) - Returns margin base data or symbol-specific tradable balance data. ``` -------------------------------- ### GET /status/{status_type} Source: https://bitfinex.readthedocs.io/en/latest/restv2.html Retrieve platform information, specifically for derivatives pair status. ```APIDOC ## GET /status/{status_type} ### Description Receive different types of platform information, currently supporting derivatives pair status. ### Method GET ### Endpoint /status/{status_type} ### Parameters #### Path Parameters - **status_type** (string) - Required - The status message type (e.g., 'deriv') #### Query Parameters - **keys** (string) - Required - Comma-separated keys or 'ALL' - **start** (string) - Optional - Millisecond start time - **end** (string) - Optional - Millisecond end time - **limit** (int) - Optional - Max 10000 ### Response #### Success Response (200) - **data** (list) - Array containing status details including price, insurance fund, and open interest. #### Response Example [ ["tBTCF0:USTF0", 1568123933000, null, 10000.5, 9999.0, null, 500000, null, 1568127533000, 0.01, 1, null, 0.0001, null, null, 10000.2, null, null, 500] ] ``` -------------------------------- ### POST /v2/auth/calc/order/avail Source: https://bitfinex.readthedocs.io/en/latest/_modules/bitfinex/rest/restv2.html Calculates the available balance for a specific order configuration. ```APIDOC ## POST v2/auth/calc/order/avail ### Description Calculates the available balance for a given symbol, direction, rate, and order type. ### Method POST ### Endpoint v2/auth/calc/order/avail ### Parameters #### Request Body - **symbol** (string) - Required - The trading symbol (e.g., 'tIOTUSD') - **dir** (integer) - Required - Direction of the order - **rate** (float) - Required - The price rate - **type** (string) - Required - The order type (e.g., 'EXCHANGE') ### Request Example { "symbol": "tIOTUSD", "dir": 1, "rate": 0.02, "type": "EXCHANGE" } ### Response #### Success Response (200) - **[AMOUNT_AVAIL]** (float) - The calculated available amount. #### Response Example [100.50] ```