//+------------------------------------------------------------------------------+//
//) ____ _ _ ____ ____ ____ ____ __ __ __ ___ _____ __ __ (//
//) ( ___)( \/ )( _ \( _ \( ___)( ___)( \/ ) /__\ / __)( _ )( \/ ) (//
//) )__) ) ( )(_) )) / )__) )__) ) ( /(__)\ ( (__ )(_)( ) ( (//
//) (__) (_/\_)(____/(_)\_)(____)(____)(_/\/\_)(__)(__)()\___)(_____)(_/\/\_) (//
//) 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 ";
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) ";
extern string inp36_BlockID="100"; //
extern string inp40="(40) Look for entry once per bar \"timeframe\" ";
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 ";
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
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
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 (LocOpen) {
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 (cCloseRo) {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 ) //
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 && nowt1 && (now>=t0 || nowt1) {t1=t1-86400;}
}
if ((now>=t0 && nowt1 && (now>=t0 || now) //
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 && nowt1 && (now>=t0 || now) //
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) //
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) //
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 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 ) //
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 ) //
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 (LoRo) {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 (LoRo) {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=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 ) //
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 (time00) {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 (lotsMaxLots) {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 && sl0) {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 && sl0) {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 && tpaskbid))
{
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 && tptplimit))
{
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; i0)
{
for (int i=0; i0)
{
for (int i=0; i0)
{
int i=0; int x=0;
for (i=0; i0)
{
int i=0; int x=0;
for (i=0; i0)
{
int i=0; int x=0;
for (i=0; i0)
{
int i=0; int x=0;
for (i=0; i=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; s2) {
lots = initial_lots*(list[0]+list[size-1]);
// Cancel first and last numbers in our list
// shift array 1 step left
for(pos=0; pos1)
{
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; s0) {
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; pos0) {
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",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_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 (sizeMaxLots) {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= 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= 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=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; i0 && 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)=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 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=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 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; pos0 && 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/ |
//+------------------------------------------------------------------+
/**/