Official Python bfxapi
This repo contains an official python library that is used to connect to the both the Bitfinex api and the Honey Frameworks data-server. The library communicates with these servers using both websocket connection and a REST interface.
bfxapi.LiveWebsocket
The websocket exposes a collection of events that are triggered when certain data is received. Here is a full list of available events:
all: listen for all messages coming throughconnected:called when a connection is madeauthenticated: called when the websocket passes authenticationmessage(string): new incoming message from the websocketnotification(array): incoming account notificationerror(string): error from the websocketorder_closed(string): when an order confirmation is recievedwallet_snapshot(string): Initial wallet balances (Fired once)order_snapshot(string): Initial open orders (Fired once)positions_snapshot(string): Initial open positions (Fired once)wallet_update(string): changes to the balance of walletsseed_candle(candleArray): initial past candle to prime strategyseed_trade(tradeArray): initial past trade to prime strategyfunding_offer_snapshot: opening funding offer balancesfunding_loan_snapshot:opening funding loan balancesfunding_credit_snapshot: opening funding credit balancesbalance_updatewhen the state of a balance is changednew_trade: a new trade on the market has been executednew_candle: a new candle has been produced
For example. If you wanted to subscribe to all of the trades on the tBTCUSD market, then you can simply listen to the new_trade event. For Example:
ws = LiveBfxWebsocket(
logLevel='INFO'
)
@ws.on('new_trade')
def log_trade(trade):
print ("New trade: {}".format(trade))
@ws.on('connected')
def start():
ws.subscribe('trades', 'tBTCUSD')
ws.run()
NOTE: Instead of using the python decorators, you can also listen to events via function call:
ws.on('new_trade', log_trade)
bfxapi.DataServerWebsocket
The data-server websocket is used for retrieving large amounts of historical data from a bfx-hf-data-server instance. The library then takes all of the incoming historical data from the server and pushes it down the new_trade and new_candle events. For information on how to start a data-server instance please visit the repo at: https://github.com/bitfinexcom/bfx-hf-data-server
A list of events available:
connected: connection is madenew_trade: a historical trade item is receivednew_candle: a historical candle item is receiveddone: backtest has finished running
An example of a script that loads all of the historical trades for symbol tBTCUSD over the last 2 days:
ws = DataServerWebsocket(
symbol='tBTCUSD',
host='ws://localhost:8899'
)
@ws.on('new_trade')
def trade(trade):
print ("Backtest trade: {}".format(trade))
@ws.on('done')
def finish():
print ("Backtest complete!")
now = int(round(time.time() * 1000))
then = now - (1000 * 60 * 60 * 24 * 2) # 2 days ago
ws.run(then, now)