from AlgorithmImports import *
class BTCUSDTrendFollowingAlgorithm(QCAlgorithm):
def Initialize(self):
# Extended backtest period
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2024, 1, 1)
self.SetCash(100000)
# Add BTC/USDC pair
self.symbol = self.AddCrypto("BTCUSDC", Resolution.Daily).Symbol
# Use a 10-day EMA
self.ema = self.EMA(self.symbol, 10, Resolution.Daily)
self.SetWarmUp(10, Resolution.Daily) # Match warm-up to EMA period
# Adjusted parameters
self.stop_loss_percentage = 0.05 # 5% stop-loss
self.allocation_percentage = 0.5 # 50% allocation
def OnData(self, data):
if not self.IsWarmingUp and data.ContainsKey(self.symbol):
price = data[self.symbol].Close
ema_value = self.ema.Current.Value
# Enter trades when not invested
if not self.Portfolio.Invested:
if price > ema_value: # Long
quantity = self.CalculateOrderQuantity(self.symbol, self.allocation_percentage)
self.MarketOrder(self.symbol, quantity)
elif price < ema_value: # Short
quantity = self.CalculateOrderQuantity(self.symbol, -self.allocation_percentage)
self.MarketOrder(self.symbol, quantity)
# Manage existing trades
else:
holding = self.Portfolio[self.symbol]
if holding.Invested:
if holding.Quantity > 0: # Long
stop_price = holding.AveragePrice * (1 - self.stop_loss_percentage)
if price < stop_price:
self.Liquidate(self.symbol)
elif holding.Quantity < 0: # Short
stop_price = holding.AveragePrice * (1 + self.stop_loss_percentage)
if price > stop_price:
self.Liquidate(self.symbol)