Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Hammer of Thor Forex Expert Advisor for MQL4 Development

The Hammer of Thor Forex Expert Advisor is an introduction to building your own “Trading Robot”.

The purpose of building the Hammer of Thor Forex Expert Advisor is just to serve as an introduction to how an MQL4 program can be structured.  It’s designed on the simplest level for the purposes of teaching you how to build an algorithmic trading Expert Advisor in the MetaEditor of MetaTrader 4.  The simplicity, templated design, and plug and play nature to it will help you backtest indicators, basic strategies, and different forms of technical analysis.  It is important to once again note that the creation of the Hammer of Thor Forex Expert Advisor is for the purpose of enhancing your coding knowledge, not for the purposes of actually being used in live trading.

Accessing MetaTrader 4’s MetaEditor

Hammer of Thor Forex Malaysia

It’s not too difficult to access the MetaTrader 4 MetaEditor, it’s on the toolbar.  To get to it, just click on the post-it note icon that is in between ‘New Order’ and ‘AutoTrading’.

MetaEditor’s Appearance

Hammer of Thor Forex Indonesia MQL4

If it is not obvious, there are a bunch of Expert Advisors that were made for the purposes of testing.  There are all sorts of MQL4 files here.

Starting from Scratch with MQL4 and Building The Hammer of Thor Forex Strategy

So you are going to build your first Expert Advisor.  This experience will change the way you look at trading forever because you will be in a position to test all sorts of strategies.

The process starts by clicking the ‘New’ icon.

Hammer of Thor Forex MQL4

This screen appears with different options as far as what you want to build.  In this case, you’re building The Hammer of Thor Forex Expert Advisor.

MQL4 Wizard

The ‘Expert Advisor (template)’ will be the choice you select with the radio button options.  Then you click ‘Next >’.

MQL4 Expert Advisor

The name of the file comes after Experts, so just name it in this case ‘HammerOfThor’.  The author is YOU, so put in your name or your company’s name.  The link is purely optional, but we put in the Freevestor Home Page.  Parameters are not necessary.  After all of this click ‘Next >’.

MQL4 Event Handlers

Feel free to click ‘Next >’ through these options above while leaving everything unchecked.  You’ll do the same thing with the Tester event handlers as illustrated below.  Just click ‘Finish’ and move on.

MQL4 Tester Event Handlers - Hammer of Thor Forex


//+------------------------------------------------------------------+
//| HammerOfThor.mq4 |
//| Freevestor |
//| https://freevestor.com |
//+------------------------------------------------------------------+
#property copyright "Freevestor"
#property link "https://freevestor.com"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---

//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---

}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---

}
//+------------------------------------------------------------------+

Now do not worry if your background is not black or that the code highlight colors do not match.  MQ4 files are not mainstream like C++, Python or PHP, which means that showing the code in a neat and organized fashion may not necessarily match the experience in the MetaEditor.  Don’t worry, everything is fine.

Time to Edit the Barebones Code Considerably

Starting piece-by-piece here.  Before the Expert Initialization Function, there’s a global variable section.  These can all be edited in the Strategy Tester and in The Hammer of Thor Forex Expert Advisor as part of the loading process.

What would we look to have as the variable inputs?

  • Lot Size:  Decimal amount of Standard Lots
  • Take Profit:  Number of pips to Take Profit point
  • Stop Loss:  Number of pips to Stop Loss point
  • Magic Number:  Identifies orders, can be any number chosen
  • Slippage:  Number of pips to allow for slippage of price

Establish that pips can have a decimal amount like 30.0 or 2.4.

//+------------------------------------------------------------------+
//| HammerOfThor.mq4 |
//| Freevestor |
//| https://freevestor.com |
//+------------------------------------------------------------------+
#property copyright "Freevestor"
#property link "https://freevestor.com"
#property version "1.00"
#property strict

extern double LotSize=0.03;
extern int TakeProfit=60;
extern int StopLoss=30;
extern int MagicNumber=3232;
extern int Slippage=3;
double pips;

Above are the established global variables for the entire program.  However, there is much more code to add to this.  The nice part is that once you understand what the code does and what code to include, future programs are as simple as editing global variables and editing a portion of the Expert Tick Function.  The next part to building Hammer of Thor Forex Expert Advisor?  The Expert Initialization Function.

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---

double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
if(ticksize ==0.00001 || ticksize == 0.001)
pips = ticksize*10;
else pips = ticksize;

//---
return(INIT_SUCCEEDED);
}

In this section, you are inserting the portion in between the — and the //.  It’s a vacant space that is to be filled while the rest remains untouched.

What you are establishing is the size of a pip.  Pips are not all uniform in size as currency pairs come in two types.  The first example in the ‘if’ statement above is what is used for all currency pairs except for those that involve the Japanese Yen.  The second example, which comes after the ‘or’, which is ‘||’ in MQL4 is what would be used for currency pairs that involve the Japanese Yen.

What is nice is that after placing this in there, you do not have to touch it ever again.

What’s next?  The Expert Deinitialization Function.  The good news is that we’re leaving it alone for the Hammer of Thor Forex Expert Advisor.

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---

}

The next part is the longest, it is the Expert Tick Function.

In this section, it is like making a sandwich.  The beginning and end of the code are the sourdough bread that holds everything together.  You are establishing the new candle function.  Taking action on the new candle rather than placing a trade on something that happened in the recent or far out past.

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(IsNewCandle())
FadeBreak();

//---

}

//+------------------------------------------------------------------+

//Ensuring it is a new candle function.

bool IsNewCandle()
{
static int BarsOnChart=0;
if (Bars == BarsOnChart)
return (false);
BarsOnChart = Bars;
return (true);
}

We’ll be looking to occupy the area between these two parts with code, but before we get to the dynamic part of the code that makes the Hammer of Thor Forex Expert Advisor what it is, there’s another important element to add – Order Entry.

There must be a Buy Order and a Sell Order.  Given that the trades are being placed with an ECN broker, the structure of the code is a bit different from what you would see in many Expert Advisors.  In this Expert Advisor, there is one trade being made at a time, which means that simultaneous positions are not held.  Either the position goes to the Stop Loss or it reaches the Take Profit.

void OrderEntry(int direction)
{

if(direction==0)
{
double bsl=0;
double btp=0;
int buyticket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,Slippage,0,0,NULL,MagicNumber,0,Green); //Buy Order w/ TP/SL;
if(StopLoss!=0)bsl=Ask-(StopLoss*pips);
if(TakeProfit!=0)btp=Ask+(TakeProfit*pips);
if(OpenOrdersThisPair(Symbol()==0)) buyticket;
if(buyticket>0) OrderModify(buyticket,OrderOpenPrice(),bsl,btp,0,CLR_NONE);
}
if(direction==1)
{
double ssl=0;
double stp=0;
int sellticket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,Slippage,0,0,NULL,MagicNumber,0,Red); //Sell Order w/ TP/SL
if(StopLoss!=0)ssl=Bid+(StopLoss*pips);
if(TakeProfit!=0)stp=Bid-(TakeProfit*pips);
if(OpenOrdersThisPair(Symbol()==0)) sellticket;
if(sellticket>0)OrderModify(sellticket,OrderOpenPrice(),ssl,stp,0,CLR_NONE);
}
}

int OpenOrdersThisPair(string pair)
{
int total=0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()== pair) total++;
}
return (total);
}

What are the “0” and “1” supposed to mean as far as direction?  That’s the directive to buy or sell and this is connected to ‘if’ statements established in the most intuitive part of the Hammer of Thor Forex Expert Advisor code.  The best part is that if you want a program that keeps open one trade at a time and is a plug-and-play Expert Advisor solution, you do not have to mess around with this part of the code at all.  You can literally copy and paste most of the code and just edit the Global Variables and the Conditional Statements, which were about to get into here.

Why is this called the Hammer of Thor Forex Expert Advisor?

It is called Hammer of Thor Forex Expert Advisor because it uses Bearish and Bullish Hammer Candlestick Patterns and Bearish and Bullish Inverted Hammer Candlestick Patterns.  We don’t like the term ‘Hanging Man’, which is just gruesome.

void FadeBreak()
{

//Bullish Hammer - Bullish Reversal
if((High[1]==Close[1])&&
(((Close[1]-Open[1])*2)High[1])&&
(OrdersTotal()==0))
OrderEntry(0);

//Bearish Hammer - Bullish Reversal
if((High[1]==Open[1])&&
(((Open[1]-Close[1])*2)High[1])&&
(OrdersTotal()==0))
OrderEntry(0);

//Inverted Bullish Hammer - Bearish Reversal
if((Low[1]==Open[1])&&
(((Close[1]-Open[1])*2)Open[2])&&
(Close[3]>Open[3])&&
(High[1]>High[iHighest(Symbol(),NULL,MODE_HIGH,15,2)])&&
(BidOpen[2])&&
(Close[3]>Open[3])&&
(High[1]>High[iHighest(Symbol(),NULL,MODE_HIGH,15,2)])&&
(Bid

The Hammer and Inverted Hammer are used in a fashion to encourage reversals.  The price would reverse course on the Hammer and Inverted Hammer.  Notice how this portion of the code involves the requirements that are found with the elements of the price itself.  Close, Open, High, and Low are all components of the price.  The [1] means that the price is the previous bar, the [2] means that the component of the price is the second-to-previous bar, and the [3] means that the price is the third-to-previous bar.

When you code in the MetaEditor, you’ll notice that there are semi-instructional reminders of what to fill in each of the functions.

If you need help with any of the functions or just in general with MetaEditor, just press the F1 Button.  You will get more details about the functions or parameters.

If you want to use it or save your progress and see if there are any errors in your code, just click ‘Compile’ on the Toolbar.  If you see Yellow triangles like below, do not be alarmed.  They do not mean that there is anything wrong with the code in terms of its execution capability.  The line and column will tell you where the Warning (yellow triangle icon) or Error (would be with a red icon with a line through it) is located.

An error in compilation would look like this.  Errors are bad, Warnings are not a problem.

Hammer of Thor Forex Expert Advisor

//+------------------------------------------------------------------+
//| HammerOfThor.mq4 |
//| Freevestor |
//| https://freevestor.com |
//+------------------------------------------------------------------+
#property copyright "Freevestor"
#property link "https://freevestor.com"
#property version "1.00"
#property strict

extern double LotSize=0.03;
extern int TakeProfit=60;
extern int StopLoss=30;
extern int MagicNumber=3232;
extern int Slippage=3;
double pips;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---

double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
if(ticksize ==0.00001 || ticksize == 0.001)
pips = ticksize*10;
else pips = ticksize;

//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---

}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if(IsNewCandle())
FadeBreak();

//---

}

void FadeBreak()
{

//Bullish Hammer - Bullish Reversal
if((High[1]==Close[1])&&
(((Close[1]-Open[1])*2)High[1])&&
(OrdersTotal()==0))
OrderEntry(0);

//Bearish Hammer - Bullish Reversal
if((High[1]==Open[1])&&
(((Open[1]-Close[1])*2)High[1])&&
(OrdersTotal()==0))
OrderEntry(0);

//Inverted Bullish Hammer - Bearish Reversal
if((Low[1]==Open[1])&&
(((Close[1]-Open[1])*2)Open[2])&&
(Close[3]>Open[3])&&
(High[1]>High[iHighest(Symbol(),NULL,MODE_HIGH,15,2)])&&
(BidOpen[2])&&
(Close[3]>Open[3])&&
(High[1]>High[iHighest(Symbol(),NULL,MODE_HIGH,15,2)])&&
(Bid0) OrderModify(buyticket,OrderOpenPrice(),bsl,btp,0,CLR_NONE);
}
if(direction==1)
{
double ssl=0;
double stp=0;
int sellticket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,Slippage,0,0,NULL,MagicNumber,0,Red); //Sell Order w/ TP/SL
if(StopLoss!=0)ssl=Bid+(StopLoss*pips);
if(TakeProfit!=0)stp=Bid-(TakeProfit*pips);
if(OpenOrdersThisPair(Symbol()==0)) sellticket;
if(sellticket>0)OrderModify(sellticket,OrderOpenPrice(),ssl,stp,0,CLR_NONE);
}
}

int OpenOrdersThisPair(string pair)
{
int total=0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()== pair) total++;
}
return (total);
}

//+------------------------------------------------------------------+

//Ensuring it is a new candle function.

bool IsNewCandle()
{
static int BarsOnChart=0;
if (Bars == BarsOnChart)
return (false);
BarsOnChart = Bars;
return (true);
}

Hammer of Thor Forex Expert Advisor will get you started on your path to developing and testing indicators to see if they actually work like they should and a wide variety of strategies.  This is the very step in the process and to see how each piece of the code interacts with each other.  It’s like making a sandwich and the best part is that you don’t have to make the bread every time because the above is a template.

Freevestor can help you with creating your perfect portfolio.  Get started with Freevestor today and enhance your returns.

The post Hammer of Thor Forex Expert Advisor for MQL4 Development appeared first on freevestor.



This post first appeared on Freevestor, please read the originial post: here

Share the post

Hammer of Thor Forex Expert Advisor for MQL4 Development

×

Subscribe to Freevestor

Get updates delivered right to your inbox!

Thank you for your subscription

×