Trading and Orders

Crypto Trades

Introduction

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 cash book and adds some BTC. The virtual pair BTCUSD represents your position in the trade, but the virtual pair doesn't actually exist. It simply represents an open trade.

Place Trades

When you place Crypto trades, don't use the CalculateOrderQuantity or SetHoldings methods. Instead, calculate the order quantity based on the currency amounts in your cash book and place manual orders.

The following code snippet demonstrates how to allocate 90% of your portfolio to BTC.

public override void OnData(Slice data)
{
    SetCryptoHoldings(_symbol, 0.9m);
}

private void SetCryptoHoldings(Symbol symbol, decimal percentage)
{
    var crypto = Securities[symbol] as Crypto;
    var baseCurrency = crypto.BaseCurrency;

    // Calculate the target quantity in the base currency
    var targetQuantity = percentage * (Portfolio.TotalPortfolioValue - Settings.FreePortfolioValue) / baseCurrency.ConversionRate;
    var quantity = targetQuantity - baseCurrency.Amount;

    // Round down to observe the lot size
    var lotSize = crypto.SymbolProperties.LotSize;
    quantity = Math.Round(quantity / lotSize) * lotSize;

    if (IsValidOrderSize(crypto, quantity))
    {
        MarketOrder(symbol, quantity);
    }
}

// Brokerages have different order size rules
// Binance considered the minimum volume (price x quantity):
private bool IsValidOrderSize(Crypto crypto, decimal quantity)
{
    return Math.Abs(crypto.Price * quantity) > crypto.SymbolProperties.MinimumOrderSize;
}
def OnData(self, data: Slice):
    self.set_crypto_holdings(self.symbol, .9)

def set_crypto_holdings(self, symbol, percentage):
    crypto = self.Securities[symbol]
    base_currency = crypto.BaseCurrency

    # Calculate the target quantity in the base currency
    target_quantity = percentage * (self.Portfolio.TotalPortfolioValue - self.Settings.FreePortfolioValue) / base_currency.ConversionRate    
    quantity = target_quantity - base_currency.Amount

    # Round down to observe the lot size
    lot_size = crypto.SymbolProperties.LotSize
    quantity = round(quantity / lot_size) * lot_size

    if self.is_valid_order_size(crypto, quantity):
        self.MarketOrder(symbol, quantity)

# Brokerages have different order size rules
# Binance considers the minimum volume (price x quantity):
def is_valid_order_size(self, crypto, quantity):
    return abs(crypto.Price * quantity) > crypto.SymbolProperties.MinimumOrderSize

The preceding example doesn't take into account order fees. You can add a 0.1% buffer to accommodate it.

The following example demonstrates how to form an equal-weighted Crypto portfolio and stay within the cash buffer.

public override void OnData(Slice data)
{
    var percentage = (1m - Settings.FreePortfolioValuePercentage) / _symbols.Count;
    foreach (var symbol in _symbols)
    {
        SetCryptoHoldings(_symbol, percentage);
    }
}
def OnData(self, data: Slice):
    percentage = (1 - self.Settings.FreePortfolioValuePercentage) / len(self.symbols);
    for symbol in self.symbols:
        self.set_crypto_holdings(symbol, percentage)

You can replace the self.Settings.FreePortfolioValuePercentage for a class variable (e.g. self.cash_buffer_cashBuffer).

When you place Crypto trades, ensure you have a sufficient balance of the base or quote currency before each trade. If you hold multiple assets and you want to put all of your capital into BTCUSD, you need to first convert all your non-BTC assets into USD and then purchase BTCUSD.

For a full example of placing crypto trades, see the BasicTemplateCryptoAlgorithmBasicTemplateCryptoAlgorithm.

Liquidate Positions

If you use the Liquidate method to liquidate a Crypto position, it only liquidates the quantity of the virtual pair. Since the virtual pair BTCUSD may not represent all of your BTC holdings, don't use the Liquidate method to liquidate Crypto positions. Instead, calculate the order quantity based on the currency amounts in your cash book and place manual orders. The following code snippet demonstrates how to liquidate a BTCUSD position.

public override void OnData(Slice data)
{
    LiquidateCrypto(_symbol);
}

private void LiquidateCrypto(Symbol symbol)
{
    var crypto = Securities[symbol] as Crypto;
    var baseCurrency = crypto.BaseCurrency;

    // Avoid negative amount after liquidate
    var quantity = Math.Min(crypto.Holdings.Quantity, baseCurrency.Amount);
    
    // Round down to observe the lot size
    var lotSize = crypto.SymbolProperties.LotSize;
    quantity = (Math.Round(quantity / lotSize) - 1) * lotSize;

    if (IsValidOrderSize(crypto, quantity))
    {
        MarketOrder(symbol, -quantity);
    }
}
def OnData(self, data: Slice):
    self.liquidate_crypto(self.symbol)

def liquidate_crypto(self, symbol):
    crypto = self.Securities[symbol]
    base_currency = crypto.BaseCurrency

    # Avoid negative amount after liquidate
    quantity = min(crypto.Holdings.Quantity, base_currency.Amount)
        
    # Round down to observe the lot size
    lot_size = crypto.SymbolProperties.LotSize;
    quantity = (round(quantity / lot_size) - 1) * lot_size

    if self.IsValidOrderSize(crypto, quantity):
        self.MarketOrder(symbol, -quantity)

The order fees don't respect the lot size. When you try to liquidate a position, the absolute value of the base currency quantity can be less than the lot size and greater than zero. In this case, your algorithm holds a position that you can't liquidate and self.Portfolio[symbol].Invested is Truetrue. The following code snippet demonstrates how to determine if you can liquidate a position:

public override void OnData(Slice data)
{
    var crypto = Securities[_symbol];
    if (Math.Abs(crypto.Holdings.Quantity) > crypto.SymbolProperties.LotSize)
    {
        LiquidateCrypto(_symbol);
    }
}
def OnData(self, data: Slice):
    crypto = self.Securities[self.symbol]
    if abs(crypto.Holdings.Quantity) > crypto.SymbolProperties.LotSize:
        self.liquidate_crypto(self.symbol)

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: