avatarSofien Kaabar, CFA

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

9318

Abstract

<span class="hljs-keyword">data</span></pre></div><div id="18ff"><pre><span class="hljs-title">def</span> ma(<span class="hljs-class"><span class="hljs-keyword">data</span>, lookback, close, position): </span>

<span class="hljs-class"><span class="hljs-keyword">data</span> = add_column(<span class="hljs-title">data</span>, 1)</span>

for i <span class="hljs-keyword">in</span> range(len(<span class="hljs-class"><span class="hljs-keyword">data</span>)):</span>
       
        try:
            
            <span class="hljs-class"><span class="hljs-keyword">data</span>[i, position] = (<span class="hljs-title">data</span>[<span class="hljs-title">i</span> - <span class="hljs-title">lookback</span> + 1:<span class="hljs-title">i</span> + 1, <span class="hljs-title">close</span>].<span class="hljs-title">mean</span>())</span>
        
        except <span class="hljs-type">IndexError</span>:
            
            pass
        
<span class="hljs-class"><span class="hljs-keyword">data</span> = delete_row(<span class="hljs-title">data</span>, <span class="hljs-title">lookback</span>)</span>

return <span class="hljs-class"><span class="hljs-keyword">data</span></span></pre></div><div id="cf75"><pre>def smoothed_ma(data, <span class="hljs-keyword">alpha</span>, lookback, <span class="hljs-keyword">close</span>, position):

lookback = (2 * lookback) - 1

<span class="hljs-keyword">alpha</span> = <span class="hljs-keyword">alpha</span> / (lookback + 1.0)

beta  = 1 - <span class="hljs-keyword">alpha</span>

data = <span class="hljs-keyword">ma</span>(data, lookback, <span class="hljs-keyword">close</span>, position)</pre></div><div id="6e4a"><pre>    <span class="hljs-keyword">data</span>[lookback + <span class="hljs-number">1</span>, <span class="hljs-keyword">position</span>] = (<span class="hljs-keyword">data</span>[lookback + <span class="hljs-number">1</span>, close] * alpha) + (<span class="hljs-keyword">data</span>[lookback, <span class="hljs-keyword">position</span>] * beta)</pre></div><div id="94e9"><pre>    for i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(lookback + <span class="hljs-number">2</span>, len(<span class="hljs-keyword">data</span>)):
    
        try:
            
            <span class="hljs-keyword">data</span>[i, <span class="hljs-keyword">position</span>] = (<span class="hljs-keyword">data</span>[i, close] * alpha) + (<span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">position</span>] * beta)
    
        except IndexError:
            
            <span class="hljs-keyword">pass</span>
        
<span class="hljs-keyword">return</span> <span class="hljs-keyword">data</span></pre></div><p id="fd64">And now, to calculate the average true range, we can define the below function:</p><div id="989e"><pre>def atr(<span class="hljs-keyword">data</span>, lookback, high, low, close, <span class="hljs-keyword">position</span>):

<span class="hljs-keyword">data</span> = add_column(<span class="hljs-keyword">data</span>, <span class="hljs-number">1</span>)
  
for i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(len(<span class="hljs-keyword">data</span>)):
    
    try:
        
        <span class="hljs-keyword">data</span>[i, <span class="hljs-keyword">position</span>] = <span class="hljs-built_in">max</span>(<span class="hljs-keyword">data</span>[i, high] - <span class="hljs-keyword">data</span>[i, low], <span class="hljs-built_in">abs</span>(<span class="hljs-keyword">data</span>[i, high] - <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, close]), <span class="hljs-built_in">abs</span>(<span class="hljs-keyword">data</span>[i, low]  - <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, close]))
        
    except ValueError:
        
        <span class="hljs-keyword">pass</span>
    
<span class="hljs-keyword">data</span>[<span class="hljs-number">0</span>, <span class="hljs-keyword">position</span>] = <span class="hljs-number">0</span>   
  
<span class="hljs-keyword">data</span> = smoothed_ma(<span class="hljs-keyword">data</span>, <span class="hljs-number">2</span>, lookback, <span class="hljs-keyword">position</span>, <span class="hljs-keyword">position</span> + <span class="hljs-number">1</span>)</pre></div><div id="68be"><pre>    <span class="hljs-class"><span class="hljs-keyword">data</span> = delete_column(<span class="hljs-title">data</span>, <span class="hljs-title">position</span>, 1)</span>

<span class="hljs-class"><span class="hljs-keyword">data</span> = delete_row(<span class="hljs-title">data</span>, <span class="hljs-title">lookback</span>)</span>

return <span class="hljs-class"><span class="hljs-keyword">data</span></span></pre></div><figure id="03f3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*3p8IxBWLCUmQHyji.png"><figcaption><b>Hourly EURUSD values with the 13-period ATR.</b></figcaption></figure><p id="7f0c">The trailing stop indicator is an overlay moving line that gives us where exactly we must move our stop when following the move. It is based on volatility, thus uses the average true range. The default version uses 13-period ATR and a multiplier of 3. The multiplier can be thought of as an ingredient in determining the position of the new stop.</p><figure id="8c28"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*-aCF0bq-BFzTsHnU.png"><figcaption><b>EURUSD hourly values with the trailing stop indicator(13, 3).</b></figcaption></figure><div id="2d94"><pre>def atr_trailing_stop(<span class="hljs-keyword">data</span>, atr_column, multiplier, close, <span class="hljs-keyword">where</span>):

# adding columns
<span class="hljs-keyword">data</span> = add_column(<span class="hljs-keyword">data</span>, <span class="hljs-number">1</span>)

# atr trailing <span class="hljs-keyword">stop</span>    
for i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(len(<span class="hljs-keyword">data</span>)):
    
    try:
        
        # <span class="hljs-keyword">stop</span>
        <span class="hljs-keyword">stop</span> = multiplier * <span class="hljs-keyword">data</span>[i, atr_column]</pre></div><div id="29c8"><pre><span class="hljs-keyword">if</span> <span class="hljs-keyword">data</span>[i, close] &gt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>] and <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, close] &gt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>]:
            
            <span class="hljs-keyword">data</span>[i, <span class="hljs-keyword">where</span>] = <span class="hljs-built_in">max</span>(<span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>], <span class="hljs-keyword">data</span>[i, close] - <span class="hljs-keyword">stop</span>)</pre></div><div id="8771"><pre>elif <span class="hljs-keyword">data</span>[i, close] &lt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>] and <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, close] &lt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>]:
            
            <span class="hljs-keyword">data</span>[i, <span class="hljs-keyword">where</span>] = <span class="hljs-built_in">min</span>(<span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>], <span class="hljs-keyword">data</span>[i, close] + <span class="hljs-keyword">stop</span>)
            
        elif <span class="hljs-keyword">data</span>[i, close] &gt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>] and <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, close] &lt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>]:
            
            <span class="hljs-keyword">data</span>[i, <span class="hljs-keyword">where</span>] = <span class="hljs-keyword">data</span>[i, close] - <span class="hljs-keyword">stop</span>
            
        elif <span class="hljs-keyword">data</span>[i, close] &lt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>] and <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, close] &gt; <span class="hljs-keyword">data</span>[i - <span class="hljs-number">1</span>, <span class="hljs-keyword">where</span>]:
        
            <span class="hljs-keyword">data</span>[i, <span class="hljs-keyword">where</span>

Options

] = <span class="hljs-keyword">data</span>[i, close] + <span class="hljs-keyword">stop</span>

    except ValueError:
        
        <span class="hljs-keyword">pass</span>

<span class="hljs-keyword">return</span> <span class="hljs-keyword">data</span></pre></div><figure id="2e33"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*69AqLNnSPpVy4y8K.png"><figcaption><b>USDCAD hourly values with the trailing stop indicator(13, 3).</b></figcaption></figure><p id="bec0">The indicator can also be used to determine changes in the market regime which is very useful for trend-following. It however needs to be optimized in every market.</p><p id="5292" type="7">Make sure to focus on the concepts and not the code. You can find the codes of most of my strategies in my books. The most important thing is to comprehend the techniques and strategies.</p><p id="7da3">I have recently started following courses from Lumiwealth which offers an amazingly simple and generous knowledge in algorithmic trading, blockchain, and machine learning. I highly suggest you check them out and give them a try. <b>Coding and finance is the future of this field.</b></p><div id="e574" class="link-block">
      <a href="https://www.lumiwealth.com/algorithmic-trading-landing-page/?utm_source=influence&amp;utm_campaign=sofien">
        <div>
          <div>
            <h2>Lumiwealth: Learn Algorithmic Trading with Python</h2>
            <div><h3>Using Pandas Datareader Economic Data from FRED Getting Yahoo Finance Data Project 1 Introduction Q&amp;A Week 2: Financial…</h3></div>
            <div><p>www.lumiwealth.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*o0hjZd-Kz5Nbk_y-)"></div>
          </div>
        </div>
      </a>
    </div><h1 id="d9aa">Using the Trailing Stop Indicator</h1><p id="b9a2">Let us use the indicator to find trading signals although this is not really its main use.</p><p id="d6ea">The trading conditions are as follows:</p><ul><li><b>A long (Buy) signal is generated whenever the market surpasses the trailing stop indicator.</b></li><li><b>A short (Sell) signal is generated whenever the market surpasses the trailing stop indicator.</b></li></ul><figure id="9af2"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*bPAHn5lwSpN2J2jhljG2fA.png"><figcaption><b>Signal chart.</b></figcaption></figure><div id="49ff"><pre><span class="hljs-title">def</span> signal(<span class="hljs-class"><span class="hljs-keyword">data</span>, close, trailing_stop, buy_column, sell_column):</span>

<span class="hljs-class"><span class="hljs-keyword">data</span> = add_column(<span class="hljs-title">data</span>, 10)</span>

for i <span class="hljs-keyword">in</span> range(len(<span class="hljs-class"><span class="hljs-keyword">data</span>)):</span>
    
    try:
        
        <span class="hljs-keyword">if</span> <span class="hljs-class"><span class="hljs-keyword">data</span>[i, trailing_stop] &lt; <span class="hljs-keyword">data</span>[i, close] and <span class="hljs-keyword">data</span>[i - 1, trailing_stop] &gt; <span class="hljs-keyword">data</span>[i - 1, close]:</span>
            
            <span class="hljs-class"><span class="hljs-keyword">data</span>[i + 1, buy_column] = 1</span>
            
        elif <span class="hljs-class"><span class="hljs-keyword">data</span>[i, trailing_stop] &gt; <span class="hljs-keyword">data</span>[i, close] and <span class="hljs-keyword">data</span>[i - 1, trailing_stop] &lt; <span class="hljs-keyword">data</span>[i - 1, close]:</span>
            
            <span class="hljs-class"><span class="hljs-keyword">data</span>[i + 1, sell_column] = -1    </span>
            
    except <span class="hljs-type">IndexError</span>:</pre></div><div id="f244"><pre>               <span class="hljs-keyword">pass</span>           
    
<span class="hljs-keyword">return</span> <span class="hljs-keyword">data</span></pre></div><figure id="14d1"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*T5UbTzWsXTmsXTwoPeOx_A.png"><figcaption><b>Signal chart.</b></figcaption></figure><p id="cf4c">The indicator reminds us of another famous trend-following overlay called the SuperTrend where we are supposed to trade the flips between the market and the indicator.</p><h1 id="8ee3">The Right Way of Using the Trailing Stop Indicator</h1><p id="81ac">Now that we have stopped playing with the indicator, we have to remember that it must be used as a risk indicator in a trend-following strategy. Therefore:</p><ul><li><b>Whenever we have a buy signal generated from another technique, we can follow the stop with the trailing stop indicator.</b></li><li><b>Whenever we have a sell signal generated from another technique, we can follow the stop with the trailing stop indicator.</b></li></ul><p id="8f35">The indicator as its name suggests gives us a trailing stop that helps us in out trend-following strategies. Naturally, when we initiate a trend-following position, we are hoping to squeeze out the most of the underlying move and ride it until it ends. Unfortunately, it is extremely complicated to sell exactly at the end of the move. Therefore, we can just move up our stop as the position goes in our favor. Here is a simple illustration:</p><ul><li><b>A buy position is opened on the EURUSD at 1.1000 in expectation that the bullish move will continue. We place the stop at 1.0900 and no take-profit order as we want to remain long as much as possible.</b></li><li><b>Two days later, the EURUSD is trading at 1.1100. This is a 0.90% increase that we would like to keep at least some of it and to lock in some profits. Therefore, we move our stop to 1.1010. Now, we have a position that is up 100 pips and at worst case will be closed at a profit of 10 pips because we have moved our stop from 1.0900 to 1.1010 in order to lock it.</b></li><li><b>Five days later the EURUSD is trading at 1.1300. We have bought initially at 1.1000. Therefore, the market is up 2.72% since opening the position. We can move our stop to 1.1200 to lock in at least a 1.81% profit.</b></li><li><b>Finally, a day after reaching 1.1300, the EURUSD corrects to 1.1800. Our stop is triggered at 1.1200 with a profit of 2.72%.</b></li></ul><h1 id="e420">Summary</h1><p id="05a4">To summarize up, what I am trying to do is to simply contribute to the world of objective technical analysis which is promoting more transparent techniques and strategies that need to be back-tested before being implemented. This way, technical analysis will get rid of the bad reputation of being a subjective and scientifically unfounded.</p><p id="570c">Medium is a hub to many interesting reads. I read a lot of articles before I decided to start writing. Consider joining Medium using my referral link (at <b>no </b>additional cost to you).</p><div id="de8c" class="link-block">
      <a href="https://kaabar-sofien.medium.com/membership">
        <div>
          <div>
            <h2>Join Medium with my referral link — Sofien Kaabar</h2>
            <div><h3>As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…</h3></div>
            <div><p>kaabar-sofien.medium.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*XBqK-oHjNF_4ydU8)"></div>
          </div>
        </div>
      </a>
    </div><p id="5d41">I recommend you always follow the the below steps whenever you come across a trading technique or strategy:</p><ul><li>Have a critical mindset and get rid of any emotions.</li><li>Back-test it using real life simulation and conditions.</li><li>If you find potential, try optimizing it and running a forward test.</li><li>Always include transaction costs and any slippage simulation in your tests.</li><li>Always include risk management and position sizing in your tests.</li></ul><p id="beb3">Finally, even after making sure of the above, stay careful and monitor the strategy because market dynamics may shift and make the strategy unprofitable.</p><p id="ee2d">For the PDF alternative, the price of the book is <b>9.99 EUR</b>. Please include your email in the note before paying so that you receive it on the right address. Also, once you receive it, make sure to download it through google drive.</p><div id="7959" class="link-block">
      <a href="https://www.paypal.com/paypalme/sofienkaabar?country.x=FR&amp;locale.x=en_US">
        <div>
          <div>
            <h2>Pay Kaabar using PayPal.Me</h2>
            <div><h3>If you accept cookies, we’ll use them to improve and customize your experience and enable our partners to show you…</h3></div>
            <div><p>www.paypal.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*jGRNX0DxL9tTvUV7)"></div>
          </div>
        </div>
      </a>
    </div></article></body>

Using the Risk Management to Generate Trading Signals

Coding the Trailing Stop Indicator

Risk management is supposed to protect your capital not generate trading signals. This being said, there are certain risk management indicators that can actually function as signal generators. This article discusses the concept of a trailing stop from a trading perspective.

I have released a new book after the success of my previous one “Trend Following Strategies in Python”. It features advanced contrarian indicators and strategies with a GitHub page dedicated to the continuously updated code. If you feel that this interests you, feel free to visit the below Amazon link (which contains a sample), or if you prefer to buy the PDF version, you could check the link at the end of the article.

Creating the Trailing Stop Indicator

The trailing stop indicator we will be creating is based on the average true range. To understand the average true range, we must first understand the concept of volatility. It is a key concept in finance, whoever masters it holds a tremendous edge in the markets.

Unfortunately, we cannot always measure and predict it with accuracy. Even though the concept is more important in options trading, we need it pretty much everywhere else. Traders cannot trade without volatility nor manage their positions and risk. Before we discuss the different types of volatility, why not look at a graph that sums up the concept? Check out the below image to get you started.

You can code the above in Python yourself using the following snippet:

# Importing the necessary libraries
import numpy as np
import matplotlib.pyplot as plt
# Creating high volatility noise
hv_noise = np.random.normal(0, 1, 250)
# Creating low volatility noise
lv_noise = np.random.normal(0, 0.1, 250)
# Plotting
plt.plot(hv_noise, color = 'red', linewidth = 1.5, label = 'High Volatility')
plt.plot(lv_noise, color = 'green', linewidth = 1.5, label = 'Low Volatility')
plt.axhline(y = 0, color = 'black', linewidth = 1)
plt.grid()
plt.legend(

The different types of volatility around us can be summed up in the following:

  • Historical volatility: It is the realized volatility over a certain period of time. Even though it is backward looking, historical volatility is used more often than not as an expectation of future volatility. One example of a historical measure is the standard deviation, which we will see later. Another example is the Average True Range, the protagonist of this article.
  • Implied volatility: In its simplest definition, implied volatility is the measure that when inputted into the Black-Scholes equation, gives out the option’s market price. It is considered as the expected future actual volatility by market participants. It has one time scale, the option’s expiration.
  • Forward volatility: It is the volatility over a specific period in the future.
  • Actual volatility: It is the amount of volatility at any given time. Also known as local volatility, this measure is hard to calculate and has no time scale.

Volatility is the average distance away from the mean that we expect to find when we analyze the different components of the time series.

In technical analysis, an indicator called the Average True Range -ATR- can be used as a gauge for historical volatility. Although it is considered as a lagging indicator, it gives some insights as to where volatility is now and where has it been last period (day, week, month, etc.).

But first, we should understand how the True Range is calculated (the ATR is just the average of that calculation). Consider an OHLC data composed of an timely arranged open, high, low, and close prices. For each time period (bar), the true range is simply the greatest of the three price differences:

  • High — Low
  • High — Previous close
  • Previous close — Low

Once we have got the maximum out of the above three, we simply take a smoothed average of n periods of the true ranges to get the average true range. Generally, since in periods of panic and price depreciation we see volatility go up, the ATR will most likely trend higher during these periods, similarly in times of steady uptrends or downtrends, the ATR will tend to go lower.

One should always remember that this indicator is lagging and therefore has to be used with extreme caution.

Since it has been created by Welles Wilder Jr., also the creator of the relative strength index, it uses Wilder’s own type of moving average, the smoothed kind. To simplify things, the smoothed moving average can be found through a simple transformation of the exponential moving average.

The above formula means that a 100 smoothed moving average is the same thing as (100 x 2) -1 = 199 exponential moving average. While we are on that, we can code the exponential moving average using this function:

def add_column(data, times):
    
    for i in range(1, times + 1):
    
        new = np.zeros((len(data), 1), dtype = float)
        
        data = np.append(data, new, axis = 1)
    return data
def delete_column(data, index, times):
    
    for i in range(1, times + 1):
    
        data = np.delete(data, index, axis = 1)
    return data
   
def delete_row(data, number):
    
    data = data[number:, ]
    
    return data
def ma(data, lookback, close, position): 
    
    data = add_column(data, 1)
    
    for i in range(len(data)):
           
            try:
                
                data[i, position] = (data[i - lookback + 1:i + 1, close].mean())
            
            except IndexError:
                
                pass
            
    data = delete_row(data, lookback)
    
    return data
def smoothed_ma(data, alpha, lookback, close, position):
    
    lookback = (2 * lookback) - 1
    
    alpha = alpha / (lookback + 1.0)
    
    beta  = 1 - alpha
    
    data = ma(data, lookback, close, position)
    data[lookback + 1, position] = (data[lookback + 1, close] * alpha) + (data[lookback, position] * beta)
    for i in range(lookback + 2, len(data)):
        
            try:
                
                data[i, position] = (data[i, close] * alpha) + (data[i - 1, position] * beta)
        
            except IndexError:
                
                pass
            
    return data

And now, to calculate the average true range, we can define the below function:

def atr(data, lookback, high, low, close, position):
    
    data = add_column(data, 1)
      
    for i in range(len(data)):
        
        try:
            
            data[i, position] = max(data[i, high] - data[i, low], abs(data[i, high] - data[i - 1, close]), abs(data[i, low]  - data[i - 1, close]))
            
        except ValueError:
            
            pass
        
    data[0, position] = 0   
      
    data = smoothed_ma(data, 2, lookback, position, position + 1)
    data = delete_column(data, position, 1)
    
    data = delete_row(data, lookback)
    
    return data
Hourly EURUSD values with the 13-period ATR.

The trailing stop indicator is an overlay moving line that gives us where exactly we must move our stop when following the move. It is based on volatility, thus uses the average true range. The default version uses 13-period ATR and a multiplier of 3. The multiplier can be thought of as an ingredient in determining the position of the new stop.

EURUSD hourly values with the trailing stop indicator(13, 3).
def atr_trailing_stop(data, atr_column, multiplier, close, where):
    
    # adding columns
    data = add_column(data, 1)
    
    # atr trailing stop    
    for i in range(len(data)):
        
        try:
            
            # stop
            stop = multiplier * data[i, atr_column]
if data[i, close] > data[i - 1, where] and data[i - 1, close] > data[i - 1, where]:
                
                data[i, where] = max(data[i - 1, where], data[i, close] - stop)
elif data[i, close] < data[i - 1, where] and data[i - 1, close] < data[i - 1, where]:
                
                data[i, where] = min(data[i - 1, where], data[i, close] + stop)
                
            elif data[i, close] > data[i - 1, where] and data[i - 1, close] < data[i - 1, where]:
                
                data[i, where] = data[i, close] - stop
                
            elif data[i, close] < data[i - 1, where] and data[i - 1, close] > data[i - 1, where]:
            
                data[i, where] = data[i, close] + stop   
                
        except ValueError:
            
            pass
    
    return data
USDCAD hourly values with the trailing stop indicator(13, 3).

The indicator can also be used to determine changes in the market regime which is very useful for trend-following. It however needs to be optimized in every market.

Make sure to focus on the concepts and not the code. You can find the codes of most of my strategies in my books. The most important thing is to comprehend the techniques and strategies.

I have recently started following courses from Lumiwealth which offers an amazingly simple and generous knowledge in algorithmic trading, blockchain, and machine learning. I highly suggest you check them out and give them a try. Coding and finance is the future of this field.

Using the Trailing Stop Indicator

Let us use the indicator to find trading signals although this is not really its main use.

The trading conditions are as follows:

  • A long (Buy) signal is generated whenever the market surpasses the trailing stop indicator.
  • A short (Sell) signal is generated whenever the market surpasses the trailing stop indicator.
Signal chart.
def signal(data, close, trailing_stop, buy_column, sell_column):
    
    data = add_column(data, 10)
    
    for i in range(len(data)):
        
        try:
            
            if data[i, trailing_stop] < data[i, close] and data[i - 1, trailing_stop] > data[i - 1, close]:
                
                data[i + 1, buy_column] = 1
                
            elif data[i, trailing_stop] > data[i, close] and data[i - 1, trailing_stop] < data[i - 1, close]:
                
                data[i + 1, sell_column] = -1    
                
        except IndexError:
               pass           
        
    return data
Signal chart.

The indicator reminds us of another famous trend-following overlay called the SuperTrend where we are supposed to trade the flips between the market and the indicator.

The Right Way of Using the Trailing Stop Indicator

Now that we have stopped playing with the indicator, we have to remember that it must be used as a risk indicator in a trend-following strategy. Therefore:

  • Whenever we have a buy signal generated from another technique, we can follow the stop with the trailing stop indicator.
  • Whenever we have a sell signal generated from another technique, we can follow the stop with the trailing stop indicator.

The indicator as its name suggests gives us a trailing stop that helps us in out trend-following strategies. Naturally, when we initiate a trend-following position, we are hoping to squeeze out the most of the underlying move and ride it until it ends. Unfortunately, it is extremely complicated to sell exactly at the end of the move. Therefore, we can just move up our stop as the position goes in our favor. Here is a simple illustration:

  • A buy position is opened on the EURUSD at 1.1000 in expectation that the bullish move will continue. We place the stop at 1.0900 and no take-profit order as we want to remain long as much as possible.
  • Two days later, the EURUSD is trading at 1.1100. This is a 0.90% increase that we would like to keep at least some of it and to lock in some profits. Therefore, we move our stop to 1.1010. Now, we have a position that is up 100 pips and at worst case will be closed at a profit of 10 pips because we have moved our stop from 1.0900 to 1.1010 in order to lock it.
  • Five days later the EURUSD is trading at 1.1300. We have bought initially at 1.1000. Therefore, the market is up 2.72% since opening the position. We can move our stop to 1.1200 to lock in at least a 1.81% profit.
  • Finally, a day after reaching 1.1300, the EURUSD corrects to 1.1800. Our stop is triggered at 1.1200 with a profit of 2.72%.

Summary

To summarize up, what I am trying to do is to simply contribute to the world of objective technical analysis which is promoting more transparent techniques and strategies that need to be back-tested before being implemented. This way, technical analysis will get rid of the bad reputation of being a subjective and scientifically unfounded.

Medium is a hub to many interesting reads. I read a lot of articles before I decided to start writing. Consider joining Medium using my referral link (at no additional cost to you).

I recommend you always follow the the below steps whenever you come across a trading technique or strategy:

  • Have a critical mindset and get rid of any emotions.
  • Back-test it using real life simulation and conditions.
  • If you find potential, try optimizing it and running a forward test.
  • Always include transaction costs and any slippage simulation in your tests.
  • Always include risk management and position sizing in your tests.

Finally, even after making sure of the above, stay careful and monitor the strategy because market dynamics may shift and make the strategy unprofitable.

For the PDF alternative, the price of the book is 9.99 EUR. Please include your email in the note before paying so that you receive it on the right address. Also, once you receive it, make sure to download it through google drive.

Data Science
Investing
Finance
Cryptocurrency
Trading
Recommended from ReadMedium