//+------------------------------------------------------------------------------+//
//)   ____  _  _  ____  ____  ____  ____  __  __    __      ___  _____  __  __   (//
//)  ( ___)( \/ )(  _ \(  _ \( ___)( ___)(  \/  )  /__\    / __)(  _  )(  \/  )  (//
//)   )__)  )  (  )(_) ))   / )__)  )__)  )    (  /(__)\  ( (__  )(_)(  )    (   (//
//)  (__)  (_/\_)(____/(_)\_)(____)(____)(_/\/\_)(__)(__)()\___)(_____)(_/\/\_)  (//
//)   http://fxdreema.com                              Copyright 2014, fxDreema  (//
//+------------------------------------------------------------------------------+//
#property copyright ""
#property link      "https://fxdreema.com"

/************************************************************************************************************************/
// +------------------------------------------------------------------------------------------------------------------+ //
// |                       INPUT PARAMETERS, GLOBAL VARIABLES, CONSTANTS, IMPORTS and INCLUDES                        | //
// |                      System and Custom variables and other definitions used in the project                       | //
// +------------------------------------------------------------------------------------------------------------------+ //
/************************************************************************************************************************/

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// System constants (project settings) //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
#define PROJECT_ID           "mt4-1797"
#define VIRTUAL_STOPS_ENABLED    false // true or false
#define VIRTUAL_STOPS_TIMEOUT 0//--
#define USE_EMERGENCY_STOPS  "no"   // "yes" to use emergency (hard stops) when virtual stops are in use. "always" to use EMERGENCY_STOPS_ADD as emergency stops when there is no virtual stop.
#define EMERGENCY_STOPS_REL  0       // Use 0 to disable hard stops when virtual stops are enabled. Use a value >=0 to automatically set hard stops with virtual. Example: if 2 is used, then hard stops will be 2 times bigger than virtual ones.
#define EMERGENCY_STOPS_ADD  0       // Add pips to relative size of emergency stops (hard stops)
//--
#define ON_TRADE_REALTIME    0 //
#define ON_TIMER_PERIOD   60        // Timer event period (in seconds)
//--
#define ENABLE_EVENT_TICK  1 // "Tick"  event: 1 - enable, 0 - disable
#define ENABLE_EVENT_TRADE 0 // "Trade" event: 1 - enable, 0 - disable
#define ENABLE_EVENT_TIMER 0 // "Timer" event: 1 - enable, 0 - disable
///////

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// System constants (predefined constants) //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
#define TLOBJPROP_TIME1 801
#define OBJPROP_TL_PRICE_BY_SHIFT 802
#define OBJPROP_TL_SHIFT_BY_PRICE 803
#define OBJPROP_FIBOVALUE 804
#define OBJPROP_FIBOPRICEVALUE 805
#define OBJPROP_BARSHIFT1 807
#define OBJPROP_BARSHIFT2 808
#define OBJPROP_BARSHIFT3 809
#define SEL_CURRENT 0
#define SEL_INITIAL 1

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// Project global variables, includes, imports //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
// Imported functions
#import "kernel32.dll"
bool SleepEx(int ms, bool bAlertable);
#import

extern string inp15="(15) Time filter 1<br>";
extern string inp15_ServerOrLocalTime="server"; // 
extern string inp15_TimeStart="23:59"; // 
extern string inp15_TimeEnd="23:58"; // 

extern string inp36="(36) trade(100) or alert(200)<br>";
extern string inp36_BlockID="100"; // 

extern string inp40="(40) Look for entry once per bar \"timeframe\"<br>";
extern int inp40_TIMEFRAME=0; // 

extern string inp55="(55) After \"n\" bars";
extern int inp55_Xbars=5; // 

extern string inp65="(65) Close profitable trades after \"n\" bars? 700 for yes<br>";
extern string inp65_BlockID="700"; // 

extern string inp799="(799) Buy now";
extern double inp799_VolumeSize=0.01; // 
extern double inp799_StopLossPips=20; // 
extern double inp799_TakeProfitPips=5; // 

extern string inp800="(800) Sell now";
extern double inp800_VolumeSize=0.01; // 
extern double inp800_StopLossPips=20; // 
extern double inp800_TakeProfitPips=5; // 
extern int MagicStart=1797; // Magic Start (MagicNumber=MagicStart+Group#)

//VVVVVVVVVVVVVVVVVVVVVVVVV//
// System global variables //
//^^^^^^^^^^^^^^^^^^^^^^^^^//
int FXD_CURRENT_FUNCTION_ID=0;
double FXD_MILS_INIT_END=0;
bool FXD_FIRST_TICK_PASSED=false;
bool FXD_BREAK=false;
bool FXD_CONTINUE=false;
bool FXD_CHART_IS_OFFLINE = false;
bool FXD_ONTIMER_TAKEN = false;
bool FXD_ONTIMER_TAKEN_IN_MILLISECONDS = false;
double FXD_ONTIMER_TAKEN_TIME = 0;
bool USE_VIRTUAL_STOPS = VIRTUAL_STOPS_ENABLED;

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// Global variables used as On-Off property for fxDreema blocks //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
bool block1=true; // Condition
bool block2=true; // Condition
bool block3=true; // Condition
bool block4=true; // Condition
bool block5=true; // Pass
bool block6=true; // AND
bool block15=true; // Time filter 1
bool block25=false; // Time filter 2
bool block35=false; // Time filter 3
bool block36=true; // trade(100) or alert(200)
bool block40=true; // Look for entry once per bar "timeframe"
bool block55=true; // After "n" bars
bool block65=true; // Close profitable trades after "n" bars? 700 for yes
bool block94=true; // AND
bool block100=false; // trade
bool block102=true; // Close profitable trades&nbsp;
bool block105=true; // If trade/order exists
bool block107=true; // Alert message
bool block108=true; // Alert message
bool block111=true; // Send Email
bool block112=true; // Send Email&nbsp;
bool block127=true; // Condition
bool block128=true; // Condition
bool block129=true; // Condition
bool block130=true; // Condition
bool block131=true; // AND
bool block132=true; // AND
bool block200=false; // alert
bool block244=true; // Condition
bool block245=true; // Condition
bool block699=true; // No trade/order exists
bool block700=false; // yes
bool block701=true; // No trade/order exists
bool block709=false; // Draw Arrow
bool block712=true; // Once per bar
bool block713=true; // Once per bar
bool block714=false; // Draw Arrow
bool block715=false; // Draw Arrow
bool block720=false; // Draw Arrow
bool block795=true; // Close profitable trades
bool block796=true; // Close profitable trades
bool block797=true; // Delay
bool block798=true; // Look for exit once per bar
bool block799=true; // Buy now
bool block800=true; // Sell now

/************************************************************************************************************************/
// +------------------------------------------------------------------------------------------------------------------+ //
// |                                                 EVENT FUNCTIONS                                                  | //
// |                           These are the main functions that controls the whole project                           | //
// +------------------------------------------------------------------------------------------------------------------+ //
/************************************************************************************************************************/

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// This function is executed once when the program starts //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
int OnInit()
{
	Comment("");

	if (!MQLInfoInteger(MQL_DLLS_ALLOWED))
	{
		Alert("This program requires DLL imports to be allowed.");
	}
	if (IsOptimization()) {
		// According to http://docs.mql4.com/runtime/testing: During optimization, working with graphical objects is not supported.
		USE_VIRTUAL_STOPS = false;
	}
	TimeAtStart("set"); // Set local and server time at start
	AccountBalanceAtStart(); // Set balance at start
	DrawSpreadInfo();
	DrawStatus("waiting for tick...");

	if (MQLInfoInteger(MQL_PROGRAM_TYPE) == PROGRAM_EXPERT)
	{
		FXD_CHART_IS_OFFLINE = ChartGetInteger(0, CHART_IS_OFFLINE);
	}

	if (MQLInfoInteger(MQL_PROGRAM_TYPE) != PROGRAM_SCRIPT)
	{
		if (FXD_CHART_IS_OFFLINE == true || (ENABLE_EVENT_TRADE == 1 && ON_TRADE_REALTIME == 1))
		{
			FXD_ONTIMER_TAKEN = true;
			EventSetMillisecondTimer(1);
		}
		if (ENABLE_EVENT_TIMER) {
			OnTimerSet(ON_TIMER_PERIOD);
		}
	}

	FXD_MILS_INIT_END = GetTickCount();
	FXD_FIRST_TICK_PASSED = false; // reset is needed when changing inputs

	return(INIT_SUCCEEDED);
}

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// This function is executed on every incoming tick //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
// This is the native MQL4 on-tick function
void OnTick()
{
	if (FXD_FIRST_TICK_PASSED==false)
	{
		FXD_FIRST_TICK_PASSED=true;
		DrawStatus("working");
	}

	//-- special system actions
	DrawSpreadInfo();
	TicksData(""); // Collect ticks (if needed)
	if (USE_VIRTUAL_STOPS) {VirtualStopsDriver();}
	ExpirationDriver();
	if (ENABLE_EVENT_TRADE) {OnTradeListener();}

	// Main beginning on the graph
	block5();



	TicksFromStart(true);
	return;
}

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// This function is executed on trade events - open, close, modify //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
void EventTrade()
{

	OnTradeQueue(-1);
}

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// This function is executed on a period basis //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
void OnTimer()
{
	//-- to simulate ticks in offline charts, Timer is used instead of infinite loop
	//-- the next function checks for changes in price and calls OnTick() manually
	if (FXD_CHART_IS_OFFLINE && RefreshRates()) {
		OnTick();
	}
	if (ON_TRADE_REALTIME == 1) {
		OnTradeListener();
	}

	static int t0 = 0;
	int t = 0;
	bool ok = false;

	if (FXD_ONTIMER_TAKEN)
	{
		if (FXD_ONTIMER_TAKEN_TIME > 0)
		{
			if (FXD_ONTIMER_TAKEN_IN_MILLISECONDS == true)
			{
				t = GetTickCount();
			}
			else
			{
				t = TimeLocal();
			}
			if ((t - t0) >= FXD_ONTIMER_TAKEN_TIME)
			{
				t0 = t;
				ok = true;
			}
		}

		if (ok == false) {
			return;
		}
	}


}

//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//
// This function is executed once when the program ends //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
void OnDeinit(const int reason)
{
	//-- if Timer was set, kill it here
	EventKillTimer();

	if (MQLInfoInteger(MQL_TESTER)) {
		Print("Backtested in "+DoubleToStr((GetTickCount()-FXD_MILS_INIT_END)/1000, 2)+" seconds");
		Print("Average ticks per second: "+DoubleToStr(TicksFromStart()/(GetTickCount()-FXD_MILS_INIT_END),0));
	}

	DrawStatus("stopped");
	if (MQLInfoInteger(MQL_PROGRAM_TYPE) == PROGRAM_EXPERT)
	{
		switch(UninitializeReason())
		{
			case REASON_PROGRAM		: Print("Expert Advisor self terminated"); break;
			case REASON_REMOVE		: Print("Expert Advisor removed from the chart"); break;
			case REASON_RECOMPILE	: Print("Expert Advisorhas been recompiled"); break;
			case REASON_CHARTCHANGE	: Print("Symbol or chart period has been changed"); break;
    		case REASON_CHARTCLOSE	: Print("Chart has been closed"); break;
    		case REASON_PARAMETERS	: Print("Input parameters have been changed by a user"); break;
    		case REASON_ACCOUNT		: Print("Another account has been activated or reconnection to the trade server has occurred due to changes in the account settings"); break;
			case REASON_TEMPLATE	: Print("A new template has been applied"); break;
			case REASON_INITFAILED	: Print("OnInit() handler has returned a nonzero value"); break;
			case REASON_CLOSE		: Print("Terminal has been closed"); break;
		}
	}
}

/************************************************************************************************************************/
// +------------------------------------------------------------------------------------------------------------------+ //
// |                                   FUNCTIONS THAT REPRESENTS BLOCKS IN FXDREEMA                                   | //
// |                                    Each block is represented as function here                                    | //
// +------------------------------------------------------------------------------------------------------------------+ //
/************************************************************************************************************************/

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #1 (Condition) //
void block1(int _parent_=0)
{
	if (block1==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=1;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iClose", 2, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iOpen", 2, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo<Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro<Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block94(1);} else if (o2==true) {block6(1);}
}
double _candles(string iOHLC, int CandleID, string SYMBOL, int TIMEFRAME) {
	double retval=0;
	double cOpen=0;
	double cHigh=0;
	double cLow=0;
	double cClose=0;
	CandleID=CandleID+IndicatorMoreShift();
	
	if (iOHLC=="iOpen")        {retval=iOpen(SYMBOL, TIMEFRAME, CandleID);}
	else if (iOHLC=="iHigh")   {retval=iHigh(SYMBOL, TIMEFRAME, CandleID);}
	else if (iOHLC=="iLow")    {retval=iLow(SYMBOL, TIMEFRAME, CandleID);}
	else if (iOHLC=="iClose")  {retval=iClose(SYMBOL, TIMEFRAME, CandleID);}
	else if (iOHLC=="iVolume") {retval=iVolume(SYMBOL, TIMEFRAME, CandleID);}
	else if (iOHLC=="iTime")   {retval=iTime(SYMBOL, TIMEFRAME, CandleID);}
	else if (iOHLC=="iMedian") {
	   cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		retval=((cLow+cHigh)/2);
	}
	else if (iOHLC=="iTypical") {
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=((cLow+cHigh+cClose)/3);
	}
	else if (iOHLC=="iAverage") {
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=((cLow+cHigh+cClose+cClose)/4);
	}
	else if (iOHLC=="iTotal") {
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips(MathAbs(cHigh-cLow),SYMBOL);
	}
	else if (iOHLC=="iBody") {
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips(MathAbs(cClose-cOpen),SYMBOL);
	}
	else if (iOHLC=="iUpperWick") {
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		retval=0;
		if (cClose>cOpen) {
		   retval=toPips(MathAbs(cHigh-cClose),SYMBOL);
		} else {
		   retval=toPips(MathAbs(cHigh-cOpen),SYMBOL);
		}
	}
	else if (iOHLC=="iBottomWick") {
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		retval=0;
		if (cClose>cOpen) {
		   retval=toPips(MathAbs(cOpen-cLow),SYMBOL);
		} else {
		   retval=toPips(MathAbs(cClose-cLow),SYMBOL);
		}
	}
	else if (iOHLC=="iBullTotal") {
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cHigh-cLow),SYMBOL);
		if (cClose<cOpen) {SkipThePass(true); return(0);}
	}
	else if (iOHLC=="iBullBody") {
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cClose-cOpen),SYMBOL);
		if (cClose<cOpen) {SkipThePass(true); return(0);}
	}
	else if (iOHLC=="iBullUpperWick") {
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cHigh-cClose),SYMBOL);
		if (cClose<cOpen) {SkipThePass(true); return(0);}
	}
	else if (iOHLC=="iBullBottomWick") {
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cOpen-cLow),SYMBOL);
		if (cClose<cOpen) {SkipThePass(true); return(0);}
	}
	else if (iOHLC=="iBearTotal") {
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cHigh-cLow),SYMBOL);
		if (cOpen<cClose) {SkipThePass(true); return(0);}
	}
	else if (iOHLC=="iBearBody") {
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cOpen-cClose),SYMBOL);
		if (cOpen<cClose) {SkipThePass(true); return(0);}
	}
	else if (iOHLC=="iBearUpperWick") {
		cHigh=iHigh(SYMBOL,TIMEFRAME,CandleID);
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cHigh-cOpen),SYMBOL);
		if (cOpen<cClose) {SkipThePass(true); return(0);}
	}
	else if (iOHLC=="iBearBottomWick") {
		cLow=iLow(SYMBOL,TIMEFRAME,CandleID);
		cOpen=iOpen(SYMBOL,TIMEFRAME,CandleID);
		cClose=iClose(SYMBOL,TIMEFRAME,CandleID);
		retval=toPips((cClose-cLow),SYMBOL);
		if (cOpen<cClose) {SkipThePass(true); return(0);}
	}
	return(retval);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #2 (Condition) //
void block2(int _parent_=0)
{
	if (block2==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=2;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iLow", 1, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iLow", 2, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo<Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro<Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block94(2);} else if (o2==true) {block6(2);}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #3 (Condition) //
void block3(int _parent_=0)
{
	if (block3==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=3;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iHigh", 1, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iHigh", 2, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo>Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro>Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block94(3);} else if (o2==true) {block6(3);}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #4 (Condition) //
void block4(int _parent_=0)
{
	if (block4==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=4;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iOpen", 1, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo>Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro>Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block94(4);} else if (o2==true) {block6(4);}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #5 (Pass) //
void block5(int _parent_=0)
{
	if (block5==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=5;

	block15(5); block25(5); block35(5); block798(5);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #6 (AND) //
void block6(int _parent_=0)
{
	if (block6==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=6;

	static bool passed=false;
	static string list[];
	static string check[];
	static int old_tick=-1;
	bool go_to_next=false;
	static int list_size;
	
	if (!passed) {passed=true;
	   StringExplode(",",fxD_BlocksLookupTable(3,"6"),list);
	   list_size=ArraySize(list);
	}
	if (list_size==0) {
	   // This block is at the very top => pass everytime
	   go_to_next=true;
	}
	else {
	   // This block is child
	   int ticks=TicksFromStart();
	   if (old_tick!=ticks) {old_tick=ticks;
	      ArrayResize(check,0); // reset
	   }
	   if (ArraySearch(list,_parent_)>-1 && ArraySearch(check,_parent_)==-1) {
	      ArrayValue(check,_parent_); // add current parent
	      if (list_size==ArraySize(check)) {go_to_next=true;}
	   }
	   
	}
	if (go_to_next==true) {block796(6);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #15 (Time filter 1<br>) //
void block15(int _parent_=0)
{
	if (block15==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=15;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string ServerOrLocalTime=inp15_ServerOrLocalTime; // Server or local time
	string TimeStartMode="text"; // Start time mode
	string TimeStart=inp15_TimeStart; // Start time
	int TimeStartYear=0; // Start time: Year
	int TimeStartMonth=0; // Start time: Month
	int TimeStartDay=0; // Start time: Day
	int TimeStartHour=1; // Start time: Hour
	int TimeStartMinute=0; // Start time: Minute
	int TimeStartSecond=0; // Time start: Second
	string TimeEndMode="text"; // End time mode
	string TimeEnd=inp15_TimeEnd; // End time
	int TimeEndYear=0; // End time: Year
	int TimeEndMonth=0; // End time: Month
	int TimeEndDay=0; // End time: Day
	int TimeEndHour=1; // End time: Hour
	int TimeEndMinute=1; // End time: Minute
	int TimeEndSecond=0; // End time: Second
	int TimeEndRelYears=0; // Relative: Years
	int TimeEndRelMonths=0; // Relative: Months
	int TimeEndRelDays=0; // Relative: Days
	int TimeEndRelHours=0; // Relative: Hours
	int TimeEndRelMinutes=1; // Relative: Minutes
	int TimeEndRelSeconds=0; // Relative: Seconds
	
	///////////////
	// Main code //
	///////////////
	
	datetime t0=0;
	datetime t1=0;
	datetime tx=0;
	datetime now=0;
	
	if (ServerOrLocalTime=="server") {now=TimeCurrent();} else
	if (ServerOrLocalTime=="local")  {now=TimeLocal();}
	
	if (TimeStartMode=="text") {t0=TimeFromString(TimeStart, now);} else
	if (TimeStartMode=="component") {
	   if (TimeStartYear==0)   {TimeStartYear=TimeYear(now);}
	   if (TimeStartMonth==0)  {TimeStartMonth=TimeMonth(now);}
	   if (TimeStartDay==0)    {TimeStartDay=TimeDay(now);}
	   t0=StrToTime(TimeStartYear+"."+TimeStartMonth+"."+TimeStartDay+" "+TimeStartHour+":"+TimeStartMinute+":"+TimeStartSecond);
	}
	if (TimeEndMode=="text") {t1=TimeFromString(TimeEnd, now);} else
	if (TimeEndMode=="component") {
	   if (TimeEndYear==0)     {TimeEndYear=TimeYear(now);}
	   if (TimeEndMonth==0)    {TimeEndMonth=TimeMonth(now);}
	   if (TimeEndDay==0)      {TimeEndDay=TimeDay(now);}
	   t1=StrToTime(TimeEndYear+"."+TimeEndMonth+"."+TimeEndDay+" "+TimeEndHour+":"+TimeEndMinute+":"+TimeEndSecond);
	   
	} else
	if (TimeEndMode=="relative") {
	   t1=StrToTime((TimeYear(t0)+TimeEndRelYears)+"."+(TimeMonth(t0)+TimeEndRelMonths)+".01 00:00");
	   t1=t1+((TimeDay(t0)+TimeEndRelDays-1)*86400)+((TimeHour(t0)+TimeEndRelHours)*3600)+((TimeMinute(t0)+TimeEndRelMinutes)*60)+(TimeSeconds(t0)+TimeEndRelSeconds);
	   if (t0>t1) {t1=t1-86400;}
	}
	
	if ((now>=t0 && now<t1) || (t0>t1 && (now>=t0 || now<t1))) {block40(15);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #25 (Time filter 2) //
void block25(int _parent_=0)
{
	if (block25==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=25;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string ServerOrLocalTime="server"; // Server or local time
	string TimeStartMode="text"; // Start time mode
	string TimeStart="00:00"; // Start time
	int TimeStartYear=0; // Start time: Year
	int TimeStartMonth=0; // Start time: Month
	int TimeStartDay=0; // Start time: Day
	int TimeStartHour=1; // Start time: Hour
	int TimeStartMinute=0; // Start time: Minute
	int TimeStartSecond=0; // Time start: Second
	string TimeEndMode="text"; // End time mode
	string TimeEnd="00:01"; // End time
	int TimeEndYear=0; // End time: Year
	int TimeEndMonth=0; // End time: Month
	int TimeEndDay=0; // End time: Day
	int TimeEndHour=1; // End time: Hour
	int TimeEndMinute=1; // End time: Minute
	int TimeEndSecond=0; // End time: Second
	int TimeEndRelYears=0; // Relative: Years
	int TimeEndRelMonths=0; // Relative: Months
	int TimeEndRelDays=0; // Relative: Days
	int TimeEndRelHours=0; // Relative: Hours
	int TimeEndRelMinutes=1; // Relative: Minutes
	int TimeEndRelSeconds=0; // Relative: Seconds
	
	///////////////
	// Main code //
	///////////////
	
	datetime t0=0;
	datetime t1=0;
	datetime tx=0;
	datetime now=0;
	
	if (ServerOrLocalTime=="server") {now=TimeCurrent();} else
	if (ServerOrLocalTime=="local")  {now=TimeLocal();}
	
	if (TimeStartMode=="text") {t0=TimeFromString(TimeStart, now);} else
	if (TimeStartMode=="component") {
	   if (TimeStartYear==0)   {TimeStartYear=TimeYear(now);}
	   if (TimeStartMonth==0)  {TimeStartMonth=TimeMonth(now);}
	   if (TimeStartDay==0)    {TimeStartDay=TimeDay(now);}
	   t0=StrToTime(TimeStartYear+"."+TimeStartMonth+"."+TimeStartDay+" "+TimeStartHour+":"+TimeStartMinute+":"+TimeStartSecond);
	}
	if (TimeEndMode=="text") {t1=TimeFromString(TimeEnd, now);} else
	if (TimeEndMode=="component") {
	   if (TimeEndYear==0)     {TimeEndYear=TimeYear(now);}
	   if (TimeEndMonth==0)    {TimeEndMonth=TimeMonth(now);}
	   if (TimeEndDay==0)      {TimeEndDay=TimeDay(now);}
	   t1=StrToTime(TimeEndYear+"."+TimeEndMonth+"."+TimeEndDay+" "+TimeEndHour+":"+TimeEndMinute+":"+TimeEndSecond);
	   
	} else
	if (TimeEndMode=="relative") {
	   t1=StrToTime((TimeYear(t0)+TimeEndRelYears)+"."+(TimeMonth(t0)+TimeEndRelMonths)+".01 00:00");
	   t1=t1+((TimeDay(t0)+TimeEndRelDays-1)*86400)+((TimeHour(t0)+TimeEndRelHours)*3600)+((TimeMinute(t0)+TimeEndRelMinutes)*60)+(TimeSeconds(t0)+TimeEndRelSeconds);
	   if (t0>t1) {t1=t1-86400;}
	}
	
	if ((now>=t0 && now<t1) || (t0>t1 && (now>=t0 || now<t1))) {block40(25);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #35 (Time filter 3<br>) //
void block35(int _parent_=0)
{
	if (block35==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=35;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string ServerOrLocalTime="server"; // Server or local time
	string TimeStartMode="text"; // Start time mode
	string TimeStart="00:00"; // Start time
	int TimeStartYear=0; // Start time: Year
	int TimeStartMonth=0; // Start time: Month
	int TimeStartDay=0; // Start time: Day
	int TimeStartHour=1; // Start time: Hour
	int TimeStartMinute=0; // Start time: Minute
	int TimeStartSecond=0; // Time start: Second
	string TimeEndMode="text"; // End time mode
	string TimeEnd="00:01"; // End time
	int TimeEndYear=0; // End time: Year
	int TimeEndMonth=0; // End time: Month
	int TimeEndDay=0; // End time: Day
	int TimeEndHour=1; // End time: Hour
	int TimeEndMinute=1; // End time: Minute
	int TimeEndSecond=0; // End time: Second
	int TimeEndRelYears=0; // Relative: Years
	int TimeEndRelMonths=0; // Relative: Months
	int TimeEndRelDays=0; // Relative: Days
	int TimeEndRelHours=0; // Relative: Hours
	int TimeEndRelMinutes=1; // Relative: Minutes
	int TimeEndRelSeconds=0; // Relative: Seconds
	
	///////////////
	// Main code //
	///////////////
	
	datetime t0=0;
	datetime t1=0;
	datetime tx=0;
	datetime now=0;
	
	if (ServerOrLocalTime=="server") {now=TimeCurrent();} else
	if (ServerOrLocalTime=="local")  {now=TimeLocal();}
	
	if (TimeStartMode=="text") {t0=TimeFromString(TimeStart, now);} else
	if (TimeStartMode=="component") {
	   if (TimeStartYear==0)   {TimeStartYear=TimeYear(now);}
	   if (TimeStartMonth==0)  {TimeStartMonth=TimeMonth(now);}
	   if (TimeStartDay==0)    {TimeStartDay=TimeDay(now);}
	   t0=StrToTime(TimeStartYear+"."+TimeStartMonth+"."+TimeStartDay+" "+TimeStartHour+":"+TimeStartMinute+":"+TimeStartSecond);
	}
	if (TimeEndMode=="text") {t1=TimeFromString(TimeEnd, now);} else
	if (TimeEndMode=="component") {
	   if (TimeEndYear==0)     {TimeEndYear=TimeYear(now);}
	   if (TimeEndMonth==0)    {TimeEndMonth=TimeMonth(now);}
	   if (TimeEndDay==0)      {TimeEndDay=TimeDay(now);}
	   t1=StrToTime(TimeEndYear+"."+TimeEndMonth+"."+TimeEndDay+" "+TimeEndHour+":"+TimeEndMinute+":"+TimeEndSecond);
	   
	} else
	if (TimeEndMode=="relative") {
	   t1=StrToTime((TimeYear(t0)+TimeEndRelYears)+"."+(TimeMonth(t0)+TimeEndRelMonths)+".01 00:00");
	   t1=t1+((TimeDay(t0)+TimeEndRelDays-1)*86400)+((TimeHour(t0)+TimeEndRelHours)*3600)+((TimeMinute(t0)+TimeEndRelMinutes)*60)+(TimeSeconds(t0)+TimeEndRelSeconds);
	   if (t0>t1) {t1=t1-86400;}
	}
	
	if ((now>=t0 && now<t1) || (t0>t1 && (now>=t0 || now<t1))) {block40(35);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #36 (trade(100) or alert(200)<br>) //
void block36(int _parent_=0)
{
	if (block36==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=36;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string BlockID=inp36_BlockID; // Block IDs to turn ON
	
	///////////////
	// Main code //
	///////////////
	
	static string blocks_raw="";
	static string blocks[];
	static bool turns[];
	static int count=0;
	int i=0;
	
	//-- initially decode the data and put it to the memory, and also in case the data is modified ------------
	if (blocks_raw!=BlockID) {
	   blocks_raw=BlockID;
	   StringExplode(",",BlockID,blocks);
	   count=ArraySize(blocks);
	   ArrayResize(turns,count);
	   ArrayInitialize(turns,false);
	   for (i=0; i<count; i++) {
	      blocks[i]=StringTrimLeft(blocks[i]);
	      blocks[i]=StringTrimRight(blocks[i]);
	   }
	}
	
	//-- actually turn ON all the blocks in the list ----------------------------------------------------------
	for (i=0; i<count; i++) {
	   if (turns[i]==false) {
	      Print("fxDreema: Block \""+blocks[i]+"\" goes ON");
	      turns[i]=true;
	   }
	   fxD_BlocksLookupTable(1,blocks[i],true);
	}
	block100(36); block200(36);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #40 (Look for entry once per bar "timeframe"<br>) //
void block40(int _parent_=0)
{
	if (block40==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=40;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	int TIMEFRAME=inp40_TIMEFRAME; // Timeframe
	
	///////////////
	// Main code //
	///////////////
	
	static datetime time0;
	datetime time=iTime(SYMBOL,TIMEFRAME,0);
	if (time0<time) {time0=time; block36(40);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #55 (After "n" bars) //
void block55(int _parent_=0)
{
	if (block55==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=55;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	int TIMEFRAME=CurrentTimeframe(); // Timeframe
	int Xbars=inp55_Xbars; // "n" bars count
	
	///////////////
	// Main code //
	///////////////
	
	static int BarTime;
	static int BarCount=0;
	bool pass=false;
	if (BarTime<iTime(SYMBOL,TIMEFRAME,0)) {
	   BarCount++;
	   if (BarCount==Xbars || BarTime==0) {BarCount=0;
	      pass=true;
	   }
	   BarTime=iTime(SYMBOL,TIMEFRAME,0);
	}
	if (pass==true) {block65(55);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #65 (Close profitable trades after "n" bars? 700 for yes<br>) //
void block65(int _parent_=0)
{
	if (block65==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=65;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string BlockID=inp65_BlockID; // Block IDs to turn ON
	
	///////////////
	// Main code //
	///////////////
	
	static string blocks_raw="";
	static string blocks[];
	static bool turns[];
	static int count=0;
	int i=0;
	
	//-- initially decode the data and put it to the memory, and also in case the data is modified ------------
	if (blocks_raw!=BlockID) {
	   blocks_raw=BlockID;
	   StringExplode(",",BlockID,blocks);
	   count=ArraySize(blocks);
	   ArrayResize(turns,count);
	   ArrayInitialize(turns,false);
	   for (i=0; i<count; i++) {
	      blocks[i]=StringTrimLeft(blocks[i]);
	      blocks[i]=StringTrimRight(blocks[i]);
	   }
	}
	
	//-- actually turn ON all the blocks in the list ----------------------------------------------------------
	for (i=0; i<count; i++) {
	   if (turns[i]==false) {
	      Print("fxDreema: Block \""+blocks[i]+"\" goes ON");
	      turns[i]=true;
	   }
	   fxD_BlocksLookupTable(1,blocks[i],true);
	}
	block700(65);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #94 (AND) //
void block94(int _parent_=0)
{
	if (block94==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=94;

	static bool passed=false;
	static string list[];
	static string check[];
	static int old_tick=-1;
	bool go_to_next=false;
	static int list_size;
	
	if (!passed) {passed=true;
	   StringExplode(",",fxD_BlocksLookupTable(3,"94"),list);
	   list_size=ArraySize(list);
	}
	if (list_size==0) {
	   // This block is at the very top => pass everytime
	   go_to_next=true;
	}
	else {
	   // This block is child
	   int ticks=TicksFromStart();
	   if (old_tick!=ticks) {old_tick=ticks;
	      ArrayResize(check,0); // reset
	   }
	   if (ArraySearch(list,_parent_)>-1 && ArraySearch(check,_parent_)==-1) {
	      ArrayValue(check,_parent_); // add current parent
	      if (list_size==ArraySize(check)) {go_to_next=true;}
	   }
	   
	}
	if (go_to_next==true) {block795(94);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #100 (trade) //
void block100(int _parent_=0)
{
	if (block100==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=100;

	block1(100); block2(100); block3(100); block4(100);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #102 (Close profitable trades&nbsp;) //
void block102(int _parent_=0)
{
	if (block102==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=102;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersScope="group"; // Group mode
	string OrdersGroup=""; // Group # (empty=Default)
	string SymbolScope="symbol"; // Market mode
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string BuysOrSells="both"; // Filter by type
	int OrderMinutes=0; // Only older than
	string MeasureMode="pips"; // Measure mode
	double PipsAmount=0; // Profit is more than
	double MoneyAmount=0; // Profit is more than
	double Slippage=4; // Slippage
	color ArrowColor=DeepPink; // Arrow color
	
	///////////////
	// Main code //
	///////////////
	
	int closed_count=0;
	bool finished=false;
	while (finished==false) {
	   int count=0;
	   for (int pos=OrdersTotal()-1; pos>=0; pos--) {
	      if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)) {
	         if (FilterOrderBy(OrdersScope,OrdersGroup, SymbolScope,SYMBOL, BuysOrSells)) {
	            if (TimeCurrent()-attrOpenTime()>=60*OrderMinutes) {
	               SetSymbol(SYMBOL);
	               if (
	                  (MeasureMode=="money" && (attrProfit()+attrCommission()+attrSwap())>MoneyAmount)
	                  ||
	                  (MeasureMode=="pips" && ((attrType()==OP_BUY && SymbolBid()-attrOpenPrice()>toDigits(PipsAmount)) || (attrType()==OP_SELL && attrOpenPrice()-SymbolAsk()>toDigits(PipsAmount))))
	                  )
	               {
	                  if (CloseTrade(attrTicket(),Slippage,ArrowColor)) {closed_count++;}
	                  count++;
	   }  }  }  }  }
	   if (count==0) {finished=true;}
	}
	
	/* Orange output */
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #105 (If trade/order exists) //
void block105(int _parent_=0)
{
	if (block105==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=105;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersScope="group"; // Group mode
	string OrdersGroup=""; // Group # (empty=Default)
	string SymbolScope="symbol"; // Market mode
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string BuysOrSells="both"; // Filter by type
	
	///////////////
	// Main code //
	///////////////
	
	bool exist=false;
	for (int pos=OrdersTotal()-1; pos>=0; pos--) {
	   if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)) {
	      if (FilterOrderBy(OrdersScope,OrdersGroup, SymbolScope,SYMBOL, BuysOrSells, "both", 2)) {
	         exist=true; break;
	      }
	   }
	}
	
	if (exist==true) {block55(105);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #107 (Alert message) //
void block107(int _parent_=0)
{
	if (block107==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=107;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string AlertTitle="Obi says BUY!"; // Alert
	string AlertLabel1=""; // Label 1
	string AlertLabel2=""; // Label 2
	string AlertLabel3=""; // Label 3
	string AlertLabel4=""; // Label 4
	string AlertLabel5=""; // Label 5
	string AlertLabel6=""; // Label 6
	string AlertLabel7=""; // Label 7
	string AlertLabel8=""; // Label 8
	string AlertLabel9=""; // Label 9
	string AlertLabel10=""; // Label 10
	bool AlsoSendNotification=false; // Also send notification to my phone
	
	///////////////
	// Main code //
	///////////////
	
	string AlertDataRows="";
	if (AlertLabel1!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel1,": ",_value(0));
	if (AlertLabel2!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel2+": ",_value(0));
	if (AlertLabel3!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel3+": ",_value(0));
	if (AlertLabel4!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel4+": ",_value(0));
	if (AlertLabel5!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel5+": ",_value(0));
	if (AlertLabel6!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel6+": ",_value(0));
	if (AlertLabel7!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel7+": ",_value(0));
	if (AlertLabel8!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel8+": ",_value(0));
	if (AlertLabel9!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel9+": ",_value(0));
	if (AlertLabel10!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel10+": ",_value(0));
	Alert(AlertTitle+"\n"+AlertDataRows);
	if (AlsoSendNotification==true) {
	   SendNotification(AlertTitle+"\n"+AlertDataRows);  
	}
	/* Orange output */
}
double _value(double Value) {
	return(Value);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #108 (Alert message) //
void block108(int _parent_=0)
{
	if (block108==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=108;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string AlertTitle="Obi says SELL!"; // Alert
	string AlertLabel1=""; // Label 1
	string AlertLabel2=""; // Label 2
	string AlertLabel3=""; // Label 3
	string AlertLabel4=""; // Label 4
	string AlertLabel5=""; // Label 5
	string AlertLabel6=""; // Label 6
	string AlertLabel7=""; // Label 7
	string AlertLabel8=""; // Label 8
	string AlertLabel9=""; // Label 9
	string AlertLabel10=""; // Label 10
	bool AlsoSendNotification=false; // Also send notification to my phone
	
	///////////////
	// Main code //
	///////////////
	
	string AlertDataRows="";
	if (AlertLabel1!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel1,": ",_value(0));
	if (AlertLabel2!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel2+": ",_value(0));
	if (AlertLabel3!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel3+": ",_value(0));
	if (AlertLabel4!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel4+": ",_value(0));
	if (AlertLabel5!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel5+": ",_value(0));
	if (AlertLabel6!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel6+": ",_value(0));
	if (AlertLabel7!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel7+": ",_value(0));
	if (AlertLabel8!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel8+": ",_value(0));
	if (AlertLabel9!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel9+": ",_value(0));
	if (AlertLabel10!="") AlertDataRows=StringConcatenate(AlertDataRows,"\n",AlertLabel10+": ",_value(0));
	Alert(AlertTitle+"\n"+AlertDataRows);
	if (AlsoSendNotification==true) {
	   SendNotification(AlertTitle+"\n"+AlertDataRows);  
	}
	/* Orange output */
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #111 (Send Email) //
void block111(int _parent_=0)
{
	if (block111==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=111;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string EmailSubject="Obi says BUY!"; // Email Subject
	string EmailMessage="All conditions are met."; // Email Message
	string DataTitle1=""; // Data 1 title
	string DataTitle2=""; // Data 2 title
	string DataTitle3=""; // Data 3 title
	string DataTitle4=""; // Data 4 title
	string DataTitle5=""; // Data 5 title
	string DataTitle6=""; // Data 6 title
	string DataTitle7=""; // Data 7 title
	string DataTitle8=""; // Data 8 title
	string DataTitle9=""; // Data 9 title
	string DataTitle10=""; // Data 10 title
	
	///////////////
	// Main code //
	///////////////
	
	string EmailDataRows="";
	if (DataTitle1!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle1,": ",_value(0));
	if (DataTitle2!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle2+": ",_value(0));
	if (DataTitle3!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle3+": ",_value(0));
	if (DataTitle4!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle4+": ",_value(0));
	if (DataTitle5!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle5+": ",_value(0));
	if (DataTitle6!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle6+": ",_value(0));
	if (DataTitle7!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle7+": ",_value(0));
	if (DataTitle8!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle8+": ",_value(0));
	if (DataTitle9!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle9+": ",_value(0));
	if (DataTitle10!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle10+": ",_value(0));
	SendMail(EmailSubject, EmailMessage+"\n"+EmailDataRows);
	/* Orange output */
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #112 (Send Email&nbsp;) //
void block112(int _parent_=0)
{
	if (block112==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=112;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string EmailSubject="Obi says SELL!"; // Email Subject
	string EmailMessage="All conditions are met."; // Email Message
	string DataTitle1=""; // Data 1 title
	string DataTitle2=""; // Data 2 title
	string DataTitle3=""; // Data 3 title
	string DataTitle4=""; // Data 4 title
	string DataTitle5=""; // Data 5 title
	string DataTitle6=""; // Data 6 title
	string DataTitle7=""; // Data 7 title
	string DataTitle8=""; // Data 8 title
	string DataTitle9=""; // Data 9 title
	string DataTitle10=""; // Data 10 title
	
	///////////////
	// Main code //
	///////////////
	
	string EmailDataRows="";
	if (DataTitle1!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle1,": ",_value(0));
	if (DataTitle2!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle2+": ",_value(0));
	if (DataTitle3!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle3+": ",_value(0));
	if (DataTitle4!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle4+": ",_value(0));
	if (DataTitle5!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle5+": ",_value(0));
	if (DataTitle6!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle6+": ",_value(0));
	if (DataTitle7!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle7+": ",_value(0));
	if (DataTitle8!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle8+": ",_value(0));
	if (DataTitle9!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle9+": ",_value(0));
	if (DataTitle10!="") EmailDataRows=StringConcatenate(EmailDataRows,"\n",DataTitle10+": ",_value(0));
	SendMail(EmailSubject, EmailMessage+"\n"+EmailDataRows);
	/* Orange output */
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #127 (Condition) //
void block127(int _parent_=0)
{
	if (block127==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=127;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iClose", 2, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iOpen", 2, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo<Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro<Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block131(127);} else if (o2==true) {block132(127);}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #128 (Condition) //
void block128(int _parent_=0)
{
	if (block128==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=128;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iLow", 1, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iLow", 2, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo<Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro<Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block131(128);} else if (o2==true) {block132(128);}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #129 (Condition) //
void block129(int _parent_=0)
{
	if (block129==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=129;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iHigh", 1, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iHigh", 2, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo>Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro>Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block131(129);} else if (o2==true) {block132(129);}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #130 (Condition) //
void block130(int _parent_=0)
{
	if (block130==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=130;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iOpen", 1, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo>Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro>Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block131(130);} else if (o2==true) {block132(130);}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #131 (AND) //
void block131(int _parent_=0)
{
	if (block131==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=131;

	static bool passed=false;
	static string list[];
	static string check[];
	static int old_tick=-1;
	bool go_to_next=false;
	static int list_size;
	
	if (!passed) {passed=true;
	   StringExplode(",",fxD_BlocksLookupTable(3,"131"),list);
	   list_size=ArraySize(list);
	}
	if (list_size==0) {
	   // This block is at the very top => pass everytime
	   go_to_next=true;
	}
	else {
	   // This block is child
	   int ticks=TicksFromStart();
	   if (old_tick!=ticks) {old_tick=ticks;
	      ArrayResize(check,0); // reset
	   }
	   if (ArraySearch(list,_parent_)>-1 && ArraySearch(check,_parent_)==-1) {
	      ArrayValue(check,_parent_); // add current parent
	      if (list_size==ArraySize(check)) {go_to_next=true;}
	   }
	   
	}
	if (go_to_next==true) {block712(131);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #132 (AND) //
void block132(int _parent_=0)
{
	if (block132==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=132;

	static bool passed=false;
	static string list[];
	static string check[];
	static int old_tick=-1;
	bool go_to_next=false;
	static int list_size;
	
	if (!passed) {passed=true;
	   StringExplode(",",fxD_BlocksLookupTable(3,"132"),list);
	   list_size=ArraySize(list);
	}
	if (list_size==0) {
	   // This block is at the very top => pass everytime
	   go_to_next=true;
	}
	else {
	   // This block is child
	   int ticks=TicksFromStart();
	   if (old_tick!=ticks) {old_tick=ticks;
	      ArrayResize(check,0); // reset
	   }
	   if (ArraySearch(list,_parent_)>-1 && ArraySearch(check,_parent_)==-1) {
	      ArrayValue(check,_parent_); // add current parent
	      if (list_size==ArraySize(check)) {go_to_next=true;}
	   }
	   
	}
	if (go_to_next==true) {block713(132);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #200 (alert) //
void block200(int _parent_=0)
{
	if (block200==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=200;

	block127(200); block128(200); block129(200); block130(200); block244(200); block245(200);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #244 (Condition) //
void block244(int _parent_=0)
{
	if (block244==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=244;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_prices("BID", 0, CurrentSymbol());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo<Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro<Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block131(244);} else if (o2==true) {/* Yellow output */}
}
double _prices(string Price, int TickID, string SYMBOL) {
	double retval=0;
	TickID=TickID+IndicatorMoreShift();
	if (Price=="ASK")       {retval=TicksData(SYMBOL,MODE_ASK,TickID);}
	else if (Price=="BID")  {retval=TicksData(SYMBOL,MODE_BID,TickID);}
	else if (Price=="MID")  {retval=((TicksData(SYMBOL,MODE_ASK,TickID)+TicksData(SYMBOL,MODE_BID,TickID))/2);}
	return(retval);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #245 (Condition) //
void block245(int _parent_=0)
{
	if (block245==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=245;

	int crossover=0;
	int crosswidth=1;
	bool o1=false, o2=false;
	
	for (int i=0; i<=crossover; i++) {
	   // i=0 - normal pass, i=1 - crossover pass
	   
	   // Left operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Lo=_prices("ASK", 0, CurrentSymbol());
	   // Right operand of the condition
	   IndicatorMoreShift(true,i*crosswidth);
	   double Ro=_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe());
	   
	   if (SkipThePass()==true) {return;}
	   // Conditions
	   if (Lo>Ro) {if(i==0){o1=true;}}else{if(i==0){o2=true;}else{o2=false;}}
	   if (crossover==1) {if (Ro>Lo) {if(i==0){o2=true;}}else{if(i==1){o1=false;}}}
	}
	IndicatorMoreShift(true,0); // reset
	// Outputs
	if (o1==true) {block132(245);} else if (o2==true) {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #699 (No trade/order exists) //
void block699(int _parent_=0)
{
	if (block699==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=699;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersScope="group"; // Group mode
	string OrdersGroup=""; // Group # (empty=Default)
	string SymbolScope="symbol"; // Market mode
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string BuysOrSells="both"; // Filter by type
	
	///////////////
	// Main code //
	///////////////
	
	bool exist=false;
	for (int pos=OrdersTotal()-1; pos>=0; pos--) {
	   if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)) {
	      if (FilterOrderBy(OrdersScope,OrdersGroup, SymbolScope,SYMBOL, BuysOrSells, "both", 2)) {
	         exist=true; break;
	      }
	   }
	}
	
	if (exist==false) {block799(699);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #700 (yes) //
void block700(int _parent_=0)
{
	if (block700==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=700;

	block102(700);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #701 (No trade/order exists) //
void block701(int _parent_=0)
{
	if (block701==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=701;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersScope="group"; // Group mode
	string OrdersGroup=""; // Group # (empty=Default)
	string SymbolScope="symbol"; // Market mode
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string BuysOrSells="both"; // Filter by type
	
	///////////////
	// Main code //
	///////////////
	
	bool exist=false;
	for (int pos=OrdersTotal()-1; pos>=0; pos--) {
	   if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)) {
	      if (FilterOrderBy(OrdersScope,OrdersGroup, SymbolScope,SYMBOL, BuysOrSells, "both", 2)) {
	         exist=true; break;
	      }
	   }
	}
	
	if (exist==false) {block800(701);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #709 (Draw Arrow) //
void block709(int _parent_=0)
{
	if (block709==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=709;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	bool ObjectPerBar=true; // This block can create 1 object per bar
	bool ObjectUpdate=true; // Redraw the current object
	string ObjName=""; // Object name/prefix (optional)
	ENUM_OBJECT ObjectType=OBJ_ARROW_DOWN; // Object type
	int ObjArrowCode=58; // Wingdings code (0 - 255)
	int ObjAnchor=ANCHOR_TOP; // Anchor type
	color ObjColor=clrRed; // Color
	ENUM_LINE_STYLE ObjStyle=STYLE_SOLID; // Line style
	int ObjWidth=1; // Width
	bool ObjBack=false; // In the background
	bool ObjSelectable=true; // Selectable
	bool ObjSelected=false; // Selected
	bool ObjHidden=false; // Visibility
	int ObjZorder=0; // Z-order
	int ObjChartID=0; // Chart ID (where to draw)
	
	///////////////
	// Main code //
	///////////////
	
	string name          = "";
	string name_base     = "";
	static int count     = 0;
	static datetime time0= 0;
	bool get_new_name    = false;
	bool do_update       = true;
	
	if (ObjectPerBar==true) {
	   datetime time=iTime(Symbol(),0,0);
	   if (time0 < time) {
	      time0 = time;
	      get_new_name = true;
	   } else {
	      if (ObjectUpdate==false) {do_update = false;}
	   }
	}
	else {
	   if (ObjectUpdate==false) {get_new_name = true;}
	}
	
	if (do_update)
	{
	   if (ObjName!="") {name_base=ObjName;} else {name_base=StringConcatenate("fxd_arrow_","709","_");}
	   if (get_new_name == false) {
	      name=StringConcatenate(name_base,count);
	   } else {
	      while(true) {
	         count++;
	         name=StringConcatenate(name_base,count);
	         if (ObjectFind(ChartID(),name)<0) {break;}
	      }
	   }
	   if (ObjName!="" && count==0) {name = ObjName;}
	   
	   if(ObjectFind(ObjChartID,name)<0 && !ObjectCreate(ObjChartID,name,ObjectType,0,0,0))
	   {
	      Print(__FUNCTION__,": failed to create arrow object! Error code = ",GetLastError());
	   }
	
	   if (ObjectType==OBJ_ARROW) {ObjectSetInteger(ObjChartID,name,OBJPROP_ARROWCODE,ObjArrowCode);}
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_TIME,0,_time(0, 0, "00:00", 0, "", 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false));
	   ObjectSetDouble(ObjChartID,name,OBJPROP_PRICE,0,_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe()));
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_STYLE,ObjStyle);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_COLOR,ObjColor);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_BACK,ObjBack);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_WIDTH,ObjWidth);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTABLE,ObjSelectable);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTED,ObjSelected);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_HIDDEN,ObjHidden);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_ZORDER,ObjZorder);
	
	   ChartRedraw();
	}
	
	/* Orange output */
}
datetime _time(int ModeTime, int TimeSource, string TimeStamp, int TimeCandleID, string TimeMarket, int TimeCandleTimeframe, int TimeComponentYear, int TimeComponentMonth, int TimeComponentDay, int TimeComponentHour, int TimeComponentMinute, int TimeComponentSecond, int ModeTimeShift, int TimeShiftYears, int TimeShiftMonths, int TimeShiftWeeks, int TimeShiftDays, int TimeShiftHours, int TimeShiftMinutes, int TimeShiftSeconds, bool TimeSkipWeekdays) {
	static datetime retval=0, retval0=0;
	static int ModeTime0=0;
	static int smodeshift=0;
	
	if(ModeTime==0) {
	   if (TimeSource==1) {retval=TimeLocal();} else {retval=TimeCurrent();}
	}
	else if(ModeTime==1) {
	   //static string TimeStamp0="";
	   //if (ModeTime!=ModeTime0 || TimeStamp!=TimeStamp0) {
	   //   TimeStamp0=TimeStamp;
	      retval=StrToTime(TimeStamp);
	      retval0=retval;
	   //}
	   //else {retval=retval0;}
	}
	else if(ModeTime==2) {
	   if (TimeSource==1) {retval=TimeLocal();} else {retval=TimeCurrent();}
	   
	   if (TimeComponentYear==0)  {TimeComponentYear=TimeYear(retval);}
	   else if (TimeComponentYear<100) {TimeComponentYear=2000+TimeComponentYear;}
	   if (TimeComponentMonth==0) {TimeComponentMonth=TimeMonth(retval);}
	   if (TimeComponentDay==0)   {TimeComponentDay=TimeDay(retval);}
	
	   retval=StrToTime((TimeComponentYear)+"."+(TimeComponentMonth)+"."+(TimeComponentDay)+" "+(TimeComponentHour)+":"+(TimeComponentMinute)+":"+(TimeComponentSecond));
	}
	else if(ModeTime==3) {
	   if (TimeMarket=="") {TimeMarket=Symbol();}
	   retval=iTime(TimeMarket,TimeCandleTimeframe,TimeCandleID);
	}
	
	if (ModeTimeShift>0) {
	   int sh=1;
	   if (ModeTimeShift==1) {sh=-1;}
	   
	   static int years0=0,months0=0;
	   
	   if (
	      ModeTimeShift!=smodeshift
	      || TimeShiftYears!=years0 || TimeShiftMonths!=months0
	   )
	   {
	      years0=TimeShiftYears; months0=TimeShiftMonths;
	      
	      if (TimeShiftYears>0 || TimeShiftMonths>0) {
	         int year=0,month=0,week=0,day=0,hour=0,minute=0,second=0;
	         if (ModeTime==3) {
	            year=TimeComponentYear; month=TimeComponentYear;    day=TimeComponentDay;
	            hour=TimeComponentHour; minute=TimeComponentMinute; second=TimeComponentSecond;
	         }
	         else {
	            year=TimeYear(retval); month=TimeMonth(retval);   day=TimeDay(retval);
	            hour=TimeHour(retval); minute=TimeMinute(retval); second=TimeSeconds(retval);
	         }
	         
	         year  =year+TimeShiftYears*sh;
	         month =month+TimeShiftMonths*sh;
	         if (month<0) {month=12-month;}
	         else if (month>12) {month=month-12;}
	         retval=StrToTime(year+"."+month+"."+day+" "+hour+":"+minute+":"+second);
	      }
	   }
	
	   retval=retval+TimeShiftWeeks*604800*sh+TimeShiftDays*86400*sh+TimeShiftHours*3600*sh+TimeShiftMinutes*60*sh+TimeShiftSeconds*sh;
	      
	   if (TimeSkipWeekdays==true) {
	      int weekday=TimeDayOfWeek(retval);
	      
	      if (sh>0) { // forward
	         if (weekday==0) {retval=retval+86400;}
	         else if (weekday==6) {retval=retval+172800;}
	      }
	      else if (sh<0) { // back
	         if (weekday==0) {retval=retval-172800;}
	         else if (weekday==6) {retval=retval-86400;}
	      }
	   }
	}
	smodeshift=ModeTimeShift;
	ModeTime0=ModeTime;
	
	return(retval);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #712 (Once per bar) //
void block712(int _parent_=0)
{
	if (block712==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=712;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	int TIMEFRAME=CurrentTimeframe(); // Timeframe
	
	///////////////
	// Main code //
	///////////////
	
	static datetime time0;
	datetime time=iTime(SYMBOL,TIMEFRAME,0);
	if (time0<time) {time0=time; block107(712); block111(712); block720(712);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #713 (Once per bar) //
void block713(int _parent_=0)
{
	if (block713==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=713;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	int TIMEFRAME=CurrentTimeframe(); // Timeframe
	
	///////////////
	// Main code //
	///////////////
	
	static datetime time0;
	datetime time=iTime(SYMBOL,TIMEFRAME,0);
	if (time0<time) {time0=time; block108(713); block112(713); block715(713);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #714 (Draw Arrow) //
void block714(int _parent_=0)
{
	if (block714==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=714;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	bool ObjectPerBar=true; // This block can create 1 object per bar
	bool ObjectUpdate=true; // Redraw the current object
	string ObjName=""; // Object name/prefix (optional)
	ENUM_OBJECT ObjectType=OBJ_ARROW_UP; // Object type
	int ObjArrowCode=58; // Wingdings code (0 - 255)
	int ObjAnchor=ANCHOR_TOP; // Anchor type
	color ObjColor=clrLime; // Color
	ENUM_LINE_STYLE ObjStyle=STYLE_SOLID; // Line style
	int ObjWidth=1; // Width
	bool ObjBack=false; // In the background
	bool ObjSelectable=true; // Selectable
	bool ObjSelected=false; // Selected
	bool ObjHidden=false; // Visibility
	int ObjZorder=0; // Z-order
	int ObjChartID=0; // Chart ID (where to draw)
	
	///////////////
	// Main code //
	///////////////
	
	string name          = "";
	string name_base     = "";
	static int count     = 0;
	static datetime time0= 0;
	bool get_new_name    = false;
	bool do_update       = true;
	
	if (ObjectPerBar==true) {
	   datetime time=iTime(Symbol(),0,0);
	   if (time0 < time) {
	      time0 = time;
	      get_new_name = true;
	   } else {
	      if (ObjectUpdate==false) {do_update = false;}
	   }
	}
	else {
	   if (ObjectUpdate==false) {get_new_name = true;}
	}
	
	if (do_update)
	{
	   if (ObjName!="") {name_base=ObjName;} else {name_base=StringConcatenate("fxd_arrow_","714","_");}
	   if (get_new_name == false) {
	      name=StringConcatenate(name_base,count);
	   } else {
	      while(true) {
	         count++;
	         name=StringConcatenate(name_base,count);
	         if (ObjectFind(ChartID(),name)<0) {break;}
	      }
	   }
	   if (ObjName!="" && count==0) {name = ObjName;}
	   
	   if(ObjectFind(ObjChartID,name)<0 && !ObjectCreate(ObjChartID,name,ObjectType,0,0,0))
	   {
	      Print(__FUNCTION__,": failed to create arrow object! Error code = ",GetLastError());
	   }
	
	   if (ObjectType==OBJ_ARROW) {ObjectSetInteger(ObjChartID,name,OBJPROP_ARROWCODE,ObjArrowCode);}
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_TIME,0,_time(0, 0, "00:00", 0, "", 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false));
	   ObjectSetDouble(ObjChartID,name,OBJPROP_PRICE,0,_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe()));
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_STYLE,ObjStyle);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_COLOR,ObjColor);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_BACK,ObjBack);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_WIDTH,ObjWidth);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTABLE,ObjSelectable);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTED,ObjSelected);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_HIDDEN,ObjHidden);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_ZORDER,ObjZorder);
	
	   ChartRedraw();
	}
	
	/* Orange output */
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #715 (Draw Arrow) //
void block715(int _parent_=0)
{
	if (block715==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=715;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	bool ObjectPerBar=true; // This block can create 1 object per bar
	bool ObjectUpdate=true; // Redraw the current object
	string ObjName=""; // Object name/prefix (optional)
	ENUM_OBJECT ObjectType=OBJ_ARROW_DOWN; // Object type
	int ObjArrowCode=58; // Wingdings code (0 - 255)
	int ObjAnchor=ANCHOR_TOP; // Anchor type
	color ObjColor=clrRed; // Color
	ENUM_LINE_STYLE ObjStyle=STYLE_SOLID; // Line style
	int ObjWidth=1; // Width
	bool ObjBack=false; // In the background
	bool ObjSelectable=true; // Selectable
	bool ObjSelected=false; // Selected
	bool ObjHidden=false; // Visibility
	int ObjZorder=0; // Z-order
	int ObjChartID=0; // Chart ID (where to draw)
	
	///////////////
	// Main code //
	///////////////
	
	string name          = "";
	string name_base     = "";
	static int count     = 0;
	static datetime time0= 0;
	bool get_new_name    = false;
	bool do_update       = true;
	
	if (ObjectPerBar==true) {
	   datetime time=iTime(Symbol(),0,0);
	   if (time0 < time) {
	      time0 = time;
	      get_new_name = true;
	   } else {
	      if (ObjectUpdate==false) {do_update = false;}
	   }
	}
	else {
	   if (ObjectUpdate==false) {get_new_name = true;}
	}
	
	if (do_update)
	{
	   if (ObjName!="") {name_base=ObjName;} else {name_base=StringConcatenate("fxd_arrow_","715","_");}
	   if (get_new_name == false) {
	      name=StringConcatenate(name_base,count);
	   } else {
	      while(true) {
	         count++;
	         name=StringConcatenate(name_base,count);
	         if (ObjectFind(ChartID(),name)<0) {break;}
	      }
	   }
	   if (ObjName!="" && count==0) {name = ObjName;}
	   
	   if(ObjectFind(ObjChartID,name)<0 && !ObjectCreate(ObjChartID,name,ObjectType,0,0,0))
	   {
	      Print(__FUNCTION__,": failed to create arrow object! Error code = ",GetLastError());
	   }
	
	   if (ObjectType==OBJ_ARROW) {ObjectSetInteger(ObjChartID,name,OBJPROP_ARROWCODE,ObjArrowCode);}
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_TIME,0,_time(0, 0, "00:00", 0, "", 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false));
	   ObjectSetDouble(ObjChartID,name,OBJPROP_PRICE,0,_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe()));
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_STYLE,ObjStyle);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_COLOR,ObjColor);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_BACK,ObjBack);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_WIDTH,ObjWidth);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTABLE,ObjSelectable);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTED,ObjSelected);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_HIDDEN,ObjHidden);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_ZORDER,ObjZorder);
	
	   ChartRedraw();
	}
	
	/* Orange output */
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #720 (Draw Arrow) //
void block720(int _parent_=0)
{
	if (block720==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=720;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	bool ObjectPerBar=true; // This block can create 1 object per bar
	bool ObjectUpdate=true; // Redraw the current object
	string ObjName=""; // Object name/prefix (optional)
	ENUM_OBJECT ObjectType=OBJ_ARROW_UP; // Object type
	int ObjArrowCode=58; // Wingdings code (0 - 255)
	int ObjAnchor=ANCHOR_TOP; // Anchor type
	color ObjColor=clrLime; // Color
	ENUM_LINE_STYLE ObjStyle=STYLE_SOLID; // Line style
	int ObjWidth=1; // Width
	bool ObjBack=false; // In the background
	bool ObjSelectable=true; // Selectable
	bool ObjSelected=false; // Selected
	bool ObjHidden=false; // Visibility
	int ObjZorder=0; // Z-order
	int ObjChartID=0; // Chart ID (where to draw)
	
	///////////////
	// Main code //
	///////////////
	
	string name          = "";
	string name_base     = "";
	static int count     = 0;
	static datetime time0= 0;
	bool get_new_name    = false;
	bool do_update       = true;
	
	if (ObjectPerBar==true) {
	   datetime time=iTime(Symbol(),0,0);
	   if (time0 < time) {
	      time0 = time;
	      get_new_name = true;
	   } else {
	      if (ObjectUpdate==false) {do_update = false;}
	   }
	}
	else {
	   if (ObjectUpdate==false) {get_new_name = true;}
	}
	
	if (do_update)
	{
	   if (ObjName!="") {name_base=ObjName;} else {name_base=StringConcatenate("fxd_arrow_","720","_");}
	   if (get_new_name == false) {
	      name=StringConcatenate(name_base,count);
	   } else {
	      while(true) {
	         count++;
	         name=StringConcatenate(name_base,count);
	         if (ObjectFind(ChartID(),name)<0) {break;}
	      }
	   }
	   if (ObjName!="" && count==0) {name = ObjName;}
	   
	   if(ObjectFind(ObjChartID,name)<0 && !ObjectCreate(ObjChartID,name,ObjectType,0,0,0))
	   {
	      Print(__FUNCTION__,": failed to create arrow object! Error code = ",GetLastError());
	   }
	
	   if (ObjectType==OBJ_ARROW) {ObjectSetInteger(ObjChartID,name,OBJPROP_ARROWCODE,ObjArrowCode);}
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_TIME,0,_time(0, 0, "00:00", 0, "", 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false));
	   ObjectSetDouble(ObjChartID,name,OBJPROP_PRICE,0,_candles("iClose", 1, CurrentSymbol(), CurrentTimeframe()));
	
	   ObjectSetInteger(ObjChartID,name,OBJPROP_STYLE,ObjStyle);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_COLOR,ObjColor);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_BACK,ObjBack);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_WIDTH,ObjWidth);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTABLE,ObjSelectable);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTED,ObjSelected);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_HIDDEN,ObjHidden);
	   ObjectSetInteger(ObjChartID,name,OBJPROP_ZORDER,ObjZorder);
	
	   ChartRedraw();
	}
	
	/* Orange output */
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #795 (Close profitable trades) //
void block795(int _parent_=0)
{
	if (block795==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=795;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersScope="group"; // Group mode
	string OrdersGroup=""; // Group # (empty=Default)
	string SymbolScope="symbol"; // Market mode
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string BuysOrSells="sells"; // Filter by type
	int OrderMinutes=0; // Only older than
	string MeasureMode="pips"; // Measure mode
	double PipsAmount=0; // Profit is more than
	double MoneyAmount=0; // Profit is more than
	double Slippage=4; // Slippage
	color ArrowColor=DeepPink; // Arrow color
	
	///////////////
	// Main code //
	///////////////
	
	int closed_count=0;
	bool finished=false;
	while (finished==false) {
	   int count=0;
	   for (int pos=OrdersTotal()-1; pos>=0; pos--) {
	      if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)) {
	         if (FilterOrderBy(OrdersScope,OrdersGroup, SymbolScope,SYMBOL, BuysOrSells)) {
	            if (TimeCurrent()-attrOpenTime()>=60*OrderMinutes) {
	               SetSymbol(SYMBOL);
	               if (
	                  (MeasureMode=="money" && (attrProfit()+attrCommission()+attrSwap())>MoneyAmount)
	                  ||
	                  (MeasureMode=="pips" && ((attrType()==OP_BUY && SymbolBid()-attrOpenPrice()>toDigits(PipsAmount)) || (attrType()==OP_SELL && attrOpenPrice()-SymbolAsk()>toDigits(PipsAmount))))
	                  )
	               {
	                  if (CloseTrade(attrTicket(),Slippage,ArrowColor)) {closed_count++;}
	                  count++;
	   }  }  }  }  }
	   if (count==0) {finished=true;}
	}
	
	block699(795);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #796 (Close profitable trades) //
void block796(int _parent_=0)
{
	if (block796==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=796;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersScope="group"; // Group mode
	string OrdersGroup=""; // Group # (empty=Default)
	string SymbolScope="symbol"; // Market mode
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string BuysOrSells="buys"; // Filter by type
	int OrderMinutes=0; // Only older than
	string MeasureMode="pips"; // Measure mode
	double PipsAmount=0; // Profit is more than
	double MoneyAmount=0; // Profit is more than
	double Slippage=4; // Slippage
	color ArrowColor=DeepPink; // Arrow color
	
	///////////////
	// Main code //
	///////////////
	
	int closed_count=0;
	bool finished=false;
	while (finished==false) {
	   int count=0;
	   for (int pos=OrdersTotal()-1; pos>=0; pos--) {
	      if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)) {
	         if (FilterOrderBy(OrdersScope,OrdersGroup, SymbolScope,SYMBOL, BuysOrSells)) {
	            if (TimeCurrent()-attrOpenTime()>=60*OrderMinutes) {
	               SetSymbol(SYMBOL);
	               if (
	                  (MeasureMode=="money" && (attrProfit()+attrCommission()+attrSwap())>MoneyAmount)
	                  ||
	                  (MeasureMode=="pips" && ((attrType()==OP_BUY && SymbolBid()-attrOpenPrice()>toDigits(PipsAmount)) || (attrType()==OP_SELL && attrOpenPrice()-SymbolAsk()>toDigits(PipsAmount))))
	                  )
	               {
	                  if (CloseTrade(attrTicket(),Slippage,ArrowColor)) {closed_count++;}
	                  count++;
	   }  }  }  }  }
	   if (count==0) {finished=true;}
	}
	
	block701(796);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #797 (Delay) //
void block797(int _parent_=0)
{
	if (block797==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=797;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	double SleepSeconds=15; // Seconds
	bool SleepInTesterNormal=false; // Realtime delay (Normal mode)
	bool SleepInTesterVisual=false; // Realtime delay  (Visual mode)
	
	///////////////
	// Main code //
	///////////////
	
	if (!IsTesting()) {Sleep(SleepSeconds*1000);}
	else {
	   bool doit=false;
	   if (IsVisualMode()) {
	      if (SleepInTesterVisual==true) {doit=true;}  
	   }
	   else {
	      if (SleepInTesterNormal==true) {doit=true;}
	   }
	   if (doit==true) {
	      SleepEx(SleepSeconds*1000,false);
	   }
	   else {Sleep(SleepSeconds*1000);} // This is actually not needed
	}
	block105(797);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #798 (Look for exit once per bar<br>) //
void block798(int _parent_=0)
{
	if (block798==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=798;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	int TIMEFRAME=CurrentTimeframe(); // Timeframe
	
	///////////////
	// Main code //
	///////////////
	
	static datetime time0;
	datetime time=iTime(SYMBOL,TIMEFRAME,0);
	if (time0<time) {time0=time; block797(798);} else {/* Yellow output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #799 (Buy now) //
void block799(int _parent_=0)
{
	if (block799==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=799;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersGroup=""; // Group # (empty=Default)
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string VolumeMode="fixed"; // Money management
	double VolumeSize=inp799_VolumeSize; // Lot size
	double VolumeSizeRisk=50; // Risk fixed amount of money
	double VolumeRisk=2.5; // Risk percent
	double VolumePercent=100; // Volume size
	double VolumeBlockPercent=3; // Block % of Balance
	double FixedRatioUnitSize=0.01; // Fixed Ratio: Unit size
	double FixedRatioDelta=20; // Fixed Ratio: Delta parameter
	double mmMgInitialLots=0.1; // Initial volume
	double mmMgMultiplyOnLoss=2; // Multiply on loss
	double mmMgMultiplyOnProfit=1; // Multiply on profit
	double mmMgAddLotsOnLoss=0; // Add lots on loss
	double mmMgAddLotsOnProfit=0; // Add lots on profit
	int mmMgResetOnLoss=0; // Reset after how many losses?
	int mmMgResetOnProfit=1; // Reset after how many profits?
	double mm1326InitialLots=0.1; // Initial volume
	bool mm1326Reverse=false; // Reverse 1-3-2-6?
	double mmFiboInitialLots=0.1; // Initial volume
	double mmDalembertInitialLots=0.1; // Initial volume
	bool mmDalembertReverse=false; // Reverse D'Alembert
	double mmLabouchereInitialLots=0.1; // Initial volume
	string mmLabouchereList="1,2,3,4,5,6"; // List of numbers
	bool mmLabouchereReverse=false; // Reverse Labouchere
	double mmSeqBaseLots=0.1; // Base volume
	string mmSeqOnLoss="3,2,6"; // Sequence on loss
	string mmSeqOnProfit="1"; // Sequence on profit
	bool mmSeqReverse=false; // Reverse system?
	double VolumeUpperLimit=0; // Volume upper limit
	string StopLossMode="fixed"; // Stop-Loss mode
	double StopLossPips=inp799_StopLossPips; // in pips...
	string TakeProfitMode="fixed"; // Take-Profit mode
	double TakeProfitPips=inp799_TakeProfitPips; // in pips...
	string ExpMode="GTC"; // Expiration mode
	int ExpDays=0; // Days
	int ExpHours=1; // Hours
	int ExpMinutes=0; // Minutes
	double Slippage=4; // Slippage
	string MyComment="Long trade"; // Comment
	color ArrowColorBuy=Blue; // Arrow color
	
	///////////////
	// Main code //
	///////////////
	
	SetSymbol(SYMBOL);
	
	//-- stops ------------------------------------------------------------------
	double sll=0, slp=0, tpl=0, tpp=0;
	
	     if (StopLossMode=="fixed")        {slp=StopLossPips;}
	else if (StopLossMode=="dynamicPips")  {slp=_value(100);}
	else if (StopLossMode=="dynamicDigits"){slp=toPips(_value(0.0100),SYMBOL);}
	else if (StopLossMode=="dynamicLevel") {sll=_value(1);}
	
	     if (TakeProfitMode=="fixed")         {tpp=TakeProfitPips;}
	else if (TakeProfitMode=="dynamicPips")   {tpp=_value(100);}
	else if (TakeProfitMode=="dynamicDigits") {tpp=toPips(_value(0.0100),SYMBOL);}
	else if (TakeProfitMode=="dynamicLevel")  {tpl=_value(1);}
	
	//-- lots -------------------------------------------------------------------
	double lots=0;
	double pre_sll=sll; if (pre_sll==0) {pre_sll=SymbolAsk(SYMBOL);}
	double pre_sl_pips=toPips(SymbolAsk(SYMBOL)-(pre_sll-toDigits(slp,SYMBOL)));
	
	     if (VolumeMode=="fixed")             {lots=DynamicLots(VolumeMode, VolumeSize);}
	else if (VolumeMode=="block-equity")      {lots=DynamicLots(VolumeMode, VolumeBlockPercent);}
	else if (VolumeMode=="block-balance")     {lots=DynamicLots(VolumeMode, VolumeBlockPercent);}
	else if (VolumeMode=="block-freemargin")  {lots=DynamicLots(VolumeMode, VolumeBlockPercent);}
	else if (VolumeMode=="equity")            {lots=DynamicLots(VolumeMode, VolumePercent);}
	else if (VolumeMode=="balance")           {lots=DynamicLots(VolumeMode, VolumePercent);}
	else if (VolumeMode=="freemargin")        {lots=DynamicLots(VolumeMode, VolumePercent);}
	else if (VolumeMode=="equityRisk")        {lots=DynamicLots(VolumeMode, VolumeRisk, pre_sl_pips);}
	else if (VolumeMode=="balanceRisk")       {lots=DynamicLots(VolumeMode, VolumeRisk, pre_sl_pips);}
	else if (VolumeMode=="freemarginRisk")    {lots=DynamicLots(VolumeMode, VolumeRisk, pre_sl_pips);}
	else if (VolumeMode=="fixedRisk")         {lots=DynamicLots(VolumeMode, VolumeSizeRisk, pre_sl_pips);}
	else if (VolumeMode=="fixedRatio")        {lots=DynamicLots(VolumeMode, FixedRatioUnitSize, FixedRatioDelta);}
	else if (VolumeMode=="dynamic")           {lots=AlignLots(_value(0.1));}
	else if (VolumeMode=="1326")              {lots=Bet1326(OrdersGroup, SYMBOL, mm1326InitialLots, mm1326Reverse);}
	else if (VolumeMode=="fibonacci")         {lots=BetFibonacci(OrdersGroup, SYMBOL, mmFiboInitialLots);}
	else if (VolumeMode=="dalembert")         {lots=BetDalembert(OrdersGroup, SYMBOL, mmDalembertInitialLots, mmDalembertReverse);}
	else if (VolumeMode=="labouchere")        {lots=BetLabouchere(OrdersGroup, SYMBOL, mmLabouchereInitialLots, mmLabouchereList, mmLabouchereReverse);}
	else if (VolumeMode=="martingale")        {lots=BetMartingale(OrdersGroup, SYMBOL, mmMgInitialLots, mmMgMultiplyOnLoss, mmMgMultiplyOnProfit, mmMgAddLotsOnLoss, mmMgAddLotsOnProfit, mmMgResetOnLoss, mmMgResetOnProfit);}
	else if (VolumeMode=="sequence")          {lots=BetSequence(OrdersGroup, SYMBOL, mmSeqBaseLots, mmSeqOnLoss, mmSeqOnProfit, mmSeqReverse);}
	
	lots = AlignLots(lots, 0, VolumeUpperLimit);
	
	datetime exp = ExpirationTime(ExpMode,ExpDays,ExpHours,ExpMinutes,_time(0, 0, "00:00", 1, "", 0, 0, 0, 0, 12, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, true));
	
	//-- send -------------------------------------------------------------------
	int ticket=BuyNow(SYMBOL, lots, sll, tpl, slp, tpp, Slippage, (MagicStart+(int)OrdersGroup), MyComment, ArrowColorBuy, exp);
	
	if (ticket>0) {block714(799);} else {/* Gray output */}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// fxDreema block #800 (Sell now) //
void block800(int _parent_=0)
{
	if (block800==false || FXD_BREAK==true) {return;}
	FXD_CURRENT_FUNCTION_ID=800;

	//////////////////////
	// Input parameters //
	//////////////////////
	
	string OrdersGroup=""; // Group # (empty=Default)
	string SYMBOL=CurrentSymbol(); // Market (empty=Current)
	string VolumeMode="fixed"; // Money management
	double VolumeSize=inp800_VolumeSize; // Lot size
	double VolumeSizeRisk=50; // Risk fixed amount of money
	double VolumeRisk=2.5; // Risk percent
	double VolumePercent=100; // Volume size
	double VolumeBlockPercent=3; // Block % of Balance
	double FixedRatioUnitSize=0.01; // Fixed Ratio: Unit size
	double FixedRatioDelta=20; // Fixed Ratio: Delta parameter
	double mmMgInitialLots=0.1; // Initial volume
	double mmMgMultiplyOnLoss=2; // Multiply on loss
	double mmMgMultiplyOnProfit=1; // Multiply on profit
	double mmMgAddLotsOnLoss=0; // Add lots on loss
	double mmMgAddLotsOnProfit=0; // Add lots on profit
	int mmMgResetOnLoss=0; // Reset after how many losses?
	int mmMgResetOnProfit=1; // Reset after how many profits?
	double mm1326InitialLots=0.1; // Initial volume
	bool mm1326Reverse=false; // Reverse 1-3-2-6?
	double mmFiboInitialLots=0.1; // Initial volume
	double mmDalembertInitialLots=0.1; // Initial volume
	bool mmDalembertReverse=false; // Reverse D'Alembert
	double mmLabouchereInitialLots=0.1; // Initial volume
	string mmLabouchereList="1,2,3,4,5,6"; // List of numbers
	bool mmLabouchereReverse=false; // Reverse Labouchere
	double mmSeqBaseLots=0.1; // Base volume
	string mmSeqOnLoss="3,2,6"; // Sequence on loss
	string mmSeqOnProfit="1"; // Sequence on profit
	bool mmSeqReverse=false; // Reverse system?
	double VolumeUpperLimit=0; // Volume upper limit
	string StopLossMode="fixed"; // Stop-Loss mode
	double StopLossPips=inp800_StopLossPips; // in pips...
	string TakeProfitMode="fixed"; // Take-Profit mode
	double TakeProfitPips=inp800_TakeProfitPips; // in pips...
	string ExpMode="GTC"; // Expiration mode
	int ExpDays=0; // Days
	int ExpHours=1; // Hours
	int ExpMinutes=0; // Minutes
	double Slippage=4; // Slippage
	string MyComment="Short trade"; // Comment
	color ArrowColorSell=Red; // Arrow color
	
	///////////////
	// Main code //
	///////////////
	
	SetSymbol(SYMBOL);
	
	//-- stops ------------------------------------------------------------------
	double sll=0, slp=0, tpl=0, tpp=0;
	
	     if (StopLossMode=="fixed")        {slp=StopLossPips;}
	else if (StopLossMode=="dynamicPips")  {slp=_value(100);}
	else if (StopLossMode=="dynamicDigits"){slp=toPips(_value(0.0100),SYMBOL);}
	else if (StopLossMode=="dynamicLevel") {sll=_value(1);}
	
	     if (TakeProfitMode=="fixed")         {tpp=TakeProfitPips;}
	else if (TakeProfitMode=="dynamicPips")   {tpp=_value(100);}
	else if (TakeProfitMode=="dynamicDigits") {tpp=toPips(_value(0.0100),SYMBOL);}
	else if (TakeProfitMode=="dynamicLevel")  {tpl=_value(1);}
	
	//-- lots -------------------------------------------------------------------
	double lots=0;
	double pre_sll=sll; if (pre_sll==0) {pre_sll=SymbolBid(SYMBOL);}
	double pre_sl_pips=toPips((pre_sll+toDigits(slp,SYMBOL))-SymbolBid(SYMBOL));
	
	     if (VolumeMode=="fixed")             {lots=DynamicLots(VolumeMode, VolumeSize);}
	else if (VolumeMode=="block-equity")      {lots=DynamicLots(VolumeMode, VolumeBlockPercent);}
	else if (VolumeMode=="block-balance")     {lots=DynamicLots(VolumeMode, VolumeBlockPercent);}
	else if (VolumeMode=="block-freemargin")  {lots=DynamicLots(VolumeMode, VolumeBlockPercent);}
	else if (VolumeMode=="equity")            {lots=DynamicLots(VolumeMode, VolumePercent);}
	else if (VolumeMode=="balance")           {lots=DynamicLots(VolumeMode, VolumePercent);}
	else if (VolumeMode=="freemargin")        {lots=DynamicLots(VolumeMode, VolumePercent);}
	else if (VolumeMode=="equityRisk")        {lots=DynamicLots(VolumeMode, VolumeRisk, pre_sl_pips);}
	else if (VolumeMode=="balanceRisk")       {lots=DynamicLots(VolumeMode, VolumeRisk, pre_sl_pips);}
	else if (VolumeMode=="freemarginRisk")    {lots=DynamicLots(VolumeMode, VolumeRisk, pre_sl_pips);}
	else if (VolumeMode=="fixedRisk")         {lots=DynamicLots(VolumeMode, VolumeSizeRisk, pre_sl_pips);}
	else if (VolumeMode=="fixedRatio")        {lots=DynamicLots(VolumeMode, FixedRatioUnitSize, FixedRatioDelta);}
	else if (VolumeMode=="dynamic")           {lots=AlignLots(_value(0.1));}
	else if (VolumeMode=="1326")              {lots=Bet1326(OrdersGroup, SYMBOL, mm1326InitialLots, mm1326Reverse);}
	else if (VolumeMode=="fibonacci")         {lots=BetFibonacci(OrdersGroup, SYMBOL, mmFiboInitialLots);}
	else if (VolumeMode=="dalembert")         {lots=BetDalembert(OrdersGroup, SYMBOL, mmDalembertInitialLots, mmDalembertReverse);}
	else if (VolumeMode=="labouchere")        {lots=BetLabouchere(OrdersGroup, SYMBOL, mmLabouchereInitialLots, mmLabouchereList, mmLabouchereReverse);}
	else if (VolumeMode=="martingale")        {lots=BetMartingale(OrdersGroup, SYMBOL, mmMgInitialLots, mmMgMultiplyOnLoss, mmMgMultiplyOnProfit, mmMgAddLotsOnLoss, mmMgAddLotsOnProfit, mmMgResetOnLoss, mmMgResetOnProfit);}
	else if (VolumeMode=="sequence")          {lots=BetSequence(OrdersGroup, SYMBOL, mmSeqBaseLots, mmSeqOnLoss, mmSeqOnProfit, mmSeqReverse);}
	
	lots = AlignLots(lots, 0, VolumeUpperLimit);
	
	datetime exp = ExpirationTime(ExpMode,ExpDays,ExpHours,ExpMinutes,_time(0, 0, "00:00", 1, "", 0, 0, 0, 0, 12, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, true));
	
	//-- send -------------------------------------------------------------------
	int ticket=SellNow(SYMBOL, lots, sll, tpl, slp, tpp, Slippage, (MagicStart+(int)OrdersGroup), MyComment, ArrowColorSell, exp);
	
	if (ticket>0) {block709(800);} else {/* Gray output */}
}


/************************************************************************************************************************/
// +------------------------------------------------------------------------------------------------------------------+ //
// |                                                  API FUNCTIONS                                                   | //
// |                                 System and Custom functions used in the program                                  | //
// +------------------------------------------------------------------------------------------------------------------+ //
/************************************************************************************************************************/

// System functions
double AccountBalanceAtStart()
{
   // This function MUST be run once at pogram's start
	static double memory=0;
   if (memory==0) {memory=AccountBalance();}
   return(memory);
}
double AlignLots(double lots, double lowerlots=0, double upperlots=0)
{
	string symbol=GetSymbol();

   double LotStep=MarketInfo(symbol,MODE_LOTSTEP);
   double LotSize=MarketInfo(symbol,MODE_LOTSIZE);
   double MinLots=MarketInfo(symbol,MODE_MINLOT);
   double MaxLots=MarketInfo(symbol,MODE_MAXLOT);
   double margin_required=MarketInfo(symbol,MODE_MARGINREQUIRED);
   
   //if (lots>MaxLots) {lots=lots/LotSize;}
   
   //double stepsize=0;
   //while(lots+0.000000001>stepsize){stepsize+=LotStep;}
   //lots=stepsize-LotStep;
   lots=MathRound(lots/LotStep)*LotStep;
   
   if (lots<MinLots) {lots=MinLots;}
   if (lots>MaxLots) {lots=MaxLots;}

   if (lowerlots > 0)
   {
      lowerlots = MathRound(lowerlots/LotStep)*LotStep;
      if (lots < lowerlots) {lots = lowerlots;}
   }
   if (upperlots > 0)
   {
      upperlots = MathRound(upperlots/LotStep)*LotStep;
      if (lots > upperlots) {lots = upperlots;}
   }
   
   return (lots);
}
double AlignStopLoss(
   string symbol,
   int type,
   double price,
   double sll=0,
   double slp=0,
   bool consider_freezelevel=false
   )
{
   double sl=0;

   if (sll==0 && slp==0) {return(0);} // no sl - return 0
   if (price<=0) {Print("AlignStopLoss() error: No price entered");return(-1);}
   
   double point   =MarketInfo(symbol,MODE_POINT);
   double digits  =MarketInfo(symbol,MODE_DIGITS);
   slp=slp*PipValue(symbol)*point;
   
   //-- buy-sell identifier ---------------------------------------------
   int bs=1;
   if (
      type==OP_BUY
      || type==OP_BUYSTOP
      || type==OP_BUYLIMIT
      )
   {
      bs=1;
   }
   else if (
      type==OP_SELL
      || type==OP_SELLSTOP
      || type==OP_SELLLIMIT
      )
   {
      bs=-1;
   }
   
   //-- prices that will be used ----------------------------------------
   double askbid=price;
   double bidask=price;
   
   if (type==OP_BUY || type==OP_SELL)
   {
      double ask =MarketInfo(symbol,MODE_ASK);
      double bid =MarketInfo(symbol,MODE_BID);
      
      askbid=ask;
      bidask=bid;
      if (bs<0) {
        askbid=bid;
        bidask=ask;
      }
   }
   
   //-- build sl level -------------------------------------------------- 
   if (sll==0 && slp!=0) {sll=price;}

   if (sll>0) {sl=sll-slp*bs;}
   
   if (sl<0) {return(-1);}
      
   sl=NormalizeDouble(sl,digits);
   
   //-- build limit levels ----------------------------------------------
   double minstops=MarketInfo(symbol,MODE_STOPLEVEL);
   if (consider_freezelevel==true) {
      int freezelevel=MarketInfo(symbol,MODE_FREEZELEVEL);
      if (freezelevel>minstops) {minstops=freezelevel;}
   }
   minstops=NormalizeDouble(minstops*point,digits);
      
   double sllimit=bidask-minstops*bs; // SL min price level
   
   //-- check and align sl, print errors --------------------------------
   if (sl>0) {
      if (sl==askbid)
      {
         sl=0;
      }
      else if ((bs>0 && sl>askbid) || (bs<0 && sl<askbid))
      {
         string abstr="";
         if (bs>0) {abstr="Ask";} else {abstr="Bid";}
         Print(
            "Error: Invalid SL requested (",
            DoubleToStr(sl,digits),
            " for ",abstr," price ",
            askbid,
            ")"
         );
         return(-1);
      }
      else if ((bs>0 && sl>sllimit) || (bs<0 && sl<sllimit))
      {
         if (USE_VIRTUAL_STOPS) {
            return(sl);
         }

         Print(
            "Warning: Too short SL requested (",
            DoubleToStr(sl,digits),
            " or ",
            DoubleToStr(MathAbs(sl-askbid)/point,0),
            " points), minimum will be taken (",
            DoubleToStr(sllimit,digits),
            " or ",
            DoubleToStr(MathAbs(askbid-sllimit)/point,0),
            " points)"
         );
         sl=sllimit;

         return(sl);
      }
   }
   return(sl);
}
double AlignTakeProfit(
   string symbol,
   int type,
   double price,
   double tpl=0,
   double tpp=0,
   bool consider_freezelevel=false
   )
{
   double tp=0;
   
   if (tpl==0 && tpp==0) {return(0);} // no tp - return 0
   if (price<=0) {Print("AlignTakeProfit() error: No price entered");return(-1);}

   double point   =MarketInfo(symbol,MODE_POINT);
   double digits  =MarketInfo(symbol,MODE_DIGITS);
   tpp=tpp*PipValue(symbol)*point;
   
   //-- buy-sell identifier ---------------------------------------------
   int bs=1;
   if (
      type==OP_BUY
      || type==OP_BUYSTOP
      || type==OP_BUYLIMIT
      )
   {
      bs=1;
   }
   else if (
      type==OP_SELL
      || type==OP_SELLSTOP
      || type==OP_SELLLIMIT
      )
   {
      bs=-1;
   }
   
   //-- prices that will be used ----------------------------------------
   double askbid=price;
   double bidask=price;
   
   if (type==OP_BUY || type==OP_SELL)
   {
      double ask =MarketInfo(symbol,MODE_ASK);
      double bid =MarketInfo(symbol,MODE_BID);
      
      askbid=ask;
      bidask=bid;
      if (bs<0) {
        askbid=bid;
        bidask=ask;
      }
   }
   
   //-- build tp level --------------------------------------------------- 
   if (tpl==0 && tpp!=0) {tpl=price;}

   if (tpl>0) {tp=tpl+tpp*bs;}
   
   if (tp<0) {return(-1);}

   tp=NormalizeDouble(tp,digits);
   
   //-- build limit levels ----------------------------------------------
   double minstops=MarketInfo(symbol,MODE_STOPLEVEL);
   if (consider_freezelevel==true) {
      int freezelevel=MarketInfo(symbol,MODE_FREEZELEVEL);
      if (freezelevel>minstops) {minstops=freezelevel;}
   }
   minstops=NormalizeDouble(minstops*point,digits);
   
   double tplimit=bidask+minstops*bs; // TP min price level
   
   //-- check and align tp, print errors --------------------------------
   if (tp>0) {
      if (tp==askbid)
      {
         tp=0;
      }
      else if ((bs>0 && tp<askbid) || (bs<0 && tp>askbid))
      {
         string abstr="";
         if (bs>0) {abstr="Ask";} else {abstr="Bid";}
         Print(
            "Error: Invalid TP requested (",
            DoubleToStr(tp,digits),
            " for ",abstr," price ",
            askbid,
            ")"
            );
         return(-1);
      }
      else if ((bs>0 && tp<tplimit) || (bs<0 && tp>tplimit))
      {
         if (USE_VIRTUAL_STOPS) {
            return(tp);
         }

         Print(
            "Warning: Too short TP requested (",
            DoubleToStr(tp,digits),
            " or ",
            DoubleToStr(MathAbs(tp-askbid)/point,0),
            " points), minimum will be taken (",
            DoubleToStr(tplimit,digits),
            " or ",
            DoubleToStr(MathAbs(askbid-tplimit)/point,0),
            " points)"
         );
         tp=tplimit;
         return(tp);
      }
   }
   return(tp);
}
int ArraySearch(double &array[], double value)
{
   static bool founded; founded=false;
   static int index;    index=0;
   static int size;
   size=ArraySize(array);
   
   if (size>0)
   {
   	for (int i=0; i<size; i++)
      {
         if (array[i]==value)
         {
            founded=true;
            index=i;
            break;
         }  
   	}
   }

   if (founded==true) {return (index);} else {return (-1);}
}
int ArraySearch(int &array[], int value)
{
   static bool founded; founded=false;
   static int index;    index=0;
   static int size;
   size=ArraySize(array);
   
   if (size>0)
   {
      for (int i=0; i<size; i++)
      {
         if (array[i]==value)
         {
            founded=true;
            index=i;
            break;
         }  
   	}
   }

   if (founded==true) {return (index);} else {return (-1);}
}
int ArraySearch(string &array[], string value)
{
   static bool founded; founded=false;
   static int index;    index=0;
   static int size;
   size=ArraySize(array);
   
   if (size>0)
   {
      for (int i=0; i<size; i++)
      {
         if (array[i]==value)
         {
            founded=true;
            index=i;
            break;
         }  
   	}
   }

   if (founded==true) {return (index);} else {return (-1);}
}
bool ArrayStrip(double &array[], double value)
{
   bool stripped=false;
   int size=ArraySize(array);
   if (size>0)
   {
      int i=0; int x=0;
      for (i=0; i<size; i++)
      {
         if (array[i]!=value)
         {
            array[x]=array[i];
            x++;
         } else {
            stripped=true;  
         }
      }
      ArrayResize(array,x);
   }
   return (stripped);
}
bool ArrayStripKey(double &array[], double key)
{
   static bool stripped; stripped=false;
   static int size;
   size = ArraySize(array);
   if (size>0)
   {
      int i=0; int x=0;
      for (i=0; i<size; i++)
      {
         if (i!=key)
         {
            array[x]=array[i];
            x++;
         } else {
            stripped=true;  
         }
      }
      ArrayResize(array,x);
   }
   return (stripped);
}
bool ArrayStripKey(int &array[], int key)
{
   static bool stripped; stripped=false;
   static int size;
   size = ArraySize(array);
   if (size>0)
   {
      int i=0; int x=0;
      for (i=0; i<size; i++)
      {
         if (i!=key)
         {
            array[x]=array[i];
            x++;
         } else {
            stripped=true;  
         }
      }
      ArrayResize(array,x);
   }
   return (stripped);
}
bool ArrayStripKey(string &array[], string key)
{
   static bool stripped; stripped=false;
   static int size;
   size = ArraySize(array);
   if (size>0)
   {
      int i=0; int x=0;
      for (i=0; i<size; i++)
      {
         if (i!=key)
         {
            array[x]=array[i];
            x++;
         } else {
            stripped=true;  
         }
      }
      ArrayResize(array,x);
   }
   return (stripped);
}
bool ArrayValue(double &array[], double value)
{
   bool founded=false;
   int size=ArraySize(array);
   for (int i=0; i<size; i++) {
      if (array[i]==value) {founded=true; break;}
   }
   if (founded==false) {
      ArrayResize(array,size+1);
      array[size]=value;
      return (true);
   } else {
      return (false);
   }
}
bool ArrayValue(int &array[], int value)
{
   bool founded=false;
   int size=ArraySize(array);
   for (int i=0; i<size; i++) {
      if (array[i]==value) {founded=true; break;}
   }
   if (founded==false) {
      ArrayResize(array,size+1);
      array[size]=value;
      return (true);
   } else {
      return (false);
   }
}
bool ArrayValue(string &array[], string value)
{
   bool founded=false;
   int size=ArraySize(array);
   for (int i=0; i<size; i++) {
      if (array[i]==value) {founded=true; break;}
   }
   if (founded==false) {
      ArrayResize(array,size+1);
      array[size]=value;
      return (true);
   } else {
      return (false);  
   }
}
double attrClosePrice(string sel="")
{
   return(OrderClosePrice());
}
string attrComment(string sel="")
{
   return(OrderComment());
}
double attrCommission(string sel="")
{
   if (sel=="e" || sel=="event") {return(e_attrCommission());}
   return(OrderCommission());
}
datetime attrExpiration(string sel="")
{
   return(OrderExpiration());
}
double attrLots(string sel="")
{
   return(OrderLots());
}
int attrMagicNumber(string sel="")
{
   return(OrderMagicNumber());
}
double attrOpenPrice(string sel="")
{
   return(OrderOpenPrice());
}
datetime attrOpenTime(string sel="")
{
   return(OrderOpenTime());
}
double attrProfit(string sel="")
{
   return(OrderProfit());
}
double attrStopLoss()
{
   if (USE_VIRTUAL_STOPS) {return(VirtualStopsDriver("get sl",OrderTicket()));}
   return(OrderStopLoss());
}
double attrSwap(string sel="")
{
   return(OrderSwap());
}
string attrSymbol(string sel="")
{
   return(OrderSymbol());
}
double attrTakeProfit()
{
   if (USE_VIRTUAL_STOPS) {return(VirtualStopsDriver("get tp",OrderTicket()));}
   return(OrderTakeProfit());
}
int attrTicket()
{
   return(OrderTicket());
}
double attrType(string sel="")
{
   return(OrderType());
}
double Bet1326(int group, string symbol, double initial_lots, bool reverse=false)
{  
   int pos=0;
   int total=0;
   double lots=0;
   double profit=0;
   int profit_or_loss=0; // 0 - unknown, 1 - profit, -1 - loss
   
   //-- try to get last lot size from running trades
   total=OrdersTotal();
   for (pos=total-1; pos>=0; pos--)
   {
      if (!OrderSelect(pos, SELECT_BY_POS, MODE_TRADES)) {continue;}
      if (OrderMagicNumber() != MagicStart+group) {continue;}
      if (OrderSymbol() != symbol) {continue;}
      if (TimeCurrent() - OrderOpenTime() < 3) {continue;}
      
      if (lots==0) {
         lots=OrderLots();
      }
      
      profit = OrderClosePrice()-OrderOpenPrice();
      profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
      if (IsOrderTypeSell()) {profit = -1*profit;}
      if (profit == 0) {
         return(lots);
      }
      
      if (profit<0) {profit_or_loss=-1;}
      else {profit_or_loss=1;}
      
      break;
   }
   
   //-- if no running trade was found, search in history trades
   if (lots==0)
   {
      total=OrdersHistoryTotal();
      for (pos=total-1; pos>=0; pos--)
      {
         if(!OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY)) {continue;}
         if (OrderMagicNumber() != MagicStart+group) {continue;}
         if (OrderSymbol() != symbol) {continue;}
         
         if (lots==0) {
            lots=OrderLots();
         }
         
         profit = OrderClosePrice()-OrderOpenPrice();
         profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
         if (IsOrderTypeSell()) {profit = -1*profit;}
         if (profit == 0) {
            return(lots);
         }
         
         if (profit<0) {profit_or_loss=-1;}
         else {profit_or_loss=1;}
         
         break;
      }
   }
   
   //--
   if (initial_lots < MarketInfo(symbol,MODE_MINLOT)) {
      initial_lots = MarketInfo(symbol,MODE_MINLOT);  
   }

   if (lots==0) {lots = initial_lots;}
   else
   {
      if ((reverse==false && profit_or_loss==1) || (reverse==true && profit_or_loss==-1))
      {
         double div = lots/initial_lots;
         
         if (div < 1.5) {lots = initial_lots*3;}
         else if (div < 2.5) {lots = initial_lots*6;}
         else if (div < 3.5) {lots = initial_lots*2;}
         else {lots = initial_lots;}
      }
      else {
         lots = initial_lots;
      }
   }
   
   return lots;
}
double BetDalembert(int group, string symbol, double initial_lots, double reverse=false)
{  
   int pos=0;
   int total=0;
   double lots=0;
   double profit=0;
   int profit_or_loss=0; // 0 - unknown, 1 - profit, -1 - loss
   
   //-- try to get last lot size from running trades
   total=OrdersTotal();
   for (pos=total-1; pos>=0; pos--)
   {
      if (!OrderSelect(pos, SELECT_BY_POS, MODE_TRADES)) {continue;}
      if (OrderMagicNumber() != MagicStart+group) {continue;}
      if (OrderSymbol() != symbol) {continue;}
      if (TimeCurrent() - OrderOpenTime() < 3) {continue;}
      
      if (lots==0) {
         lots=OrderLots();
      }
      
      profit = OrderClosePrice()-OrderOpenPrice();
      profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
      if (IsOrderTypeSell()) {profit = -1*profit;}
      if (profit == 0) {
         return(lots);
      }
      
      if (profit<0) {profit_or_loss=-1;}
      else {profit_or_loss=1;}
      
      break;
   }
   
   //-- if no running trade was found, search in history trades
   if (lots==0)
   {
      total=OrdersHistoryTotal();
      for (pos=total-1; pos>=0; pos--)
      {
         if(!OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY)) {continue;}
         if (OrderMagicNumber() != MagicStart+group) {continue;}
         if (OrderSymbol() != symbol) {continue;}
         
         if (lots==0) {
            lots=OrderLots();
         }
         
         profit = OrderClosePrice()-OrderOpenPrice();
         profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
         if (IsOrderTypeSell()) {profit = -1*profit;}
         if (profit == 0) {
            return(lots);
         }
         
         if (profit<0) {profit_or_loss=-1;}
         else {profit_or_loss=1;}
         
         break;
      }
   }
   
   //--
   if (initial_lots < MarketInfo(symbol,MODE_MINLOT)) {
      initial_lots = MarketInfo(symbol,MODE_MINLOT);  
   }

   if (lots==0) {lots = initial_lots;}
   else
   {
      if ((reverse==0 && profit_or_loss==1) || (reverse==1 && profit_or_loss==-1))
      {
         lots = lots - initial_lots;
         if (lots < initial_lots) {lots = initial_lots;}
      }
      else {
         lots = lots + initial_lots;
      }
   }
   
   return lots;
}
double BetFibonacci(
   int group,
   string symbol,
   double initial_lots
   )
{
   int pos=0;
   int total=0;
   double lots=0;
   double profit=0;
   int profit_or_loss=0; // 0 - unknown, 1 - profit, -1 - loss
   
   //-- try to get last lot size from running trades
   total=OrdersTotal();
   for (pos=total-1; pos>=0; pos--)
   {
      if (!OrderSelect(pos, SELECT_BY_POS, MODE_TRADES)) {continue;}
      if (OrderMagicNumber() != MagicStart+group) {continue;}
      if (OrderSymbol() != symbol) {continue;}
      if (TimeCurrent() - OrderOpenTime() < 3) {continue;}
      
      if (lots==0) {
         lots=OrderLots();
      }
      
      profit = OrderClosePrice()-OrderOpenPrice();
      profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
      if (IsOrderTypeSell()) {profit = -1*profit;}
      if (profit == 0) {
         return(lots);
      }
      
      if (profit<0) {profit_or_loss=-1;}
      else {profit_or_loss=1;}
      
      break;
   }
   
   //-- if no running trade was found, search in history trades
   if (lots==0)
   {
      total=OrdersHistoryTotal();
      for (pos=total-1; pos>=0; pos--)
      {
         if(!OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY)) {continue;}
         if (OrderMagicNumber() != MagicStart+group) {continue;}
         if (OrderSymbol() != symbol) {continue;}
         
         if (lots==0) {
            lots=OrderLots();
         }
         
         profit = OrderClosePrice()-OrderOpenPrice();
         profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
         if (IsOrderTypeSell()) {profit = -1*profit;}
         if (profit == 0) {
            return(lots);
         }
         
         if (profit<0) {profit_or_loss=-1;}
         else {profit_or_loss=1;}
         
         break;
      }
   }

   //--
   if (initial_lots < MarketInfo(symbol,MODE_MINLOT)) {
      initial_lots = MarketInfo(symbol,MODE_MINLOT);  
   }

   if (lots==0) {lots = initial_lots;}
   else
   {  
      int fibo1=1, fibo2=0, fibo3=0, fibo4=0;
      double div = lots/initial_lots;
      
      if (div<=0) {div=1;}

      while(true)
      {
         fibo1=fibo1+fibo2;
         fibo3=fibo2;
         fibo2=fibo1-fibo2;
         fibo4=fibo2-fibo3;
         if (fibo1 > NormalizeDouble(div, 2)) {break;}
      }
      //Print("("+fibo1 + "+" + fibo2+"+"+fibo3+") > "+div);
      if (profit_or_loss==1)
      {
         if (fibo4<=0) {fibo4=1;}
         //Print("Profit "+lots+"*"+fibo4);
         lots=initial_lots*(fibo4);
      }
      else {
         //Print("Loss "+lots+"*"+fibo1+"+"+fibo2);
         lots=initial_lots*(fibo1);
      }
   }
   
   lots=NormalizeDouble(lots, 2);
   return lots;
}
double BetLabouchere(int group, string symbol, double initial_lots, string list_of_numbers, double reverse=false)
{   
   int pos=0;
   int total=0;
   double lots=0;
   double profit=0;
   int profit_or_loss=0; // 0 - unknown, 1 - profit, -1 - loss
   
   //-- try to get last lot size from running trades
   total=OrdersTotal();
   for (pos=total-1; pos>=0; pos--)
   {
      if (!OrderSelect(pos, SELECT_BY_POS, MODE_TRADES)) {continue;}
      if (OrderMagicNumber() != MagicStart+group) {continue;}
      if (OrderSymbol() != symbol) {continue;}
      if (TimeCurrent() - OrderOpenTime() < 3) {continue;}
      
      if (lots==0) {
         lots=OrderLots();
      }
      
      profit = OrderClosePrice()-OrderOpenPrice();
      profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
      if (IsOrderTypeSell()) {profit = -1*profit;}
      if (profit == 0) {
         return(lots);
      }
      
      if (profit<0) {profit_or_loss=-1;}
      else {profit_or_loss=1;}
      
      break;
   }
   
   //-- if no running trade was found, search in history trades
   if (lots==0)
   {
      total=OrdersHistoryTotal();
      for (pos=total-1; pos>=0; pos--)
      {
         if(!OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY)) {continue;}
         if (OrderMagicNumber() != MagicStart+group) {continue;}
         if (OrderSymbol() != symbol) {continue;}
         
         if (lots==0) {
            lots=OrderLots();
         }
         
         profit = OrderClosePrice()-OrderOpenPrice();
         profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
         if (IsOrderTypeSell()) {profit = -1*profit;}
         if (profit == 0) {
            return(lots);
         }

         if (profit<0) {profit_or_loss=-1;}
         else {profit_or_loss=1;}
         
         break;
      }
   }
   
   //-- Labouchere stuff
   static int mem_group[];
   static string mem_list[];
   static int mem_ticket[];
   int start_again=false;
   
   //- get the list of numbers as it is stored in the memory, or store it
   int id=ArraySearch(mem_group, group);
   if (id == -1) {
      start_again=true;
      if (list_of_numbers=="") {list_of_numbers="1";}
      id = ArraySize(mem_group);
      ArrayResize(mem_group, id+1, id+1);
      ArrayResize(mem_list, id+1, id+1);
      ArrayResize(mem_ticket, id+1, id+1);
      mem_group[id]=group;
      mem_list[id]=list_of_numbers;
   }
   
   if (mem_ticket[id]==OrderTicket()) {
      // the last known ticket (mem_ticket[id]) should be different than OderTicket() normally
      // when failed to create a new trade - the last ticket remains the same
      // so we need to reset
      mem_list[id]=list_of_numbers;
   }
   mem_ticket[id]=OrderTicket();
   
   //- now turn the string into integer array
   int list[];
   string listS[];
   StringExplode(",", mem_list[id], listS);
   ArrayResize(list, ArraySize(listS));
   for (int s=0; s<ArraySize(listS); s++) {
      list[s]=StringToInteger(StringTrim(listS[s]));  
   }

   //-- 
   int size = ArraySize(list);

   if (initial_lots < MarketInfo(symbol,MODE_MINLOT)) {
      initial_lots = MarketInfo(symbol,MODE_MINLOT);  
   }

   if (lots==0) {
      start_again=true;
   }
   
   if (start_again==true)
   {
      if (size==1) {
         lots = initial_lots*list[0];
      } else {
         lots = initial_lots*(list[0]+list[size-1]);
      }
   }
   else 
   {
      if ((reverse==0 && profit_or_loss==1) || (reverse==1 && profit_or_loss==-1))
      {
         if (size==1) {
            lots=initial_lots*list[0];
            ArrayResize(list, 0);
         }
         else if (size==2) {
            lots = initial_lots*(list[0]+list[1]);
            ArrayResize(list, 0);
         }
         else if (size>2) {
            lots = initial_lots*(list[0]+list[size-1]);
            // Cancel first and last numbers in our list
            // shift array 1 step left
            for(pos=0; pos<size-1; pos++) {
               list[pos]=list[pos+1];
            }
            ArrayResize(list,ArraySize(list)-2); // remove last 2 elements		
         }
         if (lots < initial_lots) {lots = initial_lots;}
      }
      else {
         if (size>1)
         {
            ArrayResize(list, size+1);
            list[size]=list[0]+list[size-1];
            lots = initial_lots*(list[0]+list[size]);
         } else {
            lots = initial_lots*list[0];
         }
         if (lots < initial_lots) {lots = initial_lots;}
      }

   }
   
   Print("Labouchere (for group "+id+") current list of numbers:"+StringImplode(",", list));
   size=ArraySize(list);
   if (size==0) {
      ArrayStripKey(mem_group, id);
      ArrayStripKey(mem_list, id);
      ArrayStripKey(mem_ticket, id);
   } else {
      mem_list[id]=StringImplode(",", list);
   }

   return lots;
}
double BetMartingale(
   int group,
   string symbol,
   double initial_lots,
   double multiply_on_loss,
   double multiply_on_profit,
   double add_on_loss,
   double add_on_profit,
   int reset_on_loss,
   int reset_on_profit
   )
{
   int pos=0;
	int total=0;
   double lots=0;
   double profit=0;
   int profit_or_loss=0; // 0 - unknown, 1 - profit, -1 - loss
   int in_a_row=0;
   
   //-- try to get last lot size from running trades
   total=OrdersTotal();
   for (pos=total-1; pos>=0; pos--)
   {
      if (!OrderSelect(pos, SELECT_BY_POS, MODE_TRADES)) {continue;}
      if (OrderMagicNumber() != MagicStart+group) {continue;}
      if (OrderSymbol() != symbol) {continue;}
      if (TimeCurrent() - OrderOpenTime() < 3) {continue;}

      if (lots==0) {
         lots=OrderLots();
      }
      
      profit = OrderClosePrice()-OrderOpenPrice();
      profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
      if (IsOrderTypeSell()) {profit = -1*profit;}
      if (profit == 0) {
         return(lots);
      }
      
      if (profit_or_loss == 0)
      {
         
         if (profit<0) {profit_or_loss=-1;}
         else {profit_or_loss=1;}
      }
      else {
              if (profit_or_loss==1 && profit<0) {break;}
         else if (profit_or_loss==-1 && profit>=0) {break;}
      }
      
      in_a_row++;
   }
   
   //-- if no running trade was found, search in history trades
   if (lots==0)
   {
      total=OrdersHistoryTotal();
      for (pos=total-1; pos>=0; pos--)
      {
         if(!OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY)) {continue;}
         if (OrderMagicNumber() != MagicStart+group) {continue;}
         if (OrderSymbol() != symbol) {continue;}
         
         if (lots==0) {
            lots=OrderLots();
         }
         
         profit = OrderClosePrice()-OrderOpenPrice();
         profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
         if (IsOrderTypeSell()) {profit = -1*profit;}
         if (profit == 0) {
            return(lots);
         }
         
         if (profit_or_loss == 0)
         {
            if (profit<0) {profit_or_loss=-1;}
            else {profit_or_loss=1;}
         }
         else {
                 if (profit_or_loss==1 && profit<0) {break;}
            else if (profit_or_loss==-1 && profit>=0) {break;}
         }
         
         in_a_row++;
      }
   }

   //--
   /*
   if (initial_lots < MarketInfo(symbol,MODE_MINLOT)) {
      initial_lots = MarketInfo(symbol,MODE_MINLOT);  
   }*/

   if (lots==0) {lots = initial_lots;}
   else {
      if (profit_or_loss==1)
      {
         if (reset_on_profit>0 && in_a_row >= reset_on_profit) {
            lots=initial_lots;  
         }
         else {
            if (multiply_on_profit<=0) {multiply_on_profit=1;}
            lots=(lots*multiply_on_profit) + add_on_profit;
         }
      }
      else {
         if (reset_on_loss>0 && in_a_row >= reset_on_loss) {
            lots=initial_lots;  
         }
         else {
            if (multiply_on_loss<=0) {multiply_on_loss=1;}
            lots=(lots*multiply_on_loss) + add_on_loss;
         }
      }
   }
   
   return lots;
}
double BetSequence(int group, string symbol, double initial_lots, string sequence_on_loss, string sequence_on_profit, bool reverse=false)
{  
   int pos=0;
   int total=0;
   double lots=0;
   int size=0;
   double profit=0;
   int profit_or_loss=0; // 0 - unknown, 1 - profit, -1 - loss
   
   //-- try to get last lot size from running trades
   total=OrdersTotal();
   for (pos=total-1; pos>=0; pos--)
   {
      if (!OrderSelect(pos, SELECT_BY_POS, MODE_TRADES)) {continue;}
      if (OrderMagicNumber() != MagicStart+group) {continue;}
      if (OrderSymbol() != symbol) {continue;}
      if (TimeCurrent() - OrderOpenTime() < 3) {continue;}
      
      if (lots==0) {
         lots=OrderLots();
      }
      
      profit = OrderClosePrice()-OrderOpenPrice();
      profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
      if (IsOrderTypeSell()) {profit = -1*profit;}
      if (profit == 0) {
         return(lots);
      }
      
      if (profit<0) {profit_or_loss=-1;}
      else {profit_or_loss=1;}
      
      break;
   }
   
   //-- if no running trade was found, search in history trades
   if (lots==0)
   {
      total=OrdersHistoryTotal();
      for (pos=total-1; pos>=0; pos--)
      {
         if(!OrderSelect(pos, SELECT_BY_POS, MODE_HISTORY)) {continue;}
         if (OrderMagicNumber() != MagicStart+group) {continue;}
         if (OrderSymbol() != symbol) {continue;}
         
         if (lots==0) {
            lots=OrderLots();
         }
         
         profit = OrderClosePrice()-OrderOpenPrice();
         profit = NormalizeDouble(profit, SymbolDigits(OrderSymbol()));
         if (IsOrderTypeSell()) {profit = -1*profit;}
         if (profit == 0) {
            return(lots);
         }
         
         if (profit<0) {profit_or_loss=-1;}
         else {profit_or_loss=1;}
         
         break;
      }
   }
   
   //-- Sequence stuff
   static int mem_group[];
   static string mem_list_loss[];
   static string mem_list_profit[];
   static int mem_ticket[];
   
   //- get the list of numbers as it is stored in the memory, or store it
   int id=ArraySearch(mem_group, group);
   if (id == -1)
   {
      if (sequence_on_loss=="") {sequence_on_loss="1";}
      if (sequence_on_profit=="") {sequence_on_profit="1";}
      id = ArraySize(mem_group);
      ArrayResize(mem_group, id+1, id+1);
      ArrayResize(mem_list_loss, id+1, id+1);
      ArrayResize(mem_list_profit, id+1, id+1);
      ArrayResize(mem_ticket, id+1, id+1);
      mem_group[id]        =group;
      mem_list_loss[id]    =sequence_on_loss;
      mem_list_profit[id]  =sequence_on_profit;
   }
   
   bool loss_reset=false;
   bool profit_reset=false;
   if (profit_or_loss==-1 && mem_list_loss[id]=="") {
      loss_reset=true;
      mem_list_profit[id]="";
   }
   if (profit_or_loss==1 && mem_list_profit[id]=="") {
      profit_reset=true;
      mem_list_loss[id]="";
   }
   
   if (profit_or_loss==1 || mem_list_loss[id]=="") {
      mem_list_loss[id]=sequence_on_loss;
      if (loss_reset) {mem_list_loss[id]="1,"+mem_list_loss[id];}
      
   }
   if (profit_or_loss==-1 ||mem_list_profit[id]=="") {
      mem_list_profit[id]=sequence_on_profit;
      if (profit_reset) {mem_list_profit[id]="1,"+mem_list_profit[id];}
   }
   
   if (mem_ticket[id]==OrderTicket()) {
      // the last known ticket (mem_ticket[id]) should be different than OderTicket() normally
      // when failed to create a new trade - the last ticket remains the same
      // so we need to reset
      mem_list_loss[id]=sequence_on_loss;
      mem_list_profit[id]=sequence_on_profit;
   }
   mem_ticket[id]=OrderTicket();
   
   //- now turn the string into integer array
   int s=0;
   int list_loss[];
   int list_profit[];
   string listS[];
   StringExplode(",", mem_list_loss[id], listS);
   ArrayResize(list_loss, ArraySize(listS), ArraySize(listS));
   for (s=0; s<ArraySize(listS); s++) {
      list_loss[s]=(int)StringToInteger(StringTrim(listS[s]));  
   }
   StringExplode(",", mem_list_profit[id], listS);
   ArrayResize(list_profit, ArraySize(listS), ArraySize(listS));
   for (s=0; s<ArraySize(listS); s++) {
      list_profit[s]=(int)StringToInteger(StringTrim(listS[s]));  
   }

   //--
   if (initial_lots < MarketInfo(symbol,MODE_MINLOT)) {
      initial_lots = MarketInfo(symbol,MODE_MINLOT);  
   }

   if (lots==0) {lots = initial_lots;}
   else
   {
      if ((reverse==false && profit_or_loss==1) || (reverse==true && profit_or_loss==-1))
      {
         lots = initial_lots*list_profit[0];
         // shift array 1 step left
         size=ArraySize(list_profit);
         for(pos=0; pos<size-1; pos++) {
            list_profit[pos]=list_profit[pos+1];
         }
         if (size>0) {
            ArrayResize(list_profit, size-1, size-1);
            mem_list_profit[id]=StringImplode(",", list_profit);
         }
         // reset the opposite sequence
         //mem_list_loss[id]="";
      }
      else {
         
         lots = initial_lots*list_loss[0];
         // shift array 1 step left
         size=ArraySize(list_loss);
         for(pos=0; pos<size-1; pos++) {
            list_loss[pos]=list_loss[pos+1];
         }
         if (size>0) {
            ArrayResize(list_loss, size-1, size-1);
            mem_list_loss[id]=StringImplode(",", list_loss);
         }
         // reset the opposite sequence
         //mem_list_profit[id]="";
      }
   }
   
   return lots;
}
int BuyNow(
   string symbol,
   double lots,
   double sll,
   double tpl,
   double slp,
   double tpp,
   double slippage=0,
   int magic=0,
   string comment="",
   color arrowcolor=CLR_NONE,
   int expiration = 0
   )
{
   int ticket=OrderCreate(
      symbol,
      OP_BUY,
      lots,
      0,
      sll,
      tpl,
      slp,
      tpp,
      slippage,
      magic,
      comment,
      arrowcolor,
      expiration
      );
   return(ticket);
}
double ChartEventParameterDouble(int cmd=0,double inp=-1) {static double mem=-1; if(cmd==1){mem=inp;} return(mem);}
double ChartEventParameterLong(int cmd=0,double inp=-1) {static double mem=-1; if(cmd==1){mem=inp;} return(mem);}
string ChartEventParameterString(int cmd=0,string inp="") {static string mem=""; if(cmd==1){mem=inp;} return(mem);}
int ChartEventType(int cmd=0,int inp=-1) {static int mem=-1; if(cmd==1){mem=inp;} return(mem);}
int CheckForTradingError(int error_code=-1, string msg_prefix="")
{
   // return 0 -> no error
   // return 1 -> overcomable error
   // return 2 -> fatal error
   
	if (error_code<0) {
      error_code=GetLastError();  
	}
   
   int retval=0;
   static int tryouts=0;
   
   //-- error check -----------------------------------------------------
   switch(error_code)
   {
      //-- no error
      case 0:
         retval=0;
         break;
      //-- overcomable errors
      case 1: // No error returned
         RefreshRates();
         retval=1;
         break;
      case 4: //ERR_SERVER_BUSY
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         Sleep(1000);
         RefreshRates();
         retval=1;
         break;
      case 6: //ERR_NO_CONNECTION
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         while(!IsConnected()) {Sleep(100);}
         while(IsTradeContextBusy()) {Sleep(50);}
         RefreshRates();
         retval=1;
         break;
      case 128: //ERR_TRADE_TIMEOUT
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         RefreshRates();
         retval=1;
         break;
      case 129: //ERR_INVALID_PRICE
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         while(RefreshRates()==false) {Sleep(1);}
         retval=1;
         break;
      case 130: //ERR_INVALID_STOPS
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
         while(RefreshRates()==false) {Sleep(1);}
         retval=1;
         break;
      case 135: //ERR_PRICE_CHANGED
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
         while(RefreshRates()==false) {Sleep(1);}
         retval=1;
         break;
      case 136: //ERR_OFF_QUOTES
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
         while(RefreshRates()==false) {Sleep(1);}
         retval=1;
         break;
      case 137: //ERR_BROKER_BUSY
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         Sleep(1000);
         retval=1;
         break;
      case 138: //ERR_REQUOTE
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
         while(RefreshRates()==false) {Sleep(1);}
         retval=1;
         break;
      case 142: //This code should be processed in the same way as error 128.
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         RefreshRates();
         retval=1;
         break;
      case 143: //This code should be processed in the same way as error 128.
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         RefreshRates();
         retval=1;
         break;
      /*case 145: //ERR_TRADE_MODIFY_DENIED
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
         while(RefreshRates()==false) {Sleep(1);}
         return(1);
      */
      case 146: //ERR_TRADE_CONTEXT_BUSY
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
         while(IsTradeContextBusy()) {Sleep(50);}
         RefreshRates();
         retval=1;
         break;
      //-- critical errors
      default:
         if (msg_prefix!="") {Print(StringConcatenate(msg_prefix,": ",ErrorMessage(error_code)));}
         retval=2;
         break;
   }

   if (retval==0) {tryouts=0;}
   else if (retval==1) {
      tryouts++;
      if (tryouts>=10) {
         tryouts=0;
         retval=2;
      } else {
         Print("retry #"+tryouts+" of 10");
      }
   }
   
   return(retval);
}
bool CloseTrade(int ticket, double slippage=0, color arrowcolor=CLR_NONE)
{
   bool success=false;
   if (!OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) {return(false);}
   
   while(true)
   {
      //-- wait if needed -----------------------------------------------
      WaitTradeContextIfBusy();
      //-- close --------------------------------------------------------
      success=OrderClose(ticket,attrLots(),attrClosePrice(),slippage*PipValue(attrSymbol()),arrowcolor);
      if (success==true) {
         if (USE_VIRTUAL_STOPS) {
            VirtualStopsDriver("clear",ticket);
         }
         RegisterEvent("trade");
         return(true);
      }
      //-- errors -------------------------------------------------------
      int erraction=CheckForTradingError(GetLastError(), "Closing trade #"+ticket+" error");
      switch(erraction)
      {
         case 0: break;    // no error
         case 1: continue; // overcomable error
         case 2: break;    // fatal error
      }
      break;
   }
   return(false);
}
string CurrentSymbol(string symbol="")
{
   static string memory="";
   if (symbol!="") {memory=symbol;} else
   if (memory=="") {memory=Symbol();}
   return(memory);
}
int CurrentTimeframe(int tf=-1)
{
	static int memory=0;
   if (tf>=0) {memory=tf;}
   return(memory);
}
void DrawSpreadInfo()
{
   static bool allow_draw = true;
   if (allow_draw==false) {return;}
   if (MQLInfoInteger(MQL_TESTER)) {allow_draw=false;} // Allowed to draw only once in testing mode

   static bool passed         = false;
   static double max_spread   = 0;
   static double min_spread   = EMPTY_VALUE;
   static double avg_spread   = 0;
   static double avg_add      = 0;
   static double avg_cnt      = 0;

   double current_spread = (SymbolInfoDouble(Symbol(),SYMBOL_ASK)-SymbolInfoDouble(Symbol(),SYMBOL_BID))/(CustomPoint(Symbol()));
   if (current_spread > max_spread) {max_spread = current_spread;}
   if (current_spread < min_spread) {min_spread = current_spread;}
   
   avg_cnt++;
   avg_add     = avg_add + current_spread;
   avg_spread  = avg_add / avg_cnt;

   int x=0; int y=0;
   string name;

   // create objects
   if (passed == false)
   {
      passed=true;
      
      name="fxd_spread_current_label";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+1);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 18);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "Spread:");
      }
      name="fxd_spread_max_label";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+148);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+17);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrOrangeRed);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "max:");
      }
      name="fxd_spread_avg_label";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+148);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+9);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "avg:");
      }
      name="fxd_spread_min_label";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+148);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrGold);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "min:");
      }
      name="fxd_spread_current";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+93);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 18);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "0");
      }
      name="fxd_spread_max";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+173);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+17);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrOrangeRed);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "0");
      }
      name="fxd_spread_avg";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+173);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+9);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "0");
      }
      name="fxd_spread_min";
      if (ObjectFind(0, name)==-1) {
         ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
         ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+173);
         ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
         ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
         ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
         ObjectSetInteger(0, name, OBJPROP_COLOR, clrGold);
         ObjectSetString(0, name, OBJPROP_FONT, "Arial");
         ObjectSetString(0, name, OBJPROP_TEXT, "min:");
      }
   }
   
   ObjectSetString(0, "fxd_spread_current", OBJPROP_TEXT, DoubleToStr(current_spread,2));
   ObjectSetString(0, "fxd_spread_max", OBJPROP_TEXT, DoubleToStr(max_spread,2));
   ObjectSetString(0, "fxd_spread_avg", OBJPROP_TEXT, DoubleToStr(avg_spread,2));
   ObjectSetString(0, "fxd_spread_min", OBJPROP_TEXT, DoubleToStr(min_spread,2));
}
string DrawStatus(string text="")
{
   static string memory;
   if (text=="") {
      return(memory);
   }
   
   static bool passed = false;
   int x=210; int y=0;
   string name;

   //-- draw the objects once
   if (passed == false)
   {
      passed = true;
      name="fxd_status_title";
      ObjectCreate(0,name, OBJ_LABEL, 0, 0, 0);
      ObjectSetInteger(0,name, OBJPROP_BACK, false);
      ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
      ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
      ObjectSetInteger(0,name, OBJPROP_XDISTANCE, x);
      ObjectSetInteger(0,name, OBJPROP_YDISTANCE, y+17);
      ObjectSetString(0,name, OBJPROP_TEXT, "Status");
      ObjectSetString(0,name, OBJPROP_FONT, "Arial");
      ObjectSetInteger(0,name, OBJPROP_FONTSIZE, 7);
      ObjectSetInteger(0,name, OBJPROP_COLOR, clrGray);
      
      name="fxd_status_text";
      ObjectCreate(0,name, OBJ_LABEL, 0, 0, 0);
      ObjectSetInteger(0,name, OBJPROP_BACK, false);
      ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
      ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
      ObjectSetInteger(0,name, OBJPROP_XDISTANCE, x+2);
      ObjectSetInteger(0,name, OBJPROP_YDISTANCE, y+1);
      ObjectSetString(0,name, OBJPROP_FONT, "Arial");
      ObjectSetInteger(0,name, OBJPROP_FONTSIZE, 12);
      ObjectSetInteger(0,name, OBJPROP_COLOR, clrAqua);
   }

   //-- update the text when needed
   if (text != memory) {
      memory=text;
      ObjectSetString(0,"fxd_status_text", OBJPROP_TEXT, text);
   }
   
   return(text);
}
double DynamicLots(string mode="balance", double value=0, double sl=0, string align="align", double RJFR_initial_lots=0)
{
   double size=0;
   string symbol=GetSymbol();
   double LotStep=MarketInfo(symbol,MODE_LOTSTEP);
   double LotSize=MarketInfo(symbol,MODE_LOTSIZE);
   double MinLots=MarketInfo(symbol,MODE_MINLOT);
   double MaxLots=MarketInfo(symbol,MODE_MAXLOT);
   double TickValue=MarketInfo(symbol,MODE_TICKVALUE);
   double point=MarketInfo(symbol,MODE_POINT);
   double ticksize=MarketInfo(symbol,MODE_TICKSIZE);
   double margin_required=MarketInfo(symbol,MODE_MARGINREQUIRED);
   
   if (mode=="fixed" || mode=="lots")     {size=value;}
   else if (mode=="block-equity")      {size=(value/100)*AccountEquity()/margin_required;}
   else if (mode=="block-balance")     {size=(value/100)*AccountBalance()/margin_required;}
   else if (mode=="block-freemargin")  {size=(value/100)*AccountFreeMargin()/margin_required;}
   else if (mode=="equity")      {size=(value/100)*AccountEquity()/(LotSize*TickValue);}
   else if (mode=="balance")     {size=(value/100)*AccountBalance()/(LotSize*TickValue);}
   else if (mode=="freemargin")  {size=(value/100)*AccountFreeMargin()/(LotSize*TickValue);}
   else if (mode=="equityRisk")     {size=((value/100)*AccountEquity())/(sl*((TickValue/ticksize)*point)*PipValue(symbol));}
   else if (mode=="balanceRisk")    {size=((value/100)*AccountBalance())/(sl*((TickValue/ticksize)*point)*PipValue(symbol));}
   else if (mode=="freemarginRisk") {size=((value/100)*AccountFreeMargin())/(sl*((TickValue/ticksize)*point)*PipValue(symbol));}
   else if (mode=="fixedRisk")   {size=(value)/(sl*((TickValue/ticksize)*point)*PipValue(symbol));}
   else if (mode=="fixedRatio" || mode=="RJFR") {
      
      /////
      // Ryan Jones Fixed Ratio MM static data
      static double RJFR_start_lots=0;
      static double RJFR_delta=0;
      static double RJFR_units=1;
      static double RJFR_target_lower=0;
      static double RJFR_target_upper=0;
      /////
      
      if (RJFR_start_lots<=0) {RJFR_start_lots=value;}
      if (RJFR_start_lots<MinLots) {RJFR_start_lots=MinLots;}
      if (RJFR_delta<=0) {RJFR_delta=sl;}
      if (RJFR_target_upper<=0) {
         RJFR_target_upper=AccountEquity()+(RJFR_units*RJFR_delta);
         Print("Fixed Ratio MM: Units=>",RJFR_units,"; Delta=",RJFR_delta,"; Upper Target Equity=>",RJFR_target_upper);
      }
      if (AccountEquity()>=RJFR_target_upper)
      {
         while(true) {
            Print("Fixed Ratio MM going up to ",(RJFR_start_lots*(RJFR_units+1))," lots: Equity is above Upper Target Equity (",AccountEquity(),">=",RJFR_target_upper,")");
            RJFR_units++;
            RJFR_target_lower=RJFR_target_upper;
            RJFR_target_upper=RJFR_target_upper+(RJFR_units*RJFR_delta);
            Print("Fixed Ratio MM: Units=>",RJFR_units,"; Delta=",RJFR_delta,"; Lower Target Equity=>",RJFR_target_lower,"; Upper Target Equity=>",RJFR_target_upper);
            if (AccountEquity()<RJFR_target_upper) {break;}
         }
      }
      else if (AccountEquity()<=RJFR_target_lower)
      {
         while(true) {
         if (AccountEquity()>RJFR_target_lower) {break;}
            if (RJFR_units>1) {         
               Print("Fixed Ratio MM going down to ",(RJFR_start_lots*(RJFR_units-1))," lots: Equity is below Lower Target Equity | ", AccountEquity()," <= ",RJFR_target_lower,")");
               RJFR_target_upper=RJFR_target_lower;
               RJFR_target_lower=RJFR_target_lower-((RJFR_units-1)*RJFR_delta);
               RJFR_units--;
               Print("Fixed Ratio MM: Units=>",RJFR_units,"; Delta=",RJFR_delta,"; Lower Target Equity=>",RJFR_target_lower,"; Upper Target Equity=>",RJFR_target_upper);
            } else {break;}
         }
      }
      size=RJFR_start_lots*RJFR_units;
   }
   
   size=MathRound(size/LotStep)*LotStep;
   
   static bool alert_min_lots=false;
   if (size<MinLots && alert_min_lots==false) {
      alert_min_lots=true;
      Alert("You want to trade ",size," lot, but your broker's minimum is ",MinLots," lot. The trade/order will continue with ",MinLots," lot instead of ",size," lot. The same rule will be applied for next trades/orders with desired lot size lower than the minimum. You will not see this message again until you restart the program.");
   }
   
   if (align=="align") {
      if (size<MinLots) {size=MinLots;}
      if (size>MaxLots) {size=MaxLots;}
   }
   
   return (size);
}
double e_attrClosePrice(bool set=false, double inp=-1) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
string e_attrComment(bool set=false, string inp="") {static string mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
double e_attrCommission(bool set=false, double inp=0) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
datetime e_attrExpiration(bool set=false, datetime inp=0) {static datetime mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
double e_attrLots(bool set=false, double inp=-1) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
int e_attrMagicNumber(bool set=false, int inp=-1) {static int mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
double e_attrOpenPrice(bool set=false, double inp=-1) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
datetime e_attrOpenTime(bool set=false, datetime inp=-1) {static datetime mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
double e_attrProfit(bool set=false, double inp=0) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
double e_attrStopLoss(bool set=false, double inp=-1) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
double e_attrSwap(bool set=false, double inp=0) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
string e_attrSymbol(bool set=false, string inp="") {static string mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
double e_attrTakeProfit(bool set=false, double inp=-1) {static double mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
int e_attrTicket(bool set=false, int inp=-1) {static int mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
int e_attrType(bool set=false, int inp=-1) {static int mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
string e_Reason(bool set=false, string inp="") {
   static string mem[];
   int queue=OnTradeQueue()-1;
   if(set==true){
      ArrayResize(mem,queue+1);
      mem[queue]=inp;
   }
   return(mem[queue]);
}
string e_ReasonDetail(bool set=false, string inp="") {static string mem[];int queue=OnTradeQueue()-1;if(set==true){ArrayResize(mem,queue+1);mem[queue]=inp;}return(mem[queue]);}
string ErrorMessage(int error_code=-1)
{
   if (error_code<0) {error_code=GetLastError();}
   string error_string="";

   switch(error_code)
     {
      //-- codes returned from trade server
      case 0:   return("");
      case 1:   error_string="No error returned"; break;
      case 2:   error_string="Common error"; break;
      case 3:   error_string="Invalid trade parameters"; break;
      case 4:   error_string="Trade server is busy"; break;
      case 5:   error_string="Old version of the client terminal"; break;
      case 6:   error_string="No connection with trade server"; break;
      case 7:   error_string="Not enough rights"; break;
      case 8:   error_string="Too frequent requests"; break;
      case 9:   error_string="Malfunctional trade operation (never returned error)"; break;
      case 64:  error_string="Account disabled"; break;
      case 65:  error_string="Invalid account"; break;
      case 128: error_string="Trade timeout"; break;
      case 129: error_string="Invalid price"; break;
      case 130: error_string="Invalid Sl or TP"; break;
      case 131: error_string="Invalid trade volume"; break;
      case 132: error_string="Market is closed"; break;
      case 133: error_string="Trade is disabled"; break;
      case 134: error_string="Not enough money"; break;
      case 135: error_string="Price changed"; break;
      case 136: error_string="Off quotes"; break;
      case 137: error_string="Broker is busy (never returned error)"; break;
      case 138: error_string="Requote"; break;
      case 139: error_string="Order is locked"; break;
      case 140: error_string="Only long trades allowed"; break;
      case 141: error_string="Too many requests"; break;
      case 145: error_string="Modification denied because order too close to market"; break;
      case 146: error_string="Trade context is busy"; break;
      case 147: error_string="Expirations are denied by broker"; break;
      case 148: error_string="Amount of open and pending orders has reached the limit"; break;
      case 149: error_string="Hedging is prohibited"; break;
      case 150: error_string="Prohibited by FIFO rules"; break;
      //-- mql4 errors
      case 4000: error_string="No error"; break;
      case 4001: error_string="Wrong function pointer"; break;
      case 4002: error_string="Array index is out of range"; break;
      case 4003: error_string="No memory for function call stack"; break;
      case 4004: error_string="Recursive stack overflow"; break;
      case 4005: error_string="Not enough stack for parameter"; break;
      case 4006: error_string="No memory for parameter string"; break;
      case 4007: error_string="No memory for temp string"; break;
      case 4008: error_string="Not initialized string"; break;
      case 4009: error_string="Not initialized string in array"; break;
      case 4010: error_string="No memory for array string"; break;
      case 4011: error_string="Too long string"; break;
      case 4012: error_string="Remainder from zero divide"; break;
      case 4013: error_string="Zero divide"; break;
      case 4014: error_string="Unknown command"; break;
      case 4015: error_string="Wrong jump"; break;
      case 4016: error_string="Not initialized array"; break;
      case 4017: error_string="dll calls are not allowed"; break;
      case 4018: error_string="Cannot load library"; break;
      case 4019: error_string="Cannot call function"; break;
      case 4020: error_string="Expert function calls are not allowed"; break;
      case 4021: error_string="Not enough memory for temp string returned from function"; break;
      case 4022: error_string="System is busy"; break;
      case 4050: error_string="Invalid function parameters count"; break;
      case 4051: error_string="Invalid function parameter value"; break;
      case 4052: error_string="String function internal error"; break;
      case 4053: error_string="Some array error"; break;
      case 4054: error_string="Incorrect series array using"; break;
      case 4055: error_string="Custom indicator error"; break;
      case 4056: error_string="Arrays are incompatible"; break;
      case 4057: error_string="Global variables processing error"; break;
      case 4058: error_string="Global variable not found"; break;
      case 4059: error_string="Function is not allowed in testing mode"; break;
      case 4060: error_string="Function is not confirmed"; break;
      case 4061: error_string="Send mail error"; break;
      case 4062: error_string="String parameter expected"; break;
      case 4063: error_string="Integer parameter expected"; break;
      case 4064: error_string="Double parameter expected"; break;
      case 4065: error_string="Array as parameter expected"; break;
      case 4066: error_string="Requested history data in update state"; break;
      case 4099: error_string="End of file"; break;
      case 4100: error_string="Some file error"; break;
      case 4101: error_string="Wrong file name"; break;
      case 4102: error_string="Too many opened files"; break;
      case 4103: error_string="Cannot open file"; break;
      case 4104: error_string="Incompatible access to a file"; break;
      case 4105: error_string="No order selected"; break;
      case 4106: error_string="Unknown symbol"; break;
      case 4107: error_string="Invalid price parameter for trade function"; break;
      case 4108: error_string="Invalid ticket"; break;
      case 4109: error_string="Trade is not allowed in the expert properties"; break;
      case 4110: error_string="Longs are not allowed in the expert properties"; break;
      case 4111: error_string="Shorts are not allowed in the expert properties"; break;
      case 4200: error_string="Object is already exist"; break;
      case 4201: error_string="Unknown object property"; break;
      case 4202: error_string="Object is not exist"; break;
      case 4203: error_string="Unknown object type"; break;
      case 4204: error_string="No object name"; break;
      case 4205: error_string="Object coordinates error"; break;
      case 4206: error_string="No specified subwindow"; break;
      case 4207: error_string="Some error in object function"; break;
      default:   error_string="Unknown error";
     }

   //if (error_code>0) {Print("("+error_code+") "+error_string);}
   error_string=StringConcatenate(error_string," ("+error_code+")");
   return(error_string);
}
void ExpirationDriver()
{
   static int last_checked_ticket;
   static int db_tickets[];
   static int db_expirations[];

   static int total; total   = OrdersTotal();
   static int size;  size    = 0;
   static int do_reset; do_reset=false;
   static string print;
   static int i;
   
   //-- check expirations and close trades
   size = ArraySize(db_tickets);
   if (size>0)
   {
      if (total==0) {
         ArrayResize(db_tickets, 0);
         ArrayResize(db_expirations, 0);
      }
      else
      {
         for (i=0; i<size; i++)
         {
            WaitTradeContextIfBusy();
            if (!OrderSelect(db_tickets[i],SELECT_BY_TICKET, MODE_TRADES)) {continue;}
            if (OrderSymbol() != Symbol()) {continue;}
            
            if (TimeCurrent() >= OrderOpenTime()+db_expirations[i]) {
               
               //-- trying to skip conflicts with the same functionality running from neighbour EA
               WaitTradeContextIfBusy();
               if (!OrderSelect(db_tickets[i],SELECT_BY_TICKET, MODE_TRADES)) {continue;}
               if (OrderCloseTime()>0) {continue;}
               
               //-- closing the trade
               if (CloseTrade(OrderTicket())) 
               {
                  print = "#"+(string)OrderTicket()+" was closed due to expiration";
                  Print(print);
                  last_checked_ticket=0;
                  do_reset = true;
                  total    = OrdersTotal();
               }
            }
         }
      }
   }
   
   //-- check the ticket of the newest trade
   if (do_reset==false && total>0)
   {
      if (OrderSelect(total-1,SELECT_BY_POS)) {
         if (OrderTicket()!=last_checked_ticket) {
            do_reset = true;
         }
      }
   }

   //-- rebuild the database of trades with expirations
   if (do_reset==true)
   {
      static string comment;
      ArrayResize(db_tickets, 0);
      ArrayResize(db_expirations, 0);
      for (int pos=0; pos<total; pos++)
      {
         if (!OrderSelect(pos,SELECT_BY_POS)) {continue;}
         last_checked_ticket = OrderTicket();

         comment = OrderComment();
         int exp_pos_begin = StringFind(comment, "[exp:");
         if (exp_pos_begin >= 0)
         {
            exp_pos_begin = exp_pos_begin+5;
            int exp_pos_end = StringFind(comment, "]", exp_pos_begin);
            if (exp_pos_end == -1) {continue;}
            
            size = ArraySize(db_tickets);
            ArrayResize(db_tickets, size+1);
            ArrayResize(db_expirations, size+1);
            db_tickets[size]     = OrderTicket();
            db_expirations[size] = StringToInteger(StringSubstr(comment, exp_pos_begin, exp_pos_end));
         }
      }
   }
}
datetime ExpirationTime(string mode="GTC",int days=0, int hours=0, int minutes=0, datetime custom=0)
{
	datetime expiration=TimeCurrent();
   if (mode=="GTC" || mode=="")   {expiration=0;}
   else if (mode=="today") {expiration=StrToTime(TimeYear(TimeCurrent())+"."+TimeMonth(TimeCurrent())+"."+TimeDay(TimeCurrent()))+86400;}
   else if (mode=="specified") {
      expiration=0;
      if ((days + hours + minutes)>0) {
         expiration=TimeCurrent()+(86400*days)+(3600*hours)+(60*minutes);
      }
   }
   else
   {
      if (custom <= TimeCurrent()) {
         if (custom < 31557600) {
            custom = TimeCurrent()+custom;
         }
         else {
            custom=0;
         }
      }
      expiration = custom;
   }
   return(expiration);
}
bool FilterOrderBy(string _group_mode="all", string _group="0", string _market_mode="all", string _market="", string _BuysOrSells="both", string _LimitsOrStops="both", int _TradesOrders=0)
{
   // TradesOrders=0 - trades only
   // TradesOrders=1 - orders only
   // TradesOrders=2 - trades and orders

   //-- db
   static string market0="-";
   static string markets[];
   static int markets_size=0;
   
   static string group0="-";
   static string groups[];
   static int groups_size=0;
   
   //-- local variables
   static bool type_pass; type_pass = false;
   static bool market_pass; market_pass = false;
   static bool group_pass; group_pass = false;
   
   static int i;
   static int type;
   
   //-- get
   static string group_mode;     group_mode = _group_mode;
   static string group;          group = _group;
   static string market_mode;    market_mode = _market_mode;
   static string market;         market = _market;
   static string BuysOrSells;    BuysOrSells = _BuysOrSells;
   static string LimitsOrStops;  LimitsOrStops = _LimitsOrStops;
   static int TradesOrders;      TradesOrders = _TradesOrders;
   
   // Trades
   type=OrderType();
   if (TradesOrders==0)
   {
      if (
            (BuysOrSells=="both"  && (type==OP_BUY || type==OP_SELL))
         || (BuysOrSells=="buys"  && type==OP_BUY)
         || (BuysOrSells=="sells" && type==OP_SELL)
         
         )
      {
         type_pass = true;
      }
   }
   // Pending orders
   else if (TradesOrders==1)
   {
      if (
            ((BuysOrSells=="buys" || BuysOrSells=="both") && (type==OP_BUYLIMIT || type==OP_BUYSTOP))
         || ((BuysOrSells=="sells" || BuysOrSells=="both") && (type==OP_SELLLIMIT || type==OP_SELLSTOP))
         )
      {
         if (
               ((LimitsOrStops=="stops" || LimitsOrStops=="both") && (type==OP_BUYSTOP || type==OP_SELLSTOP))
            || ((LimitsOrStops=="limits" || LimitsOrStops=="both") && (type==OP_BUYLIMIT || type==OP_SELLLIMIT))               
            )
         {
            type_pass = true;
         }
      }
   }
   //-- Trades and orders --------------------------------------------
   else
   {
      if (
            (BuysOrSells=="both")
         || (BuysOrSells=="buys"  && (type==OP_BUY || type==OP_BUYLIMIT || type==OP_BUYSTOP))
         || (BuysOrSells=="sells" && (type==OP_SELL || type==OP_SELLLIMIT || type==OP_SELLSTOP))
         )
      {
         type_pass = true;
      }
   }
   if (type_pass == false) {return false;}

   //-- check group
   if (group_mode=="group")
   {
      if (group0!=group)
      {
         group0=group;
         StringExplode(",",group,groups);
         groups_size = ArraySize(groups);
         for(i=0; i<groups_size; i++)
         {
            groups[i]=StringTrimRight(groups[i]);
            groups[i]=StringTrimLeft(groups[i]);
            if (groups[i]=="") {groups[i]="0";}
         }
      }
      for(i=0; i<groups_size; i++)
      {
         if (OrderMagicNumber()==(MagicStart+(int)groups[i]))
         {
            group_pass=true;
            break;
         }
      }
   }
   else if (group_mode=="all" || (group_mode=="manual" && OrderMagicNumber()==0)) {
      group_pass = true;  
   }
   if (group_pass == false) {return false;}
   
   // check market
   if (market_mode=="all") {
      market_pass=true;
      
   }
   else {
      if (market0!=market)
      {
         market0=market;
         if (market=="")
         {
            markets_size = 1;
            ArrayResize(markets,1);
            markets[0]=Symbol();
         }
         else
         {
            StringExplode(",", market,markets);
            markets_size = ArraySize(markets);
            for(i=0; i<markets_size; i++)
            {
               markets[i]=StringTrimRight(markets[i]);
               markets[i]=StringTrimLeft(markets[i]);
               if (markets[i]=="") {markets[i]=Symbol();}
            }
         }
      }
      for(i=0; i<markets_size; i++) {
         if (OrderSymbol()==markets[i]) {
            market_pass = true;
            break;
         }
      }
   }
   if (market_pass == false) {return false;}
   
   return true;
}
string GetSymbol(string symbol="")
{
   static string memory="";
   if (symbol=="") {
      if (memory=="") {memory=Symbol();}
   }
   else {memory=symbol;}
   return(memory);
}
bool InArray(double &array[], double value)
{
   bool founded=false;
   int size=ArraySize(array);
   for (int i=0; i<size; i++) {
      if (array[i]==value) {founded=true; break;}  
   }
   return (founded);
}
bool InArray(int &array[], int value)
{
   bool founded=false;
   int size=ArraySize(array);
   for (int i=0; i<size; i++) {
      if (array[i]==value) {founded=true; break;}  
   }
   return (founded);
}
bool InArray(string &array[], string value)
{
   bool founded=false;
   int size=ArraySize(array);
   for (int i=0; i<size; i++) {
      if (array[i]==value) {founded=true; break;}  
   }
   return (founded);
}
int IndicatorMoreShift(bool set=false, int shift=0)
{
	static int mem;
   if (set==true) {mem=shift;}
   else {
      int return_val=mem; mem=0; // reset
      return(return_val);
   }
   return(mem);
}
bool IsOrderTypeSell() {
   if (
   OrderType()==OP_SELL
   ||
   OrderType()==OP_SELLSTOP
   ||
   OrderType()==OP_SELLLIMIT
   ) {return(true);}
   return(false);
}
bool ModifyOrder(
   int ticket,
   double op,
   double sll=0,
   double tpl=0,
   double slp=0,
   double tpp=0,
   datetime exp=0,
   color clr=CLR_NONE,
   bool ontrade_event=true)
{
//-----------------------------------------------------------------------
   int bs=1;
   if (
         OrderType()==OP_SELL
      || OrderType()==OP_SELLSTOP
      || OrderType()==OP_SELLLIMIT
      )
   {bs=-1;} // Positive when Buy, negative when Sell

   while(true)
   {
      int time0=GetTickCount();
      
      WaitTradeContextIfBusy();
      
      if (!OrderSelect(ticket,SELECT_BY_TICKET)) {
         return(false);
      }
      
      string symbol     =OrderSymbol();
      int type          =OrderType();
      double ask        =MarketInfo(symbol,MODE_ASK);
      double bid        =MarketInfo(symbol,MODE_BID);
      double digits     =MarketInfo(symbol,MODE_DIGITS);
      double point      =MarketInfo(symbol,MODE_POINT);
      
      if (OrderType()<2) {op=OrderOpenPrice();} else {op=NormalizeDouble(op,digits);}
      sll=NormalizeDouble(sll,digits);
      tpl=NormalizeDouble(tpl,digits);
      if (op<0 || op>=EMPTY_VALUE)  {break;}
      if (sll<0) {break;}
      if (slp<0) {break;}
      if (tpl<0) {break;}
      if (tpp<0) {break;}
      
      //-- SL and TP ----------------------------------------------------
      double sl=0, tp=0, vsl=0, vtp=0;
      sl=AlignStopLoss(symbol, type, op, sll, slp);
      if (sl<0) {break;}
      tp=AlignTakeProfit(symbol, type, op, tpl, tpp);
      if (tp<0) {break;}
      
      if (USE_VIRTUAL_STOPS)
      {
         //-- virtual SL and TP --------------------------------------------
         vsl=sl;
         vtp=tp;
         sl=0; tp=0;
      
         double askbid=ask;
         if (bs<0) {askbid=bid;}
         
         if (vsl>0 || USE_EMERGENCY_STOPS=="always") {
            if (EMERGENCY_STOPS_REL>0 || EMERGENCY_STOPS_ADD>0)
            {
               sl=vsl-EMERGENCY_STOPS_REL*MathAbs(askbid-vsl)*bs;
               if (sl<=0) {sl=askbid;}
               sl=sl-toDigits(EMERGENCY_STOPS_ADD,symbol)*bs;
            }
         }
         if (vtp>0 || USE_EMERGENCY_STOPS=="always") {
            if (EMERGENCY_STOPS_REL>0 || EMERGENCY_STOPS_ADD>0)
            {
               tp=vtp+EMERGENCY_STOPS_REL*MathAbs(vtp-askbid)*bs;
               if (tp<=0) {tp=askbid;}
               tp=tp+toDigits(EMERGENCY_STOPS_ADD,symbol)*bs;
            }
         }
         vsl=NormalizeDouble(vsl,digits);
         vtp=NormalizeDouble(vtp,digits);
      }
      sl=NormalizeDouble(sl,digits);
      tp=NormalizeDouble(tp,digits);

      //-- modify -------------------------------------------------------
      if (USE_VIRTUAL_STOPS) {
         if (vsl!=attrStopLoss() || vtp!=attrTakeProfit()) {
            VirtualStopsDriver("set", ticket, vsl, vtp, toPips(MathAbs(op-vsl), symbol), toPips(MathAbs(vtp-op), symbol));
         }
         int error=GetLastError();
      }
      bool success=false;
      //Print(op+"!=+"+NormalizeDouble(OrderOpenPrice(),digits));
      if (
            (OrderType()>1 && op!=NormalizeDouble(OrderOpenPrice(),digits))
         || sl!=NormalizeDouble(OrderStopLoss(),digits)
         || tp!=NormalizeDouble(OrderTakeProfit(),digits)
         || exp!=OrderExpiration()
      ) {
         success=OrderModify(ticket,op,sl,tp,exp,clr);
      }
         
      //-- error check --------------------------------------------------
      int erraction=CheckForTradingError(GetLastError(), "Modify error");
      switch(erraction)
      {
         case 0: break;    // no error
         case 1: continue; // overcomable error
         case 2: break;    // fatal error
      }
      
      //-- finish work --------------------------------------------------
      if (success==true) {
         if (!IsTesting() && !IsVisualMode()) Print("Operation details: Speed "+(GetTickCount()-time0)+" ms");
         if (ontrade_event == true)
         {
            OrderModified(ticket);
            RegisterEvent("trade");
         }
         if (OrderSelect(ticket,SELECT_BY_TICKET)) {}
         return(true);
      }
      
      break;
   }

   return(false);
}
bool OnTimerSet(double seconds)
{
   if (FXD_ONTIMER_TAKEN)
   {
      if (seconds<=0) {
         FXD_ONTIMER_TAKEN_IN_MILLISECONDS = false;
         FXD_ONTIMER_TAKEN_TIME = 0;
      }
      else if (seconds < 1) {
         FXD_ONTIMER_TAKEN_IN_MILLISECONDS = true;
         FXD_ONTIMER_TAKEN_TIME = seconds*1000; 
      }
      else {
         FXD_ONTIMER_TAKEN_IN_MILLISECONDS = false;
         FXD_ONTIMER_TAKEN_TIME = seconds;
      }
      
      return true;
   }

   if (seconds<=0) {
      EventKillTimer();
   }
   else if (seconds < 1) {
      return (EventSetMillisecondTimer((int)(seconds*1000)));  
   }
   else {
      return (EventSetTimer((int)seconds));
   }
   
   return true;
}
void OnTradeListener()
{
   if (!ENABLE_EVENT_TRADE) {return;}

   int i=-1, j=-1, k=-1; int ti=-1; int ty=-1;
   int size=-1;
   static int start_time=-1;
  
   int pos=0;
   
   if (start_time==-1) {start_time=TimeCurrent();}

   string e_reason="";
   string e_detail="";
   
   ///////
   // TRADES AND ORDERS
   int tickets_now[]; ArrayResize(tickets_now,0);
   int tn=0;
   static int    memory_ti[];
   static int    memory_ty[];
   static double memory_sl[];
   static double memory_tp[];
   static double memory_vl[];
   static bool loaded=false;
   
   int total=OrdersTotal();
   
   // initial fill of the local DB
   if (loaded==false)
   {
      loaded=true;
      for (pos=total-1; pos>=0; pos--)
      {
         if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES))
         {
            ArrayResize(memory_ti,tn+1);
            ArrayResize(memory_ty,tn+1);
            ArrayResize(memory_sl,tn+1);
            ArrayResize(memory_tp,tn+1);
            ArrayResize(memory_vl,tn+1);
            memory_ti[tn]=OrderTicket();
            memory_ty[tn]=OrderType();
            memory_sl[tn]=attrStopLoss();
            memory_tp[tn]=attrTakeProfit();
            memory_vl[tn]=OrderLots();
            tn++;
         }
      }
      return;
   }
   tn=0;
   
   bool pending_opens=false;
   
   for (pos=total-1; pos>=0; pos--)
   {
      if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES))
      {
         ArrayResize(tickets_now,tn+1);
         tickets_now[tn]=OrderTicket();
         tn++;
         
         // Trades and Orders
         i=-1; ti=-1; ty=-1; size=ArraySize(memory_ti);
         
         if (size>0)
         {
           for (i=0; i<size; i++)
           {
              if (memory_ti[i]==OrderTicket())
              {
                 if (memory_ty[i]==OrderType()) {
                    ty=OrderType();
                  }
                  else {
                     pending_opens=true;
                  }
                  ti=OrderTicket(); break;
              }
           }
         }

         // Order become a trade
         if (ti>0 && ty<0)
         {
            memory_ti[i]=OrderTicket();
            memory_ty[i]=OrderType();
           
            memory_sl[i]=attrStopLoss();
            memory_tp[i]=attrTakeProfit();
            memory_vl[i]=OrderLots();
            e_reason="new";
            e_detail="";
            break;
         }

         // New trade/order opened
         else if (ti<0 && ty<0)
         {
            ArrayResize(memory_ti,size+1); memory_ti[size]=OrderTicket();
            ArrayResize(memory_ty,size+1); memory_ty[size]=OrderType();
            ArrayResize(memory_sl,size+1); memory_sl[size]=attrStopLoss();
            ArrayResize(memory_tp,size+1); memory_tp[size]=attrTakeProfit();
            ArrayResize(memory_vl,size+1); memory_vl[size]=OrderLots();
            e_reason="new";
            e_detail="";
            break;
         }
         
         // Check for Lots, SL or TP modification
         else if (ty>=0 && i>-1) {
            if (memory_vl[i]!=OrderLots())
            {
               memory_vl[i]=OrderLots();
               e_reason="modify";
               e_detail="lots";
               break;
            }
            else {
               if (memory_sl[i]!=attrStopLoss())   {memory_sl[i]=attrStopLoss(); e_reason="modify"; e_detail="sl"; break;}
               if (memory_tp[i]!=attrTakeProfit()) {memory_tp[i]=attrTakeProfit(); e_reason="modify"; if (e_detail=="sl") {e_detail="sltp";} else {e_detail="tp";} break;}
            }
         }
      }
   }
   
   // Check for closed orders/trades
   bool missing=true;
   if (e_reason=="" && pending_opens==false && ArraySize(tickets_now)<ArraySize(memory_ti))
   {
      for(i=ArraySize(memory_ti)-1; i>=0; i--) { // for each ticket in the memory...
         for(j=0; j<=ArraySize(tickets_now); j++) { // check if trade exists now
            if (memory_ti[i]==tickets_now[j]) {missing=false; break;}
         }
         if (missing==true) {
            if (OrderSelect(memory_ti[i],SELECT_BY_TICKET))
            {
               // This can happen more than once
               ArrayStripKey(memory_ti,i);
               ArrayStripKey(memory_ty,i);
               ArrayStripKey(memory_sl,i);
               ArrayStripKey(memory_tp,i);
               ArrayStripKey(memory_vl,i);
               
               e_reason="closed";
               e_detail="";
               break;
            }
         }
         missing=true;
      }
   }
   // TRADES AND ORDERS
   ///////
   
   if (e_reason!="") {
      UpdateEventValues(e_reason,e_detail);
      EventTrade();
      OnTradeListener();
      if (USE_VIRTUAL_STOPS && e_reason=="closed") {
         ObjectDelete("#"+OrderTicket()+" sl");
         ObjectDelete("#"+OrderTicket()+" tp");
      }
      return;
   }
}
int OnTradeQueue(int queue=0)
{
   static int mem=0;
   mem=mem+queue;
   return(mem);
}
int OrderCreate(
   string symbol="",
   int    type=OP_BUY,
   double lots=0,
   double op=0,
   double sll=0, // SL level
   double tpl=0, // TO level
   double slp=0, // SL adjust in points
   double tpp=0, // TP adjust in points
   double slippage=0,
   int    magic=0,
   string comment="",
   color  arrowcolor=CLR_NONE,
   datetime expiration=0
   )
{
   int time0=GetTickCount();
   
   int ticket=-1;
   int bs=1;
   if (
         type==OP_SELL
      || type==OP_SELLSTOP
      || type==OP_SELLLIMIT
      ) {bs=-1;} // Positive when Buy, negative when Sell
   
   if (symbol=="") {symbol=Symbol();}

   lots=AlignLots(lots);

   //-- attempt to send trade/order -------------------------------------
   while(true)
   {
      //Print(sll+" "+tpl+" "+slp+" "+tpp);
      WaitTradeContextIfBusy();
      
      static bool not_allowed_message = false;
      if (!MQLInfoInteger(MQL_TESTER) && !MarketInfo(symbol, MODE_TRADEALLOWED)) {
         if (not_allowed_message == false) {
            Print("Market ("+symbol+") is closed");
         }
         not_allowed_message = true;
         return(false);
      }
      not_allowed_message = false;
      
      int digits     =MarketInfo(symbol,MODE_DIGITS);
      double ask     =MarketInfo(symbol,MODE_ASK);
      double bid     =MarketInfo(symbol,MODE_BID);
      double point   =MarketInfo(symbol,MODE_POINT);
      
      //- not enough money check: fix maximum possible lot by margin required, or quit
      if (type==OP_BUY || type==OP_SELL)
      {
         double LotStep=MarketInfo(symbol,MODE_LOTSTEP);
         double MinLots=MarketInfo(symbol,MODE_MINLOT);
         double margin_required=MarketInfo(symbol,MODE_MARGINREQUIRED);
         static bool not_enough_message = false;
         
         if (margin_required != 0)
         {
            double max_size_by_margin = AccountFreeMargin()/margin_required;
         
            if (lots > max_size_by_margin) {
               double size_old = lots;
               lots = max_size_by_margin;
               if (lots<MinLots)
               {
                  if (not_enough_message==false) {
                     Print("Not enough money to trade :( The robot is still working, waiting for some funds to appear...");
                  }
                  not_enough_message = true;
                  return(false);
               }
               else
               {
                  lots = MathFloor(lots/LotStep)*LotStep;
                  Print("Not enough money to trade "+DoubleToString(size_old, 2)+", the volume to trade will be the maximum possible of "+DoubleToString(lots, 2));
               }
            }
         }
         not_enough_message = false;
      }
      
      //- expiration for trades
      if (type==OP_BUY || type==OP_SELL)
      {
         if (expiration > 0)
         {
            //- convert UNIX to seconds
            if (expiration > TimeCurrent()-100) {
               expiration = expiration - TimeCurrent();
            }
            
            //- bo broker?
            if (StringLen(symbol)>6 + StringSubstr(symbol, StringLen(symbol)-2=="bo")) {
               comment = "BO exp:"+expiration;
            }
            else {
               string expiration_str   = "[exp:"+IntegerToString(expiration)+"]";
               int expiration_len      = StringLen(expiration_str);
               int comment_len         = StringLen(comment);
               if (comment_len > (27-expiration_len))
               {
                  comment = StringSubstr(comment, 0, (27-expiration_len));
               }
               comment = comment + expiration_str;
            }
         }
      }

      if (type==OP_BUY || type==OP_SELL)
      {
         op=ask;
         if (bs<0) {
           op=bid;
         }
      }
      op=NormalizeDouble(op, digits);
      sll=NormalizeDouble(sll,digits);
      tpl=NormalizeDouble(tpl,digits);
      if (op<0 || op>=EMPTY_VALUE)  {break;}
      if (sll<0) {break;}
      if (slp<0) {break;}
      if (tpl<0) {break;}
      if (tpp<0) {break;}

      //-- SL and TP ----------------------------------------------------
      double sl=0, tp=0, vsl=0, vtp=0;
      
      sl=AlignStopLoss(symbol, type, op, NormalizeDouble(sll,digits), slp);
      if (sl<0) {break;}
      tp=AlignTakeProfit(symbol, type, op, NormalizeDouble(tpl,digits), tpp);
      if (tp<0) {break;}
      
      if (USE_VIRTUAL_STOPS)
      {
         //-- virtual SL and TP --------------------------------------------
         vsl=sl;
         vtp=tp;
         sl=0; tp=0;
         
         double askbid=ask;
         if (bs<0) {askbid=bid;}
         
         if (vsl>0 || USE_EMERGENCY_STOPS=="always") {
            if (EMERGENCY_STOPS_REL>0 || EMERGENCY_STOPS_ADD>0)
            {
               sl=vsl-EMERGENCY_STOPS_REL*MathAbs(askbid-vsl)*bs;
               if (sl<=0) {sl=askbid;}
               sl=sl-toDigits(EMERGENCY_STOPS_ADD,symbol)*bs;
            }
         }
         if (vtp>0 || USE_EMERGENCY_STOPS=="always") {
            if (EMERGENCY_STOPS_REL>0 || EMERGENCY_STOPS_ADD>0)
            {
               tp=vtp+EMERGENCY_STOPS_REL*MathAbs(vtp-askbid)*bs;
               if (tp<=0) {tp=askbid;}
               tp=tp+toDigits(EMERGENCY_STOPS_ADD,symbol)*bs;
            }
         }
         vsl=NormalizeDouble(vsl,digits);
         vtp=NormalizeDouble(vtp,digits);
      }
      sl=NormalizeDouble(sl,digits);
      tp=NormalizeDouble(tp,digits);

      //-- fix expiration for pending orders ----------------------------
      if (expiration>0 && type>OP_SELL) {
         if ((expiration-TimeCurrent())<(11*60)) {
            Print("Expiration time cannot be less than 11 minutes, so it was automatically modified to 11 minutes.");
            expiration=TimeCurrent()+(11*60);
         }
      }

      //-- send ---------------------------------------------------------
      ResetLastError();
      ticket=OrderSend(symbol,type,lots,op,slippage*PipValue(symbol),sl,tp,comment,magic,expiration,arrowcolor);

      //-- error check --------------------------------------------------
      string msg_prefix="New trade error";
      if (type>OP_SELL) {msg_prefix="New order error";}
      int erraction=CheckForTradingError(GetLastError(), msg_prefix);
      switch(erraction)
      {
         case 0: break;    // no error
         case 1: continue; // overcomable error
         case 2: break;    // fatal error
      }
      
      //-- finish work --------------------------------------------------
      if (ticket>0) {
         if (USE_VIRTUAL_STOPS) {
            VirtualStopsDriver("set", ticket, vsl, vtp, toPips(MathAbs(op-vsl), symbol), toPips(MathAbs(vtp-op), symbol));
         }
         
         //-- show some info
         double slip=0;
         if (OrderSelect(ticket,SELECT_BY_TICKET)) {
            if (!IsTesting() && !IsVisualMode() &&!IsOptimization()) {
               slip=OrderOpenPrice()-op;
               Print(StringConcatenate(
                  "Operation details: Speed ",
                  (GetTickCount()-time0),
                  " ms | Slippage ",
                  DoubleToStr(toPips(slip, symbol),1),
                  " pips"
               ));
            }
         }
         
         //-- fix stops in case of slippage
         if (!IsTesting() && !IsVisualMode() &&!IsOptimization())
         {
            slip = NormalizeDouble(OrderOpenPrice(), digits) - NormalizeDouble(op, digits);
            if (slip != 0 && (OrderStopLoss()!=0 || OrderTakeProfit()!=0))
            {
               Print("Correcting stops because of slippage...");
               sl = OrderStopLoss();
               tp = OrderTakeProfit();
               if (sl != 0 || tp != 0)
               {
                  if (sl != 0) {sl = NormalizeDouble(OrderStopLoss()+slip, digits);}
                  if (tp != 0) {tp = NormalizeDouble(OrderTakeProfit()+slip, digits);}
                  ModifyOrder(ticket, OrderOpenPrice(), sl, tp, 0, 0, 0, CLR_NONE, false);
               }
            }
         }
         RegisterEvent("trade");
         break;
      }
      
      break;
   }
   return(ticket);
}
bool OrderModified(double id=-1, string action="set")
{
   static double memory[];
   
   if (id==-1) {
      id=OrderTicket();
      action="get";
   }
   else if (id>-1 && action!="clear") {
      action="set";
   }
   
   bool modified_status=InArray(memory,id);
   
   if (action=="set") {
   //- Set Trade ID
      ArrayValue(memory,id);
      return(true);
   }
   else if (action=="clear") {
   //- Unset Trade ID
      ArrayStrip(memory,id);
      return(true);
   }
   else if (action=="get") {
   //- Get State
      return(modified_status);
   }
   
   Print("Error: The second parameter of the function \"OrderModified\" should be \"set\", \"get\" or \"clear\"");
   return (false);
}
double PipValue(string symbol="")
{
   if (symbol=="") {symbol=GetSymbol();}
   return(CustomPoint(symbol)/MarketInfo(symbol,MODE_POINT));
   /*
   if (symbol=="") {symbol=GetSymbol();}
   int digits=MarketInfo(symbol,MODE_DIGITS);
   if ((digits==2 || digits==4)) {return(POINT_FORMAT/0.0001);}
   if ((digits==3 || digits==5)) {return(POINT_FORMAT/0.00001);}
   if ((digits==6))              {return(POINT_FORMAT/0.000001);}
   return(1);
   */
}
// Collect events, if any
void RegisterEvent(string command="")
{
   int ticket=OrderTicket();
	OnTradeListener();
   ticket=OrderSelect(ticket,SELECT_BY_TICKET);
   return;
}
int SellNow(
   string symbol,
   double lots,
   double sll,
   double tpl,
   double slp,
   double tpp,
   double slippage=0,
   int magic=0,
   string comment="",
   color arrowcolor=CLR_NONE,
   int expiration = 0
   )
{
   int ticket=OrderCreate(
      symbol,
      OP_SELL,
      lots,
      0,
      sll,
      tpl,
      slp,
      tpp,
      slippage,
      magic,
      comment,
      arrowcolor,
      expiration
      );
   return(ticket);
}
string SetSymbol(string symbol="")
{
	if (symbol=="") {symbol=Symbol();}
   GetSymbol(symbol); return(symbol);
}
bool SkipThePass(bool set=false)
{
   static int mem_fid=0;
   static bool mem=false;
   if (set==true) {
      mem=true;
      mem_fid=FXD_CURRENT_FUNCTION_ID;
   }
   else {
      if (mem_fid!=FXD_CURRENT_FUNCTION_ID) {
         mem=false; // reset
         return(false);
      }
      if (mem==true) {
         mem=false; // reset
         return(true);
      }
   }
   return(mem);
}
void StringExplode(string delimiter, string explode, string &sReturn[])
{
   static int ilBegin; ilBegin = -1;
   static int ilEnd; ilEnd = 0;
   static int ilElement; ilElement = 0;
   
   static string sDelimiter; sDelimiter = delimiter;
   static string sExplode; sExplode = explode;
   
   while (ilEnd != -1)
   {
      ilEnd = StringFind(sExplode, sDelimiter, ilBegin+1);
      ArrayResize(sReturn,ilElement+1);
      sReturn[ilElement] = "";     
      if (ilEnd == -1){
         if (ilBegin+1 != StringLen(sExplode)){
            sReturn[ilElement] = StringSubstr(sExplode, ilBegin+1, StringLen(sExplode));
         }
      } else { 
         if (ilBegin+1 != ilEnd){
            sReturn[ilElement] = StringSubstr(sExplode, ilBegin+1, ilEnd-ilBegin-1);
         }
      }      
      ilBegin = StringFind(sExplode, sDelimiter,ilEnd);  
      ilElement++;    
   }
}
string StringImplode(string sDelimiter, string &sImplode[]){
   string slImplode = "";
   for (int i = 0; i < ArraySize(sImplode); i++) {
      slImplode = StringConcatenate(slImplode, sImplode[i], sDelimiter);
   }
   return(StringSubstr(slImplode, 0, (StringLen(slImplode) - StringLen(sDelimiter))));
}
string StringImplode(string sDelimiter, int &sImplode[]){
   string slImplode = "";
   for (int i = 0; i < ArraySize(sImplode); i++) {
      slImplode = StringConcatenate(slImplode, sImplode[i], sDelimiter);
   }
   return(StringSubstr(slImplode, 0, (StringLen(slImplode) - StringLen(sDelimiter))));
}
string StringImplode(string sDelimiter, double &sImplode[]){
   string slImplode = "";
   for (int i = 0; i < ArraySize(sImplode); i++) {
      slImplode = StringConcatenate(slImplode, sImplode[i], sDelimiter);
   }
   return(StringSubstr(slImplode, 0, (StringLen(slImplode) - StringLen(sDelimiter))));
}
string StringTrim(string text)
{
   static string t; t = text;
   t = StringTrimRight(t);
   t = StringTrimLeft(t);
	return(t);
}
double SymbolAsk(string symbol="")
{
   if (symbol=="") {symbol=GetSymbol();}
   return(MarketInfo(symbol,MODE_ASK));
}
double SymbolBid(string symbol="")
{
   if (symbol=="") {symbol=GetSymbol();}
   return(MarketInfo(symbol,MODE_BID));
}
int SymbolDigits(string symbol="")
{
   if (symbol=="") {symbol=GetSymbol();}
   return(MarketInfo(symbol,MODE_DIGITS));
}
double TicksData(string symbol="", int type=0, int shift=0)
{
   
   //return(MarketInfo(symbol,type));
   static bool collecting_ticks=false;
   //static string feeded_symbols[];
   static string symbols[1];
   static int zero_sid[1];
   static double memoryASK[1][100];
   static double memoryBID[1][100];
   int sid; int size; int i; int id;
   double ask, bid, retval;
   bool exists=false;
   
   if (symbols[0]!=Symbol()) {symbols[0]=Symbol();}
   
   if (symbol=="") {symbol=Symbol();}
	
   if (type>0 && shift>0) {collecting_ticks=true;}
   if (collecting_ticks==false) {
      if (type>0 && shift==0) {
         // going to get ticks
      } else {return(0);}
   }
   
	if (type==0)
	{
      //StringExplode(",",symbol,feeded_symbols);
	   //for (s=0; s<ArraySize(feeded_symbols); s++)
	   //{
	      //symbol=feeded_symbols[s];
         //if (symbol=="") {symbol=Symbol();}
	      exists=false;
         size=ArraySize(symbols);
	      for (i=0; i<size; i++) {
	         if (symbols[i]==symbol) {exists=true; sid=i; break;}
	      }
         if (exists==false) {
            int newsize=ArraySize(symbols)+1;
            ArrayResize(symbols,newsize); symbols[newsize-1]=symbol;
            ArrayResize(zero_sid,newsize);
            ArrayResize(memoryASK,newsize);
            ArrayResize(memoryBID,newsize);
            sid=newsize;
         }
         if (sid>=0) {
            ask=MarketInfo(symbol,MODE_ASK);
            bid=MarketInfo(symbol,MODE_BID);
            if (bid==0 && MQLInfoInteger(MQL_TESTER)) {
               Print("Ticks data collector error: "+symbol+" cannot be backtested. Only the current symbol can be backtested. The EA will be terminated.");
               ExpertRemove();
            }
            if (symbol==Symbol() || ask!=memoryASK[sid][0] || bid!=memoryBID[sid][0])
            {
               memoryASK[sid][zero_sid[sid]]=ask;
               memoryBID[sid][zero_sid[sid]]=bid;
               zero_sid[sid]=zero_sid[sid]+1;
               if (zero_sid[sid]==100) {zero_sid[sid]=0;}
	         }
   	   }
      //}
   }
   else {
      if (shift<=0) {
         if (type==MODE_ASK) {
            return(MarketInfo(symbol, MODE_ASK));
         }
         else if (type==MODE_BID) {
            return(MarketInfo(symbol, MODE_BID)); 
         }
         else {
            double mid=((MarketInfo(symbol, MODE_ASK)+MarketInfo(symbol, MODE_BID))/2);
            return(mid);
         }
      }
      else {
         size=ArraySize(symbols);
         for (i=0; i<size; i++) {
            if (symbols[i]==symbol) {sid=i;}
         }
         if (shift<100) {
            id=zero_sid[sid]-shift-1; if(id<0) {id=id+100;}
            
            if (type==MODE_ASK) {
               retval=(memoryASK[sid][id]);
               if (retval==0) {retval=MarketInfo(symbol,MODE_ASK);}
            }
            else if (type==MODE_BID) {
               retval=(memoryBID[sid][id]);
               if (retval==0) {retval=MarketInfo(symbol,MODE_BID);}
            }
            //Print(shift+" "+id+" "+retval);
         }
      }
   }
   return(retval);
}
int TicksFromStart(bool upd=false)
{
   static int ticks=1;
   if (upd==true) {ticks++; if (ticks<0) ticks=0;}
   return(ticks);
}
datetime TimeAtStart(string cmd="server")
{
   static datetime local=0;
   static datetime server=0;
	
   if (cmd=="local") {return(local);}
   else if (cmd=="server") {return(server);}
   else if (cmd=="set") {
      local=TimeLocal();
      server=TimeCurrent();
   }
   return(0);
}
datetime TimeFromString(string format="", datetime now=0)
{
   if (now==0) {now=TimeCurrent();}
	if(StringFind(format,".",0)==-1) {
      if (StringFind(format, ":", 0)==-1) {format=format+":00";}
      format=TimeYear(now)+"."+TimeMonth(now)+"."+TimeDay(now)+" "+format;
   }
   return(StrToTime(format));
}
double toDigits(double pips,string symbol="")
{
	if (symbol=="") {symbol=GetSymbol();}
   return(
      NormalizeDouble(
         pips*PipValue(symbol)*MarketInfo(symbol,MODE_POINT),
         MarketInfo(symbol,MODE_DIGITS)
      )
   );
}
double toPips(double digits,string symbol="")
{
   if (symbol=="") {symbol=GetSymbol();}
   return(digits/(PipValue(symbol)*MarketInfo(symbol,MODE_POINT)));
}
void UpdateEventValues(string e_reason="",string e_detail="")
{
   OnTradeQueue(1);
   e_Reason(true,e_reason);
   e_ReasonDetail(true,e_detail);
   e_attrClosePrice (true,attrClosePrice());
   e_attrComment    (true,attrComment());
   e_attrCommission (true,attrCommission());
   e_attrExpiration (true,attrExpiration());
   e_attrLots       (true,attrLots());
   e_attrMagicNumber(true,attrMagicNumber());
   e_attrOpenPrice  (true,attrOpenPrice());
   e_attrProfit     (true,attrProfit());
   e_attrStopLoss   (true,attrStopLoss());
   e_attrSymbol     (true,attrSymbol());
   e_attrTakeProfit (true,attrTakeProfit());
   e_attrTicket     (true,attrTicket());
   e_attrType       (true,attrType());
   // Not set, just execute without reason
   e_attrOpenTime();
   e_attrSwap();
}
double VirtualStopsDriver(string _command="", int _ti=-1, double _sl=0, double _tp=0, double _slp=0, double _tpp=0)
{
   if (!USE_VIRTUAL_STOPS) {return(0);} // Virtual stops are not enabled => stop here
   
   static int mem_to_ti[]; // tickets
   static int mem_to[];    // timeouts
   static int last_checked_ticket=0;
   
   static string command;  command=_command;
   static int ti;          ti=_ti;
   static double sl;       sl=_sl;
   static double tp;       tp=_tp;
   static double slp;      slp=_slp;
   static double tpp;      tpp=_tpp;
   
   static int i; i=0;
   static int ii; ii=-1;
   static int size; size=0;
   static int error; error=0;
   static int pos;
   static int total;
   static string name;
   static double ask, bid;
   static string print;
   
   // Listen trades/orders
   if (command=="" || command=="listen")
   {
      //-- delete lines of virtual stops of manually closed trades ------
      total = OrdersHistoryTotal();
      if (total>0)
      {
         static int prev_ticket; prev_ticket=0;
         for (pos=total-1; pos>=0; pos--)
         {
            if (OrderSelect(pos,SELECT_BY_POS,MODE_HISTORY))
            {
               if (OrderTicket()==last_checked_ticket) {break;}
               prev_ticket=OrderTicket();
               static bool clear; clear=true;
               
               name = "#"+OrderTicket()+" sl";
               if (ObjectFind(name)<0) {
                  error=GetLastError();
               }
               else {
                  clear=false;
                  ObjectDelete(name);
               }
               
               name = "#"+OrderTicket()+" tp";
               if (ObjectFind(name)<0) {
                  clear=true;
                  error=GetLastError();
               }
               else {
                  clear=false;
                  ObjectDelete(name);
               }
            }
         }
      
         if (prev_ticket==0) {prev_ticket=OrderTicket();}
         last_checked_ticket = prev_ticket;
      }
      
      //-- parse trades -------------------------------------------------
      total = OrdersTotal();
      for (pos=0; pos<total; pos++)
      {
         if (OrderSelect(pos,SELECT_BY_POS))
         {
            static int ticket;
            static string symbol;
            static double lots;
            static double cp;
            ticket   = OrderTicket();
            symbol   = OrderSymbol();
            lots     = OrderLots();
            cp       = OrderClosePrice();
            
            // check SL and TP
            static double sl_lvl;
            static double tp_lvl;
            
            name = "#"+ticket+" sl";
            sl_lvl = ObjectGet(name,OBJPROP_PRICE1);
            name = "#"+ticket+" tp";
            tp_lvl = ObjectGet(name,OBJPROP_PRICE1);
            
            // close trade/order
            if (OrderType()==OP_BUY)
            {
               bid = MarketInfo(symbol,MODE_BID);
               if ((sl_lvl>0 && bid<=sl_lvl) || (tp_lvl>0 && bid>=tp_lvl))
               {
                  if (VIRTUAL_STOPS_TIMEOUT>0 && (sl_lvl>0 && bid<=sl_lvl))
                  {
                     i=ArraySearch(mem_to_ti, ticket);
                     if (i<0)
                     { // start timeout
                        size = ArraySize(mem_to_ti);
                        ArrayResize(mem_to_ti, size+1);
                        ArrayResize(mem_to, size+1);
                        mem_to_ti[size]   = ticket;
                        mem_to[size]      = TimeLocal();
                        print = StringConcatenate("#",ticket," timeout of ",VIRTUAL_STOPS_TIMEOUT," seconds started");
                        Print(print);
                        return(0);
                     }
                     else {
                        if (TimeLocal()-mem_to[i] <= VIRTUAL_STOPS_TIMEOUT) {return(0);}
                     }
                  }
                  if (OrderClose(ticket, lots, cp, 0, clrNONE))
                  {
                     OnTradeListener(); // check this before deleting the lines
                     name = "#"+OrderTicket()+" sl";
                     ObjectDelete(name);
                     name = "#"+OrderTicket()+" tp";
                     ObjectDelete(name);
                  }
                  return(0);
               }
               else
               {
                  if (VIRTUAL_STOPS_TIMEOUT>0) {
                     i=ArraySearch(mem_to_ti,ticket);
                     if (i>=0) {
                        ArrayStripKey(mem_to_ti,i);
                        ArrayStripKey(mem_to,i);
                     }
                  }
               }
            }
            else if (OrderType()==OP_SELL)
            {
               ask = MarketInfo(symbol,MODE_ASK);
               if ((sl_lvl>0 && ask>=sl_lvl) || (tp_lvl>0 && ask<=tp_lvl))
               {
                  if (VIRTUAL_STOPS_TIMEOUT>0 && (sl_lvl>0 && ask>=sl_lvl))
                  {
                     i=ArraySearch(mem_to_ti, ticket);
                     if (i<0)
                     { // start timeout
                        size = ArraySize(mem_to_ti);
                        ArrayResize(mem_to_ti, size+1);
                        ArrayResize(mem_to, size+1);
                        mem_to_ti[size]   = ticket;
                        mem_to[size]      = TimeLocal();
                        print = StringConcatenate("#",ticket," timeout of ",VIRTUAL_STOPS_TIMEOUT," seconds started");
                        Print(print);
                        return(0);
                     }
                     else {
                        if (TimeLocal()-mem_to[i] <= VIRTUAL_STOPS_TIMEOUT) {return(0);}
                     }
                  }
                  if (OrderClose(ticket, lots, cp, 0, clrNONE))
                  {
                     OnTradeListener(); // check this before deleting the lines
                     name = "#"+OrderTicket()+" sl";
                     ObjectDelete(name);
                     name = "#"+OrderTicket()+" tp";
                     ObjectDelete(name);
                  }
                  return(0);
               }
               else
               {
                  if (VIRTUAL_STOPS_TIMEOUT>0)
                  {
                     i=ArraySearch(mem_to_ti,ticket);
                     if (i>=0) {
                        ArrayStripKey(mem_to_ti,i);
                        ArrayStripKey(mem_to,i);
                     }
                  }
               }
            }
         }
      }
   }
   // Set SL and TP
   else if ((command=="set" || command=="modify" || command=="clear" || command=="partial") && ti>-1)
   {
      static string settext;
      // update record (add/modify)
      name = "#"+ti+" sl";
      if (sl>0) {
         if (ObjectFind(name)==-1)
         {
            ObjectCreate(name,OBJ_HLINE,0,0,sl);
            ObjectSet(name,OBJPROP_WIDTH,1);
            ObjectSet(name,OBJPROP_COLOR,DeepPink);
            ObjectSet(name,OBJPROP_STYLE,STYLE_DOT);
            settext = name+" (virtual)";
            ObjectSetText(name, settext);
            error=GetLastError();
         }
         else {
            ObjectSet(name,OBJPROP_PRICE1,sl);
         }
      } else {ObjectDelete(name);}
      
      name="#"+ti+" tp";
      if (tp>0)
      {
         if (ObjectFind(name)==-1) {
            ObjectCreate(name,OBJ_HLINE,0,0,tp);
            ObjectSet(name,OBJPROP_WIDTH,1);
            ObjectSet(name,OBJPROP_COLOR,DodgerBlue);
            ObjectSet(name,OBJPROP_STYLE,STYLE_DOT);
            settext = name+" (virtual)";
            ObjectSetText(name, settext);
            error=GetLastError();
         }
         else {
            ObjectSet(name, OBJPROP_PRICE1, tp);
         }
      }
      else {
         ObjectDelete(name);
      }
      
      // print message
      if (command=="set" || command=="modify") {
         print = command+" #"+ti+": virtual sl "+DoubleToStr(sl,Digits)+" tp "+DoubleToStr(tp,Digits);
         Print(print);
      }
      return(1);
   }
   
   // Get SL or TP
   else if ((command=="get sl" || command=="get tp") && ti>0)
   {
      if (command=="get sl")
      {
         name = "#"+ti+" sl";
         if (ObjectFind(name) == -1) {error=GetLastError();return(0);} 
         return(ObjectGet(name, OBJPROP_PRICE1));
      }
      else if (command=="get tp")
      {
         name = "#"+ti+" tp";
         if (ObjectFind(name) == -1) {error=GetLastError();return(0);}
         return(ObjectGet(name, OBJPROP_PRICE1));
      }
      return(0);
   }
   
   return(1);
}
void WaitTradeContextIfBusy()
{
	if(IsTradeContextBusy()) {
      while(true)
      {
         Sleep(1);
         if(!IsTradeContextBusy()) {
            RefreshRates();
            break;
         }
      }
   }
   return;
}
int CustomDigits(string symbol="") {
	if (symbol=="") {symbol=GetSymbol();}
	double point=CustomPoint(symbol);
	if (point==0) {return(0);}
	int digits=0;
	while(true) {
		if (point>=1) {break;}
		point=point*10;
		digits++;
	}
	return(digits);
}
double CustomPoint(string symbol="") {
	static string symbols[];
	static double points[];
	static string last_symbol="-";
	static double last_point=0;
	static int last_i=0;
	static int size=0;

	if (symbol=="") {symbol=GetSymbol();}
	if (symbol==last_symbol) {return(last_point);}

	int i=last_i;
	int start_i=i;
	bool found=false;
	if (size>0) {
		while(true) {
			if (symbols[i]==symbol) {
				last_symbol=symbol;
				last_point=points[i];
				last_i=i;
				return(last_point);
				break;
			}
			i++;
			if (i>=size) {i=0;}
			if (i==start_i) {break;}
		}
	}

	//if (MarketInfo(symbol, MODE_DIGITS)<=0) {Print("Market "+symbol+" does not exists!"); return(0);} // commented because for indices digits = 0

	i=size;
	size=size+1;
	ArrayResize(symbols, size);
	ArrayResize(points, size);
	symbols[i]=symbol;
	points[i]=0;
	last_symbol=symbol;
	last_i=i;

	if (MarketInfo(symbol, MODE_POINT)==0.001) {points[i]=0.01;}
	if (MarketInfo(symbol, MODE_POINT)==0.00001) {points[i]=0.0001;}
	if (MarketInfo(symbol, MODE_POINT)==0.000001) {points[i]=0.0001;}
	if (points[i]==0) {points[i]=MarketInfo(symbol, MODE_POINT);}
	last_point=points[i];
	return(last_point);
}

string fxD_BlocksLookupTable(int cmd=0, string id="", bool onoff=false, bool toggle=false)
{
	int intID=0;
	bool notfound=false;

	while(true)
	{
		intID=StrToInteger(id);
		break;
	}
	switch(intID)
	{
		case 1: if(!cmd){block1();}else if(cmd==1){block1=onoff;}else if(cmd==2){block1=!(block1);}else if(cmd==3){return("100");}break;
		case 2: if(!cmd){block2();}else if(cmd==1){block2=onoff;}else if(cmd==2){block2=!(block2);}else if(cmd==3){return("100");}break;
		case 3: if(!cmd){block3();}else if(cmd==1){block3=onoff;}else if(cmd==2){block3=!(block3);}else if(cmd==3){return("100");}break;
		case 4: if(!cmd){block4();}else if(cmd==1){block4=onoff;}else if(cmd==2){block4=!(block4);}else if(cmd==3){return("100");}break;
		case 5: if(!cmd){block5();}else if(cmd==1){block5=onoff;}else if(cmd==2){block5=!(block5);}break;
		case 6: if(!cmd){block6();}else if(cmd==1){block6=onoff;}else if(cmd==2){block6=!(block6);}else if(cmd==3){return("1,2,3,4");}break;
		case 15: if(!cmd){block15();}else if(cmd==1){block15=onoff;}else if(cmd==2){block15=!(block15);}else if(cmd==3){return("5");}break;
		case 25: if(!cmd){block25();}else if(cmd==1){block25=onoff;}else if(cmd==2){block25=!(block25);}else if(cmd==3){return("5");}break;
		case 35: if(!cmd){block35();}else if(cmd==1){block35=onoff;}else if(cmd==2){block35=!(block35);}else if(cmd==3){return("5");}break;
		case 36: if(!cmd){block36();}else if(cmd==1){block36=onoff;}else if(cmd==2){block36=!(block36);}else if(cmd==3){return("40");}break;
		case 40: if(!cmd){block40();}else if(cmd==1){block40=onoff;}else if(cmd==2){block40=!(block40);}else if(cmd==3){return("15,25,35");}break;
		case 55: if(!cmd){block55();}else if(cmd==1){block55=onoff;}else if(cmd==2){block55=!(block55);}else if(cmd==3){return("105");}break;
		case 65: if(!cmd){block65();}else if(cmd==1){block65=onoff;}else if(cmd==2){block65=!(block65);}else if(cmd==3){return("55");}break;
		case 94: if(!cmd){block94();}else if(cmd==1){block94=onoff;}else if(cmd==2){block94=!(block94);}else if(cmd==3){return("1,2,3,4");}break;
		case 100: if(!cmd){block100();}else if(cmd==1){block100=onoff;}else if(cmd==2){block100=!(block100);}else if(cmd==3){return("36");}break;
		case 102: if(!cmd){block102();}else if(cmd==1){block102=onoff;}else if(cmd==2){block102=!(block102);}else if(cmd==3){return("700");}break;
		case 105: if(!cmd){block105();}else if(cmd==1){block105=onoff;}else if(cmd==2){block105=!(block105);}else if(cmd==3){return("797");}break;
		case 107: if(!cmd){block107();}else if(cmd==1){block107=onoff;}else if(cmd==2){block107=!(block107);}else if(cmd==3){return("712");}break;
		case 108: if(!cmd){block108();}else if(cmd==1){block108=onoff;}else if(cmd==2){block108=!(block108);}else if(cmd==3){return("713");}break;
		case 111: if(!cmd){block111();}else if(cmd==1){block111=onoff;}else if(cmd==2){block111=!(block111);}else if(cmd==3){return("712");}break;
		case 112: if(!cmd){block112();}else if(cmd==1){block112=onoff;}else if(cmd==2){block112=!(block112);}else if(cmd==3){return("713");}break;
		case 127: if(!cmd){block127();}else if(cmd==1){block127=onoff;}else if(cmd==2){block127=!(block127);}else if(cmd==3){return("200");}break;
		case 128: if(!cmd){block128();}else if(cmd==1){block128=onoff;}else if(cmd==2){block128=!(block128);}else if(cmd==3){return("200");}break;
		case 129: if(!cmd){block129();}else if(cmd==1){block129=onoff;}else if(cmd==2){block129=!(block129);}else if(cmd==3){return("200");}break;
		case 130: if(!cmd){block130();}else if(cmd==1){block130=onoff;}else if(cmd==2){block130=!(block130);}else if(cmd==3){return("200");}break;
		case 131: if(!cmd){block131();}else if(cmd==1){block131=onoff;}else if(cmd==2){block131=!(block131);}else if(cmd==3){return("127,128,129,130,244");}break;
		case 132: if(!cmd){block132();}else if(cmd==1){block132=onoff;}else if(cmd==2){block132=!(block132);}else if(cmd==3){return("127,128,129,130,245");}break;
		case 200: if(!cmd){block200();}else if(cmd==1){block200=onoff;}else if(cmd==2){block200=!(block200);}else if(cmd==3){return("36");}break;
		case 244: if(!cmd){block244();}else if(cmd==1){block244=onoff;}else if(cmd==2){block244=!(block244);}else if(cmd==3){return("200");}break;
		case 245: if(!cmd){block245();}else if(cmd==1){block245=onoff;}else if(cmd==2){block245=!(block245);}else if(cmd==3){return("200");}break;
		case 699: if(!cmd){block699();}else if(cmd==1){block699=onoff;}else if(cmd==2){block699=!(block699);}else if(cmd==3){return("795");}break;
		case 700: if(!cmd){block700();}else if(cmd==1){block700=onoff;}else if(cmd==2){block700=!(block700);}else if(cmd==3){return("65");}break;
		case 701: if(!cmd){block701();}else if(cmd==1){block701=onoff;}else if(cmd==2){block701=!(block701);}else if(cmd==3){return("796");}break;
		case 709: if(!cmd){block709();}else if(cmd==1){block709=onoff;}else if(cmd==2){block709=!(block709);}else if(cmd==3){return("800");}break;
		case 712: if(!cmd){block712();}else if(cmd==1){block712=onoff;}else if(cmd==2){block712=!(block712);}else if(cmd==3){return("131");}break;
		case 713: if(!cmd){block713();}else if(cmd==1){block713=onoff;}else if(cmd==2){block713=!(block713);}else if(cmd==3){return("132");}break;
		case 714: if(!cmd){block714();}else if(cmd==1){block714=onoff;}else if(cmd==2){block714=!(block714);}else if(cmd==3){return("799");}break;
		case 715: if(!cmd){block715();}else if(cmd==1){block715=onoff;}else if(cmd==2){block715=!(block715);}else if(cmd==3){return("713");}break;
		case 720: if(!cmd){block720();}else if(cmd==1){block720=onoff;}else if(cmd==2){block720=!(block720);}else if(cmd==3){return("712");}break;
		case 795: if(!cmd){block795();}else if(cmd==1){block795=onoff;}else if(cmd==2){block795=!(block795);}else if(cmd==3){return("94");}break;
		case 796: if(!cmd){block796();}else if(cmd==1){block796=onoff;}else if(cmd==2){block796=!(block796);}else if(cmd==3){return("6");}break;
		case 797: if(!cmd){block797();}else if(cmd==1){block797=onoff;}else if(cmd==2){block797=!(block797);}else if(cmd==3){return("798");}break;
		case 798: if(!cmd){block798();}else if(cmd==1){block798=onoff;}else if(cmd==2){block798=!(block798);}else if(cmd==3){return("5");}break;
		case 799: if(!cmd){block799();}else if(cmd==1){block799=onoff;}else if(cmd==2){block799=!(block799);}else if(cmd==3){return("699");}break;
		case 800: if(!cmd){block800();}else if(cmd==1){block800=onoff;}else if(cmd==2){block800=!(block800);}else if(cmd==3){return("701");}break;
		default:notfound=true;
	}
	if (notfound==true) {
		string attempt="";
		if (cmd==0) {attempt=" (attempt to run block)";}
		else if (cmd==1) {
			if (onoff==true) {attempt=" (attempt to turn block ON)";}
			else {attempt=" (attempt to turn block OFF)";}
		}
		else if (cmd==2) {
			attempt=" (attempt to toggle block)";
		}
		else if (cmd==3) {
			attempt=" (attempt to get connections information for block)";
		}
		Alert("fxDreema Error: Block "+id+" was not found for this project!"+attempt);
	}
	return("");
}

//+------------------------------------------------------------------+
//| END                                                              |
//| Created with fxDreema EA Builder           https://fxdreema.com/ |
//+------------------------------------------------------------------+
/*<fxdreema:eNrtXVlz2zqW/isaPUz1VKXSBLjrdt0Zb+lkRpY8lpPbd15UtAQ77FCkmqSSqLv83wcbSZAiKFCLZfvyJQsPiHPw4Sw4BA7kDZzBvxL8Rz9BaeqHj0n/F28AIXkI4KC/jKO/o1k6Db0F6v+Cn7mD/vjen16dTf9r4cXfUDrV3kOLkoTm6XpJm1uDPvq5RHGaNZhFcxR44ePKe6QNjEH/+n+HBiWDQX/upWg6ixH+q/+LPwAGcG1L021NpC+iuf+wFuiGBjl94T36s2mSeowj7h3Yrp31fh9Es28JeZ+NZdDX6N/2oP8Ye8uv0yj2UZh6qR+F2Tt30fIuOo/SNFrQR3hE3iz1v2MxI9zUD1HMOd35s2/knxC/9d1P/PsATQP/Pvbi9fQxjlZLDkiyTlK0yMDMWlLZZO30QT/1FyieJghznSdk7FaGyTLyw3QarwJE504f/MsfaGQSyRxiuR5iJrqJh/te0wCVEXcYcbnxQ/zsCaNZ85LNXqq+ZvHH7EVY86KTvdjw5hPDfpWg6Xc/TldegKcuWib8hTAq4BSoUwJFtEoJCBpHkXSBMECPKJytazohbSr0aYyCkhbUNPHm81IT/A/0HWtIoUMGmRk277QDRp2tZ3hKsd770ZzqKSHjpom/WAVEhck7idg1GWWZOmXmxTG7+nz7eXKJMaNT8sMP59EPOt2GSYDPnwHyDGjcptmzT5d8JvMmycAl87EcPzwkiAJpahRKbdAP0ENaPIeOxlpLtX3Q9+e8xwusm35mPPj/PkZilVDLuadThUWa+4mH9X2ePSIKsPRi7F5SFOP2URTPKTJYFK61ycwLMm8SRvHCC3j/3LrY+Mr8RZzgdkxgG0x06/Vjom/HRG+DiaGbrx4TYzsmRhtMTPD69cTcjolZhwkw6jGxdVVMsPBXi2W6PgUeBW8RC2s7FlatfrjmnjZD3h1GeGnjBWejy1MgUpXgScAAyJWk1KZGSxwJMk4bZO7weuCDH6Ss1SmQESUQkYEKyMBWyJjmUZEBz4WMroCM3goZy9DeBjKWAjK1fkaX+FwLKOsMSXhWcTge0XTkJOZUFUHExtC2Y2NoddhAW7JuAW3saRzO0A2Kz72TeRpRAhEZU8GezHp7cuuRca02yFx9R/H6b/denJwKGVECERlLARmrFhmo13saB74Ve3KN7di4Rps1jQ6117ymcfP1iiZ3NeVGNX5YYlGGZh5n7QuOtvYVhgpV8KjNo5lO1HgY5fyIKrH3Dd3E0YOfJiezI1GEMjqmCjoS/yvxMpoqOpjhp4dxPEencb4l9mVUbBVU7DpUbInvdQ1VG4L43bMAxek1ShLvEZ3Nv3s4eM5PAZFcljJejgpeThu8MLza2wUMAAXAAGgDmGO2+GgzQeH8auH5wYk+2gj8y7ioOGsAWykSsM3XDwxU8UjQbvOVz3Zf7Vc+Ycgqngc6bXBx7LeAi6uCi9sGF/UI9oJx0VVWx7rWBhe8eHwDCqOrRCQdtEmpHP2NpFS6SlTSYRts1I3pZWMDVdJN2C7ddMHrTTehYSjgYRjtHMwbiNTQMFWAMVsBA95AqLZchVBNG6mveXW7RQo+ik6aghfsRVRsFb9ia5JP5hKfa79ev2JrQAWPVhmjqfw5+OVqiauCSq3tOO7em0744cVXL04vY+/HWRxHP06yJVcjRQkjlZzars+pLWPfT3wvcvNJGLaugk3tgSJr/w9XLx0cQwUco41xGeZbMy5TBaPaVY0DZKsadet6HSBBlVgOtTYgucYbw8hVUSS3VpEsU3IE1jLfyDaV7Voq6FhtYphpaG8GHVsFHbvNcccWOScexCRAaHmi846cdxkQRwUQpw0g7ltZ8qikm3Z9uilzxtBVdTRY7PPVeqTsgw8Ki8BcRMRRSTUdrVV4spRP2ttkzycITgSJyJ1WtWhix7IyDYs80vGjugINPLIfw7pPLoQwqiOQ9y9KQyZNb3hNEP3fMOpnpTqFneFRzrxwHiCM
APs7U/7yEOgIcGN//HF4wSHxL4IoQTy5vKBvc9sZ9CFvM/n9+nw8FGDFgt99ur76cHt2fVUqr8H0i/Ht7dXF3afxKH/hiZ3BnkULLE9WuPUXDsXtQUdE/71E4bEHxE+VT1IvXSX5ADD3KIweHsQuDFrz5lXBEApbZFoEX4kW4RH6Q2a2m5CD16dDjeN5cSqkN6mQ/kpUiPz7o//49QQ69OvR/JB8QC9OiYwmJTLeRjR7pVokj2bgpWmRmQ+iRovMkhaJGwu5BuHOb7wk2aI8eHn6tFHUJeNqlbhubiHnvPG7/NF21pW6KbvMu1IxVWJeLlrJmZNlLCH1HiitB/5yH/+6RRZIjQjQhWv8HcXjeBjhcZFusvJz+jwrPyeECSmrvxYKn9HPNFOYjMxnB3dvuhvv/o5YIscVDRilfsP0q0iEAvHSW4sksc+P0SoWNZqYS9GpH67Scq2/SJ7QavpqhTchX4XzmoHaOVEYplN5rzpIKPRYGaKWkyoDLHrbGJ5edCcOrkqsGZqZE29RQKQsFaCTiw0KMhW1TDdEOpY3kXdOhE6qNywInVPBk5LkpQaT7JaDrIcnhsmPCSIuL43iRPSTCRC7Ig9g8WA/51Sp5DMltgrVbVUv2yo8rZ1q2oBl5DV2OpKY6KjWOkcvyjDJuECtYY5qbXJUY46jzhJrLHGziFNmFPrOAUw/fQDrDKMzjD0Mw6rJiCrVu4VhbBYJ5pYB8Utp7M3Rn4Cm/UcvinseqYr4E8T/UzASwD86npOOmRRYHlq2dqC4yCpyZSNltbglF1D+pF8s3nWyto6+9R7wGFGYxutehFv2ltgd3Htxj95/9EDSnb6KcyDyqOc2B8KC1eDKsDA33WG5aLZwh5jL2QNxhP2w38vI2xLiNqkcHlrOFj8zDwaB1QiBZSorvolZ02y8t6R7deS7fY9aQtLzStj8Z8/WNKo2a5TsbBP2AW2CVdXKwqJrHCOprBauVqagWrLanEmb3OkosN4LsWp1qS0VGm4qTnknufCYrlRx/j28T5a/bFMPqh+EAzspN5lF7Co7k1wSx29nK8h/zR4JqdtkvbiPgvxFepUbeSL74ELeOV+tk3FMNpESjtZ9xJJFEpMpr3JMyoP/NfKSVYyE4L/0l/knohv877NFtArTjfeiEK03SQ7ZCvaXS34/H35sZH3R8xYXURDFvOElQssbP/wmS9CsaoKmVRO0/IFefWBUH5jVJM86lAOvlvGaUjUs+69K3W2hgoAQmNL9OSL0HvrpJ+k2N27uonmjdko32qJvTzUFvHKztEt4NBWQlhJg2qi3YK22hXJ2FWXW9Z2fsv1Y0s/43u8leJnXO//8+79l6NBmQ+8eBaBiY5TyxQtWCNR8ZiXXDBLalP5Z/4k1U6sveZPtH3vLMkGpTPBkMulSmfSTyWRIZTJOJpMplck8mUyWVCbrZDLZUpnsk8nkSGVyTiaTK5XJfU6ZYMlnapVv14LT1J5RKhZLkogUco+i1H/AC+RsaxB39eAFZKOuftnBlnCHXndoNesO9sCuPnCqD1zxgU4E0zaegCMsZ5zm8O2cMHwbQvieXA2HXfzu4ncXv7v43cXvLn538Vu83kgav8HGQeHStTtFzNYYpZeTtgdsSL4L4taT1T35QQd5xp01vC6WA5CuEYLeLDvPlfS8GOEFQ/o+E+cSD5quBUBFXQnhIgpTFKbPGuRFmaBcJngqmXS5TPqpZDLkMhmnksmUy2SeSiZLLpN1KplsuUz2qWRy5DI5p5LJlcvkPvPCo/CZWuUwnOg0ny/IS4K39qqC98FCdfMGFoCKodoSQ7XShlVDwK7PsbuI3UXsLmJ3EbuL2F3E/gNHbHYVrPScDLS7KtyuCldNk5xmTXK6StyuEldBjdxmNXK7atyuGldFkfTmE6C61lXkdhW5apoEGs9D6uC4R5nZhdFy9vCo7PmdzDL2UPEkNS3YaMvaMJpMmF98/HwmrJNf9vZnWN/ZX/XqbnAluyFtOOzn
+Z1B5Moe9h+u1bVHoU++aHg2p3MgG+UXQstVxXwtqnI2+Z9jqcqvnaoUV2TLHBq/HFs83i7eVlw63j6K3sDxdru5VMZWcfD4vTVKnq1Qht9fbUpFBn+0KXSb9l34ndXFEqH2EtPSQQlC6eWkpkIhO9t3GdMdl6KokdTfxvyTXE7+vMSziipkm1JHHqtZFhwbe+duvSwOS57/9/Ts9nb82/Ry/NtI6JtX5bDqH/yIXUjhUBqpV63blNGyz4spL5eu+boI+D1+pLAoq6oWPRWtSY5W8axEKUqpF8uNUmpeXVzxk6Uer734G0pFNFzxpbu8CrSmdPcC+/woROHGPSNOhb5xEYdVaVC5jqPaf1bxjMfDNvZyIXMOm2Xc1SY15c96gfbkq/+Q1hU3U0JeGp1JaArEojC6es8Kof6G0Lek7jIVQsxqputezCumK6AxnkVtWh1ZqJaukr/5SyLSnHMWzoYxO8daTBcJ4JVmlmwIZ+HsKyubo0ehRxcfx7fTu/FNYap5XR3mOwviWzQvaJN0zU9NEzd69/vwajoZD/O6UtziN3/OqwW59MyznHusrLZANTvG9XfsWLGHIdWRVZcFBDqaV19n4/noz+corKf9Hw0oVXjIEInnFc2+fj/CULnWpbwdAarbEeBg+wT83n9pxAVQtcSd+muhpr1lDftIXr5ecxe/XF79pclrNEZwYLyJCA7FCP75povfXfzu4vebjN82jd9DbnFdAD99ADebA4zZpYhdiOlCTBdiuhSxizA7RRj2w0zSCAO1LoXp4ksXX7r40qUwXYDZJcC4zSmMa6pfj6dLr8d7FRfjkZ9kyv79x7oZD5zyZjz+y4FyDbT+MBpINqJX604Bn1sB7WYFtKtnNfIfUxQP412igK2rth1vIlNLexDWDWStZWYLKUr8FN6hBIf4Uf7LcKUoV232xU9W1WaSmpya6TkYkk7jBpHrqG4Q6Zp4Z/NPPy1d2bzDNc2qW0Zu86GPyjmm0o8l5sLb9Gkv3JpiGW7Z61Tdiuxs2pcoWC1y2ycT7v9E8zJ14v8z8wzae34vuyESb/0kuxfZ1MrvZiSMAHxvZqsqRsOTNUPMeWT3fbMchJHp1cdCGzw2PfM9c1Gyw9Sl6WR0YFu9HJbuA0HoltwT8zn00zpwTLERNmam5Fg+mN/xvlhcP37Cr/teMIxY7BEEcFiD61WQ+stgPQ6HUZKIJ/nJxTXlFiyIVa+CJ23O5nPCotRJnmmVGpT6KIl6ixKU1vRgl8gyGYAOLflg9azJLfqOJwdtOCjaxwf/PpL2ASFpcukFaHGP8Mq5Gdi8nYQhpBINvftoNfuKYiTvzio3HPpJmikgeAff6e+Md+Y7q8C6aCobK2U9Qf849xJUwxBwcjEV+G0ds7JKb9dOBeREGWsrM7zPS+wccV7lp5Ui1UkaLQnfWnch0G/4+qHQeNzJPMjIB6wkBQo1t/PloRkL3moL6/mhWVvMzWznbohr29oJK7XIpozds8+mcx4U9OecM8J6eXjWarNGmM8Pz1x13rCvu/q5zOYLi/zXuwse+vHz6q+FOPSp+CshObikl831PllzYcpL/9IJui+dzV864bN/6cxn5fk/deaf3PjvV9SllxjK6zUGcpEtFumqP3zs5T8RQe+EzRNQvKrmXZ9TC61PcMyt+Sdon38eLkniP2YuSzGcSmlA+dfH8xzDYY+7JKNLMroko0syuiSjSzK6JKNLMroko0syuiSjOckge3VfozgVsgxDzDLIupqbGD0H93qyDC4pRi9EM3rXJt2Pyy5hm2n5HhR19yiYcwdyefXh7PPwLtu3zA21eiMFJqZe/IjSzQvNnhgLcCwWTs4CHouFm7PQj8RC13IWxs4s+P1xMhYgZ2HuwcJRY2HtwcJVY2HvzkLX1Fg4tSzwe59GX65ud58KmHNwd+fgbOegE8PTdmfhKrIAO7NongmBxR7GzW6uaZ5tymMP62ZXniiMwziOB6GDzHiYx+JhFjz2MPAa
HnZOLDjYx+EgzIVzHA56wcE9DodirmHr0C1CXem/9HvBGQOwMwOoxgDuzEBXY6DvzMBQY2C0dH8NU5CTrKJ7c9fuoVL31q7d60rd27t2byh17+w8uaZ8ckHh6GBrE8570a0GX8p/+5uw0LWdWVgNYccWWYCjjAKILODOLNyGAE0PGmcs9GNMNhQYGMdgoAsMzJ0ZWE0YFQahWztPg6E1jEHgYO/MATSgZAiq5OzMASpy2MOq1TgY2h7pCWyYa1AsL4zdk2p+J4fMrJ2CBzwSD1AsxAx9D6xAE1YCD2OPccCmcRRLVsM8Eg/NLnhYx+FBKwYzHvZx5twW4qqx++LbbvyUoglzvvvym9e31POgtxZyHqa2B48mn64VemWCPdKIBndlFtNh7h69zQYOlsBB3wOopq8pmsDjkPG7fDw947CHibtOE4/CxM3dTZzfpynjIajtHiauNbhcR1gRmnuYeOM4QJF7mbubuNPkRugtjnx3Df1MUcw+mdt8O6tYzhRX06J8G2mC4u8oHsfDaOYF2a4XaQHKm1vsjmZCgFxoQrgK2d5Cae1VlGcwNqSUgBx2IftfT5UVSLVtubzhqWK61dYYxr/d042hp4ohb5GhWitRwWXjbFAOiOQcAIKyPeeaU1NHZMa4zaIwSb0wTYrLVV2y/xn7pJhMeEqu346Rlz95+n/i0alP
:fxdreema>*/