Saturday, March 7, 2009

Sample MQ4 Code

Here is a bit of code that demonstrates what I've been blogging about. It's a simple way to manage pending position requests.

The idea is that a signal his been raised but that this code will let you wait for an improvement in the price before actually opening a position.


// *******************************************************************
// Name: AMS_PEND.MQ4
// Date: 01-Mar-2009
// Prog: Rookie
//
// Desc: A pending position queue manager. Pending positions can be
// held until a period of time or some favorable conditions.
// *******************************************************************
#property copyright "Copyright © 2009, Rookie"
#property link "http://trying-forex.blogspot.com/"

static double pendlask[4096]; // Ask price for a pending long
static int pendltime[4096]; // Time used to calculate pending time
static int pendlqty = 0; // How many items in pendlask queue

static double pendsbid[4096]; // Bid price for a pending short
static int pendstime[4096]; // Time used to calculate pending time
static int pendsqty = 0; // How many items in pendsbid queue

// ****************************************************************************
// Add a pending position entry to the long list
// ****************************************************************************
void addpendl(double ask)
{
static double last = 0;

if ( Time[0] > last )
{
pendltime[pendlqty] = Time[0];
pendlask[pendlqty] = Ask;
pendlqty++;
}
last = Time[0];
}

// ****************************************************************************
// Add a pending position entry to the short list
// ****************************************************************************
void addpends(double bid)
{
static double last = 0;

if ( Time[0] > last )
{
pendstime[pendsqty] = Time[0];
pendsbid[pendsqty] = Bid;
pendsqty++;
}
last = Time[0];
}

// ****************************************************************************
// A simple way to determining if a pending long position should be
// activated.
// ****************************************************************************
int dopendl_simple()
{
int i;
static int this=0;

// Dead simple "drop" style pending manager
// ----------------------------------------
for (i=0; i {
if ( pendltime[i]>0 )
{
if ( pendlask[i] > Ask )
Print("Pending L #",i," ask was ",pendlask[i]," at ",pendltime[i]," now ",Ask);

// Terminate items that don't fire
// -------------------------------
if ( Time[0] - pendltime[i] > 3000 )
{
Print("Pending L #",i," from ",pendltime[i]," cleared due to time ",Time[0]);
pendltime[i]=0;
continue;
}

// Fire first pending item more than N points down
// -----------------------------------------------
if ( pendlask[i] - Ask > 5.0*Point )
{
if ( Bid < iMA(this,this,5,0,MODE_SMA,PRICE_TYPICAL,0) )
{
Print("Pending L #",i," firing");
pendltime[i] = 0;
pendlask[i] = 0.0;
return(1);
}
}
}
}

return(0);
}

// ****************************************************************************
// A simple way to determining if a pending short position should be
// activated.
// ****************************************************************************
int dopends_simple()
{
int i;
static int this=0;

// Dead simple "drop" style pending manager
// ----------------------------------------
for (i=0; i {
if ( pendstime[i]>0 )
{
if ( pendsbid[i] < Bid )
Print("Pending S #",i," bid was ",pendsbid[i]," at ",pendstime[i]," now ",Bid);

// Terminate items that don't fire
// -------------------------------
if ( Time[0] - pendstime[i] > 3000 )
{
Print("Pending S #",i," from ",pendstime[i]," cleared due to time ",Time[0]);
pendstime[i]=0;
continue;
}

// Fire first pending item more than N points up
// ---------------------------------------------
if ( Bid - pendsbid[i] > 5.0*Point )
{
if ( Bid > iMA(this,this,5,0,MODE_SMA,PRICE_TYPICAL,0) )
{
Print("Pending S #",i," firing");
pendstime[i] = 0;
pendsbid[i] = 0.0;
return(1);
}
}
}
}

return(0);
}

// ****************************************************************************
// Algorithm selection point for long position pend processing
// ****************************************************************************
int dopendl()
{
return(dopendl_simple());
}

// ****************************************************************************
// Algorithm selection point for short position pend processing
// ****************************************************************************
int dopends()
{
return(dopends_simple());
}

You'd use code like the following in the start function to see whether or not to add a pending position and whether or not to open a position based on a prior pending position.

int openl;

// See if you have an "open long" signal. If so, add it to the
// queue.
// ------------------------------------------------------------
openl = ...;
if ( openl>0 )
{
addpendl(Ask);
Print("Pending LONG at ask ",Ask);
}

// Now, see if the queue manager suggests it's time to open a
// long position from within the queue.
// ----------------------------------------------------------
openl = dopendl();

// Open a position here if necessary
// ---------------------------------
if ( openl > 0 )
{
...
}

Notice that this design allows you to simply comment out all the pending code and open positions directly from your original signal. This makes it easy to integrate into your own code in case you want to try this in your own testing platform and see how affects your existing EA.

Friday, March 6, 2009

Expert Adviser Weekend

Finally, the weekend is almost here. I've been stealing a few moments here and there during the week but it's not that productive.

Basically, I've limited myself to testing various "opening" strategies. What I've found is that I can increase earnings across the test set -- but generally at the expense of a bigger draw down. I'd like to come up with a system that tests out a tripling of the original account value while only drawing down 10% or less.

If I can create something like that I'll give it a live run.

Interestingly, even when I create something with a massive drawdown and a huge return over a short period, it's still incredibly inefficient. Using the visual testing tool you can always spot opportunities to enter and exit the market profitably that the system completely ignored.

What I expect, once I get that far along, is that I'll open positions under varying conditions. For example, one reason that the trades mentioned above are not done is that the underlying market conditions are deemed risky by my EA. There is nothing wrong with risk it just means you need to manage potential losses better.

So, entering during a less risky period would mean that the position can be given more leeway and presumably be more likely to generate a profit. Entering during a more risky period would entail letting go of more positions at a loss while maintaining a net positive return expectation on those trades.

Lastly, a quick tip. If you minimize the visual display window the tester will run a lot quicker. However, you can then open the window after the run has completed and look at how things progressed. You can have your record and eat it!

Oh, I almost forgot... if you are using the iHighest(...) function, be sure to use the iHigh(...,...,iHighest(...)) value instead of the High[iHighest(...)] value. If you don't you'll be scratching your head wondering why you aren't getting values from previous bars. What a pain in the ass that was.

Tuesday, March 3, 2009

EA Development by Component

Okay, I've got a few EA components under my belt now.

First, I've made myself a trivial system to determine potential entry points. Basically, this system raises a signal when the price is above or below a moving average for some period of time and then crosses over. Remember, I'm only concerned about making an easy to manage framework at this point.

Second, signals raised above are tossed into a queue pending execution. A simple queue manager currently checks whether or not the price has moved lower or higher, as appropriate, and raises what should be considered a true signal if so.

While this seems trivial, I can assure you that it isn't.

Third, I have a position closing module with the job of letting my winners run. While counter-trend trades don't generally run well it can be extremely valuable to let a position accrue for a significant trend lasting one or more days.

This weekend I'll probably try to improve my code, test various strategies in each component, and come up with something that works. Again, I have to stress that if I do find something that works, I won't be telling you about it or selling it to you. I'll be bragging about it and keeping it to myself!

Monday, March 2, 2009

EA Development

I was able to put some serious effort into developing an expert adviser over the weekend. At this stage I believe I can build something that will be both relatively safe and profitable.

This is not an easy task!

Anyway, I do want to assure you that I have no intention of ever selling an EA. If it works I'll use it for myself. If it doesn't work, then I'd have nothing worth selling in any case. Something I might consider, if I can't build a good one for myself, is selling the EA framework that I'm developing.

What do I mean by framework?

I mean that creating a good trading system involves managing a lot of complexity. I intend to create a framework that will let different EA components perform small sub-tasks as part of a larger whole. This framework would make it easier for any programmer to plug in their own components.

For example, I expect that my trading robot framework will include the following independent components:

1) entry point requester
2) pending entry point executor
3) open position analyzer
4) position closer

Entry Point Requester
When I use the visual testing tool provided by MT4 I inevitably notice that my entry points are not optimal. However, it is very difficult to manage an intended entry over time as other entry signals may be generated. The entry point requester will queue up entry signals for further analysis.

Pending Entry Point Executor
Knowing that an entry point signal has arrived, the executor will loop through the pending requests and see whether or not they should be executed. Think about it. Imagine if you forced all entries to be one or two pips better than they are using your current trading tool?

Open Position Analyzer
Okay, now that you have an open position what should you do with it? I find that putting in hard stops and profit points to be less than optimal. For example, if you are in a long term profitable trend it may be advantageous to allow more profit to accumulate.

Position Closer
This portion is relatively simple. If a position is marked as needing to be closed, then it will be closed. Using a system such as this can allow your longer term trades to execute where they need to execute without being concerned about the order entry limitations of your provider.

Good Trading!

Thursday, February 26, 2009

Programming An EA

I'm finding it takes a lot more time to program an EA than I would expect. Alternately, perhaps I am dumb enough to think that I could just throw together some ideas and have a profit machine?

Anyway, after another night of testing I have some new software that is able to detect or indicate various conditions.

I'm hoping that doing enough visual testing will clue me in enough, personally, to the mechanics of price movement, correction and reversal and then allow me to find a way to codify that knowledge. It's pretty tough. However, I guess it's also sort of a holy grail quest. Invent your own money machine -- how often does that happen?

Anyway, some of the things I'm starting to look for are indications that represent shifts in market sentiment on various chart times. Is this curve smooth? Is the rate of change increasing or decreasing? Was that supported on the next higher time frame?

Wednesday, February 25, 2009

MT4 - Moving Average Crossover

Believe it or not I think I'm going to use a simple moving average crossover as a signal for my automated trading system.

Obviously, and testing verifies this, there are two issues to manage:

1) Getting whipsawed.
2) Entering the trend too late.

I believe that I can at least alleviate these issues somewhat. Technical indicators can provide clues about whether or not the market is currently trending -- such that if it isn't trending you can avoid opening positions. Additionally, I believe I can impose restrictions that will greatly reduce purchases near the end of a trend.

Even with these two problems I am able to see spectacular gains temporarily. Trends with few reversals and a slow conversion to the opposite direction yield very high profits... so I can see the potential that is available.

Tuesday, February 24, 2009

Ongoing MT4 Development

As I develop and test more expert advisers I see just how tricky it is to translate common sense into a series of hard and fast rules.

In short, my adviser does stupid things!

When I trade Forex on my own I'll combine a "feel" for the current situation along with some technical indicators. For example, in recent times, if something funny is going on, then the market I'm trading almost always takes an extended dive.

Basically, every time the world goes into a micro-panic things head south.

Anyway, when I program a set of rules I find it will do stupid things. It will not take into account these "feel" issues that let a person "read" the market. The same cold hard logic that has me enticed happens to be a double edged sword.

Anyway, as I mentioned before, I'm a programmer by trade so hopefully I'll figure something out.

Monday, February 23, 2009

MT4 Programming

I love the fact that I can program the MT4 system. However, wouldn't it be nice if there was documentation in English? Well, yes, there is some, but it obviously wasn't written by somebody who speaks it fluently.

Anyway, I spent much of the weekend fooling around with some custom expert advisers. One or two had promise, but obviously if it was easy to do then everyone would be doing it. It isn't. They aren't. I'm not, yet.

What I really need to be able to do is figure out how to determine that a position is not likely to become profitable again. Then, once that is known, it would be nice to look for an opportune time to trim that position. You see, picking a maximum loss generally means that the software will simply allow or force that level of loss.

I have some ideas and the tester is being put through it's paces...

Thursday, February 19, 2009

Automated Forex Trading Robot

I've signed up for a second account. This one is at a broker that uses a dealing desk and an MT4 based trading platform.

Why?

Because I write software for a living. Because I sometimes have a decided lack of discipline. Because my life is stressful and I don't need to be glued to my screen worrying about charts, margins and limits.

No, really, it's because I'd like to think that I can create a program, known as an expert advisor (EA), that will watch the markets for me 24x5 and eek out money with ruthless disregard to extraneous factors. No need to sleep. No need to eat. No ability to be distracted by anything at all.

A mindless devotion to price action, indicators, and limits. No if's, and's or but's allowed.

Perhaps I'll have the time and energy to put something together this weekend?

UPDATE: Also, an automated system won't select the wrong currency or the wrong trade size because it is in a hurry to get to the bathroom!

Tuesday, February 10, 2009

Infrequent Nibbles

I'm getting into this small position size infrequent trading style.

For example, with a pittance of my capital at risk I am earning nearly a 5% annual return. What am I trading? I'm holding the ever popular AUDJPY carry trade pair of course.

Even with the recent wildfires in Australia I really don't see them falling off the map completely. Come on, realistically, how low can their dollar sink? Now that it is at these very low levels any given change in pips is magnified in terms of percentage moved. This gets amplified as the AUD falls relative to the JPY.

So, I have my average position displayed on my chart. When possible I'll try to snap up a small position when the price is relatively low. When it is relatively high I'll do the opposite. By this, I mean that I'll sell a position that was opened above the average price and take a profit.

At the same time, I'll pump a small amount of additional capital into the account on a monthly basis to ensure that I never have a significant total percentage of account value at risk. Given the economic mess that we are in I see this as a long term play measured in years.

Tuesday, February 3, 2009

Not Enough Time To Trade

Well, my days have become very busy as of late. I go to work early, come home late, and need to get some sleep when I am not swamped with the normal day to day duties of life. I need time to cook and clean, pay the bills, service the car, look after my home, watch the superbowl, do laundry, and so on.

While I've been making money I certainly am not making enough money to hire someone to look after all my day to day tasks.

Okay, enough whining! What, you may be asking, am I going to do about this?

I'm going to focus my energies on my job. It's interesting, pays well, and I can't afford to ignore it in the current economic situation. This means that I am going to scale back the amount of time I can trade.

To put it concisely, I'm going to trade very small position sizes and look towards lowering the average price of my open positions. This means checking my account once in a while, taking profit when I'm ahead, and opening more positions when I am behind. As a hands-off trader I'm going to have to trade in small amounts and make sure I have the longevity to wait for days at at time for a swing to give me some profits.