Moving average crossover bot - Step by Step tutorial
- Intro
- Create the strategy - Tradingview
- Create the strategy without writing code - Tradingview
- Create the trading bot without writing code - Metatrader 4
- Conclusion
Intro
You will create your first trend-following strategy . You will create a simple moving average crossover strategy and learn how to solve errors in your script. Next, you will automate this strategy. Every strategy script has a basic structure. It specifies conditions that need to be met to enter a position, and it specifies what criteria need to be met to exit a position. In this strategy, you will enter a position when the fast-moving average crosses over the slow-moving average. You will exit the position when the fast-moving average crosses below the slow-moving average. As shown in the picture below.
1. Create the strategy - Tradingview
Head to TradingView.com
Select open pine script editor.
Select new and select blank strategy script. Afterwards, a script will appear.
First, we delete everything below line 2. Now we will create a variable that will be our fast moving average. Tradingview has a lot of built-in functions that will do certain calculations for you. The calculation of a moving average is incredibly simple. Calculation moving average by hand. Sma is the function in Tradingview that calculates a moving average for you. Now you will only need to specify the type of price information, and the length. You can choose the open, high, low, or close as the type of price information. And the length of the moving average is a metric you can specify yourself. We will calculate the fast moving average based on the open price and 50 candles. We will calculate the slow moving average based on the open price and 200 candles.
Now that we have both moving averages we will specify when to buy and when to sell. We only want to take a long trade or short trade if a specific condition is met. Thus in Tradingview script, we begin with an If statement. Afterward, we specify the long condition. We only want to take a long trade when the fast moving average is greater than the slow moving average. The first variable we specify in this function is the variable that is greater than the second variable. Thus (fast_moving_average > slow_moving_average). Now we will need to tell the software to take a long trade when this condition is met. Tradingview has a function that does this, strategy.entry. Between the brackets we specify the trade ID, then we specify which side of the market we want to trade. We want to take a long trade thus we state trade.long, and lastly, we put in a comment which will show on the chart. This makes it easier to see what happened. We will call this long. It is important to indent the strategy.entry line. The indentation makes sure that we take a long trade only when the condition in the IF statement is true.
For the short trade, we do almost the same. Only now we want to take a short trade when the fast moving averages is smaller than the slow moving average. Furthermore, we want to take a short trade thus we state trade.short.
Now we press the “Add to Chart” button on the right side.
Congratulations! You have created your first strategy! On the chart, the blue arrows that point upward indicate a long trade, and the red arrows that point downward indicate a short trade.
I created a Pinescript generator. So you won't need to write Pinescript code anymore. I'll show you how much simpler it is. As a result, you will save time, which you can use to improve your trading strategy.
2. Create the strategy without writing code - Tradingview
We select the moving average indicator. We change the price to OPEN, we then select the period of 50. Next we select the condition. Greater than. Next we select the second indicator. Also a moving average, with the OPEN price and an period of 200. Displayed below.
Afterwards we specify the conditions to close the order. We select the moving average indicator. We change the price to OPEN, we then select the period of 50. Next we select the condition. Smaller than. Next we select the second indicator. Also a moving average, with the OPEN price and an period of 200. Displayed below.
Select generate strategy and we generate the pine script code.
Now simply copy and past the code in TradingView Pine Editor. And select save to the chart. Almost identical code, but much more easy. And I’ve already included time features. Lines 18 to 25 allow you to select a specific period in the strategy settings. For instance, show the strategy's performance from 1-1-2019 to 1-1-2020. Or you can change default values in the code
In the picture below, you can see that you can now specify by month, day and year when to show the strategy’s performance for a specific period.
When you switch to the "Strategy Tester" panel, you can see the performance of this strategy. When you press the setting icon, the settings of this strategy appear. Now we have used the default settings. We have $100,000 in initial capital and have traded one contract. In this instance, one contract is one bitcoin. When we would have traded with 1 bitcoin, we would have made 2077 dollars, which is a net profit of 2.08% for our initial capital of 100 000 dollars. It is easy to see that this is not ideal for testing the performance of your strategy. You might want to trade 100% of your capital at all times, allowing for compounding interest. Or you want to trade for a specific amount of dollars. You can specify this in the settings tab or the pine editor. I like to use the pine editor as these changes are permanent until you change the code in the pine editor.
I often use the same order size as the initial capital, in this example $100,000, because this is the same for all securities. This allows me to compare the performance of a strategy between securities, and determine which security I should trade this strategy on. In this scenario, when we would have traded with an order size of $100,000, we would have made a return of roughly 20%.
3. Create the trading bot without writing code - Metatrader 4
Now that you have created your first trend-following strategy, it is time to automate this strategy. We will automate this moving average crossover strategy with Metatrader. We will use OANDA as our broker. Unfamiliar with trading bots? Read our blog about trading bots so called expert advisors in metatraders MQL programming language. And discover some tips to help you increase your chances of succes with tr ading bots.
First, we need to transform our trading rules into Metatrader code. We will use the "Trading Bot Generator" to easily create the trading robot. Or you can program it yourself within Metatrader editor. If you have not subscribed yet, you can create your account and purchase a subscription register. Or try our free trading bot generator
Let’s revisit the trading rules. You open a buy trade when the fast-moving average of 50 candles calculated on the open price is greater than the slow-moving average of 200 candles calculated on the open price.
Open order: Indicator 1
Open order: Condition and second indicator
You will exit the position when the fast-moving average of 50 candles calculated on the open price is smaller than the slow-moving average of 200 candles calculated on the open price.
Close order: Indicator 1
Close order: Condition and indicator 2
Now we can generate the trading bot. Press the “Generate Buy Trading Bot” button. Next, we generate the MQL code.
Visit Metatraders website to download Metatrader 4:Or
Download Metatrader 4 for windows directlyNext MetaEditor will appear. Within MetaEditor you can write and edit code to create trading bots. We however can use the generated code and start using our bot directly. Press the green start button in the middle and top of your screen or press f5. Metatrader will open.
Next, within Metatrader, add the security you want. We will select “File” and "New Chart" select EURUSD.
If you did select EURUSD, and the chart will show up. We will now deploy the trading bot and make your first automated trade. Press the buttons "CTRL" + “n” to open the navigator panel. It will open on the left side of the chart. Press the buttons “CTRL” + “t” to open the trade panel. It will open at the bottom of the chart. If you do this well, your screen will look something like this:
Now open the Expert Advisor section and select your new trading bot. Drag and drop the expert advisor on the chart. A small window will pop up. Within this window, you can configure your trading bot. Check “Allow live trading”.
When you head over to the Inputs tab, you can change some settings of the trading bot directly. Do you, for instance, want to trade with a stoploss, take-profit, or trailing stop? Then you can select this here. For this strategy we won’t use any so we keep the values at 0.
Be sure to enable automated trading. Press the “AutoTrading” button in the middle of the screen, or press “CTRL” + “e”. If you did this correctly, the “AutoTrading” button will turn green and the smiley on the right side of the screen will turn happy.
We want to plot our indicators. We can easily do this within Metrader. Select “Inset” and then “Indicators” and then “Moving Average”
Select the correct values, and the color you like. The moving average will now be shown on the chart. This allows you to visually track your strategy.
4. Conclusion
Today, you've created and automated a moving average crossover strategy. Now, you can test your robot. I challenge you to try it out. Want to know how to test if a strategy is successful? Become a subscriber and get a free copy of Automated Trading Masterclass. Do you want to generate more robots or TradingView scripts right away? Register now!
Do you want to learn more trading strategies? Read our blog 25 Must-Know Trading Strategies That You Can Implement Today (2024)
Ready to start your automated trading journey?
- Register to the Trading Bot Generator
- Purchase a subscription to the Trading Bot Generator
- Sign in
- Watch the tutorial or follow the step by step guide
- Enjoy your trading robot or unlimited Tradingview indicators/strategies!
Testimonials
4.1
out of
5
97 reviews
Great code generator!
The trading bot generator is a total game-changer! It simplifies the process of creating custom trading bots, saving me hours of coding. The wide range of indicators and customization options allows me to fine-tune my strategies easily. The web-based platform is user-friendly and accessible from anywhere. It has significantly improved my trading results. Highly recommended!
Jane
Unlimited Tradingview indicators without a tradingview subscription
I finally have a piece of my life back. I don't have to spend hours in front of a screen, but can just enjoy time with my friends. Moreover I am a frequent Tradingview user and enjoy multiple indicators without a Tradingview subscription. I've saved $45 a month
Jack
Creating a trading bot has never been easier, but documentation is sparse
The trading bot generator has made trading bots accessible to all skill levels. I can quickly assess the profitability of different strategies. If a strategy falls short, I can easily generate a new bot. The emotionless trading eliminates impulsive decisions. Comprehensive documentation could improve. Overall, a fantastic tool for boosting trading success.
Kate