Saturday, September 29, 2012

Meta-Trader - Performance Based Lot Sizing

Welcome back, Meta-Traders.

Albert Einstein once said:  "The measure of intelligence is the ability to change". This quote really rings true since I'm more convinced than ever that the only way we are going to make any profits (and not end up giving them back) is to make systems which are adaptable to recent market conditions.

Case in point is the chart on the left which is a reconstructed equity graph of Atipaq Full Portfolio, which I have been tracking for nearly 2 years on the right side of the blog.  Note how the system started to rally right from the start and peaked (up nearly 100% from the start!) back in March of this year.  Since then, its been a straight slide downward and the system has now given back all of its gains and remains above positive only because of a deposit made back in March of 2012.

We know that the pair behind these losses - and behind much of the losses in my other portfolios -  has been the Atipaq USD/CHF instance.  Historically, this has been one on of the most profitable instances and is why I trade it in 3 of the 5 live accounts I'm tracking.  But up to now, I have been at a loss to explain what's behind the poor performance. Yesterday, Daniel Fernandez cleared it up in a post when he identified the problem as the year-long commitment from the Swiss Central Bank to prevent the EUR/CHF to fall below 1.20 level to stem runaway rally in the Swissie.  Since then, the pair has basically flat-lined, with the Swiss Central Bank coming  in with unlimited funds to prevent any meaningful breakdown of EUR/CHF below 1.20 level which has a related affect on USD/CHF and makes it behave more like EUR/USD.

This move has completely changed the dynamic in USD/CHF and caused a failure of our Atipaq USD/CHF instance.  But what can we do about it?  Its easy to see in retrospect what happened, but how can we guard against these type of changes in future systems?   I thought about it and came up with the idea of varying lot sizes based on recent performance of the systems.  Here's how it works:

  • Track the equity of the portfolio as a data series D
  • Calculate a 5-period moving average of portfolio equity as MA5
  • Calculate a 21-period moving average of portfolio equity as MA21
  • If D is greater than MA5, set M1=0.5, otherwise set M1=0.25
  • If MA5 is greater than MA21, set M2 = 0.5, otherwise set M2=0.25
  • Set M3 = M1 + M2
  • Multiple the baseline lot size (say 1%) times M3 to get your adjust lot size
  • Calculate the new equity portfolio as data series D1

At the end of this calculation, M3 will be a value between 0.5 and 1.  Multiply M3 times your normally expected lot size for the system.  I did a "thought experiment" using this system on a spreadsheet and came up with this adjusted equity graph:

The adjusted equity graph shows the following:

- Identical starting account size at $2100

- Peak valuation for the original series at $4396 versus  $4050 for the adjusted series

- Current valuation for the original series is $2297 versus $2736 for the adjusted series

Bottom line is that the adjusted series results in lower equity highs, but also lower draw down.

In this experiment, the lot size change was simulated in a spreadsheet outside of MT4.  In a true implementation, the logic would be inside the EA and would look back on the account equity and make the lot size adjustments on the fly.  Once that's done the return and draw down statistics can be compared "apples for apples" versus the spreadsheet method which is a construction.

Adjusting lot sized based on recent performance is just one potential method of making systems adaptive.  A more powerful idea would be a system which either buys or sells breakouts, depending on which method has worked recently.  A similar method would potentially have been able to adapt to the complete change in character of USD/CHF.

As always, more to come.  Have a great week.

Sunday, September 23, 2012

Meta-Trader - Moving Average Clusters

Welcome back Meta-Traders.

Taking a page from the Oliver Velez material, I recently setup my charts with 3 moving averages, 5, 21 and 50 periods.  I setup the colors with pink for for the 50-period, blue for the 20-period and red for the 5-period.

This is a great combination of indicators since the pink line gives you an excellent idea of the underlying trend, the blue the intermediate trend, and the red line the shortest time frame hugging the price and always leading the other 2 MA's in the direction of the price.   The indicators work well with nearly any time frame for the chart,  but my favorites are M5, M30, H1 and D1.

Next, I noticed that good trading opportunities often occur when all 3 moving averages are bunched up close to each other, along with the price.  Thinking of how to turn this into an indicator, and possibly a trading system, here's what I came up with:

double dMA5 = iMA(NULL, 0, 5, 0, MODE_SMA, PRICE_CLOSE, 1);
double dMA21 = iMA(NULL, 0, 21, 0, MODE_SMA, PRICE_CLOSE, 1);
double dMA50 = iMA(NULL, 0, 50, 0, MODE_SMA, PRICE_CLOSE, 1);
/* Lowest of the 3 MA's */
double dLowest = MathMin(MathMin(dMA5, dMA21),dMA50);
/* Highest of the 3 MA's */
double dHighest = MathMax(MathMax(dMA5, dMA21),dMA50);

// Grab bar high and low
double dBarHigh = High[1];
double dBarLow = Low[1];

// In Range action
bool InRange = (dBarLow <= dLowest) && (dBarHigh >= dHighest);

In other words, we had to have a single price bar whose low was lower than the lowest of the 3 MA's and whose high was higher that the highest of the 3 MA's.  Put another way we look for a single price bar that straddles all 3 MA's.  The result is an indicator call MA-Clusters with arrows show. above.  The chart above shows a buy signal on Thursday 9/20/2012 with a sell signal a bar or 2 later that led to a nice downward move in EUR/USD.

The signal direction comes in the direction of the price close.  In the example above, we had a lower close, so this would be a sell signal.   Stop loss for the trade would be the opposite end of the signal bar.  In other words, if you took the sell signal above,  the stop loss would be right around where the red arrow is located.  There are several ways to take profit, one is to stick with the trade until you get a close above the 5-bar MA.

The next step was to turn this into an Expert Advisor to see if the system had any merit as an Automated Trading system.  After all, automated trading is what this blog is about, right?  To simplify the system, I used a fixed number of pips for SL and TP.  For the tests below, I used a stop of 55 pips and a Take Profit of 150 pips.

What I found from testing is that the system has some decent recent performance.  On a year-to-date basis, the system is up about 20% with maximum draw down of about 18%. But the system does not appear to be profitable on a stable basis over longer periods of time and therefore seems to have more merit as a tool for manual trading.  Perhaps with more work, it can be turned into a long-term profitable Expert Advisor.

You can find the attached files: ma-cluster.mq4 indicator file, FxMA-Cluster.mq4 expert advisor file and year to date back test files attached to my Yahoo group in case you want to play around with it.

Have a great week.

Saturday, September 15, 2012

Meta-Trader - Don't fight the Fed

Welcome back, Meta-Traders.

It was an historic week in world markets. We had 3 huge developments with macro level implications as follows:

- On Wednesday the German high court ruled in favor (or at least not against) Angela Merkel's agreement with European Central Bank's plan championed by (Mario Party) Draghi to print large quantities of Euros to buy EUR denominated bonds to reduce pressure on Spain, Italy and other sovereign's under duress.

- Later on Wednesday, my favorite stock and world's highest capitalized stock Apple Computer announced the 5th generation of their popular iPhone smart phone.  By all counts, the product is a hit, lighter, thinner and with a higher resolution screen.  Throw in new 4G networking and the accolades came in from all angles.  Apple stock rallied on the day of the announcement and also on Thursday and Friday closing Friday at an all-time high of about $691 a share adding about 16 Billion in market cap for this week alone.

- The big bomb dropped on Thursday at 12:30 PM when the US Fed issued their interest rate decision ending weeks of speculation and hint-dropping with key highlights as follows:

1) New stimulus program centered on Mortgage-backed securities pledging to buy 40 Billion (that's right billion) of Mortgage bonds per month.  They also indicated this position was opened-ended, and they would continue to buy bonds as long as necessary until the economy improved.

2) The Fed indicated they would keep interest rates between 0 and 1/4 of 1% until late in 2015.

3) The Fed also indicated they would not be in a hurry to tighten policy and would remain accommodative well after the economy starts to show signs of strength.

Well this was all the Fed bulls could expect and was quickly tagged by the financial media as the most fiscally accomodative statement in the history of the Federal Reserve.  This was all it took to light a huge rally under stocks on Thursday which had already rallied significantly for weeks into the announcement.  Uncle Ben promised big action and he delivered beyond expectations.

Asian stocks also loved the news on their Friday session which ignited another rally in US Stocks on Friday pushing the Dow Jones 30 and the S&P 500 up to 4+ year highs and within a few percentage points of the all-time highs set back in 2007.

All this bullishness sent currencies rallying with across the board dollar weakness and a capping a huge week in EUR/USD which was in solid rally mode all week, even before the Fed Announcement.  2 of my 5 currency accounts had solid gains for the week.  But extreme volatility in the Atipaq instances took profits from those accounts and gave back some recent gains.

Its no doubt and free and easy money is here to say and tighter monetary policy is a long way off.

Not much happening on the development side with currency trading since my regular day job, college search and household responsibilites have me hemmed in.  But we had a great week in markets on top of an already great year.  So we'll take it for now and live to trade (and code) another day.

Have a great week.

Saturday, September 8, 2012

Meta-Trader - Super Mario Party

Welcome back, Meta-Traders.

It was a big week in world markets with a few notable developments as follows:

The European Central Bank (ECB) signaled their intention to create money out of nowhere and buy large numbers of EUR denominated bonds, taking a page from the US Federal Reserve and igniting a huge rally in EUR/USD.  As a result, US Stocks moved out to new 4+ year highs with the S&P 500 moving out to levels not seen since 2007.  Also, my favorite stock, Apple Computer quietly moved out to a new all-time high in anticipation of a release of the iPhone 5 expected this coming Wednesday September 12th.

Even more interesting is that this happened in the face of a very seasonally weak period for the stock market.  It reinforces the point that the "Smart Money" was widely expecting a correcting coming into September and as a result loaded up on put contracts and  long volatility which typically spikes in the face of big market sell-offs.  When everyone is expecting a sell-off, we don't get one, and instead the shorts and VIX bulls got slammed with volatility plunging throught the week.

While my Equity Portfolios benefited from this, my Forex accounts did not respond as well and the only account that was up for the week was Atinalla #3.  Breakout related systems took some trades in the breakout direction, but were shaken out on premature exits.  Fortunately, most accounts went out long EUR/USD with some solid unrealized gains as shown in the screen shot on the left.   We also took some gains in long AUD/USD trades in Atipaq Full Portfolio, but continue to be punished by our Atipaq USD/CHF instance.

Overall, Forex continues to underperform for me as an asset class.  But generally my assets continue to grow and I have my hands full with career and my son's college selection process.  My time will come with Forex, so stick with my on my journey and have a great week.

Sunday, September 2, 2012

Meta-Trader - Fun with Forex Historical

Welcome back Meta-Traders.

One cool thing to have come out of Asirikuy lately is forex historical data from  The site sells 5 minute Historical data on 21 currency pairs to Asirikuy members for a modest fee through an arrangement between Daniel and Forex Historical.  The site also offers free end-of-day data in for those same 21-pairs in 12-hour resolution. 

Free is always transformational, so I downloaded the data for the free end of day data to see if I could get a better idea about seasonality.  Specifically, I was contemplating how much seasonality can be measured.  Put another way, how much different are the movements of the market during 'busy' times versus quiet times during August?  With that in mind, I could potentially filter our trading signals during slow weeks to see if that would improve performance or perhaps decrease drawdown.

Data leads to information, and information leads to knowledge.  But you can't get there without some work.  So I dug right in and came up against these hurdles.  First, the data is in 12-hour format with a single 12-hour record for Sunday, then 2 records for Monday, etc.  I wanted to combine the data by date, so I imported it into MS-Access and ran some queries:

FROM [EURUSD-Daily-RangePct]
GROUP BY [EURUSD-Daily-RangePct].DayOfWeek;

That query produced the first graph which shows that Sunday evening session is the slowest, with only 0.6 times 1% of an average move.  Monday comes up to just under 0.9 of 1% move followed by higher values on Tuesday and Wednesday and Thursday topping out at 0.98 of 1% and back to 0.82 of 1% on Friday.  So much for the myth that Friday is the most active day of the week.

So with Days of the week tackled, I went onto seasonality.  The way the holidays fall you can't really be sure that active times are going to fall on a specific day of the month, so month's are much help.  I decided to go with this qualifier:


This picks off the "week number" of the year.  There are number of different ways to consider week numbers, but I don't care about the implementation, I just want to see what it tells us.  

FROM [EURUSR-Daily-WeekNo]
GROUP BY [EURUSR-Daily-WeekNo].TheWeek;

This query produced the following table.  There is one column for each week.  As expected the busiest time of the year is actually the 2nd week of the year with average moves of over 1%.  After that, the moves generally decrease then form another plateau around week 40.  The 2nd highest expected move week is week #45 which is late October, early November.   

So now that we are armed with this data, we can calculate our current week of the year and know how much movement to expect the coming week.  We just finished week #36 which ends a period of several weeks with expected moved under 0.9 times 1%.  In the next 3 weeks, we are now expecting generally higher moves of > 0.90 of 1% for the next 3 weeks.

Overall, the seasonality factor was not as great as I expected, at the maximum about 40% of the movement, but on average is was closer to explaining at most 20 or 25% of the price action.  Anyway, I will upload both the MS-Excel file (Forex-Historical.mdb) and the Excel Spreadsheet DayOfWeek-WeekOfYear.xls to by Yahoo Group in case you want to play around with it.

On the topic of Forex performance, we finally had a good week, with nice gains in almost all accounts.  But with the amount of draw down we have seen, its going to take some pretty spectacular gains just to get back to even.   

Its a healthy reminder that Forex is not an easy way to make money versus say equities which at least have a positive historical expectation.  Throw in a decent dividend yields and the expectation is even better.  Makes me wonder why I even bother with Forex.  Except that its a challenge and so much fun.

Have a great week and enjoy upcoming week #37 when we expect 0.92 of 1% average moves for the EUR/USD.