24 October, 2009

To back test

To have a legit and more accurate backtest, you got to have enough history data in your platform in order to perform a good backtest. Press F2 on your keyboard, MT4 will automatically direct you to a history centre. Select a symbol you wish you backtest, in this case we use GBPUSD as our test. Double click on GBPUSD, system will drop down several timeframe. Double click on 1 minute(M1), then hit Download button. MT4 will download as much history data as possible from Meta Quotes Corporation.

Once download completed, you'll be able to see something similar to the above. This can apply to other currency pair. If you wish to backtest with other symbol, simply repeat the procedure on other symbol's 1 minutes (M1) data. Click close button to close data center. Hold your "Control" button and press "R"(Ctrl+R), this will call out the tester window at the bottom of MT4.


Here is a brief introduction for each function in the tester:
Expert name: You can change any expert advisor to test with
Symbol: Currency pair you wish to test with
Model: Normally we use every tick as the quality of backtest is more reliable. You can choose other type of modeling, but less accurate.
Period: Time frame to test with (1 minute, 5 minutes, 15 minutes, 30 minutes, Hourly...etc)
Expert properties: Allow you to change settings on the EA
Symbol properties: To show you the testing environment of the currency pair you wish to test with
Open chart: Once backtest finish, by clicking this button, you'll be able to see all the trades placed on the chart.
Modify expert: MT4 will call out Meta Editor and immediately open the source code of the EA for your convenient to modify codes.

Below are screenshots for Expert Properties:


The above shows Initial deposit as 10000. It means the backtest should start with initial balance of 10k. Position Long & Short meaning both buy and sell are allowed. You can choose either buy only or sell only.


Above screenshot shows the input tab in Expert Properties. You can change the parameter of the EA for this particular backtest. In this case, we change the stop loss to 200pips from original 50pips. You can Save your parameter by clicking "Save button" or load a preset you've previously saved. Once completed setting up parameter, click OK button to exit.


Back to tester main window. Select the date of testing. From ~ To must be complete. Now, you can enable Visual mode. By enabling visual mode, you'll be able to view the trades on the chart whilst the tester is doing all the calculation at the background. Visual mode is obviously slower compare to non visual mode. Or you can choose to run a quick backtest without visual, and click on the Open Chart button later to view the trades offline. Click on Start button to begin backtest.

After the test, you can go to Report tab at the bottom of the tester window. You'll be able to see the full detail of the backtest. You can right click on the report and choose Save Report to get a full HTML report with equity graph in it. If you notice, there are 2 important column in report. Mismatched charts errors is the number of bars you downloaded from history center does not match with the visual on the chart. Many reason causes this, such as difference of brokerege firm's rollover time, data corruption, data overlapping and so on. With a bad history data, automatically your Modelling Quality will drop. Normally 90% is good enough and very acceptable. However, there are professionals that uses TICK DATA to produce 99% accuracy backtest result. There is a whole bunch of knowledge in collecting good quality tick data and how to import them into Meta Trader 4 to do backtest with Expert Advisors. I have not plan to extend our focus that far, let's just stick with this for the time being. Meanwhile, if you're interested in 99% backtest, you can search online.

The above equity graph are generated automatically from the backtester after I ran a 3 month backtest on GBPUSD.

18 October, 2009

Magic number

OK. Let's talk about trade handling. This EA was made to trade alone, and not suitable when there is human interference or other EA trading on the same account. When you try to place a trade on the account with MACD Sample trading at the same time, the EA will take over your position and modify your stop loss according to the TrailingStop you've declared in the EA earlier. Which is why a Magic Number is important. We need a special tag for a robot to recognize which are the trades that they should handle, instead of modify all stop losses for all the trades on the same platform. So, here we go...


Place a new external variable for user to key in Magic Number for the EA to recognize it. Magic Number is a special tag that doesn't show on your trading statement because its hidden. Since we're doing Magic Number, I've take another step to pull out the trade comment. By putting the trade comment as a variable, this can help us trace our trading history. In example, while we're modifying the EA from version 001 until current version 004, we have trouble to figure out from where our EA evolved. By looking at the trading statement, scroll all the way down, all the trade comment saids the trades are triggered by "macd sample". Therefore, in the future we can change the trade comment directly from the variable everytime we modify the EA.

Magic number had taken over the original fixed magic number 16384. Meanwhile, trade comment will automatically refer to the variable we've declared earlier.

Added new filter here. Whilst the EA trying to filter out all the trades from the same pair(OrderSymbol()), we've added new Magic Number as new filter for the EA to recognize which are the trades needs to handle instead of handle all the trades from the same pair.

04 October, 2009

Been busy lately

Hello there. I've been busy lately. Have not been able to update the blog. I'm sorting things out and will continue to blog as soon as possible. Here is what happened to me while I'm not around:

18 July, 2009

An efficient way to declare SL and TP

Previously we have discussed about how to put down a stop loss in the EA. Now, it is time to further improve it. Originally, the EA came with fraction variable declared on its Take Profit column. The reason for using "double" in the code is to hold the value of market price, such as bid on EURUSD as 1.4002. Previous code explanation as below:

Ask+TakeProfit*Point = Actual take profit
1.4002 + (50pips * 0.0001) = 1.4052

And therefore the EA will put down 1.4052 as our take profit. Here is the problem. What if we revalue the parameter of Take Profit as ZERO? Further elaboration as below:

Ask+TakeProfit*Point = Actual take profit
1.4002 + (ZERO * 0.0001) = 1.4002

Now, I doubted what is the purpose for you to trade something stupid like opening and close trade at breakeven? I even doubted whether your broker is going to allow you to do so. Most broker has the minimum 5pips limit between their order open price and their take profit/stop loss... hmmm... here is what I did. Change it from "double" to "int", add new variable as SL and TP to accommodate the actual value of the price we want to take profit and stop loss.



Screenshot above is showing how I declare my new variable. I've added "//" to remark the old codes.


2nd screenshot. I've removed the TakeProfit checking routine. We will check the take profit value later.



Here is the screenshot I added the new set of codes to allow 0 stop loss and 0 take profit to the system. The logic as below:

StopLoss=50
if StopLoss>0
Ask-StopLoss*Point = SL
1.4002 - (50pips * 0.0001) = 1.3952
Otherwise
SL = 0

Now we have a real 0 Stop Loss.



Here is the set of code I added to sell position.

27 May, 2009

To put down a stop loss

MACD Sample EA is a swing trading system. However, this swing trading system doesn't come with a stop loss. Its either you get it right on your buy position, you sell off at higher price to make money; or you got it wrong on your buy position, then you get a sell signal at lower price. So, you can choose to put down a stop loss in order to limit your losses when thing goes wrong.
Place these codes into your MACD Sample EA.

By adding extern in the code, you'll be able to control the external panel. StopLoss is the variable name. double in the code will allow the StopLoss variable to store fractional figures. We temporary put 50point as the default figure. Anytime when you load the EA on the chart, your default TakeProfit and StopLoss will be 50.



We have defined the parameter. Now we add an extra code into the OrderSend() function. OrderSend fucntion work with these element:
Option = OP_BUY,OP_SELL,OP_BUYSTOP,OP_SELLSTOP,OP_BUYLIMIT,OP_SELLLIMIT
Lot size = Any figure your account able can trade
Order open price = Ask for buy, Bid for sell, or put down a figure if you want to use pending order
Slippage = How many point of slippage allowed
Stop loss = The price when you decided to cut loss
Take profit = The price when you liquidate your profit
Trade comment = To put down a comment on your trade in order to recognize them traded from which trading system
Magic number = Any integer figure. This is for the EA to recognize its an auto trade instead of trader's manual position
Expiry date = Trade will be close after exceeded this amount of time.
Color marking = Trade will be indicate on the chart. Choose a color to represent your buy/sell position, inorder to recognize them in the future.
Original code came with 0 stop loss, so we added some code for this system to recognize a new stop loss we added earlier at the external panel.

26 May, 2009

To do list

A back test does not mean anything, until an EA start making money in your live trading account. Again I would like to emphasize the fact that I mentioned previously, I'm not going to put my hard earned money into something I don't even know what is inside it. So, we are going to explore bit by bit in the MACD Sample EA, at the same time combine some useful codes to improve it. I'll list down our to do list here, and we are going to follow the list and modify this EA step by step to make it more stable and reliable.

1) To have stop loss where MACD Sample did not build in readily
2) To have control number of trades allowed at the same time
3) To avoid the EA to manage human trades and or other EA's trades
4) To include a simple money management into the EA
5) To clean up some codes to make the EA more efficient
6) To optimize the parameter uses by the EA

Now we have a plan. We are going to follow it and improve this EA step by step

24 May, 2009

FREE profitable robot?! Where?!

If you are not familiar with any of Meta Trader 4 and their FOREX automated trading system, this is a good time to start learning and understand what is actually happening. On the other hand, if you're an experienced trader, or you have very much experience in using other people's Expert Advisor(automated trading system) in the 1st place, I hope you find this is interesting because you're about to learn to develop your own system. You will never have to blackbox trading an EA you bought from ebay. Without knowing what is inside the bought EA, I have never feel comfortable to put down my hard earned money with these commercial EA.

Here is the deal. We're going to review the MACD Sample.mq4 from Meta Trader 4. You can find it freely available after you installed MT4. You may be getting ready to pay some money to buy a new EA from ebay, please hold the horses, because we may have something really worthwhile, and the best part of it is... it is FREE. You may think there is no free lunch, neither do I think there is free lunch. Therefore, we are going to have to do some work here. I've downloaded some history data from the broker and ran some test on it. You can download history by pressing F2 to get the history center.

Above screenshot showing bad data in USDJPY. You can notice that when you see only 1024 record existing in your computer. You'll have to click on the Download button to download history data from your broker.

Now, once download completed, MT4 will automatically extract all the downloaded file and import them to your platform. With these downloaded history, you'll be able to backtrack history as far back as 1999. Hold your Ctrl + R to access to your Tester window. Select Expert Advisor: MACD Sample, then Symbol change to the downloaded data. My case is EURJPY because I downloaded it. This is a crusial part, you can choose different type of modelling quality. I only use Every Tick as my modelling quality, as they provide the most precise test compare to real time trading. Finally, check the Use date box, fill in the column with desired testing date. Hit the start button and wait for it to finish testing.


Once test completed, you'll see the green indicator bar had filled up the entire column. And the Stop had changed to Start button again. Tabs at the lower tester window are for different function. You can view the tester graph, trade's detail, statistic report, and your trade journal.
-Settings is the main console to control your testing parameter.
-Results will show the trade's detail. From what price trade got opened, trade parameter modifications, take profits and stop losses.
-Graph will show the equity in 2D line chart
-Report is where the statistics are.
-Journal can be very useful to troubleshoot if an EA have error. Basically it record all trades in and out.


To generate a full report from your backtest, hit the Report tab in your tester window, right click in any column within your statistic report, select Save and report, and it will direct you to a file save window. Select your folder and it will save a copy of the tester report and open it up with your web browser as HTML format. Its very useful and handy.

So, here is the complete backtest of 2006 data on EURJPY with MACD Sample. Its FREE. This EA is not ready to use in my opinion. So, we're going to add in some parameter to ensure this EA is safe to use.

23 May, 2009

Meta Editor 4

Meta Editor 4 is the official programming platform for Meta Trader 4. It uses 3rd generation programming language, and very similar to C language programming, and they named it Meta Quotes Language 4. Anyway, from what I heard, MQL4 will be replace by MQL5 in near future. For me, its still too early, until they have finalized, launched it a year or two, then I'll consider to migrate to 5.


So, how do we get into Meta Editor? Its simple, by clicking the icon shows at the above picture, you'll be able to access to programming platform. I'm currently drafting on what kind of syllabus we should cover in the coming weeks. There will be a lot of mind blowing things, and I am going to reveal them to you one by one. You'll be able to understand exactly what is worth and what is not. I'll probably start with basic programming guidelines. Then to modify a readily made Expert Advisor in Meta Editor 4. In very short time, you'll be able to understand how does an EA work. You'll be able to program your own indicator/trading discretion in a template provided by Meta Editor 4.

I work with Meta Trader 4

Here is another infamous trading platform provided by Meta Quotes. Some of you may found this platform very useful because they also provide a platform for your iPhone and PDA. I will try to shorten the introduction for this trading platform, as they have too many function, some of them I do not even know how to use them. Basically, I like this platform because its free to use. Data feed from broker are always free. The most important is, I need their automated trading system facilities. I will be focusing on this 1 in the near future, to build a trading robot in an open blog and it will be free for the public to use it. You'll be able to understand the basic programming in automated trading system by following this blog.

The layout of MT4(Meta Trader 4) is very simple and easy to understand. The Navigator window will show you whether you're on a demo/live trading account. A demo account, the icon is in green color, or it will be gold in color if its a live account. Terminal window is where all your trade statistic situated. All your buy/sell orders will be situated here. The above screenshot shows I'm lossing 14pips. Quote board is in the Market Watch window. By double clicking the Bid/Ask price of desired trading pairs, the trading window will pop up.


This is a order window. You can key in your trade parameter here like lot size in Volume column, your stop loss, take profit and also comment on your trade. Finally, by clicking Sell/Buy button to execute your position instantly.

You can choose to place pending order by changing the value in Type column to Pending Order. You can place your execution price, and other parameter just like a market order. Some of you may not understand how pending order works. I decided to touch up a little bit here:

Buy stop : When current ask price is lower then your desired buy price
Buy limit: When current ask price is higher then your desired buy price
Sell stop: When current bid price is higher then your desired sell price
Sell limit: When current bid price is lower then your desired sell price

There is 1 very useful column here. By ticking the Expiry column, you can also put an expiry date to your pending trade. After the expiry, trade will be automatically deleted.



The best part of Meta Trader 4 is to have an investor password. If you are having a share account, or managing other's account, you can always publish your investor password. By accessing to the account with investor password, you can see all the running trades on the chart. All statistics are available. The only thing that the investor couldn't do is to execute any transaction.

21 May, 2009

What is trading platform

Trading platform is the software where you execute your buy/sell order. You can put a stop loss / take profit point for the future reference. For example if you bought some gold for the price of $50 from your local goldsmith, you intended to sell it when the price got up to $75, but the thing is, you'll have to monitor the gold price every minute, otherwise you will miss it. Good thing is, when price exceeded your expectation, you'll get more. What if price already hit $75, and you are not around / not aware? Price could fall down again, and you missed the opportunity to make a nice profit by selling the gold you bought earlier with $50 for $75. This is where the trading platform play a role. You can set your target accordingly. When the market price meet your expectation, your transaction will be auto executed in split second. You will never have to worry about missing a transaction anymore.

Basically, you can have different type of trading software with you. Below is a series of screenshot I took from OANDA trading platform. Its a JAVA edition trading software. This is a very useful trading platform, offering trade from chart function.

Candlesticks chart:

You can add different studies in the chart to survey current market condition/trend. I have included RSI, Stochastics and MACD to it.



Account statistics and quote board:

Upper part of this screenshot is my account statistics. The quote board are updating currency price real time by the data feed by broker. Green color indicate up; Red for down; Grey for unchange.

How to trade?


You'll need to understand the quoteboard before you make any transaction. Your tradeboard normally consist of 2 major element, Buy/Sell price, some broker preferred to use Bid/Ask price. Basically these 2 represent the price of a certain currency pairs buying and selling. At the above/side of the quote board are normally the currency name. EURUSD meaning EURO vs US Dollars. The number is representing the actual price of US Dollars exchanged with EURO. The above example shows:

Buy 1 EURO with $1.38102
Sell 1 EURO with $1.38093

Meaning that, even if I buy and sell at the same time, I will still make a loss of $0.00009. Where does the money goes? You're right, my broker need that money to pay their employee, their electricity bil, and ofcourse to pay their boss Rich Olsen

20 May, 2009

Something about my work

My name is David Lai a.k.a davidke20 in forums. I'm a part time foreign currency trader(FOREX trader). Working full time like a donkey day time, taking care of the kid after work, do some codings after family asleep. Most of the time I past out infront of my computer screen while coding some trading system.

What is FOREX

FOREX is the short form of Foreign Exchange. This is the world largest financial market. According to Bank for International Settlement, the currency trading involved of daily 3.2 trillion(3,200,000,000,000.00) dollars turnover. Full article can be found here. FOREX is an investing opportunity, one that can bring an investor profit or loss. FOREX is a volatile market intensified by leverage. Money is made(or lost) when investment values fluctuate. Although a market that moves up and down like a roller coaster can be nerve wracking, it also offers more trading opportunities.

In the 1990s. The currency markets grew more sophisticated and faster because money, and how people viewed and used it, was changing. The notion that money was not just a piece of paper, but also something that could assume electronic form, was accepted fitfully by the public. Today money has moved beyond paper. By depositing a certain amount of money to your retail broker, you can start trading one click basis in front of your desktop. The internet provides rates and price spreads virtually instantaneously, 24 hours a day, seven days a week. You can download a free trading platform, install them on your computer. Thats like having your own currency board infront of your computer, just exactly the same as the money changer you found in your local shopping mall. The only difference is, you get faster response, more accurate pricing compare to them. You can download the software here, its called MetaTrader4. Feel free to pass it around if your buddy is interested on this.

The reason of the existence of this blog

To be honest, I wish to understand how blog works. Meanwhile, to earn a few penny from the clicks paid by AdSense. This blog will be maintain as a trading and on going automated trading system developement journal for my own pleasure, and possibly will be my stepping stone to my next business.