learning mql5

hayseed

Master Trader
Jul 27, 2010
1,147
273
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,212
1,504
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,147
273
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,147
273
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,147
273
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,147
273
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,147
273
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

//-----