If one were to simply look on the statistics available on trader's behavior, a realization dawns that almost four in five people loose money in trading in currencies and CFDs.
You must be aware of the risks of investing in forex, futures, and options and be willing to accept them in order to trade in these markets. Forex trading involves substantial risk of loss and is not suitable for all investors. Please do not trade with borrowed money or money you cannot afford to lose. This website is neither a solicitation nor an offer to Buy or Sell currencies, futures, or options. No representation is being made that any account will or is likely to achieve profits or losses similar to those discussed on this website.
Any opinions, news, research, analysis, prices, or other information contained on this website is provided as general market commentary and does not constitute investment advice. Website owners and affiliates will not accept liability for any loss or damage, including without limitation to, any loss of profit, which may arise directly or indirectly from the use of or reliance on such information. Please remember that the past performance of any trading system or methodology is not necessarily indicative of future results.
An e-mail with your verification code has been sent to your e-mail address. Please access your in-box and use the verification button or verification code to complete your registration. You already have an account linked with this E-mail it maybe standard or social login.
Please, sign in with it. Please, provide us your e-mail so we can verify your account. Keep me signed in. MA Cross The best way to illustrate how to code up an expert advisor is by example. The few manuals and guides that discuss the building of an expert advisor tend to use the moving average cross MACross as an example. The reason for this is that it is the most popular indicator based strategy out there, and it so much easier to teach new coding concepts using a trading concept most people are already familiar with.
Following this familiar path, I submit a basic expert advisor based on a simple moving cross One way to get over the intimidation factor is to worry less about the little details and focus on the big picture.
Try not to figure out exactly how each and every bit of the language works and wondering what is happening behind the scenes, at the processor level, and just accept that it is working. You don't need to get caught up in the details of the language and it's format.
You don't need to be concerned with the nuts and bolts in order to understand and construct an EA. At this point in time you just need to know how the pieces of the puzzle fit together, and what are the most important pieces that can be manipulated in order to develop new strategies. I will assist you in putting the puzzle together, and point you in the direction of the most important pieces.
I have numbered and labeled each section in the EA to enable easier cross-referencing as I guide you through the understanding of each of the parts. Preprocessor Directives, external and internal Variables First, a word on Comments. We include comments even though the computer ignores them in order to help explain in plain English the meaning of our programming statements.
Yes, programming language can be hard to understand at first glance, and adding comments can be useful as you write your code to make your life easier. Next, a word on Preprocessor Directives. Each directive begins with a pound sign. There are many advanced forms of directives, such as the import and include, but we are just using the simplest of them all, the property copyright preprocessor directive that identifies the code as ours.
Other than that, it is not that important and does nothing fancy. The external variables are next, and they are important. In the previous article, I have explained how a variable is like a small box where can store things for later use. The external variable which has the word extern preceding it is important because it displays its parameters outside the program in the Expert Dialog box for the user to easily manipulate. Many of the external variables you see in the basic EA above are self-explanatory.
These variables refer mostly to that function. The interesting external variables in this section are: Moving Average Parameter Variables. Notice that I have placed all the moving average parameter values as external variables. I did not have to do this. I could have just just made the most important variable, the MAPeriod, an external variable, leaving the rest of the parameters in their defaulted values within the indicators when I call them in Section 3B, Indicator Calling.
I have declared almost all the parameters as external variables just in case I want to optimize any at a later point. For now I'll probably end up just optimizing the MAPeriod, but it could be useful to optimize some of the others in the future.
We will discuss more about these parameters when we tackle Section 3B, Indicator Calling. OppositeClose, and EnterOpenBar When you see a bool in a variable, it is a type used for values of truth. The type bool comes from Boole, the last name of the inventor of the logical calculus.
Let's examine the bool OppositeClose. Whenever oppositeclose is referenced in the code, it will be defaulted as true, meaning I want it to be switched on. If set to false, it will be swtiched off. Optionally, instead of using true or false, you can use 0 for false and 1 for true. The OppositeClose bool refers to the idea of being able to close an order on an opposite signal.
What does this mean? If set to true, and I am currently in a long position , and a short entry order is triggered, the short entry order closes out my current long before putting on a short trade. The short entry signal is the opposite signal that closes the current long and vice versa. I have defaulted oppositeclose as true because I definately want it activated.
If I had chosen false, that is, decativated the oppositeclose, the short entry signal would not close out my prior long trade, and my long trade would remain open until it was closed by hitting the stoploss or takeprofit. In general it is a good idea to have the oppositeclose set to true and activated. When making new strategies based on indicators I prefer to default the EnterOpenBar as true in order to quickly see how the strategy backtests. The strategytester has three types of backtest modes in its drop down menu: Every tick is more accurate but slower than the others.
Open prices are less accurate but faster than the others. Control points sits in the middle of the two in both accuracy and speed. However, if EnterOpenBar is set to true, then you can safely backtest on the open prices only mode, vastly increasing your speed of backtesting , while at the same time having the very similar accuracy and results to the everytick mode. Besides the speed of backtesting, I have also noticed that when enteronopenbar is set to true, it improves the overall performance and reliability of the system, particularly if it is based on common indicators.
I encourage you to experiment with turning the enteronopenbar to true and false in order to see the differences in results. Lastingly, in this section I have declared a few internal variables sometimes called Global Variables , such as double ticket, number, vPoint; Notice how I do not declare a particular value for each identifier.
Without a declared value, each indentifier is defaulted at 0, waiting to be later determined. When it is finished with its determination, it reverts back to 0. Also notice that I am listing the identifiers after double, one after another, seperated by commas, till I end the statement with the semicolon. This can be done because none have a globally distinct value.
But, if the stock could stay above the average, I should just hold my position and let the money flow to me. I'm not even going to worry about giving you the ticker of the above chart because it's honestly irrelevant. The pattern I was fixated on was a cross above the period moving average and then a rally to the moon. I remember feeling such excitement of how easy it was going to be to make money day trading this simple pattern.
Now, shifting gears for a second; anyone that knows me knows that I have a strong analytical mind. At this point in my journey, it's about the summer of I am placing some trades and trying different systems, but nothing with great success. I am using the period simple moving average in conjunction with Bollinger Bands and a few other indicators. So, after reviewing my trades, I, of course, came to the realization that one moving average is not enough on the chart.
The need to put more indicators on a chart is always the wrong answer for traders, but we must go through this process to come out of the other side. I felt that if I combined a short-term, mid-term and long-term simple moving average, I could quickly validate each signal.
You are welcomed to use any setting that works best for you, but the point is each moving average should be a multiple or two from one another to avoid chaos on the chart. I used the shortest SMA as my trigger average. When it crossed above or below the mid-term line, I would have a potential trade. The sign I needed to pull the trigger was if the price was above or below the long-term moving average. So, going back to the chart the first buy signal came when the blue line crossed above the red and the price was above the purple line.
This would have given us a valid buy signal. Then after a nice profit, once the short line crossed below the red line, it was our time to get out. Notice that the price was still above the purple line long-term , so no short position should have been taken. The purple long-term prevents is from always being in a long or short position like in the cryptocurrency case study mentioned earlier.
Looking back many years later, it sounds a bit confusing, but I do have to compliment myself on just having some semblance of a system. At this point of my journey, I am still in a good place. That's what I was hoping to represent with the green smiley faces. The green also represents the expectation of the money flow as well. It's around late summer at this point and I was ready to roll out my new system of using three simple moving averages.
It became apparent to me rather quickly that this was much harder than I had originally anticipated. Once I landed on trading volatile stocks, they either gave false entry signals or did not trend all day. This level of rejection from the market cut deeply. I remember staring at the screen thinking, "Why is this not working? Charts began to look like the one below and there was nothing I could do to prevent this from happening.
Anyone that has been trading for longer than a few months using indicators at some point has started tinkering with the settings. Well, I took that concept to an entirely different level. I was using TradeStation at the time trading US equities and I began to run combinations of every time period you can imagine.
As you can see, these were desperate times. I was running all sorts of combinations until I felt I landed on one that had decent results. The goal was to find an Apple or another high-volume security I could trade all day using these signals to turn a profit. Similar to my attempt to add three moving averages after first settling with the period as my average of choice, I did the same thing of needing to add more validation checks this time as well.
So, instead of just moving forward with the settings I had discovered based on historical data which is useless the very next day, because the market never repeats itself , I wanted to outsmart the market yet again. It's important to note that I was feeling pretty good after all this analysis. I felt that I had addressed my shortcomings and displacing the averages was going to take me to the elite level.
For those of you not familiar with displaced moving averages, it's a means for moving the average before or after the price action.
I'm not going to drain this concept in this article, as the focus of this discussion is around simple moving averages. The point is, I felt that using the averages as a predictive tool would further increase the accuracy of my signals. This way I could jump into a trade before the breakout or exit a winner right before it fell off the cliff.
To illustrate this point, check out this chart example where I would use the same simple moving average duration, but I would displace one of the averages to jump the trend.
The reality is that I would jump into trades that would never materialize or exit winners too soon before the real pop. I think this feeling of utter disgust and wanting to never think about trading again is part of the journey to consistent profits. Going back to my journey, at this point it was late fall, early winter and I was just done with moving averages. This is clearly reflected in my red unhappy face.
This of course left me feeling completely broken and lost. I don't say that lightly. I mean the feeling of despair was so real; you feel like quitting, to be honest.
Al Hill Click to tweet. Technical indicators and systems lead to more indicators to try and crack the ever-elusive stock market. I would try one system one day and then abandon it for the next hot system. This process went on for years as I kept searching for what would work consistently regardless of the market. If you get anything out of this article, do not make the same mistake I did with years of worthless analysis.
You will make some traction, but it's a far better use of your time to zone in on yourself and how you are perceiving the market. After many years of trading, I have landed on the period simple moving average. At times I will fluctuate between the simple and exponential, but 20 is my number.
This is because I have progressed as a trader from not only a breakout trader, but also a pullback trader. I use the period moving average to gauge market direction, but not as a trigger for buying or selling. At times a stock will crack right through the average, but I don't panic that a sell-off is looming. I just wait and see how the stock performs at this level. It's funny to think that I have essentially reverted to exactly what I was looking at over 10 years ago - one average.
You may ask "Are you upset that it took you this long to come to this conclusion? It wasn't all death and gloom along the way and the simple moving average is just one component of my trading toolkit.
In other words, mastering the simple moving average was not going to make or break me as a trader. However, understanding how to properly use this technical indicator has positioned me to make consistent profits. The thing is they have little to do with trading or technicals. Both disadvantages for me deal with the mental aspect of trading, which is where most traders struggle - the problem is rarely your system.
This is something I touched on briefly earlier in this article, essentially with a lagging indicator, you will never get out at the top or bottom.
Now, you could be thinking, well if we make money that is all that matters. Well, if only your brain worked that way. You could fall into the trap of doing look backs on your trading activity and anguishing at all the loss revenue from exiting too early. Very simple, you let go.
You stop obsessing about what you did not receive and start praising and thanking God for what you have! The other very real disadvantage is the intestinal fortitude required to let your winners run.
You are going to feel all kinds of emotions that are telling you to just exit the position. Or that you have made enough. Or that the pullback is going to come, and you will end up giving back many of the gains. You must find some way of just charging through all of that and letting the security do the hard work for you.
We have been conditioned our entire lives to always work hard towards something. The market is a lot like sports. A lot of the hard work is done at practice and not just during game time. It would be wrong of me to not go into this a little more as the comparison of the simple moving average to the exponential moving average is a common question in the trading community.
The formula for the exponential moving average is more complicated as the simple only considers the last number of closing prices across a specified range. The exponential moving average however adjusts as it moves to a greater degree based on the price action.
To learn more about the exponential moving average and its calculations, please visit the article - ' Why Professional Traders Prefer Using the Exponential Moving Average '. It is really going to come down to your preference.
If you like clean charts, stick to the simple moving average. If you feel that you need to try and capture more of your gains, while realizing you may be shaken out of perfectly good trades- the exponential moving average will suit you better. Are you able to guess which line is the exponential moving average? If it's not obvious, the red line is the EMA. You can tell, because even though the SMA and EMA are set to 10, the red line hugs the price action a little tighter as it makes its way up.
The only time there is really a difference is when the price breaks. What's slightly confusing is that when the price does break, it will likely penetrate the SMA first. This is because the SMA is slower to react to the price move and if things have been trending higher for a long period of time, the SMA will have a higher value than the EMA.
As you can see, the EMA red line hugs the price action as the stock sells off. But then something happens as the price flattens. The slower SMA is weighting all the closing prices equally, therefore it continues to decline at a faster rate. Conversely, the EMA accounts for the most recent price movement and begins to climb upwards pulling away from the stock's price as it is in a bottoming formation.
So, you may be asking yourself, "Well when will the EMA get me out faster? The answer to that question is when a stock goes parabolic.
The EMA will stop you out first because a sharp reversal in a parabolic stock will not have the lengthy bottoming formation as depicted in the last chart example.
If you haven't already figured it out, the simple moving average is not an indicator you can use as a standalone trigger. Now, that doesn't mean that the indicator can't be a great tool for monitoring the direction of a trend or helping you determine when the market is getting tired after an impulsive move. Think of the SMA as a compass. If you want detailed coordinates, you will need other tools, but you at least have an idea of where you are headed.
Free Trial Log In. Popular Simple Moving Averages. Simple Moving Average Example. Flat Simple Moving Average. Simple Moving Average - Perfect Example. Simple Moving Average Crossover Strategy. Riding the Simple Moving Average. Two-period simple moving average. Displaced Moving Average Sell Signal.