learning mql5

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
raghee horner with mini dashboard reflecting in left to right order, 1 minute to daily......

checking the current unfinished bar to last completed bar......h
//------

mnqm24-d1-amp-global-clearing-mini.png


//------
 

Attachments

  • raghee horner 34 ema mini dash.ex5
    10.4 KB · Views: 4
  • raghee horner 34 ema mini dash.mq5
    5.3 KB · Views: 7

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
had been having trouble getting buttons to display on currency futures..... thought at first it might have to do with them beginning with a number..... "6E_U"..... never pursued that thought.....

turns out my code which has always worked might not be entirely correct...... always used _Symbol before ......

ObjectCreate(_Symbol,"Buy",OBJ_BUTTON,0,0,0);

that works on everything but currency futures...... on futures it returned error 4101, chart id error......

turns out ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0); works better......

mq5 seems to like that better.......h
//------



MQL5:
 ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0);
 
 ObjectSetInteger(0,"Buy",OBJPROP_XDISTANCE,10);
 
 ObjectSetInteger(0,"Buy",OBJPROP_XSIZE,200);
 
 ObjectSetInteger(0,"Buy",OBJPROP_YDISTANCE,50);
 
 ObjectSetInteger(0,"Buy",OBJPROP_YSIZE,40);
 
 ObjectSetInteger(0,"Buy",OBJPROP_CORNER,0);
 
 ObjectSetString(0,"Buy",OBJPROP_TEXT,"Buy");
 
 ObjectSetInteger(0,"Buy",OBJPROP_BGCOLOR,clrAqua);
 
 
//----

//-----

enivid 20.jpg
 
Last edited by a moderator:

Enivid

Administrator
Staff member
Nov 30, 2008
19,234
1,507
144
Odesa
www.earnforex.com
had been having trouble getting buttons to display on currency futures..... thought at first it might have to do with them beginning with a number..... "6E_U"..... never pursued that thought.....

turns out my code which has always worked might not be entirely correct...... always used _Symbol before ......

ObjectCreate(_Symbol,"Buy",OBJ_BUTTON,0,0,0);

that works on everything but currency futures...... on futures it returned error 4101, chart id error......

turns out ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0); works better......

mq5 seems to like that better.......h
//------



MQL5:
 ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0);
 
 ObjectSetInteger(0,"Buy",OBJPROP_XDISTANCE,10);
 
 ObjectSetInteger(0,"Buy",OBJPROP_XSIZE,200);
 
 ObjectSetInteger(0,"Buy",OBJPROP_YDISTANCE,50);
 
 ObjectSetInteger(0,"Buy",OBJPROP_YSIZE,40);
 
 ObjectSetInteger(0,"Buy",OBJPROP_CORNER,0);
 
 ObjectSetString(0,"Buy",OBJPROP_TEXT,"Buy");
 
 ObjectSetInteger(0,"Buy",OBJPROP_BGCOLOR,clrAqua);
 
 
//----

//-----

View attachment 29053
Yeah, that's because the first parameter should be the chart window number (zero = main), not the symbol. It probably worked fine for other symbols because they didn't contain any numbers in their names, so the string got converted to 0. Your futures symbol's name contains a number, and it got converted to that number, failing to create an object at the chart window 6 or something.
 
  • 👍
Reactions: hayseed

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
couple functions.....h

//-----

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

//-----

Code:
void closingall()                                   //----- closes or deletes  all symbols......   all type orders.....
   {
    for(int i=PositionsTotal()-1; i>=0; i--)
       {
       ulong ticket = PositionGetTicket(i);
     
       trade.PositionClose(ticket);
       }
//----

    for(int i=OrdersTotal()-1; i>=0; i--)
       {
       ulong tickets = OrderGetTicket(i);
     
       trade.OrderDelete(tickets);
       }        
       
 
   }


//-----


Code:
double symprofit()                                          //----- chart symbol profit only
   {
       double profit = 0.0;                                 //-----  use AccountInfoDouble(ACCOUNT_PROFIT) for total account profit
     
    for(int i=PositionsTotal()-1; i>=0; i--)
       {
     
       if(PositionGetSymbol(i) != _Symbol) continue;
     
       profit += PositionGetDouble(POSITION_PROFIT);
       }
     
     return(profit);
     
   }

//-----


onclick example.....

Code:
 void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
 {
 
  double target =   0;
 
  double points = 500;
 
  double pnts   = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
 
  if((_Symbol == "YM_U")  || (_Symbol == "YMU24"))   {target = 500;  points = 10*pnts;}               //  0 digits 5*30 == 150         10 is 10 full points
  if((_Symbol == "ES_U")  || (_Symbol == "EPU24"))   {target = 1000; points = 100*pnts;}              //  2 digits                     500 is 5 full points
  if((_Symbol == "NQ_U")  || (_Symbol == "ENQU24"))  {target = 5000; points = 500*pnts;}              //  2 didgits                    500 is 5 full points
  if((_Symbol == "RTY_U") || (_Symbol == "RTYU24"))  {target = 100;  points = 40*pnts;}               //  1 digits                     100 is 10 full points
 
  if((_Symbol == "FDAX_U"))                          {target = 300; points = 300*pnts;}
  if((_Symbol == "FEXU_U"))                          {target = 200; points = 200*pnts;}
 
 
  if((_Symbol == "6A_U"))                            {target = 500*pnts; points = 500*pnts;}       // audusd
  if((_Symbol == "6E_U"))                            {target = 500*pnts; points = 500*pnts;}       // eurusd
  if((_Symbol == "6B_U"))                            {target = 500*pnts; points = 500*pnts;}       // gbpusd
  if((_Symbol == "6C_U"))                            {target = 500*pnts; points = 500*pnts;}       // usdcad
  if((_Symbol == "6N_U"))                            {target = 500*pnts; points = 500*pnts;}       // nzdusd
 
//----  ag

  if((_Symbol == "ZC_U"))                            {target = 300*pnts;  points = 300*pnts;}      // corn                   375.75
  if((_Symbol == "ZM_Z"))                            {target = 100*pnts;  points = 100*pnts;}      // soybean meal           308.6
  if((_Symbol == "ZS_X"))                            {target = 5000*pnts; points = 5000*pnts;}     // soybeans               976.55
  if((_Symbol == "ZL_Z"))                            {target = 300*pnts;  points = 300*pnts;}      // soybean oil             39.38
  if((_Symbol == "KE_U"))                            {target = 3000*pnts; points = 3000*pnts;}     // hard red wheat         548.95


  // SymbolInfoInteger(Symbol,SYMBOL_DIGITS);
 
 if(id==CHARTEVENT_OBJECT_CLICK)
    {
    if(sparam == "Buy")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
   
   
    trade.Buy(contracts,NULL,Ask,Ask-target,Ask+target,NULL);
   
    }
   
   
    if(sparam == "Buy Limit")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
   
   
    trade.BuyLimit(contracts,Ask-points,NULL,(Ask-points-target),(Ask-points+target),ORDER_TIME_GTC,0,0);
   
    }  
   
   
    if(sparam == "Buy Stop")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
   
   
    trade.BuyStop(contracts,Ask+points,NULL,(Ask+points-target),(Ask+points+target),ORDER_TIME_GTC,0,0);
   
    }      
   
   
   
   
   
    if(sparam == "Sell")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
 
    trade.Sell(contracts,NULL,Bid,(Bid+target),(Bid-target),NULL);
   
    }  
   
   
   
    if(sparam == "Sell Limit")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
 
    trade.SellLimit(contracts,Bid+points,NULL,(Bid+target+points),(Bid+points-target),ORDER_TIME_DAY,0,0);
   
    }  
     
   
    if(sparam == "Sell Stop")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
 
    trade.SellStop(contracts,Bid-points,NULL,(Bid-points+target),(Bid-points-target),ORDER_TIME_DAY,0,0);
   
    }
   
//------  
   
    if(sparam == "Close")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
 
    closing();
    closing();
    closing();
   
    }      
   
   
    if(sparam == "Close All")
    {
   
    Alert(sparam+ " was pressed on  "+_Symbol +" with target of "+ DoubleToString(target,0));
 
    closingall();
    closingall();
    closingall();
   
    }      
   
   
   
   
     
    }      
 }
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
close and delete chart symbol orders only.....h
//-----

Code:
//------

 
void closing()                                          //----- closes  or deletes chart symbol only ......   
   {
    for(int i=PositionsTotal()-1; i>=0; i--)
       {
       ulong ticket = PositionGetTicket(i);
      
       if(PositionGetSymbol(i) != _Symbol)         continue;

       if(PositionGetSymbol(i) == _Symbol)
       {
       trade.PositionClose(ticket);
       }
       }
//----

    for(int i=OrdersTotal()-1; i>=0; i--)     
       {
       ulong tickets = OrderGetTicket(i); 
      
       if(OrderGetString(ORDER_SYMBOL) != _Symbol) continue;
      
       if(OrderGetString(ORDER_SYMBOL) == _Symbol)
       {       
       trade.OrderDelete(tickets);
       }         
       }
      
   }
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
code to create standard button for onclick action...... as seen in chart example.....h
//-----

Code:
int OnInit()
  {
//---

 


 ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0);

 ObjectSetInteger(0,"Buy",OBJPROP_XDISTANCE,10);
 
 ObjectSetInteger(0,"Buy",OBJPROP_XSIZE,200);

 ObjectSetInteger(0,"Buy",OBJPROP_YDISTANCE,50);

 ObjectSetInteger(0,"Buy",OBJPROP_YSIZE,40);
 
 ObjectSetInteger(0,"Buy",OBJPROP_CORNER,0);

 ObjectSetString(0,"Buy",OBJPROP_TEXT,"Buy");
 
 ObjectSetInteger(0,"Buy",OBJPROP_BGCOLOR,clrAqua);
 

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



//------
dragging.jpg
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
code example to place info in indicator window......h

//------

nq-u-m1-tradeslide-trading-tech.png


//------


Code:
           Display("total"+ shortname, (1550),(50));      // 1375           
           ObjectSetText("total"+ shortname,  DoubleToString(cnts,0)+"  "+ DoubleToString(cnt,0), 10, "Verdana", clrYellow);
                      
           Display("marginrequired"+ shortname, (1700),(1));      // 1375                                                       
           ObjectSetText("marginrequired"+ shortname,  "margin required is "+DoubleToString(SymbolInfoDouble(_Symbol,SYMBOL_MARGIN_INITIAL),0), 10, "Verdana", clrYellow);
 
           Display("digits tv"+ shortname, (1700),(25));      // 1375                                                     
           ObjectSetText("digits tv"+ shortname,  "tick value is "+DoubleToString(SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE),2), 10, "Verdana", clrYellow);
 
           Display("tick size"+ shortname, (1700),(50));      // 1375                                                     
           ObjectSetText("tick size"+ shortname,  "tick size is "+DoubleToString(SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE),2), 10, "Verdana", clrYellow);
 
           Display("point value"+ shortname, (1700),(75));      // 1375                                                     
           ObjectSetText("point value"+ shortname,  "point value is "+DoubleToString( ((1/SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE)) * SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE)),2) , 10, "Verdana", clrYellow);
          
           double range = ((iHigh(NULL,PERIOD_D1,0)-iLow(NULL,PERIOD_D1,0)));
           double atr   = 0.0;
          
           if(_Symbol == "YM_U")  {atr = 568;}
           if(_Symbol == "ES_U")  {atr = 90;}
           if(_Symbol == "NQ_U")  {atr = 480;}
           if(_Symbol == "RTY_U") {atr = 50;}
 
          
           double dailyatrvalue = atr*((1/SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE)) * SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE));


           Display("daily atr"+ shortname, (1700),(100));      // 1375                                                     
           ObjectSetText("daily atr"+ shortname,  "daily atr is "+DoubleToString(atr,0)+"  "+DoubleToString(range,0), 10, "Verdana", clrYellow);
 
           Display("daily atr value"+ shortname, (1700),(125));      // 1375                                                     
           ObjectSetText("daily atr value"+ shortname,  "daily atr value is "+DoubleToString( dailyatrvalue,0), 10, "Verdana", clrYellow);
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
indicators , such as the one below, tend to be updated at a minimum..... if updated on every tick the cpu load is wasteful.....

if updating on a new bar, the weekend issue becomes apparent..... including a true/false bool input, solves that issue.....

the newbar code below is widely used......

be sure to keep weekend bool set to false unless its a weekend......h


//------

Code:
  bool NewBar()
    {
      static datetime previous = 0;
      datetime        current  = iTime(_Symbol,PERIOD_M1,0);
      
      if(previous!=current)
      {
      previous = current;
      return(true);
      }
      return(false);
    }

//-----

used in this manner......

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[])
  {




     if(NewBar() || weekend)
     { 
    
     //----
     //----
    
        
    } // if(NewBar)
    
    return rates_total;
}

//-----


chart as seen with weekend set false...... the graphics will not be updated....

//------

enivid weekend.jpg

//------


chart as seen with weekend set true...... graphics will be updated.....

//-----


weekend true.jpg
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
......h
//----

Code:
string symbol[]          = {"YM_U","ES_U","NQ_U","RTY_U","GC_V","","","6A_U","6B_U","6C_U","6E_U","6J_U","6N_U","6S_U","","","KE_U","ZC_U","ZL_Z","ZM_Z","ZS_X","BZ_U","CL_U","CL_V","HO_U","NG_U","RB_U","HE_U","LE_U","HG_U","PL_U","SL_U","ZN_U"};                           //   ,"","","","","","","","",""




int OnInit()
{
    IndicatorSetString(INDICATOR_SHORTNAME, shortname);
    
    int syms = ArraySize(symbol);
            
     for(int y = 0; y < syms; y++)                                         
        {
        Display(symbol[y], -100, 100+(y*50));                 
        ObjectSetText(symbol[y] , symbol[y], 10, "Verdana", clrAqua);
        }


    
    return INIT_SUCCEEDED;
}
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
zigzag direction.....h

//-----

Code:
//------

        double a = 0.0;
        double b = 0.0;
        double c = 0.0;
        
        for(int n=0; n<100; n++)  //  i<100
        {
        if(zigs[n]!=0.0)                                       
        {
         c = b;
         b = a;       
         a = zigs[n];
        
         if(c>0) break;
         n++;
        }
        }       
                  
    
        string zztxt = "dn";
        color  zzclr = clrMagenta;
        
        
        if(c > b)
          {
           zztxt = "up";
           zzclr = clrAqua;
          }
          
           Display("zig "+ shortname+ "  "+ IntegerToString(x) + " "+symbol[m] ,  4100+(x*100), 100+(m*50));                     
           ObjectSetText("zig "+ shortname+ "  "+ IntegerToString(x) + " "+symbol[m], zztxt, 10, "Verdana", zzclr);
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
does not appear to affect anything negatively, but when printing timeframes returns unexpected results.....h
//------

Code:
case 0: return(PERIOD_CURRENT);
      case 1: return(PERIOD_M1);
      case 5: return(PERIOD_M5);
      case 15: return(PERIOD_M15);
      case 30: return(PERIOD_M30);
      case 60: return(PERIOD_H1);
      case 240: return(PERIOD_H4);
      case 1440: return(PERIOD_D1);
      case 10080: return(PERIOD_W1);
      case 43200: return(PERIOD_MN1);
      
      case 2: return(PERIOD_M2);
      case 3: return(PERIOD_M3);
      case 4: return(PERIOD_M4);     
      case 6: return(PERIOD_M6);
      case 10: return(PERIOD_M10);
      case 12: return(PERIOD_M12);
      case 16385: return(PERIOD_H1);    // above  period m30 returns  
      case 16386: return(PERIOD_H2);
      case 16387: return(PERIOD_H3);
      case 16388: return(PERIOD_H4);
      case 16390: return(PERIOD_H6);
      case 16392: return(PERIOD_H8);
      case 16396: return(PERIOD_H12);
      case 16408: return(PERIOD_D1);
      case 32769: return(PERIOD_W1);
      case 49153: return(PERIOD_MN1);
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
mq5 multi dimensional arrays appear the same as mq4......h

//------

Code:
int signal[30][14][20];     // [symbol][time][indi]


ENUM_TIMEFRAMES TF[]   = {PERIOD_M1, PERIOD_M2, PERIOD_M3, PERIOD_M4, PERIOD_M5, PERIOD_M6, PERIOD_M10, PERIOD_M12, PERIOD_M15, PERIOD_M20, PERIOD_M30, PERIOD_H1, PERIOD_H4, PERIOD_D1};  //PERIOD_H1


//-----

//----
    
     for(int s = 0; s < 30; s++)                               // s for symbol
        {
     for(int t = 0; t < 14; t++)                               // t for time
        {
     for(int u = 0; u < 7; u++)                               // u for signal
        { 
        
         if(u==0)                                                            // zigzag
         {       
         if(signal[s][t][7 ] == 0) {Print(symbol[s]+"  "+TF[t]+"  "+ind[u]+" zigzag up");} else {Print(symbol[s]+"  "+TF[t]+"  "+ind[u]+" zigzag dn");}
         }
        }   
        }
        }
 

Enivid

Administrator
Staff member
Nov 30, 2008
19,234
1,507
144
Odesa
www.earnforex.com
does not appear to affect anything negatively, but when printing timeframes returns unexpected results.....h
//------

Code:
case 0: return(PERIOD_CURRENT);
      case 1: return(PERIOD_M1);
      case 5: return(PERIOD_M5);
      case 15: return(PERIOD_M15);
      case 30: return(PERIOD_M30);
      case 60: return(PERIOD_H1);
      case 240: return(PERIOD_H4);
      case 1440: return(PERIOD_D1);
      case 10080: return(PERIOD_W1);
      case 43200: return(PERIOD_MN1);
     
      case 2: return(PERIOD_M2);
      case 3: return(PERIOD_M3);
      case 4: return(PERIOD_M4);    
      case 6: return(PERIOD_M6);
      case 10: return(PERIOD_M10);
      case 12: return(PERIOD_M12);
      case 16385: return(PERIOD_H1);    // above  period m30 returns 
      case 16386: return(PERIOD_H2);
      case 16387: return(PERIOD_H3);
      case 16388: return(PERIOD_H4);
      case 16390: return(PERIOD_H6);
      case 16392: return(PERIOD_H8);
      case 16396: return(PERIOD_H12);
      case 16408: return(PERIOD_D1);
      case 32769: return(PERIOD_W1);
      case 49153: return(PERIOD_MN1);
In MQL5, ENUM_TIMEFRAMES elements don't have their int values equal the number of minutes in the respective timeframe. It's just a numeral for ordering timeframes. That doesn't change much - you just now have to use PeriodSeconds() to convert a timeframe to time.
 
  • 👍
Reactions: hayseed

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
In MQL5, ENUM_TIMEFRAMES elements don't have their int values equal the number of minutes in the respective timeframe. It's just a numeral for ordering timeframes. That doesn't change much - you just now have to use PeriodSeconds() to convert a timeframe to time.
//-----

thanks enivid...... i'll for sure read up on that ...... would have never noticed except was coding alerts and push notifications......

i'm slowly getting better with mq5...... makes me wish i could have started sooner, but had no place to put it to practical use.....

several of the futures brokers offer mq5......

hope as is well......h
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
some time back i was getting an error saying order close only or something like that.... quotes and all were coming in, indicators and all worked..... buy i could not place trades......

ea was working perfectly on everything else...... eventually gave up and just did not trade whatever it was......

figured it out today......

this morning 6n_u, new zeland dollar, trades would go in..... somewhere about mid morning i began to get that close only error again...... the charts works fine.....

changing the contract month to december, 6n_z, allows the trades to go thru..... had to edit the ea...... went ahead and changed all currencies to z......

possibly the best approach now is to use ide search function and replace 6n_u with 6n_z...... in all eas , indicators and scripts..... for all symbols affected......

do dread that......h

//---

enivid 6nu.jpg
 

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
rough but working draft of simple example .......

exporting to excel ..... will expand..... important thing is the symbol list is encoded so it's almost user explicit......h
//-------

enivid 27.jpg
 

Attachments

  • export to excel.mq5
    3.4 KB · Views: 1

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
bare minimum trailing ma stoploss code for darwin ea....... appears to work for sells..... yellow ma is 20.......h

//----

Screenshot 2024-09-16 201400.png





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);
           }
        
         }       
      
      
       }
    
      }
  
  
  
     }
 
Last edited:

hayseed

Master Trader
Jul 27, 2010
1,159
275
149
usa
trailing stops should probably run on New Bar() only...... otherwise needless load......

also, if using PERIOD_CURRENT switching timeframes can cause problems......

this is just me learning so all potential issues are not accounted for......h
//-----



//------ buttons on foreground
ObjectSetInteger(0,"Close All",OBJPROP_BACK,false);




//------
Code:
        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);
 
 double psars[];
 
 int   psar  = iSAR(NULL,PERIOD_CURRENT,0.01,0.2);
 
              ArraySetAsSeries(psars,true);
 
              CopyBuffer(psar,0,0,3,psars);
              
              


  if( NewBar())
  {
  if(trailingstophighlow)
    {
      if(Ask > low)
       {
       trailingstopbuy(low);
       }
      
       if(Bid < high)
       { 
       trailingstopsell(high);
       }
          
     }
//------

  if(trailingstopma  && (mas[0] > 0.0))
      {
       trailingma(mas[0]); 
      }



//------

  if(trailingstoppsar  && (psars[0] > 0.0))
      {
       trailingpsar(psars[0]); 
      }
 
 
   }
  
  
 //----
 //----



//-------
//-------



void trailingpsar(double psar)                                    //   
     {
      double newstoploss = NormalizeDouble(psar,_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 < psar)
           {
            trade.PositionModify(ticket,newstoploss,0);
           }
          
         }
        
        
       if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL)
         {
          ulong  ticket          = PositionGetInteger(POSITION_TICKET);
          
          double currentstoploss = PositionGetDouble(POSITION_SL);
          
          if(currentstoploss > psar)
           {
            trade.PositionModify(ticket,newstoploss,0);
           }
          
         }         
        
        
       }
      
      }
    
    
    
     }




 
  bool NewBar()
    {
      static datetime previous = 0;
      datetime        current  = iTime(_Symbol,PERIOD_M1,0);
      
      if(previous!=current)
      {
      previous = current;
      return(true);
      }
      return(false);
    }