stevehopwoodforex.com
https://www.stevehopwoodforex.com/phpBB3/
Print view

code needed
https://www.stevehopwoodforex.com/phpBB3/viewtopic.php?t=4906
Page 1 of 1
Author:  Dreamer711 [ Mon Sep 19, 2016 10:19 pm ]
Post subject:  code needed

Hi guys
i need help with my EA in mql4
i basically need to add a code that tells the EA not to open a buy order if there is already an open buy order within e.g. 10 pips of the current market price
and same thing not to open a sell order if there is already A sell order close to the market price by a certain number of pips.
thank you
Author:  renexxxx [ Mon Sep 19, 2016 10:41 pm ]
Post subject:  code needed

you could create function tradeExists() like so:

Code: Select all

bool tradeExists(string symbol, int orderType, double proximity) {

   bool exists = false;
   
   for (int iOrder=OrdersTotal()-1; iOrder >= 0; iOrder--) {
   
      if ( OrderSelect( iOrder, SELECT_BY_POS, MODE_TRADES ) ) {
      
         if ( OrderMagicNumber() != MagicNumber ) continue;
         if ( OrderSymbol() != symbol) continue;
         if ( OrderType() != orderType ) continue;
         
         double ask = MarketInfo( symbol, MODE_ASK );
         double bid = MarketInfo( symbol, MODE_BID );

         if ( ( (orderType == OP_BUY) && ( MathAbs(OrderOpenPrice() - ask) < proximity ) ) ||
              ( (orderType == OP_SELL) && ( MathAbs(OrderOpenPrice() - bid) < proximity ) ) ) {
            
            exists = true;
            break;
         }
      }
   }
   return(exists);
}
and call it somewhere in your code as:

Code: Select all

   double pipFactor = 10000.0; // Set the pipFactor appropriately
   
   if ( tradeExists( _Symbol, OP_BUY, ProximityPIPs / pipFactor ) ) {
      
      Print(" Trade already exists ... ");
   }
assuming that you have the input parameters ..

Code: Select all

input     int        MagicNumber      = 3249214;
input     double     ProximityPIPs    = 10.0;
Hope this helps.
Author:  Dreamer711 [ Mon Sep 19, 2016 11:54 pm ]
Post subject:  code needed

Thank you so much for responding , can i give you my EA and you add the code to it

Code: Select all

//-------------------------------------------------------------------------------------
//                  NoProgra Builder - Create EAs without any programming
//                      Copyright © 2012, NoProgra (http://www.noprogra.com)
//                         Get support at http://www.noprogra.com                      
//+--------------------------------------------------------------------------------------
// EXPERT ADVISOR GENERATED USING NOPROGRA BUILDER FOR EDUCATIONAL PURPOSES. 
// This EA does not constitute financial advice.  
//
// 
// UNDER NO CIRCUMSTANCES WILL NOPROGRA BE LIABLE TO YOU, OR ANY OTHER PERSON OR ENTITY,
// FOR ANY LOSS OF USE, REVENUE OR PROFIT, LOST OR DAMAGED DATA, OR OTHER COMMERCIAL OR
// ECONOMIC LOSS OR FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, STATUTORY, PUNITIVE,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES WHATSOEVER RELATED TO YOUR USE OF THIS EXPERT 
// ADVISOR OR NOPROGRA BUILDER     
//
// USE THIS EXPERT ADVISOR AT YOUR OWN RISK. 
//  
//+--------------------------------------------------------------------------------------
	
#property copyright "Copyright © 2011, Generated with NoProgra Builder"
#property link      "http://www.noprogra.com"

//************Variables

//Empty4 Variables
extern double Lotsize1 = 0.01;
extern double takeprofit1 = 0;
extern double stoploss1 = 0;
extern double trailing1 = 0;

extern double MAperiod = 2;
extern double BWLevel = 0;
extern double BWEXIT = 0;


//Main Variables

extern int Start_Time = 0;          // Time to allow trading to start ( hours of 24 hr clock ) 0 for both disables
extern int End_Time = 24;        // Time to stop trading ( hours of 24 hr clock ) 0 for both disables
extern bool TradeBars = true;  // You can trade bars or ticks. If TradeBars=true, the ea trade bars.
extern bool UseFiveDigits = true;    // You can use 5 or 4 digit brokers. If UseFiveDigits = true, your broker uses 5 digits
int FiveDMultiplier = 1;             // Manages the 5 digit fix  
extern bool isECN = false;            // If true, orders are opened and later TP/SL is added
extern int Positions = 99;            // Max open positions
extern bool AllowHedge=true; 		 // Set AllowHedge=true to hedge
extern int Slippage = 3;             // Minimum slippage to trade 
extern int MagicNumber = 5432101;    //EA's magic number 
string goLong="SUPERENKO101";    //Comment for long order
string goShort="SUPERENKO101";  //Comment for short order
int PreviousBars = 0;                  // Used for bar counting



//************Include Empty4 files
#include <stdlib.mqh>
#include <stderror.mqh>
#include <WinUser32.mqh>
////////////////////////////////////////////////////////////////////////////////////////
string StringSubstrOld(string x,int a,int b=-1) 
{
   if(a<0) a=0; // Stop odd behaviour
   if(b<=0) b=-1; // new MQL4 EOL flag
   return StringSubstr(x,a,b);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

//************Init EA
int init()
{

   	Print("NoProgra: Starting EA ");  
 	Print("NoProgra: Broker Information : Symbol=",Symbol(),". MIN LOT=",MarketInfo(Symbol(), MODE_MINLOT),". MAX LOT=",MarketInfo(Symbol(), MODE_MAXLOT),". LOT SIZE IN BASE CURRENCY=",MarketInfo(Symbol(), MODE_LOTSIZE));
 	Print("NoProgra: Min Stops= ",MarketInfo(Symbol(), MODE_STOPLEVEL), " pips.");
   
   	goLong="SUPERENKO101 "+MagicNumber;              
   	goShort="SUPERENKO101 "+MagicNumber;            
	
	
	if (UseFiveDigits) 
   	{
      FiveDMultiplier = 10;    
   	}
   	Slippage = Slippage*FiveDMultiplier;
   
   	if( (Digits==5 || Digits==3) && (!UseFiveDigits) )
     {
      Print("NoProgra:",Symbol()," Your setup is 4 digits but you seem to use a 5 digits broker. Please change UseFiveDigits to true");
      MessageBox("NoProgra: Your setup is 4 digits but you seem to use a 5 digits broker. Please change UseFiveDigits to true","5 Digits management");
     }
   	if( (Digits==4 || Digits==2) && (UseFiveDigits) )
     {
      Print("NoProgra:",Symbol()," Your setup is 5 digits but you seem to use a 4 digits broker. Please change UseFiveDigits to false");
      MessageBox("NoProgra: Your setup is 5 digits but you seem to use a 4 digits broker. Please change UseFiveDigits to false","5 Digits management");
     }   
     
	if (AllowHedge) {
	Print("NoProgra:",Symbol()," You ALLOW hedging.");	     
	} else {
	Print("NoProgra:",Symbol()," You DO NOT ALLOW hedging.");
	}
	
   	if(OrdersTotal()>0) {
   	  Print("NoProgra:",Symbol()," Warning! There are existing positions. You may want to close them before running this EA.");	     
   	  MessageBox("NoProgra: Warning! There are existing positions. You may want to close them before running this EA.","NoProgra Warning: There are existing positions");       
   	}
if (Hour()>=Start_Time || Hour()<End_Time) //Preferd Trading Hours
   
   if(Bars<80) {    
    Print("NoProgra:",Symbol()," There are less than 80 historical bars."); 
    MessageBox("NoProgra: There are less than 80 historical bars.","NoProgra Warning");
   }
   
   if(IsTradeAllowed()==false) {    
    Print("NoProgra: Trading is not allowed! Make sure the checkbox Allow Live Trading is checked.");
    MessageBox("Trading is not allowed! Make sure the checkbox Allow Live Trading is checked.","NoProgra Warning");
   }

 	RefreshRates();   

 	return(0);
}
  
//************Stop EA
int deinit()
  {
	Print("NoProgra:",Symbol()," Stopping EA.");   
   	return(0);
  }
  
//************EA Execution
int start()
{
  if(IsStopped())
    {
     Print("NoProgra:",Symbol()," EA is stopping!");
     return(0);
    } 
   
   if ((PreviousBars==Bars) && TradeBars) {
      return(0);
   }
  
	
//************Trading conditions

//************GO LONG

  if ( iClose(Symbol(), 0, 1) > iMA(Symbol(), 0, 3, 0, MODE_SMA, PRICE_CLOSE, 1) && 

iCustom(Symbol(), 0, "BandsBandwidth",5,0,2.0, 0, 1) > BWLevel )
 { Print("Trading condition [iClose(Symbol(), 0, 1) > iMA(Symbol(), 0, 3, 0, MO...] is valid.Trying to open long position...");
       Buy(Symbol(), Lotsize1, takeprofit1, stoploss1, trailing1); }     
 
//************EXIT LONG


 if  (iCustom(Symbol(), 0, "BandsBandwidth",5,0,2.0, 0, 1) < BWEXIT)
CloseLong(Symbol()); 

//************GO SHORT
 
  if ( iClose(Symbol(), 0, 1) < iMA(Symbol(), 0, 3, 0, MODE_SMA, PRICE_CLOSE, 1) && 

 iCustom(Symbol(), 0, "BandsBandwidth",5,0,2.0, 0, 1) > BWLevel)
 { Print("Trading condition [iClose(Symbol(), 0, 1) > iMA(Symbol(), 0, 3, 0, MO...] is valid.Trying to open long position...");
       Sell(Symbol(), Lotsize1, takeprofit1, stoploss1, trailing1); }     
 
  

//************EXIT SHORT


 if ( iCustom(Symbol(), 0, "BandsBandwidth",5,0,2.0, 0, 1) < BWEXIT)
CloseShort(Symbol()); 

  
  

//************LONG TRAILING STOPS

 CheckTrailingStop(Symbol(), OP_BUY, MagicNumber, trailing1);



//************SHORT TRAILING STOPS

 CheckTrailingStop(Symbol(), OP_SELL, MagicNumber, trailing1);



	PreviousBars=Bars;    
   	return(0);
}
//+------------------------------------------------------------------+

//************EA Functions

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int Buy(string symbol, double lotsize, double takeprofit, double stoploss, double trailings) {
   
      if (!AllowHedge) CloseAllPositions(symbol,OP_SELL,MagicNumber);
      if (!isECN) {
         if (ExecuteOrder(OP_BUY, symbol, lotsize, stoploss, takeprofit, goLong, MagicNumber, Green)>0) {   
         } 
      } else {
         if (ExecuteECNOrder(OP_BUY, symbol, lotsize, stoploss, takeprofit, goLong, MagicNumber, Green)>0) {   
         } 
      }
         
 	return(0);
}  

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int Sell(string symbol, double lotsize, double takeprofit, double stoploss, double trailings) {
   
      if (!AllowHedge) CloseAllPositions(symbol,OP_BUY,MagicNumber);
      if (!isECN) {
         if (ExecuteOrder(OP_SELL, symbol, lotsize,stoploss, takeprofit, goShort, MagicNumber, Red)>0) {   
         } 
      } else {
         if (ExecuteECNOrder(OP_SELL, symbol, lotsize, stoploss, takeprofit, goShort, MagicNumber, Red)>0) {   
         } 
      }
         
 	return(0);
}   

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int CloseLong(string symbol) {
 
 	CloseAllPositions(symbol,OP_BUY,MagicNumber);
 	CloseAllPositions(symbol,OP_BUY,MagicNumber);
 	
 	return(0);
}

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int CloseShort(string symbol) {
 
 	CloseAllPositions(symbol,OP_SELL,MagicNumber);
 	CloseAllPositions(symbol,OP_SELL,MagicNumber);
 
 	return(0);
}

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
bool EnoughMoney(string symbol, double lotsize) {
   
   	if( ( AccountFreeMarginCheck( symbol, OP_BUY,  lotsize ) < 15 ) || 
             ( AccountFreeMarginCheck( symbol, OP_SELL, lotsize ) < 15 ) || ( GetLastError() == 134 ) ) {
         Print("NoProgra: No money to trade. Free Margin=", AccountFreeMargin()); 
         Alert("NoProgra: NoProgra: No money to trade. Free Margin=", AccountFreeMargin()); 
         return(false); 
         } else {
           return(true); 
         }
}

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int ExecuteECNOrder(int ordertype, string symbol, double lotsize, double stoploss, double takeprofit, string commentOrder, int magic, color ordercolor) 
 {
   	int errorcode_ts=0;
   	Print("NoProgra:",Symbol()," ECN order: 1 Sending order without stops");
   	int my_ticket = ExecuteOrder(ordertype, symbol, lotsize, 0, 0, commentOrder, magic, ordercolor);  
   	if ( my_ticket > 0 && (stoploss != 0 || takeprofit != 0) )
    {
     Print("NoProgra:",Symbol()," ECN order: Adding stops");
     if (OrderSelect(my_ticket, SELECT_BY_TICKET)) {
         RefreshRates();
         double points_,digits_, price_;
		 bool golong;
   		 digits_ = MarketInfo(symbol, MODE_DIGITS);
	     points_ = MarketInfo(symbol, MODE_POINT);
	     stoploss=stoploss*FiveDMultiplier;
	     takeprofit=takeprofit*FiveDMultiplier;
	     		   
   		 switch (ordertype) {
	     	case OP_BUY: 
		    	golong=true;
			    break; 
		   case OP_SELL: 
			    golong=false;
			    break;
		   default:    
			   Print("NoProgra:",Symbol()," ERROR - Wrong order type. Cannot add stops to ECN order - ", ordertype);
		       return(-1);
		       break; 
		   }

   	  if (golong) {
	     		price_ = NormalizeDouble(MarketInfo(symbol,MODE_ASK),digits_);
		    	if (stoploss > 0) {
			      	stoploss = NormalizeDouble(price_-stoploss*points_, digits_);
			    }
			   if (takeprofit>0) {
				   takeprofit = NormalizeDouble(price_+takeprofit*points_, digits_);
			    }
		  } else {  
			   price_ = NormalizeDouble(MarketInfo(symbol,MODE_BID),digits_);
			   if (stoploss > 0) {
				  stoploss = NormalizeDouble(price_+stoploss*points_, digits_); 
			    }
			   if (takeprofit>0) {
				  takeprofit = NormalizeDouble(price_-takeprofit*points_, digits_);
			   }
		  }
  	   

           if (OrderModify(my_ticket,OrderOpenPrice(),stoploss,takeprofit,0,ordercolor))
                     {
                        Print("NoProgra:",Symbol()," ECN order - Stops added. SL=",stoploss," TP=",takeprofit);                        
                     } else {
                        errorcode_ts=GetLastError(); 
                        Print("NoProgra:",Symbol()," ECN order failed. Order executed but stops were not added. Error:",errorcode_ts," ",ErrorDescription(errorcode_ts));
                     }

      } else {//closes if order select 
         errorcode_ts=GetLastError(); 
         Print("NoProgra:",Symbol()," ECN order failed. Order executed but couldn't select order to add stops. Error:",errorcode_ts," ",ErrorDescription(errorcode_ts));
      }
    
    } 
   
 }

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
 int ExecuteOrder(int ordertype_, string symbol_, double lotsize_, double stoploss_, double takeprofit_, string comment_, int magic_, color ordercolor_)   
 { int digits_;
   double points_;
   double price_;
   
   int ticket_;
   bool golong_;
   int errorcode_;
   
   stoploss_=stoploss_*FiveDMultiplier;
   takeprofit_=takeprofit_*FiveDMultiplier;
   
   
   switch (ordertype_) {
      case OP_BUY: 
         golong_=true;
         break; 
      case OP_SELL: 
         golong_=false;
         break;
      default:    
         Print("NoProgra:",Symbol()," ERROR : Wrong order type ", ordertype_);
         return(-1);
         break; 
   }
   
   
   if (CalculateOpenPositions(symbol_,ordertype_,magic_)>=Positions) {
        Print("NoProgra:",Symbol()," Max number of ",Positions," open positions reached. Cannot execute new ",OrderTypetoString(ordertype_)," order for Symbol ",symbol_); 
        return(0); 
   }
   
   if (!EnoughMoney(symbol_, lotsize_)) {
       return(-1); }
          
   digits_ = MarketInfo(symbol_, MODE_DIGITS);
   points_ = MarketInfo(symbol_, MODE_POINT);
   

   RefreshRates();

  
   if (golong_) {
         price_ = NormalizeDouble(MarketInfo(symbol_,MODE_ASK),digits_);
         
         if (stoploss_ > 0)  { 
 
               stoploss_ = NormalizeDouble(price_-stoploss_*points_, digits_);
             
               }
         
         
         if (takeprofit_ > 0) {

            takeprofit_= NormalizeDouble(price_+takeprofit_*points_, digits_);
            
            }
         
         Print("NoProgra:",Symbol()," Preparing BUY order for ",symbol_);
         
      } else {  
         price_ = NormalizeDouble(MarketInfo(symbol_,MODE_BID),digits_);
         
          if (stoploss_ > 0) {
               
               stoploss_ = NormalizeDouble(price_+stoploss_*points_, digits_); 
               
               }
         
         if (takeprofit_>0) {
            
            takeprofit_= NormalizeDouble(price_-takeprofit_*points_, digits_);
            
            }
           
         Print("NoProgra:",Symbol()," Preparing SELL order for ",symbol_);
         
      } 

         if (!isTradingPossible()) {
                       Print("NoProgra:",Symbol()," Trading may not be possible. Trying to execute order anyway...");
                       }
                             
         ticket_=OrderSend(symbol_,ordertype_,lotsize_,price_,Slippage,stoploss_,takeprofit_,comment_,magic_,0,ordercolor_);
         
         if(ticket_>=0)
           {
            Sleep(2000);
                       
            if(OrderSelect(ticket_,SELECT_BY_TICKET)) 
               {
             
                 Print("NoProgra:",Symbol()," Order ", OrderTypetoString(ordertype_)," for Symbol=", symbol_, " was executed Successfully. Ticket=",ticket_);         
                 return(ticket_);
                 
               }  else {
                    
                    Print("NoProgra:",Symbol()," Order ", OrderTypetoString(ordertype_)," for Symbol=", symbol_, " was executed Successfully but cannot get ticket. Trying again...");
                    Sleep(2000);
                    if(OrderSelect(ticket_,SELECT_BY_TICKET)) 
                     {             
                     
                       Print("NoProgra:",Symbol()," Got ticket for Order ", OrderTypetoString(ordertype_)," for Symbol=", symbol_, " Ticket=",ticket_);
					   return(ticket_);
                       
                     } else {
                       Print("NoProgra:",Symbol()," Order ", OrderTypetoString(ordertype_)," for Symbol=", symbol_, " was executed Successfully but cannot get ticket. WILL NOT TRY AGAIN");	
                       return(0);
                     }
               
               }
           } else {
                  errorcode_ = GetLastError();
                  Print("NoProgra:",Symbol()," ERROR - Couldn't execute order ", OrderTypetoString(ordertype_)," for Symbol=", symbol_," due to error ",errorcode_, " ",ErrorDescription(errorcode_)); 
                  Alert("NoProgra:",Symbol()," ERROR - Couldn't execute order ", OrderTypetoString(ordertype_)," for Symbol=", symbol_," due to error ",errorcode_, " ",ErrorDescription(errorcode_)); 
           }          
       
 }

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int CalculateOpenPositions(string symbol,int ordertype,int magicn) 
  {
   int sells=0;
   int buys=0;
   
   int sellstop=0;
   int buystop=0;
   
   bool magiccond=true;
  
   if(ordertype==OP_BUY || ordertype==OP_SELL || ordertype==OP_SELLSTOP || ordertype==OP_BUYSTOP) {
   
   } else {
    Print("NoProgra:",Symbol()," Failed to calculate number of open positions. Order type is wrong.");
    Alert("NoProgra:",Symbol()," Failed to calculate number of open positions. Order type is wrong.");
    return(-1);
  }

   int orderstotal = OrdersTotal();
   for(int i=0;i<orderstotal;i++)
     {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
        if (magicn==0) { 
                 magiccond=true; 
               } else {
                 if (OrderMagicNumber() == magicn) {
                     magiccond=true;
                 } else {
                     magiccond=false;                
                 }
                     
         }
               
      if ((OrderSymbol()==symbol) && (magiccond))
        {
         
         if(OrderType()==OP_SELL) sells++;
         if(OrderType()==OP_BUY) buys++;
         
         if(OrderType()==OP_SELLSTOP) sellstop++;
         if(OrderType()==OP_BUYSTOP) buystop++;
         
        }
     }

   if(ordertype==OP_SELL) return(sells);
   if(ordertype==OP_BUY) return(buys);
   
   if(ordertype==OP_SELLSTOP) return(sellstop);
   if(ordertype==OP_BUYSTOP) return(buystop);
   
   return(-1);      
  }
   
//************Copyright © 2012, NoProgra (http://www.noprogra.com)
string OrderTypetoString(int ordertypecode)
{
	if (ordertypecode == OP_BUY)
		return("OP_BUY");

	if (ordertypecode == OP_SELL)
		return("OP_SELL");

	if (ordertypecode == OP_BUYSTOP)
		return("OP_BUYSTOP");

	if (ordertypecode == OP_SELLSTOP)
		return("OP_SELLSTOP");

	if (ordertypecode == OP_BUYLIMIT)
		return("OP_BUYLIMIT");

	if (ordertypecode == OP_SELLLIMIT)
		return("OP_SELLLIMIT");

	return("Unknow order type");
}


//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int CloseAllPositions(string symbolclose, int ordertypeclose, int magicclose)
{
  
  int cnt;
  int err;
  int retrynumberclose=0;
  double priceclose;
  bool magiccond=true;
  //verify type is ok
  if(ordertypeclose==OP_BUY || ordertypeclose==OP_SELL) {
   //ok 
   } else {
    Print("NoProgra:",Symbol()," Closing all positions failed. Order type is wrong.");
    Alert("NoProgra:",Symbol()," Closing all positions failed. Order type is wrong.");
    return(-1);
  }
  
  
  int orderstotal=OrdersTotal();          
  bool loopcl=true;
  while (loopcl) { 
   loopcl=false;
   orderstotal=OrdersTotal();
   for(cnt=0;cnt<orderstotal;cnt++)
        {
         if (OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES)) //executes if gets valid order
            {
            
            if (magicclose==0) { 
                 magiccond=true; 
               } else {
                 if (OrderMagicNumber() == magicclose) {
                     magiccond=true;
                 } else {
                     magiccond=false;                
                 }
                     
               }
            if((OrderType()==ordertypeclose) && (OrderSymbol()==symbolclose) && (magiccond))  
               {
                   
                   RefreshRates();
                    if(ordertypeclose==OP_BUY) priceclose=MarketInfo(symbolclose,MODE_BID);
                      else priceclose=MarketInfo(symbolclose,MODE_ASK);
                   if (!isTradingPossible()) {
                       Print("NoProgra: Trading may not be possible. Trying to close position anyway...");
                       }
                   if (OrderClose(OrderTicket(),OrderLots(),priceclose,Slippage,Violet)) // close position
                         {
                           Print("NoProgra:",Symbol()," Position closed successfully. Trade info: Symbol:",symbolclose,". Lots:",OrderLots(),". Ticket number:",OrderTicket(),". Closed at price:",OrderClosePrice(),". Position was opened at price:",OrderOpenPrice()," Profit:",OrderProfit());                           
                           loopcl=true;
                           retrynumberclose=1;
                           break;
                        }else {
                           err=GetLastError();
                           Print("NoProgra:",Symbol()," Closing Order failed. Trade info: Symbol:",symbolclose,". Lots:",OrderLots(),". Ticket number:",OrderTicket(),". Error:",err," ",ErrorDescription(err));
                           Alert("NoProgra:",Symbol()," Closing Order failed. Trade info: Symbol:",symbolclose,". Lots:",OrderLots(),". Ticket number:",OrderTicket(),". Error:",err," ",ErrorDescription(err));
                           Sleep(2000);
                                            
                           loopcl=true;
                           retrynumberclose++;
                           break;  
                        }
                  
               }    
             
            }
         }
   if (retrynumberclose>20) {
      Print("NoProgra:",Symbol()," Stopping Closing all positions. Too many errors when closing positions. Symbol:",symbolclose);
      Print("NoProgra:",Symbol()," URGENT: User interaction is required.");
      Alert("NoProgra:",Symbol()," Stopping Closing all positions. Too many errors when closing positions. Symbol:",symbolclose);
      Alert("NoProgra:",Symbol()," URGENT: User interaction is required.");
      return(-1);
   }      
  } 
 
return(0); 
}

//************Copyright © 2012, NoProgra (http://www.noprogra.com)
bool isTradingPossible()
{
//Check if trading is possible
bool tmpresponse=true;
  if(!IsConnected())
    {
     Print("NoProgra: URGENT ACTION REQUIRED : There is no connection to the server!");
     Alert("URGENT ACTION REQUIRED : There is no connection to the server!");
     tmpresponse=false;
    }
  if(IsStopped())
    {
     Print("NoProgra:",Symbol()," ERROR: EA was commanded to stop its operation!");
     Alert("ERROR : EA was commanded to stop its operation!");
     tmpresponse=false;
    } 
   if (!IsTradeAllowed()) {
     Print("NoProgra:",Symbol()," ERROR : Trading is not allowed!");
     Alert("ERROR : Trading is not allowed!");
     tmpresponse=false; 
   } 
   return(tmpresponse);
} 
   
//************Copyright © 2012, NoProgra (http://www.noprogra.com)
int CheckTrailingStop(string symbol_ts, int ordertypeclose_ts,int magicnumber_ts, double tralingstop_ts)
{
   
   if (tralingstop_ts<=0)
      {  return(0);
      }
    
  if(ordertypeclose_ts==OP_BUY || ordertypeclose_ts==OP_SELL) {
   
   } else {
    Print("NoProgra:",Symbol()," Check Trailing Stop failed. Order type is wrong.");
    return(-1);
  }
    double TrailingStop = tralingstop_ts;
    double oldStop=0;
    int errorcode_ts = 0;
    bool magiccond_ts; 
            
   int orderstotal=OrdersTotal();   
   for(int i=0;i<orderstotal;i++)
   {
      
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) {
         Print("NoProgra:",Symbol()," Warning: Could not select order to ckeck change on trailing stop. Continuing..."); 
         continue;
      }
      
      if (magicnumber_ts==0) { 
                 magiccond_ts=true; 
               } else {
               if (OrderMagicNumber() == magicnumber_ts) {
                     magiccond_ts=true; 
               } else {
                     magiccond_ts=false;                
               }
                     
      }
               
      if(OrderSymbol()==symbol_ts && magiccond_ts)
      {
         RefreshRates();
         if(ordertypeclose_ts==OP_SELL) 
          {
            if(TrailingStop>0)  
            {                 
               RefreshRates();
               if((OrderOpenPrice()-MarketInfo(symbol_ts, MODE_ASK))>(MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier))
                 {
                  if((OrderStopLoss()>(MarketInfo(symbol_ts, MODE_ASK)+MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier)) || (OrderStopLoss()==0))
                    {
                     oldStop=OrderStopLoss();
                     if (OrderModify(OrderTicket(),OrderOpenPrice(),MarketInfo(symbol_ts, MODE_ASK)+MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier,OrderTakeProfit(),0,Red))
                     {
                        Print("NoProgra:",Symbol()," SL changed using trailing stop. Old SL=",oldStop," New SL=",MarketInfo(symbol_ts, MODE_ASK)+MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier);
                        
                     }else {
                        errorcode_ts=GetLastError(); 
                        Print("NoProgra:",Symbol()," Warning: Could not change SL value with trailing stop. Error:",errorcode_ts," ",ErrorDescription(errorcode_ts));
                     }
                     
                    }
                 }
            }
            
          }
          if(ordertypeclose_ts==OP_BUY)  
            {
             if(TrailingStop>0)  
              {                 
               RefreshRates();
               if(MarketInfo(symbol_ts, MODE_BID)-OrderOpenPrice()>MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier)
                 {
                  if(OrderStopLoss()<MarketInfo(symbol_ts, MODE_BID)-MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier)
                    {
                     oldStop=OrderStopLoss();
                     if (OrderModify(OrderTicket(),OrderOpenPrice(),MarketInfo(symbol_ts, MODE_BID)-MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier,OrderTakeProfit(),0,Green))
                     {
                        Print("NoProgra:",Symbol()," SL changed using trailing stop. Old SL=",oldStop," New SL=",MarketInfo(symbol_ts, MODE_BID)-MarketInfo(symbol_ts, MODE_POINT)*TrailingStop*FiveDMultiplier);
                     }else {
                        errorcode_ts=GetLastError(); 
                        Print("NoProgra:",Symbol()," Warning: Could not change SL value with trailing stop. Error:",errorcode_ts," ",ErrorDescription(errorcode_ts));
                     }
                     
                    }
                 }
              }
            }
             
       }
     }
return(1);
}

]
Author:  renexxxx [ Tue Sep 20, 2016 9:38 pm ]
Post subject:  code needed

Here you go (attached).

Don't ask me for support. You would be far better of if you'd learn to code, rather than to use this code generator, as you will be stuck if the code generator can't do what you want.

R.
Author:  Dreamer711 [ Tue Sep 20, 2016 10:42 pm ]
Post subject:  code needed

Hi Renexxx

the EA still put orders closer than the proximityPIPS , but anyway thank you so much for taking the time to work on this , I appreciate your effort
Cheers :D
Author:  renexxxx [ Wed Sep 21, 2016 12:56 am ]
Post subject:  code needed

Dreamer711 » Wed Sep 21, 2016 8:42 am wrote: the EA still put orders closer than the proximityPIPS , but anyway thank you so much for taking the time to work on this , I appreciate your effort
Redownload the file. I made a small change. As this does not concern anyone else this topic is now closed.
All times are UTC Page 1 of 1