Overall Statistics
Total Orders
39
Average Win
0.12%
Average Loss
0%
Compounding Annual Return
1597.371%
Drawdown
5.500%
Expectancy
0
Start Equity
1000000
End Equity
1363860.81
Net Profit
36.386%
Sharpe Ratio
16.223
Sortino Ratio
30.296
Probabilistic Sharpe Ratio
96.354%
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
6.737
Beta
2.6
Annual Standard Deviation
0.436
Annual Variance
0.19
Information Ratio
18.566
Tracking Error
0.374
Treynor Ratio
2.718
Total Fees
$85.55
Estimated Strategy Capacity
$1600000000.00
Lowest Capacity Asset
TSLA UNU3P8Y3WFAD
Portfolio Turnover
5.50%
Drawdown Recovery
7
# 2025-11-22 07:40:22.963 | CodeBlock(path='./03 Writing Algorithms/34 Algorithm Framework/06 Execution/01 Key Concepts/99 Examples.html', div=1, pre=0, language=csharp, url='quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/execution/key-concepts#99-Examples')
# 2025-11-22 07:40:22.963 |  -> Backtest failed. Error: Failed queries: ['Insufficient buying power to complete orders', '']
# 2025-11-22 07:40:22.963 | 
# 2025-11-22 08:57:12.452 | CodeBlock(path='./03 Writing Algorithms/34 Algorithm Framework/06 Execution/01 Key Concepts/99 Examples.html', div=1, pre=1, language=python, url='quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/execution/key-concepts#99-Examples')
# 2025-11-22 08:57:12.453 |  -> Backtest failed. Error: Failed queries: ['Insufficient buying power to complete orders', '']

# region imports
from AlgorithmImports import *
# endregion

class FrameworkExecutionModelAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 10, 10)
        self.set_cash(1000000)
        #self.settings.free_portfolio_value_percentage = 0.5
        self.universe_settings.resolution = Resolution.DAILY
            
        # Add a universe of the most liquid stocks since their trend is more capital-supported.
        self.add_universe(self.universe.top(2))
        #self.add_universe_selection(ETFConstituentsUniverseSelectionModel("QQQ"))
        # Emit insights for selected stocks.
        self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days=7)))
        # Equal weighting on each insight to dissipate capital risk evenly.
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        # To place bracket orders besides basic orders as well.
        self.set_execution(StopLossExecutionModel(0.05))

class StopLossExecutionModel(ExecutionModel):
    def __init__(self, stop_loss: float = 0.05) -> None:
        self.targets_collection = PortfolioTargetCollection()
        # The stop loss percent of the bracket order.
        self.stop_loss = stop_loss
        # Track stop loss tickets by symbol
        self.stop_loss_tickets = {}

    def execute(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> None:
        self.targets_collection.add_range(targets)
        if not self.targets_collection.is_empty:
            for target in self.targets_collection.order_by_margin_impact(algorithm):
                security = algorithm.securities[target.symbol]
                # Calculate the remaining quantity to be ordered
                quantity = target.quantity - security.holdings.quantity                
                if quantity == 0: continue
                above_minimum_portfolio = BuyingPowerModelExtensions.above_minimum_order_margin_portfolio_percentage(
                    security.buying_power_model,
                    security,
                    quantity,
                    algorithm.portfolio,
                    algorithm.settings.minimum_order_margin_portfolio_percentage)
                # Place orders and the bracket orders.
                if above_minimum_portfolio:
                    algorithm.market_order(security, quantity, tag='Entry')
                elif not PortfolioTarget.minimum_order_margin_percentage_warning_sent:
                    # will trigger the warning if it has not already been sent
                    PortfolioTarget.minimum_order_margin_percentage_warning_sent = False

            self.targets_collection.clear_fulfilled(algorithm)

    def on_order_event(self, algorithm: QCAlgorithm, order_event: OrderEvent) -> None:
        if order_event.status == OrderStatus.FILLED:
            if order_event.ticket.order_type == OrderType.MARKET or order_event.ticket.order_type == OrderType.MARKET_ON_OPEN:
                stop_loss_price = order_event.fill_price * (1 - self.stop_loss if order_event.fill_quantity > 0 else 1 + self.stop_loss)
                ticket = algorithm.stop_market_order(order_event.symbol, -order_event.fill_quantity, stop_loss_price, tag='SL')