Bitfinex (v2)

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.

V2 REST

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

Client for the bitfinex.com API REST V2. Link for official bitfinex documentation :

Bitfinex rest2 docs

Bitfinex rest2 reference

Parameters:
  • key (str) – Bitfinex api key
  • secret (str) – Bitfinex api secret
  • nonce_multiplier (Optional float) – Multiply nonce by this number

Examples

bfx_client = Client(key,secret)

bfx_client = Client(key,secret,2.0)
platform_status()[source]

Bitfinex platform_status reference

Get the current status of the platform. Maintenance periods last for just few minutes and might be necessary from time to time during upgrades of core components of our infrastructure. Even if rare it is important to have a way to notify users. For a real-time notification we suggest to use websockets and listen to events 20060/20061

Returns:
  • 1 = operative
  • 0 = maintenance
Return type:int

Example

bfx_client.platform_status()
tickers(symbol_list)[source]

Bitfinex tickers reference

The ticker is a high level overview of the state of the market. It shows you the current best bid and ask, as well as the last trade price.It also includes information such as daily volume and how much the price has moved over the last day.

Parameters:symbol_list (list) – The symbols you want information about as a comma separated list, or ALL for every symbol.
Returns:
[
  # on trading pairs (ex. tBTCUSD)
  [
    SYMBOL,
    BID,
    BID_SIZE,
    ASK,
    ASK_SIZE,
    DAILY_CHANGE,
    DAILY_CHANGE_PERC,
    LAST_PRICE,
    VOLUME,
    HIGH,
    LOW
  ],
  # on funding currencies (ex. fUSD)
  [
    SYMBOL,
    FRR,
    BID,
    BID_SIZE,
    BID_PERIOD,
    ASK,
    ASK_SIZE,
    ASK_PERIOD,
    DAILY_CHANGE,
    DAILY_CHANGE_PERC,
    LAST_PRICE,
    VOLUME,
    HIGH,
    LOW
  ],
  ...
]
Return type:list

Note

Field Type Description
FRR float Flash Return Rate - average of all fixed rate funding over the last hour
BID float Price of last highest bid
BID_PERIOD int Bid period covered in days
BID_SIZE float Sum of the 25 highest bid sizes
ASK float Price of last lowest ask
ASK_PERIOD int Ask period covered in days
ASK_SIZE float Sum of the 25 lowest ask sizes
DAILY_CHANGE float Amount that the last price has changed since yesterday
DAILY_CHANGE_PERC float Amount that the price has changed expressed in percentage terms
LAST_PRICE float Price of the last trade
VOLUME float Daily volume
HIGH float Daily high
LOW float Daily low

Examples

bfx_client.tickers(['tIOTUSD', 'fIOT'])
bfx_client.tickers(['tBTCUSD'])
bfx_client.tickers(['ALL'])
ticker(symbol)[source]

Bitfinex ticker reference

The ticker is a high level overview of the state of the market.It shows you the current best bid and ask, as well as the last trade price.It also includes information such as daily volume and how much the price has moved over the last day.

Parameters:symbol (str) – The symbol you want information about. You can find the list of valid symbols by calling the symbols method
Returns:
# on trading pairs (ex. tBTCUSD)
[
  BID,
  BID_SIZE,
  ASK,
  ASK_SIZE,
  DAILY_CHANGE,
  DAILY_CHANGE_PERC,
  LAST_PRICE,
  VOLUME,
  HIGH,
  LOW
]
# on funding currencies (ex. fUSD)
[
  FRR,
  BID,
  BID_SIZE,
  BID_PERIOD,
  ASK,
  ASK_SIZE,
  ASK_PERIOD,
  DAILY_CHANGE,
  DAILY_CHANGE_PERC,
  LAST_PRICE,
  VOLUME,
  HIGH,
  LOW
]
Return type:list

Examples

bfx_client.ticker('tIOTUSD')
bfx_client.ticker('fIOT')
bfx_client.ticker('tBTCUSD')
trades(symbol, **kwargs)[source]

Bitfinex trades reference

The trades endpoint allows the retrieval of past public trades and includes details such as price, size, and time. Optional parameters can be used to limit the number of results; you can specify a start and end timestamp, a limit, and a sorting method.

Parameters:
  • symbol (str) –

    The symbol you want information about. You can find the list of valid symbols by calling the symbols method

  • start (string) – Millisecond start time for /hist ( ex : 1568123933000)
  • end (string) – Millisecond end time for /hist (ex : 1570578740000)
  • sort – set to 1 for oldest > newest records , -1 for reverse
  • limit – Limit of retrieved records. (Max: 10000)
Returns:

// on trading pairs (ex. tBTCUSD)
[
  [
    ID,
    MTS,
    AMOUNT,
    PRICE
  ]
]

// on funding currencies (ex. fUSD)
[
  [
    ID,
    MTS,
    AMOUNT,
    RATE,
    PERIOD
  ]
]

//trading
[[388063448,1567526214876,1.918524,10682]]

//funding
[[124486873,1567526287066,-210.69675707,0.00034369,2]]

Return type:

list

Examples

bfx_client.trades('tIOTUSD')
bfx_client.trades('fIOT')
bfx_client.trades('tBTCUSD', limit=1, sort=-1)
book(symbol, precision='P0', **kwargs)[source]

Bitfinex book reference

The Order Book channel allow you to keep track of the state of the Bitfinex order book. It is provided on a price aggregated basis, with customizable precision.

Parameters:
  • symbol (str) – The symbol you want information about.
  • precision (Optional str) – Level of price aggregation (P0, P1, P2, P3, R0). R0 means “gets the raw orderbook”.
  • len (Optional str) – Number of price points (“1”, “25”, “100”)
Returns:

// on trading pairs (ex. tBTCUSD)
[
  [
    PRICE,
    COUNT,
    AMOUNT
  ],
  ...
]

// on funding currencies (ex. fUSD)
[
  [
    RATE,
    PERIOD,
    COUNT,
    AMOUNT
  ],
  ...
]

// on raw books (precision of R0)
// on trading currencies:
[
  [
    ORDER_ID,
    PRICE,
    AMOUNT
  ],
  ...
]

// on funding currencies:

[
  [
    ORDER_ID,
    PERIOD,
    RATE,
    AMOUNT
  ],
  ...
]

//trading
[[8744.9,2,0.45603413],[8745,8,-3.64426815]]

//funding
[[0.0003301,30,1,-3862.874],[0.00027999,2,2,1843.05088178]]

//raw books

//trading
[[34006738527,8744.9,0.25603413],[34005496171,8745,-0.2]]

//funding
[[645902785,30,0.0003301,-3862.874],[649139359,2,0.0003168747915,52.36]]

Return type:

list

Examples

bfx_client.book('tIOTUSD')
bfx_client.book('fIOT')
bfx_client.book('tBTCUSD')
stats(key, size, symbol, side='', section='last', **kwargs)[source]

Bitfinex stats reference

Various statistics about the requested pair.

Parameters:
  • Key (str) – Allowed values: “funding.size”, “credits.size”, “credits.size.sym”, “pos.size”
  • Size (str) – Available values: ‘1m’
  • Symbol (str) – The symbol you want information about.
  • Side (str) – Available values: “long”, “short”
  • Section (str) – Available values: “last”, “hist”
  • start (Options str) – Millisecond start time for /hist ( ex : 1568123933000)
  • end (Options str) – Millisecond end time for /hist (ex : 1570578740000)
  • sort (Options str) – set to 1 for oldest > newest records , -1 for reverse
  • limit (Options str) – Limit of retrieved records. (Max: 10000)
Returns:

// response with Section = "last"
[
  MTS,
  VALUE
]

// response with Section = "hist"
[
  [
   MTS,
   VALUE
  ],
  ...
]

//pos size
[[1573554000000,25957.94278561],[1573553940000,25964.29056204]]

//funding size
[[1573560420000,374049888.4504578],[1573560360000,373962908.58560276]]

//credits size
[[1573560420000,369005353.5945115],[1573560360000,368918780.2238935]]

//credits size sym
[[1573560480000,141144084.0479222],[1573560420000,141144084.0479222]]

Return type:

list

Examples

bfx_client.stats('funding.size', '1m', 'fUSD', section="hist", limit=1)
bfx_client.stats('pos.size', '1m', 'tBTCUSD', side="long", section="hist", limit=1)
bfx_client.stats('credits.size', '1m', 'fUSD', section="hist", limit=1)
bfx_client.stats('credits.size.sym', '1m', 'fUSD:tBTCUSD', section="hist", limit=1)
candles(timeframe, symbol, section, period='', **kwargs)[source]

Bitfinex candles reference

Provides a way to access charting candle info

Parameters:
  • timeframe (str) – Available values: ‘1m’, ‘5m’, ‘15m’, ‘30m’, ‘1h’, ‘3h’, ‘6h’, ‘12h’, ‘1D’, ‘7D’, ‘14D’, ‘1M’
  • symbol (str) – The symbol you want information about. (eg : tBTCUSD, tETHUSD, fUSD, fBTC)
  • section (str) – Available values: “last”, “hist”
  • period (str) – Funding period. Only required for funding candles. Enter after the symbol (trade:1m:fUSD:p30/hist).
  • limit (int) – Number of candles requested (Max: 10000)
  • start (str) – Filter start (ms)
  • end (str) – Filter end (ms)
  • sort (int) – if = 1 it sorts results returned with old > new
Returns:

# response with Section = "last"
[ MTS, OPEN, CLOSE, HIGH, LOW, VOLUME ]

# response with Section = "hist"
[
  [ MTS, OPEN, CLOSE, HIGH, LOW, VOLUME ],
  ...
]

Return type:

list

Examples

# 1 minute candles
bfx_client.candles("1m", "tBTCUSD", "hist")

# 1 hour candles , limit to 1 candle
bfx_client.candles("1h", "tBTCUSD", "hist", limit='1')
bfx_client.candles("1h", "tBTCUSD", "last")

# funding candles

bfx_client.candles("1m", "fUSD", "hist", period="p30", limit=1)
configs(action: str, obj=None, detail=None)[source]

Bitfinex configs reference

Fetch currency and symbol site configuration data.

A variety of types of config data can be fetched by constructing a path with an Action, Object, and conditionally a Detail value.

Multiple sets of parameters may be passed, in a single request, to fetch multiple parts of the sites currency and symbol configuration data.

Parameters:
  • action (str) – Valid action values: : ‘map’, ‘list’, ‘info’, ‘fees’
  • Object (str) –

    Valid object values for the map action: ‘currency’, ‘tx’.

    Valid object values for the list action: ‘currency’, ‘pair’, ‘competitions’.

    Valid object values for the info action: ‘pair’

    Valid object values for the fees action: none

  • Detail (str) –

    The detail parameter is only required for the below action:object values:

    A map:currency request requires one of the following detail values: ‘sym’, ‘label’, ‘unit’, ‘undl’, ‘pool’, ‘explorer’.

    A map:tx request requires the following detail value: ‘method’.

    A list:pair request requires one of the following detail values: ‘exchange’, ‘margin’

Returns:

[]

Return type:

list

Examples

bfx_client.configs("fees")
bfx_client.configs("map","currency","sym")
configs_list(cfg_list: list)[source]

Bitfinex configs reference

Instead of performing a request for each configuration item it is possible to fetch multiple configurations in a single request.

Parameters:cfg_list (list) – Contains a list of dictionaries that have the following keys : action, obj, detail
Returns:
[]
Return type:list

Examples

bfx_client = Client("key", "secret")
cfgs = [
    {
        "action": "fees"
    },
    {
        "action": "map",
        "obj": "currency",
        "detail": "sym"
    }
]

bfx_client.configs_list(cfgs)
status(status_type, keys, **kwargs)[source]

Bitfinex status reference

Endpoint used to receive different types of platform information - currently supports derivatives pair status only.

Parameters:
  • status_type (string) – Path parameter. The status message type. Valid values: deriv
  • keys (string) – The key or keys (Separate by commas) of the pairs to fetch status information. To fetch information for all pairs use the key value ‘ALL’, (ex: tBTCF0:USTF0 or tETHF0:USTF0)
  • start (string) – Millisecond start time for /hist ( ex : 1568123933000)
  • end (string) – Millisecond end time for /hist (ex : 1570578740000)
  • sort – set to 1 for oldest > newest records , -1 for reverse
  • limit – Limit of retrieved records. (Max: 10000)
Returns:

[
  [
    KEY,
    MTS,
    PLACEHOLDER,
    DERIV_PRICE,
    SPOT_PRICE,
    PLACEHOLDER,
    INSURANCE_FUND_BALANCE,
    PLACEHOLDER,
    NEXT_FUNDING_EVT_TIMESTAMP_MS,
    NEXT_FUNDING_ACCRUED,
    NEXT_FUNDING_STEP,
    PLACEHOLDER,
    CURRENT_FUNDING,
    PLACEHOLDER,
    PLACEHOLDER,
    MARK_PRICE,
    PLACEHOLDER,
    PLACEHOLDER,
    OPEN_INTEREST
  ]
]

Return type:

list

Examples

bfx_client.status("deriv","ALL")

bfx_client.status("deriv","tBTCF0:USTF0")

bfx_client.status("deriv", "tBTCF0:USTF0",start="1580020000000",end="1580058375000")
liquidation_feed(**kwargs)[source]

Bitfinex Liquidation Feed reference

Endpoint to retrieve liquidations. By default it will retrieve the most recent liquidations, but time-specific data can be retrieved using timestamps.

Parameters:
  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records (Max: 10000)
  • sort (Optional int) – if = 1 it sorts results returned with old > new
Returns:

[
 [
  ['pos',
   POS_ID,
   MTS,
   PLACEHOLDER,
   SYMBOL,
   AMOUNT,
   BASE_PRICE,
   PLACEHOLDER,
   IS_MATCH,
   IS_MARKET_SOLD,
   PLACEHOLDER,
   PRICE_ACQUIRED],
  ['pos',
   ...,]
 ]
]

Return type:

list

Examples

bfx_client.liquidation_feed(start="1580020000000",end="1580058375000");
bfx_client.liquidation_feed()
leaderboards(key, timeframe, symbol, section='hist', **kwargs)[source]

Bitfinex Liquidation Feed reference

The leaderboards endpoint allows you to retrieve leaderboard standings for unrealized profit (period delta), unrealized profit (inception), volume, and realized profit.

Parameters:
  • key (str) – Allowed values: “plu_diff” for unrealized profit (period delta); “plu” for unrealized profit (inception); “vol” for volume; “plr” for realized profit
  • timeframe (str) – Available values: “3h”, “1w”, “1M” - see bitfinex documentation for available time frames per key
  • symbol (str) –
    The symbol you want information about. (e.g. tBTCUSD, tETHUSD, tGLOBAL:USD)
    see bitfinex documentation for available symbols per key
  • section (str) – available values : hist
  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records (Max: 10000)
  • sort (Optional int) – if = 1 it sorts results returned with old > new
Returns:

[[
  MTS,
  PLACEHOLDER,
  USERNAME,
  RANKING,
  PLACEHOLDER,
  PLACEHOLDER,
  VALUE,
  PLACEHOLDER
  PLACEHOLDER
  TWITTER_HANDLE
],
 [
  ...
 ]
]

Return type:

list

Examples

bfx_client.liquidation_feed(start="1580020000000",end="1580058375000");
bfx_client.liquidation_feed()
market_average_price(**kwargs)[source]

Bitfinex market average price reference

Calculate the average execution rate for Trading or Margin funding.

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • amount (str) – Amount. Positive for buy, negative for sell (ex. “1.123”)
  • period (Optional int) – Maximum period for Margin Funding
  • rate_limit (str) – Limit rate/price (ex. “1000.5”)
Returns:

[RATE_AVG, AMOUNT]

Return type:

list

Example

bfx_client.market_average_price(symbol="tBTCUSD", amount="100", period="1m")
foreign_exchange_rate(**kwargs)[source]

Bitfinex foreign exchange rate reference

Parameters:
  • ccy1 (str) – First currency
  • ccy2 (str) – Second currency
Returns:

[ CURRENT_RATE ]

Return type:

list

Example

bfx_client.foreign_exchange_rate(ccy1="IOT", ccy2="USD")
wallets_balance()[source]

Bitfinex wallets balance reference

Get account wallets

Returns:
[
  [
    WALLET_TYPE,
    CURRENCY,
    BALANCE,
    UNSETTLED_INTEREST,
    BALANCE_AVAILABLE,
    ...
  ],
  ...
]
Return type:list

Example

bfx_client.wallets_balance()
wallets_history(**kwargs)[source]

Get account wallet balances for a specific point in time using the “end” param.

Get account wallets historic balance

Returns:
[
  [
    WALLET_TYPE,
    CURRENCY,
    BALANCE,
    UNSETTLED_INTEREST,
    BALANCE_AVAILABLE,
    PLACEHOLDER,
    MTS_UPDATE
  ],
  ...
]

[["margin","BTC",0.00111839,0,null,null,1521244800000],["margin","USD",0.02024216,0,null,null,1544054400000],["funding","ETH",0.15158373,0,null,null,1527379200000]]
Return type:list

Example

bfx_client.wallets_balance()
active_orders(trade_pair='')[source]

Bitfinex active orders reference

Fetch active orders using rest api v2

Parameters:symbol (Optional str) –

The symbol you want information about.

Returns:
[
  [
    ID,
    GID,
    CID,
    SYMBOL,
    MTS_CREATE,
    MTS_UPDATE,
    AMOUNT,
    AMOUNT_ORIG,
    TYPE,
    TYPE_PREV,
    _PLACEHOLDER,
    _PLACEHOLDER,
    FLAGS,
    STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    PRICE,
    PRICE_AVG,
    PRICE_TRAILING,
    PRICE_AUX_LIMIT,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    HIDDEN,
    PLACED_ID,
    ...
  ],
  ...
]
Return type:list

Examples

bfx_client.active_orders("tIOTUSD")
bfx_client.active_orders()
submit_order(order_type, symbol, price, amount, **kwargs)[source]

Bitfinex submit order reference

Submit an Order.

Parameters:
  • order_type (str) – The type of the order: LIMIT, MARKET, STOP, STOP LIMIT, TRAILING STOP, EXCHANGE MARKET, EXCHANGE LIMIT, EXCHANGE STOP, EXCHANGE STOP LIMIT, EXCHANGE TRAILING STOP, FOK, EXCHANGE FOK, IOC, EXCHANGE IOC.
  • symbol (str) – Symbol for desired pair (ex : ‘tBTCUSD’)
  • price (str) – Price of order
  • amount (str) – Amount of order (positive for buy, negative for sell)
  • gid (Optional int32) – (optional) Group id for the order
  • cid (Optional int32) – Client id, Should be unique in the day (UTC) (not enforced)
  • flags (Optional int32) – flags
  • lev (int32) – Set the leverage for a derivative order, supported by derivative symbol orders only. The value should be between 1 and 100 inclusive. The field is optional, if omitted the default leverage value of 10 will be used.
  • price_trailing (str) – The trailing price for a trailing stop order
  • price_aux_limit (str) – Auxiliary Limit price (for STOP LIMIT)
  • price_oco_stop (str) – One cancels other stop price
  • tif (str) – Time-In-Force: datetime for automatic order cancellation (ie. 2020-01-01 10:45:23) )
  • meta (The meta object allows you to pass along an affiliate code inside the object) –
    • example: meta: {aff_code: “AFF_CODE_HERE”}
Returns:

[
  MTS,
  TYPE,
  MESSAGE_ID,
  null,

  [[
     ID,
     GID,
     CID,
     SYMBOL,
     MTS_CREATE,
     MTS_UPDATE,
     AMOUNT,
     AMOUNT_ORIG,
     TYPE,
     TYPE_PREV,
     MTS_TIF,
     _PLACEHOLDER,
     FLAGS,
     ORDER_STATUS,
     _PLACEHOLDER,
     _PLACEHOLDER,
     PRICE,
     PRICE_AVG,
     PRICE_TRAILING,
     PRICE_AUX_LIMIT,
     _PLACEHOLDER,
     _PLACEHOLDER,
     _PLACEHOLDER,
     HIDDEN,
     PLACED_ID,
     _PLACEHOLDER,
     _PLACEHOLDER,
     _PLACEHOLDER,
     ROUTING,
     _PLACEHOLDER,
     _PLACEHOLDER,
     META
   ],
   ]

  CODE,
  STATUS,
  TEXT
]

[1567590617.442,"on-req",null,null,[[30630788061,null,1567590617439,"tBTCUSD",
1567590617439,1567590617439,0.001,0.001,"LIMIT",null,null,null,0,"ACTIVE",
null,null,15,0,0,0,null,null,null,0,null,null,null,null,"API>BFX",null,null,null]],
null,"SUCCESS","Submitting 1 orders."]

Return type:

list

Examples

Submit order to sell 100 leo at 2$
bfx_client.submit_order("EXCHANGE LIMIT", "tLEOUSD", "2.0", "-100");
Submit order to sell 100 leo at 2$ with client id 1829 and make the order hidden
bfx_client.submit_order("EXCHANGE LIMIT", "tLEOUSD", "2.0", "-100", cid=1729, flags=64);
order_update(order_id, **kwargs)[source]

Bitfinex order update reference

Update an existing order, can be used to update margin, exchange, and derivative orders.

Parameters:
  • order_id (int32) – Order ID (Can be retrieved by calling the Retrieve Orders endpoint)
  • cid (Optional int32) – Client id, Should be unique in the day (UTC) (not enforced)
  • cid_date – Client Order ID Date format must be YYYY-MM-DD
  • gid (Optional int32) – (optional) Group id for the order
  • amount (str) – Amount of order (positive for buy, negative for sell)
  • price (str) – Price of order
  • flags (Optional int32) –

    flags

  • lev (int32) – Set the leverage for a derivative order, supported by derivative symbol orders only. The value should be between 1 and 100 inclusive. The field is optional, if omitted the default leverage value of 10 will be used.
  • delta (string) – Change of amount
  • price_aux_limit (str) – Auxiliary Limit price (for STOP LIMIT)
  • price_trailing (str) – The trailing price for a trailing stop order
  • tif (str) – Time-In-Force: datetime for automatic order cancellation (ie. 2020-01-01 10:45:23) )
Returns:

[
  MTS,
  TYPE,
  MESSAGE_ID,
  null,

   [
     ID,
     GID,
     CID,
     SYMBOL,
     MTS_CREATE,
     MTS_UPDATE,
     AMOUNT,
     AMOUNT_ORIG,
     TYPE,
     TYPE_PREV,
     MTS_TIF,
     _PLACEHOLDER,
     FLAGS,
     ORDER_STATUS,
     _PLACEHOLDER,
     _PLACEHOLDER,
     PRICE,
     PRICE_AVG,
     PRICE_TRAILING,
     PRICE_AUX_LIMIT,
     _PLACEHOLDER,
     _PLACEHOLDER,
     _PLACEHOLDER,
     HIDDEN,
     PLACED_ID,
     _PLACEHOLDER,
     _PLACEHOLDER,
     _PLACEHOLDER,
     ROUTING,
     _PLACEHOLDER,
     _PLACEHOLDER,
     META
   ],

  CODE,
  STATUS,
  TEXT
]

[1568110298859,"ou-req",null,null,[30854813589,null,1568109670135,"tBTCUSD",
1568109673000,1568109866000,0.002,0.002,"LIMIT","LIMIT",null,null,0,"ACTIVE",
null,null,20,0,0,0,null,null,null,0,0,null,null,null,"API>BFX",null,null,null],
null,"SUCCESS","Submitting update to limit buy order for 0.002 BTC."]

Return type:

list

Examples

[38646826900, None, 1580627473757, 'tLEOUSD', 1580627474000,
1580627474000, -100, -100, 'EXCHANGE LIMIT', None, None, None, 0,
'ACTIVE', None, None, 2, 0, 0, 0, None, None, None, 0, 0, None,
None, None, 'BFX', None, None, None], [38648166834, None, 1580629128587,
'tLEOUSD', 1580629129000, 1580629129000, -100, -100, 'EXCHANGE LIMIT',
None, None, None, 0, 'ACTIVE', None, None, 2, 0, 0, 0, None, None, None,
0, 0, None, None, None, 'API>BFX', None, None, {'aff_code': 'b2UR2iQr'}]

bfx_client.order_update(38646826900, price="2.01")
bfx_client.order_update(38646826900, amount="-99")
bfx_client.order_update(38646826900, price="2.02", amount="-98", flags=64)
cancel_order(**kwargs)[source]

Bitfinex cancel order reference

Cancel an existing order, can be used to cancel margin, exchange, and derivative orders. You can cancel the order by the Internal Order ID or using a Client Order ID (supplied by you). The Client Order ID is unique per day, so you also have to provide the date of the order as a date string in this format YYYY-MM-DD.

Parameters:
  • order_id (int32) – Order ID (Can be retrieved by calling the Retrieve Orders endpoint)
  • cid (int32) – Client id, Should be unique in the day (UTC) (not enforced)
  • cid_date – Client Order ID Date format must be YYYY-MM-DD
Returns:

[
  MTS,
  TYPE,
  MESSAGE_ID,
  null,

  [
     ID,
     GID,
     CID,
     SYMBOL,
     MTS_CREATE,
     MTS_UPDATE,
     AMOUNT,
     AMOUNT_ORIG,
     TYPE,
     TYPE_PREV,
     MTS_TIF,
     _PLACEHOLDER,
     FLAGS,
     ORDER_STATUS,
     _PLACEHOLDER,
     _PLACEHOLDER,
     PRICE,
     PRICE_AVG,
     PRICE_TRAILING,
     PRICE_AUX_LIMIT,
     _PLACEHOLDER,
     _PLACEHOLDER,
     _PLACEHOLDER,
     HIDDEN,
     PLACED_ID,
     _PLACEHOLDER,
     _PLACEHOLDER,
     _PLACEHOLDER,
     ROUTING,
     _PLACEHOLDER,
     _PLACEHOLDER,
     META
   ]

  CODE,
  STATUS,
  TEXT
]

[1568298355648,"oc-req",null,null,[30937950333,null,1568298279766,"tBTCUSD",
1568298281000,1568298281000,0.001,0.001,"LIMIT",null,null,null,0,"ACTIVE",
null,null,15,0,0,0,null,null,null,0,0,null,null,null,"API>BFX",null,null,
null],null,"SUCCESS","Submitted for cancellation; waiting for confirmation
(ID: 30937950333)."]

Return type:

list

Examples

bfx_client.cancel_order(id=38646826900)
bfx_client.cancel_order(cid=1729, date="2020-02-04")

Canceling by clientid did not work at the time this was written 04/02/2020
get_order_op(op, **kwargs)[source]

utility method to create new order operation

It supports the creation of operations for new order, update order, cancel order, multiple cancel order

Parameters:
  • op (Enum(Operation)) – Operation must be imported from utils
  • kwargs (key value parameters for the operation you want created) –
Returns:

[
  OPERATION,
  {
    ORDER_TYPE,
    ID,
    ...
  }
]

['on', {'order_type': 'EXCHANGE_LIMIT', 'symbol': 'tLEOUSD', 'price': '3', 'amount': '10'}]
['ou', {'id': 124342, 'amount': '10'}]
['oc', {'id': 124342}]
['oc_multi', {'id': [124342, 32432]}]

Return type:

list

Examples

from bitfinex import ClientV2 as Client2
from bitfinex.utils import Operation as Op
bfx_client = Client2('', '')
bfx_client.get_order_op(
    Op.NEW,
    type="EXCHANGE_LIMIT",
    symbol="tLEOUSD",
    price="3",
    amount="10"
    )

bfx_client.get_order_op(
    Op.UPDATE,
    id=124342,
    amount="10"
    )

bfx_client.get_order_op(
    Op.CANCEL,
    id=124342
    )

bfx_client.get_order_op(
    Op.MULTI_CANCEL,
    id=[124342, 32432]
    )
order_multi_op(order_ops)[source]

Bitfinex order multi reference

Send Multiple order-related operations. Please note the sent object has only one property with a value of an array of arrays detailing each order operation.

Parameters:
  • order_type (str) – The type of the order: LIMIT, MARKET, STOP, STOP LIMIT, TRAILING STOP, EXCHANGE MARKET, EXCHANGE LIMIT, EXCHANGE STOP, EXCHANGE STOP LIMIT, EXCHANGE TRAILING STOP, FOK, EXCHANGE FOK, IOC, EXCHANGE IOC.
  • symbol (str) – Symbol for desired pair (ex : ‘tBTCUSD’)
  • price (str) – Price of order
  • amount (str) – Amount of order (positive for buy, negative for sell)
  • gid (Optional int32) – (optional) Group id for the order
  • cid (Optional int32) – Client id, Should be unique in the day (UTC) (not enforced)
  • flags (Optional int32) –

    flags

  • lev (int32) – Set the leverage for a derivative order, supported by derivative symbol orders only. The value should be between 1 and 100 inclusive. The field is optional, if omitted the default leverage value of 10 will be used.
  • price_trailing (str) – The trailing price for a trailing stop order
  • price_aux_limit (str) – Auxiliary Limit price (for STOP LIMIT)
  • price_oco_stop (str) – One cancels other stop price
  • tif (str) – Time-In-Force: datetime for automatic order cancellation (ie. 2020-01-01 10:45:23) )
  • cid_date (str) – Client Order Id Data
  • all (int) – Cancel all open orders if value is set to: 1
Returns:

  • list

  • ::

    [

    MTS, TYPE, MESSAGE_ID, null,

    [

    ID, GID, CID, SYMBOL, MTS_CREATE, MTS_UPDATE, AMOUNT, AMOUNT_ORIG, TYPE, TYPE_PREV, MTS_TIF, _PLACEHOLDER, FLAGS, ORDER_STATUS, _PLACEHOLDER, _PLACEHOLDER, PRICE, PRICE_AVG, PRICE_TRAILING, PRICE_AUX_LIMIT, _PLACEHOLDER, _PLACEHOLDER, _PLACEHOLDER, HIDDEN, PLACED_ID, _PLACEHOLDER, _PLACEHOLDER, _PLACEHOLDER, ROUTING, _PLACEHOLDER, _PLACEHOLDER, META

    ]

    CODE, STATUS, TEXT

    ]

    [1568298355648,”oc-req”,null,null,[30937950333,null,1568298279766,”tBTCUSD”, 1568298281000,1568298281000,0.001,0.001,”LIMIT”,null,null,null,0,”ACTIVE”, null,null,15,0,0,0,null,null,null,0,0,null,null,null,”API>BFX”,null,null,null], null,”SUCCESS”,”Submitted for cancellation; waiting for confirmation (ID: 30937950333).”]

Examples

order_op = bfx_client.get_order_op(
    Op.MULTI_CANCEL,
    id=[38646826900, 38648166834]
)

ops = [order_op]
order_op = bfx_client.get_order_op(
    Op.NEW,
    type="EXCHANGE LIMIT",
    symbol="tLEOUSD",
    price="3",
    amount="-10"
)
ops.append(order_op)

resp = bfx_client.order_multi_op(ops)
print(resp)
cancel_order_multi(**kwargs)[source]

Bitfinex cancel order multi reference

Cancel multiple orders simultaneously.

Orders can be canceled based on the Order ID, the combination of Client Order ID and Client Order Date, or the Group Order ID. Alternatively, the body param ‘all’ can be used with a value of 1 to cancel all orders.

Parameters:
  • id (list) – Order ID (Can be retrieved by calling the Retrieve Orders endpoint)
  • cid (int32) – Client id, Should be unique in the day (UTC) (not enforced)
  • cid_date (str) – Client Order ID Date format must be YYYY-MM-DD
  • gid (int) – Group Order ID
  • all (int) – Cancel all open orders if value is set to: 1 (Trading and Derivatives)
Returns:

[[
    ID,
    GID,
    CID,
    SYMBOL,
    MTS_CREATE,
    MTS_UPDATE,
    AMOUNT,
    AMOUNT_ORIG,
    TYPE,
    TYPE_PREV,
    MTS_TIF,
    _PLACEHOLDER,
    FLAGS,
    ORDER_STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    PRICE,
    PRICE_AVG,
    PRICE_TRAILING,
    PRICE_AUX_LIMIT,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    HIDDEN,
    PLACED_ID,
    _PLACEHOLDER,
    _PLACEHOLDER,
    ROUTING,
    _PLACEHOLDER,
    _PLACEHOLDER,
    META
   ],
    [ID, ...]
   ],
  CODE,
  STATUS,
  TEXT
]

[1568711312683,"oc_multi-req",null,null,[[31123704044,null,1568711144715,"tBTCUSD",
1568711147000,1568711147000,0.001,0.001,"LIMIT",null,null,null,0,"ACTIVE",null,
null,15,0,0,0,null,null,null,0,0,null,null,null,"API>BFX",null,null,null],
[31123725368,null,1568711155664,"tBTCUSD",1568711158000,1568711158000,0.001,0.001,
"LIMIT",null,null,null,0,"ACTIVE",null,null,15,0,0,0,null,null,null,0,0,null,null,
null,"API>BFX",null,null,null]],null,"SUCCESS","Submitting 2 order cancellations."]

Return type:

list

Examples

bfx_client.cancel_order_multi(id=[39259104169, 39271246477])
bfx_client.cancel_order_multi(cid=[[1729, "2020-02-10"], [1729, "2020-02-02"]])
bfx_client.cancel_order_multi(all=1)
Canceling using cid did not work at the time this was written 11/02/2020
orders_history(trade_pair=None, **kwargs)[source]

Bitfinex orders history reference

Returns the most recent closed or canceled orders up to circa two weeks ago

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
  • id (Optional list) – Allows you to retrieve specific orders by order ID (id: [ID1, ID2, ID3])
Returns:

[
  [
    ID,
    GID,
    CID,
    SYMBOL,
    MTS_CREATE,
    MTS_UPDATE,
    AMOUNT,
    AMOUNT_ORIG,
    TYPE,
    TYPE_PREV,
    MTS_TIF,
    _PLACEHOLDER,
    FLAGS,
    ORDER_STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    PRICE,
    PRICE_AVG,
    PRICE_TRAILING,
    PRICE_AUX_LIMIT,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    HIDDEN,
    PLACED_ID,
    _PLACEHOLDER,
    _PLACEHOLDER,
    ROUTING,
    _PLACEHOLDER,
    _PLACEHOLDER,
    META
  ],
  ...
]

[[33961681942,"1227",1337,"tBTCUSD",1573482478000,1573485373000,0.001,0.001,
"EXCHANGE LIMIT",null,null,null,"0","CANCELED",null,null,15,0,0,0,null,null,null,
0,0,null,null,null,"API>BFX",null,null,null],[33950998276,null,1573476812756,
"tBTCUSD",1573476813000,1573485371000,0.0026,0.0026,"LIMIT",null,null,null,"0",
"CANCELED",null,null,8000,0,0,0,null,null,null,0,0,null,null,null,"BFX",
null,null,null]]

Return type:

list

Example

bfx_client.orders_history("tIOTUSD")
bfx_client.orders_history(id=[29889265065,29865773141])
order_trades(trade_pair, order_id)[source]

Bitfinex order trades reference

Get Trades generated by an Order

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • orderid (int) – Order id
Returns:

[
  [
    ID,
    PAIR,
    MTS_CREATE,
    ORDER_ID,
    EXEC_AMOUNT,
    EXEC_PRICE,
    _PLACEHOLDER,
    _PLACEHOLDER,
    MAKER,
    FEE,
    FEE_CURRENCY,
    ...
  ],
  ...
]

Return type:

list

Example

bfx_client.order_trades("tIOTUSD", 14395751815)
trades_history(trade_pair=None, **kwargs)[source]

Bitfinex trades history reference

List of trades

Parameters:
  • trade_pair (Optional str) –

    The symbol you want information about. Omit for all symbols

  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
  • sort (Optional int) – set to 1 to get results in ascending order
Returns:

[
  [
    ID,
    PAIR,
    MTS_CREATE,
    ORDER_ID,
    EXEC_AMOUNT,
    EXEC_PRICE,
    ORDER_TYPE,
    ORDER_PRICE,
    MAKER,
    FEE,
    FEE_CURRENCY,
    ...
  ],
  ...
]

Return type:

list

Examples

bfx_client.trades_history('tIOTUSD', limit=10)

TH = BTFXCLIENT.trades_history("tIOTUSD")
for trade in TH:
    print(trade)
ledgers(currency='', **kwargs)[source]

Bitfinex ledgers reference

View your past ledger entries.

Parameters:
  • Currency (str) – Currency (BTC, …)
  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
Returns:

[
  [
    ID,
    CURRENCY,
    MTS,
    AMOUNT,
    BALANCE,
    DESCRIPTION
  ],
  ...
]

Return type:

list

Example

bfx_client.ledgers('IOT')
margin_info(tradepair='base')[source]

Bitfinex margin info reference

Get account margin info

Parameters:key (str) – “base” | SYMBOL
Returns:
# margin base
[
  "base",
  [
    USER_PL,
    USER_SWAPS,
    MARGIN_BALANCE,
    MARGIN_NET,
    ...
  ]
]

# margin symbol
[
  SYMBOL,
  [
    TRADABLE_BALANCE,
    GROSS_BALANCE,
    BUY,
    SELL,
    ...
  ]
]
Return type:list

Examples

bfx_client.margin_info()

bfx_client.margin_info('base')

bfx_client.margin_info('tIOTUSD')
active_positions()[source]

Bitfinex positions reference

Get active positions

Returns:
[
  [
    SYMBOL,
    STATUS,
    AMOUNT,
    BASE_PRICE,
    MARGIN_FUNDING,
    MARGIN_FUNDING_TYPE,
    PL,
    PL_PERC,
    PRICE_LIQ,
    LEVERAGE
    ...
  ],
  ...
]
Return type:list

Example

bfx_client.active_positions()
positions_history(**kwargs)[source]

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:

[
  [
    SYMBOL,
    STATUS,
    AMOUNT,
    BASE_PRICE,
    MARGIN_FUNDING,
    MARGIN_FUNDING_TYPE,
    PL,
    PL_PERC,
    PRICE_LIQ,
    LEVERAGE,
    ID,
    MTS_CREATE,
    MTS_UPDATE
  ],
  ...
]

Return type:

list

Examples

positions = bfx_client.positions_history(limit=10)
for position in positions:
    print(position)
positions_audit(**kwargs)[source]

Bitfinex positions audit reference

Return and audit of the positions of a user that correspond to the ids send

Parameters:
  • id (Optional list of ints) – List of position IDs to audit
  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
Returns:

[
  [
    SYMBOL,
    STATUS,
    AMOUNT,
    BASE_PRICE,
    MARGIN_FUNDING,
    MARGIN_FUNDING_TYPE,
    PL,
    PL_PERC,
    PRICE_LIQ,
    LEVERAGE,
    ID,
    MTS_CREATE,
    MTS_UPDATE,
    TYPE,
    COLLATERAL,
    COLLATERAL_MIN,
    META
  ],
  ...
]

Return type:

list

Examples

positions = bfx_client.positions_audit([1, 2, 3])
for position in positions:
    print(position)
funding_offers(symbol='')[source]

Bitfinex funding offers reference

Get active funding offers.

Parameters:symbol (str) –

The symbol you want information about.

Returns:
[
  [
    ID,
    SYMBOL,
    MTS_CREATED,
    MTS_UPDATED,
    AMOUNT,
    AMOUNT_ORIG,
    TYPE,
    _PLACEHOLDER,
    _PLACEHOLDER,
    FLAGS,
    STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    RATE,
    PERIOD,
    NOTIFY,
    HIDDEN,
    _PLACEHOLDER,
    RENEW,
    ...
  ],
  ...
]
Return type:list

Examples

bfx_client.funding_offers()

bfx_client.funding_offers("fIOT")
funding_offers_history(symbol='', **kwargs)[source]

Bitfinex funding offers hist reference

Get past inactive funding offers. Limited to last 3 days.

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
Returns:

[
  [
    ID,
    SYMBOL,
    MTS_CREATED,
    MTS_UPDATED,
    AMOUNT,
    AMOUNT_ORIG,
    TYPE,
    _PLACEHOLDER,
    _PLACEHOLDER,
    FLAGS,
    STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    RATE,
    PERIOD,
    NOTIFY,
    HIDDEN,
    _PLACEHOLDER,
    RENEW,
    ...
  ],
  ...
]

Return type:

list

Examples

bfx_client.funding_offers_history()

bfx_client.funding_offers_history('fOMG')
funding_loans(symbol='')[source]

Bitfinex funding loans reference

Funds not used in active positions

Parameters:symbol (str) –

The symbol you want information about.

Returns:
[
  [
    ID,
    SYMBOL,
    SIDE,
    MTS_CREATE,
    MTS_UPDATE,
    AMOUNT,
    FLAGS,
    STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    RATE,
    PERIOD,
    MTS_OPENING,
    MTS_LAST_PAYOUT,
    NOTIFY,
    HIDDEN,
    _PLACEHOLDER,
    RENEW,
    _PLACEHOLDER,
    NO_CLOSE,
    ...
  ],
  ...
]
Return type:list

Example

bfx_client.funding_loans('fOMG')
funding_loans_history(symbol='', **kwargs)[source]

Bitfinex funding loans history reference

Inactive funds not used in positions. Limited to last 3 days.

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
Returns:

[
  [
    ID,
    SYMBOL,
    SIDE,
    MTS_CREATE,
    MTS_UPDATE,
    AMOUNT,
    FLAGS,
    STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    RATE,
    PERIOD,
    MTS_OPENING,
    MTS_LAST_PAYOUT,
    NOTIFY,
    HIDDEN,
    _PLACEHOLDER,
    RENEW,
    _PLACEHOLDER,
    NO_CLOSE,
    ...
  ],
  ...
]

Return type:

list

Example

bfx_client.funding_loans_history('fOMG')
funding_credits(symbol='')[source]

Bitfinex funding credits reference

Funds used in active positions

Parameters:symbol (str) –

The symbol you want information about.

Returns:
[
  [
    ID,
    SYMBOL,
    SIDE,
    MTS_CREATE,
    MTS_UPDATE,
    AMOUNT,
    FLAGS,
    STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    RATE,
    PERIOD,
    MTS_OPENING,
    MTS_LAST_PAYOUT,
    NOTIFY,
    HIDDEN,
    _PLACEHOLDER,
    RENEW,
    _PLACEHOLDER,
    NO_CLOSE,
    ...
  ],
  ...
]
Return type:list

Example

bfx_client.funding_credits('fUSD')
funding_credits_history(symbol='', **kwargs)[source]

Bitfinex funding credits history reference

Inactive funds used in positions. Limited to last 3 days.

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
Returns:

[
  [
    ID,
    SYMBOL,
    SYMBOL,
    MTS_CREATE,
    MTS_UPDATE,
    AMOUNT,
    FLAGS,
    STATUS,
    _PLACEHOLDER,
    _PLACEHOLDER,
    _PLACEHOLDER,
    RATE,
    PERIOD,
    MTS_OPENING,
    MTS_LAST_PAYOUT,
    NOTIFY,
    HIDDEN,
    _PLACEHOLDER,
    RENEW,
    _PLACEHOLDER,
    NO_CLOSE,
    POSITION_PAIR,
    ...
  ],
  ...
]

Return type:

list

Example

bfx_client.funding_credits_history('fUSD')
funding_trades(symbol='', **kwargs)[source]

Bitfinex funding trades hitory reference

Get funding trades

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records
Returns:

[
  [
    ID,
    CURRENCY,
    MTS_CREATE,
    OFFER_ID,
    AMOUNT,
    RATE,
    PERIOD,
    MAKER,
    ...
  ],
  ...
]

Return type:

list

Example

bfx_client.funding_trades('fUSD')
funding_info(tradepair)[source]

Bitfinex funding info reference

Get account funding info

Parameters:symbol (str) –

The symbol you want information about.

Returns:
[
  "sym",
  SYMBOL,
  [
    YIELD_LOAN,
    YIELD_LEND,
    DURATION_LOAN,
    DURATION_LEND,
    ...
  ],
  ...
]
Return type:list

Example

bfx_client.funding_info('fIOT')
transfer_between_wallets(from_wallet, to_wallet, **kwargs)[source]

`Bitfinex Transfer funds between wallets. Can also be used to convert USDT to USDT0 for derivatives trading. <https://docs.bitfinex.com/reference#rest-auth-transfer`_

Post transfer between wallets

Parameters:
  • from_wallet (str) – Select the wallet from which to transfer (exchange, margin, funding (can also use the old labels which are exchange, trading and deposit respectively))
  • to_wallet (str) – Select the wallet from which to transfer (exchange, margin, funding (can also use the old labels which are exchange, trading and deposit respectively))
  • currency (str) –
  • the currency that you would like to transfer (USD, UST, BTC, ...) (Select) –
  • currency_to (str) – (optional) Select the currency that you would like to exchange to (USTF0 === USDT for derivatives pairs)
  • amount (str) – Select the amount to transfer
  • email_dst (str) – (optional) Allows transfer of funds to a sub- or master-account identified by the associated email address
Returns:

  • list

    ::
    [

    MTS, TYPE, MESSAGE_ID, null, [

    MTS_UPDATE, WALLET_FROM, WALLET_TO, _PLACEHOLDER, CURRENCY, CURRENCY_TO, _PLACEHOLDER, AMOUNT

    ] CODE, STATUS, TEXT

    ]

  • //Transfer

  • [1568736745789,”acc_tf”,null,null,[1568736745790,”margin”,”exchange”,null,”USD”,null,null,50],null, – “SUCCESS”,”50.0 US Dollar transferred from Margin to Exchange”]

  • //Transfer and conversion to USDT0

  • [1574173088379,”acc_tf”,null,null,[1574173088379,”exchange”,”margin”,null,”UST”,”USTF0”,null,200],null,

  • ”SUCCESS”,”200.0 Tether USDt transfered from Exchange to Margin”]

Example

::
bfx_client.transfer_between_wallets(from_wallet=’margin’,
to_wallet=’exchange’, currency=’USTF0’, currency_to=’UST’ amount=’1.31’)
movements(currency='', **kwargs)[source]

Bitfinex movements reference

View your past deposits/withdrawals.

Parameters:
  • currency (str) – Currency (BTC, …)
  • start (Optional int) – Millisecond start time
  • end (Optional int) – Millisecond end time
  • limit (Optional int) – Number of records, default & max: 25
Returns:

[
  [
    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
  ],
  ...
]

Return type:

list

Example

bfx_client.movements()

bfx_client.movements("BTC")
alert_list()[source]

Bitfinex list alerts reference

List of active alerts

Returns:
[
  [
    'price:tBTCUSD:560.92',
    'price',
    'tBTCUSD',
    560.92,
    91
  ],
  ...
]
Return type:list

Example

bfx_client.alert_list()
alert_set(alert_type, symbol, price)[source]

Bitfinex auth alert set reference

Sets up a price alert at the given value

Parameters:
  • type (str) – Only one type is available : “price”
  • symbol (str) –

    The symbol you want information about.

  • price (float) – Price where you want to receive alerts
Returns:

[
  'price:tBTCUSD:600',
  'price',
  'tBTCUSD',
  600,
  100
]

Return type:

list

Example

bfx_client.alert_set('price', 'tIOTUSD', 3)
alert_delete(symbol, price)[source]

Bitfinex auth alert delete reference

Bitfinex always returns [True] no matter if the request deleted an alert or not

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • price (float) – Price where you want to receive alerts
Returns:

[ True ]

Return type:

list

Example

bfx_client.alert_delete('tIOTUSD', 1)
calc_available_balance(symbol, direction, rate, order_type)[source]

Bitfinex calc balance available reference

Calculate available balance for order/offer example : calc_available_balance(“tIOTUSD”,”1”,”1.13”,”EXCHANGE”)

Parameters:
  • symbol (str) –

    The symbol you want information about.

  • dir (int) – direction of the order/offer (orders: > 0 buy, < 0 sell | offers: > 0 sell, < 0 buy)
  • rate (string) – Rate of the order/offer
  • type (string) – Type of the order/offer EXCHANGE or MARGIN
Returns:

[AMOUNT_AVAIL]

Return type:

list

Example

bfx_client.calc_available_balance('tIOTUSD', 1, 0.02, 'EXCHANGE')
user_settings_write(pkey)[source]

Bitfinex user settings write reference

Write user settings

Warning

Not Implemented

user_settings_read(pkey)[source]

Bitfinex user settings read reference

Read user settings

Parameters:pkey (str) – Requested Key
Returns:
[
  [
    KEY
    VALUE
  ],
  ...
]
Return type:list

Example

none available
user_settings_delete(pkey)[source]

Bitfinex user settings delete reference

Delete user settings

Warning

Not Implemented

V1 REST

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

Client for the bitfinex.com API.

Link for official bitfinex documentation :

Bitfinex rest1 docs

Bitfinex rest1 reference

Parameters:
  • key (str) – Bitfinex api key
  • secret (str) – Bitfinex api secret
  • nonce_multiplier (Optional float) – Multiply nonce by this number

Examples

bfx_client = Client(key,secret)

bfx_client = Client(key,secret,2.0)
place_order(amount, price, side, ord_type, symbol='btcusd', exchange='bitfinex')[source]

Bitfinex new order

Submit a new Order

Parameters:
  • amount (float) – Order size: how much you want to buy or sell
  • price (float) – Price to buy or sell at. Must be positive. Use random number for market orders.
  • side (string) – Either “buy” or “sell”.
  • ord_type (string) – Either “market” / “limit” / “stop” / “trailing-stop” / “fill-or-kill” / “exchange market” / “exchange limit” / “exchange stop” / “exchange trailing-stop” / “exchange fill-or-kill”. (type starting by “exchange ” are exchange orders, others are margin trading orders)
  • symbol (str) – The symbol you want information about.
  • exchange (str) – ‘bitfinex’
Returns:

# response
{
  "id":448364249,
  "symbol":"btcusd",
  "exchange":"bitfinex",
  "price":"0.01",
  "avg_execution_price":"0.0",
  "side":"buy",
  "type":"exchange limit",
  "timestamp":"1444272165.252370982",
  "is_live":true,
  "is_cancelled":false,
  "is_hidden":false,
  "was_forced":false,
  "original_amount":"0.01",
  "remaining_amount":"0.01",
  "executed_amount":"0.0",
  "order_id":448364249
}

Return type:

dict

Examples

bfx_client.place_order(0.01, 0.01, "buy", "exchange limit", "btcusd")
place_multiple_orders(orders)[source]
Parameters:orders (list) – Each item in the list is a dict that must have the following items : symbol, amount, price, side, type, exchange
Returns:
// response
{
  "order_ids":[
    {
        "id":448383727,
        "symbol":"btcusd",
        "exchange":"bitfinex",
        "price":"0.01",
        "avg_execution_price":"0.0",
        "side":"buy",
        "type":"exchange limit",
        "timestamp":"1444274013.621701916",
        "is_live":true,
        "is_cancelled":false,
        "is_hidden":false,
        "was_forced":false,
        "original_amount":"0.01",
        "remaining_amount":"0.01",
        "executed_amount":"0.0"
    },{
        "id":448383729,
        "symbol":"btcusd",
        "exchange":"bitfinex",
        "price":"0.03",
        "avg_execution_price":"0.0",
        "side":"buy",
        "type":"exchange limit",
        "timestamp":"1444274013.661297306",
        "is_live":true,
        "is_cancelled":false,
        "is_hidden":false,
        "was_forced":false,
        "original_amount":"0.02",
        "remaining_amount":"0.02",
        "executed_amount":"0.0"
    }],
  "status":"success"
}
Return type:dict

Examples

# Make a list with 3 orders to buy 100 iota at 3 dollars,100 iota at 4 dollars and
# 100 iota at 5 dollars
# The list is sent to the method place_multiple_orders
orders = []
for price in range(3, 6):
    print(price)
    payload = {
        "symbol": 'IOTUSD',
        "amount": '100',
        "price": str(price),
        "exchange": 'bitfinex',
        "side": 'buy',
        "type": 'limit'
    }
    orders.append(payload)
response = bfx_client.place_multiple_orders(orders)
print(response)
delete_order(order_id)[source]

Bitfinex cancel order reference

Cancel an order.

Parameters:order_id (int) – The order ID given by new_order function
Returns:
{
  "id":446915287,
  "symbol":"btcusd",
  "exchange":null,
  "price":"239.0",
  "avg_execution_price":"0.0",
  "side":"sell",
  "type":"trailing stop",
  "timestamp":"1444141982.0",
  "is_live":true,
  "is_cancelled":false,
  "is_hidden":false,
  "was_forced":false,
  "original_amount":"1.0",
  "remaining_amount":"1.0",
  "executed_amount":"0.0"
}
Return type:dict

Example

bfx_client.delete_order(448411153)
delete_all_orders()[source]

Bitfinex cancel all orders reference

Cancel all orders at once.

Returns:
{"result":"Orders cancelled"}
Return type:dict

Example

bfx_client.delete_all_orders()
status_order(order_id)[source]

Bitfinex status order reference

Get the status of an order. Is it active? Was it cancelled? To what extent has it been executed? etc.

Parameters:order_id (int) – The order ID given by new_order function
Returns:
{
  "id":448411153,
  "symbol":"btcusd",
  "exchange":null,
  "price":"0.01",
  "avg_execution_price":"0.0",
  "side":"buy",
  "type":"exchange limit",
  "timestamp":"1444276570.0",
  "is_live":false,
  "is_cancelled":true,
  "is_hidden":false,
  "oco_order":null,
  "was_forced":false,
  "original_amount":"0.01",
  "remaining_amount":"0.01",
  "executed_amount":"0.0"
}
Return type:dict

Example

bfx_client.status_order(448411153)
active_orders()[source]

Bitfinex active orders reference

View your active orders.

Returns:
[{
  "id":448411365,
  "symbol":"btcusd",
  "exchange":"bitfinex",
  "price":"0.02",
  "avg_execution_price":"0.0",
  "side":"buy",
  "type":"exchange limit",
  "timestamp":"1444276597.0",
  "is_live":true,
  "is_cancelled":false,
  "is_hidden":false,
  "was_forced":false,
  "original_amount":"0.02",
  "remaining_amount":"0.02",
  "executed_amount":"0.0"
}]
Return type:list

Example

bfx_client.active_orders(448411153)
active_positions()[source]

Bitfinex active positions reference

View your active positions.

Returns:
[{
  "id":943715,
  "symbol":"btcusd",
  "status":"ACTIVE",
  "base":"246.94",
  "amount":"1.0",
  "timestamp":"1444141857.0",
  "swap":"0.0",
  "pl":"-2.22042"
}]
Return type:list

Example

bfx_client.active_positions(448411153)
claim_position(position_id)[source]

Bitfinex claim position reference

A position can be claimed if: It is a long position: The amount in the last unit of the position pair that you have in your trading wallet AND/OR the realized profit of the position is greater or equal to the purchase amount of the position (base price * position amount) and the funds which need to be returned. For example, for a long BTCUSD position, you can claim the position if the amount of USD you have in the trading wallet is greater than the base price * the position amount and the funds used. It is a short position: The amount in the first unit of the position pair that you have in your trading wallet is greater or equal to the amount of the position and the margin funding used.

Parameters:position_id (int) – The position ID
Returns:
{
  "id":943715,
  "symbol":"btcusd",
  "status":"ACTIVE",
  "base":"246.94",
  "amount":"1.0",
  "timestamp":"1444141857.0",
  "swap":"0.0",
  "pl":"-2.2304"
}
Return type:dict

Example

bfx_client.claim_position(18411153)
close_position(position_id)[source]

Bitfinex close position reference

Closes the selected position with a market order.

Parameters:position_id (int) – The position ID
Returns:
{
  "message": "",
    "order": {},
  "position": {}
}
Return type:dict

Example

bfx_client.close_position(18411153)
past_trades(timestamp='0.0', symbol='btcusd')[source]

Bitfinex past trades reference

View your past trades.

Parameters:
  • timestamp (str) – Trades made before this timestamp won’t be returned.
  • symbol (str) –

    The symbol you want information about.

Returns:

[{
  "price":"246.94",
  "amount":"1.0",
  "timestamp":"1444141857.0",
  "exchange":"",
  "type":"Buy",
  "fee_currency":"USD",
  "fee_amount":"-0.49388",
  "tid":11970839,
  "order_id":446913929
}]

Return type:

list

Example

bfx_client.past_trades('0.0','btcusd')
bfx_client.past_trades()
place_offer(currency, amount, rate, period, direction)[source]

Bitfinex place offer reference

Submit a new Offer

Parameters:
  • currency (string) – The name of the currency.
  • amount (float) – Order size: how much to lend or borrow.
  • rate (float) – Rate to lend or borrow at. In percentage per 365 days. (Set to 0 for FRR).
  • period (int) – Number of days of the funding contract (in days)
  • direction (string) – Either “lend” or “loan”.
Returns:

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

Return type:

dict

Example

bfx_client.place_offer("USD",50.0,20.0,2,"lend")
cancel_offer(offer_id)[source]

Bitfinex cancel offer reference

Cancel an offer.

Parameters:offer_id (int) – The offer ID given by new_offer function
Returns:
{
  "id":13800585,
  "currency":"USD",
  "rate":"20.0",
  "period":2,
  "direction":"lend",
  "timestamp":"1444279698.0",
  "is_live":true,
  "is_cancelled":false,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0"
}
Return type:dict

Example

bfx_client.cancel_offer(1231153)
status_offer(offer_id)[source]

Bitfinex status offer reference

Get the status of an offer. Is it active? Was it cancelled? To what extent has it been executed? etc.

Parameters:offer_id (int) – The offer ID given by new_offer function
Returns:
{
  "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"
}
Return type:dict

Example

bfx_client.status_offer(354352)
offers_history()[source]

Bitfinex offers history reference

View your latest inactive offers. Limited to last 3 days and 1 request per minute.

Returns:
[{
  "id":13800719,
  "currency":"USD",
  "rate":"31.39",
  "period":2,
  "direction":"lend",
  "timestamp":"1444280237.0",
  "is_live":false,
  "is_cancelled":true,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0"
}]
Return type:list

Example

bfx_client.offers_history()
active_offers()[source]

Bitfinex active offers reference

View your active offers.

Returns:
[{
  "id":13800719,
  "currency":"USD",
  "rate":"31.39",
  "period":2,
  "direction":"lend",
  "timestamp":"1444280237.0",
  "is_live":true,
  "is_cancelled":false,
  "original_amount":"50.0",
  "remaining_amount":"50.0",
  "executed_amount":"0.0"
}]
Return type:list

Example

bfx_client.active_offers()
balances()[source]

Bitfinex balances reference

See your balances

Returns:
[
    {"type":"deposit", "currency":"btc", "amount":"0.0", "available":"0.0"},
    {"type":"deposit", "currency":"usd", "amount":"1.0", "available":"1.0"},
    {"type":"exchange", "currency":"btc", "amount":"1", "available":"1"},
    {"type":"exchange", "currency":"usd", "amount":"1", "available":"1"},
    {"type":"trading", "currency":"btc", "amount":"1", "available":"1"},
    {"type":"trading", "currency":"usd", "amount":"1", "available":"1"},
...
]
Return type:list

Example

bfx_client.balances()
history(currency, since=0, until=9999999999, limit=500, wallet='exchange')[source]

Bitfinex balance history reference

View all of your balance ledger entries.

Parameters:
  • currency (str) – The currency to look for.
  • since (Optional str) – Return only the history after this timestamp. (Max 3 months before until)
  • until (Optional str) – Return only the history before this timestamp. (Default now)
  • limit (Optional int) – Limit the number of entries to return.
  • wallet (Optional str) – Return only entries that took place in this wallet. Accepted inputs are: “trading”, “exchange”, “deposit”.
Returns:

[{
  "currency":"USD",
  "amount":"-246.94",
  "balance":"515.4476526",
  "description":"Position claimed @ 245.2 on wallet trading",
  "timestamp":"1444277602.0"
}]

Return type:

list

Example

bfx_client.history('USD')
movements(currency, start=0, end=9999999999, limit=10000, method='bitcoin')[source]

Bitfinex Deposit-Withdrawal History reference

View your past deposits/withdrawals.

Parameters:
  • currency (str) – The currency to look for.
  • start (Optional str) – Return only the history after this timestamp. (Max 3 months before until)
  • end (Optional str) – Return only the history before this timestamp. (Default now)
  • limit (Optional int) – Limit the number of entries to return.
  • method (str) – The method of the deposit/withdrawal (can be “bitcoin”, “litecoin”, “iota”, “wire”).
Returns:

[{
  "id":581183,
  "txid": 123456,
  "currency":"BTC",
  "method":"BITCOIN",
  "type":"WITHDRAWAL",
  "amount":".01",
  "description":"3QXYWgRGX2BPYBpUDBssGbeWEa5zq6snBZ, offchain transfer ",
  "address":"3QXYWgRGX2BPYBpUDBssGbeWEa5zq6snBZ",
  "status":"COMPLETED",
  "timestamp":"1443833327.0",
  "timestamp_created": "1443833327.1",
  "fee": 0.1
}]

Return type:

list

Example

bfx_client.movements('USD')
symbols()[source]

Bitfinex symbols reference

A list of symbol names.

Returns:
[
  "btcusd",
  "ltcusd",
  "ltcbtc",
  ...
]
Return type:list

Example

bfx_client.symbols()
symbols_details()[source]

Bitfinex symbols details reference

Get a list of valid symbol IDs and the pair details.

Returns:
[{
  "pair":"btcusd",
  "price_precision":5,
  "initial_margin":"30.0",
  "minimum_margin":"15.0",
  "maximum_order_size":"2000.0",
  "minimum_order_size":"0.01",
  "expiration":"NA"
},{
  "pair":"ltcusd",
  "price_precision":5,
  "initial_margin":"30.0",
  "minimum_margin":"15.0",
  "maximum_order_size":"5000.0",
  "minimum_order_size":"0.1",
  "expiration":"NA"
},{
  "pair":"ltcbtc",
  "price_precision":5,
  "initial_margin":"30.0",
  "minimum_margin":"15.0",
  "maximum_order_size":"5000.0",
  "minimum_order_size":"0.1",
  "expiration":"NA"
},
...
]
Return type:list

Example

bfx_client.symbols_details()
ticker(symbol)[source]

Bitfinex ticker reference

The ticker is a high level overview of the state of the market. It shows you the current best bid and ask, as well as the last trade price. It also includes information such as daily volume and how much the price has moved over the last day.

Parameters:symbol (str) –

The symbol you want information about.

Returns:
{
  "mid":"244.755",
  "bid":"244.75",
  "ask":"244.76",
  "last_price":"244.82",
  "low":"244.2",
  "high":"248.19",
  "volume":"7842.11542563",
  "timestamp":"1444253422.348340958"
}
Return type:dict

Example

bfx_client.ticker("BTCUSD")
today(symbol)[source]

Get today stats

Parameters:symbol (str) –

The symbol you want information about.

Returns:
{"low":"550.09","high":"572.2398","volume":"7305.33119836"}
Return type:dict

Example

bfx_client.today("BTCUSD")
stats(symbol)[source]

Bitfinex stats reference

Various statistics about the requested pair.

Parameters:symbol (str) –

The symbol you want information about.

Returns:
[{
  "period":1,
  "volume":"7967.96766158"
},{
  "period":7,
  "volume":"55938.67260266"
},{
  "period":30,
  "volume":"275148.09653645"
}]
Return type:dict

Example

bfx_client.stats("BTCUSD")
lendbook(currency, parameters=None)[source]

Bitfinex Fundingbook reference

Get the full margin funding book

Parameters:currency (str) – Currency
Returns:
{
  "bids":[{
      'rate': '7.0482',
      'amount': '244575.00836875',
      'period': 30,
      'timestamp': '1539157649.0',
      'frr': False
  }]
  "asks":[{
      'rate': '5.6831',
      'amount': '63.5744',
      'period': 2,
      'timestamp':
      '1539165059.0',
      'frr': False
  }]
}
Return type:dict

Example

bfx_client.lendbook("USD")
order_book(symbol, parameters=None)[source]

Bitfinex Orderbook reference

Get the full order book.

Parameters:currency (str) – Currency
Returns:
{
  "bids":[{
    "price":"574.61",
    "amount":"0.1439327",
    "timestamp":"1472506127.0"
  }],
  "asks":[{
    "price":"574.62",
    "amount":"19.1334",
    "timestamp":"1472506126.0"
  }]
}
Return type:dict

Example

bfx_client.order_book("BTCUSD")
key_permissions()[source]

Bitfinex API Key Permissions

Check the permissions of the key being used to generate this request.

Returns:
{
    'account': {'read': True, 'write': False},
    'history': {'read': True, 'write': False},
    'orders': {'read': True, 'write': False},
    'positions': {'read': True, 'write': False},
    'funding': {'read': True, 'write': False},
    'wallets': {'read': True, 'write': False},
    'withdraw': {'read': False, 'write': False}
}
Return type:dict

Example

bfx_client.order_book("BTCUSD")

Utilities

Module for rest and websocket utilities

class Operation[source]

An enumeration.

create_cid()[source]

Create a new Client order id. Based on timestamp multiplied to 10k to make it improbable that two actions are assigned the same cid.

Returns:A integer number equal to the current timestamp * 10 thousend.
Return type:int
cid_to_date(cid)[source]

Converts a cid to date string YYYY-MM-DD

Parameters:cid (int) – A cid as it is generated by the function utils.create_cid()
Returns:A string formated date (e.g. YYYY-MM-DD, 2018-10-01)
Return type:str
get_nonce(multiplier)[source]

Returns a nonce used in authentication. Nonce must be an increasing number. If other frameworks have used higher numbers you might need to increase the nonce_multiplier.

TRADE_SYMBOL_MISSING = re.compile('^[a-zA-Z]{6}$')

Regular expression used to match trade symbols without a leading t (e.g. BTCUSD)

FUNDING_SYMBOL_MISSING = re.compile('^[a-zA-Z]{3}$')

Regular expression used to match financing symbols without a leading f (e.g. BTC)

order_symbol(symbol, capital=True)[source]

Convinience function for skipping t or f before symbols for trade and funding orders.

Parameters:
  • symbol (str) – Symbol as a string. For example BTCUSD for trades or BTC for funding.
  • capital (bool) – Boolean to capitalize trading and funding symbols. Capilat symbols are required in v2 of the Bitfinex API. Default: True
get_bitfinex_logger(name)[source]

Utility method for class specific logging