Brokerages

Bitfinex

Introduction

QuantConnect enables you to run your algorithms in live mode with real-time market data. We have successfully hosted more than 200,000 live algorithms and have had more than $15B in volume traded on our servers since 2015. Brokerages supply a connection to the exchanges so that you can automate orders using LEAN. You can use multiple data feeds in live trading algorithms.

Bitfinex was founded by Giancarlo Devasini and Raphael Nicolle in 2012 with the goal to "give our users the ultimate cryptocurrency trading experience". Bitfinex provides access to trading Crypto for clients outside prohibited jurisdictions with no minimum deposit to set up an account. If you fund your account with fiat currency, they enforce a 10,000 minimum for USD, EUR, and GBP. However, if you fund your account with Crypto, they do not enforce a minimum deposit. Bitfinex also provides Crypto staking, a mobile app, and an unrealized profit leaderboard for the traders on the platform. Bitfinex has always been at the forefront of technological innovation in digital asset trading.

Account Types

Bitfinex supports cash and margin accounts.

SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Cash);
SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin);
self.SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Cash)
self.SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin)

Use AccountType.Cash to connect to your Exchange wallet or AccountType.Margin to connect to your Margin wallet. You can not connect to your Funding or Capital Raise wallet. If you provide the wrong AccountType to the SetBrokerageModel method, you may connect to an empty wallet, causing Lean to throw a warning. If you have a currency in your wallet that ends with "F0", it will not load into your CashBook.

Create an Account

Follow the account creation wizard on the Bitfinex website to create a Bitfinex account.

You will need API credentials to deploy live algorithms. After you have an account, create API credentials and store them somewhere safe.

Paper Trading

Bitfinex supports paper trading with only the TESTBTCTESTUSD and TESTBTCTESTUSDT securities. Follow these steps to paper trade with Bitfinex:

  1. Create a paper trading sub-account and refill the paper balance For instructions, see Paper Trading at Bitfinex on the Bitfinex website.
  2. Create an API key for your sub-account. For instructions, see How to create and revoke a Bitfinex API Key on the Bitfinex website.
  3. Use AccountType.Cash in your algorithms.

To paper trade securities other than TESTBTCTESTUSD and TESTBTCTESTUSDT, follow these steps to simulate paper trading with the QuantConnect Paper Trading brokerage:

  1. In the Initialize method of your algorithm, add one of the preceding SetBrokerageModel method calls.
  2. Deploy your algorithm with the QuantConnect Paper Trading brokerage.

Asset Classes

Bitfinex supports trading Crypto.

AddCrypto("BTCUSDT", Resolution.Minute, Market.Bitfinex);
self.AddCrypto("BTCUSDT", Resolution.Minute, Market.Bitfinex)

If you call the SetBrokerageModel method with the correct BrokerageName, then you don't need to pass a Market argument to the AddCrypto method because the brokerage model automatically selects the correct market.

Assets Available

Refer to the Bitfinex Crypto Price Data dataset to see the assets available.

Orders

We model the Bitfinex API by supporting several order types, order properties, and order updates. When you deploy live algorithms, you can place manual orders through the IDE.

Order Types

Bitfinex supports the following order types:

  • MarketOrder
  • LimitOrder
  • StopMarketOrder
  • StopLimitOrder
  • MarketOnOpenOrder
  • MarketOnCloseOrder
  • LimitIfTouchedOrder
MarketOrder(_symbol, quantity);
LimitOrder(_symbol, quantity, limitPrice);
StopMarketOrder(_symbol, quantity, stopPrice);
StopLimitOrder(_symbol, quantity, stopPrice, limitPrice);
MarketOnOpenOrder(_symbol, quantity);
MarketOnCloseOrder(_symbol, quantity);
LimitIfTouchedOrder(_symbol, quantity, triggerPrice, limitPrice);
self.MarketOrder(self.symbol, quantity)
self.LimitOrder(self.symbol, quantity, limit_price)
self.StopMarketOrder(self.symbol, quantity, stop_price)
self.StopLimitOrder(self.symbol, quantity, stop_price, limit_price)
self.MarketOnOpenOrder(self.symbol, quantity)
self.MarketOnCloseOrder(self.symbol, quantity)
self.LimitIfTouchedOrder(self.symbol, quantity, trigger_price, limit_price)

Order Properties

We model custom order properties from the Bitfinex API. The following table describes the members of the BitfinexOrderProperties object that you can set to customize order execution:

PropertyDescription
TimeInForce A TimeInForce instruction to apply to the order. The following instructions are supported:
  • Day
  • GoodTilCanceled
  • GoodTilDate
HiddenA flag to signal that the order should be hidden. Hidden orders do not appear in the order book, so they do not influence other market participants. Hidden orders incur the taker fee.
PostOnlyA flag to signal that the order must only add liquidity to the order book and not take liquidity from the order book. If part of the order results in taking liquidity rather than providing liquidity, the order is rejected without any part of it being filled.
public override void Initialize()
{
    // Set the default order properties
    DefaultOrderProperties = new BitfinexOrderProperties
    {
        TimeInForce = TimeInForce.GoodTilCanceled,
        Hidden = false,
        PostOnly = false
    };
}

public override void OnData(Slice slice)
{
    // Use default order order properties
    LimitOrder(_symbol, quantity, limitPrice);
    
    // Override the default order properties
    LimitOrder(_symbol, quantity, limitPrice, 
               orderProperties: new BitfinexOrderProperties
               { 
                   TimeInForce = TimeInForce.Day,
                   Hidden = true,
                   PostOnly = false
               });
    LimitOrder(_symbol, quantity, limitPrice, 
               orderProperties: new BitfinexOrderProperties
               { 
                   TimeInForce = TimeInForce.GoodTilDate(new DateTime(year, month, day)),
                   Hidden = false,
                   PostOnly = true
               });
}
def Initialize(self) -> None:
    # Set the default order properties
    self.DefaultOrderProperties = BitfinexOrderProperties()
    self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled
    self.DefaultOrderProperties.Hidden = False
    self.DefaultOrderProperties.PostOnly = False

def OnData(self, slice: Slice) -> None:
    # Use default order order properties
    self.LimitOrder(self.symbol, quantity, limit_price)
    
    # Override the default order properties
    order_properties = BitfinexOrderProperties()
    order_properties.TimeInForce = TimeInForce.Day
    order_properties.Hidden = True
    order_properties.PostOnly = False
    self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties)

    order_properties.TimeInForce = TimeInForce.GoodTilDate(datetime(year, month, day))
    order_properties.Hidden = False
    order_properties.PostOnly = True
    self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties)

Updates

We model the Bitfinex API by supporting order updates. You can define the following members of the UpdateOrderFields object to update active orders:

  • Quantity
  • LimitPrice
  • StopPrice
  • TriggerPrice
  • Tag
var ticket = StopLimitOrder(symbol, quantity, stopPrice, limitPrice, tag);
var orderFields = new UpdateOrderFields { 
Quantity = newQuantity,
LimitPrice = newLimitPrice,
StopPrice = newStopPrice,
Tag = newTag
}; ticket.Update(orderFields);
ticket = self.StopLimitOrder(symbol, quantity, stop_price, limit_price, tag)
update_fields = UpdateOrderFields() update_fields.Quantity = new_quantity
update_fields.LimitPrice = new_limit_price
update_fields.StopPrice = new_stop_price update_fields.Tag = new_tag ticket.Update(update_fields)

Fees

We model the order fees of Bitfinex, which are a 0.1% maker fee and a 0.2% taker fee. If you place a limit order that hits a hidden order or you add liquidity to the order book by placing a limit order that doesn't cross the spread, you pay maker fees. If you place a hidden order or you remove liquidity from the order book by placing an order that crosses the spread, you pay taker fees. Bitfinex adjusts your fees based on your 30-day trading volume and LEO balance, but we don't currently model these metrics to adjust fees. To check the latest fees at all the fee levels, see the Fees Schedule page on the Bitfinex website.

To use the Bitfinex brokerage in a live algorithm, the following table shows the fee settings you need on your Account > Fees page on the Bitfinex website:

Fee SettingValue
Default currency for feesUSD
Fee type for Exchange ordersCurrency Exchange Fee

Margin

We model buying power and margin calls to ensure your algorithm stays within the margin requirements.

Buying Power

Bitfinex allows up to 3.3x leverage for margin accounts.

Margin Calls

Regulation T margin rules apply. When the amount of margin remaining in your portfolio drops below 5% of the total portfolio value, you receive a warning. When the amount of margin remaining in your portfolio drops to zero or goes negative, the portfolio sorts the generated margin call orders by their unrealized profit and executes each order synchronously until your portfolio is within the margin requirements.

Slippage

Orders through Bitfinex do not experience slippage in backtests. In paper trading and live trading, your orders may experience slippage.

Fills

We fill market orders immediately and completely in backtests. In live trading, if the quantity of your market orders exceeds the quantity available at the top of the order book, your orders are filled according to what is available in the order book.

Settlements

Trades settle immediately after the transaction.

security.SettlementModel = new ImmediateSettlementModel();
security.SettlementModel = ImmediateSettlementModel()

Security and Stability

Note the following security and stability aspects of our Bitfinex integration.

Account Credentials

When you deploy live algorithms with Bitfinex, we don't save your brokerage account credentials.

API Outages

We call the Bitfinex API to place live trades. Sometimes the API may be down. Check the Bitfinex status page to see if the API is currently working.

Deposits and Withdraws

You can deposit and withdraw cash from your brokerage account while you run an algorithm that's connected to the account. We sync the algorithm's cash holdings with the cash holdings in your brokerage account every day at 7:45 AM Eastern Time (ET).

Demo Algorithm

The following algorithm demonstrates the functionality of the Bitfinex brokerage:

Deploy Live Algorithms

You must have an available live trading node for each live trading algorithm you deploy.

Follow these steps to deploy a live algorithm:

  1. Open the project that you want to deploy.
  2. If you are deploying a paper trading algorithm without the QuantConnect Paper Trading brokerage, include the following lines of code in the Initialize method of your algorithm:

    self.SetAccountCurrency("TESTUSD") # or "TESTUSDT"
    self.SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Cash)
    self.SetBenchmark(lambda x: 0) # or the Symbol of the TESTBTCTESTUSD/TESTBTCTESTUSDT securities
    SetAccountCurrency("TESTUSD"); // or "TESTUSDT"
    SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Cash);
    SetBenchmark(x => 0); // or the Symbol of the TESTBTCTESTUSD/TESTBTCTESTUSDT securities
    
  3. Click the Deploy Live icon.
  4. On the Deploy Live page, click the Brokerage field and then click Bitfinex Exchange from the drop-down menu.
  5. Enter your API key and secret.
  6. To generate your API credentials, see Account Types. Your account details are not saved on QuantConnect.

  7. Click the Node field and then click the live trading node that you want to use from the drop-down menu.
  8. (Optional) Set up notifications.
  9. Configure the Automatically restart algorithm setting.
  10. By enabling automatic restarts, the algorithm will use best efforts to restart the algorithm if it fails due to a runtime error. This can help improve the algorithm's resilience to temporary outages such as a brokerage API disconnection.

  11. Click Deploy.

The deployment process can take up to 5 minutes. When the algorithm deploys, the live results page displays. If you know your brokerage positions before you deployed, you can verify they have been loaded properly by checking your equity value in the runtime statistics, your cashbook holdings, and your position holdings.

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: