from bfxapi import Client
bfx = Client(
API_KEY=API_KEY,
API_SECRET=API_SECRET,
logLevel='DEBUG'
)
@bfx.ws.on('new_trade')
def log_trade(trade):
print ("New trade: {}".format(trade))
@bfx.ws.on('connected')
def start():
bfx.ws.subscribe('trades', 'tBTCUSD')
bfx.ws.run()
This is an official python library that is used to connect interact with the Bitfinex api. Currently it only has support for websockets but will soon have Rest functionality as well.
Install dependencies
pip3 install -r requirements.txt
Run the trades/candles example:
cd bfxapi/examples
python3 subsribe_trades_candles.py
- Fast websocket connection
- Event based routing
- Subscribe to trade, candles and orderbook channels
- Authenticate with api key/secret
- Orderbook checksum validation
- Create, update and close orders
- Track wallet updates
bfx = Client(
API_KEY='<YOUR_API_KEY>'
API_SECRET='<YOUR_API_SECRET>'
)
@bfx.ws.on('authenticated')
async def do_something():
print ("Success!")
bfx.ws.run()
from bfxapi import Order
await bfx.ws.submit_order('tBTCUSD', 100, 0.01, Order.Type.EXCHANGE_MARKET)
@bfx.ws.on('order_confirmed')
async def order_completed(order, trade):
print ("Order has been confrmed")
wallets = bfxapi.ws.wallets.get_wallets()
# [ Wallet <'exchange_BTC' balance='41.25809589' unsettled='0'>,
# Wallet <'exchange_USD' balance='62761.86070104' unsettled='0'> ]
All order function support onConfirm and onClose async callbacks. onConfirm is fired when we receive a signal from the websocket that the order has been confirmed. onClose is fired when we receive a signal that the order has either been filled or canceled.
async def on_confirm(order):
await bfx.ws.update_order(order.id, price=1000)
await bfx.ws.submit_order('tBTCUSD', 800, 0.1, onConfirm=on_confirm)
await bfx.ws.close_all_orders()
The websocket exposes a collection of events that are triggered when certain data is received. When subscribing to an event you are able to pass either a standard function or an asyncio co-routine Here is a full list of available events:
all
(array|json): listen for all messages coming throughconnected:
() called when a connection is madedisconnected
: () called when a connection is ended (A reconnect attempt may follow)stopped
: () called when max amount of connection retries is met and the socket is closedauthenticated
(): called when the websocket passes authenticationnotification
(array): incoming account notificationerror
(array): error from the websocketorder_closed
(Order, Trade): when an order has been closedorder_new
(Order, Trade): when an order has been created but not closed. Note: will not be called if order is executed and filled instantlyorder_confirmed
(Order, Trade): When an order has been submitted and receivedwallet_snapshot
(array[Wallet]): Initial wallet balances (Fired once)order_snapshot
(array[Order]): Initial open orders (Fired once)positions_snapshot
(array): Initial open positions (Fired once)wallet_update
(Wallet): changes to the balance of walletsseed_candle
(json): initial past candle to prime strategyseed_trade
(json): initial past trade to prime strategyfunding_offer_snapshot
(array): opening funding offer balancesfunding_loan_snapshot
(array): opening funding loan balancesfunding_credit_snapshot
(array): opening funding credit balancesbalance_update
(array): when the state of a balance is changednew_trade
(array): a new trade on the market has been executednew_candle
(array): a new candle has been producedmargin_info_updates
(array): new margin information has been broadcastedfunding_info_updates
(array): new funding information has been broadcastedorder_book_snapshot
(array): initial snapshot of the order book on connectionorder_book_update
(array): a new order has been placed into the ordebrooksubscribed
(Subscription): a new channel has been subscribed tounsubscribed
(Subscription): a channel has been un-subscribed
Subscribe a given function to be called when an event fires
Subscribes the function to the given event but only triggers once.
Subscribes the socket to a data feed such as 'trades' or 'candles'.
Unsubscribes from the given data feed
Unsubscribes and then subscribes to the given data feed. Usually used to trigger a snapshot response from the API.
Unsubscribe from all data feeds.
Unsubscribe and subscribe to all data feeds
submit_order(symbol, price, amount, market_type, hidden=False, onConfirm=None, onClose=None, *args, **kwargs)
Submits an order to the Bitfinex api. When it has been verified that bitfine xhas received the order then the onConfirm
callback will be called followed by the order_confirmed
event. Once it has been verified that the order has completely closed due to either being filled or canceled then the onClose
function will be called, followed by the order_closed
event.
update_order(orderId, price=None, amount=None, delta=None, price_aux_limit=None, price_trailing=None, flags=None, time_in_force=None, onConfirm=None, onClose=None)
Attempts to update an order with the given values. If the order is no longer open then the update will be ignored.
Close the order with the given orderId if it still open.
Tells the OrderManager to close all of the open orders
Takes an array of orderIds and closes them all.
Returns an array of wallets that represent the users balance in the different currencies
Sends a subscribe command to start receiving data
Sends a unsubscribe command to stop receiving data
Returns true if the subscription is open and receiving data
Get All of the public candles between the given start and end period
Get all of the public trades between the start and end period
Get the public orderbook of a given symbol
Get tickers for the given symbol. Tickers shows you the current best bid and ask, as well as the last trade price.
Get tickers for the given symbols. Tickers shows you the current best bid and ask, as well as the last trade price.
Get all wallets on account associated with API_KEY - Requires authentication.
Get all of the active orders associated with API_KEY - Requires authentication.
Get all of the orders between the start and end period associated with API_KEY
- Requires authentication.
Get all of the active position associated with API_KEY - Requires authentication.
Get all of the trades that have been generated by the given order associated with API_KEY - Requires authentication.
Get all of the trades between the start and end period associated with API_KEY
- Requires authentication.
Get all of the funding offers associated with API_KEY - Requires authentication.
Get all of the funding offers between the start and end period associated with API_KEY - Requires authentication.
Get all of the funding loans associated with API_KEY - Requires authentication.
Get all of the funding loans between the start and end period associated with API_KEY - Requires authentication.
Get all of the funding credits associated with API_KEY - Requires authentication.
Get all of the funding credits between the start and end period associated with API_KEY - Requires authentication.
For more info on how to use this library please see the example scripts in the bfxapi/examples
directory. Here you will find usage of all interface exposed functions for both the rest and websocket.
Also please see this medium article for a tutorial.
- Fork it ( https://github.com/[my-github-username]/bitfinex/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request