learning mql5

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
hey tram...... not sure exactly what your referring to.....

the idea behind trailing stop ea's does work..... the 5 minute chart picture below is from last night...... it's easy to visualize a trailing stop riding the psars or yellow 20 ma......

a trailing stop can trail many things like psar, moving averages, trendlines and such......

enivid has a psar trailing stop ea here.....

enivid has a moving average trailing stop here.....

atr trailing stop here.....


i'm just now learning mq5..... so some of my functions are at the beginner level..... will need to be improved.....

these functions eventually have the absolute minimum code required.....h
//------
//-----Screenshot 2024-09-17 031559.png
 

Enivid

Administrator
Staff member
Nov 30, 2008
19,240
1,507
144
Odesa
www.earnforex.com
bare minimum trailing ma stoploss code for darwin ea....... appears to work for sells..... yellow ma is 20.......h

//----

View attachment 29490





top lines in code box will not display correctly for some reason..... most likely html conflicts with < .....

the includes are,

#include <Trade\OrderInfo.mqh>
#include <Trade\Trade.mqh>
CTrade trade;


//------



Code:
//-----
#include 
#include 
CTrade trade;


CPositionInfo  m_position;                   // object of CPositionInfo class
COrderInfo     m_order;                      // object of COrderInfo class



double   Ask,Bid,high,low;

input int    contracts           =     1;



input double profit              =  1000;
 
input double dailytarget         =  2000;

input bool   trailingstophighlow = false;

input bool   trailingpsar        = false;

input bool   trailingstopma      = false;
 
input ulong  magicnumber         =  7000;      // magicnumber

input int    periods             =    20;
//---------


int OnInit()
  {
//---

 
 trade.SetExpertMagicNumber(magicnumber);     // used to set trades magicnumber sent by other functions

//-------
 
//---
   return(INIT_SUCCEEDED);
  }


//------ on tick code  

void OnTick()    
  {
//---

        Ask  = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);

        Bid  = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
 
        high = NormalizeDouble(iHigh(NULL,PERIOD_M15,1),_Digits);

        low  = NormalizeDouble(iLow(NULL,PERIOD_M15,1),_Digits);

 double mas[];
 
 int   ma   = iMA(NULL,PERIOD_CURRENT,periods,0,MODE_SMA,PRICE_CLOSE);
 
              ArraySetAsSeries(mas,true);
 
              CopyBuffer(ma,0,0,3,mas);
 
 
 

//------

  if(trailingstopma  && (mas[0] > 0.0))
      {
       trailingstopma(mas[0]);
      }
 
 //----
 //----
 
  }
 
 
//-------   just the function  itself
 
void trailingstopma(double ma)                                    //
     {
      double newstoploss = NormalizeDouble(ma,_Digits);
   
     for(int i=PositionsTotal()-1; i>=0; i--)
      {
          string symbol = PositionGetSymbol(i);
       
          ulong  pm     = PositionGetInteger(POSITION_MAGIC);
       
       if((_Symbol == symbol) && (pm == magicnumber))
         {
     
       if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY)
         {
          ulong  ticket          = PositionGetInteger(POSITION_TICKET);
       
          double currentstoploss = PositionGetDouble(POSITION_SL);
       
          if(currentstoploss < ma)
           {
            trade.PositionModify(ticket,newstoploss,0);
           }
       
         }
     
     
       if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
         {
          ulong  ticket          = PositionGetInteger(POSITION_TICKET);
       
          double currentstoploss = PositionGetDouble(POSITION_SL);
       
          if(currentstoploss > ma)
           {
            trade.PositionModify(ticket,newstoploss,0);
           }
       
         }      
     
     
       }
   
      }
 
 
 
     }
For the < brackets not to get garbled by the forum, it's necessary to insert them directly to the code box, like this:
MQL5:
#include <Trade\OrderInfo.mqh>
#include <Trade\Trade.mqh>
CTrade trade;
 
  • ℹ️
Reactions: hayseed

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
note to me...... verify on every instrument......

need to account for tick size..... this will set the psar, ma, and other type values dead on the closest price.....

otherwise considerable chance of invalid stops error......h



//-----
Code:
void trailingpsar(double psar)                                    //   
     {
      
      int    digits              = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    
      double ticksize            = SymbolInfoDouble( _Symbol, SYMBOL_TRADE_TICK_SIZE );

      double adjusted            = round(psar / ticksize ) * ticksize;
    
      double newstoploss         = NormalizeDouble(adjusted,digits);
            
      
     for(int i=PositionsTotal()-1; i>=0; i--)
      {   
          string symbol          = PositionGetSymbol(i);
          
          ulong  pm              = PositionGetInteger(POSITION_MAGIC);
          
          ulong  ticket          = PositionGetInteger(POSITION_TICKET);
          
          double currentstoploss = PositionGetDouble(POSITION_SL);
          
          double tp              = PositionGetDouble(POSITION_TP);
          
       if((_Symbol == symbol) && (pm == magicnumber))   
         {
        
       if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY)
         {
        
          if(currentstoploss < newstoploss)
           {
            trade.PositionModify(ticket,newstoploss,tp);
           }
          
         }
        
        
       if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
         {
        
          if(currentstoploss > newstoploss)
           {
            trade.PositionModify(ticket,newstoploss,tp);
           }
          
         }         
        
        
       }
      
      }
          
     }
 

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
having premade symbol arrays was ok in typical forex and such because they never change...... that approach is a real pain with futures....... the preferred contract month changes and somewhat randomly........ editing the list gets real old real quick......

in futures, seems best to just arrange the market watch symbols in your preferred order..... slide them up or down...... you will memorize their location quickly......

then use the market watch as your symbol[array] list..........h
//-----

Code:
const int total = SymbolsTotal(true);
   for(int i = 0; i < total; ++i)
   {
  
      string sym = SymbolName(i,true);   
      
      Print(sym);
   }

//------

Screenshot 2024-09-29 092217.png
 

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
position properties for use with PositionGetInterger...... or getstring......

order properties for use with OrderGetInterger...... or getstring......

positions are filled ....... op_buy....... op_sell.......

pendings are unfilled..... buystop, sellstop and such......

deals.........

PositionsTotal().....

OrdersTotal()......

per help docs, Do not confuse positions with valid pending orders, which are also displayed on the Trading tab of the Toolbox window.

rough idea of modifying pending orders below.......h

//------
Code:
//------
//------


void trailsellstoppsar(double psar)                                    //
     {
  
      int    digits                 = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
 
      double ticksize              = SymbolInfoDouble( _Symbol, SYMBOL_TRADE_TICK_SIZE );

      double adjusted            = round(psar / ticksize ) * ticksize;
 
      double newprice            = NormalizeDouble(adjusted,digits);
      
      
    for(int i=OrdersTotal()-1; i>=0; i--)                                                                                       // use orderstotal not positionstotal
       {
          string symbol          = OrderGetString(ORDER_SYMBOL);                                               
      
          ulong  pm                   = OrderGetInteger(ORDER_MAGIC);
      
          ulong  ticket             = OrderGetTicket(i);
      
          double sl                    = OrderGetDouble(ORDER_SL);
      
          double tp                  = OrderGetDouble(ORDER_TP);
      
          double price           = OrderGetDouble(ORDER_PRICE_OPEN);
      
  
      
      
       if((_Symbol == symbol) && (pm == magicnumber) && (OrderGetInteger(ORDER_TYPE) == 5))      // 5 is sellstop
         {

    
       if(OrderGetInteger(ORDER_TYPE) == 5)
         {
    
          if(price < newprice)
           {
            trade.OrderModify(ticket,newprice,sl,tp,ORDER_TIME_GTC,0,0);          // make sure existing sl and tp are still valid...... or modify them also
           }
    
         }     
    
    
       }       // if((_Symbol == symbol)
  
      }        //   for(int i=
      
     }

//----
 

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
use OBJPROP_TOOLTIP and SYMBOL_DESCRIPTION to hover object description.....

symbol description could be replaced with any such useful info........

thanks to enivid for panel structure code......h
//------




Code:
    ObjectSetString(0, PanelLabel, OBJPROP_TOOLTIP, symbol + SymbolInfoString(symbol, SYMBOL_DESCRIPTION));       
    ObjectSetString(0, PanelLabel, OBJPROP_TEXT, symbol + " alma");

//------

Screenshot 2024-11-03 103558.png

//----

Screenshot 2024-11-03 104536.png
 

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
just preserving work so far...... have not fully tested on everything.....

several goals here..... such as placing a value on gaps, and more obscure uses like placing values on stochastic, macd, ao type indicator cycles......

bare minimum code so far..... should calculate value between two lines...... lines at this point need to be manually placed and named...... line named hi should be largest and lo should be the smallest.....

value is in the comment top left......

will expand user inputs later.....

final goal is a stand alone function to return values of average cycles of indicators peak to trough...........h
//------



Code:
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---


 int     digits  = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);

 double  ts     = SymbolInfoDouble( _Symbol, SYMBOL_TRADE_TICK_SIZE);
 double  tv     = SymbolInfoDouble( _Symbol, SYMBOL_TRADE_TICK_VALUE);
 double  ps     = SymbolInfoDouble( _Symbol, SYMBOL_POINT );           
 double  pv     = (tv * ps) / ts;                                       




 
 double hi    = ObjectGetDouble(0,"hi",OBJPROP_PRICE);      // highest line
 
 double lo    = ObjectGetDouble(0,"lo",OBJPROP_PRICE);      // lowest line
 
 double ahi   = round(hi / ts ) * ts;                       // this is to adjust line to set tick size
 
 double alo   = round(lo / ts ) * ts;                       // this is to adjust line to set tick size
 
 double value =  (ahi-alo) * tv * (1/ts);
 
 
 
 Comment(DoubleToString(value,2));
 

 
  
//--- return value of prev_calculated for next call
   return(rates_total);
  }


Screenshot 2024-11-04 185241.png

//----

Screenshot 2024-11-04 185221.png

//-----
 

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
a simple method of conditional background color....... OBJPROP_BGCOLOR.......

color clrs[14]; must be global......

conditional colors determined in the OnCalculate section.......h
//-----


//----- enivids line

ObjectSetInteger(0, PanelLabel, OBJPROP_BGCOLOR, clrPurple);

//------ conditional line

ObjectSetInteger(0, TrendRowText, OBJPROP_BGCOLOR, clrs); // clrPurple);




//------

Screenshot 2024-11-10 101850.png
//-----









Code:
 //-------  clrs[14] must be global...... conditional colors determined in oncalculate section

    for (int k = 0; k < ArraySize(trends)-2; k++)  // -2 because not using week and month
    {   
    
    
    int ma[16];

        ma[k]       = iMA(symbol,tfs[k],200,0,MODE_SMA,0);   // change condition as needed


        double mas[];       
                                          
        ArraySetAsSeries(mas,true);                // set arrays in series, read docs
                                              
        CopyBuffer(ma[k], 0, 0, 4, mas);           // copies values from buffers

        clrs[k] = clrYellow;                       // initially set yellow
        
        if(mas[0] > mas[2])  {clrs[k] = clrBlue;}  //  clrBlue if rising
        if(mas[0] < mas[2])  {clrs[k] = clrRed;}   //  clrRed  if falling
 
    }
 
Last edited:

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
Code:
ObjectSetInteger(0, TrendRowText, OBJPROP_BGCOLOR, clrs[i]); //  clrPurple);


fwi........ the post above has several errors that that for some reason i can not fix even after multiple edits......


the overall idea should still be clear......h
 

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
prediction timer code example......h

//-----
MQL5:
   for (int l = 0; l < ArraySize(tf); l++)
    {   
    int zig[14];
    int bars      = iBars(symbol, tf[l]);
      zig[l]      = iCustom(symbol,tf[l],"Examples\\ZigZag",12,5,3);
 
 
        double zigs[];       
 
        ArraySetAsSeries(zigs,true);   
 
        CopyBuffer(zig[l], 0, 0, 200, zigs);
 
 
        double a = 0.0;
 
        for(int n=0; n<bars; n++) 
        {
        if(zigs[n]!=0.0)                                       
        {       
 
         zzbar[l] = n;   
         if(n>0) break;
         n++;
        }
        }       
    }

Screenshot 2024-11-12 150519.png
 
Last edited:

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
For the < brackets not to get garbled by the forum, it's necessary to insert them directly to the code box, like this:
//------

now i see my full error...... even when using the code box with the code pasted and correct, occasionally it would be quite different in the completed post......

we need to select mq5 in the drop down code box, if code is mq5 for best results .....

have always used the default general code .... usually it works........ never knew other options existed......

will select mq5 from now on...... .h
//-------

Screenshot 2024-11-12 151945.png
 
Last edited:
  • 👍
Reactions: Enivid

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
alma.......h

//-----

MQL5:
//----------
 
 
  if(usealma)
  {
    for (int m = 0; m < 14; m++)
    {   
 
    int alma[14];
 
      alma[m]     = iCustom(symbol,tfs[m],"alma");
 
        double almas[];       
 
        ArraySetAsSeries(almas,true);          // set arrays in series, read docs
 
        CopyBuffer(alma[m], 0, 0, 30, almas);  // copies values from buffers
 
       for(int n=0; n< 20; n++)
          {       
           if( ((almas[n] > almas[n+1]) && (almas[n+1] < almas[n+2])) || ((almas[n] < almas[n+1]) && (almas[n+1] > almas[n+2])) )
           {
           cntalma[m] = n;   
           if(n>0) break;
           n++;
           }
          }
    }   
 
    }

//-----

Screenshot 2024-11-12 194726.png

//------

Screenshot 2024-11-12 194716.png
 
  • 👍
Reactions: Enivid

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
for future reference.....

multi conditional colors.......

proper ichi, 5 sma, 10 sma, 20 sma alignment.......

in progress.......h

//-----

MQL5:
//------
//------
 
    for(int r = 0; r < 14; r++)
      {
 
    int ma5[14];     
    int ma10[14];     
    int ma20[14];     
 
 
    int spana[14];
    int spanb[14];   
 
 
      ma5[r]      = iMA(symbol, tfs[r],5,0,MODE_SMA,PRICE_CLOSE);
      ma10[r]     = iMA(symbol, tfs[r],10,0,MODE_SMA,PRICE_CLOSE);
      ma20[r]     = iMA(symbol, tfs[r],20,0,MODE_SMA,PRICE_CLOSE);
 
      spana[r]    = iIchimoku(symbol,tfs[r],9,26,52);     
      spanb[r]    = iIchimoku(symbol,tfs[r],9,26,52);     
 
 
 
        double ma5s[];
 
        ArraySetAsSeries(ma5s,true);   
 
        CopyBuffer(ma5[r],0,0,4,ma5s);
 
 
        double ma10s[];
 
        ArraySetAsSeries(ma10s,true);   
 
        CopyBuffer(ma10[r],0,0,4,ma10s);
 
 
 
        double ma20s[];
 
        ArraySetAsSeries(ma20s,true);   
 
        CopyBuffer(ma20[r],0,0,4,ma20s);
 
 
       double spanas[];
 
        ArraySetAsSeries(spanas,true);   
 
        CopyBuffer(spana[r],2,0,20,spanas);
 
 
        double spanbs[];
 
        ArraySetAsSeries(spanbs,true);   
 
        CopyBuffer(spanb[r],3,0,20,spanbs);
 
 
        clrichi[r]  = clrYellow;
 
        if( ((iClose(symbol,tfs[r],0) > spanas[0]) && (iClose(symbol,tfs[r],0) > spanbs[0]))  &&   ( (iClose(symbol,tfs[r],0) > ma5s[0]) &&  (iClose(symbol,tfs[r],0) > ma10s[0]) &&  (iClose(symbol,tfs[r],0) > ma20s[0]) ) &&  ( (ma5s[0] > ma10s[0]) && (ma5s[0] > ma20s[0])  && (ma10s[0] > ma20s[0]) )  &&  ( (ma5s[0] > ma5s[1]) && (ma10s[0] > ma10s[1])  && (ma20s[0] > ma20s[1]) )  )     
 
           {
           clrichi[r] = clrBlue;
           }
 
 
        if( ((iClose(symbol,tfs[r],0) < spanas[0]) && (iClose(symbol,tfs[r],0) < spanbs[0]))  &&   ( (iClose(symbol,tfs[r],0) < ma5s[0]) &&  (iClose(symbol,tfs[r],0) < ma10s[0]) &&  (iClose(symbol,tfs[r],0) < ma20s[0]) ) &&  ( (ma5s[0] < ma10s[0]) && (ma5s[0] < ma20s[0])  && (ma10s[0] < ma20s[0]) )   &&  ( (ma5s[0] < ma5s[1]) && (ma10s[0] < ma10s[1])  && (ma20s[0] < ma20s[1]) )  )     
 
           {
           clrichi[r] = clrRed;
           }
 
      }
 
//------   
//------





Screenshot 2024-11-13 084912.png

//-------
Screenshot 2024-11-13 090658.png
 

hayseed

Master Trader
Jul 27, 2010
1,160
275
149
usa
added another band to the extreme tma line indicator..... alorente, from spain, popularized the concept in this thread, extreme tma system.......

great care and consideration should be given before using real money..... at first glance the idea of fading extreme moves is appealing......

as a painful real life example, at this very moment i am around 50k in the hole...... i was originally completely confident it would work out in my favor, but still the risk often far out weighed the reward.......

my confidence was shaken somewhat......h
//------



Screenshot 2024-11-13 133451.png
 

Attachments

  • Extreme_TMA_line_indicator.ex5
    14.6 KB · Views: 0
  • Extreme_TMA_line_indicator.mq5
    14.8 KB · Views: 0