How to Build a Trading System on Energy Stocks with the Donchian Channel (Open-Source Code)

Need More Help? Book Your FREE Strategy Session With Our Team Today!

We'll help you map out a plan to fix the problems in your trading and get you to the next level. Answer a few questions on our application and then choose a time that works for you.

BOOK YOUR FREE STRATEGY SESSION NOW >>

When we talk about trading in the energy market, one immediately thinks of futures on oil, gasoline, gas, etc.

In reality, if we want to trade this market, we can also think of "less popular" instruments, such as stocks of companies that operate in this sector.

For example, in this video, we offer a promising trading system for the stocks of the Italian multinational oil and gas company called Eni, which is listed on Euronext Milan.

According to our test results, which we also show in the video, the system seems to be able to beat a Buy & Hold strategy and achieve a very good average trade of more than 1%.

By watching the video, you’ll discover:

  • The system's logic, with all the entry and exit rules (Donchian Channel Breakout)

  • The code, explained step-by-step (it's open source, so you can freely reuse and adapt it!)

  • A trick to improve the performance of the system (Volatility Filter)

Enjoy! 😎

Transcription

Introduction

Hey everyone and welcome to this brand new video! One of the coaches at Unger Academy here, and today, I’d like to show you how to create a trading system on an Italian stock. In particular, this stock is "Eni S.p.A.", which is a leading energy company and multinational in the Italian market. This stock is traded on the Italian stock exchange, now called Euronext Milan.

So what we're going to be doing today is we're going to try to understand the nature of this stock and see together how to exploit the potential that it can offer us.

The Idea

So let's start right away with the main idea behind this strategy. The idea is to build a Donchian Channel. We've already talked about this channel before in one of our videos. Now this Donchian Channel is nothing more than a price channel constructed using the highest high and lowest low of the last… in this case, the last 18 periods, so the last 18 candlesticks. But why specifically 18, you say? Well, because since we are using an hourly time frame, for each session we'll have 9 bars, which means that to build a Donchian Channel with a time horizon of about two sessions, we'll need to use 18 bars. Of course, we could also use 20, and little would change.

Anyway, we'll build this Donchian Channel and try to enter at the breakout of this level, so we'll buy at the crossing of this level. Let me explain further. Let's assume the case that the market closes at this time. At this price, this level marked by the Donchian Channel, here… We'd buy (so we'd go long) at the price achieved by this Donchian Channel. So, we'd go long at precisely this price.

So in this way, we try to follow a running trend that has already formed and that was able to reach the high of the last two sessions. So to enter at the breakout of this level means exactly to believe in this ongoing trend.

This system can only take long positions because taking short positions in stock markets is generally quite complicated. We'll use a Stop loss and a Take profit set as a percentage. So, we'll enter with a fixed amount of capital, so for this backtest, we'll use €100,000 as a countervalue for each open position. And the Stop loss and Take profit will be around plus/minus 5%.

In addition to the Stop Loss and Take Profit in percentage, we'll close the position if the opposite setup forms. In other words, the setup that would be used to go short (if this system went short, which it does not do). Let's assume, for example, that we're long in this position. We entered at the breakout of this support, the Donchian Channel. Then the price fell, so a false breakout occurred. Here at this Donchian Channel level, we'll close the position when this level is crossed because we consider it appropriate, let's say, to follow the opposite trend. In this case, as said, we won't go short, but we’ll just close the long position.

But what happens if we don't hit the Take profit, we don't hit the Stop loss, and we don't even close the position with the reverse setup? In that case, a time exit will intervene and allow us to exit from the market after a few weeks, but I mean, this rarely happens.

So now, let's go and have a look at the results of the system. I've already inserted a time filter that allows me to trade only within a specific time window within the session. The purpose of this filter is just to avoid entering right after the market has opened or right before it closes.

But let's take a look at the inputs of the system. Here are the Stop loss and Take profit values, at 5% and 7% respectively. The Donchian Channel, we said, has been set at 18 periods. As we have already said, the system trades only if there's a breakout between 11 a.m. and 4 p.m. exchange time, so Central European Time. As a reminder, this market remains open from 9 am until 5:30 pm CET. And it will exit with a time exit after about 90 bars.

First Results

Let's close and take a look at the results. That’s what we get to see. We see that the equity curve has a rising shape so the system earns. Let's take a look at the Buy & Hold of this stock, "Eni", and as you can see it's been very fluctuating. This system, which I remind you works only on the long side, because the short side has no trade, this system seems to be definitely able to beat the Buy & Hold.

But let's look at the number of trades. I mean, we make about 300 trades, an average trade of €360, which corresponds to a 0.3%, because I remind you that we enter with a countervalue of €100,000.

The Total trades. If we limit ourselves to a Stop loss of about 5%, we should end up with about €5,000. But… this isn't the case. You see, there’s even a loss of more than €6,000. This is because the market has probably opened in gap. A gap that can be positive, as in this case, since only one trade has taken place, or negative, as in this other case.

The results are good in the sense that this breakout system based on the Donchian Channel and working across two sessions seems pretty good, so it is an idea that seems to be worthwhile.

Volatility Filter

But how can we make it even more profitable? I'll add a condition – don't worry, I'll show you the code in a minute! – based on a volatility contraction. Basically, what we'll do is to open positions when a specific volatility compression condition occurs, which says that the body must be below the range by at least 75%.

What does this mean? Let's assume 100 is our bar range, which is this here, the range that goes from the high to the low. So, let's assume it’s 100. The body, which is the part that corresponds to the difference between the opening and the closing… The body taken as an absolute value – so it doesn’t matter whether it’s a green or red candlestick – the body must be less than 75% of the range. So, this body must be less than 75, of course if the range is 100.

I’ll add one more condition, which is that this range must not be too tiny because in that case we would have a Doji – a Doji is simply a bar with a very tiny body in relation to its range. So in our case, the body part should be between 25% and 75% of the range.

Final Results

Alright, back to us. Let's apply this filter. Let's go and see how the results change. Here it is, this is the new system. If we apply these filters, we’ll have fewer trades. We had 300 before if you remember. Now we only have 200, but the average trade has increased significantly and it’s 1.1%, so even more than 1%.

The equity curve is undoubtedly excellent, especially if compared to a Buy & Hold. So, this type of approach, which is really very simple, could pay off in the long run when applied to this underlying asset.

The Code

And finally, let’s look at the code of the system, which is also very simple. I'll describe it very briefly. So here we define all the inputs that we’ve mentioned so far.

The definition of the upper and lower channels for our Donchian Channel. How they are constructed, with the highest high of "MyLength", which we said is 18 periods. The same happens for the lower channel.

The definition of how many stocks will be traded is 100,000 divided by the closing price.

The identification of the body of the range of the day before. "Value1" is equal to the highest high minus the lowest low, and "Value2" is equal to the absolute value of the difference between Open and Close.

So if we are within the time window in which trading is allowed, so from 11 a.m. to 4 p.m. CET, so exchange time as we've seen before. Here it is, between 11 a.m. and 4 p.m… Here 1700 was previously entered so let's correct it.

Ok, if we are in a situation where the body is less than 75% but more than 25% of the range, we'll buy with a Stop Order at the Upper channel level, at the upper level of the Donchian Channel. Conversely, we'll sell at the Lower channel if the opposite condition occurs. So, we buy if we are within that time frame and in a situation where there was this kind of volatility compression the day before.

Here we have the Stop loss and Take profit.

And the last line is about the time exit from the market.

Final Thoughts

That's it. I mean, there is no secret! You can test it yourself.

I subscribed to the data at Interactive Brokers, so the data feed I used is the one provided by Interactive Brokers.

You can add commission costs, of course, depending on your broker. With Directa, for example, there's a fixed commission of €5, and it doesn't matter what the volume is unless the countervalue is less than half a million. With other brokers like Interactive Brokers, it can be proportional, but still a few euros per position, both entry and exit, of course.

I can assure you that the slippage is very low because it’s a very liquid stock so you don't have to worry about slippage. And I guarantee you that a generous average trade of over 1% is more than enough to cover all the trading costs.

So I invite you to go beyond this example and try to develop other breakout strategies for this stock to find more excellent insights.

Finally, let's have a look at the annual gains of the strategy. As you can see, we have an excellent 2022 but a bad 2017. The tests start from 2012, the first year for which I have the data.

And as you can see, despite being very simple, this system's performance seems pretty consistent.

Well, I hope this video was helpful. If you need help investing in the markets with a systematic approach, as we do here at Unger Academy, I recommend that you go and click on the link below, which will take you to a page where you can find handy resources. From there, you can sign up for a free presentation by Andrea Unger, or get our best-selling book, "The Unger Method", paying only for shipping, or book a call with a member of our team to get some free strategic advice.

Finally, if you haven't already done so, please remember to subscribe to our channel, you'll be promptly notified if new videos and content are released.

Also, write in the comments if you have any other insights that you would like us to explore for you.

Thank you so much for following me this far, and I will see you soon in a new video! Bye-bye for now!

Need More Help? Book Your FREE Strategy Session With Our Team Today!

We'll help you map out a plan to fix the problems in your trading and get you to the next level. Answer a few questions on our application and then choose a time that works for you.

BOOK YOUR FREE STRATEGY SESSION NOW >>
Andrea Unger

Andrea Unger

Andrea Unger here and I help retail traders to improve their trading, scientifically. I went from being a cog in the machine in a multinational company to the only 4-Time World Trading Champion in a little more than 10 years.

I've been a professional trader since 2001 and in 2008 I became World Champion using just 4 automated trading systems. 

In 2015 I founded Unger Academy, where I teach my method of developing effecting trading strategies: a scientific, replicable and universal method, based on numbers and statistics, not hunches, which led me and my students to become Champions again and again.

Now I'm here to help you learn how to develop your own strategies, autonomously. This channel will help you improve your trading, know the markets better, and apply the scientific method to financial markets.

Becoming a trader is harder than you think, but if you have passion, will, and sufficient capital, you'll learn how to code and develop effective strategies, manage risk, and diversify a portfolio of trading systems to greatly improve your chances of becoming successful.