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

please help :/
https://www.stevehopwoodforex.com/phpBB3/viewtopic.php?t=947
Page 1 of 1
Author:  monkeh [ Sat Nov 10, 2012 7:17 pm ]
Post subject:  please help :/

hello all,

before i kill myself, could someone please help me correcting this code for me.

EA places pending order x pips away, but if price gone too far (example by 30 pips) or at X number of candle close it should delete all pending orders - but it DOESNT...

can not get my head around it..

Code: Select all



#include <stderror.mqh>
extern string  EAName                        = "MK";
extern string  _1___________________________ = "___Money & Risk Management___";
extern double Lots                           = 0.1;
extern double TakeProfit                     = 8; // In Pips. Take Profit
extern double StopLoss                       = 8; // In Pips. Stop Loss 

extern string PrintComments                  = "___Prints Comments on the Screen__";
extern bool   PrintCommentsOnScreen          = true;
extern string TradeComments                  = " ";

extern string PipsDistance                   = "___Pips Distance for Pending Orders__";
extern int    Distance                       = 4;
extern double MagicNumber                    = 49999;
extern bool   IsOrderDeleteAllowed           = true;
extern int    OrderDeleteDistance            = 30;

extern string TradesClosing                  = "___Number of candles for Trade Closing__";
extern bool   CloseOnSameCandle              = false;
extern bool   CloseOnFixedNumberOfCandles    = true;
extern int    NumberOfCandles                = 2;

extern string TradesAllowed                  = "___Number of pending Orders Allowed__";
extern int    SellOrders                     = 10;
extern int    BuyOrders                      = 10;
extern bool   DoNotOpenOrdersAfterOne        =true;

extern string TimeFrame                      = "___Time Frame Selection__";
extern bool   IsMultiTimeFrame               = true;
extern int    TF                             = 60; 

datetime CurrentOrderTime;
string CurrentOrderComments;
double CurrentOrderProfitLoss, CurrentOrderOpenPrice, CurrentOrderTP, CurrentOrderSL;
datetime BarTime;
// Timeout 10 seconds
int Timeout = 10000;

// Number of retries upon failure
int Retries = 10;

// Current symbol to use if different from Chart
string CurrentSymbol = "";

// Current number of Digits
int CurrentDigits = 5;
//double MagicNumber;
// Current Points
double CurrentPoints = 0.0001;
string EAComment;
bool modify_allowed=false;
bool AllowTrade=true;

bool NewBar;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+

int init()
{
EAComment=EAName+", "+Symbol()+" "+Period(); 
BarTime=Time[0];
//MagicNumber = GetMagicNumber(Magic);
// If no symbol set use current chart
if(StringLen(CurrentSymbol) == 0)
CurrentSymbol = Symbol();

CurrentPoints = MarketInfo(CurrentSymbol, MODE_POINT);
CurrentDigits = MarketInfo(CurrentSymbol, MODE_DIGITS);

// Check the digits and points
if(CurrentPoints == 0.001)
{
CurrentPoints = 0.01;
CurrentDigits = 3;
}
else if(CurrentPoints == 0.00001)
{
CurrentPoints = 0.0001;
CurrentDigits = 5;
}
return(0);
}

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   if (ObjectFind("BKGR") >= 0) ObjectDelete("BKGR");
   if (ObjectFind("BKGR2") >= 0) ObjectDelete("BKGR2");
   if (ObjectFind("BKGR3") >= 0) ObjectDelete("BKGR3");
   if (ObjectFind("BKGR4") >= 0) ObjectDelete("BKGR4");
   if (ObjectFind("LV") >= 0) ObjectDelete("LV");
//----
   return(0);
  }

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
NewBar=isNewBar();

//if(AllowTrade) Print (AllowTrade);
if (PrintCommentsOnScreen) ShowComments ();
if ((!IsTesting()) && IsStopped()) { Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError()); return (0); }
if ((!IsTesting()) && !IsTradeAllowed()) { Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError()); return (0); }
if ((!IsTesting()) && IsTradeContextBusy()) { Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError()); return (0); }

if (!IsMultiTimeFrame)
{
if (TF!=Period()) { Print ("Wrong Time Frame", Period()) ; return (0);}
}

if (DoNotOpenOrdersAfterOne && (IsExecuted (OP_SELL)>0 || IsExecuted (OP_BUY)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());
} 

if (CloseOnSameCandle && (IsExecuted (OP_SELL)>0 || IsExecuted (OP_BUY)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());

}
if (DoNotOpenOrdersAfterOne && (IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());
} 

if (CloseOnSameCandle && (IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());

}
 
if (AllowTrade==true)
{   
if(IsExecuted (OP_BUYSTOP)<BuyOrders && Open[0]>Ask+Distance*CurrentPoints)
{
// No Buy stops open one
//modify_allowed=true;
NewStopOrder(OP_BUYSTOP);
}
else if(IsExecuted (OP_SELLSTOP)<SellOrders && Open[0]<Bid-Distance*CurrentPoints)
{
// No Sell stops open one
//modify_allowed=true;
NewStopOrder(OP_SELLSTOP);
}
else if (IsExecuted (OP_SELL)>0 || IsExecuted (OP_BUY)>0 || IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0)
{ OrderUpdate(); } 

else if (IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0)
{ 
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());
}
}
return(0);
}


double pips2Points(double pips)
{
double points;
if(Close[0]<10) {
points = pips*MathPow(10,Digits-4);
}
else if(Close[0]>10) {
points = pips*MathPow(10,Digits-2);
}
return(points);
}

void NewStopOrder(int orderType)
{
bool result;
bool loop = True;
int count = 0;
while (loop && count < Retries)
{
while (IsTradeContextBusy())
{
Sleep(Timeout);
count++;
}
RefreshRates();
double ask = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_ASK), CurrentDigits);
double bid = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_BID), CurrentDigits);
double point = MarketInfo(CurrentSymbol, MODE_POINT);

switch(orderType)
{
case OP_BUYSTOP:
result=OrderSend(CurrentSymbol, OP_BUYSTOP, Lots, ask + Distance*CurrentPoints, 0, 0, 0, TradeComments, MagicNumber, 0, Green);
if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
break;
case OP_SELLSTOP:
result=OrderSend(CurrentSymbol, OP_SELLSTOP, Lots, bid - Distance*CurrentPoints, 0, 0, 0, TradeComments, MagicNumber, 0, Red);
if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
break;
}
loop = parseError();
}
}


void OrderUpdate()
{
bool result;
double OrderTP, OrderSL;

for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol && OrderMagicNumber()==MagicNumber)
   {
      if (OrderStopLoss()==0)
      {  
         RefreshRates();
         double tp = pips2Points(TakeProfit)*Point;
         double sl = pips2Points(StopLoss)*Point;
         if (OrderType()==OP_SELL || OrderType()==OP_BUY) 
         {       
         switch(OrderType())
         {
            case OP_SELL:
            OrderSL=Bid+sl; OrderTP=Bid-tp;
            break;
            case OP_BUY:
            OrderSL=Ask-sl; OrderTP=Ask+tp;
            break;
         }
         if (TakeProfit==0) OrderTP=0;
         if (StopLoss==0) OrderSL=0;
         result=OrderModify(OrderTicket(),OrderOpenPrice(), OrderSL, OrderTP, 0, CLR_NONE);
         if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
         }
         
         else if (OrderType()==OP_SELLSTOP || OrderType()==OP_BUYSTOP) 
         {       
         switch(OrderType())
         {
            case OP_SELLSTOP:
            OrderSL=OrderOpenPrice()+sl; OrderTP=OrderOpenPrice()-tp;
            break;
            case OP_BUYSTOP:
            OrderSL=OrderOpenPrice()-sl; OrderTP=OrderOpenPrice()+tp;
            break;
         }
         if (TakeProfit==0) OrderTP=0;
         if (StopLoss==0) OrderSL=0;
         result=OrderModify(OrderTicket(),OrderOpenPrice(), OrderSL, OrderTP, 0, CLR_NONE);
         if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
         }
         
       }
       else 
       {
         RefreshRates();
         if (OrderType()==OP_SELL || OrderType()==OP_BUY) 
            {       
            
            switch(OrderType())
            {
            case OP_SELL:
            if (CloseOnSameCandle && Time[0]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Ask,0,Red);
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            else if(CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Ask,0,Red);
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            break;
            case OP_BUY:
            if (CloseOnSameCandle && Time[0]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Bid,0,MediumSeaGreen);
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            else if(CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Bid,0,MediumSeaGreen); 
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            break;
            }
            }
         }
          
      }
   }

}


int IsExecuted(int orderType)
{
int count = 0;
for (int i = 0; i < OrdersTotal(); i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol && OrderMagicNumber()==MagicNumber)
{
if (OrderType() == orderType)
{

if(orderType==OP_BUY) {
CurrentOrderProfitLoss=(Bid-OrderOpenPrice())/CurrentPoints;
CurrentOrderTime=OrderOpenTime();
CurrentOrderOpenPrice=OrderOpenPrice();
CurrentOrderComments=OrderComment();
CurrentOrderTP=(OrderTakeProfit()-OrderOpenPrice())/CurrentPoints;
CurrentOrderSL=(OrderOpenPrice()-OrderStopLoss())/CurrentPoints;
}
else if (orderType==OP_SELL) {
CurrentOrderProfitLoss= (OrderOpenPrice()-Ask)/CurrentPoints;
CurrentOrderTime=OrderOpenTime();
CurrentOrderOpenPrice=OrderOpenPrice();
CurrentOrderComments=OrderComment();
CurrentOrderTP=(OrderOpenPrice()-OrderTakeProfit())/CurrentPoints;
CurrentOrderSL=(OrderStopLoss()-OrderOpenPrice())/CurrentPoints;
}
count++;
}
}
}
return (count);
}

void DeletePendingOrder( int ticket)
{
bool BuyCond1, BuyCond2,BuyCond3,SellCond1,SellCond2,SellCond3, result;
RefreshRates();
if (OrderSelect(ticket, SELECT_BY_POS))
{
SellCond1=OrderType()== OP_SELLSTOP && (OrderOpenPrice() + OrderDeleteDistance*CurrentPoints) >= Bid;
SellCond2=OrderType()== OP_SELLSTOP && CloseOnSameCandle && Time[0]>OrderOpenTime();
SellCond3=OrderType()== OP_SELLSTOP && CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime();
BuyCond1=OrderType()== OP_BUYSTOP && (OrderOpenPrice() - OrderDeleteDistance*CurrentPoints) <= Ask;
BuyCond2=OrderType()== OP_BUYSTOP && CloseOnSameCandle && Time[0]>OrderOpenTime();
BuyCond3=OrderType()== OP_BUYSTOP && CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime();

   if ((SellCond1 || SellCond2 || SellCond3 || BuyCond1 || BuyCond2 || BuyCond3) && OrderMagicNumber()==MagicNumber )
   {  
   result=OrderDelete(ticket); Sleep(2000);
   if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
   } 
}
}

//+--------------------------------------------------------------------------------------------------------------+
//| ShowComments. Function to Show comments to User
//+--------------------------------------------------------------------------------------------------------------+
void ShowComments() {
//+--------------------------------------------------------------------------------------------------------------+
int stp, ssl;
//stp=TakeProfit; ssl=StopLoss;
string ComSpacer = ""; //--- "/n"
datetime MyOpDate = TIME_DATE; //--- 
//---
ComSpacer = ComSpacer
      + "\n  " 
      + "\n "
          + "\n-----------------------------------------------"
      + "\nEA Attached to : " + Symbol() + " M-"+Period()
      //+ "\n  Optimization date: " + TimeToStr (Date, MyOpDate)
      + "\n-----------------------------------------------" 
      + "\nSL = " + DoubleToStr(CurrentOrderSL,0) + " pips / TP = " + DoubleToStr(CurrentOrderTP,0) + " pips" ;
   
      //ComSpacer = ComSpacer 
      //+ "\n-----------------------------------------------"
      //ComSpacer = ComSpacer 
      //+ "\nTrading Lots = " + DoubleToStr(Lots, 2);
   
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nCurrrent Date: " 
      + TimeToStr (TimeCurrent());
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Comments : " 
      + CurrentOrderComments;
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Open Price : " 
      + DoubleToStr(CurrentOrderOpenPrice,CurrentDigits);
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Open Time : " 
      + TimeToStr(CurrentOrderTime);
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Profit/Loss (Pips): " 
      + DoubleToStr(CurrentOrderProfitLoss,1);

      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------";
      Comment(ComSpacer);
   
   if (ObjectFind("LV") < 0) {
      ObjectCreate("LV", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("LV", "EA By Bacha", 9, "Tahoma Bold", White);
      ObjectSet("LV", OBJPROP_CORNER, 0);
      ObjectSet("LV", OBJPROP_BACK, FALSE);
      ObjectSet("LV", OBJPROP_XDISTANCE, 13);
      ObjectSet("LV", OBJPROP_YDISTANCE, 23);
   }
   if (ObjectFind("BKGR") < 0) {
      ObjectCreate("BKGR", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR", "g", 110, "Webdings", White 	);
      ObjectSet("BKGR", OBJPROP_CORNER, 0);
      ObjectSet("BKGR", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR", OBJPROP_YDISTANCE, 15);
   }
   if (ObjectFind("BKGR2") < 0) {
      ObjectCreate("BKGR2", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR2", "g", 110, "Webdings", White);
      ObjectSet("BKGR2", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR2", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR2", OBJPROP_YDISTANCE, 60);
   }
   if (ObjectFind("BKGR3") < 0) {
      ObjectCreate("BKGR3", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR3", "g", 110, "Webdings", White);
      ObjectSet("BKGR3", OBJPROP_CORNER, 0);
      ObjectSet("BKGR3", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR3", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR3", OBJPROP_YDISTANCE, 45);
   }
   if (ObjectFind("BKGR4") < 0) {
      ObjectCreate("BKGR4", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR4", "g", 110, "Webdings", White);
      ObjectSet("BKGR4", OBJPROP_CORNER, 0);
      ObjectSet("BKGR4", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR4", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR4", OBJPROP_YDISTANCE, 84);
   }
}   

bool isNewBar() 
{
//---- 
   bool res=false; 
   if (BarTime!=Time[0]) 
      { BarTime=Time[0]; AllowTrade=true; } 
      res=true;
} 
   
//+--------------------------------------------------------------------------------------------------------------+
//| ErrorDescription. 
//+--------------------------------------------------------------------------------------------------------------+
string ErrorDescription(int error) {
//+--------------------------------------------------------------------------------------------------------------+

   string ErrorNumber;
   //---
   switch (error) {
   case 0:
   case 1:     ErrorNumber = "No error returned, but the result is unknown";        break;
   case 2:     ErrorNumber = "Common error";                                        break;
   case 3:     ErrorNumber = "Invalid trade parameters";                            break;
   case 4:     ErrorNumber = "Trade server is busy";                                break;
   case 5:     ErrorNumber = "Old version of the client terminal";                  break;
   case 6:     ErrorNumber = "No connection with trade server";                     break;
   case 7:     ErrorNumber = "Not enough rights";                                   break;
   case 8:     ErrorNumber = "Too frequent requests";                               break;
   case 9:     ErrorNumber = "Malfunctional trade operation";                       break;
   case 64:    ErrorNumber = "Account disabled";                                    break;
   case 65:    ErrorNumber = "Invalid account";                                     break;
   case 128:   ErrorNumber = "Trade timeout";                                       break;
   case 129:   ErrorNumber = "Invalid price";                                       break;
   case 130:   ErrorNumber = "Invalid stops";                                       break;
   case 131:   ErrorNumber = "Invalid trade volume";                                break;
   case 132:   ErrorNumber = "Market is closed";                                    break;
   case 133:   ErrorNumber = "Trade is disabled";                                   break;
   case 134:   ErrorNumber = "Not enough money";                                    break;
   case 135:   ErrorNumber = "Price changed";                                       break;
   case 136:   ErrorNumber = "Off quotes";                                          break;
   case 137:   ErrorNumber = "Broker is busy";                                      break;
   case 138:   ErrorNumber = "Requote";                                             break;
   case 139:   ErrorNumber = "Order is locked";                                     break;
   case 140:   ErrorNumber = "Long positions only allowed";                         break;
   case 141:   ErrorNumber = "Too many requests";                                   break;
   case 145:   ErrorNumber = "Modification denied because order too close to market";break;
   case 146:   ErrorNumber = "Trade context is busy";                                break;
   case 147:   ErrorNumber = "Expirations are denied by broker";                    break;
   case 148:   ErrorNumber = "The amount of open and pending orders has reached the limit set by the broker"; break;
   //---- 
   case 4000:  ErrorNumber = "No error";                                            break;
   case 4001:  ErrorNumber = "Wrong function pointer";                              break;
   case 4002:  ErrorNumber = "Array index is out of range";                         break;
   case 4003:  ErrorNumber = "No memory for function call stack";                   break;
   case 4004:  ErrorNumber = "Recursive stack overflow";                            break;
   case 4005:  ErrorNumber = "Not enough stack for parameter";                      break;
   case 4006:  ErrorNumber = "No memory for parameter string";                      break;
   case 4007:  ErrorNumber = "No memory for temp string";                           break;
   case 4008:  ErrorNumber = "Not initialized string";                              break;
   case 4009:  ErrorNumber = "Not initialized string in array";                     break;
   case 4010:  ErrorNumber = "No memory for array string";                          break;
   case 4011:  ErrorNumber = "Too long string";                                     break;
   case 4012:  ErrorNumber = "Remainder from zero divide";                          break;
   case 4013:  ErrorNumber = "Zero divide";                                         break;
   case 4014:  ErrorNumber = "Unknown command";                                     break;
   case 4015:  ErrorNumber = "Wrong jump (never generated error)";                  break;
   case 4016:  ErrorNumber = "Not initialized array";                               break;
   case 4017:  ErrorNumber = "DLL calls are not allowed";                           break;
   case 4018:  ErrorNumber = "Cannot load library";                                 break;
   case 4019:  ErrorNumber = "Cannot call function";                                break;
   case 4020:  ErrorNumber = "Expert function calls are not allowed";               break;
   case 4021:  ErrorNumber = "Not enough memory for temp string returned from function";    break;
   case 4022:  ErrorNumber = "System is busy (never generated error)";              break;
   case 4050:  ErrorNumber = "Invalid function parameters count";                   break;
   case 4051:  ErrorNumber = "Invalid function parameter value";                    break;
   case 4052:  ErrorNumber = "String function internal error";                      break;
   case 4053:  ErrorNumber = "Some array error";                                    break;
   case 4054:  ErrorNumber = "Incorrect series array using";                        break;
   case 4055:  ErrorNumber = "Custom indicator error";                              break;
   case 4056:  ErrorNumber = "Arrays are incompatible";                             break;
   case 4057:  ErrorNumber = "Global variables processing error";                   break;
   case 4058:  ErrorNumber = "Global variable not found";                           break;
   case 4059:  ErrorNumber = "Function is not allowed in testing mode";             break;
   case 4060:  ErrorNumber = "Function is not confirmed";                           break;
   case 4061:  ErrorNumber = "Send mail error";                                     break;
   case 4062:  ErrorNumber = "String parameter expected";                           break;
   case 4063:  ErrorNumber = "Integer parameter expected";                          break;
   case 4064:  ErrorNumber = "Double parameter expected";                           break;
   case 4065:  ErrorNumber = "Array as parameter expected";                         break;
   case 4066:  ErrorNumber = "Requested history data in updating state";            break;
   case 4067:  ErrorNumber = "Some error in trading function";                      break;
   case 4099:  ErrorNumber = "End of file";                                         break;
   case 4100:  ErrorNumber = "Some file error";                                     break;
   case 4101:  ErrorNumber = "Wrong file name";                                     break;
   case 4102:  ErrorNumber = "Too many opened files";                               break;
   case 4103:  ErrorNumber = "Cannot open file";                                    break;
   case 4104:  ErrorNumber = "Incompatible access to a file";                       break;
   case 4105:  ErrorNumber = "No order selected";                                   break;
   case 4106:  ErrorNumber = "Unknown symbol";                                      break;
   case 4107:  ErrorNumber = "Invalid price";                                       break;
   case 4108:  ErrorNumber = "Invalid ticket";                                      break;
   case 4109:  ErrorNumber = "Trade is not allowed. Enable checkbox Allow live trading in the expert properties";                                      break;
   case 4110:  ErrorNumber = "Longs are not allowed. Check the expert properties";  break;
   case 4111:  ErrorNumber = "Shorts are not allowed. Check the expert properties"; break;
   case 4200:  ErrorNumber = "Object exists already";                               break;
   case 4201:  ErrorNumber = "Unknown object property";                             break;
   case 4202:  ErrorNumber = "Object does not exist";                               break;
   case 4203:  ErrorNumber = "Unknown object type";                                 break;
   case 4204:  ErrorNumber = "No object name";                                      break;
   case 4205:  ErrorNumber = "Object coordinates error";                            break;
   case 4206:  ErrorNumber = "No specified subwindow";                              break;
   case 4207:  ErrorNumber = "Some error in object function";                       break;
   default:    ErrorNumber = "Unknown error";
   }
   //---
   return (ErrorNumber);
}
   
bool parseError()
{
bool buffer = false;
int Err = GetLastError();
switch (Err)
{
case ERR_NO_ERROR:
buffer = false;
break;
case ERR_SERVER_BUSY:
case ERR_NO_CONNECTION:
case ERR_INVALID_PRICE:
case ERR_OFF_QUOTES:
case ERR_BROKER_BUSY:
case ERR_TRADE_CONTEXT_BUSY:
case ERR_PRICE_CHANGED:
case ERR_REQUOTE:
buffer = true;
break;
case ERR_INVALID_STOPS:
buffer = false;
Print("Invalid Stops");
break;
case ERR_INVALID_TRADE_VOLUME:
buffer = false;
Print("Invalid Lots");
break;
case ERR_MARKET_CLOSED:
buffer = false;
Print("Market Close");
break;
case ERR_TRADE_DISABLED:
buffer = false;
Print("Trades Disabled");
break;
case ERR_NOT_ENOUGH_MONEY:
buffer = false;
Print("Not Enough Money");
break;
case ERR_TRADE_TOO_MANY_ORDERS:
buffer = false;
Print("Too Many Orders");
break;
case ERR_NO_RESULT:
default:
if(Err > 1)
Print("Unknown Error ", Err);
else
buffer = false;
break;
}
return (buffer);
}
Author:  gaheitman [ Sat Nov 10, 2012 10:27 pm ]
Post subject:  Re: please help :/

I don't think you are selecting the ticket correctly. In DeletePendingOrder() you have

Code: Select all

     if (OrderSelect(ticket, SELECT_BY_POS))
but you should have

Code: Select all

     if (OrderSelect(ticket, SELECT_BY_TICKET ))
George

monkeh wrote:hello all,

before i kill myself, could someone please help me correcting this code for me.

EA places pending order x pips away, but if price gone too far (example by 30 pips) or at X number of candle close it should delete all pending orders - but it DOESNT...

can not get my head around it..

Code: Select all



#include <stderror.mqh>
extern string  EAName                        = "MK";
extern string  _1___________________________ = "___Money & Risk Management___";
extern double Lots                           = 0.1;
extern double TakeProfit                     = 8; // In Pips. Take Profit
extern double StopLoss                       = 8; // In Pips. Stop Loss 

extern string PrintComments                  = "___Prints Comments on the Screen__";
extern bool   PrintCommentsOnScreen          = true;
extern string TradeComments                  = " ";

extern string PipsDistance                   = "___Pips Distance for Pending Orders__";
extern int    Distance                       = 4;
extern double MagicNumber                    = 49999;
extern bool   IsOrderDeleteAllowed           = true;
extern int    OrderDeleteDistance            = 30;

extern string TradesClosing                  = "___Number of candles for Trade Closing__";
extern bool   CloseOnSameCandle              = false;
extern bool   CloseOnFixedNumberOfCandles    = true;
extern int    NumberOfCandles                = 2;

extern string TradesAllowed                  = "___Number of pending Orders Allowed__";
extern int    SellOrders                     = 10;
extern int    BuyOrders                      = 10;
extern bool   DoNotOpenOrdersAfterOne        =true;

extern string TimeFrame                      = "___Time Frame Selection__";
extern bool   IsMultiTimeFrame               = true;
extern int    TF                             = 60; 

datetime CurrentOrderTime;
string CurrentOrderComments;
double CurrentOrderProfitLoss, CurrentOrderOpenPrice, CurrentOrderTP, CurrentOrderSL;
datetime BarTime;
// Timeout 10 seconds
int Timeout = 10000;

// Number of retries upon failure
int Retries = 10;

// Current symbol to use if different from Chart
string CurrentSymbol = "";

// Current number of Digits
int CurrentDigits = 5;
//double MagicNumber;
// Current Points
double CurrentPoints = 0.0001;
string EAComment;
bool modify_allowed=false;
bool AllowTrade=true;

bool NewBar;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+

int init()
{
EAComment=EAName+", "+Symbol()+" "+Period(); 
BarTime=Time[0];
//MagicNumber = GetMagicNumber(Magic);
// If no symbol set use current chart
if(StringLen(CurrentSymbol) == 0)
CurrentSymbol = Symbol();

CurrentPoints = MarketInfo(CurrentSymbol, MODE_POINT);
CurrentDigits = MarketInfo(CurrentSymbol, MODE_DIGITS);

// Check the digits and points
if(CurrentPoints == 0.001)
{
CurrentPoints = 0.01;
CurrentDigits = 3;
}
else if(CurrentPoints == 0.00001)
{
CurrentPoints = 0.0001;
CurrentDigits = 5;
}
return(0);
}

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   if (ObjectFind("BKGR") >= 0) ObjectDelete("BKGR");
   if (ObjectFind("BKGR2") >= 0) ObjectDelete("BKGR2");
   if (ObjectFind("BKGR3") >= 0) ObjectDelete("BKGR3");
   if (ObjectFind("BKGR4") >= 0) ObjectDelete("BKGR4");
   if (ObjectFind("LV") >= 0) ObjectDelete("LV");
//----
   return(0);
  }

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
NewBar=isNewBar();

//if(AllowTrade) Print (AllowTrade);
if (PrintCommentsOnScreen) ShowComments ();
if ((!IsTesting()) && IsStopped()) { Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError()); return (0); }
if ((!IsTesting()) && !IsTradeAllowed()) { Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError()); return (0); }
if ((!IsTesting()) && IsTradeContextBusy()) { Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError()); return (0); }

if (!IsMultiTimeFrame)
{
if (TF!=Period()) { Print ("Wrong Time Frame", Period()) ; return (0);}
}

if (DoNotOpenOrdersAfterOne && (IsExecuted (OP_SELL)>0 || IsExecuted (OP_BUY)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());
} 

if (CloseOnSameCandle && (IsExecuted (OP_SELL)>0 || IsExecuted (OP_BUY)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());

}
if (DoNotOpenOrdersAfterOne && (IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());
} 

if (CloseOnSameCandle && (IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0))
{ 
AllowTrade=false;
OrderUpdate();
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());

}
 
if (AllowTrade==true)
{   
if(IsExecuted (OP_BUYSTOP)<BuyOrders && Open[0]>Ask+Distance*CurrentPoints)
{
// No Buy stops open one
//modify_allowed=true;
NewStopOrder(OP_BUYSTOP);
}
else if(IsExecuted (OP_SELLSTOP)<SellOrders && Open[0]<Bid-Distance*CurrentPoints)
{
// No Sell stops open one
//modify_allowed=true;
NewStopOrder(OP_SELLSTOP);
}
else if (IsExecuted (OP_SELL)>0 || IsExecuted (OP_BUY)>0 || IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0)
{ OrderUpdate(); } 

else if (IsExecuted (OP_SELLSTOP)>0 || IsExecuted (OP_BUYSTOP)>0)
{ 
if (IsOrderDeleteAllowed)
DeletePendingOrder(OrderTicket());
}
}
return(0);
}


double pips2Points(double pips)
{
double points;
if(Close[0]<10) {
points = pips*MathPow(10,Digits-4);
}
else if(Close[0]>10) {
points = pips*MathPow(10,Digits-2);
}
return(points);
}

void NewStopOrder(int orderType)
{
bool result;
bool loop = True;
int count = 0;
while (loop && count < Retries)
{
while (IsTradeContextBusy())
{
Sleep(Timeout);
count++;
}
RefreshRates();
double ask = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_ASK), CurrentDigits);
double bid = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_BID), CurrentDigits);
double point = MarketInfo(CurrentSymbol, MODE_POINT);

switch(orderType)
{
case OP_BUYSTOP:
result=OrderSend(CurrentSymbol, OP_BUYSTOP, Lots, ask + Distance*CurrentPoints, 0, 0, 0, TradeComments, MagicNumber, 0, Green);
if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
break;
case OP_SELLSTOP:
result=OrderSend(CurrentSymbol, OP_SELLSTOP, Lots, bid - Distance*CurrentPoints, 0, 0, 0, TradeComments, MagicNumber, 0, Red);
if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
break;
}
loop = parseError();
}
}


void OrderUpdate()
{
bool result;
double OrderTP, OrderSL;

for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol && OrderMagicNumber()==MagicNumber)
   {
      if (OrderStopLoss()==0)
      {  
         RefreshRates();
         double tp = pips2Points(TakeProfit)*Point;
         double sl = pips2Points(StopLoss)*Point;
         if (OrderType()==OP_SELL || OrderType()==OP_BUY) 
         {       
         switch(OrderType())
         {
            case OP_SELL:
            OrderSL=Bid+sl; OrderTP=Bid-tp;
            break;
            case OP_BUY:
            OrderSL=Ask-sl; OrderTP=Ask+tp;
            break;
         }
         if (TakeProfit==0) OrderTP=0;
         if (StopLoss==0) OrderSL=0;
         result=OrderModify(OrderTicket(),OrderOpenPrice(), OrderSL, OrderTP, 0, CLR_NONE);
         if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
         }
         
         else if (OrderType()==OP_SELLSTOP || OrderType()==OP_BUYSTOP) 
         {       
         switch(OrderType())
         {
            case OP_SELLSTOP:
            OrderSL=OrderOpenPrice()+sl; OrderTP=OrderOpenPrice()-tp;
            break;
            case OP_BUYSTOP:
            OrderSL=OrderOpenPrice()-sl; OrderTP=OrderOpenPrice()+tp;
            break;
         }
         if (TakeProfit==0) OrderTP=0;
         if (StopLoss==0) OrderSL=0;
         result=OrderModify(OrderTicket(),OrderOpenPrice(), OrderSL, OrderTP, 0, CLR_NONE);
         if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
         }
         
       }
       else 
       {
         RefreshRates();
         if (OrderType()==OP_SELL || OrderType()==OP_BUY) 
            {       
            
            switch(OrderType())
            {
            case OP_SELL:
            if (CloseOnSameCandle && Time[0]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Ask,0,Red);
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            else if(CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Ask,0,Red);
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            break;
            case OP_BUY:
            if (CloseOnSameCandle && Time[0]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Bid,0,MediumSeaGreen);
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            else if(CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime())
            { 
            result=OrderClose(OrderTicket(),OrderLots(),Bid,0,MediumSeaGreen); 
            if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
            }
            break;
            }
            }
         }
          
      }
   }

}


int IsExecuted(int orderType)
{
int count = 0;
for (int i = 0; i < OrdersTotal(); i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol && OrderMagicNumber()==MagicNumber)
{
if (OrderType() == orderType)
{

if(orderType==OP_BUY) {
CurrentOrderProfitLoss=(Bid-OrderOpenPrice())/CurrentPoints;
CurrentOrderTime=OrderOpenTime();
CurrentOrderOpenPrice=OrderOpenPrice();
CurrentOrderComments=OrderComment();
CurrentOrderTP=(OrderTakeProfit()-OrderOpenPrice())/CurrentPoints;
CurrentOrderSL=(OrderOpenPrice()-OrderStopLoss())/CurrentPoints;
}
else if (orderType==OP_SELL) {
CurrentOrderProfitLoss= (OrderOpenPrice()-Ask)/CurrentPoints;
CurrentOrderTime=OrderOpenTime();
CurrentOrderOpenPrice=OrderOpenPrice();
CurrentOrderComments=OrderComment();
CurrentOrderTP=(OrderOpenPrice()-OrderTakeProfit())/CurrentPoints;
CurrentOrderSL=(OrderStopLoss()-OrderOpenPrice())/CurrentPoints;
}
count++;
}
}
}
return (count);
}

void DeletePendingOrder( int ticket)
{
bool BuyCond1, BuyCond2,BuyCond3,SellCond1,SellCond2,SellCond3, result;
RefreshRates();
if (OrderSelect(ticket, SELECT_BY_POS))
{
SellCond1=OrderType()== OP_SELLSTOP && (OrderOpenPrice() + OrderDeleteDistance*CurrentPoints) >= Bid;
SellCond2=OrderType()== OP_SELLSTOP && CloseOnSameCandle && Time[0]>OrderOpenTime();
SellCond3=OrderType()== OP_SELLSTOP && CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime();
BuyCond1=OrderType()== OP_BUYSTOP && (OrderOpenPrice() - OrderDeleteDistance*CurrentPoints) <= Ask;
BuyCond2=OrderType()== OP_BUYSTOP && CloseOnSameCandle && Time[0]>OrderOpenTime();
BuyCond3=OrderType()== OP_BUYSTOP && CloseOnFixedNumberOfCandles && Time[NumberOfCandles]>OrderOpenTime();

   if ((SellCond1 || SellCond2 || SellCond3 || BuyCond1 || BuyCond2 || BuyCond3) && OrderMagicNumber()==MagicNumber )
   {  
   result=OrderDelete(ticket); Sleep(2000);
   if (!result)Print(TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" | "+EAComment+" | "+ErrorDescription(GetLastError())+GetLastError());
   } 
}
}

//+--------------------------------------------------------------------------------------------------------------+
//| ShowComments. Function to Show comments to User
//+--------------------------------------------------------------------------------------------------------------+
void ShowComments() {
//+--------------------------------------------------------------------------------------------------------------+
int stp, ssl;
//stp=TakeProfit; ssl=StopLoss;
string ComSpacer = ""; //--- "/n"
datetime MyOpDate = TIME_DATE; //--- 
//---
ComSpacer = ComSpacer
      + "\n  " 
      + "\n "
          + "\n-----------------------------------------------"
      + "\nEA Attached to : " + Symbol() + " M-"+Period()
      //+ "\n  Optimization date: " + TimeToStr (Date, MyOpDate)
      + "\n-----------------------------------------------" 
      + "\nSL = " + DoubleToStr(CurrentOrderSL,0) + " pips / TP = " + DoubleToStr(CurrentOrderTP,0) + " pips" ;
   
      //ComSpacer = ComSpacer 
      //+ "\n-----------------------------------------------"
      //ComSpacer = ComSpacer 
      //+ "\nTrading Lots = " + DoubleToStr(Lots, 2);
   
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nCurrrent Date: " 
      + TimeToStr (TimeCurrent());
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Comments : " 
      + CurrentOrderComments;
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Open Price : " 
      + DoubleToStr(CurrentOrderOpenPrice,CurrentDigits);
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Open Time : " 
      + TimeToStr(CurrentOrderTime);
      
      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------"
      +"\nTrade Profit/Loss (Pips): " 
      + DoubleToStr(CurrentOrderProfitLoss,1);

      ComSpacer = ComSpacer 
      + "\n-----------------------------------------------";
      Comment(ComSpacer);
   
   if (ObjectFind("LV") < 0) {
      ObjectCreate("LV", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("LV", "EA By Bacha", 9, "Tahoma Bold", White);
      ObjectSet("LV", OBJPROP_CORNER, 0);
      ObjectSet("LV", OBJPROP_BACK, FALSE);
      ObjectSet("LV", OBJPROP_XDISTANCE, 13);
      ObjectSet("LV", OBJPROP_YDISTANCE, 23);
   }
   if (ObjectFind("BKGR") < 0) {
      ObjectCreate("BKGR", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR", "g", 110, "Webdings", White 	);
      ObjectSet("BKGR", OBJPROP_CORNER, 0);
      ObjectSet("BKGR", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR", OBJPROP_YDISTANCE, 15);
   }
   if (ObjectFind("BKGR2") < 0) {
      ObjectCreate("BKGR2", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR2", "g", 110, "Webdings", White);
      ObjectSet("BKGR2", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR2", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR2", OBJPROP_YDISTANCE, 60);
   }
   if (ObjectFind("BKGR3") < 0) {
      ObjectCreate("BKGR3", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR3", "g", 110, "Webdings", White);
      ObjectSet("BKGR3", OBJPROP_CORNER, 0);
      ObjectSet("BKGR3", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR3", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR3", OBJPROP_YDISTANCE, 45);
   }
   if (ObjectFind("BKGR4") < 0) {
      ObjectCreate("BKGR4", OBJ_LABEL, 0, 0, 0);
      ObjectSetText("BKGR4", "g", 110, "Webdings", White);
      ObjectSet("BKGR4", OBJPROP_CORNER, 0);
      ObjectSet("BKGR4", OBJPROP_BACK, TRUE);
      ObjectSet("BKGR4", OBJPROP_XDISTANCE, 5);
      ObjectSet("BKGR4", OBJPROP_YDISTANCE, 84);
   }
}   

bool isNewBar() 
{
//---- 
   bool res=false; 
   if (BarTime!=Time[0]) 
      { BarTime=Time[0]; AllowTrade=true; } 
      res=true;
} 
   
//+--------------------------------------------------------------------------------------------------------------+
//| ErrorDescription. 
//+--------------------------------------------------------------------------------------------------------------+
string ErrorDescription(int error) {
//+--------------------------------------------------------------------------------------------------------------+

   string ErrorNumber;
   //---
   switch (error) {
   case 0:
   case 1:     ErrorNumber = "No error returned, but the result is unknown";        break;
   case 2:     ErrorNumber = "Common error";                                        break;
   case 3:     ErrorNumber = "Invalid trade parameters";                            break;
   case 4:     ErrorNumber = "Trade server is busy";                                break;
   case 5:     ErrorNumber = "Old version of the client terminal";                  break;
   case 6:     ErrorNumber = "No connection with trade server";                     break;
   case 7:     ErrorNumber = "Not enough rights";                                   break;
   case 8:     ErrorNumber = "Too frequent requests";                               break;
   case 9:     ErrorNumber = "Malfunctional trade operation";                       break;
   case 64:    ErrorNumber = "Account disabled";                                    break;
   case 65:    ErrorNumber = "Invalid account";                                     break;
   case 128:   ErrorNumber = "Trade timeout";                                       break;
   case 129:   ErrorNumber = "Invalid price";                                       break;
   case 130:   ErrorNumber = "Invalid stops";                                       break;
   case 131:   ErrorNumber = "Invalid trade volume";                                break;
   case 132:   ErrorNumber = "Market is closed";                                    break;
   case 133:   ErrorNumber = "Trade is disabled";                                   break;
   case 134:   ErrorNumber = "Not enough money";                                    break;
   case 135:   ErrorNumber = "Price changed";                                       break;
   case 136:   ErrorNumber = "Off quotes";                                          break;
   case 137:   ErrorNumber = "criminal is busy";                                      break;
   case 138:   ErrorNumber = "Requote";                                             break;
   case 139:   ErrorNumber = "Order is locked";                                     break;
   case 140:   ErrorNumber = "Long positions only allowed";                         break;
   case 141:   ErrorNumber = "Too many requests";                                   break;
   case 145:   ErrorNumber = "Modification denied because order too close to market";break;
   case 146:   ErrorNumber = "Trade context is busy";                                break;
   case 147:   ErrorNumber = "Expirations are denied by criminal";                    break;
   case 148:   ErrorNumber = "The amount of open and pending orders has reached the limit set by the criminal"; break;
   //---- 
   case 4000:  ErrorNumber = "No error";                                            break;
   case 4001:  ErrorNumber = "Wrong function pointer";                              break;
   case 4002:  ErrorNumber = "Array index is out of range";                         break;
   case 4003:  ErrorNumber = "No memory for function call stack";                   break;
   case 4004:  ErrorNumber = "Recursive stack overflow";                            break;
   case 4005:  ErrorNumber = "Not enough stack for parameter";                      break;
   case 4006:  ErrorNumber = "No memory for parameter string";                      break;
   case 4007:  ErrorNumber = "No memory for temp string";                           break;
   case 4008:  ErrorNumber = "Not initialized string";                              break;
   case 4009:  ErrorNumber = "Not initialized string in array";                     break;
   case 4010:  ErrorNumber = "No memory for array string";                          break;
   case 4011:  ErrorNumber = "Too long string";                                     break;
   case 4012:  ErrorNumber = "Remainder from zero divide";                          break;
   case 4013:  ErrorNumber = "Zero divide";                                         break;
   case 4014:  ErrorNumber = "Unknown command";                                     break;
   case 4015:  ErrorNumber = "Wrong jump (never generated error)";                  break;
   case 4016:  ErrorNumber = "Not initialized array";                               break;
   case 4017:  ErrorNumber = "DLL calls are not allowed";                           break;
   case 4018:  ErrorNumber = "Cannot load library";                                 break;
   case 4019:  ErrorNumber = "Cannot call function";                                break;
   case 4020:  ErrorNumber = "Expert function calls are not allowed";               break;
   case 4021:  ErrorNumber = "Not enough memory for temp string returned from function";    break;
   case 4022:  ErrorNumber = "System is busy (never generated error)";              break;
   case 4050:  ErrorNumber = "Invalid function parameters count";                   break;
   case 4051:  ErrorNumber = "Invalid function parameter value";                    break;
   case 4052:  ErrorNumber = "String function internal error";                      break;
   case 4053:  ErrorNumber = "Some array error";                                    break;
   case 4054:  ErrorNumber = "Incorrect series array using";                        break;
   case 4055:  ErrorNumber = "Custom indicator error";                              break;
   case 4056:  ErrorNumber = "Arrays are incompatible";                             break;
   case 4057:  ErrorNumber = "Global variables processing error";                   break;
   case 4058:  ErrorNumber = "Global variable not found";                           break;
   case 4059:  ErrorNumber = "Function is not allowed in testing mode";             break;
   case 4060:  ErrorNumber = "Function is not confirmed";                           break;
   case 4061:  ErrorNumber = "Send mail error";                                     break;
   case 4062:  ErrorNumber = "String parameter expected";                           break;
   case 4063:  ErrorNumber = "Integer parameter expected";                          break;
   case 4064:  ErrorNumber = "Double parameter expected";                           break;
   case 4065:  ErrorNumber = "Array as parameter expected";                         break;
   case 4066:  ErrorNumber = "Requested history data in updating state";            break;
   case 4067:  ErrorNumber = "Some error in trading function";                      break;
   case 4099:  ErrorNumber = "End of file";                                         break;
   case 4100:  ErrorNumber = "Some file error";                                     break;
   case 4101:  ErrorNumber = "Wrong file name";                                     break;
   case 4102:  ErrorNumber = "Too many opened files";                               break;
   case 4103:  ErrorNumber = "Cannot open file";                                    break;
   case 4104:  ErrorNumber = "Incompatible access to a file";                       break;
   case 4105:  ErrorNumber = "No order selected";                                   break;
   case 4106:  ErrorNumber = "Unknown symbol";                                      break;
   case 4107:  ErrorNumber = "Invalid price";                                       break;
   case 4108:  ErrorNumber = "Invalid ticket";                                      break;
   case 4109:  ErrorNumber = "Trade is not allowed. Enable checkbox Allow live trading in the expert properties";                                      break;
   case 4110:  ErrorNumber = "Longs are not allowed. Check the expert properties";  break;
   case 4111:  ErrorNumber = "Shorts are not allowed. Check the expert properties"; break;
   case 4200:  ErrorNumber = "Object exists already";                               break;
   case 4201:  ErrorNumber = "Unknown object property";                             break;
   case 4202:  ErrorNumber = "Object does not exist";                               break;
   case 4203:  ErrorNumber = "Unknown object type";                                 break;
   case 4204:  ErrorNumber = "No object name";                                      break;
   case 4205:  ErrorNumber = "Object coordinates error";                            break;
   case 4206:  ErrorNumber = "No specified subwindow";                              break;
   case 4207:  ErrorNumber = "Some error in object function";                       break;
   default:    ErrorNumber = "Unknown error";
   }
   //---
   return (ErrorNumber);
}
   
bool parseError()
{
bool buffer = false;
int Err = GetLastError();
switch (Err)
{
case ERR_NO_ERROR:
buffer = false;
break;
case ERR_SERVER_BUSY:
case ERR_NO_CONNECTION:
case ERR_INVALID_PRICE:
case ERR_OFF_QUOTES:
case ERR_BROKER_BUSY:
case ERR_TRADE_CONTEXT_BUSY:
case ERR_PRICE_CHANGED:
case ERR_REQUOTE:
buffer = true;
break;
case ERR_INVALID_STOPS:
buffer = false;
Print("Invalid Stops");
break;
case ERR_INVALID_TRADE_VOLUME:
buffer = false;
Print("Invalid Lots");
break;
case ERR_MARKET_CLOSED:
buffer = false;
Print("Market Close");
break;
case ERR_TRADE_DISABLED:
buffer = false;
Print("Trades Disabled");
break;
case ERR_NOT_ENOUGH_MONEY:
buffer = false;
Print("Not Enough Money");
break;
case ERR_TRADE_TOO_MANY_ORDERS:
buffer = false;
Print("Too Many Orders");
break;
case ERR_NO_RESULT:
default:
if(Err > 1)
Print("Unknown Error ", Err);
else
buffer = false;
break;
}
return (buffer);
}
Author:  monkeh [ Sat Nov 10, 2012 10:58 pm ]
Post subject:  Re: please help :/

[quote="gaheitman"]I don't think you are selecting the ticket correctly. In DeletePendingOrder() you have

Code: Select all

     if (OrderSelect(ticket, SELECT_BY_POS))
but you should have

Code: Select all

     if (OrderSelect(ticket, SELECT_BY_TICKET ))
George


hi George,

im thanking you for your help!
how -ever it still does not delete pending orders when conditions are met, as if they would be wrongly defined..
Author:  gaheitman [ Sat Nov 10, 2012 11:37 pm ]
Post subject:  Re: please help :/

OK, another issue is that you aren't explicitly selecting an order in Start() prior to calling

Code: Select all

DeletePendingOrder(OrderTicket());
You'll use whatever the last ticket was that OrderUpdate() selected. So, you are only running this code against the first order on the trade tab.

George
monkeh wrote:
gaheitman wrote:I don't think you are selecting the ticket correctly. In DeletePendingOrder() you have

Code: Select all

     if (OrderSelect(ticket, SELECT_BY_POS))
but you should have

Code: Select all

     if (OrderSelect(ticket, SELECT_BY_TICKET ))
George


hi George,

im thanking you for your help!
how -ever it still does not delete pending orders when conditions are met, as if they would be wrongly defined..
Author:  monkeh [ Sun Nov 11, 2012 1:10 am ]
Post subject:  Re: please help :/

but isnt it selected @

Code: Select all

void DeletePendingOrder( int ticket)
{
bool BuyCond1, BuyCond2,BuyCond3,SellCond1,SellCond2,SellCond3, result;
RefreshRates();
if (OrderSelect(ticket, SELECT_BY_TICKET))
?

sorry George,
im just totally newb at mql4.
my knowledge is 5 days old :oops:
Author:  gaheitman [ Sun Nov 11, 2012 2:04 am ]
Post subject:  Re: please help :/

You select it within DeletePendingOrder(), but when you call DeletePendingOrder(), you call it with the currently selected ticket (which means you are just re-selecting the same ticket that is already active):

Code: Select all

		if (IsOrderDeleteAllowed)
			DeletePendingOrder(OrderTicket());
If you want to review all the pending tickets, you need to have the call to DeletePendingOrder in the same kind of loop you are using on the open tickets in OrderUpdate().

George
monkeh wrote:but isnt it selected @

Code: Select all

void DeletePendingOrder( int ticket)
{
bool BuyCond1, BuyCond2,BuyCond3,SellCond1,SellCond2,SellCond3, result;
RefreshRates();
if (OrderSelect(ticket, SELECT_BY_TICKET))
?

sorry George,
im just totally newb at mql4.
my knowledge is 5 days old :oops:
Author:  monkeh [ Sun Nov 11, 2012 11:37 am ]
Post subject:  Re: please help :/

thank you very much!
theory understood, will give it a try.
Author:  SteveHopwood [ Sun Nov 11, 2012 11:51 pm ]
Post subject:  Re: please help :/

monkeh wrote:hello all,

before i kill myself, could someone please help me correcting this code for me.
I know how you feel. :lol:

Stick with it; you will not be sorry and will soon see why I proclaim that all traders should also be coders. I see you have George's help, so you will make rapid progress. I wish I had A George when I started...................

Up an' at 'em, tiger. Have fun too; it is fantastic when a piece of code works out.

:D
All times are UTC Page 1 of 1