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.

var targetQuantity = 0.9m * Portfolio.TotalPortfolioValue / Securities["BTCUSD"].Price;
var quantity = targetQuantity - Portfolio.CashBook['BTC'].Amount;
MarketOrder("BTCUSD", quantity);
target_quantity = 0.9 * self.Portfolio.TotalPortfolioValue / self.Securities["BTCUSD"].Price
quantity = target_quantity - self.Portfolio.CashBook['BTC'].Amount
self.MarketOrder("BTCUSD", quantity)

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

var usdPerSymbol = Portfolio.CashBook["USD"].Amount * (1m - _cashBuffer) / _symbols.Count();
foreach (var symbol in _symbols)
{
    MarketOrder(symbol, usdPerSymbol / data[symbol].Price);
}
usd_per_symbol = self.Portfolio.CashBook['USD'].Amount * (1 - self.cash_buffer) / len(self.symbols)
for symbol in self.symbols:
    self.MarketOrder(symbol, usd_per_symbol / data[symbol].Price)

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.

var quantity = Portfolio.CashBook['BTC'].Amount / Securities["BTCUSD"].Price;
MarketOrder("BTCUSD", quantity);
quantity = self.Portfolio.CashBook['BTC'].Amount / self.Securities["BTCUSD"].Price
self.MarketOrder("BTCUSD", quantity)

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: