Amps

Showing posts with label forex mt4 expert advisor coding. Show all posts
Showing posts with label forex mt4 expert advisor coding. Show all posts

Monday, June 18, 2018

How difference between mt4 input extern

MT4 input extern

Wondering, how difference between MT4 input and extern. Both variable used for specific variable, which in visual programming like, Visual basic, C#, Delphi or Lazarus those would know in properties section.
input and extern in MT4 is the variable, which used in MA, some programmer call global variable 

input

A variable with the input modifier can't be changed inside mql4-programs

extern

extern ones also determine the input parameters of an mql4 program. They are available from the Properties window, values of extern variables can be modified in the program during its operation.


note: photo by doc mql4

Global Variables

Global variables are created by placing their declarations outside function descriptions, they are not local in any block. Global variable can be used in any function of EA.
Example:
int GlobalFlag=10;   // Global variable
int OnStart()
  {
   ...
  }

Short note buy and sell

Open Buy use ask price
TP buy use ask price

Open Sell use bid price
TP sell use bid price

Tuesday, February 23, 2016

Moving Average EA Example Step Conclusion

Moving Average EA Example Step Conclusion



Moving Average Activate Open and Close order Function MQL4

Moving Average Activate Open and Close order Function MQL4

Basic Function Moving Average Multi order EA Example MQL4

bool IsTradeAllowed
string symbol
datetime Time to check status

Full code on this part OnTick

//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//---
  }
//+------------------------------------------------------------------+

Finish Moving Average EA coding MQL4

Auto Close Order Moving Average EA MQL4

Auto Close Order Moving Average EA MQL4

This part very useful because this part we able to use protect the Take profit and Stop Loss, which would make us live in Forex Trading and got best profit and minimum loss.

MQL4 Basic function used Close Order Moving Average EA MQL4

Table Function OrderSelect MQL4


bool OrderSelect It returns true if the function succeeds The order must be previously selected by the OrderSelect() function
Int index Order index or order ticket depending on the second parameter
Int select
SELECT_BY_POS index in the order pool
SELECT_BY_TICKET index is order ticket
int pool=MODE_TRADES
MODE_TRADES (default) order selected from trading pool(opened and pending orders)
MODE_HISTORY order selected from history pool (closed and canceled order)
int OrderMagicNumber(); Returns an identifying (magic) number of the currently selected order

string  OrderSymbol() Returns symbol name of the currently selected order.

Table Function Order Type MQL4

int OrderType();
Returned value Should specific when we using
OP_BUY
OP_SELL
OP_BUYLIMIT
OP_BUYSTOP
OP_SELLLIMIT
OP_SELLSTOP
double Open[] contains open prices of each bar of the current chart
double Close[] contains close prices for each bar of the current chart

Table Function Order Close MQL4

bool OrderClose Closes opened order
Int ticket Unique number of the order ticket
Double lots Number of lots
Double price Closing price
Int slippage Value of the maximum price slippage in points
color arrow_color Color of the closing arrow
long Volume[] contains tick volumes of each bar of the current chart

moving average EA close order conditions:

Close Buy when Candle open price over MA reference and close candle price under ma
Open[1]>ma && Close[1]<ma
Close Sell when Candle open price under MA reference and close candle price over ma
Open[1]<ma && Close[1]>ma

Full code moving average close order

//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma;
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average 
  //original ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
  //new
  ma=iMA(NULL,TimeFrameUsed,MovingPeriod,MovingShift,EMA_method1,Applied_Price1,0);
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //--- check order type 
      if(OrderType()==OP_BUY)
        {
         if(Open[1]>ma && Close[1]<ma)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(Open[1]<ma && Close[1]>ma)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }

This EA prepare example for activate open and close order, next chapster we would find out how to.

Moving Average EA Open Order with Modify Take profit and Stop Loss

Moving Average EA Open Order with Modify Take profit and Stop Loss

In previous chapter we guide moving average properties. In this chapster we would coding Moving Average EA MQL4 for modify take profit and Stop Loss.
Mention to Forex Broker have the exchange digits show 3,5 and 4 digits, which modify Take profit and Stop Loss that depend on broker we trading.

Refer to properties code in this part are:












extern string TP_SL = " --- TP and Stop Loss ---";
extern bool Broke3_5Digits = True;
extern double My_TP = 10;
extern double My_SL = 10;

And Moving Average Properties part we would always change as below
//Add extern parameter as Label
extern string MovingAvr = " --- Moving Average parameter ---";
//Change from original
extern int    MovingPeriod  =12;
extern int    MovingShift   =6;
//Add properties
extern ENUM_TIMEFRAMES TimeFrameUsed = PERIOD_CURRENT;
extern ENUM_MA_METHOD   EMA_method1 = MODE_SMA;
extern ENUM_APPLIED_PRICE Applied_Price1 = PRICE_CLOSE;

In checking the open order we would add the condition to design broker digits using as follow

void CheckForOpen()
  {
   double ma;
   int    res;

// calculate TP and Stop Loss   
   double BrokerTPSell,BrokerTPBuy;
   double BrokerSLSell,BrokerSLBuy;
 if(Broke3_5Digits=True)
 { 
   if (My_TP!=0)
   {
    BrokerTPSell = Bid-((My_TP*Point)*10);
    BrokerTPBuy = Ask+((My_TP*Point)*10);
   }
   
   if (My_TP==0)
   {
    BrokerTPSell = 0;
    BrokerTPBuy = 0;
   }
   
   if (My_SL!=0)
   {
    BrokerSLSell = Bid+((My_SL*Point)*10);
    BrokerSLBuy = Ask-((My_SL*Point)*10);
   }
   
   if (My_SL==0)
   {
    BrokerSLSell = 0;
    BrokerSLBuy = 0;
   }
   
 }
 if(Broke3_5Digits=False)
 { 
   if (My_TP!=0)
   {
    BrokerTPSell = Bid-(My_TP*Point);
    BrokerTPBuy = Ask+(My_TP*Point);
   }
   
   if (My_TP==0)
   {
    BrokerTPSell = 0;
    BrokerTPBuy = 0;
   }
   
   if (My_SL!=0)
   {
    BrokerSLSell = Bid+(My_SL*Point);
    BrokerSLBuy = Ask-(My_SL*Point);
   }
   
   if (My_SL==0)
   {
    BrokerSLSell = 0;
    BrokerSLBuy = 0;
   }
   
 }

So the open order we would put the value from Moving Average EA as below

//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//--- get Moving Average 
  // original ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
  //new
  ma=iMA(NULL,TimeFrameUsed,MovingPeriod,MovingShift,EMA_method1,Applied_Price1,0);
//--- sell conditions
   if(Open[1]>ma && Close[1]<ma)
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,BrokerSLSell,BrokerTPSell,"",MAGICMA,0,Red);
     
      return;
     }
//--- buy conditions
   if(Open[1]<ma && Close[1]>ma)
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,BrokerSLBuy,BrokerTPBuy,"",MAGICMA,0,Blue);
      return;
     }
//---
  }

In next chapster we would detail for auto close order

Thursday, January 28, 2016

Moving Average EA Open Order Function

Moving Average EA Open Order Function

Check open order EA MQL4 moving average have new function use as below

Function used for open order MQL4 moving average EA

long Volume[] Series array that contains tick volumes of each bar of the current chart
double Open[] Series array that contains open prices of each bar of the current chart.
double Close[] Series array that contains close prices for each bar of the current chart.
string  Symbol() Returns a text string with the name of the currency pair

int OrderSend
string NULL
Int cmd
0 OP_BUY
1 OP_SELL
2 OP_BUYLIMIT
3 OP_SELLLIMIT
4 OP_BUYSTOP
5 OP_SELLSTOP
double volume Number of lots
Double price Order price (double Bid price for Sell, double Ask price for buy)
Int slippage Maximum price slippage for buy or sell orders
double stoploss
double takeprofit
string comment=NULL Order comment text. Last part of the comment may be changed by server
Int magic=0 Order magic number. May be used as user defined identifier
Datetime expiration=0 Order expiration time (for pending orders only)
color arrow_color=clrNONE Color of open order
Mention to this EA example not have EA Setting properties for Take Profit and Stop Loss, so at first we would add this parameter in to EA properties as below, which TP and Stop Loss that for broker 5 digits that need specify Point*10 and broker 4 digits would specify Point.
Incase no TP and SL that we would specify 0 in to these part.

Properties for Moving Average Parameter as below

extern string TP_SL = " --- TP and Stop Loss ---";
extern bool Broke3_5Digits = True;
extern double My_TP = 10;
extern double My_SL = 10;

//Add extern parameter as Label
extern string MovingAvr = " --- Moving Average parameter ---";
//Change from original
extern int    MovingPeriod  =12;
extern int    MovingShift   =6;
//Add properties
extern ENUM_TIMEFRAMES TimeFrameUsed = PERIOD_CURRENT;
extern ENUM_MA_METHOD   EMA_method1 = MODE_SMA;
extern ENUM_APPLIED_PRICE Applied_Price1 = PRICE_CLOSE;


//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma;
   int    res;
//--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;

//--- get Moving Average 
  // original ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
  //new
  ma=iMA(NULL,TimeFrameUsed,MovingPeriod,MovingShift,EMA_method1,Applied_Price1,0);

//--- sell conditions
   if(Open[1]>ma && Close[1]<ma)
     {
      // old send sell order: res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
     }
//--- buy conditions
   if(Open[1]<ma && Close[1]>ma)
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
     }
//---
  }

This Moving Average function that sell condition is Open[1]>ma && Close[1]<ma
Buy condition is Open[1]<ma && Close[1]>ma

in the next chapster would explain about auto close order part in case open order is not the right way.

Wednesday, January 13, 2016

EA MA Optimal Lot or Trading Money Management

Optimal Lot or Trading Money Management

Money Management that nessary for our trading because this would protect our loss could be happen all the time, so this part should have in our Expert Advisor.

The MQL4 function used for this module detail as below.

Function Feature
double NormalizeDouble Return Value of double type with preset accuracy
double value Value with a floating point
int digits Accuracy format, number of digits after point (0-8)
double AccountFreeMargin(); Free margin value of the current account.
double OrderProfit() Returns profit of the currently selected order The net profit value (without swaps or commissions)
int OrdersHistoryTotal(); The number of closed orders in the account history loaded into the terminal. The history list size depends on the current settings of the "Account history" tab of the terminal

Meaning of Moving Average Money Management MQL4 code

double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//Calculate account free margin from Maximum risk, which specified in EA properties

//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }


//This function decrease lot size depend on order pending got loss
//DecreaseFactor would got specified on EA properties

//if(DecreaseFactor>0) would do the lot optimization if specified number greater than 0 
//in EA properties
//----- in DecreaseFactor Function----
//if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
//Check order false status and report

//if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
//            continue;
//order success check
//if(OrderProfit()>0) break;
//if order got profit not do the lot optimization
// if(OrderProfit()<0) losses++;
//     }
//      if(losses>1)
//        lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
//     }

// if order have loss do the lot optimization or decrease lot to next order
//----- end of DecreaseFactor check condition

//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }

//---- end of  

Test Run Moving Average EA on youtube
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//Calculate account free margin from Maximum risk, which specified in EA properties

//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }


//This function decrease lot size depend on order pending got loss
//DecreaseFactor would got specified on EA properties

//if(DecreaseFactor>0) would do the lot optimization if specified number greater than 0 
//in EA properties
//----- in DecreaseFactor Function----
//if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
//Check order false status and report

//if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
//            continue;
//order success check
//if(OrderProfit()>0) break;
//if order got profit not do the lot optimization
// if(OrderProfit()<0) losses++;
//     }
//      if(losses>1)
//        lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
//     }

// if order have loss do the lot optimization or decrease lot to next order
//----- end of DecreaseFactor check condition

//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }

//---- end of  

Test Run Moving Average EA on youtube


Monday, December 21, 2015

Visual Back Test EA and Indicator MT4

Visual Back Test EA and Indicator MT4 

2 step Fastest Test Expert Adviser and Forex Indicator MT4

1. Select MT4 Expert Adviser Tester set properties and parameter TF for back testing click at Visual

Click the Start testing slide bar at visual mode to slowest position and then go to step 2


2. Drag the indicator want to check to the visual chart

Monday, December 14, 2015

Example MQL4 Code Moving Average EA Check Pending Order

Example MQL4 Code Moving Average EA Check Pending Order

In the last chapster we learn about how to build expert advisor properties and link the extern variable 

Moving Average EA function. In this chapster we would learn open order condition from MetaTrader 

Moving Average EA Code

Moving Average sample expert advisor by MetaQuotes designed the coding as 5 block of code
Calculate Pending order
Optimal Lot or Trading Money Management
Open order condition
Close order condition
Activate on Tick Function

This Chapter we would learn about Calculation The pending order.

 Calculate Pending order

Calculate Pending order including function as below
Function Feature
int OrdersTotal(); Returns the number of market and pending orders.
bool OrderSelect The function selects an order for further processing.
Order index or order ticket number of ticket
Selecting flags
SELECT_BY_POS index in the order pool
SELECT_BY_TICKET index is order ticket
pool=MODE_TRADES
MODE_TRADES opened and pending orders
MODE_HISTORY closed and canceled order
string OrderSymbol(); The symbol name of the currently selected order
string Symbol(); Returns a text string with the name of the current financial
int OrderMagicNumber(); The identifying (magic) number of the currently selected order
int OrderType();
OP_BUY buy order
OP_SELL sell order
OP_BUYLIMIT buy limit pending order
OP_BUYSTOP buy stop pending order
OP_SELLLIMIT sell limit pending order
OP_SELLSTOP sell stop pending order

Mention to the code and using function in this part


Basic MQL4 Function creation example from document page of MQL4


Explian the code MA EA calculate pending order

First Step specify function name and return value to function
From the MA EA code this part would return Integer value to function, which when we would like to use this 

function that we should call this function with (string variable)

for(int i=0;i<OrdersTotal();i++) // check total pending order

if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break; // no action if have pending order
//if have pending order Buy or Sell count buys and sells variable
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }

//--- return total orders pending
   if(buys>0) return(buys);
   else       return(-sells);
}

Check order pending by function OrderSelect, which command in this part would check total order pass minor function SELECT_BY_POS and trade was opened or trade pending MODE_TRADE.
This if not have pending order would call open order function pass OrderType function

This Chapter we learn about how to check pending order in next chapter we would learn about Optimal Lot or money management


Friday, December 11, 2015

Forex MQL4 EA Properties Coding Learn Free 1

MQL4 EA Properties Coding

Learning from MetaQuotes Moving Average EA Example

Access MetaQuotes Language Editor

Open Data Folder 



Copy File Moving Average EA and Rename to New one



Check Properties and Activate Auto Trading





Check The original code Moving Average EA

Input variable MQL 4
Input variable with the input modifier can't be changed inside mql4-programs
input variables can be changed only by a user from the program properties window

Example in original code of moving average ea

input double Lots          =0.1;
input double MaximumRisk   =0.02;
input double DecreaseFactor=3;
input int    MovingPeriod  =12;
input int    MovingShift   =6;



Change The Variable Type from Original EA code

External variable or Extern Variable MQL4
Extern ones also determine the input parameters of an mql4 EA
They are available from the Properties window
Extern variables can be modified in the Properties window and MQL4 Program

so, we would add External variable in the properties part of EA and change input variable to extern variable code as below



Sunday, November 29, 2015

MT4 EA build procedure 1 MQL4 EA Structure

MT4 EA build procedure 1 MT4 EA Structure

MQL4 Property structure


//+------------------------------------------------------------------+
//|                                             test_bistechn_ea.mq4 |
//|                               Copyright 2015, BIS and Technology |
//|                                                 www.bistechn.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, BIS and Technology"
#property link      "www.bistechn.com"
#property version   "1.00"
#property strict

This part for declare the property owner of this EA or MQL4 code after Meta Editor complied this MT4 EA property would show in Metatrader program (MT4) part of Expert Advisors during we point this mouse to this EA.

Also this part used for declare public variable. (public variable would able used in any function in MT4 EA)

MT4 EA properties for setting basic parameter would declared in this part

MQL4 Initialization function


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  } 

The Initialization function part used for initialize EA instance Change the Time Frame Trading and etc.

MQL4 Expert deinitialization function


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

This part used for clean all draw line, arrow, which build by EA after not using

MQL4 Expert Start function 


//+------------------------------------------------------------------+
//| Expert Start function                                             |
//+------------------------------------------------------------------+
int start()
  {
//---
   
  }return (result);
//+------------------------------------------------------------------+

The MQL4 Expert Start Function used for create function what we want this EA working or trade instance open buy or sell and all of  activities we would like to do


Tuesday, September 29, 2015

Forex MT4 coding 2 variable Structure


MT4 variable structure

Look at MACD Sample code for example.


Properties show the code owner


Global variable

This part used for declare  global variable, which variable in this part would able to see and able to used by every function of code
(so these variable name in this part should be unique name)



Function variable

Variable in this part able to used in this part only unable to used by other function.




Forex MT4 EA coding Step1 Starting build The EA


First Step MT4 EA coding

Goto Menu Tools => Metaquotes Language Editors or F4
To access MetaEditor code Editors


Use MQL Wizard to tell what type of code we would build => Select Expert Advisor Template to build Expert Advisor


Input the name of MT4 EA, Author and Link (if have your web sites)


Select Function would like to build instance MT4 work under Timer, on ChartEvent and etc.