Thursday, January 26, 2012
How Backtests Simulate Ticks
Consider a typical bar. It has a high, low, open and close. That's only 4 data points. If you're looking at something like an H1 bar, there could be several thousand ticks - maybe tens of thousands of ticks - that comprise that entire bar. And you're trying to encapsulate it by only referencing 4 points.
MetaTrader brokers in particular do not want to provide tick data. The sheer volume of information would put a lot of strain on the servers. The brokers are the ones paying MetaQuotes for MT4. Their concerns go ahead of you as the trader. Thus, no tick data is available unless you go to a ton of extra effort.
That leaves the backtester guessing what should have happened at all of the points in between. Strategies that trade intrabar or EAs that place the stop and take profit so closely together that they might get hit on the same bar are particularly vulnerable to bad assumptions.
Example:
You placed an order to buy a forex pair at 100, which is also the open. You set the take profit at 105 and the stop loss at 97. The low of the bar is 96, the high of the bar is 110 and the close is 102. Is there any way to know whether the stop loss or take profit hit first?
No, you cannot tell. The price might have fell from 100 down to 96, climbed up to 110 and then fallen to 102. Alternatively, it may have climbed from 100 to 110, then fallen to 96, then climbed back to 102. More than likely, the price followed a complex path that vaguely resembles one of those paths.
MetaTrader and NinjaTrader have no way of knowing which answer is correct. They do their best to work around the gap in knowledge. NinjaTrader simply assumes the worst case scenario, which is probably the best policy to avoid false positives. If a stop or take profit both hit within a bar, then NinjaTrader assumes that the stop loss was hit first. There are no exceptions. The slightly good news is that if your NinjaTrader backtest looks abysmal and faces this issue, it may not be as bad as you first thought.
MetaTrader approaches the backtest assumptions differently. It tries to build the path of the bar by inferring from the relationship between the high and low and the open and close. If the bar closes up, I believe that MetaTrader assumes that the low comes first, then retraces up to the high of the bar before settling back down to the close. I don't have a theory on the algorithm that powers what happens in between; it's usually not relevant. If your stops and take profits are so close that the up/down bar assumption cannot sort it out, then no amount of backtesting will provide an accurate answer until you finally import tick data.
The spread at the time of entry, and thus the cost of trading, are also unknown. This can heavily distort the results. MetaTrader makes assumptions about the spread. Although it generally reflects the average spread, it's a safe bet that it does not reflect the actual spread at the time you traded. Whether or not the assumed spread works out in your favor over hundreds of trades varies from Expert Advisor to Expert Advisor.
NinjaTrader can work around the tick assumptions, but you must anticipate it within the strategy's programming. I plan to write a future blog post that will explain how to force NinjaTrader to use tick data for both the bid and ask to generate accurate backtests in NinjaTrader.
Wednesday, January 25, 2012
Iran's Ahmadinejad ups rates to stem money crisis
Thursday, January 19, 2012
EES VPS for Forex Traders
To learn more, visit: http://eesfx.com/portal/trading/vps
See bundling info at CNS: https://cp.commercialnetworkservices.net/announcements.php?_m=news&_a=viewnews&newsid=31
http://helpdesk.commercialnetworkservices.net/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=195
EES also offers dedicated servers for professional traders at http://fxsystemhosting.com
Wednesday, January 18, 2012
Local currencies: 'In the U.S. we don't trust'
While there were only about 20 active community currencies in the United States in 2009, there has been a recent resurgence, with at least a dozen communities developing their own currencies in the past couple of years, estimates Loren Gatch, a professor of political science at the University of Central Oklahoma who researches these alternative currencies. In addition, currencies that have been around for years have seen a spike in interest, with membership doubling in some cases.
http://money.cnn.com/2012/01/17/pf/local_currency/index.htm
Friday, January 13, 2012
EES Article FX Trader Mag
"Expert Advisors and Retail Forex"
Also EES recently was published in Stocks & Commodities magazine (January, 2012) "A Practical Guide to Forex Arbitrage" see an excerpt here: http://www.traders.com/index.php/sac-magazine/current-contents/forex-focus
Tuesday, January 10, 2012
MetaTrader is more popular than NinjaTrader
Fumbling through NinjaTrader
All of the things that MetaTrader does well, NinjaTrader does very poorly. The first time that I downloaded the 42 MB installation file, NinjaTrader said that I couldn't use it because I didn't have the .NET 3.5 framework installed. That makes sense to me as a programmer. To people that do not program for a living (i.e., the people reading this blog), that error message is next to worthless. NinjaTrader ought to handle this type of issue automatically.
Once I installed the program, I tried to open a chart. Nothing happened. I messed with it for about 5 minutes until I finally gave up and decided that the program wasn't worth the effort.
I decided to try again a few months later, at which point I realized that NinjaTrader did not include a datafeed. So then I had to go through their list of 50+ vendors to figure out where I might find a decent forex feed to try using their platform. The feed that I happened to have, Interactive Brokers, required that I download a special version of their software. Naturally, I did not figure this out until I got endless error messages and had to contact NinjaTrader suppport. An hour and several handfuls of hair later, I finally was able to do what MetaTrader allows me to do in seconds - look at a forex chart.
My Windows XP machine with 2 GB RAM, which is pretty typical of your average software user, takes about 20 seconds to load NinjaTrader. I have the nasty habit of closing and opening applications repeatedly. It gets on my nerves when I close NinjaTrader because it takes so long to get it back up again. I would consider leaving the application open, but I usually have 5-6 windows open within their platform. The taskbar always looks so cluttered. Call me crazy, but I find it very difficult to work on the computer with so many window tabs showing at the same time. It feels like there is too much going on visually.
Whenever you have a question about MetaTrader, you simply pick up the phone and call any MetaTrader broker. They answer your question immediately. NinjaTrader, in spite of its excellent online support, largely takes the help yourself approach. You can figure out most problems eventually, but it requires digging through forums and reading a few articles before you stumble upon the one with the answer. That type of self-help approach requires patience. Most people, especially us Americans that expect answers on the spot, are not blessed with that particular virtue.
Products and Add Ons
MetaTrader is like Google Android and NinjaTrader is like Apple. MetaQuotes takes the Android style, hands-off approach. Anything that does not interfere with the MetaTrader itself is allowed. "Allow" isn't even the right word. MetaTrader is entirely removed from the process. The result is there are thousands of products available for sale that work exclusiely in MetaTrader. It's an accidental ecosystem for trading products that relates directly to the approach so prevalent in social media and mobile phones.
NinjaTrader takes the Apple, big brother approach; all products are screened and vetted. This does come with some advantages. You're a lot less likely to buy a total piece of garbage for NinjaTrader than you are for MetaTrader. That said, the centralized also stifles the products on offer. Maybe it's just because I'm Texan and resent anything that feels like authority making choices for me, but I think you see a lot more life and innovation when the people selling a related a product don't have to ask permission to do so.
What does Ninjatrader do, anyway?
You need to take a week's worth of online training to really get a sense for how to use the product. NinjaTrader, for some odd reason, does not offer YouTube videos or any friendly beginners guides to get up and running. They require that you attend online webinars, which are always scheduled in the middle of the work day, in order to thoroughly learn each of the product's main features.
When you open the software, it's not at all apparent what exactly it's supposed to do. Is it an automated trading platform? Is it a charting platform? Is it a tool for active traders? NinjaTrader does all of the above, but my opinion is that the software itself does a terrible job making this clear. Little things like a first-time walk after downloading through would help traders get over the steep learning curve and give the product a chance.
I actually love NinjaTrader, but it nearly takes a graduate degree to figure out how to use it. That's the only reason that I'm so hesistant to recommend it to my MetaTrader programming clients. Once you figure out how to use the tools, they are incredibly powerful. The built in trading analytics eliminate the need for MetaTrader related sites like MyFXBook and MT4Stats for viewing and studying my daily performance. Comparing MetaTrader and NinjaTrader in the backtester is not even worth doing: NinjaTrader is infinitely superior. It's too bad that NinjaTrader gets in its own way.
The features that NinjaTrader offers should make it way more popular than MetaTrader. I just don't see that happening any time soon with how long it takes to learn the software.
Forex Correlation
What are correlated currency pairs?
Correlation offers a mathematical probability of two "time series" moving in the same direction. Applying the idea to forex, it means that we need to pick two currency pairs. EURUSD and USDCHF are two popular choices due to their extremely high correlation, so we'll use those.
Now we ask a simple question: "If the EURUSD rises, what is the probability of that the USDCHF will also rise"? Our calculations will pump out a simple a number between -1 and +1. +1 means that that if Currency A rose in value, then it is 100% certain that Currency B rose in value. -1 means that if Currency A increased in value, then it is 100% certain that Currency B decreased in value. A value of 0 means that the movement of Currency A exercises no effect at all on Currency B.
Traders generally consider a correlation significant whenever the number is greater than 70%. EURUSD and USDCHF are so popular because they hold the strongest correlation among the major currency pairs. When market volatility was very low a few years ago, it was around -93%. Today, the correlation tends to hang around -80%. The European debt problems and Swiss National Bank's intervention have a lot to do with the decrease in this number. Their trading relationships are far less stable.
Risks of correlation strategies
Let's move back into familiar territory with my favorite example, the moving average. If you take the average over the past 20 bars, you know from experience that the average will differ if you study a 50 period versus a 200 period average. If you look at the average on a 5 minute chart versus an hourly chart, the number will vary yet again.
The take-away here is that the correlations work the same way. The correlation between EURUSD and USDCHF might even be positive if you look at a short enough time scale. As you back away in time, you will notice that the further out you go, the more steady the correlation numbers look. If the weekly correlation of the EURUSD and USDCHF is -80%, you would expect the numbers to get more wild and erratic as you scale all the way down to a tick chart.
The same problem with the moving average also appears. Studying the correlation over 50 periods provides a responsive number, but it is also far less consistent than the 200 period correlation. What a short period gains in responsiveness, it loses in stability.
You should also consider whether the correlation that you're studying makes fundamental sense. Just because the temperature change in Mongolia predicted the direction of USDJPY for the past week does not make it a good idea to use in the future. The same goes with pair trading.
EURUSD and USDCHF should be highly correlated for two reasons. They both contain the same currency in the pair (USD), which half weights them with the same instrument. Additionally, the EUR and CHF both have strong trading relationships with the US. You would expect both the Euro Zone and Switzerland to share a need for buying and selling US dollars. They need them for buying oil, importing and exporting to the US, etc. Anyone with a cursory understanding of macroeconomics could explain why this relationship makes sense.
Correlation traders typically settle on pairs that share a common currency. The EURUSD and USDCHF trade both share the US dollar. When you buy EURUSD and buy USDCHF, you are really:
Buying EUR and
Notice that the USD cancels itself out. What you are really doing is buying EUR and selling CHF. This is commonly known as the EURCHF pair. Assuming that the spread is not outrageous, it makes more sense to simply buy or sell EURCHF directly rather than going through the convoluted process of managing two open trades.
If you decide to pursue the two pair approach in a MetaTrader expert advisor, you must consider the need to balance the trade sizes against each other. Using standard lots as the example, 100,000 EUR is 137,500 USD. 100,000 USD is 90,900 CHF. If you buy one standard lot of EURUSD, you are buying $137,500 of it. When you buy a standard lot of USDCHF, you are only buying $100,000.
$137,500 obviously does not equal $100,000. Unless you intentionally decided to trade different sizes, you may want to consider equalizing them.
Solve for x:
€100,000 / $137,500 = x * (₣90,900/$100,000)
x = €100,000 / ₣90,00 * $100,000 / $137,500 = 0.803
You would need your EURUSD trade to be 80% of the size of the USDCHF trade.
What correlation is not
Correlation only provides insight into the probability of direction. It says absolutely nothing about the strength of a particular move. A few months ago the USDCHF climbed 1,000 points in value within a single day. The EURUSD only moved a few hundred pips. The USDCHF moved dramatically further than the EURUSD both in terms of pips, but more importantly, as a percentage of price.
Consider if you were short EURUSD that day and short USDCHF. You lost a ton of money. On the flip side, if you were long EURUSD and long USDCHF, then you got lucky and earned the move. Regardless of what happened, correlation told you nothing about the outcome when they move in the same direction. For that reason, I prefer looking at a less intuitive method called cointegration.
Cointegration
Conintegration turns the problem on its head. Rather than asking whether or not two pairs move in the same direction, it asks how likely are they to remain a certain distance apart. Naturally, that distance tends to vary with time. What you want the cointegration formula to tell you is how likely two pairs are to come back to a standard distance. If you see two pairs spread unusually far apart and the numbers tell you that they usually come back together, then it makes sense to consider a pair trade.
Ernest Chan has a friendly introduction to cointegration that I highly recommend. A much uglier, math intensive introduction to the subject, albeit one that is also far more thorough, is in the book Pairs Trading by Ganapathy Vidyamurthy.
Wednesday, December 28, 2011
Euro drops to near 10 year low
S&P 500 Snaps 5-Day Rally Amid Europe Concern
Wednesday, December 21, 2011
Monday, December 19, 2011
Repainting Indicator
If this sounds familiar, then you need to consider whether or not the indicator repaints.
What is a repainting indicator?
First consider a baseball analogy. Last week, the St. Louis Cardinals beat the Texas Rangers to win the World Series. A repainting indicator is like asking you today, "Would you bet on the Cardinals or Rangers?," then pretending like you placed your bet 3 weeks ago and not today. You had no way of knowing for certain who would actually win.How normal indicators work
If that sounds stupid, that's because it is. Repainting indicators use knowledge of the "historical future" to "predict" which way the market was going to go. Indicators typically start with old bars on the left side of the chart, then walk forward to the right side until they obtain enough information to make a decision. Say, for example, that you want to create the RSI indicator on a daily chart and you want to start on October 25. You start at October 25, and make decisions based on information from Oct. 24, 23, etc., until you've collected 14 bars worth of data or however long you set the period. You then say definitively that the RSI on October 25 is X.Now you move on to October 26. You look back at October 25, 24, and so on, until you get the final RSI value for October 26. All of the examples move forward into the future, then look back into the past to get the current value.
A hypothetical repainting indicator
Now let's make a hypothetical RSI indicator that repaints. Say our first date under consideration is October 25. We might start by looking into the past, which is what we did last time. But for the sake of making the example obvious, let's look the other way - into the future.We gather data from October 26, 27, and so on. Now, having learned the future, we jump back to October 25 and pretend that we knew the future all along. The RSI looks amazing.
A Real Example
I receive copies of the 3_Level_ZZ_Semafor every once in a while and it tends to cause problems. It's based on the same idea as the zig zag indicator, which helps it to pick perfect tops and bottoms. Trend traders love looking at it. The information seems like it would be so valuable.
Making an EA off of it, however, presents numerous problems. The trades that the Expert Advisor makes do not match up with what the indicator looks like a few hours later. What actually happens is that the indicator changes its mind. It doesn't leave behind any evidence of its incorrect prediction. The novice EA designer naturally concludes that the programming is all wrong and that we need to fix it.
The first image below shows the value of the semafor on a EURSUD M5 chart at 00:00 on October 10, 2011. You'll notice that a purple dot with the number 2 appears on that bar. The market is moving strongly upwards. The indicator at this point predicts that the move is likely overextended.
If we jump 2 bars into the future at 00:10, now magically a number 3 dot appears. What's worse is that the number 2 dot disappears entirely from the 00:00 bar! The indicator sees that the price jumped up, so it goes back in time and deletes the evidence of its incorrect prediction. If you weren't watching the indicator or taking screenshots, it is as though the number 2 dot was never there.
Test your indicator and look for repainting
No automated process exists to determine whether or not your indicator repaints. It's something that you have to do by staring at the chart during a backtest to see if the values change or not.I like to do this by selecting an Expert Advisor without caring too much about which one I pick. If you don't have any installed, you can grab one from the free Expert Advisor page for the sake of testing.
You'll need to select settings to get the backtester to run. The options that you choose are not important, so long as you have selected something. I highlighted the required items in red below. I personally prefer to use M5 EURUSD charts. M5 is good because the backtester moves over the data quickly on full speed without going so fast that I cannot control the process. It strikes a nice balance between speed and following what's actually happening. I like EURUSD simply because I always have EURUSD data loaded. I don't have to worry about the tester not working, whereas that would likely be an issue if I selected an exotic currency like TRY/ZAR.
When the visual backtest chart pops up, the first thing to do is to load your indicator onto the chart. As the test progresses, watch how the indicator behaves. Some repainting indicators like the Semafor are completely obvious. They repaint on most bars, so it's easy to tell that it is not consistent. You can safely assume that it repaints.
Other indicators are more tricky. They only plot once every 50 bars and sometimes even less frequently. You have to watch closely to make sure that where plots appear, that they don't subsequently dance onto another bar. I like to use the same technique in the first screenshot that I posted with a vertical red line. Whenever the indicator plots something on the chart, mark it with a vertical line. Continue doing so for about a day's worth of data on the M5 chart. Stop the test, then scroll back through the chart. If 100% of the plotted values match the vertical lines, then your indicator does not repaint.
Wednesday, December 14, 2011
Time based orders in MetaTrader 4
The short summary is that time based orders in MT4 are possible. You just need to keep in mind some of the technical limitations. MetaTrader 4 EAs work based off of incoming ticks. Whenever the bid/ask changes by a micro pip or more, that event triggers the EA to do something.
When the markets hum along at a rapid pace, this effect is not noticeable. When the quote flow slows down, however, it can cause the EA to sleep entirely through your trading window.
Many news traders want to bracket buy and sell stops around the price at 08:29 on NFP Friday. Everyone knows that a major news event is about to release. Trading slows down, as does the flow of quotes. The pending orders may not set in time if an incoming tick does not arrive in the 60 seconds between 08:29 and 08:30. This seems unlikely to many novice traders, but it happens frequently enough that we inevitably receive these types of questions whenever we program a time-based order placement EA.
The workaround typically satisfies most traders. EAs place an order at the first available tick within a certain time window. Using NFP as the example, the EA might seek to place bracket orders around the first tick between 08:29-08:32. The chances of making it 2 minutes past 08:30 without a single tick are low. And given that you are taking the first tick, the orders will succesfully bracket around the price the vast majority of the time. It is important to keep in mind how the backend works for those one-off events where the orders do not function as desired.
MetaTrader 5 addresses MT4′s time weakness by offering event driven programming. It is possible to rewrite MQL4 EAs into MQL5 and to demand an action at a precise moment in time. The MQL5 timer actively watches the clock. Regardless of what the markets do, the EA can know to wake up and do whatever action is needed. This is one of the few scenarios where converting from MQL4 into MQL5 comes with obvious advantages.
Wednesday, December 7, 2011
Automated Choice of Brokerage Company for an Efficient Operation of Expert Advisors
Introduction
- Quotes. They slightly differ because of two factors - different data feeds and different filtration that smooths quotes. For some Expert Advisors this may be relevant. Situations may occur when an EA trades often with one brokerage company and rarely on another one.
- Slippage. It may differ much in different brokerage companies. This also may lead to worse characteristics of an EA because of lower expected profit.
- Requotes. In some brokerage companies they are oftener than in others. In this case an EA will miss successful entering points because of large number of requotes.
http://articles.mql4.com/508
Color Changing Indicators in MetaTrader
Many custom indicators in MetaTrader use lines that change colors to indicate a change in trend or market condition. Those types of indicators are among the more common requests that we get for programming Expert Advisors. Unfortunately, these indicators often present problems. What you see on the chart is not necessarily what the indicator says.
Take a look at the image below or click the link to view it in full size. You'll notice that I included the data window for the indicator, which is SuperTrend. As we walk from left to right, the data window does not suddenly shift from Trend Up to Trend Down. Instead, it shifts with an in between period where the trend is both up and down.While the visual effect is immediately obvious, the numbers do not clearly indicate the indicator's condition. In fact, it frequently happens where the indicator entirely misrepresents its true calculation. If the last bar was only green and the indicator says that the current bar is red-green, then we can safely assume that the indicator is switching from green to red.
When the indicator says it's red-green and the past bar was red-green, it gets more tricky. We are forced to keep looking back through time until a "clean" red or green value appears. This enables us to capture the indicator's real value.It does not, however, make for a happy trader. Consider the case where the indicator plots red-green, red, red-green, red. Because of the way MetaTrader draws lines from point to point, the indicator actually appears as a solid red line - a long, beautiful sell signal, right?
In fact, its true calculated values are red, green, red, green. This glitch can make for some ugly surprises. This is especially so when traders expect to ride a down trend and the line appears as solid red, but the indicator (and thus EA) keeps flip flopping on the trade direction. You have to keep this in mind when building EAs around custom indicators.Tuesday, December 6, 2011
Copyright Issues When Programming Expert Advisors
The crux of the matter is what you intend to do with it. Intellectual property (IP) law has a concept called public domain. If you create an indicator and then share it on a public web site, then the file is presumably free for all to use. Essentially, you give away the copyright when you share it for all to see. The only caveat would be if the file or hosting page places an explicit restriction on how the file may or may not be used.
Personal use of an Expert Advisor does not pose a problem. This includes indicators that you purchased. The only legal reason that prevents you from using a commercial indicator in a personal EA is if the purchasing agreement for the indicator forbids creating derivative products, such as using the indicator to build a new EA.
Writing a commercial EA with a public domain custom indicator also meets the hurdle. You cannot take someone else's work and pass it off as your own; you must substantially alter or improve it before the work becomes yours. Turning an indicator into an automated strategy qualifies as a substantial improvement.
The thorniest issue pops up when you want to use a commercial indicator to create a commercial EA without the permission of the indicator's owner. Most people, myself included, would call this theft. The only way that you can do this legally and ethically is to secure an agreement from the indicator's copyright owner.
I am a programmer. If you're deeply concerned about this issue and want to ensure this information truly reflects US law, then I strongly suggest that you speak with an intellectual property attorney. The information above is for general information purposes and should not be construed as legal advice.
Here's a quick summary:
Create a private EA from a public domain custom indicator - Almost always ok, unless the indicator owner forbids it
- Create a private EA from a commercial custom indicator - generally OK, unless your purchasing agreement forbids it
- Create a commercial EA from a public domain custom indicator - generally OK, unless the indicator's creator forbids it
- Create a commercial EA from a commercial indicator - never OK, unless you strike an agreement with the copyright owner