Backtrader Trend line Indicator

This is a code snippet for trend line indicator. As the name suggests, it calculates the price value at different points of a trend line and generates buy and sell signals accordingly. One thing I like to able to do is take a semi-automated approach to algorithmic trading. I might spot a nice trend line on Tradingview but want to execute trades in a forward testing environment using Backtrader when price reaches the trend line. As such, I consider this a short term indicator that can be used for as long as the trend line holds up.

The trend line indicator written in this post is intended to be used in the backtrader framework but the calculations used to calculate the trend line should be portable to other frameworks.


If like me, you are not a maths wizard, a bit of background reading might be required so that you can understand the equations contained in the code. In the world of maths we need to study “linear equations” to develop this indicator.

I found this tutorial to be well written and quite helpful:

The main takeaway is that to be able to calculate the price of the trend line at any point in time, we need to calculate how fast the slope changes between two points in time. These points in time are the two prices you input into the indicator. How you identify those two points is up to you. As mentioned above I personally identify and draw a trend line on Tradingview and then make a note of the start and end points to use with this indicator.

The equation we need to arrive at is:



y = price

m = slope

x = date / time

b = y-intercept

Now one thing I found difficult to wrap my brain around is that most tutorials assume you can visually see the y-intercept. It is the value of y when it crosses the y-axis at 0. Like this:

Line crossing the y axis

As we know price charts look a little different and we are unlikely to go back in time (Where we would cross the y-axis). We cannot see what the y-intercepts is. So we need to calculate it! To do this you need to flip the equation around a bit.



b = y – m*x

When solving this, you can use the y and x values you already have from the start and end points of your trend line. You will see how I have implemented it in the code below.

Indicator Rules

The trend line indicator will generate a buy signal if price crosses down into the trend line from above. It will generate a sell signal if price crosses up into it. I reasoned that because the trend line will either act as support or resistance, it will always be below price when you are looking for buy signals and above price when you are looking for sell signals.

The Trend Line Indicator Code


The doc string (long comment under the class declaration), hopefully gives a good enough explanation of the input parameters and format they are required in.

There are two lines being generated for the indicator. One is the trend line and the other is the signal line. Note that the trend line is not plotted. This is because in backtrader we cannot plot one line on the master plot and another line on the subplot. We need to choose one or the other. We could technically plot both on the subplot but that would look a little strange since the trend line can be any number (ie. the value depends on the price of the instrument) but the signal line will only oscillate between -1 and 1. A workaround for this is provided in the results section.

Another thing to note is that the dates must be converted to a timestamp so that calculations can made against a number and not a date object.

Finally, you might be wondering why I am building the trendline and calling get_y() in the next() method instead of __init__()? This is because backtrader will throw an IndexError if I try and obtain the date information during __init__(). If anyone knows how to workaround this, let me know! I probably missed something in the docs.

The key methods

If you want to implement this code in another frame work the three key methods that are needed are below:

As above, just make sure you pass time stamps for the x parameters and call the functions in the following order:

  1. get_slope()
  2. get_y_intercept(), because it needs the value of m from get_slope()
  3. get_y, to get the final price from any given timestamp.


As mentioned above, if you run this code as is, the indicator will not plot a trend line on the resulting graph automatically. Since the indicator is designed to produce buy and sell signals, I prioritize the plotting of the signal line.

As a workaround and in order to build some visual confidence that the indicator is working correctly, you can initialize a second indicator in the strategy that plots a simple moving average of the trend line with a period of 1.

Note that in the code above, you should place the line inside the __init__() method of the strategy. Assume I have initialized the indicator with the name ind1 already (self.ind1.lines.trend).

This will produce a final chart which looks like this:

Trendline indicator on a chart

As you can see, we have a trend line running through the chart and signals being generated according to our rules in the code, shown in the bottom subplot.

Find This Post Useful?

If this post saved you time and effort, please consider support the site! There are many ways to support us and some won’t even cost you a penny.