Bad stops, bad strategy generator

massive spam
mt4 every tick

2020.09.17 02:00:13.171    2017.02.24 13:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 13:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.00542, min. price allowed: 1.00692, stop/limit order price: 1.
2020.09.17 02:00:13.265    2017.02.24 14:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 14:00 Opening order type BUY STOP with price 1.00308. Current market prices: 1.00417 / 1.00416
2020.09.17 02:00:13.265    2017.02.24 14:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 14:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.00417, min. price allowed: 1.00567, stop/limit order price: 1.
2020.09.17 02:00:13.436    2017.02.24 15:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 15:00 Opening order type BUY STOP with price 1.00319. Current market prices: 1.00384 / 1.00383
2020.09.17 02:00:13.436    2017.02.24 15:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 15:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.00384, min. price allowed: 1.00534, stop/limit order price: 1.
2020.09.17 02:00:13.655    2017.02.24 16:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 16:00 Opening order type BUY STOP with price 1.00325. Current market prices: 1.00303 / 1.00302
2020.09.17 02:00:13.655    2017.02.24 16:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 16:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.00303, min. price allowed: 1.00453, stop/limit order price: 1.
2020.09.17 02:00:13.952    2017.02.24 17:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 17:00 Opening order type BUY STOP with price 1.00331. Current market prices: 1.00621 / 1.0062
2020.09.17 02:00:13.952    2017.02.24 17:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 17:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.00621, min. price allowed: 1.00771, stop/limit order price: 1.
2020.09.17 02:00:14.233    2017.02.24 18:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 18:00 Opening order type BUY STOP with price 1.00354. Current market prices: 1.00673 / 1.00672
2020.09.17 02:00:14.233    2017.02.24 18:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 18:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.00673, min. price allowed: 1.00823, stop/limit order price: 1.
2020.09.17 02:00:14.358    2017.02.24 19:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 19:00 Opening order type BUY STOP with price 1.00368. Current market prices: 1.00551 / 1.0055
2020.09.17 02:00:14.358    2017.02.24 19:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 19:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.00551, min. price allowed: 1.00701, stop/limit order price: 1.
2020.09.17 02:00:14.468    2017.02.24 20:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 20:00 Opening order type BUY STOP with price 1.00377. Current market prices: 1.0066 / 1.00659
2020.09.17 02:00:14.468    2017.02.24 20:00:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 20:00 Based on its logic, the strategy tried to place stop/limit order at incorrect price. Market price: 1.0066, min. price allowed: 1.0081, stop/limit order price: 1.00
2020.09.17 02:00:14.608    2017.02.24 20:40:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 20:40  Deleting pending order, ticket: 14
2020.09.17 02:00:14.608    2017.02.24 20:40:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: delete #14 sell stop 0.10 USDCHF at 1.00200 sl: 1.00750 tp: 0.98850 ok
2020.09.17 02:00:14.608    2017.02.24 20:40:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.24 20:40 Order deleted successfuly
2020.09.17 02:00:15.061    2017.02.27 00:01:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.27 00:01 Opening order type BUY STOP with price 1.00973. Current market prices: 1.00692 / 1.00691
2020.09.17 02:00:15.061    2017.02.27 00:01:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: open #15 buy stop 0.10 USDCHF at 1.00973 ok
2020.09.17 02:00:15.061    2017.02.27 00:01:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.27 00:01 Modifying order with ticket: 15, SL: 1.00423000 and PT: 1.02323000
2020.09.17 02:00:15.061    2017.02.27 00:01:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: modify #15 buy stop 0.10 USDCHF at 1.00973 sl: 1.00423 tp: 1.02323 ok
2020.09.17 02:00:15.061    2017.02.27 00:01:00  Strategy 5.44.150 fixed usdchf h1 USDCHF,H1: - SQ LOG 2017.02.27 00:01 Order modified successfuly



//+------------------------------------------------------------------+
//| Strategy 5.44.150 EA
//|
//| Generated by StrategyQuant X Build 129 at 09/16/2020 22:25
//|
//| This EA uses 3rd party library OrderReliable for industry-strength
//| order handling. OrderReliable library is normally distributed under
//| GPL license. Its author provided it under MIT license limited to
//| usage only within strategies generated by StrategyQuant. 
//|  
//| This means that this library doesn't restrict you to use your EA
//| generated by SQ comercially in any way you want. 
//| But if you'll use any method from OrderReliable library outside
//| of this EA in your own EAs or projects, its use will be governed
//| by its standard GPL license. 
//|
//| Scroll to the very bottom of this source code for the full text
//| of OrderReliable license.
//+------------------------------------------------------------------+

#property copyright "StrategyQuant.com"
#property link      "http://www.StrategyQuant.com"


#include <stdlib.mqh>
#include <stderror.mqh>

const int SLPTTYPE_RANGE = 0;
const int SLPTTYPE_LEVEL = 1;

//+------------------------------------------------------------------+
// -- Variables
//+------------------------------------------------------------------+
extern string CustomComment = "Strategy 5.44.150";

extern int MagicNumber = 11111;
bool LongEntrySignal = false;
bool ShortEntrySignal = false;
bool LongExitSignal = false;
bool ShortExitSignal = false;
extern int KCBarCloseserPeriod = 20;
extern double PriceEntryMult = 1.1;
extern int BarsValid = 170;
extern int ProfitTarget = 135;
extern int StopLoss = 55;
extern double TrailingStopCoef = 4.3;
extern int TrailingActivation = 80;
extern int MTATRPeriod = 14;

//+------------------------------------------------------------------+
// Money Management variables
//+------------------------------------------------------------------+

extern string smm = "----------- Money Management - Fixed size -----------";
extern double mmLots = 0.1;

//+------------------------------------------------------------------+
// Trading Options variables
//+------------------------------------------------------------------+

extern string seod = "----------- Exit At End Of Day -----------";
extern bool ExitAtEndOfDay = false;
extern string EODExitTime = "23:04";

extern string seof = "----------- Exit On Friday -----------";
extern bool ExitOnFriday = true;
extern string FridayExitTime = "20:40";

extern string sltr = "----------- Limit Time Range -----------";
extern bool LimitTimeRange = false;
extern string SignalTimeRangeFrom = "08:00";
extern string SignalTimeRangeTo = "16:00";
extern bool ExitAtEndOfRange = false;

extern string smtpd = "----------- Max Trades Per Day -----------";
extern int MaxTradesPerDay = 0;
extern string smmslpt = "----------- Min/Max SL/PT -----------";
extern int MinimumSL = 0;   //Minimum SL in pips
extern int MinimumPT = 0;   //Minimum PT in pips
extern int MaximumSL = 0;   //Maximum SL in pips
extern int MaximumPT = 0;   //Maximum PT in pips


     
extern string slts = "----------- Use Tick size from SQ (for CFDs) -----------";
// For exotic pairs (usually non forex CFDs) the default method of computing
// tick size in EA might not work correctly.
// By turning this on and specifying MainChartTickSizeSQ value you can let EA
// use the correct tick size         
extern bool UseSQTickSize = false;                                                                            
extern double MainChartTickSizeSQ = -1.0;

//+------------------------------------------------------------------+
// OrderReliable library variables
//+------------------------------------------------------------------+
string     OrderReliableVersion = "v36";
string     OrderReliable_Fname = "OrderReliable (Function Name Not Set)";

int     retry_attempts               = 10000; // general retry attempts
int     retry_attempts_bad_price   = 3;  // retry attempts if the error is bad price
double     sleep_time                   = 2.0;
double     sleep_maximum               = 20.0;


int     ErrorLevel             = 3;

bool    UseLimitToMarket     = false;
bool    UseForTesting         = false;
bool    AddSpreadToComment    = false;

//+------------------------------------------------------------------+
// -- SQ internal variables
// add word "extern" in front of the variable you want
// to make configurable
//+------------------------------------------------------------------+
int sqMaxEntrySlippage = 5;          //Max tolerated entry slippage in pips. Zero means unlimited slippage
int sqMaxCloseSlippage = 0;          //Max tolerated close slippage in pips. Zero means unlimited slippage      
bool autoCorrectMaxSlippage = true;  //If set to true, it will automatically adjust max slippage according to symbol digits (*10 for 3 and 5 digit symbols) 

//Some brokers have problems with updating position counts. Set this timeout to non-zero value if you experience this.
//For example EnterReverseAtMarket doesn't work well for Admiral Markets, because OrdersTotal() returns 1 even after the order has been closed.
uint orderSelectTimeout = 0;         //in ms

double sqMinDistance = 15.0;

//+------------------------------------------------------------------+
// Verbose mode values:
// 0 - don't print messages to log at all
// 1 - print messages to log only when trading (not when backtesting)
// 2 - print messages to log always
//+------------------------------------------------------------------+
int sqVerboseMode = 2;

extern bool sqDisplayInfoPanel = true;
extern bool ModifyInsteadOfReplacing = true;

extern int OpenBarDelay = 0; // open bar delay in minutes
// it can be used for Daily strategies to trigger trading a few minutes later -
// because brokers sometimes have technical delay after midnight and we have to postpone order execution

int sqLabelCorner = 1;
int sqOffsetHorizontal = 5;
int sqOffsetVertical = 20;
color sqLabelColor = White;

datetime _sqLastOpenBarTime = 0;
bool _sqIsBarOpen = false;
double gPointCoef = 0;
int _ticket;                    
bool cond[100];

double initialBalance = 0;                   
   
bool openingOrdersAllowed = true;
bool firstCall = true;

////////
//+------------------------------------------------------------------+
// -- Functions
//+------------------------------------------------------------------+

void OnTick() {

   sqInitStart();      
  
   sqManageOrders(MagicNumber);
  
   openingOrdersAllowed = sqHandleTradingOptions();

   //------------------------
   // Rule: Trading signals
   //------------------------
if (sqIsBarOpen()) {
     // init signals only on bar open
     LongEntrySignal = (sqGetValue("NULL",0, PRICE_CLOSE, 1) < sqKeltnerChannel(NULL,0, KCBarCloseserPeriod, 1, 0, 1));

     ShortEntrySignal = (sqGetValue("NULL",0, PRICE_CLOSE, 1) > sqKeltnerChannel(NULL,0, KCBarCloseserPeriod, 1, 1, 1));

     LongExitSignal = false;

     ShortExitSignal = false;

   }


               
   //------------------------
   // Rule: Long entry
   //------------------------
   if (sqIsBarOpen()
      && LongEntrySignal)
   {
      // Action #1
      _ticket = sqOpenOrder(OP_BUYSTOP, "Current", mmLots, (sqDaily(NULL,0, "Low", 3) + (PriceEntryMult * roundValue(iATR(NULL,0, MTATRPeriod, 2)))), MagicNumber, "", 0, true, false, CLR_NONE);

      if(_ticket > 0 && OrderSelect(_ticket, SELECT_BY_TICKET)) {
         // set or initialize all order exit methods (SL, PT, Trailing Stop, Exit After Bars, etc.)
         sqSetOrderExpiration(_ticket, BarsValid);

         // StopLoss & ProfitTarget
         sqSetSLandPT(_ticket, sqGetSLLevel("Current", OP_BUYSTOP, OrderOpenPrice(), 1, StopLoss), sqGetPTLevel("Current", OP_BUYSTOP, OrderOpenPrice(), 1, ProfitTarget));

         // TrailingStop initialization
         sqSetGlobalVariable(_ticket, "TrailingStop", sqStringHash("TrailingStopCoef * sqATR(NULL,0,20,1)"));
         sqSetGlobalVariable(_ticket, "TrailingStopType", SLPTTYPE_RANGE);
         sqSetGlobalVariable(_ticket, "TrailingActivation", sqStringHash("TrailingActivation"));
      }



  }

               
   //------------------------
   // Rule: Short entry
   //------------------------
   if (sqIsBarOpen()
      && (ShortEntrySignal
      && (!(LongEntrySignal))))
   {
      // Action #1
      _ticket = sqOpenOrder(OP_SELLSTOP, "Current", mmLots, (sqDaily(NULL,0, "High", 3) - (PriceEntryMult * roundValue(iATR(NULL,0, MTATRPeriod, 2)))), MagicNumber, "", 0, true, false, CLR_NONE);

      if(_ticket > 0 && OrderSelect(_ticket, SELECT_BY_TICKET)) {
         // set or initialize all order exit methods (SL, PT, Trailing Stop, Exit After Bars, etc.)
         sqSetOrderExpiration(_ticket, BarsValid);

         // StopLoss & ProfitTarget
         sqSetSLandPT(_ticket, sqGetSLLevel("Current", OP_SELLSTOP, OrderOpenPrice(), 1, StopLoss), sqGetPTLevel("Current", OP_SELLSTOP, OrderOpenPrice(), 1, ProfitTarget));

         // TrailingStop initialization
         sqSetGlobalVariable(_ticket, "TrailingStop", sqStringHash("TrailingStopCoef * sqATR(NULL,0,20,1)"));
         sqSetGlobalVariable(_ticket, "TrailingStopType", SLPTTYPE_RANGE);
         sqSetGlobalVariable(_ticket, "TrailingActivation", sqStringHash("TrailingActivation"));
      }



  }

               
   //------------------------
   // Rule: Long exit
   //------------------------
   if (sqIsBarOpen()
      && ((LongExitSignal
      && (!(LongEntrySignal)))
      && sqMarketPositionIsLong(MagicNumber, "Any", "")))
   {
      // Action #1
      sqClosePosition(OrderLots(), // size: SQ.Formulas.CloseSize.FullPosition
                    MagicNumber, // magic number
                    "Any", // symbol
                    1, // direction
                    "" // comment
       );

  }

               
   //------------------------
   // Rule: Short exit
   //------------------------
   if (sqIsBarOpen()
      && ((ShortExitSignal
      && (!(ShortEntrySignal)))
      && sqMarketPositionIsShort(MagicNumber, "Any", "")))
   {
      // Action #1
      sqClosePosition(OrderLots(), // size: SQ.Formulas.CloseSize.FullPosition
                    MagicNumber, // magic number
                    "Any", // symbol
                    -1, // direction
                    "" // comment
       );

  }

               
   return;
}

//+------------------------------------------------------------------+

int OnInit() {
   VerboseLog("--------------------------------------------------------");
   VerboseLog("Starting the EA");

   gPointCoef = calculatePointCoef(Symbol());

   VerboseLog("--------------------------------------------------------");

   if(sqDisplayInfoPanel) {
     sqInitInfoPanel();
   }

   SQTime = new CSQTime();

   if(!IsTesting() && !IsOptimization()) {                                        
      initTimer();
   }
          
   initialBalance = AccountInfoDouble(ACCOUNT_BALANCE);
  
   objExitAtEndOfDay = new CExitAtEndOfDay();
   objExitOnFriday = new CExitOnFriday();
   objLimitTimeRange = new CLimitTimeRange();
   objMaxTradesPerDay = new CMaxTradesPerDay();
   objMinMaxSLPT = new CMinMaxSLPT();
  
  

   double minDistanceMT = NormalizeDouble(MarketInfo(Symbol(), MODE_STOPLEVEL) * MarketInfo(Symbol(), MODE_POINT), Digits);
   double minDistanceSQ = NormalizeDouble(sqMinDistance * sqGetPointCoef(Symbol()), Digits);
  
   if(minDistanceSQ < minDistanceMT){
      VerboseLog("--------------------------------------------------------");
      VerboseLog("Warning! Min distance of this symbol is greater than min distance set in SQ! The backtest results may differ");
      VerboseLog("MT min distance: ", DoubleToStr(minDistanceMT), ", SQ min distance: ", DoubleToStr(minDistanceSQ));
      VerboseLog("--------------------------------------------------------");
   }

   return(0);
}

//+------------------------------------------------------------------+

void OnDeinit(const int reason) {
   sqDeinitInfoPanel();
  
   delete SQTime;
   delete objExitAtEndOfDay;
   delete objExitOnFriday;
   delete objLimitTimeRange;
   delete objMaxTradesPerDay;
   delete objMinMaxSLPT;
  
   return;
}
   
//+------------------------------------------------------------------+

void initTimer(){
   int period = 20 * 3600;                //20 hours
   period += MathRand() % (10 * 3600);    //add another 0-10 hours randomly

   if(!EventSetTimer(period)){
      VerboseLog("Cannot set timer. Error code: ", IntegerToString(GetLastError()));
   }
}

//+------------------------------------------------------------------+

void OnTimer(){
   //clear unused variables
   int deletedCount = 0;
  
   VerboseLog("Clearing variables...");
  
   for(int a=GlobalVariablesTotal() - 1; a>=0; a--){
      string variableName = GlobalVariableName(a);

      if(GlobalVariableCheck(variableName)){
         string variableNameParts[];
         int parts = StringSplit(variableName, '_', variableNameParts);
        
         if(parts != 3 || variableNameParts[0] != getVariablePrefix()) continue;
        
         int ticketNo = StrToInteger(variableNameParts[1]);
        
         bool variableUsed = false;
        
         for(int i=0; i < OrdersTotal(); i++) {
            if(OrderSelect(i, SELECT_BY_POS) == true) {
               if(OrderTicket() == ticketNo){
                  variableUsed = true;
                  break;
               }
            }
         }
        
         ResetLastError();
        
         if(!variableUsed){
            if(GlobalVariableDel(variableName)){
               deletedCount++;
            }
            else {
               VerboseLog("Cannot delete variable. Error code: ", IntegerToString(GetLastError()));
            }
         }
      }
   }
  
   VerboseLog(IntegerToString(deletedCount), " variables cleared");
}

//+------------------------------------------------------------------+

bool sqHandleTradingOptions() {
   bool continueWithBarUpdate = true;

   if(!objExitAtEndOfDay.onBarUpdate()) continueWithBarUpdate = false;
   if(!objExitOnFriday.onBarUpdate()) continueWithBarUpdate = false;
   if(!objLimitTimeRange.onBarUpdate()) continueWithBarUpdate = false;
   if(!objMaxTradesPerDay.onBarUpdate()) continueWithBarUpdate = false;
   if(!objMinMaxSLPT.onBarUpdate()) continueWithBarUpdate = false;

   return(continueWithBarUpdate);
}  

//+------------------------------------------------------------------+

bool checkMagicNumber(int magicNo){
    if(magicNo == MagicNumber){
         return true;
    }
    return false;
}

//+------------------------------------------------------------------+

double sqGetMarketTickSize(string symbol){
   symbol = correctSymbol(symbol);
   
      if(symbol == Symbol()){
         return MainChartTickSizeSQ;
      }
   
  
   return -1;
}

//+------------------------------------------------------------------+

double sqGetGlobalSL(string symbol, int orderType, double price) {
   return(sqGetSLLevel(symbol, orderType, price, 1, 0));
}

//+------------------------------------------------------------------+

double sqGetGlobalPT(string symbol, int orderType, double price) {
   return(sqGetPTLevel(symbol, orderType, price, 1, 0));
}

//+------------------------------------------------------------------+

double sqGetIndicatorByIdentification(string idHash, int shift) {

   return(0);
}


//+------------------------------------------------------------------+

double sqGetValueByIdentification(string idHash) {

   if(idHash == (string) sqStringHash("0")) {
      return (0);
   }

   if(idHash == (string) sqStringHash("0")) {
      return (0);
   }

   if(idHash == (string) sqStringHash("ProfitTarget")) {
      return (sqConvertToRealPips(OrderSymbol(), ProfitTarget));
   }

   if(idHash == (string) sqStringHash("StopLoss")) {
      return (sqConvertToRealPips(OrderSymbol(), StopLoss));
   }

   if(idHash == (string) sqStringHash("TrailingStopCoef * sqATR(NULL,0,20,1)")) {
      return (TrailingStopCoef * sqATR(NULL,0,20,1));
   }

   if(idHash == (string) sqStringHash("TrailingActivation")) {
      return (sqConvertToRealPips(OrderSymbol(), TrailingActivation));
   }

   if(idHash == (string) sqStringHash("0")) {
      return (0);
   }

   if(idHash == (string) sqStringHash("0")) {
      return (0);
   }

   if(idHash == (string) sqStringHash("ProfitTarget")) {
      return (sqConvertToRealPips(OrderSymbol(), ProfitTarget));
   }

   if(idHash == (string) sqStringHash("StopLoss")) {
      return (sqConvertToRealPips(OrderSymbol(), StopLoss));
   }

   if(idHash == (string) sqStringHash("TrailingStopCoef * sqATR(NULL,0,20,1)")) {
      return (TrailingStopCoef * sqATR(NULL,0,20,1));
   }

   if(idHash == (string) sqStringHash("TrailingActivation")) {
      return (sqConvertToRealPips(OrderSymbol(), TrailingActivation));
   }

   return(0);
}

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

void sqManageOrders(int magicNumber) {
   if(_sqIsBarOpen) {
      for(int i=OrdersTotal()-1; i>=0; i--) {
         if (OrderSelect(i,SELECT_BY_POS)==true) {
            if(OrderMagicNumber() != magicNumber) {
               continue;
            } 
              
            int ticket = OrderTicket();

            if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
               // handle Exit Methods only for live orders

               sqManageSL2BE(ticket);
               sqManageTrailingStop(ticket);           
               sqManageExitAfterXBars(ticket);              
            }

            sqManageOrderExpiration(ticket);
         }

         if(OrdersTotal() <= 0) return;
      }
   }
}

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

void sqResetGlobalVariablesForTicket(int ticket) {
   sqSetGlobalVariable(ticket, "sqOrderExpiration", 0);
   sqSetGlobalVariable(ticket, "sqOrderOpenTime", Time[0]);

   sqSetGlobalVariable(ticket, "MoveSL2BE", 0);   
   sqSetGlobalVariable(ticket, "SL2BEAddPips", 0);
   sqSetGlobalVariable(ticket, "TrailingStop", 0);      
   sqSetGlobalVariable(ticket, "TrailingActivation", 0);
   sqSetGlobalVariable(ticket, "ExitAfterBars", 0);
 
}

//+------------------------------------------------------------------+

void sqInitStart() {
   // changed recognition of bar open to support also range/renko charts
   if(_sqLastOpenBarTime == 0) {
      _sqLastOpenBarTime = Time[0];
      _sqIsBarOpen = true;
   }
   else {
      if(_sqLastOpenBarTime != Time[0]) {
        bool processBarOpen = true;

        if(OpenBarDelay > 0) {
           // set bar to open after X minutes from real open
           processBarOpen = false;
 
           long diffInSeconds = TimeCurrent() - Time[0];
           if(diffInSeconds >= OpenBarDelay * 60) {
              processBarOpen = true;
           }
        }
 
        if(processBarOpen) {
           _sqIsBarOpen = true;
           _sqLastOpenBarTime = Time[0];     
        }
      }
      else {
         _sqIsBarOpen = false;
      }
   }

   if(_sqIsBarOpen && Bars<30) {
      Print("NOT ENOUGH DATA: Less Bars than 30");
      return;
   }

   if(!IsTesting() && !IsOptimization()) {
      sqTextFillOpens();
      if(_sqIsBarOpen) {
         sqTextFillTotals();
      }
   }
}

//+------------------------------------------------------------------+

bool sqIsBarOpen() {
   return(_sqIsBarOpen);
}

//+------------------------------------------------------------------+

int sqGetOrderExpiration(int ticket) {
   return (int) sqGetGlobalVariable(ticket, "sqOrderExpiration");
}

//+------------------------------------------------------------------+

void sqSetOrderExpiration(int ticket, int bars) {
   sqSetGlobalVariable(ticket, "sqOrderExpiration", bars);
}

//+------------------------------------------------------------------+

void sqManageOrderExpiration(int ticket) {
   int tempValue = 0;                                                          
   int barsOpen = 0;

   // Stop/Limit Order Expiration
   if(OrderType() != OP_BUY && OrderType() != OP_SELL) {
      // handle only pending orders
      tempValue = sqGetOrderExpiration(ticket);
      if(tempValue > 0) {
         barsOpen = sqGetOpenBarsForOrder(ticket, tempValue+10);
         if(barsOpen >= tempValue) {
            Verbose("Order with ticket: ", IntegerToString(ticket), " expired");
            sqDeletePendingOrder(ticket);
         }
      }
   }
}

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

double sqIndicatorHighest(int period, int nthValue, string indicatorIdentification) {    
   if(period > 1000) {
        Alert("Period used for sqIndicatorHighest function is too high. Max value is 1000");
        period = 1000;
   }
  
   if(nthValue < 0 || nthValue >= period) {
       return(-1);
   }
  
   double indicatorValues[1000];
   int i;

   for(i=0; i<1000; i++) {
      indicatorValues[i] = -2147483647;
   }

   for(i=0; i<period; i++) {
      indicatorValues[i] = sqGetIndicatorByIdentification(indicatorIdentification, i);
   }

   ArraySort(indicatorValues, WHOLE_ARRAY,0,MODE_DESCEND);

   if(nthValue < 0 || nthValue >= period) {
      return(-1);
   }

   return(indicatorValues[nthValue]);
}

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

double sqIndicatorLowest(int period, int nthValue, string indicatorIdentification) {          
   if(period > 1000) {
        Alert("Period used for sqIndicatorLowest function is too high. Max value is 1000");
        period = 1000;
   }
  
   if(nthValue < 0 || nthValue >= period) {
       return(-1);
   }
  
   double indicatorValues[1000];
   int i;

   for(i=0; i<1000; i++) {
      indicatorValues[i] = 2147483647;
   }

   for(i=0; i<period; i++) {
      indicatorValues[i] = sqGetIndicatorByIdentification(indicatorIdentification, i);
   }

   ArraySort(indicatorValues,WHOLE_ARRAY,0,MODE_ASCEND);

   if(nthValue < 0 || nthValue >= period) {
      return(-1);
   }

   return(indicatorValues[nthValue]);
}

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

double sqIndicatorAverage(int period, int maMethod, string indicatorIdentification) {
   double indicatorValues[10000];

   for(int i=0; i<period; i++) {
      indicatorValues[i] = sqGetIndicatorByIdentification(indicatorIdentification, i);
   }

   double maValue = iMAOnArray(indicatorValues, period, period, 0, maMethod, 0);

   return(maValue);
}


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

double sqIndicatorRecent(int barsBack, string indicatorIdentification) {
   return(sqGetIndicatorByIdentification(indicatorIdentification, barsBack));
}

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

bool sqIsRising(string indicatorIdentification, int bars, bool allowSameValues, int shift) {
   bool atLeastOnce = false;

   double previousValue = NormalizeDouble(sqGetIndicatorByIdentification(indicatorIdentification, bars+shift-1), 6);

   for(int i=1; i<bars; i++) {
      double currentValue = NormalizeDouble(sqGetIndicatorByIdentification(indicatorIdentification, bars+shift-1-i), 6);

      if(currentValue < previousValue) {
         // indicator was falling
         return(false);
      }
      if(currentValue == previousValue && allowSameValues == false) {
         // indicator was the same, not allowed
         return(false);
      }
      if(currentValue > previousValue) {
         atLeastOnce = true;
      }

      previousValue = currentValue;
   }

   if(atLeastOnce) {
      return(true);
   }

   // indicator was not rising once
   return(false);
}

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

bool sqIsFalling(string indicatorIdentification, int bars, bool allowSameValues, int shift) {
   bool atLeastOnce = false;

   double previousValue = NormalizeDouble(sqGetIndicatorByIdentification(indicatorIdentification, bars+shift-1), 6);

   for(int i=1; i<bars; i++) {
      double currentValue = NormalizeDouble(sqGetIndicatorByIdentification(indicatorIdentification, bars+shift-1-i), 6);

      if(currentValue > previousValue) {
         // indicator was rising
         return(false);
      }
      if(currentValue == previousValue && allowSameValues == false) {
         // indicator was the same, not allowed
         return(false);
      }
      if(currentValue < previousValue) {
         atLeastOnce = true;
      }

      previousValue = currentValue;
   }

   if(atLeastOnce) {
      return(true);
   }

   // indicator was not falling once
   return(false);
}

//+------------------------------------------------------------------+

string getVariablePrefix(){
   return IsTesting() ? "SQX(Test)" : "SQX";
}

//+------------------------------------------------------------------+

void sqSetGlobalVariable(int ticket, string name, double value) {
   GlobalVariableSet(getVariablePrefix()+"_"+IntegerToString(ticket)+"_"+name, value);
}

//+------------------------------------------------------------------+

double sqGetGlobalVariable(int ticket, string name) {
   return (GlobalVariableGet(getVariablePrefix()+"_"+IntegerToString(ticket)+"_"+name));
}

//+------------------------------------------------------------------+

int sqStringHash(string str){
   int i, h, k;
   for (i=0; i<StringLen(str); i++){
      k = StringGetChar(str, i);
      h = (h << 5) + h + k;
   }
   return(h);
}

//+------------------------------------------------------------------+

void sqClosePosition(double size, int magicNumber, string symbol, int direction, string comment) {
   Verbose("Closing order with Magic Number: ", magicNumber, ", symbol: ", symbol, ", direction: ", direction, ", comment: ", comment);

   if(!sqSelectOrder(magicNumber, symbol, direction, comment, false, false)) {
      Verbose("Order cannot be found");
   } else {
      if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
         sqClosePositionAtMarket(size);
      } else {
         sqDeletePendingOrder(OrderTicket());
      }
   }

   Verbose("Closing order finished ----------------");
}

//+------------------------------------------------------------------+

void sqClosePendingOrder(int magicNumber, string symbol, int direction, string comment) {
   Verbose("Closing pending order with Magic Number: ", magicNumber, ", symbol: ", symbol, ", direction: ", direction, ", comment: ", comment);

   if(!sqSelectOrder(magicNumber, symbol, direction, comment, false, false, true)) {
      Verbose("Order cannot be found");
   } else {
      sqDeletePendingOrder(OrderTicket());
   }

   Verbose("Closing pending order finished ----------------");
}

//+------------------------------------------------------------------+

void sqCloseAllPendingOrders(int magicNumber, string symbol, int direction, string comment) {
   Verbose("Closing pending orders with Magic Number: ", magicNumber, ", symbol: ", symbol, ", direction: ", direction, ", comment: ", comment);

   while(sqSelectOrder(magicNumber, symbol, direction, comment, false, false, true)) {
      sqDeletePendingOrder(OrderTicket());
   }

   Verbose("Closing pending orders finished ----------------");
}

//+------------------------------------------------------------------+

int sqGetOpenBarsForOrder(int ticket, int expBarsPeriod) {
   datetime opTime;

   if (OrderType() == OP_BUY || OrderType() == OP_SELL) {             //live order
       opTime = OrderOpenTime();
   }
   else {                                                         //pending order
       opTime = sqGetGlobalVariable(ticket, "sqOrderOpenTime");
   }

   int numberOfBars = 0;
   int limit = MathMin(expBarsPeriod + 10, Bars);

   for(int i=0; i<limit; i++) {
      if(opTime < Time[i]) {
         numberOfBars++;
      }
   }

   return(numberOfBars);
}

//+------------------------------------------------------------------+

void Verbose(string st1, string st2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="", string s13="", string s14="" ) {
   if(sqVerboseMode == 0) {
      return;
   }
   
   if(sqVerboseMode == 1 && (IsTesting() || IsOptimization())) {
      return;
   }
  
   Print("- SQ LOG ", TimeToStr(TimeCurrent()), " ", st1, st2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14);
}


//+------------------------------------------------------------------+

void VerboseLog(string s1, string s2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
   if(sqVerboseMode != 1) {
      Log(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
   }

   Verbose(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
}

//+------------------------------------------------------------------+

void Log(string s1, string s2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
   Print(TimeToStr(TimeCurrent()), " ", s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
}

//+------------------------------------------------------------------+

void sqLog(string st1, string st2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
   Print(TimeToStr(TimeCurrent()), " ", st1, st2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
}


//+------------------------------------------------------------------+

void sqLogToFile(string fileName, string st1, string st2="", string s3="", string s4="", string s5="", string s6="", string s7="", string s8="", string s9="", string s10="", string s11="", string s12="" ) {
   int handle = FileOpen(fileName, FILE_READ | FILE_WRITE, ";");
   if(handle>0) {
      FileSeek(handle,0,SEEK_END);
      FileWrite(handle, TimeToStr(TimeCurrent()), " ", st1, st2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12);
      FileClose(handle);
   }
}

//+------------------------------------------------------------------+

bool sqSelectOrder(int magicNumber, string symbol, int direction, string comment, bool goFromNewest=true, bool skipPending=true, bool skipFilled=false) {
    int cc = 0;
   
    if(orderSelectTimeout > 0){
       Sleep(orderSelectTimeout);
    }
   
    if(goFromNewest){
       for (cc = OrdersTotal() - 1; cc >= 0; cc--) {
           if(orderFits(cc, magicNumber, symbol, direction, comment, skipPending, skipFilled)){
              return true;
           }
       }
    }
    else {
       for (cc = 0; cc < OrdersTotal(); cc++) {
           if(orderFits(cc, magicNumber, symbol, direction, comment, skipPending, skipFilled)){
              return true;
           }
       }
    }
    return(false);
}

//+------------------------------------------------------------------+

bool orderFits(int index, int magicNumber, string symbol, int direction, string comment, bool skipPending=true, bool skipFilled=false){
    if (OrderSelect(index, SELECT_BY_POS)) {
       // skip pending orders
       if(skipPending && (OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT || OrderType() == OP_SELLSTOP || OrderType() == OP_SELLLIMIT)) {
          return false;
       }
       // skip filled orders
       if(skipFilled && (OrderType() == OP_BUY || OrderType() == OP_SELL)) {
          return false;
       }

       if(direction != 0) {
          if(direction > 0 && (OrderType() != OP_BUY && OrderType() != OP_BUYSTOP && OrderType() != OP_BUYLIMIT)) return false;
          if(direction < 0 && (OrderType() != OP_SELL && OrderType() != OP_SELLSTOP && OrderType() != OP_SELLLIMIT)) return false;
       }

       if(magicNumber != 0) {
          if(!checkMagicNumber(OrderMagicNumber()) || OrderMagicNumber() != magicNumber) return false;
       }

       if(symbol != "Any") {
          if(OrderSymbol() != correctSymbol(symbol)) return false;
       }

     if(comment != "") {
       if(StringFind(OrderComment(), comment) == -1) return false;
     }

     // otherwise we found the order
     return(true);
   }
   else return false;
}

//+------------------------------------------------------------------+

void sqCloseAllPositions(string symbol, int magicNumber, int direction, string comment) {
   int count = 100; // maximum number of positions to close
   int lastTicket = -1;

   while(count > 0) {
      count--;
      if(!sqSelectOrder(magicNumber, symbol, direction, comment, false, false)) {
         // no position found
         break;
      }

      if(lastTicket == OrderTicket()) {
         // trying to close the same position one more time, there must be some error
         break;
      }
      lastTicket = OrderTicket();

      if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
         sqClosePositionAtMarket(OrderLots());
      } else {
         sqDeletePendingOrder(OrderTicket());
      }
   }
}

//+------------------------------------------------------------------+

void sqCloseBestPosition(string symbol, int magicNumber, int direction, string comment) {
   double maxPL = -100000000;
   int ticket = 0;
  
   if(orderSelectTimeout > 0){
       Sleep(orderSelectTimeout);
   }
  
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--) {
      if (OrderSelect(cc, SELECT_BY_POS)) {

         // skip pending orders
         if(OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT || OrderType() == OP_SELLSTOP ||OrderType() == OP_SELLLIMIT) {
            continue;
         }

         if(magicNumber != 0) {
            if(OrderMagicNumber() != magicNumber) continue;
         }
         else if(!checkMagicNumber(OrderMagicNumber())) continue;
        
         if(OrderProfit() > maxPL) {
            // found order with better profit
            maxPL = OrderProfit();
            ticket = OrderTicket();
            Verbose("Better position found, ticket: ", IntegerToString(ticket),", PL: ", DoubleToString(maxPL));
         }
      }
   }

   if(ticket > 0) {
      if(OrderSelect(ticket, SELECT_BY_TICKET)) {
         sqClosePositionAtMarket(OrderLots());
      }
   }
}

//+------------------------------------------------------------------+

void sqCloseWorstPosition(string symbol, int magicNumber, int direction, string comment) {
   double minPL = 100000000;
   int ticket = 0;

   if(orderSelectTimeout > 0){
       Sleep(orderSelectTimeout);
   }
  
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--) {
      if (OrderSelect(cc, SELECT_BY_POS)) {

         // skip pending orders
         if(OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT || OrderType() == OP_SELLSTOP ||OrderType() == OP_SELLLIMIT) {
            continue;
         }

         if(magicNumber != 0) {
            if(OrderMagicNumber() != magicNumber) continue;
         } 
         else if(!checkMagicNumber(OrderMagicNumber())) continue;
        
         if(OrderProfit() < minPL) {
            // found order with worse profit
            minPL = OrderProfit();
            ticket = OrderTicket();
            Verbose("Worse position found, ticket: ", IntegerToString(ticket),", PL: ", DoubleToString(minPL));
         }
      }
   }

   if(ticket > 0) {
      if(OrderSelect(ticket, SELECT_BY_TICKET)) {
         sqClosePositionAtMarket(OrderLots());
      }
   }
}

//+------------------------------------------------------------------+

int sqGetMarketPosition(string symbol, int magicNumber, string comment) {
   if(sqSelectOrder(magicNumber, symbol, 0, comment, false)) {
      if(OrderType() == OP_BUY) {
         return(1);
      } else {
         return(-1);
      }
   }
   return(0);
}                    

//+------------------------------------------------------------------+

bool sqMarketPositionIsShort(int magicNo, string symbol, string comment){
   return sqSelectOrder(magicNo, symbol, -1, comment, false);
}   

//+------------------------------------------------------------------+

bool sqMarketPositionIsNotShort(int magicNo, string symbol, string comment){
   if(sqSelectOrder(magicNo, symbol, -1, comment, false)) {
      return false;    
     }
     
     return true;
}    

//+------------------------------------------------------------------+

bool sqMarketPositionIsLong(int magicNo, string symbol, string comment){
   return sqSelectOrder(magicNo, symbol, 1, comment, false);
}    

//+------------------------------------------------------------------+

bool sqMarketPositionIsNotLong(int magicNo, string symbol, string comment){
   if(sqSelectOrder(magicNo, symbol, 1, comment, false)) {
      return false;    
     }
     
     return true;
}    

//+------------------------------------------------------------------+

bool sqMarketPositionIsFlat(int magicNo, string symbol, string comment){
   return sqGetMarketPosition(symbol, magicNo, comment) == 0;
}

//+------------------------------------------------------------------+

double sqGetOrderOpenPrice(string symbol, int magicNumber, int direction, string comment) {
   if(sqSelectOrder(magicNumber, symbol, direction, comment, false)) {
      return(OrderOpenPrice());
   }
   return(-1);
}

//+------------------------------------------------------------------+

double sqGetOrderStopLoss(string symbol, int magicNumber, int direction, string comment) {
   if(sqSelectOrder(magicNumber, symbol, direction, comment, false)) {
      return(OrderStopLoss());
   }
   return(-1);
}

//+------------------------------------------------------------------+

double sqGetOrderProfitTarget(string symbol, int magicNumber, int direction, string comment) {
   if(sqSelectOrder(magicNumber, symbol, direction, comment, f
Attachments
No attachments
  • Votes 0
  • Project StrategyQuant X
  • Type Bug
  • Status Refused
  • Priority Normal

History

g
#1

Gin

17.09.2020 02:06

Task created

MF
#2

Namir

17.09.2020 07:50

Answer to your question is here :


https://strategyquant.com/doc/strategyquant/the-strategy-tried-to-place-stop-limit-order-at-incorrect-price/

h
#3

hankeys

17.09.2020 13:51
users dont read :)


and why to copy here whole MQL code? i must laugh...

TB
#4

Tomas Brynda

24.09.2020 11:12

Status changed from New to Refused

Thanks Namir.


Gin, next time please attach a file rather than copying the whole content as a text here.


Best regards,

Tomas


Votes: 0

Drop files to upload

or

choose files

Max size: 5MB

Not allowed: exe, msi, application, reg, php, js, htaccess, htpasswd, gitignore

...
Wait please