Sell stop or similar crazy TP and SL

completely crazy nonsensical tp and sl for pending ordersse;;
sell stop is below previous daily low, it makes sense
but take profit and stop loss are near current price, which is way higher that pending order




2020.10.22 01:00:02.621    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: OrderDeleteReliable v36:     Successful deletion of Ticket #387750840
2020.10.22 01:00:02.621    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: delete #387750840 sell stop 0.16 USDCAD at 1.30814 sl: 0.00000 tp: 0.00000 ok
2020.10.22 00:59:59.400    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: OrderDeleteReliable v36:     Attempted deletion of pending order, #387750840
2020.10.22 00:59:59.400    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: - SQ LOG 2020.10.22 01:00 Cannot set SL / PT for this order, deleting it!
2020.10.22 00:59:59.400    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: - SQ LOG 2020.10.22 01:00 Cannot modify PT, it cannot be closer than minimum allowed: 1.31097 > 1.30814
2020.10.22 00:59:59.400    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: - SQ LOG 2020.10.22 01:00 Modifying order with ticket: 387750840, SL: 1.31614000 and PT: 1.31097000
2020.10.22 00:59:59.393    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: Ticket: 387750840 (continue) - CloseTime: 0,ClosePrice: 1.31378,Commission: 0,Swap: 0,Profit: 0,Comment: WF Matrix - usdcad-h1-mc-p3-pr,MagicNumber: 377391
2020.10.22 00:59:59.393    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: Ticket: 387750840 - OpenTime: 1603328400,Type: 5,Size: 0.16,Symbol: USDCAD,OpenPrice: 1.30814,SL: 0,PT: 0
2020.10.22 00:59:59.393    WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 USDCAD,H1: OrderSendReliable v36:     Ticket #387750840: Successful SELL STOP order placed with comment = WF Matrix - usdcad-h1-mc-p3-pr, details follow.




//+------------------------------------------------------------------+
//| WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391 EA
//|
//| Generated by StrategyQuant X Build 129 at 10/18/2020 12:42
//|
//| 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 = "WF Matrix - usdcad-h1-mc-p3-preparedStrategy 3.77.391";

extern int MagicNumber = 377391;
bool LongEntrySignal = false;
bool ShortEntrySignal = false;
bool LongExitSignal = false;
bool ShortExitSignal = false;
extern double PriceEntryMult = 2.2;
extern int BarsValid = 11;
extern int ExitAfterBars = 38;
extern double MoveSL2BECoef = 1.6;
extern int ProfitTarget = 200;
extern int StopLoss = 70;
extern int TrailingStop = 50;
extern int TEMAPeriod = 20;
extern int BBWidthRatioPeriod = 135;
extern int BarsValid2 = 113;
extern int ExitAfterBars2 = 34;
extern double MoveSL2BECoef2 = 2.1;
extern double SL2BEAddPipsCoef = 1;
extern int StopLoss2 = 80;
extern int TrailingStop2 = 100;
extern int SmallestRangePeriod = 14;

//+------------------------------------------------------------------+
// Money Management variables
//+------------------------------------------------------------------+
extern string smm = "----------- Money Management - Risk Fixed % Of Balance -----------";
extern double mmRiskPercent = 2.0;
extern int mmDecimals = 2;
extern double mmLotsIfNoMM = 1.0;
extern double mmMaxLots = 95.0;


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

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

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

extern string sltr = "----------- Limit Time Range -----------";
extern bool LimitTimeRange = true;
extern string SignalTimeRangeFrom = "01:00";
extern string SignalTimeRangeTo = "23: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.0E-4;

//+------------------------------------------------------------------+
// 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 = 35; // retry attempts if the error is bad price
double sleep_time = 5.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 = 20.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 = ((iHigh(NULL,0, 3+1) < iClose(NULL,0, 3+1)) && (iHigh(NULL,0, 3) > iClose(NULL,0, 3)));

ShortEntrySignal = (sqIsRising("iHigh(NULL,0, 1)", 4, false, 1));

LongExitSignal = false;

ShortExitSignal = false;

}



//------------------------
// Rule: Long entry
//------------------------
if (sqIsBarOpen()
&& LongEntrySignal)
{
// Action #1
_ticket = sqOpenOrder(OP_BUYLIMIT, "Current", sqMMRiskFixedBalancePct("Current",OP_BUYSTOP,(sqTEMA(NULL,0, TEMAPeriod, PRICE_LOW, 2) + (PriceEntryMult * sqBBWidthRatio(NULL,0, BBWidthRatioPeriod, 6, PRICE_MEDIAN, 2))),sqGetSLLevel("Current", OP_BUYSTOP, (sqTEMA(NULL,0, TEMAPeriod, PRICE_LOW, 2) + (PriceEntryMult * sqBBWidthRatio(NULL,0, BBWidthRatioPeriod, 6, PRICE_MEDIAN, 2))), 1, StopLoss),mmRiskPercent,mmDecimals,mmLotsIfNoMM,mmMaxLots), (sqTEMA(NULL,0, TEMAPeriod, PRICE_LOW, 2) + (PriceEntryMult * sqBBWidthRatio(NULL,0, BBWidthRatioPeriod, 6, PRICE_MEDIAN, 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_BUYLIMIT, OrderOpenPrice(), 1, StopLoss), sqGetPTLevel("Current", OP_BUYLIMIT, OrderOpenPrice(), 1, ProfitTarget));
// MoveSL2BE initialization
sqSetGlobalVariable(_ticket, "MoveSL2BE", sqStringHash("MoveSL2BECoef * sqATR(NULL,0,15,1)"));
sqSetGlobalVariable(_ticket, "MoveSL2BEType", SLPTTYPE_RANGE);

// TrailingStop initialization
sqSetGlobalVariable(_ticket, "TrailingStop", sqStringHash("TrailingStop"));
sqSetGlobalVariable(_ticket, "TrailingStopType", SLPTTYPE_RANGE);
// ExitAfterBars initialization
sqSetGlobalVariable(_ticket, "ExitAfterBars", ExitAfterBars);
}



}


//------------------------
// Rule: Short entry
//------------------------
if (sqIsBarOpen()
&& (ShortEntrySignal
&& (!(LongEntrySignal))))
{
// Action #1
_ticket = sqOpenOrder(OP_SELLSTOP, "Current", sqMMRiskFixedBalancePct("Current",OP_SELLSTOP,sqDaily(NULL,0, "Low", 1),sqGetSLLevel("Current", OP_SELLSTOP, sqDaily(NULL,0, "Low", 1), 1, StopLoss2),mmRiskPercent,mmDecimals,mmLotsIfNoMM,mmMaxLots), sqDaily(NULL,0, "Low", 1), 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, BarsValid2);

// StopLoss & ProfitTarget
sqSetSLandPT(_ticket, sqGetSLLevel("Current", OP_SELLSTOP, OrderOpenPrice(), 1, StopLoss2), sqGetPTLevel("Current", OP_SELLSTOP, OrderOpenPrice(), 3, (sqWeekly(NULL,0, "Low", 1) + (1.00 * sqSmallestRange("NULL",0, SmallestRangePeriod, 3)))));
// MoveSL2BE initialization
sqSetGlobalVariable(_ticket, "MoveSL2BE", sqStringHash("MoveSL2BECoef2 * sqATR(NULL,0,75,1)"));
sqSetGlobalVariable(_ticket, "MoveSL2BEType", SLPTTYPE_RANGE);
sqSetGlobalVariable(_ticket, "SL2BEAddPips", sqStringHash("SL2BEAddPipsCoef * sqATR(NULL,0,150,1)"));

// TrailingStop initialization
sqSetGlobalVariable(_ticket, "TrailingStop", sqStringHash("TrailingStop2"));
sqSetGlobalVariable(_ticket, "TrailingStopType", SLPTTYPE_RANGE);
// ExitAfterBars initialization
sqSetGlobalVariable(_ticket, "ExitAfterBars", ExitAfterBars2);
}



}


//------------------------
// 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) {
if(idHash == "iHigh(NULL,0, 1)") {
return (iHigh(NULL,0, 1+shift));
}

return(0);
}


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

double sqGetValueByIdentification(string idHash) {

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

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("TrailingStop")) {
return (sqConvertToRealPips(OrderSymbol(), TrailingStop));
}

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

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

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

if(idHash == (string) sqStringHash("(sqWeekly(NULL,0, Low, 1) + (1.00 * sqSmallestRange(NULL,0, SmallestRangePeriod, 3)))")) {
return ((sqWeekly(NULL,0, "Low", 1) + (1.00 * sqSmallestRange("NULL",0, SmallestRangePeriod, 3))));
}

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

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

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

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, false)) {
return(OrderTakeProfit());
}
return(-1);
}

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

double sqGetMarketPositionSize(string symbol, int magicNumber, int direction, string comment) {
double lots = 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(direction != 0) {
if(direction > 0 && OrderType() != OP_BUY) continue;
if(direction < 0 && OrderType() != OP_SELL) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

lots += OrderLots();
}
}

return(lots);
}

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

double sqGetOpenPL(string symbol, int magicNumber, int direction, string comment) {
double pl = 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(direction != 0) {
if(direction > 0 && OrderType() != OP_BUY) continue;
if(direction < 0 && OrderType() != OP_SELL) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

pl += OrderProfit();
}
}

return(pl);
}

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

double sqGetOpenPLInPips(string symbol, int magicNumber, int direction, string comment) {
double pl = 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(direction != 0) {
if(direction > 0 && OrderType() != OP_BUY) continue;
if(direction < 0 && OrderType() != OP_SELL) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

if(OrderType() == OP_BUY) {
pl += sqGetBid(OrderSymbol()) - OrderOpenPrice();
} else {
pl += OrderOpenPrice() - sqGetAsk(OrderSymbol());
}
}
}

return(sqConvertToPips(OrderSymbol(), pl));
}

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

int sqGetClosedPLInPips(string symbol, int magicNumber, int direction, string comment, int shift) {
int index = 0;

for(int i=OrdersHistoryTotal(); i>=0; i--) {
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==true ) {

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

if(direction != 0) {
if(direction > 0 && OrderType() != OP_BUY) continue;
if(direction < 0 && OrderType() != OP_SELL) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

if(index == shift) {
if(OrderType() == OP_BUY) {
return(sqConvertToPips(OrderSymbol(), OrderClosePrice() - OrderOpenPrice()));
} else {
return(sqConvertToPips(OrderSymbol(), OrderOpenPrice() - OrderClosePrice()));
}
}

index++;
}
}

return(0);
}

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

int sqGetClosedPLInMoney(string symbol, int magicNumber, int direction, string comment, int shift) {
int index = 0;

for(int i=OrdersHistoryTotal(); i>=0; i--) {
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==true ) {

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

if(direction != 0) {
if(direction > 0 && OrderType() != OP_BUY) continue;
if(direction < 0 && OrderType() != OP_SELL) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

if(index == shift) {
return(OrderProfit());
}

index++;
}
}

return(0);
}

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

int sqGetMarketPositionCount(string symbol, int magicNumber, int direction, string comment) {
double count = 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(direction != 0) {
if(direction > 0 && OrderType() != OP_BUY) continue;
if(direction < 0 && OrderType() != OP_SELL) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

count++;
}
}

return(count);
}

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

int sqGetBarsSinceOpen(string symbol, int magicNumber, int direction, string comment) {
if(sqSelectOrder(magicNumber, symbol, direction, comment, false, false)) {
datetime opTime = OrderOpenTime();

int numberOfBars = 0;
int limit = MathMin(10000, Bars);

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

return(numberOfBars);
}

return(-1);
}

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

int sqGetBarsSinceClose(string symbol, int magicNumber, int direction, string comment) {
if(sqSelectOrderInHistory(magicNumber, symbol, direction, comment)) {
datetime clTime = OrderCloseTime();

int numberOfBars = 0;
int limit = MathMin(10000, Bars);

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

return(numberOfBars);
}

return(-1);
}


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

int sqGetLastOrderType(string symbol, int magicNumber, string comment) {
if(sqSelectOrderInHistory(magicNumber, symbol, 0, comment)) {
if(OrderType() == OP_BUY || OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT) {
return(1);
} else {
return(-1);
}
}

return(0);
}

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

bool sqSelectOrderInHistory(int magicNumber, string symbol, int direction, string comment) {
for (int cc = OrdersHistoryTotal() - 1; cc >= 0; cc--) {
if (OrderSelect(cc, SELECT_BY_POS,MODE_HISTORY)) {

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

if(direction != 0) {
if(direction > 0 && OrderType() != OP_BUY) continue;
if(direction < 0 && OrderType() != OP_SELL) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

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

return(false);
}

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

bool sqSelectPendingOrderByType(int magicNumber, string symbol, int orderType, string comment) {
if(orderSelectTimeout > 0){
Sleep(orderSelectTimeout);
}

for (int cc = OrdersTotal() - 1; cc >= 0; cc--) {
if (OrderSelect(cc, SELECT_BY_POS)) {
if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
continue;
}

if(orderType != 0) {
if(OrderType() != orderType) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

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

return(false);
}

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

bool sqSelectPendingOrderByDir(int magicNumber, string symbol, int direction, string comment) {
if(orderSelectTimeout > 0){
Sleep(orderSelectTimeout);
}

for (int cc = OrdersTotal() - 1; cc >= 0; cc--) {
if (OrderSelect(cc, SELECT_BY_POS)) {
if(OrderType() == OP_BUY || OrderType() == OP_SELL) {
continue;
}

if(direction != 0) {
int orderDirection = sqGetDirectionFromOrderType(OrderType());
if(orderDirection != direction) continue;
}

if(magicNumber != 0) {
if(OrderMagicNumber() != magicNumber) continue;
}
else if(!checkMagicNumber(OrderMagicNumber())) continue;

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

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

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

return(false);
}
//+------------------------------------------------------------------+

bool sqClosePositionAtMarket(double size) {
int ticket = OrderTicket();

Verbose("Closing order with ticket: ", IntegerToString(ticket));

int orderType = OrderType();

if(orderType != OP_BUY && orderType != OP_SELL) {
Verbose("Trying to close non-live order");
return(false);
}
if(!sqCheckConnected()) {
return(false);
}

bool result;

double price = sqGetClosePrice(orderType, OrderSymbol(), 0);
result = OrderCloseReliable(ticket, size, price, correctSlippage(sqMaxCloseSlippage, OrderSymbol()));
if(result) {
Verbose("Order deleted successfuly");
return(true);
}

return(false);
}

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

double sqGetAsk(string symbol) {
if(symbol == "NULL" || symbol == "Current") {
return(NormalizeDouble(Ask, Digits));
} else {
return(NormalizeDouble(MarketInfo(correctSymbol(symbol),MODE_ASK), Digits));
}
}

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

double sqGetBid(string symbol) {
if(symbol == "NULL" || symbol == "Current") {
return(NormalizeDouble(Bid, Digits));
} else {
return(NormalizeDouble(MarketInfo(correctSymbol(symbol),MODE_BID), Digits));
}
}

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

bool sqDeleteOrder(int ticket){
if(!OrderSelect(ticket, SELECT_BY_TICKET)){
Verbose("Warning! Cannot delete order - order with ticket ", IntegerToString(ticket), " can't be selected");
return false;
}

if(sqIsPendingOrder(OrderType())){
return OrderDeleteReliable(ticket);
}
else {
return OrderCloseReliableMKT(ticket, OrderLots(), sqGetDirectionFromOrderType(OrderType()) == 1 ? Bid : Ask, correctSlippage(0, OrderSymbol()));
}
}

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

bool sqDeletePendingOrder(int ticket) {
Verbose(" Deleting pending order, ticket: " + IntegerToString(ticket));

int orderType = OrderType();

if(orderType == OP_BUY || orderType == OP_SELL) {
Verbose("Trying to delete non-pending order");
return(f

Attachments
  • Votes +1
  • Project StrategyQuant X
  • Type Bug
  • Status Refused
  • Priority Normal

History

b
#1

gin

22.10.2020 00:46

Task created

b
#2

gin

22.10.2020 00:49
Voted for this task.

Votes: +1

Drop files to upload

or

choose files

Max size: 5MB

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

...
Wait please