book
Checkout our new book! Hands on AI Trading with Python, QuantConnect, and AWS Learn More arrow

Crypto

Holdings

Introduction

Crypto holdings require special consideration because not all brokerages track your positions in each currency pair.

Cash vs Margin Brokerage Accounts

Some of the Crypto brokerages integrated into QuantConnect support cash and margin accounts while some only support cash accounts. If you want to short Crypto assets or use leverage, you need a margin account. Follow these steps to view which account types each brokerage supports:

  1. Open the brokerage guides.
  2. Click a Crypto brokerage.
  3. Scroll down to the Account Types section.

Virtual Pairs

All fiat and Crypto currencies are individual assets. When you buy a pair like BTCUSD, you trade USD for BTC. In this case, LEAN removes some USD from your portfolio cashbook and adds some BTC. The virtual pair BTCUSD represents your position in that trade, but the virtual pair doesn't actually exist. It simply represents an open trade. If you call the Liquidate method with the symbol of a virtual pair, the method only liquidates the quantity in your virtual pair. For more information about liquidating Crypto postitions, see Crypto Trades.

Access Cypto Holdings

The cash_book stores the quantity of your Crypto holdings. To access your Crypto holdings, index the cash_book with the currency ticker. The values of the CashBook dictionary are Cash objects, which have the following properties:

Select Language:
btc_quantity = self.portfolio.cash_book['BTC'].amount
btc_value = self.portfolio.cash_book['BTC'].value_in_account_currency

To access the virtual pair of your Crypto trades, index the portfolio object with the pair symbol.

Select Language:
security_holding  = self.portfolio[self._btc_usd_symbol]

Stateful Redeployments

When you make a trade inside of a running algorithm, LEAN tracks the virtual position state for you, but it won't survive between deployments. Some brokerages save your virtual pairs, so you can load them into your algorithm when you stop and redeploy it. Depending on the brokerage you select, you may be able to manually add virtual pairs when you deploy live algorithms with the LEAN CLI or cloud deployment wizard.

Examples

The following examples demonstrate some common practices for crypto holdings.

Example 1: ETH-BTC Proxy Trading

The following algorithm trades trend-following of the ETHBTC crypto pair using a 20-day EMA indicator. To reduce friction (e.g. slippage), we trade the more liquid and popular BTCUSDT and ETHUSDT pair instead. For example, if ETHBTC is above EMA (uptrend), we buy ETHUSDT and sell BTCUSDT with the same size in USDT.

Select Language:
class CryptoHoldingsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 1, 1)
        self.set_end_date(2024, 3, 1)
        self.set_account_currency("USDT", 1000000)
        # Seed the last price to set the initial holding price of the cryptos.
        self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))

        # We would like to trade the EMA cross between 2 popular cryptos: BTC & ETH,
        # so we request ETHBTC data to find trading opportunities.
        self.ethbtc = self.add_crypto("ETHBTC", Resolution.DAILY, market=Market.COINBASE).symbol
        # Trade through BTCUSDT & ETHUSDT, though, since stable coin trades have lower friction costs and higher liquidity.
        btcusdt = self.add_crypto("BTCUSDT", Resolution.DAILY, market=Market.COINBASE)
        ethusdt = self.add_crypto("ETHUSDT", Resolution.DAILY, market=Market.COINBASE)
        self.btcusdt = btcusdt.symbol
        self.ethusdt = ethusdt.symbol
        # Simulate an account with various crypto cash through holdings.
        btcusdt.holdings.set_holdings(btcusdt.price, 5)
        ethusdt.holdings.set_holdings(ethusdt.price, 22.5)

        # Add automatic updating of the EMA indicator for trend trade signal emission.
        self._ema = self.ema(self.ethbtc, 20, Resolution.DAILY)
        # Warm up the indicator for its readiness usage immediately.
        self.warm_up_indicator(self.ethbtc, self._ema, Resolution.DAILY)

    def on_data(self, slice: Slice) -> None:
        bar = slice.bars.get(self.ethbtc)
        btc = slice.bars.get(self.btcusdt)
        eth = slice.bars.get(self.ethusdt)
        if bar and self._ema.is_ready and btc and eth:
            ema = self._ema.current.value
            # ETHBTC's current price is higher than EMA, suggesting an uptrend.
            if bar.close > ema and not self.portfolio[self.btcusdt].is_short:
                # Calculate the order size needed to have equal BTC-ETH value exposure.
                btc_size, eth_size = self.calculate_order_size(btc.close, eth.close)
                # To follow the up trend of ETHBTC, sell BTCUSDT and buy ETHUSDT.
                self.market_order(self.btcusdt, -btc_size)
                self.market_order(self.ethusdt, eth_size)
            # ETHBTC's current price is below the EMA, suggesting a downtrend.
            elif bar.close < ema and not self.portfolio[self.btcusdt].is_long:
                # Calculate the order size needed to have equal BTC-ETH value exposure.
                btc_size, eth_size = self.calculate_order_size(btc.close, eth.close)
                # To follow the downtrend of ETHBTC, buy BTCUSDT and sell ETHUSDT.
                self.market_order(self.ethusdt, -eth_size)
                self.market_order(self.btcusdt, btc_size)

    def calculate_order_size(self, btc_price: float, eth_price: float) -> Tuple[float]:
        # Invest 10% of the portfolio in the 2-leg trade, which will be 5% per each leg.
        position_value = self.portfolio.total_portfolio_value * 0.05
        # Calculate the extra position needed to hold BTC/ETH in the same size as USDT in the 2-leg trade.
        btc_size = (position_value - self.portfolio.cash_book["BTC"].value_in_account_currency) / btc_price
        eth_size = (position_value - self.portfolio.cash_book["ETH"].value_in_account_currency) / eth_price
        return btc_size, eth_size

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: