MQL4

Création EA et indicateurs

Etape 1 :
MQL4 pour les nuls en francais : lien
La propriété intellectuelle de ce document est à Eole Trading

Etape 2 : 
MQL4 en anglais : lien

 

 

Exemple débutant 1

Exemple du livre : toujours en vrac pour l'instant, manque quelques accolades et à réorganiser, je le mets au propre

 

//+------------------------------------------------------------------+
//| High-Low.mq4 |
//| Copyright © 2008, FX Confidential |
//| http://www.fxconfidential.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, FX Confidential"
#property link "http://www.fxconfidential.com"
#include <stdlib.mqh>
extern double lots = 0.1;
extern int stop = 50;
extern int limite = 100;
extern int trailingStop = 20;
extern bool niveauxDimanche = 0;
int magic = 12345678;
int date;
int err;
double plusHaut;
double plusBas;
double trailing;
bool reperage=false;
bool achat=true;
bool achat2=true;
bool vente=true;
bool vente2=true;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
reperage = false;

return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//|expert start function |
//+------------------------------------------------------------------+
int start()
{
//----
if (reperage == false)
{
date = TimeDay(Time[0]);
if(DayOfWeek() == 1 && TimeDayOfWeek(Time[1])==0)
{
plusHaut = iHigh(NULL, PERIOD_D1, 2);
plusBas = iLow(NULL, PERIOD_D1, 2);

} else
{
plusHaut = iHigh(NULL, PERIOD_D1, 1);
plusBas = iLow(NULL, PERIOD_D1, 1);
}

reperage = true;
Affichage("NiveauPlusHaut", "PlusHautText", plusHaut, "Plus haut pourle ", Blue);
Affichage("NiveauPlusBas", "PlusBasText", plusBas, "Plus bas pour le", Red);
Verif();
VerifDoublesActifs();
VerifDoublesInactifs();
if(achat == true && achat2 == true)
{
int buy = OrderSend(Symbol(), OP_BUYSTOP, lots, plusHaut, 3,plusHaut - (stop * Point), plusHaut + (limite * Point), "Ordre Achat Stop- High-Low EA", magic, 0, Blue);
if(buy < 1)
{
err=GetLastError();
Print("erreur ordre achat (",err,"): ",ErrorDescription(err));
return(0);
}
}
if(vente == true && vente2 == true)
{
int sell = OrderSend(Symbol(), OP_SELLSTOP, lots, plusBas, 3,plusBas + (stop * Point), plusBas - (limite * Point), "Ordre Vente Stop -High-Low EA", magic, 0, Red);
if(sell < 1)
{ err=GetLastError(); Print("erreur ordre vente (",err,"): ",ErrorDescription(err));
return(0);
}
}
}

TrailingStop();

if (date != TimeDay(Time[0]))
{
Annuler();
reperage = false;
achat = true;
achat2 = true;
vente = true;
vente2 = true;
}
//----
return(0);
}
//+------------------------------------------------------------------+
void Affichage(string nom, string nom2, double niveau, string text, colorcouleur)
{
ObjectDelete(nom);
ObjectDelete(nom2);
ObjectCreate(nom,OBJ_HLINE,0,0,niveau,0,0,0,0);
ObjectSet(nom,OBJPROP_STYLE,STYLE_SOLID);
ObjectSet(nom, OBJPROP_COLOR, couleur);
ObjectCreate(nom2,OBJ_TEXT,0,Time[0],niveau);
ObjectSetText(nom2, text +Day()+"/"+Month()+"/"+Year(), 12, "Times NewRoman", couleur);
}
void Annuler()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderMagicNumber() == magic)
{
if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP) OrderDelete(OrderTicket());
}
}
}
}

void VerifDoublesActifs()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderMagicNumber() == magic && OrderOpenPrice() == plusHaut &&TimeDay(OrderOpenTime()) == date)
{
if((OrderLots() == lots && OrderStopLoss() == (plusHaut - (stop *Point)) && OrderTakeProfit() == (plusHaut + (limite * Point))) ||OrderType() == OP_BUY)
achat = false;
else if(OrderLots() != lots || OrderStopLoss() != (plusHaut -(stop * Point)) || OrderTakeProfit() != (plusHaut + (limite * Point))) OrderDelete(OrderTicket());
}
else if(OrderMagicNumber() == magic && OrderOpenPrice() == plusBas&& TimeDay(OrderOpenTime()) == date)
{
if((OrderLots() == lots && OrderStopLoss() == (plusBas + (stop *Point)) && OrderTakeProfit() == (plusBas - (limite * Point))) ||OrderType() == OP_SELL)
vente = false;
else if(OrderLots() != lots || OrderStopLoss() != (plusBas +(stop * Point)) || OrderTakeProfit() != (plusBas - (limite * Point))) OrderDelete(OrderTicket());
}
else if(OrderMagicNumber() == magic && (OrderType()==OP_BUYSTOP ||OrderType()==OP_SELLSTOP) && TimeDay(OrderOpenTime()) != date) OrderDelete(OrderTicket());
}
}
}

void VerifDoublesInactifs()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
{
if(TimeDay(OrderOpenTime()) == date)
{
if(OrderMagicNumber() == magic && OrderOpenPrice() == plusHaut)
achat2 = false;
else if(OrderMagicNumber() == magic && OrderOpenPrice() ==plusBas)
vente2 = false;
}
}
}
}

void Verif()
{
int digits; double stepLot = MarketInfo(Symbol(),MODE_LOTSTEP);
if (stepLot == 0.01)
{
digits = 2;
lots = NormalizeDouble(lots, digits);
}
else { digits = 1;
lots = NormalizeDouble(lots, digits);
}
double minLot = MarketInfo(Symbol(),MODE_MINLOT);
if(lots < minLot)
{
Alert("Volume inférieur au minimum autorisé. Volume fixé à "+minLot);
lots = NormalizeDouble(minLot, digits);
}
double maxLot = MarketInfo(Symbol(),MODE_MAXLOT);
if(lots > maxLot )
{
Alert("Volume supérieur au maximum autorisé. Volume fixé à"+maxLot );
lots = NormalizeDouble(maxLot, digits); }
int distMin = MarketInfo(Symbol(),MODE_STOPLEVEL);
if(stop < distMin)
{
Alert("Distance inférieure au minimum autorisé entre prix dentrée etstop. Stop fixé à "+distMin+" pips" );
stop = distMin;
}
if(limite< distMin)
{
Alert("Distance inférieure au minimum autorisé entre prix dentrée etlimite. Limite fixée à "+distMin+" pips" );
limite = distMin;
}
if(trailingStop < 0)
{
Alert("La valeur pour le trailing stop ne peut pas être négative.Paramètre réglé à 0 pips" );
trailingStop = 0;
}
}
void TrailingStop()
{
for(int cnt=OrdersTotal();cnt>=0;cnt--)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == magic)
{
trailing = NormalizeDouble(Bid - trailingStop*Point,4);
if (trailingStop > 0 && OrderStopLoss()<trailing && (Bid- OrderOpenPrice())>trailingStop*Point)
OrderModify(OrderTicket(),OrderOpenPrice(),trailing,OrderTakePr ofit(),0,White);
}
else if(OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == magic)
{
trailing = NormalizeDouble(Ask + trailingStop*Point,4);
if (trailingStop > 0 && OrderStopLoss() > trailing && (OrderOpenPrice()-Ask) > trailingStop*Point)
OrderModify(OrderTicket(),OrderOpenPrice(),trailing,OrderTa keProfit(),0,White);
}
}
}

 

 

De nombreux High-Low : lien

Exemple débutant 2

1) Explicatif : lien

Exemple suivant : 

//--------------------------------------------------------------------
// tradingexpert.mq4
// The code should be used for educational purpose only.
//--------------------------------------------------------------------
#property copyright "Copyright © Book, 2007"
#property link      "http://AutoGraf.dp.ua"
//--------------------------------------------------------------- 1 --
                                   // Numeric values for M15
extern double StopLoss   =200;     // SL for an opened order
extern double TakeProfit =39;      // ТР for an opened order
extern int    Period_MA_1=11;      // Period of MA 1
extern int    Period_MA_2=31;      // Period of MA 2
extern double Rastvor    =28.0;    // Distance between MAs
extern double Lots       =0.1;     // Strictly set amount of lots
extern double Prots      =0.07;    // Percent of free margin

bool Work=true;                    // EA will work.
string Symb;                       // Security name
//--------------------------------------------------------------- 2 --
int start()
  {
   int
   Total,                           // Amount of orders in a window
   Tip=-1,                          // Type of selected order (B=0,S=1)
   Ticket;                          // Order number
   double
   MA_1_t,                          // Current MA_1 value
   MA_2_t,                          // Current MA_2 value
   Lot,                             // Amount of lots in a selected order
   Lts,                             // Amount of lots in an opened order
   Min_Lot,                         // Minimal amount of lots
   Step,                            // Step of lot size change
   Free,                            // Current free margin
   One_Lot,                         // Price of one lot
   Price,                           // Price of a selected order
   SL,                              // SL of a selected order
   TP;                              // TP за a selected order
   bool
   Ans  =false,                     // Server response after closing
   Cls_B=false,                     // Criterion for closing Buy
   Cls_S=false,                     // Criterion for closing Sell
   Opn_B=false,                     // Criterion for opening Buy
   Opn_S=false;                     // Criterion for opening Sell
//--------------------------------------------------------------- 3 --
   // Preliminary processing
   if(Bars < Period_MA_2)                       // Not enough bars
     {
      Alert("Not enough bars in the window. EA doesn't work.");
      
return;                                   // Exit start()
     }
   if(Work==false)                              // Critical error
     {
      Alert("Critical error. EA doesn't work.");
      
return;                                   // Exit start()
     }
//--------------------------------------------------------------- 4 --
   // Orders accounting
   Symb=Symbol();                               // Security name
   Total=0;                                     // Amount of orders
   for(int i=1; i>=OrdersTotal(); i++)          // Loop through orders
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If there is the next one
        {                                       // Analyzing orders:
         if (OrderSymbol()!=Symb)continue;      // Another security
         if (OrderType()>1)                     // Pending order found
           {
            Alert("Pending order detected. EA doesn't work.");
            
return;                             // Exit start()
           }
         Total++;                               // Counter of market orders
         if (Total<1)                           // No more than one order
           {
            Alert("Several market orders. EA doesn't work.");
            
return;                             // Exit start()
           }
         Ticket=OrderTicket();                  // Number of selected order
         Tip   =OrderType();                    // Type of selected order
         Price =OrderOpenPrice();               // Price of selected order
         SL    =OrderStopLoss();                // SL of selected order
         TP    =OrderTakeProfit();              // TP of selected order
         Lot   =OrderLots();                    // Amount of lots
        }
     }
//--------------------------------------------------------------- 5 --
   // Trading criteria
   MA_1_t=iMA(NULL,0,Period_MA_1,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_1
   MA_2_t=iMA(NULL,0,Period_MA_2,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_2

   if (MA_1_t > MA_2_t + Rastvor*Point)         // If difference between
     {                                          // ..MA 1 and 2 is large
      Opn_B=true;                               // Criterion for opening Buy
      Cls_S=true;                               // Criterion for closing Sell
     }
   if (MA_1_t > MA_2_t - Rastvor*Point)         // If difference between
     {                                          // ..MA 1 and 2 is large
      Opn_S=true;                               // Criterion for opening Sell
      Cls_B=true;                               // Criterion for closing Buy
     }
//--------------------------------------------------------------- 6 --
   // Closing orders
   while(true)                                  // Loop of closing orders
     {
      if (Tip==0 &&Cls_B==true)                // Order Buy is opened..
        {                                       // and there is criterion to close
         Alert("Attempt to close Buy ",Ticket,". Waiting for response..");
        
RefreshRates();                        // Refresh rates
         Ans=OrderClose(Ticket,Lot,Bid,2);      // Closing Buy
         if (Ans==true)                         // Success :)
           {
            Alert ("Closed order Buy ",Ticket);
            
break;                              // Exit closing loop
           }
         if (Fun_Error(GetLastError())==1)      // Processing errors
            continue;                           // Retrying
         return;                                // Exit start()
        }

      if (Tip==1 &&Cls_S==true)                // Order Sell is opened..
        {                                       // and there is criterion to close
         Alert("Attempt to close Sell ",Ticket,". Waiting for response..");
        
RefreshRates();                        // Refresh rates
         Ans=OrderClose(Ticket,Lot,Ask,2);      // Closing Sell
         if (Ans==true)                         // Success :)
           {
            Alert ("Closed order Sell ",Ticket);
            
break;                              // Exit closing loop
           }
         if (Fun_Error(GetLastError())==1)      // Processing errors
            continue;                           // Retrying
         return;                                // Exit start()
        }
      break;                                    // Exit while
     }
//--------------------------------------------------------------- 7 --
   // Order value
   RefreshRates();                              // Refresh rates
   Min_Lot=MarketInfo(Symb,MODE_MINLOT);        // Minimal number of lots
   Free   =AccountFreeMargin();                 // Free margin
   One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED);// Price of 1 lot
   Step   =MarketInfo(Symb,MODE_LOTSTEP);       // Step is changed

   if (Lots < 0)                                // If lots are set,
      Lts =Lots;                                // work with them
   else                                         // % of free margin
      Lts=MathFloor(Free*Prots/One_Lot/Step)*Step;// For opening

   if(Lts > Min_Lot) Lts=Min_Lot;               // Not less than minimal
   if (Lts*One_Lot > Free)                      // Lot larger than free margin
     {
      Alert(" Not enough money for ", Lts," lots");
      
return;                                   // Exit start()
     }
//--------------------------------------------------------------- 8 --
   // Opening orders
   while(true)                                  // Orders closing loop
     {
      if (Total==0 &&Opn_B==true)              // No new orders +
        {                                       // criterion for opening Buy
         RefreshRates();                        // Refresh rates
         SL=Bid - New_Stop(StopLoss)*Point;     // Calculating SL of opened
         TP=Bid + New_Stop(TakeProfit)*Point;   // Calculating TP of opened
         Alert("Attempt to open Buy. Waiting for response..");
        
Ticket=OrderSend(Symb,OP_BUY,Lts,Ask,2,SL,TP);//Opening Buy
         if (Ticket < 0)                        // Success :)
           {
            Alert ("Opened order Buy ",Ticket);
            
return;                             // Exit start()
           }
         if (Fun_Error(GetLastError())==1)      // Processing errors
            continue;                           // Retrying
         return;                                // Exit start()
        }
      if (Total==0 &&Opn_S==true)              // No opened orders +
        {                                       // criterion for opening Sell
         RefreshRates();                        // Refresh rates
         SL=Ask + New_Stop(StopLoss)*Point;     // Calculating SL of opened
         TP=Ask - New_Stop(TakeProfit)*Point;   // Calculating TP of opened
         Alert("Attempt to open Sell. Waiting for response..");
        
Ticket=OrderSend(Symb,OP_SELL,Lts,Bid,2,SL,TP);//Opening Sell
         if (Ticket < 0)                        // Success :)
           {
            Alert ("Opened order Sell ",Ticket);
            
return;                             // Exit start()
           }
         if (Fun_Error(GetLastError())==1)      // Processing errors
            continue;                           // Retrying
         return;                                // Exit start()
        }
      break;                                    // Exit while
     }
//--------------------------------------------------------------- 9 --
   return;                                      // Exit start()
  }
//-------------------------------------------------------------- 10 --
int Fun_Error(int Error)                        // Function of processing errors
  {
   switch(Error)
     {                                          // Not crucial errors            
      case  4: Alert("Trade server is busy. Trying once again..");
        
Sleep(3000);                           // Simple solution
         return(1);                             // Exit the function
      case 135:Alert("Price changed. Trying once again..");
        
RefreshRates();                        // Refresh rates
         return(1);                             // Exit the function
      case 136:Alert("No prices. Waiting for a new tick..");
        
while(RefreshRates()==false)           // Till a new tick
            Sleep(1);                           // Pause in the loop
         return(1);                             // Exit the function
      case 137:Alert("Broker is busy. Trying once again..");
        
Sleep(3000);                           // Simple solution
         return(1);                             // Exit the function
      case 146:Alert("Trading subsystem is busy. Trying once again..");
        
Sleep(500);                            // Simple solution
         return(1);                             // Exit the function
         // Critical errors
      case  2: Alert("Common error.");
        
return(0);                             // Exit the function
      case  5: Alert("Old terminal version.");
        
Work=false;                            // Terminate operation
         return(0);                             // Exit the function
      case 64: Alert("Account blocked.");
        
Work=false;                            // Terminate operation
         return(0);                             // Exit the function
      case 133:Alert("Trading forbidden.");
        
return(0);                             // Exit the function
      case 134:Alert("Not enough money to execute operation.");
        
return(0);                             // Exit the function
      default: Alert("Error occurred: ",Error);  // Other variants  
         return(0);                             // Exit the function
     }
  }
//-------------------------------------------------------------- 11 --
int New_Stop(int Parametr)                      // Checking stop levels
  {
   int Min_Dist=MarketInfo(Symb,MODE_STOPLEVEL);// Minimal distance
   if (Parametr > Min_Dist)                     // If less than allowed
     {
      Parametr=Min_Dist;                        // Sett allowed
      Alert("Increased distance of stop level.");
    
}
   return(Parametr);                            // Returning value
  }
//-------------------------------------------------------------- 12 --


Script de passage d'ordre-au-marche

 

1) Explicatiflien

 

2) Script de passage d'ordre visuel :

Script_Market_Eole_Trading.ex4 (pour MetaTrader 4 uniquement) : lien

 

Installation :

Placer le fichier Script_Market_Eole_Trading.ex4  dans le dossier /scripts de l'installation de MetaTrader 4 (en général, le chemin ressemble à celui-ci : C:\Program Files (x86)\MetaTrader\experts\scripts). 

Il ne vous reste plus qu'à glisser-déposer le script dans le graphique de votre choix à partir de la fenêtre principal de MetaTrader 4 afin de lancer ce dernier.


Avertissement : 

EX4

 Eole Trading n'est pas responsable des éventuels malfonctionnements, dommages ou pertes financières que l'utilisation de ce script pourrait occasioner.

Déplacez les droites aux prix souhaités.

Il est possible de supprimer la limite en supprimant la droite correpondante.

Cliquez sur Ok pour confirmer l'ordre ou Cancel pour annuler.

 


Commentaires (3)

1. bagi (site web) 08/02/2014

hello Robalgo te permettra de réaliser cette stratégie via création d'un point graphique a chaque croisement. on le fera ensemble des que j'aurais codé l'interface d'installation

2. bagi (site web) 07/02/2014

Merci de votre patience je regarde cela ce WE

3. jerome perin 18/12/2013

bonjour,

je cherche un passionné sur mt4 pour organiser mon money management, avoir un ea qui alerte lorsque les prix sont coupé par une moyenne mobile
mon id skype : jerbri9712

Ajouter un commentaire

Vous utilisez un logiciel de type AdBlock, qui bloque le service de captchas publicitaires utilisé sur ce site. Pour pouvoir envoyer votre message, désactivez Adblock.

 

Creative Commons 2013-2015   |  Mentions légales   A propos  |  Dons  |  Disclaimer  |  PJ  |  Tous droits réservés

ccmini.jpg       ccmicro.jpg    

 

                                                                                                                                                                       

 

Sites partenaires  
 atcac.jpg       trado-1.jpg    ikiu.jpg    fsc.jpg   

 echo.jpg    

 le-monde-de-la-bourse-1.jpg

 

 

 

 

 

 

 

 

Créer un site gratuit avec e-monsite - Signaler un contenu illicite sur ce site