Showing posts with label mt4. Show all posts
Showing posts with label mt4. Show all posts

Saturday, October 13, 2012

Robot Thoughts

It's getting easier to look at a chart and figure out what to do. For example, recently I've been using bollinger bands on the D1 and trading infrequently when something presents itself.

It's more difficult to turn this intuition into an algorithm and quantify it. I suppose I need to come up with clever ways to localize a local bottoming or topping event and then characterize the shape of it.

What I am relatively good at is finding moments of extreme extension. Unless a major new trend is about to occur these can indicate reasonable entry points. For example, if the price is getting "far" away from a moving average and price action is respecting a boundary or throwing a good candlestick event then a robot can take action based on well defined situation.

There are also "warnings" available. If the price is moving very fast then what is considered a good entry point may be a lot riskier. This type of thing can be examined across multiple time frames to detect a larger scale event while trading on lower time periods.

The latest thought and robot experiment is to collect these little nuggets of interpretation. Accumulate the "value" of a list of reasons that it looks like a good time to trade and compare to the "value" of those reasons that a trade should not be entered.

To illustrate, let's assume our robot is "thinking" about entering a long trade on the USDJPY pair:

  • Bid price is 8 pips below the m15 moving average (+ 0.08)
  • Bid price is touching the lower h1 bollinger band (+ 0.10)
  • Bid price is within one pip of middle h4 bollinger band (+ 0.05)
At the same time we have some hazards:
  • The h1 bollinger band was recently pinched
  • The previous m15 candle dropped 25 pips
Well, never mind then, a nefarious "something" is happening that the robot should have the sense to realize it doesn't understand. Wait for a clearer situation.

Perhaps many robots would be better than people expected if they were able to look for more reasons not to enter a trade?

Tuesday, April 28, 2009

MT4 EA: Stupid Programming Mistakes

Well, I spent last evening tracking down some problems in my next foray into programming expert advisers.

It turns our that a simple logical test was using an '&' instead of an '&&' between two terms.

This little horseshoe nail caused some position closing attempts to fail with an error 138 -- meaning that the price being used to close the position was too far away from the market price.

I also ran into the example code for iHighest() again. The example shows it implemented with High[iHighest()] when you generally may want iHigh(...,...iHighest()) instead.

In all, I find programming in MT4 a bit frustrating. Sure, sure, hard core programmers may blame me for being imperfect, but it's time programmers realized that humans are imperfect. I know -- I program for a living.

Sunday, April 26, 2009

MT4 EA: Moving Towards Sustainability

Yesterday's experiments with creating an expert advisor to scalp the 5 minute chart show great profits and great risk.

I've been working to reduce the level of risk without taking away the reasonable chance of making reasonable profits.

Here is the most recent chart:


This is running from 01-Feb-2009 to 25-Apr-2009 and obviously surviving any ups and downs during that period.

I'm still not happy with the relative size of the larger draw downs. I believe I can tune it but I'll want to add back aggressiveness or the growth will start to drop more than I'd like.

... continuing ...

Alright, I'm in danger of curve fitting, but I've tuned the advisor to take less risk and earn less profit. However, right now, the earnings curve is getting near ideal. The draw down is acceptable and the profits are around $4,000 per month. Of course, remember that this is all somewhat theoretical and running in a test environment.


The question on my mind is whether or not I can somehow turn up profits without creating larger draw down. It's not easy but I'll fool around some more and see where I end up.

... continuing ...

Increasing aggressiveness did not help. Various other modifications were also unsuccessful.

I've run this starting 01-Nov-2008 and it dies a horrible death. This is not surprising, but it does imply you'd need to know when things were going horribly and stop it. If you are able to manually ascertain that the market should only be moving upwards then this EA should do okay. It only opens long positions.


Is it (ea 2009-04-m5-6.mq4) worth a try?

Saturday, April 25, 2009

MT4 EA: Aggressive 5 Minute Scalper

Well, it's the weekend, what else is a grown man to do?

I had an inspiration for an (overly) aggressive expert advisor today. Basically, it's a simple buy low and sell high machine using oscillators.

Scope out the chart. It does fairly well for a period of time and then when the market finds it's achilles heel it is undone.


All is not lost. I have some ideas for improving the aggression factor as well as tinkering with it's currently abysmal "take a loss" strategy.

... continuing ...

Theoretically, you could take out $1,000 per day and end up with more money than you started with. It ran for 20 days (01-Apr to 20-Apr) before it's massive death spiral.

... continuing ...

Check this out. By adding a pending purchase system to delay early purchases until the price is a bit better as well as turning off loss sales (a bad strategy to be fixed up soon) we get the following.


The balance, actually I mean equity, is over $77,800 by the 16th in this run. Certainly more profitable than last time around. If we can get an intelligent way to cut losses we might be able to reduce the risk of catastrophe.

... continuing ...

I'm also running on various different time periods to make sure I'm not just optimizing for a certain month. That would not be good.

... continuing ...

Okay, after some tinkering, the system is living through a three month period, but obviously there is a tradeoff involved:


This is 01-Feb-2009 through 25-Apr-2009. There are a couple of scary draw down events and a final equity of around $56,000. So, again, in theory, at about $15,000 of profit per month you could withdraw about $500 every day and calculate the likelihood of scarfing away more than $10,000 before the system has a fatal event.

Unfortunately, removing equity will make it more likely to crash during a draw down situation. Perhaps withdraw at a slower pace? More realistically, I'd like to find a predictor for the draw down events and reduce them. This would reduce overall profit but perhaps the system could trade more aggressively if the draw down situations could be avoided.

Time to look at the reports to find the important dates and then look at the historic data in various time frames.

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!