Skip to content
Home » Scripts » Mastering Stop Loss and Take Profit Orders

Mastering Stop Loss and Take Profit Orders

Stop Loss and Take Profit orders are key in trading. They manage risk and secure profits. Their design automates the trading process. This allows traders to focus on strategies, not constant market monitoring.

The Power of Stop Loss Orders

Stop Loss orders close trades at a preset level. This happens if prices shift against your position. These orders act as risk management tools. They shield traders from severe losses. With a Stop Loss order, you mark your maximum loss. This is for a specific trade. It helps minimize losses and stick to your trading plan. This is helpful even under volatile market conditions.

Securing Profits with Take Profit Orders

Take Profit orders command to wrap up a position. This is when the price hits a target level. These orders help secure your profits. They’re valuable for locking in gains. Market trends can reverse quickly after hitting your profit goal. A Take Profit order sets a clear exit point for your trade. It ensures you make the most of favorable market movements. You don’t have to worry about abrupt price reversals.

Incorporating Orders into Algorithmic Trading

Stop Loss and Take Profit orders are key in algorithmic trading. They manage risk and ensure consistent trading performance. Platforms like QuantConnect allow easy integration of these orders. They offer built-in functions to place such orders. Consider factors like asset’s volatility and your risk tolerance when setting levels.

The Code

The provided code launches a Simple Moving Average crossover strategy. It uses 14-day and 28-day SMAs. When the fast SMA outpaces the slow one, the algorithm takes a long position. It sets Stop Loss and Take Profit orders at 1% and 3% levels, respectively. When the fast SMA falls behind the slow one, the algorithm cancels open orders. It then liquidates the position.

Click on the code to copy it to your clipboard.
Click here for detailed instructions on how to use the scripts in QuantConnect.

Python
from AlgorithmImports import *

class StopLossTakeProfitExample(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 1, 1)
        self.SetEndDate(2018, 12, 31)
        self.SetCash(100000)
        
        self.symbol = self.AddEquity("AAPL").Symbol
        self.fast_sma = self.SMA(self.symbol, 10, Resolution.Daily)
        self.slow_sma = self.SMA(self.symbol, 50, Resolution.Daily)

    def OnData(self, data):
        if not self.fast_sma.IsReady or not self.slow_sma.IsReady:
            return

        # Moving average crossover strategy
        if self.fast_sma.Current.Value > self.slow_sma.Current.Value and not self.Portfolio[self.symbol].Invested:
            shares = 100
            
            # Enter a long position
            self.MarketOrder(self.symbol, shares)
            
            # Calculate Stop Loss and Take Profit prices
            stop_loss_price = self.Securities[self.symbol].Price * 0.97  # 3% risk
            take_profit_price = self.Securities[self.symbol].Price * 1.06  # 6% reward
            
            # Place Stop Loss and Take Profit orders
            self.StopMarketOrder(self.symbol, -shares, stop_loss_price, tag="Stop Loss")
            self.LimitOrder(self.symbol, -shares, take_profit_price, tag="Take Profit")
        elif self.fast_sma.Current.Value < self.slow_sma.Current.Value and self.Portfolio[self.symbol].Invested:
            # Cancel Stop Loss and Take Profit orders before exiting the position
            self.Transactions.CancelOpenOrders(self.symbol)
            
            # Exit the position
            self.Liquidate(self.symbol)
C#
using System;
using QuantConnect.Data;
using QuantConnect.Algorithm;
using QuantConnect.Indicators;

namespace QuantConnect
{
    public class StopLossTakeProfitExample : QCAlgorithm
    {
        private Symbol _symbol;
        private SimpleMovingAverage _fastSMA;
        private SimpleMovingAverage _slowSMA;

        public override void Initialize()
        {
            SetStartDate(2018, 1, 1);
            SetEndDate(2018, 12, 31);
            SetCash(100000);
            
            _symbol = AddEquity("AAPL").Symbol;
            _fastSMA = SMA(_symbol, 10, Resolution.Daily);
            _slowSMA = SMA(_symbol, 50, Resolution.Daily);
        }

        public override void OnData(Slice data)
        {
            if (!_fastSMA.IsReady || !_slowSMA.IsReady)
            {
                return;
            }
            
            // Moving average crossover strategy
            if (_fastSMA > _slowSMA && !Portfolio[_symbol].Invested)
            {
                int shares = 100;

                // Enter a long position
                MarketOrder(_symbol, shares);
                
                // Calculate Stop Loss and Take Profit prices
                decimal stopLossPrice = Securities[_symbol].Price * 0.97m; // 3% risk
                decimal takeProfitPrice = Securities[_symbol].Price * 1.06m; // 6% reward
                
                // Place Stop Loss and Take Profit orders
                StopMarketOrder(_symbol, -shares, stopLossPrice, tag: "Stop Loss");
                LimitOrder(_symbol, -shares, takeProfitPrice, tag: "Take Profit");
            }
            else if (_fastSMA < _slowSMA && Portfolio[_symbol].Invested)
            {
                // Cancel Stop Loss and Take Profit orders before exiting the position
                Transactions.CancelOpenOrders(_symbol);
                
                // Exit the position
                Liquidate(_symbol);
            }
        }
    }
}

 

Learn more about QuantConnect development services at QuantScripts.

Dynamic Stop Loss Approaches

Fixed-percentage stop losses are simple but suboptimal. They don’t account for varying volatility across different market conditions. An ATR-based (Average True Range) stop loss adapts to current volatility — wider stops in volatile markets, tighter in calm ones. A typical implementation uses 2x ATR from your entry price.

Trailing stops capture more profit in trending moves. But the trailing distance matters: too tight and you get stopped out by normal fluctuations; too wide and you give back too much profit. A good starting point is 1.5x ATR as your trailing distance, adjusted based on backtesting.

Position Sizing and Risk Per Trade

Stop losses are only half the equation — position sizing completes it. If you risk 1% of your account per trade and your stop is 2 ATR away, your position size is: (Account × 0.01) / (2 × ATR × Point Value). This formula keeps your dollar risk constant regardless of where your stop sits.

Never risk more than 2% of your account on a single trade. Even with a 60% win rate, a streak of losses can happen. At 1% risk per trade, you’d need 50 consecutive losers to lose half your account — virtually impossible with a properly backtested strategy. At 5% risk, just 14 consecutive losers halve your account.

Interested in implementing this strategy? Check out our custom Python trading solutions for professional algorithm development.

Ready to Automate Your Trading Strategy?

Whether you’re looking to build a new algorithm from scratch or optimize an existing strategy, our team of experienced quant developers can help. Book a free 30-minute consultation to discuss your project and get a custom quote.

Leave a Reply

Your email address will not be published. Required fields are marked *