8 MA ribbon
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «8 ma ribbon.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Этот файл представляет собой торгового советника для MetaTrader 4, созданного на языке MQL4. Советник предназначен для автоматической торговли на финансовых рынках и использует набор из восьми экспоненциальных скользящих средних (EMA) для формирования сигналов. В коде присутствует обработка тиковых событий, а также торговых событий, что позволяет советнику реагировать на изменения рыночной ситуации и совершать сделки.
Советник включает в себя настройки для управления лотом, тейк-профитом, сеточной торговлей и параметрами индикаторов. Пользователь может задавать периоды для каждой из восьми EMA, а также выбирать свечу для анализа. Кроме того, предусмотрены параметры для идентификации ордеров (Magic Number) и настройки отображения информации на графике.
В коде реализованы механизмы управления ордерами, включая проверку на наличие открытых позиций и обработку ошибок торговых операций. Советник также поддерживает виртуальные стопы и может работать в тестере стратегий. Все настройки выведены в входные параметры, что позволяет легко адаптировать советника под различные торговые стратегии.
Настройки программы
| Настройка | Описание |
|---|---|
| ea_name | Имя советника — Название советника, используемое для идентификации. |
| lot | Размер лота — Размер торгового лота для открытия позиций. |
| close_profit_tp_pips | Тейк-профит в пунктах — Уровень тейк-профита в пунктах для закрытия позиции при достижении прибыли. |
| grid_nearby_pips | Шаг сетки в пунктах — Расстояние в пунктах для размещения сеточных ордеров рядом с текущей ценой. |
| setting-------> (setting) | Настройка — Текстовый параметр для дополнительных настроек (например, название стратегии). |
| ema_1 | Период EMA 1 — Период первой экспоненциальной скользящей средней. |
| ema_2 | Период EMA 2 — Период второй экспоненциальной скользящей средней. |
| ema_3 | Период EMA 3 — Период третьей экспоненциальной скользящей средней. |
| ema_4 | Период EMA 4 — Период четвёртой экспоненциальной скользящей средней. |
| ema_5 | Период EMA 5 — Период пятой экспоненциальной скользящей средней. |
| ema_6 | Период EMA 6 — Период шестой экспоненциальной скользящей средней. |
| ema_7 | Период EMA 7 — Период седьмой экспоненциальной скользящей средней. |
| ema_8 | Период EMA 8 — Период восьмой экспоненциальной скользящей средней. |
| candle_id | Идентификатор свечи — Номер свечи для анализа (0 — текущая, 1 — предыдущая и т.д.). |
| Magic Number, kind of... (MagicStart) | Магический номер — Идентификатор ордеров (Magic Number), используемый для различения сделок советника. |
Поиск по коду файла
#define OP_SELL 1
#define OP_SELLSTOP 5
#define OP_SELLLIMIT 3
#define OP_BUY 0
#define SELECT_BY_POS 0
#define MODE_TRADES 0
#define SELECT_BY_TICKET 1
#define MODE_LOTSTEP 24
#define MODE_LOTSIZE 15
#define MODE_MINLOT 23
#define MODE_MAXLOT 25
#define MODE_TICKVALUE 16
#define MODE_POINT 11
#define MODE_TICKSIZE 17
#define MODE_MARGINREQUIRED 32
#define OP_BUYLIMIT 2
#define OP_BUYSTOP 4
#define MODE_HISTORY 1
#define MODE_TRADEALLOWED 22
#define MODE_DIGITS 12
#define MODE_ASK 10
#define MODE_BID 9
#property description ""
#property version "1.0"
#property strict
/************************************************************************************************************************/
/************************************************************************************************************************/
#define PROJECT_ID "mt4-8804"
#define POINT_FORMAT_RULES "0.001=0.01,0.00001=0.0001,0.000001=0.0001" // this is deserialized in a special function later
#define ENABLE_SPREAD_METER true
#define ENABLE_STATUS true
#define ENABLE_TEST_INDICATORS true
#define ENABLE_EVENT_TICK 1 // enable "Tick" event
#define ENABLE_EVENT_TRADE 0 // enable "Trade" event
#define ENABLE_EVENT_TIMER 0 // enable "Timer" event
#define VIRTUAL_STOPS_ENABLED 0 // enable virtual stops
#define VIRTUAL_STOPS_TIMEOUT 0 // virtual stops timeout
#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)
string fxdBlocksLookupTable[];
#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
input string ea_name = "8 MA ribbon";
input double lot = 0.01;
input int close_profit_tp_pips = 30;
input int grid_nearby_pips = 10;
input string setting = "moving average ribbon"; // setting------->
input int ema_1 = 20;
input int ema_2 = 25;
input int ema_3 = 30;
input int ema_4 = 35;
input int ema_5 = 40;
input int ema_6 = 45;
input int ema_7 = 50;
input int ema_8 = 55;
input int candle_id = 1;
input int MagicStart = 8804; // Magic Number, kind of...
class c
{
public:
static string ea_name;
static double lot;
static int close_profit_tp_pips;
static int grid_nearby_pips;
static string setting;
static int ema_1;
static int ema_2;
static int ema_3;
static int ema_4;
static int ema_5;
static int ema_6;
static int ema_7;
static int ema_8;
static int candle_id;
static int MagicStart;
};
string c::ea_name;
double c::lot;
int c::close_profit_tp_pips;
int c::grid_nearby_pips;
string c::setting;
int c::ema_1;
int c::ema_2;
int c::ema_3;
int c::ema_4;
int c::ema_5;
int c::ema_6;
int c::ema_7;
int c::ema_8;
int c::candle_id;
int c::MagicStart;
class v
{
public:
static double nearby_bs;
};
double v::nearby_bs;
int FXD_CURRENT_FUNCTION_ID = 0;
double FXD_MILS_INIT_END = 0;
int FXD_TICKS_FROM_START = 0;
int FXD_MORE_SHIFT = 0;
bool FXD_DRAW_SPREAD_INFO = false;
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;
string FXD_CURRENT_SYMBOL = "";
int FXD_BLOCKS_COUNT = 44;
datetime FXD_TICKSKIP_UNTIL = 0;
struct fxd_onchart
{
int id;
long lparam;
double dparam;
string sparam;
};
fxd_onchart FXD_ONCHART;
/************************************************************************************************************************/
/************************************************************************************************************************/
void OnInit()
{
// код доступен только после оплаты
}
void __OnTick__()
{
FXD_TICKS_FROM_START++;
if (ENABLE_STATUS && FXD_TICKS_FROM_START == 1) DrawStatus("working");
if (FXD_DRAW_SPREAD_INFO) DrawSpreadInfo();
TicksData(""); // Collect ticks (if needed)
TicksPerSecond(false, true); // Collect ticks per second
if (USE_VIRTUAL_STOPS) {VirtualStopsDriver();}
if (false) ExpirationWorker * expirationDummy = new ExpirationWorker();
expirationWorker.Run();
if (FBFB::OrdersTotal()) // this makes things faster
{
OCODriver(); // Check and close OCO orders
}
if (ENABLE_EVENT_TRADE) {OnTrade();}
if (TimeLocal() < FXD_TICKSKIP_UNTIL) {return;}
int blocks_to_run[] = {0,27,33,39,42};
for (int i=0; i<ArraySize(blocks_to_run); i++) {
_blocks_[blocks_to_run[i]].run();
}
return;
}
void OnTrade()
{
if (false) OnTradeEventDetector * dummy = new OnTradeEventDetector();
}
void OnTimer()
{
if (FXD_CHART_IS_OFFLINE && FBFB::RefreshRates()) {
OnTick();
}
if (ON_TRADE_REALTIME == 1) {
OnTrade();
}
static datetime t0 = 0;
datetime 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;
}
}
}
void OnChartEvent(
const int id, // Event ID
const long& lparam, // Parameter of type long event
const double& dparam, // Parameter of type double event
const string& sparam // Parameter of type string events
)
{
FXD_ONCHART.id = id;
FXD_ONCHART.lparam = lparam;
FXD_ONCHART.dparam = dparam;
FXD_ONCHART.sparam = sparam;
return;
}
void OnDeinit(const int reason)
{
int reson = UninitializeReason();
if (reson == REASON_CHARTCHANGE || reson == REASON_PARAMETERS || reason == REASON_TEMPLATE || reason == REASON_ACCOUNT ) {return;}
EventKillTimer();
if (ENABLE_STATUS) DrawStatus("stopped");
if (ENABLE_SPREAD_METER) DrawSpreadInfo();
ChartSetString(0, CHART_COMMENT, "");
if (MQLInfoInteger(MQL_TESTER)) {
Print("Backtested in "+DoubleToString((GetTickCount()-FXD_MILS_INIT_END)/1000, 2)+" seconds");
double tc = GetTickCount()-FXD_MILS_INIT_END;
if (tc > 0)
{
Print("Average ticks per second: "+DoubleToString(FXD_TICKS_FROM_START/tc, 0));
}
}
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 Advisor has 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;
}
}
for (int i=0; i<ArraySize(_blocks_); i++)
{
delete _blocks_[i];
_blocks_[i] = NULL;
}
ArrayResize(_blocks_, 0);
return;
}
/************************************************************************************************************************/
/************************************************************************************************************************/
/**
The base class for all block calls
*/
class BlockCalls
{
public:
bool __disabled; // whether or not the block is disabled
string __block_user_number;
int __block_number;
int __block_waiting;
int __parent_number;
int __inbound_blocks[];
int __outbound_blocks[];
void __addInboundBlock(int id = 0) {
int size = ArraySize(__inbound_blocks);
for (int i = 0; i < size; i++) {
if (__inbound_blocks[i] == id) {
return;
}
}
ArrayResize(__inbound_blocks, size + 1);
__inbound_blocks[size] = id;
}
void BlockCalls() {
__disabled = false;
__block_user_number = "";
__block_number = 0;
__block_waiting = 0;
__parent_number = 0;
}
/**
Announce this block to the list of inbound connections of all the blocks to which this block is connected to
*/
void __announceThisBlock()
{
for (int i = 0; i < ArraySize(__outbound_blocks); i++)
{
int block = __outbound_blocks[i]; // outbound block number
int size = ArraySize(_blocks_[block].__inbound_blocks); // the size of its inbound list
for (int j = 0; j < size; j++) {
if (_blocks_[block].__inbound_blocks[j] == __block_number)
{
return;
}
}
ArrayResize(_blocks_[block].__inbound_blocks, size + 1);
_blocks_[block].__inbound_blocks[size] = __block_number;
}
}
virtual void _execute_() = 0;
/**
In the derived class this method should be used to set dynamic parameters or other stuff before the main execute.
This method is automatically called within the main "run" method below, before the execution of the main class.
*/
virtual void _beforeExecute_() {return;};
bool _beforeExecuteEnabled; // for speed
/**
Same as _beforeExecute_, but to work after the execute method.
*/
virtual void _afterExecute_() {return;};
bool _afterExecuteEnabled; // for speed
/**
This is the method that is used to run the block
*/
virtual void run(int _parent_=0) {
__parent_number = _parent_;
if (__disabled || FXD_BREAK) {return;}
FXD_CURRENT_FUNCTION_ID = __block_number;
if (_beforeExecuteEnabled) {_beforeExecute_();}
_execute_();
if (_afterExecuteEnabled) {_afterExecute_();}
if (__block_waiting && FXD_CURRENT_FUNCTION_ID == __block_number) {fxdWait.Accumulate(FXD_CURRENT_FUNCTION_ID);}
}
};
BlockCalls *_blocks_[];
template<typename T1,typename T2,typename T3,typename T4,typename T5>
class MDL_NoOpenedOrders: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_NoOpenedOrders()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
}
public: /* The main method */
virtual void _execute_()
{
bool exist = false;
for (int index = TradesTotal()-1; index >= 0; index--)
{
if (TradeSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells))
{
exist = true;
break;
}
}
if (exist == false) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename _T1_,typename T2,typename T3,typename _T3_,typename T4>
class MDL_Condition: public BlockCalls
{
public: /* Input Parameters */
T1 Lo; virtual _T1_ _Lo_(){return(_T1_)0;
return NULL;
}
T2 compare;
T3 Ro; virtual _T3_ _Ro_(){return(_T3_)0;
return NULL;
}
T4 crosswidth;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_Condition()
{
compare = (string)">";
crosswidth = (int)1;
}
public: /* The main method */
virtual void _execute_()
{
bool output1 = false, output2 = false; // output 1 and output 2
int crossover = 0;
if (compare == "x>" || compare == "x<") {crossover = 1;}
for (int i = 0; i <= crossover; i++)
{
FXD_MORE_SHIFT = i * crosswidth;
_T1_ lo = _Lo_();
if (MathAbs(lo) == EMPTY_VALUE) {return;}
FXD_MORE_SHIFT = i * crosswidth;
_T3_ ro = _Ro_();
if (MathAbs(ro) == EMPTY_VALUE) {return;}
if (CompareValues(compare, lo, ro))
{
if (i == 0)
{
output1 = true;
}
}
else
{
if (i == 0)
{
output2 = true;
}
else
{
output2 = false;
}
}
if (crossover == 1)
{
if (CompareValues(compare, ro, lo))
{
if (i == 0)
{
output2 = true;
}
}
else
{
if (i == 1)
{
output1 = false;
}
}
}
}
FXD_MORE_SHIFT = 0; // reset
if (output1 == true) {_callback_(1);}
else if (output2 == true) {_callback_(0);}
}
};
class MDL_LogicalAND: public BlockCalls
{
/* Static Parameters */
int list[];
int check[];
int list_size;
int old_tick;
bool passed;
virtual void _callback_(int r) {return;}
public: /* The main method */
virtual void _execute_()
{
bool go_to_next = false;
if (!passed)
{
fxdGetInboundBlocks(__block_number, list);
list_size = ArraySize(list);
passed = true;
}
if (list_size == 0)
{
go_to_next = true;
}
else
{
int ticks = FXD_TICKS_FROM_START;
if (old_tick != ticks)
{
old_tick = ticks;
ArrayResize(check, 0); // reset
}
if (
ArraySearch(list, __parent_number) > -1
&& ArraySearch(check, __parent_number) == -1
)
{
ArrayEnsureValue(check, __parent_number); // add current parent
if (list_size == ArraySize(check))
{
go_to_next = true;
}
}
}
if (go_to_next == true) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6>
class MDL_SignalBullCandle: public BlockCalls
{
public: /* Input Parameters */
T1 SignalType;
T2 CandleID;
T3 MinBodySize;
T4 MaxBodySize;
T5 Symbol;
T6 Period;
/* Static Parameters */
datetime bartime;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_SignalBullCandle()
{
SignalType = (string)"continuous";
CandleID = (int)1;
MinBodySize = (double)5.0;
MaxBodySize = (double)0.0;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
/* Static Parameters (initial value) */
bartime = 0;
}
public: /* The main method */
virtual void _execute_()
{
double cOpen = FBFB::iOpen(Symbol,Period,CandleID);
double cClose = FBFB::iClose(Symbol,Period,CandleID);
if (SignalType == "continuous" || bartime < FBFB::iTime(Symbol,Period,1))
{
if (
(cOpen < cClose)
&& (cClose-cOpen >= toDigits(MinBodySize, Symbol))
&& (MaxBodySize <= 0 || cClose-cOpen <= toDigits(MaxBodySize, Symbol))
)
{
if (SignalType != "continuous") {
bartime = FBFB::iTime(Symbol,Period,1);
}
_callback_(1);
return;
}
}
_callback_(0);
}
};
template<typename T1,typename T2,typename T3>
class MDL_OncePerBar: public BlockCalls
{
public: /* Input Parameters */
T1 Symbol;
T2 Period;
T3 PassMaxTimes;
/* Static Parameters */
string tokens[];
int passes[];
datetime old_values[];
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_OncePerBar()
{
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
PassMaxTimes = (int)1;
}
public: /* The main method */
virtual void _execute_()
{
bool next = false;
string token = Symbol + IntegerToString(Period);
int index = ArraySearch(tokens, token);
if (index == -1)
{
index = ArraySize(tokens);
ArrayResize(tokens, index + 1);
ArrayResize(old_values, index + 1);
ArrayResize(passes, index + 1);
tokens[index] = token;
passes[index] = 0;
old_values[index] = 0;
}
if (PassMaxTimes > 0)
{
datetime new_value = FBFB::iTime(Symbol, Period, 1);
if (new_value == 0) {
Print("Failed to get the time from candle 1 on symbol ", Symbol, " and timeframe ", EnumToString((ENUM_TIMEFRAMES)Period), ". The history data needs to be fixed.");
}
if (new_value > old_values[index])
{
passes[index]++;
if (passes[index] >= PassMaxTimes)
{
old_values[index] = new_value;
passes[index] = 0;
}
next = true;
}
}
if (next) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename _T9_,typename T10,typename T11,typename T12,typename T13,typename T14,typename T15,typename T16,typename T17,typename T18,typename T19,typename T20,typename T21,typename T22,typename T23,typename T24,typename T25,typename T26,typename T27,typename T28,typename T29,typename T30,typename T31,typename T32,typename T33,typename T34,typename T35,typename T36,typename T37,typename _T37_,typename T38,typename _T38_,typename T39,typename _T39_,typename T40,typename T41,typename T42,typename T43,typename T44,typename _T44_,typename T45,typename _T45_,typename T46,typename _T46_,typename T47,typename T48,typename T49,typename T50,typename T51,typename _T51_,typename T52,typename T53,typename T54>
class MDL_BuyNow: public BlockCalls
{
public: /* Input Parameters */
T1 Group;
T2 Symbol;
T3 VolumeMode;
T4 VolumeSize;
T5 VolumeSizeRisk;
T6 VolumeRisk;
T7 VolumePercent;
T8 VolumeBlockPercent;
T9 dVolumeSize; virtual _T9_ _dVolumeSize_(){return(_T9_)0;
return NULL;
}
T10 FixedRatioUnitSize;
T11 FixedRatioDelta;
T12 mmTradesPool;
T13 mmMgInitialLots;
T14 mmMgMultiplyOnLoss;
T15 mmMgMultiplyOnProfit;
T16 mmMgAddLotsOnLoss;
T17 mmMgAddLotsOnProfit;
T18 mmMgResetOnLoss;
T19 mmMgResetOnProfit;
T20 mm1326InitialLots;
T21 mm1326Reverse;
T22 mmFiboInitialLots;
T23 mmDalembertInitialLots;
T24 mmDalembertReverse;
T25 mmLabouchereInitialLots;
T26 mmLabouchereList;
T27 mmLabouchereReverse;
T28 mmSeqBaseLots;
T29 mmSeqOnLoss;
T30 mmSeqOnProfit;
T31 mmSeqReverse;
T32 VolumeUpperLimit;
T33 StopLossMode;
T34 StopLossPips;
T35 StopLossPercentPrice;
T36 StopLossPercentTP;
T37 dlStopLoss; virtual _T37_ _dlStopLoss_(){return(_T37_)0;
return NULL;
}
T38 dpStopLoss; virtual _T38_ _dpStopLoss_(){return(_T38_)0;
return NULL;
}
T39 ddStopLoss; virtual _T39_ _ddStopLoss_(){return(_T39_)0;
return NULL;
}
T40 TakeProfitMode;
T41 TakeProfitPips;
T42 TakeProfitPercentPrice;
T43 TakeProfitPercentSL;
T44 dlTakeProfit; virtual _T44_ _dlTakeProfit_(){return(_T44_)0;
return NULL;
}
T45 dpTakeProfit; virtual _T45_ _dpTakeProfit_(){return(_T45_)0;
return NULL;
}
T46 ddTakeProfit; virtual _T46_ _ddTakeProfit_(){return(_T46_)0;
return NULL;
}
T47 ExpMode;
T48 ExpDays;
T49 ExpHours;
T50 ExpMinutes;
T51 dExp; virtual _T51_ _dExp_(){return(_T51_)0;
return NULL;
}
T52 Slippage;
T53 MyComment;
T54 ArrowColorBuy;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_BuyNow()
{
Group = (string)"";
Symbol = (string)CurrentSymbol();
VolumeMode = (string)"fixed";
VolumeSize = (double)0.1;
VolumeSizeRisk = (double)50.0;
VolumeRisk = (double)2.5;
VolumePercent = (double)100.0;
VolumeBlockPercent = (double)3.0;
FixedRatioUnitSize = (double)0.01;
FixedRatioDelta = (double)20.0;
mmTradesPool = (int)0;
mmMgInitialLots = (double)0.1;
mmMgMultiplyOnLoss = (double)2.0;
mmMgMultiplyOnProfit = (double)1.0;
mmMgAddLotsOnLoss = (double)0.0;
mmMgAddLotsOnProfit = (double)0.0;
mmMgResetOnLoss = (int)0;
mmMgResetOnProfit = (int)1;
mm1326InitialLots = (double)0.1;
mm1326Reverse = (bool)false;
mmFiboInitialLots = (double)0.1;
mmDalembertInitialLots = (double)0.1;
mmDalembertReverse = (bool)false;
mmLabouchereInitialLots = (double)0.1;
mmLabouchereList = (string)"1,2,3,4,5,6";
mmLabouchereReverse = (bool)false;
mmSeqBaseLots = (double)0.1;
mmSeqOnLoss = (string)"3,2,6";
mmSeqOnProfit = (string)"1";
mmSeqReverse = (bool)false;
VolumeUpperLimit = (double)0.0;
StopLossMode = (string)"fixed";
StopLossPips = (double)50.0;
StopLossPercentPrice = (double)0.55;
StopLossPercentTP = (double)100.0;
TakeProfitMode = (string)"fixed";
TakeProfitPips = (double)50.0;
TakeProfitPercentPrice = (double)0.55;
TakeProfitPercentSL = (double)100.0;
ExpMode = (string)"GTC";
ExpDays = (int)0;
ExpHours = (int)1;
ExpMinutes = (int)0;
Slippage = (ulong)4;
MyComment = (string)"";
ArrowColorBuy = (color)clrBlue;
}
public: /* The main method */
virtual void _execute_()
{
double sll = 0, slp = 0, tpl = 0, tpp = 0;
if (StopLossMode == "fixed") {slp = StopLossPips;}
else if (StopLossMode == "dynamicPips") {slp = _dpStopLoss_();}
else if (StopLossMode == "dynamicDigits") {slp = toPips(_ddStopLoss_(),Symbol);}
else if (StopLossMode == "dynamicLevel") {sll = _dlStopLoss_();}
else if (StopLossMode == "percentPrice") {sll = SymbolAsk(Symbol) - (SymbolAsk(Symbol) * StopLossPercentPrice / 100);}
if (TakeProfitMode == "fixed") {tpp = TakeProfitPips;}
else if (TakeProfitMode == "dynamicPips") {tpp = _dpTakeProfit_();}
else if (TakeProfitMode == "dynamicDigits") {tpp = toPips(_ddTakeProfit_(),Symbol);}
else if (TakeProfitMode == "dynamicLevel") {tpl = _dlTakeProfit_();}
else if (TakeProfitMode == "percentPrice") {tpl = SymbolAsk(Symbol) + (SymbolAsk(Symbol) * TakeProfitPercentPrice / 100);}
if (StopLossMode == "percentTP") {
if (tpp > 0) {slp = tpp*StopLossPercentTP/100;}
if (tpl > 0) {slp = toPips(MathAbs(SymbolAsk(Symbol) - tpl), Symbol)*StopLossPercentTP/100;}
}
if (TakeProfitMode == "percentSL") {
if (slp > 0) {tpp = slp*TakeProfitPercentSL/100;}
if (sll > 0) {tpp = toPips(MathAbs(SymbolAsk(Symbol) - sll), Symbol)*TakeProfitPercentSL/100;}
}
double lots = 0;
double pre_sll = sll;
if (pre_sll == 0) {
pre_sll = SymbolAsk(Symbol);
}
double pre_sl_pips = toPips(SymbolAsk(Symbol)-(pre_sll-toDigits(slp,Symbol)), Symbol);
if (VolumeMode == "fixed") {lots = DynamicLots(Symbol, VolumeMode, VolumeSize);}
else if (VolumeMode == "block-equity") {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
else if (VolumeMode == "block-balance") {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
else if (VolumeMode == "block-freemargin") {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
else if (VolumeMode == "equity") {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
else if (VolumeMode == "balance") {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
else if (VolumeMode == "freemargin") {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
else if (VolumeMode == "equityRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
else if (VolumeMode == "balanceRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
else if (VolumeMode == "freemarginRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
else if (VolumeMode == "fixedRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeSizeRisk, pre_sl_pips);}
else if (VolumeMode == "fixedRatio") {lots = DynamicLots(Symbol, VolumeMode, FixedRatioUnitSize, FixedRatioDelta);}
else if (VolumeMode == "dynamic") {lots = _dVolumeSize_();}
else if (VolumeMode == "1326") {lots = Bet1326(Group, Symbol, mmTradesPool, mm1326InitialLots, mm1326Reverse);}
else if (VolumeMode == "fibonacci") {lots = BetFibonacci(Group, Symbol, mmTradesPool, mmFiboInitialLots);}
else if (VolumeMode == "dalembert") {lots = BetDalembert(Group, Symbol, mmTradesPool, mmDalembertInitialLots, mmDalembertReverse);}
else if (VolumeMode == "labouchere") {lots = BetLabouchere(Group, Symbol, mmTradesPool, mmLabouchereInitialLots, mmLabouchereList, mmLabouchereReverse);}
else if (VolumeMode == "martingale") {lots = BetMartingale(Group, Symbol, mmTradesPool, mmMgInitialLots, mmMgMultiplyOnLoss, mmMgMultiplyOnProfit, mmMgAddLotsOnLoss, mmMgAddLotsOnProfit, mmMgResetOnLoss, mmMgResetOnProfit);}
else if (VolumeMode == "sequence") {lots = BetSequence(Group, Symbol, mmTradesPool, mmSeqBaseLots, mmSeqOnLoss, mmSeqOnProfit, mmSeqReverse);}
lots = AlignLots(Symbol, lots, 0, VolumeUpperLimit);
datetime exp = ExpirationTime(ExpMode,ExpDays,ExpHours,ExpMinutes,_dExp_());
long ticket = BuyNow(Symbol, lots, sll, tpl, slp, tpp, Slippage, (MagicStart+(int)Group), MyComment, ArrowColorBuy, exp);
if (ticket > 0) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6>
class MDL_SignalBearCandle: public BlockCalls
{
public: /* Input Parameters */
T1 SignalType;
T2 CandleID;
T3 MinBodySize;
T4 MaxBodySize;
T5 Symbol;
T6 Period;
/* Static Parameters */
datetime bartime;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_SignalBearCandle()
{
SignalType = (string)"continuous";
CandleID = (int)1;
MinBodySize = (double)5.0;
MaxBodySize = (double)0.0;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
/* Static Parameters (initial value) */
bartime = 0;
}
public: /* The main method */
virtual void _execute_()
{
double cOpen = FBFB::iOpen(Symbol,Period,CandleID);
double cClose = FBFB::iClose(Symbol,Period,CandleID);
if (SignalType == "continuous" || bartime < FBFB::iTime(Symbol,Period,1))
{
if (
(cClose < cOpen)
&& (cOpen-cClose >= toDigits(MinBodySize, Symbol))
&& (MaxBodySize <= 0 || cOpen-cClose <= toDigits(MaxBodySize, Symbol))
)
{
if (SignalType != "continuous") {
bartime = FBFB::iTime(Symbol,Period,1);
}
_callback_(1);
return;
}
}
_callback_(0);
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename _T9_,typename T10,typename T11,typename T12,typename T13,typename T14,typename T15,typename T16,typename T17,typename T18,typename T19,typename T20,typename T21,typename T22,typename T23,typename T24,typename T25,typename T26,typename T27,typename T28,typename T29,typename T30,typename T31,typename T32,typename T33,typename T34,typename T35,typename T36,typename T37,typename _T37_,typename T38,typename _T38_,typename T39,typename _T39_,typename T40,typename T41,typename T42,typename T43,typename T44,typename _T44_,typename T45,typename _T45_,typename T46,typename _T46_,typename T47,typename T48,typename T49,typename T50,typename T51,typename _T51_,typename T52,typename T53,typename T54>
class MDL_SellNow: public BlockCalls
{
public: /* Input Parameters */
T1 Group;
T2 Symbol;
T3 VolumeMode;
T4 VolumeSize;
T5 VolumeSizeRisk;
T6 VolumeRisk;
T7 VolumePercent;
T8 VolumeBlockPercent;
T9 dVolumeSize; virtual _T9_ _dVolumeSize_(){return(_T9_)0;
return NULL;
}
T10 FixedRatioUnitSize;
T11 FixedRatioDelta;
T12 mmTradesPool;
T13 mmMgInitialLots;
T14 mmMgMultiplyOnLoss;
T15 mmMgMultiplyOnProfit;
T16 mmMgAddLotsOnLoss;
T17 mmMgAddLotsOnProfit;
T18 mmMgResetOnLoss;
T19 mmMgResetOnProfit;
T20 mm1326InitialLots;
T21 mm1326Reverse;
T22 mmFiboInitialLots;
T23 mmDalembertInitialLots;
T24 mmDalembertReverse;
T25 mmLabouchereInitialLots;
T26 mmLabouchereList;
T27 mmLabouchereReverse;
T28 mmSeqBaseLots;
T29 mmSeqOnLoss;
T30 mmSeqOnProfit;
T31 mmSeqReverse;
T32 VolumeUpperLimit;
T33 StopLossMode;
T34 StopLossPips;
T35 StopLossPercentPrice;
T36 StopLossPercentTP;
T37 dlStopLoss; virtual _T37_ _dlStopLoss_(){return(_T37_)0;
return NULL;
}
T38 dpStopLoss; virtual _T38_ _dpStopLoss_(){return(_T38_)0;
return NULL;
}
T39 ddStopLoss; virtual _T39_ _ddStopLoss_(){return(_T39_)0;
return NULL;
}
T40 TakeProfitMode;
T41 TakeProfitPips;
T42 TakeProfitPercentPrice;
T43 TakeProfitPercentSL;
T44 dlTakeProfit; virtual _T44_ _dlTakeProfit_(){return(_T44_)0;
return NULL;
}
T45 dpTakeProfit; virtual _T45_ _dpTakeProfit_(){return(_T45_)0;
return NULL;
}
T46 ddTakeProfit; virtual _T46_ _ddTakeProfit_(){return(_T46_)0;
return NULL;
}
T47 ExpMode;
T48 ExpDays;
T49 ExpHours;
T50 ExpMinutes;
T51 dExp; virtual _T51_ _dExp_(){return(_T51_)0;
return NULL;
}
T52 Slippage;
T53 MyComment;
T54 ArrowColorSell;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_SellNow()
{
Group = (string)"";
Symbol = (string)CurrentSymbol();
VolumeMode = (string)"fixed";
VolumeSize = (double)0.1;
VolumeSizeRisk = (double)50.0;
VolumeRisk = (double)2.5;
VolumePercent = (double)100.0;
VolumeBlockPercent = (double)3.0;
FixedRatioUnitSize = (double)0.01;
FixedRatioDelta = (double)20.0;
mmTradesPool = (int)0;
mmMgInitialLots = (double)0.1;
mmMgMultiplyOnLoss = (double)2.0;
mmMgMultiplyOnProfit = (double)1.0;
mmMgAddLotsOnLoss = (double)0.0;
mmMgAddLotsOnProfit = (double)0.0;
mmMgResetOnLoss = (int)0;
mmMgResetOnProfit = (int)1;
mm1326InitialLots = (double)0.1;
mm1326Reverse = (bool)false;
mmFiboInitialLots = (double)0.1;
mmDalembertInitialLots = (double)0.1;
mmDalembertReverse = (bool)false;
mmLabouchereInitialLots = (double)0.1;
mmLabouchereList = (string)"1,2,3,4,5,6";
mmLabouchereReverse = (bool)false;
mmSeqBaseLots = (double)0.1;
mmSeqOnLoss = (string)"3,2,6";
mmSeqOnProfit = (string)"1";
mmSeqReverse = (bool)false;
VolumeUpperLimit = (double)0.0;
StopLossMode = (string)"fixed";
StopLossPips = (double)50.0;
StopLossPercentPrice = (double)0.55;
StopLossPercentTP = (double)100.0;
TakeProfitMode = (string)"fixed";
TakeProfitPips = (double)50.0;
TakeProfitPercentPrice = (double)0.55;
TakeProfitPercentSL = (double)100.0;
ExpMode = (string)"GTC";
ExpDays = (int)0;
ExpHours = (int)1;
ExpMinutes = (int)0;
Slippage = (ulong)4;
MyComment = (string)"";
ArrowColorSell = (color)clrRed;
}
public: /* The main method */
virtual void _execute_()
{
double sll = 0, slp = 0, tpl = 0, tpp = 0;
if (StopLossMode == "fixed") {slp = StopLossPips;}
else if (StopLossMode == "dynamicPips") {slp = _dpStopLoss_();}
else if (StopLossMode == "dynamicDigits") {slp = toPips(_ddStopLoss_(),Symbol);}
else if (StopLossMode == "dynamicLevel") {sll = _dlStopLoss_();}
else if (StopLossMode == "percentPrice") {sll = SymbolBid(Symbol) + (SymbolBid(Symbol) * StopLossPercentPrice / 100);}
if (TakeProfitMode == "fixed") {tpp = TakeProfitPips;}
else if (TakeProfitMode == "dynamicPips") {tpp = _dpTakeProfit_();}
else if (TakeProfitMode == "dynamicDigits") {tpp = toPips(_ddTakeProfit_(),Symbol);}
else if (TakeProfitMode == "dynamicLevel") {tpl = _dlTakeProfit_();}
else if (TakeProfitMode == "percentPrice") {tpl = SymbolBid(Symbol) - (SymbolBid(Symbol) * TakeProfitPercentPrice / 100);}
if (StopLossMode == "percentTP") {
if (tpp > 0) {slp = tpp*StopLossPercentTP/100;}
if (tpl > 0) {slp = toPips(MathAbs(SymbolBid(Symbol) - tpl), Symbol)*StopLossPercentTP/100;}
}
if (TakeProfitMode == "percentSL") {
if (slp > 0) {tpp = slp*TakeProfitPercentSL/100;}
if (sll > 0) {tpp = toPips(MathAbs(SymbolBid(Symbol) - sll), Symbol)*TakeProfitPercentSL/100;}
}
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), Symbol);
if (VolumeMode == "fixed") {lots = DynamicLots(Symbol, VolumeMode, VolumeSize);}
else if (VolumeMode == "block-equity") {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
else if (VolumeMode == "block-balance") {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
else if (VolumeMode == "block-freemargin") {lots = DynamicLots(Symbol, VolumeMode, VolumeBlockPercent);}
else if (VolumeMode == "equity") {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
else if (VolumeMode == "balance") {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
else if (VolumeMode == "freemargin") {lots = DynamicLots(Symbol, VolumeMode, VolumePercent);}
else if (VolumeMode == "equityRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
else if (VolumeMode == "balanceRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
else if (VolumeMode == "freemarginRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeRisk, pre_sl_pips);}
else if (VolumeMode == "fixedRisk") {lots = DynamicLots(Symbol, VolumeMode, VolumeSizeRisk, pre_sl_pips);}
else if (VolumeMode == "fixedRatio") {lots = DynamicLots(Symbol, VolumeMode, FixedRatioUnitSize, FixedRatioDelta);}
else if (VolumeMode == "dynamic") {lots = _dVolumeSize_();}
else if (VolumeMode == "1326") {lots = Bet1326(Group, Symbol, mmTradesPool, mm1326InitialLots, mm1326Reverse);}
else if (VolumeMode == "fibonacci") {lots = BetFibonacci(Group, Symbol, mmTradesPool, mmFiboInitialLots);}
else if (VolumeMode == "dalembert") {lots = BetDalembert(Group, Symbol, mmTradesPool, mmDalembertInitialLots, mmDalembertReverse);}
else if (VolumeMode == "labouchere") {lots = BetLabouchere(Group, Symbol, mmTradesPool, mmLabouchereInitialLots, mmLabouchereList, mmLabouchereReverse);}
else if (VolumeMode == "martingale") {lots = BetMartingale(Group, Symbol, mmTradesPool, mmMgInitialLots, mmMgMultiplyOnLoss, mmMgMultiplyOnProfit, mmMgAddLotsOnLoss, mmMgAddLotsOnProfit, mmMgResetOnLoss, mmMgResetOnProfit);}
else if (VolumeMode == "sequence") {lots = BetSequence(Group, Symbol, mmTradesPool, mmSeqBaseLots, mmSeqOnLoss, mmSeqOnProfit, mmSeqReverse);}
lots = AlignLots(Symbol, lots, 0, VolumeUpperLimit);
datetime exp = ExpirationTime(ExpMode,ExpDays,ExpHours,ExpMinutes,_dExp_());
long ticket = SellNow(Symbol, lots, sll, tpl, slp, tpp, Slippage, (MagicStart+(int)Group), MyComment, ArrowColorSell, exp);
if (ticket > 0) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5>
class MDL_IfOpenedOrders: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_IfOpenedOrders()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
}
public: /* The main method */
virtual void _execute_()
{
bool exist = false;
for (int index = TradesTotal()-1; index >= 0; index--)
{
if (TradeSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells))
{
exist = true;
break;
}
}
if (exist == true) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename T10>
class MDL_LoopStartTrades: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
T6 LoopDirection;
T7 LoopSkip;
T8 LoopEvery;
T9 LoopLimit;
T10 PassEnd;
/* Static Parameters */
double trades[][2];
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_LoopStartTrades()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
LoopDirection = (string)"newest-to-oldest";
LoopSkip = (int)0;
LoopEvery = (int)0;
LoopLimit = (int)0;
PassEnd = (int)0;
}
public: /* The main method */
virtual void _execute_()
{
int saved_type = attrTypeInLoop();
ulong saved_ticket = attrTicketInLoop(); // This ticket number will be reloaded at the end of this loop, so if we are in another overlapping loop - it will continue using it's last used ticket number
int total = TradesTotal();
int count = 0;
int skip = -1;
int every = 0;
bool get_from_array = false;
int i_start = 0, i_stop = 0, i_inc = 0, i = 0;
if (LoopDirection == "newest-to-oldest")
{
i_start = total-1;
i_stop = 0;
i_inc = -1;
}
else if (LoopDirection == "oldest-to-newest")
{
i_start = 0;
i_stop = total-1;
i_inc = 1;
}
else if (LoopDirection == "profitable-first" || LoopDirection == "profitable-last")
{
int last_index = -1;
get_from_array = true;
ArrayResize(trades,0);
int size = 0;
for (int pos=0; pos < total; pos++)
{
if (!TradeSelectByIndex(pos, GroupMode, Group, SymbolMode, Symbol, BuysOrSells)) continue;
size++;
ArrayResize(trades,size);
trades[size-1][0] = FBFB::OrderProfit();
trades[size-1][1] = (double)FBFB::OrderTicket();
}
if (size > 0)
{
FBFB::ArraySort(trades);
last_index = size - 1;
}
i_start = last_index;
i_stop = 0;
i_inc = -1;
if (LoopDirection == "profitable-last")
{
i_start = 0;
i_stop = last_index;
i_inc = 1;
}
}
i = i_start - i_inc;
while (true)
{
if (i == i_stop) break;
i = i + i_inc;
if (FXD_CONTINUE == true)
{
FXD_BREAK = false;
FXD_CONTINUE = false;
}
else if (FXD_BREAK == true)
{
FXD_BREAK = false;
FXD_CONTINUE = false;
break;
}
if (get_from_array)
{
if (!TradeSelectByTicket((ulong)trades[i][1])) continue;
}
else
{
if (!TradeSelectByIndex(i, GroupMode, Group, SymbolMode, Symbol, BuysOrSells)) continue;
}
skip++;
if (LoopSkip <= skip && (count < LoopLimit || LoopLimit == 0))
{
if (LoopEvery > 0)
{
every++;
if (every < LoopEvery) {continue;} else {every = 0;}
}
count++;
attrTypeInLoop(1);
attrTicketInLoop(FBFB::OrderTicket());
_callback_(1);
if (count == LoopLimit) break;
}
if (LoopDirection == "oldest-to-newest")
{
if (i_stop > TradesTotal()-1)
{
i_stop = TradesTotal()-1;
i--;
}
}
}
attrTypeInLoop(saved_type);
attrTicketInLoop(saved_ticket); // Reloading Ticket number from the overlapping loop (if any)
FXD_BREAK = false;
FXD_CONTINUE = false;
if (
(PassEnd == 0)
|| (PassEnd == 1 && count > 0)
|| (PassEnd == 2 && count == 0)
) {
_callback_(0);
}
}
};
template<typename T1,typename _T1_,typename T2,typename T3,typename _T3_>
class MDL_Formula_1: public BlockCalls
{
public: /* Input Parameters */
T1 Lo; virtual _T1_ _Lo_(){return(_T1_)0;
return NULL;
}
T2 compare;
T3 Ro; virtual _T3_ _Ro_(){return(_T3_)0;
return NULL;
}
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_Formula_1()
{
compare = (string)"+";
}
public: /* The main method */
virtual void _execute_()
{
_T1_ lo = _Lo_();
if (typename(_T1_) != "string" && MathAbs(lo) == EMPTY_VALUE) {return;}
_T3_ ro = _Ro_();
if (typename(_T3_) != "string" && MathAbs(ro) == EMPTY_VALUE) {return;}
v::nearby_bs = formula(compare, lo, ro);
_callback_(1);
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename _T6_,typename T7,typename _T7_,typename T8,typename T9,typename _T9_,typename T10,typename T11,typename T12,typename T13>
class MDL_NoNearbyRunning: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
T6 Time1; virtual _T6_ _Time1_(){return(_T6_)0;
return NULL;
}
T7 Time2; virtual _T7_ _Time2_(){return(_T7_)0;
return NULL;
}
T8 ModeBasePrice;
T9 BasePrice; virtual _T9_ _BasePrice_(){return(_T9_)0;
return NULL;
}
T10 ModeRange;
T11 RangePips;
T12 RangeFraction;
T13 RangePosition;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_NoNearbyRunning()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
ModeBasePrice = (string)"current";
ModeRange = (string)"pips";
RangePips = (double)10.0;
RangeFraction = (double)0.0010;
RangePosition = (int)0;
}
public: /* The main method */
virtual void _execute_()
{
int next = true;
double price = 0;
bool use_current_price = (ModeBasePrice == "current");
datetime t1 = _Time1_();
datetime t2 = _Time2_();
if (t1 >= TimeCurrent()) t1 = 0;
if (!use_current_price)
{
price = _BasePrice_();
}
for (int index = TradesTotal()-1; index >= 0; index--)
{
if (TradeSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells))
{
if ((t1 < t2 && FBFB::OrderOpenTime() < t1) || FBFB::OrderOpenTime() > t2)
{
continue;
}
double distance = RangeFraction;
if (ModeRange == "pips") {distance = toDigits(RangePips, Symbol);}
if (FBFB::OrderType() == 0) // buy?
{
if (use_current_price) {price = SymbolInfoDouble(Symbol, SYMBOL_ASK);}
switch (RangePosition)
{
case 0: if (price <= (FBFB::OrderOpenPrice() + distance/2) && price >= (FBFB::OrderOpenPrice() - distance/2)) {next = false;} break;
case 1: if (price <= FBFB::OrderOpenPrice() + distance && price >= FBFB::OrderOpenPrice()) {next = false;} break;
case 2: if (price <= FBFB::OrderOpenPrice() && price >= FBFB::OrderOpenPrice() - distance) {next = false;} break;
}
}
else
{
if (use_current_price) {price = SymbolInfoDouble(Symbol, SYMBOL_BID);}
switch (RangePosition)
{
case 0: if (price <= (FBFB::OrderOpenPrice() + distance/2) && price >= (FBFB::OrderOpenPrice() - distance/2)) {next = false;} break;
case 1: if (price <= FBFB::OrderOpenPrice() && price >= FBFB::OrderOpenPrice() - distance) {next = false;} break;
case 2: if (price <= FBFB::OrderOpenPrice() + distance && price >= FBFB::OrderOpenPrice()) {next = false;} break;
}
}
if (next == false) {break;}
}
}
if (next == true) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename _T1_,typename T2,typename T3,typename _T3_>
class MDL_Formula_2: public BlockCalls
{
public: /* Input Parameters */
T1 Lo; virtual _T1_ _Lo_(){return(_T1_)0;
return NULL;
}
T2 compare;
T3 Ro; virtual _T3_ _Ro_(){return(_T3_)0;
return NULL;
}
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_Formula_2()
{
compare = (string)"+";
}
public: /* The main method */
virtual void _execute_()
{
_T1_ lo = _Lo_();
if (typename(_T1_) != "string" && MathAbs(lo) == EMPTY_VALUE) {return;}
_T3_ ro = _Ro_();
if (typename(_T3_) != "string" && MathAbs(ro) == EMPTY_VALUE) {return;}
v::nearby_bs = formula(compare, lo, ro);
_callback_(1);
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename T10,typename T11,typename T12,typename T13>
class MDL_CheckUProfit: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
T6 EachProfitMode;
T7 EachCompare;
T8 EachProfitAmount;
T9 EachProfitAmountPips;
T10 ProfitMode;
T11 Compare;
T12 ProfitAmount;
T13 ProfitAmountPips;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_CheckUProfit()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
EachProfitMode = (string)"";
EachCompare = (string)">";
EachProfitAmount = (double)0.0;
EachProfitAmountPips = (double)10.0;
ProfitMode = (string)"money";
Compare = (string)">";
ProfitAmount = (double)0.0;
ProfitAmountPips = (double)10.0;
}
public: /* The main method */
virtual void _execute_()
{
double avgPrice = 0;
double avgLoad = 0;
double avgLots = 0;
double profitMoney = 0;
double profitPips = 0;
double pipsSum = 0;
int tradesCount = 0;
for (int index = TradesTotal()-1; index >= 0; index--) {
if (TradeSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells)) {
double OrderOpenPrice = OrderChildOpenPrice();
double tradeProfit = NormalizeDouble(FBFB::OrderProfit() + FBFB::OrderSwap() + FBFB::OrderCommission(), 2);
if (EachProfitMode == "money") {
if (compare(EachCompare, tradeProfit, EachProfitAmount)) {/* do nothing */} else {continue;}
}
else if (EachProfitMode == "pips") {
double individual_profit = toPips(FBFB::OrderClosePrice() - OrderOpenPrice, FBFB::OrderSymbol());
if (FBFB::OrderType() == 1) {individual_profit = -1 * individual_profit;}
if (compare(EachCompare, individual_profit, EachProfitAmountPips)) {/* do nothing*/} else {continue;}
}
profitMoney += tradeProfit;
if (ProfitMode == "pips" || ProfitMode == "pips-sum") {
if (IsOrderTypeBuy()) {
pipsSum += toPips(FBFB::OrderClosePrice() - OrderOpenPrice, FBFB::OrderSymbol());
avgLoad += OrderOpenPrice * FBFB::OrderLots();
avgLots += FBFB::OrderLots();
}
else {
pipsSum += toPips(OrderOpenPrice - FBFB::OrderClosePrice(), FBFB::OrderSymbol());
avgLoad -= OrderOpenPrice * FBFB::OrderLots();
avgLots -= FBFB::OrderLots();
}
}
tradesCount += 1;
}
}
if (ProfitMode == "pips") {
avgPrice = 0;
if (avgLots != 0) {
avgPrice = (avgLoad / avgLots);
}
if (avgPrice != 0) {
if (avgLots > 0) {
profitPips = SymbolInfoDouble(Symbol, SYMBOL_BID) - avgPrice;
}
else {
profitPips = avgPrice - SymbolInfoDouble(Symbol, SYMBOL_ASK);
}
profitPips = toPips(profitPips, Symbol);
}
}
if (
(ProfitMode == "money" && (CompareValues(Compare, profitMoney, ProfitAmount)))
|| (ProfitMode == "pips" && (CompareValues(Compare, profitPips, ProfitAmountPips)))
|| (ProfitMode == "pips-sum" && (CompareValues(Compare, pipsSum, ProfitAmountPips)))
) {
_callback_(1);
}
else {
_callback_(0);
}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8>
class MDL_CloseOpened: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
T6 OrderMinutes;
T7 Slippage;
T8 ArrowColor;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_CloseOpened()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
OrderMinutes = (int)0;
Slippage = (ulong)4;
ArrowColor = (color)clrDeepPink;
}
public: /* The main method */
virtual void _execute_()
{
int closed_count = 0;
bool finished = false;
while (finished == false)
{
int count = 0;
for (int index = TradesTotal()-1; index >= 0; index--)
{
if (TradeSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells))
{
datetime time_diff = TimeCurrent() - FBFB::OrderOpenTime();
if (time_diff < 0) {time_diff = 0;} // this actually happens sometimes
if (time_diff >= 60 * OrderMinutes)
{
if (CloseTrade(FBFB::OrderTicket(), Slippage, ArrowColor))
{
closed_count++;
}
count++;
}
}
}
if (count == 0) {finished = true;}
}
_callback_(1);
}
};
class MDL_Pass: public BlockCalls
{
virtual void _callback_(int r) {return;}
public: /* The main method */
virtual void _execute_()
{
_callback_(1);
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename T10,typename T11,typename T12,typename T13,typename T14,typename T15,typename T16,typename _T16_,typename T17,typename T18,typename T19,typename T20,typename _T20_,typename T21,typename T22,typename T23,typename T24,typename _T24_,typename T25,typename T26,typename T27,typename T28,typename _T28_,typename T29,typename T30,typename T31,typename T32,typename _T32_,typename T33,typename T34,typename T35,typename T36,typename _T36_,typename T37,typename T38,typename T39,typename T40,typename _T40_,typename T41,typename T42,typename T43,typename T44,typename _T44_,typename T45,typename T46>
class MDL_CommentEx: public BlockCalls
{
public: /* Input Parameters */
T1 Title;
T2 ObjChartSubWindow;
T3 ObjCorner;
T4 ObjX;
T5 ObjY;
T6 ObjTitleFont;
T7 ObjTitleFontColor;
T8 ObjTitleFontSize;
T9 ObjLabelsFont;
T10 ObjLabelsFontColor;
T11 ObjLabelsFontSize;
T12 ObjFont;
T13 ObjFontColor;
T14 ObjFontSize;
T15 Label1;
T16 Value1; virtual _T16_ _Value1_(){return(_T16_)0;
return NULL;
}
T17 FormatNumber1;
T18 FormatTime1;
T19 Label2;
T20 Value2; virtual _T20_ _Value2_(){return(_T20_)0;
return NULL;
}
T21 FormatNumber2;
T22 FormatTime2;
T23 Label3;
T24 Value3; virtual _T24_ _Value3_(){return(_T24_)0;
return NULL;
}
T25 FormatNumber3;
T26 FormatTime3;
T27 Label4;
T28 Value4; virtual _T28_ _Value4_(){return(_T28_)0;
return NULL;
}
T29 FormatNumber4;
T30 FormatTime4;
T31 Label5;
T32 Value5; virtual _T32_ _Value5_(){return(_T32_)0;
return NULL;
}
T33 FormatNumber5;
T34 FormatTime5;
T35 Label6;
T36 Value6; virtual _T36_ _Value6_(){return(_T36_)0;
return NULL;
}
T37 FormatNumber6;
T38 FormatTime6;
T39 Label7;
T40 Value7; virtual _T40_ _Value7_(){return(_T40_)0;
return NULL;
}
T41 FormatNumber7;
T42 FormatTime7;
T43 Label8;
T44 Value8; virtual _T44_ _Value8_(){return(_T44_)0;
return NULL;
}
T45 FormatNumber8;
T46 FormatTime8;
/* Static Parameters */
bool initialized;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_CommentEx()
{
Title = (string)"Comment Message";
ObjChartSubWindow = (string)"";
ObjCorner = (int)CORNER_LEFT_UPPER;
ObjX = (int)5;
ObjY = (int)24;
ObjTitleFont = (string)"Georgia";
ObjTitleFontColor = (color)clrGold;
ObjTitleFontSize = (int)13;
ObjLabelsFont = (string)"Verdana";
ObjLabelsFontColor = (color)clrDarkGray;
ObjLabelsFontSize = (int)10;
ObjFont = (string)"Verdana";
ObjFontColor = (color)clrWhite;
ObjFontSize = (int)10;
Label1 = (string)"";
FormatNumber1 = (int)EMPTY_VALUE;
FormatTime1 = (int)EMPTY_VALUE;
Label2 = (string)"";
FormatNumber2 = (int)EMPTY_VALUE;
FormatTime2 = (int)EMPTY_VALUE;
Label3 = (string)"";
FormatNumber3 = (int)EMPTY_VALUE;
FormatTime3 = (int)EMPTY_VALUE;
Label4 = (string)"";
FormatNumber4 = (int)EMPTY_VALUE;
FormatTime4 = (int)EMPTY_VALUE;
Label5 = (string)"";
FormatNumber5 = (int)EMPTY_VALUE;
FormatTime5 = (int)EMPTY_VALUE;
Label6 = (string)"";
FormatNumber6 = (int)EMPTY_VALUE;
FormatTime6 = (int)EMPTY_VALUE;
Label7 = (string)"";
FormatNumber7 = (int)EMPTY_VALUE;
FormatTime7 = (int)EMPTY_VALUE;
Label8 = (string)"";
FormatNumber8 = (int)EMPTY_VALUE;
FormatTime8 = (int)EMPTY_VALUE;
/* Static Parameters (initial value) */
initialized = false;
}
public: /* The main method */
virtual void _execute_()
{
if (!MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_VISUAL_MODE))
{
long ObjChartID = 0;
int ObjAnchor = ANCHOR_LEFT;
if (ObjCorner == CORNER_RIGHT_UPPER || ObjCorner == CORNER_RIGHT_LOWER)
{
ObjAnchor = ANCHOR_RIGHT;
}
string namebase = "fxd_cmnt_" + __block_user_number;
int subwindow = WindowFindVisible(ObjChartID, ObjChartSubWindow);
if (subwindow >= 0)
{
if ((string)Title != "")
{
string nametitle = namebase;
if(FBFB::ObjectFind(ObjChartID, nametitle) < 0)
{
if (!FBFB::ObjectCreate(ObjChartID, nametitle, OBJ_LABEL, subwindow, 0, 0, 0, 0))
{
Print(__FUNCTION__, ": failed to create text object! Error code = ", FBFB::GetLastError());
}
else
{
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_FONTSIZE, (int)(ObjTitleFontSize));
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_COLOR, ObjTitleFontColor);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_BACK, 0);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_SELECTABLE, 1);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_SELECTED, 0);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_HIDDEN, 1);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_CORNER, ObjCorner);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_ANCHOR, ObjAnchor);
FBFB::ObjectSetString(ObjChartID, nametitle, OBJPROP_FONT, ObjTitleFont);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_XDISTANCE, ObjX);
FBFB::ObjectSetInteger(ObjChartID, nametitle, OBJPROP_YDISTANCE, ObjY);
}
}
else
{
ObjX = (int)FBFB::ObjectGetInteger(ObjChartID, nametitle, OBJPROP_XDISTANCE);
ObjY = (int)FBFB::ObjectGetInteger(ObjChartID, nametitle, OBJPROP_YDISTANCE);
}
FBFB::ObjectSetString(ObjChartID, nametitle, OBJPROP_TEXT, (string)Title);
ObjY = (int)(ObjY + ObjTitleFontSize / 3);
}
for (int i = 1; i <= 8; i++)
{
string text = "";
string textlbl = "";
switch(i)
{
case 1:
{
if (Label1 != "")
{
textlbl = Label1;
text = FormatValueForPrinting(_Value1_(), FormatNumber1, FormatTime1);
}
break;
}
case 2:
{
if (Label2 != "")
{
textlbl = Label2;
text = FormatValueForPrinting(_Value2_(), FormatNumber2, FormatTime2);
}
break;
}
case 3:
{
if (Label3 != "")
{
textlbl = Label3;
text = FormatValueForPrinting(_Value3_(), FormatNumber3, FormatTime3);
}
break;
}
case 4:
{
if (Label4 != "")
{
textlbl = Label4;
text = FormatValueForPrinting(_Value4_(), FormatNumber4, FormatTime4);
}
break;
}
case 5:
{
if (Label5 != "")
{
textlbl = Label5;
text = FormatValueForPrinting(_Value5_(), FormatNumber5, FormatTime5);
}
break;
}
case 6:
{
if (Label6 != "")
{
textlbl = Label6;
text = FormatValueForPrinting(_Value6_(), FormatNumber6, FormatTime6);
}
break;
}
case 7:
{
if (Label7 != "")
{
textlbl = Label7;
text = FormatValueForPrinting(_Value7_(), FormatNumber7, FormatTime7);
}
break;
}
case 8:
{
if (Label8 != "")
{
textlbl = Label8;
text = FormatValueForPrinting(_Value8_(), FormatNumber8, FormatTime8);
}
break;
}
}
string name = namebase + "_" + (string)i;
string namelbl = name + "_l";
if (textlbl == "")
{
if (!initialized)
{
FBFB::ObjectDelete(ObjChartID, namelbl);
FBFB::ObjectDelete(ObjChartID, name);
}
continue;
}
if (FBFB::ObjectFind(ObjChartID, name) < 0)
{
if (textlbl == "")
{
continue;
}
if (FBFB::ObjectCreate(ObjChartID, namelbl, OBJ_LABEL, subwindow, 0, 0, 0, 0))
{
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_CORNER, ObjCorner);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_ANCHOR, ObjAnchor);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_BACK, 0);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_SELECTABLE, 0);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_SELECTED, 0);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_HIDDEN, 1);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_FONTSIZE, ObjLabelsFontSize);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_COLOR, ObjLabelsFontColor);
FBFB::ObjectSetString(ObjChartID, namelbl, OBJPROP_FONT, ObjLabelsFont);
}
else
{
Print(__FUNCTION__, ": failed to create text object! Error code = ", FBFB::GetLastError());
}
if (FBFB::ObjectCreate(ObjChartID, name, OBJ_LABEL, subwindow, 0, 0, 0, 0))
{
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_CORNER, ObjCorner);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_ANCHOR, ObjAnchor);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_BACK, 0);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_SELECTABLE, 0);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_SELECTED, 0);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_HIDDEN, 1);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_FONTSIZE, ObjFontSize);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_COLOR, ObjFontColor);
FBFB::ObjectSetString(ObjChartID, name, OBJPROP_FONT, ObjFont);
}
else
{
Print(__FUNCTION__, ": failed to create text object! Error code = ", FBFB::GetLastError());
}
}
else
{
if (textlbl == "")
{
FBFB::ObjectDelete(ObjChartID, namelbl);
FBFB::ObjectDelete(ObjChartID, name);
continue;
}
}
ObjY = (int)(ObjY + ObjFontSize + ObjFontSize/2);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_XDISTANCE, ObjX);
FBFB::ObjectSetInteger(ObjChartID, namelbl, OBJPROP_YDISTANCE, ObjY);
FBFB::ObjectSetString(ObjChartID, namelbl, OBJPROP_TEXT, (string)textlbl);
int x = 0;
int xsizelbl = (int)FBFB::ObjectGetInteger(ObjChartID, namelbl, OBJPROP_XSIZE);
if (xsizelbl == 0) {
xsizelbl = (int)(StringLen((string)textlbl) * ObjFontSize / 1.5 + ObjFontSize / 2);
}
x = ObjX + (xsizelbl + ObjFontSize/2);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_XDISTANCE, x);
FBFB::ObjectSetInteger(ObjChartID, name, OBJPROP_YDISTANCE, ObjY);
FBFB::ObjectSetString(ObjChartID, name, OBJPROP_TEXT, (string)text);
}
ChartRedraw();
}
initialized = true;
}
_callback_(1);
}
};
class MDLIC_indicators_iMA
{
public: /* Input Parameters */
int MAperiod;
int MAshift;
ENUM_MA_METHOD MAmethod;
ENUM_APPLIED_PRICE AppliedPrice;
string Symbol;
ENUM_TIMEFRAMES Period;
int Shift;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_indicators_iMA()
{
MAperiod = (int)14;
MAshift = (int)0;
MAmethod = (ENUM_MA_METHOD)MODE_SMA;
AppliedPrice = (ENUM_APPLIED_PRICE)PRICE_CLOSE;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
Shift = (int)0;
}
public: /* The main method */
double _execute_()
{
return FBFB::iMA(Symbol, Period, MAperiod, MAshift, MAmethod, AppliedPrice, Shift + FXD_MORE_SHIFT);
}
};
class MDLIC_candles_candles
{
public: /* Input Parameters */
string iOHLC;
string ModeCandleFindBy;
int CandleID;
string TimeStamp;
string Symbol;
ENUM_TIMEFRAMES Period;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_candles_candles()
{
iOHLC = (string)"iClose";
ModeCandleFindBy = (string)"id";
CandleID = (int)0;
TimeStamp = (string)"00:00";
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
}
public: /* The main method */
double _execute_()
{
int digits = (int)SymbolInfoInteger(Symbol, SYMBOL_DIGITS);
double O[];
double H[];
double L[];
double C[];
long cTickVolume[];
long cRealVolume[];
datetime T[];
double retval = EMPTY_VALUE;
int cID = CandleID;
if (ModeCandleFindBy == "time")
{
cID = iCandleID(Symbol, Period, StringToTimeEx(TimeStamp, "server"));
}
cID = cID + FXD_MORE_SHIFT;
if (iOHLC == "iOpen")
{
if (FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1) retval = O[0];
}
else if (iOHLC == "iHigh")
{
if (FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1) retval = H[0];
}
else if (iOHLC == "iLow")
{
if (FBFB::CopyLow(Symbol,Period,cID,1,L) > -1) retval = L[0];
}
else if (iOHLC == "iClose")
{
if (FBFB::CopyClose(Symbol,Period,cID,1,C) > -1) retval = C[0];
}
else if (iOHLC == "iVolume" || iOHLC == "iTickVolume")
{
if (FBFB::CopyTickVolume(Symbol,Period,cID,1,cTickVolume) > -1) retval = (double)cTickVolume[0];
return retval;
}
else if (iOHLC == "iRealVolume")
{
if (CopyRealVolume(Symbol,Period,cID,1,cRealVolume) > -1) retval = (double)cRealVolume[0];
return retval;
}
else if (iOHLC == "iTime")
{
if (FBFB::CopyTime(Symbol,Period,cID,1,T) > -1) retval = (double)T[0];
return retval;
}
else if (iOHLC == "iMedian")
{
if (
FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
&& FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
)
{
retval = ((L[0]+H[0])/2);
}
}
else if (iOHLC == "iTypical")
{
if (
FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
&& FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
)
{
retval = ((L[0]+H[0]+C[0])/3);
}
}
else if (iOHLC == "iAverage")
{
if (
FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
&& FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
)
{
retval = ((L[0]+H[0]+C[0]+C[0])/4);
}
}
else if (iOHLC=="iTotal")
{
if (
FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
)
{
retval = toPips(MathAbs(H[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBody")
{
if (
FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
)
{
retval = toPips(MathAbs(C[0]-O[0]),Symbol);
}
}
else if (iOHLC == "iUpperWick")
{
if (
FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
)
{
retval = (C[0] > O[0]) ? toPips(MathAbs(H[0]-C[0]),Symbol) : toPips(MathAbs(H[0]-O[0]),Symbol);
}
}
else if (iOHLC == "iBottomWick")
{
if (
FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
)
{
retval = (C[0] > O[0]) ? toPips(MathAbs(O[0]-L[0]),Symbol) : toPips(MathAbs(C[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iGap")
{
if (
FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID+1,1,C) > -1
)
{
retval = toPips(MathAbs(O[0]-C[0]),Symbol);
}
}
else if (iOHLC == "iBullTotal")
{
if (
FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
&& C[0] > O[0]
)
{
retval = toPips((H[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBullBody")
{
if (
FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] > O[0]
)
{
retval = toPips((C[0]-O[0]),Symbol);
}
}
else if (iOHLC == "iBullUpperWick")
{
if (
FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] > O[0]
)
{
retval = toPips((H[0]-C[0]),Symbol);
}
}
else if (iOHLC == "iBullBottomWick")
{
if (
FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
&& FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] > O[0]
)
{
retval = toPips((O[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBearTotal")
{
if (
FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
&& C[0] < O[0]
)
{
retval = toPips((H[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBearBody")
{
if (
FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] < O[0]
)
{
retval = toPips((O[0]-C[0]),Symbol);
}
}
else if (iOHLC == "iBearUpperWick")
{
if (
FBFB::CopyHigh(Symbol,Period,cID,1,H) > -1
&& FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] < O[0]
)
{
retval = toPips((H[0]-O[0]),Symbol);
}
}
else if (iOHLC == "iBearBottomWick")
{
if (
FBFB::CopyLow(Symbol,Period,cID,1,L) > -1
&& FBFB::CopyOpen(Symbol,Period,cID,1,O) > -1
&& FBFB::CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] < O[0]
)
{
retval = toPips((C[0]-L[0]),Symbol);
}
}
return NormalizeDouble(retval, digits);
}
};
class MDLIC_value_value
{
public: /* Input Parameters */
double Value;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_value_value()
{
Value = (double)1.0;
}
public: /* The main method */
double _execute_()
{
return Value;
}
};
class MDLIC_value_time
{
public: /* Input Parameters */
int ModeTime;
int TimeSource;
string TimeStamp;
int TimeCandleID;
string TimeMarket;
ENUM_TIMEFRAMES TimeCandleTimeframe;
int TimeComponentYear;
int TimeComponentMonth;
double TimeComponentDay;
double TimeComponentHour;
double TimeComponentMinute;
int TimeComponentSecond;
datetime TimeValue;
int ModeTimeShift;
int TimeShiftYears;
int TimeShiftMonths;
int TimeShiftWeeks;
double TimeShiftDays;
double TimeShiftHours;
double TimeShiftMinutes;
int TimeShiftSeconds;
bool TimeSkipWeekdays;
/* Static Parameters */
datetime retval;
datetime retval0;
datetime Time[];
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_value_time()
{
ModeTime = (int)0;
TimeSource = (int)0;
TimeStamp = (string)"00:00";
TimeCandleID = (int)1;
TimeMarket = (string)"";
TimeCandleTimeframe = (ENUM_TIMEFRAMES)0;
TimeComponentYear = (int)0;
TimeComponentMonth = (int)0;
TimeComponentDay = (double)0.0;
TimeComponentHour = (double)12.0;
TimeComponentMinute = (double)0.0;
TimeComponentSecond = (int)0;
TimeValue = (datetime)0;
ModeTimeShift = (int)0;
TimeShiftYears = (int)0;
TimeShiftMonths = (int)0;
TimeShiftWeeks = (int)0;
TimeShiftDays = (double)0.0;
TimeShiftHours = (double)0.0;
TimeShiftMinutes = (double)0.0;
TimeShiftSeconds = (int)0;
TimeSkipWeekdays = (bool)false;
/* Static Parameters (initial value) */
retval = 0;
retval0 = 0;
}
public: /* The main method */
datetime _execute_()
{
if (TimeMarket == "") TimeMarket = Symbol();
if (ModeTime == 0)
{
if (TimeSource == 0) {retval = TimeCurrent();}
else if (TimeSource == 1) {retval = TimeLocal() + (TimeCurrent() - TimeLocal());}
else if (TimeSource == 2) {retval = TimeGMT() + (TimeCurrent() - TimeGMT());}
}
else if (ModeTime == 1)
{
retval = StringToTime(TimeStamp);
retval0 = retval;
}
else if (ModeTime==2)
{
retval = TimeFromComponents(TimeSource, TimeComponentYear, TimeComponentMonth, TimeComponentDay, TimeComponentHour, TimeComponentMinute, TimeComponentSecond);
}
else if (ModeTime == 3)
{
ArraySetAsSeries(Time,true);
FBFB::CopyTime(TimeMarket,TimeCandleTimeframe,TimeCandleID,1,Time);
retval = Time[0];
}
else if (ModeTime == 4)
{
retval = TimeValue;
}
if (ModeTimeShift > 0)
{
int sh = 1;
if (ModeTimeShift == 1) {sh = -1;}
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 = (int)MathFloor(TimeComponentDay);
hour = (int)(MathFloor(TimeComponentHour) + (24 * (TimeComponentDay - MathFloor(TimeComponentDay))));
minute = (int)(MathFloor(TimeComponentMinute) + (60 * (TimeComponentHour - MathFloor(TimeComponentHour))));
second = (int)(TimeComponentSecond + (60 * (TimeComponentMinute - MathFloor(TimeComponentMinute))));
}
else {
year = FBFB::TimeYear(retval);
month = FBFB::TimeMonth(retval);
day = FBFB::TimeDay(retval);
hour = FBFB::TimeHour(retval);
minute = FBFB::TimeMinute(retval);
second = FBFB::TimeSeconds(retval);
}
year = year + TimeShiftYears * sh;
month = month + TimeShiftMonths * sh;
if (month < 0) {month = 12 - month;}
else if (month > 12) {month = month - 12;}
retval = StringToTime(IntegerToString(year)+"."+IntegerToString(month)+"."+IntegerToString(day)+" "+IntegerToString(hour)+":"+IntegerToString(minute)+":"+IntegerToString(second));
}
retval = retval + (sh * ((604800 * TimeShiftWeeks) + SecondsFromComponents(TimeShiftDays, TimeShiftHours, TimeShiftMinutes, TimeShiftSeconds)));
if (TimeSkipWeekdays == true)
{
int weekday = FBFB::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;}
}
}
}
return (datetime)retval;
}
};
class MDLIC_inloop_OrderOpenPrice
{
public: /* Input Parameters */
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_inloop_OrderOpenPrice()
{
}
public: /* The main method */
double _execute_()
{
return FBFB::OrderOpenPrice();
}
};
class MDLIC_prices_prices
{
public: /* Input Parameters */
string Price;
int TickID;
string Symbol;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_prices_prices()
{
Price = (string)"ASK";
TickID = (int)0;
Symbol = (string)CurrentSymbol();
}
public: /* The main method */
double _execute_()
{
int digits = (int)SymbolInfoInteger(Symbol, SYMBOL_DIGITS);
double retval = 0;
int tID = TickID + FXD_MORE_SHIFT;
if (Price == "ASK") {retval = TicksData(Symbol,SYMBOL_ASK,tID);}
else if (Price == "BID") {retval = TicksData(Symbol,SYMBOL_BID,tID);}
else if (Price == "MID") {retval = ((TicksData(Symbol,SYMBOL_ASK,tID)+TicksData(Symbol,SYMBOL_BID,tID))/2);}
else if (Price == "BIDHIGH") {retval = SymbolInfoDouble(Symbol,SYMBOL_BIDHIGH);}
else if (Price == "BIDLOW") {retval = SymbolInfoDouble(Symbol,SYMBOL_BIDLOW);}
else if (Price == "ASKHIGH") {retval = SymbolInfoDouble(Symbol,SYMBOL_ASKHIGH);}
else if (Price == "ASKLOW") {retval = SymbolInfoDouble(Symbol,SYMBOL_ASKLOW);}
else if (Price == "LAST") {retval = SymbolInfoDouble(Symbol,SYMBOL_LAST);}
else if (Price == "LASTHIGH") {retval = SymbolInfoDouble(Symbol,SYMBOL_LASTHIGH);}
else if (Price == "LASTLOW") {retval = SymbolInfoDouble(Symbol,SYMBOL_LASTLOW);}
return NormalizeDouble(retval, digits);
}
};
class MDLIC_account_AccountBalance
{
public: /* Input Parameters */
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_account_AccountBalance()
{
}
public: /* The main method */
double _execute_()
{
return NormalizeDouble(AccountInfoDouble(ACCOUNT_BALANCE), 2);
}
};
class MDLIC_account_AccountEquity
{
public: /* Input Parameters */
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_account_AccountEquity()
{
}
public: /* The main method */
double _execute_()
{
return NormalizeDouble(AccountInfoDouble(ACCOUNT_EQUITY), 2);
}
};
class MDLIC_text_text
{
public: /* Input Parameters */
string Text;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_text_text()
{
Text = (string)"sample text";
}
public: /* The main method */
string _execute_()
{
return Text;
}
};
class Block0: public MDL_NoOpenedOrders<string,string,string,string,string>
{
public: /* Constructor */
Block0() {
__block_number = 0;
__block_user_number = "1";
_beforeExecuteEnabled = true;
int ___outbound_blocks[14] = {1,14,15,16,17,18,19,2,20,3,4,5,6,7};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[1].run(0);
_blocks_[2].run(0);
_blocks_[3].run(0);
_blocks_[4].run(0);
_blocks_[5].run(0);
_blocks_[6].run(0);
_blocks_[7].run(0);
_blocks_[14].run(0);
_blocks_[15].run(0);
_blocks_[16].run(0);
_blocks_[17].run(0);
_blocks_[18].run(0);
_blocks_[19].run(0);
_blocks_[20].run(0);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
}
};
class Block1: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block1() {
__block_number = 1;
__block_user_number = "2";
int ___outbound_blocks[1] = {8};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_1;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_2;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[8].run(1);
}
}
};
class Block2: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block2() {
__block_number = 2;
__block_user_number = "3";
int ___outbound_blocks[1] = {8};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_2;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_3;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[8].run(2);
}
}
};
class Block3: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block3() {
__block_number = 3;
__block_user_number = "4";
int ___outbound_blocks[1] = {8};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_3;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_4;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[8].run(3);
}
}
};
class Block4: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block4() {
__block_number = 4;
__block_user_number = "5";
int ___outbound_blocks[1] = {8};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_4;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_5;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[8].run(4);
}
}
};
class Block5: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block5() {
__block_number = 5;
__block_user_number = "6";
int ___outbound_blocks[1] = {8};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_5;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_6;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[8].run(5);
}
}
};
class Block6: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block6() {
__block_number = 6;
__block_user_number = "7";
int ___outbound_blocks[1] = {8};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_6;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_7;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[8].run(6);
}
}
};
class Block7: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block7() {
__block_number = 7;
__block_user_number = "8";
int ___outbound_blocks[1] = {8};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_7;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_8;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[8].run(7);
}
}
};
class Block8: public MDL_LogicalAND
{
public: /* Constructor */
Block8() {
__block_number = 8;
__block_user_number = "9";
int ___outbound_blocks[1] = {9};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[9].run(8);
}
}
};
class Block9: public MDL_SignalBullCandle<string,int,double,double,string,ENUM_TIMEFRAMES>
{
public: /* Constructor */
Block9() {
__block_number = 9;
__block_user_number = "10";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {10};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[10].run(9);
}
}
virtual void _beforeExecute_()
{
CandleID = (int)c::candle_id;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
}
};
class Block10: public MDL_Condition<MDLIC_candles_candles,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block10() {
__block_number = 10;
__block_user_number = "11";
int ___outbound_blocks[1] = {11};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
Lo.iOHLC = "iOpen";
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.CandleID = c::candle_id;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_1;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[11].run(10);
}
}
};
class Block11: public MDL_Condition<MDLIC_candles_candles,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block11() {
__block_number = 11;
__block_user_number = "12";
int ___outbound_blocks[1] = {12};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
Lo.iOHLC = "iOpen";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.CandleID = c::candle_id;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_8;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[12].run(11);
}
}
};
class Block12: public MDL_OncePerBar<string,ENUM_TIMEFRAMES,int>
{
public: /* Constructor */
Block12() {
__block_number = 12;
__block_user_number = "13";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {13};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[13].run(12);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
}
};
class Block13: public MDL_BuyNow<string,string,string,double,double,double,double,double,MDLIC_value_value,double,double,double,int,double,double,double,double,double,int,int,double,bool,double,double,bool,double,string,bool,double,string,string,bool,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,int,int,int,MDLIC_value_time,datetime,ulong,string,color>
{
public: /* Constructor */
Block13() {
__block_number = 13;
__block_user_number = "14";
_beforeExecuteEnabled = true;
dVolumeSize.Value = 0.1;
dpStopLoss.Value = 100.0;
ddStopLoss.Value = 0.01;
dpTakeProfit.Value = 100.0;
ddTakeProfit.Value = 0.01;
dExp.ModeTimeShift = 2;
dExp.TimeShiftDays = 1.0;
dExp.TimeSkipWeekdays = true;
StopLossMode = "none";
TakeProfitMode = "none";
}
public: /* Custom methods */
virtual double _dVolumeSize_() {return dVolumeSize._execute_();}
virtual double _dlStopLoss_() {return dlStopLoss._execute_();}
virtual double _dpStopLoss_() {return dpStopLoss._execute_();}
virtual double _ddStopLoss_() {return ddStopLoss._execute_();}
virtual double _dlTakeProfit_() {return dlTakeProfit._execute_();}
virtual double _dpTakeProfit_() {return dpTakeProfit._execute_();}
virtual double _ddTakeProfit_() {return ddTakeProfit._execute_();}
virtual datetime _dExp_() {return dExp._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
VolumeSize = (double)c::lot;
MyComment = (string)c::ea_name;
ArrowColorBuy = (color)clrBlue;
}
};
class Block14: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block14() {
__block_number = 14;
__block_user_number = "15";
int ___outbound_blocks[1] = {21};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_1;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_2;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[21].run(14);
}
}
};
class Block15: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block15() {
__block_number = 15;
__block_user_number = "16";
int ___outbound_blocks[1] = {21};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_2;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_3;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[21].run(15);
}
}
};
class Block16: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block16() {
__block_number = 16;
__block_user_number = "17";
int ___outbound_blocks[1] = {21};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_3;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_4;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[21].run(16);
}
}
};
class Block17: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block17() {
__block_number = 17;
__block_user_number = "18";
int ___outbound_blocks[1] = {21};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_4;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_5;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[21].run(17);
}
}
};
class Block18: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block18() {
__block_number = 18;
__block_user_number = "19";
int ___outbound_blocks[1] = {21};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_5;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_6;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[21].run(18);
}
}
};
class Block19: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block19() {
__block_number = 19;
__block_user_number = "20";
int ___outbound_blocks[1] = {21};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_6;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_7;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[21].run(19);
}
}
};
class Block20: public MDL_Condition<MDLIC_indicators_iMA,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block20() {
__block_number = 20;
__block_user_number = "21";
int ___outbound_blocks[1] = {21};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.MAperiod = c::ema_7;
Lo.MAmethod = MODE_EMA;
Lo.AppliedPrice = PRICE_CLOSE;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
Lo.Shift = c::candle_id;
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_8;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[21].run(20);
}
}
};
class Block21: public MDL_LogicalAND
{
public: /* Constructor */
Block21() {
__block_number = 21;
__block_user_number = "22";
int ___outbound_blocks[1] = {25};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[25].run(21);
}
}
};
class Block22: public MDL_Condition<MDLIC_candles_candles,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block22() {
__block_number = 22;
__block_user_number = "24";
int ___outbound_blocks[1] = {23};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
Lo.iOHLC = "iOpen";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.CandleID = c::candle_id;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_1;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[23].run(22);
}
}
};
class Block23: public MDL_Condition<MDLIC_candles_candles,double,string,MDLIC_indicators_iMA,double,int>
{
public: /* Constructor */
Block23() {
__block_number = 23;
__block_user_number = "25";
int ___outbound_blocks[1] = {24};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
Lo.iOHLC = "iOpen";
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.CandleID = c::candle_id;
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
return Lo._execute_();
}
virtual double _Ro_() {
Ro.MAperiod = c::ema_8;
Ro.MAmethod = MODE_EMA;
Ro.AppliedPrice = PRICE_CLOSE;
Ro.Symbol = CurrentSymbol();
Ro.Period = CurrentTimeframe();
Ro.Shift = c::candle_id;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[24].run(23);
}
}
};
class Block24: public MDL_OncePerBar<string,ENUM_TIMEFRAMES,int>
{
public: /* Constructor */
Block24() {
__block_number = 24;
__block_user_number = "26";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {26};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[26].run(24);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
}
};
class Block25: public MDL_SignalBearCandle<string,int,double,double,string,ENUM_TIMEFRAMES>
{
public: /* Constructor */
Block25() {
__block_number = 25;
__block_user_number = "27";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {22};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[22].run(25);
}
}
virtual void _beforeExecute_()
{
CandleID = (int)c::candle_id;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
}
};
class Block26: public MDL_SellNow<string,string,string,double,double,double,double,double,MDLIC_value_value,double,double,double,int,double,double,double,double,double,int,int,double,bool,double,double,bool,double,string,bool,double,string,string,bool,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,int,int,int,MDLIC_value_time,datetime,ulong,string,color>
{
public: /* Constructor */
Block26() {
__block_number = 26;
__block_user_number = "28";
_beforeExecuteEnabled = true;
dVolumeSize.Value = 0.1;
dpStopLoss.Value = 100.0;
ddStopLoss.Value = 0.01;
dpTakeProfit.Value = 100.0;
ddTakeProfit.Value = 0.01;
dExp.ModeTimeShift = 2;
dExp.TimeShiftDays = 1.0;
dExp.TimeSkipWeekdays = true;
StopLossMode = "none";
TakeProfitMode = "none";
}
public: /* Custom methods */
virtual double _dVolumeSize_() {return dVolumeSize._execute_();}
virtual double _dlStopLoss_() {return dlStopLoss._execute_();}
virtual double _dpStopLoss_() {return dpStopLoss._execute_();}
virtual double _ddStopLoss_() {return ddStopLoss._execute_();}
virtual double _dlTakeProfit_() {return dlTakeProfit._execute_();}
virtual double _dpTakeProfit_() {return dpTakeProfit._execute_();}
virtual double _ddTakeProfit_() {return ddTakeProfit._execute_();}
virtual datetime _dExp_() {return dExp._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
VolumeSize = (double)c::lot;
ArrowColorSell = (color)clrRed;
}
};
class Block27: public MDL_IfOpenedOrders<string,string,string,string,string>
{
public: /* Constructor */
Block27() {
__block_number = 27;
__block_user_number = "29";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {28};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
BuysOrSells = "buys";
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[28].run(27);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
}
};
class Block28: public MDL_LoopStartTrades<string,string,string,string,string,string,int,int,int,int>
{
public: /* Constructor */
Block28() {
__block_number = 28;
__block_user_number = "30";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {29};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
BuysOrSells = "buys";
LoopLimit = 1;
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[29].run(28);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
}
};
class Block29: public MDL_Condition<MDLIC_candles_candles,double,string,MDLIC_inloop_OrderOpenPrice,double,int>
{
public: /* Constructor */
Block29() {
__block_number = 29;
__block_user_number = "31";
int ___outbound_blocks[1] = {30};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "<";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
return Lo._execute_();
}
virtual double _Ro_() {return Ro._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[30].run(29);
}
}
};
class Block30: public MDL_Formula_1<MDLIC_value_value,double,string,MDLIC_value_value,double>
{
public: /* Constructor */
Block30() {
__block_number = 30;
__block_user_number = "32";
int ___outbound_blocks[1] = {31};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
Ro.Value = 2.0;
compare = "*";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.Value = c::grid_nearby_pips;
return Lo._execute_();
}
virtual double _Ro_() {return Ro._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[31].run(30);
}
}
};
class Block31: public MDL_NoNearbyRunning<string,string,string,string,string,MDLIC_value_time,datetime,MDLIC_value_time,datetime,string,MDLIC_prices_prices,double,string,double,double,int>
{
public: /* Constructor */
Block31() {
__block_number = 31;
__block_user_number = "33";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {32};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
BuysOrSells = "buys";
}
public: /* Custom methods */
virtual datetime _Time1_() {return Time1._execute_();}
virtual datetime _Time2_() {return Time2._execute_();}
virtual double _BasePrice_() {
BasePrice.Symbol = CurrentSymbol();
return BasePrice._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[32].run(31);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
RangePips = (double)v::nearby_bs;
}
};
class Block32: public MDL_BuyNow<string,string,string,double,double,double,double,double,MDLIC_value_value,double,double,double,int,double,double,double,double,double,int,int,double,bool,double,double,bool,double,string,bool,double,string,string,bool,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,int,int,int,MDLIC_value_time,datetime,ulong,string,color>
{
public: /* Constructor */
Block32() {
__block_number = 32;
__block_user_number = "34";
_beforeExecuteEnabled = true;
dVolumeSize.Value = 0.1;
dpStopLoss.Value = 100.0;
ddStopLoss.Value = 0.01;
dpTakeProfit.Value = 100.0;
ddTakeProfit.Value = 0.01;
dExp.ModeTimeShift = 2;
dExp.TimeShiftDays = 1.0;
dExp.TimeSkipWeekdays = true;
StopLossMode = "none";
TakeProfitMode = "none";
}
public: /* Custom methods */
virtual double _dVolumeSize_() {return dVolumeSize._execute_();}
virtual double _dlStopLoss_() {return dlStopLoss._execute_();}
virtual double _dpStopLoss_() {return dpStopLoss._execute_();}
virtual double _ddStopLoss_() {return ddStopLoss._execute_();}
virtual double _dlTakeProfit_() {return dlTakeProfit._execute_();}
virtual double _dpTakeProfit_() {return dpTakeProfit._execute_();}
virtual double _ddTakeProfit_() {return ddTakeProfit._execute_();}
virtual datetime _dExp_() {return dExp._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
VolumeSize = (double)c::lot;
MyComment = (string)c::ea_name;
ArrowColorBuy = (color)clrBlue;
}
};
class Block33: public MDL_IfOpenedOrders<string,string,string,string,string>
{
public: /* Constructor */
Block33() {
__block_number = 33;
__block_user_number = "35";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {34};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
BuysOrSells = "sells";
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[34].run(33);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
}
};
class Block34: public MDL_LoopStartTrades<string,string,string,string,string,string,int,int,int,int>
{
public: /* Constructor */
Block34() {
__block_number = 34;
__block_user_number = "36";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {35};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
BuysOrSells = "sells";
LoopLimit = 1;
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[35].run(34);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
}
};
class Block35: public MDL_Condition<MDLIC_candles_candles,double,string,MDLIC_inloop_OrderOpenPrice,double,int>
{
public: /* Constructor */
Block35() {
__block_number = 35;
__block_user_number = "37";
int ___outbound_blocks[1] = {36};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.Symbol = CurrentSymbol();
Lo.Period = CurrentTimeframe();
return Lo._execute_();
}
virtual double _Ro_() {return Ro._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[36].run(35);
}
}
};
class Block36: public MDL_Formula_2<MDLIC_value_value,double,string,MDLIC_value_value,double>
{
public: /* Constructor */
Block36() {
__block_number = 36;
__block_user_number = "38";
int ___outbound_blocks[1] = {37};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
Ro.Value = 2.0;
compare = "*";
}
public: /* Custom methods */
virtual double _Lo_() {
Lo.Value = c::grid_nearby_pips;
return Lo._execute_();
}
virtual double _Ro_() {return Ro._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[37].run(36);
}
}
};
class Block37: public MDL_NoNearbyRunning<string,string,string,string,string,MDLIC_value_time,datetime,MDLIC_value_time,datetime,string,MDLIC_prices_prices,double,string,double,double,int>
{
public: /* Constructor */
Block37() {
__block_number = 37;
__block_user_number = "39";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {38};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
BuysOrSells = "sells";
}
public: /* Custom methods */
virtual datetime _Time1_() {return Time1._execute_();}
virtual datetime _Time2_() {return Time2._execute_();}
virtual double _BasePrice_() {
BasePrice.Symbol = CurrentSymbol();
return BasePrice._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[38].run(37);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
RangePips = (double)v::nearby_bs;
}
};
class Block38: public MDL_SellNow<string,string,string,double,double,double,double,double,MDLIC_value_value,double,double,double,int,double,double,double,double,double,int,int,double,bool,double,double,bool,double,string,bool,double,string,string,bool,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,int,int,int,MDLIC_value_time,datetime,ulong,string,color>
{
public: /* Constructor */
Block38() {
__block_number = 38;
__block_user_number = "40";
_beforeExecuteEnabled = true;
dVolumeSize.Value = 0.1;
dpStopLoss.Value = 100.0;
ddStopLoss.Value = 0.01;
dpTakeProfit.Value = 100.0;
ddTakeProfit.Value = 0.01;
dExp.ModeTimeShift = 2;
dExp.TimeShiftDays = 1.0;
dExp.TimeSkipWeekdays = true;
StopLossMode = "none";
TakeProfitMode = "none";
}
public: /* Custom methods */
virtual double _dVolumeSize_() {return dVolumeSize._execute_();}
virtual double _dlStopLoss_() {return dlStopLoss._execute_();}
virtual double _dpStopLoss_() {return dpStopLoss._execute_();}
virtual double _ddStopLoss_() {return ddStopLoss._execute_();}
virtual double _dlTakeProfit_() {return dlTakeProfit._execute_();}
virtual double _dpTakeProfit_() {return dpTakeProfit._execute_();}
virtual double _ddTakeProfit_() {return ddTakeProfit._execute_();}
virtual datetime _dExp_() {return dExp._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
VolumeSize = (double)c::lot;
ArrowColorSell = (color)clrRed;
}
};
class Block39: public MDL_IfOpenedOrders<string,string,string,string,string>
{
public: /* Constructor */
Block39() {
__block_number = 39;
__block_user_number = "41";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {40};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[40].run(39);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
}
};
class Block40: public MDL_CheckUProfit<string,string,string,string,string,string,string,double,double,string,string,double,double>
{
public: /* Constructor */
Block40() {
__block_number = 40;
__block_user_number = "42";
_beforeExecuteEnabled = true;
int ___outbound_blocks[1] = {41};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
ProfitMode = "pips-sum";
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[41].run(40);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
ProfitAmountPips = (double)c::close_profit_tp_pips;
}
};
class Block41: public MDL_CloseOpened<string,string,string,string,string,int,ulong,color>
{
public: /* Constructor */
Block41() {
__block_number = 41;
__block_user_number = "43";
_beforeExecuteEnabled = true;
}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
ArrowColor = (color)clrDeepPink;
}
};
class Block42: public MDL_Pass
{
public: /* Constructor */
Block42() {
__block_number = 42;
__block_user_number = "44";
int ___outbound_blocks[1] = {43};
FBFB::ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[43].run(42);
}
}
};
class Block43: public MDL_CommentEx<string,string,int,int,int,string,color,int,string,color,int,string,color,int,string,MDLIC_account_AccountBalance,double,int,int,string,MDLIC_account_AccountEquity,double,int,int,string,MDLIC_text_text,string,int,int,string,MDLIC_text_text,string,int,int,string,MDLIC_text_text,string,int,int,string,MDLIC_text_text,string,int,int,string,MDLIC_text_text,string,int,int,string,MDLIC_text_text,string,int,int>
{
public: /* Constructor */
Block43() {
__block_number = 43;
__block_user_number = "45";
_beforeExecuteEnabled = true;
Value3.Text = "";
Value4.Text = "";
Value5.Text = "";
Value6.Text = "";
Value7.Text = "";
Value8.Text = "";
Label1 = "BALANCE";
FormatNumber1 = 2;
Label2 = "EQUITY";
FormatNumber2 = 2;
}
public: /* Custom methods */
virtual double _Value1_() {return Value1._execute_();}
virtual double _Value2_() {return Value2._execute_();}
virtual string _Value3_() {return Value3._execute_();}
virtual string _Value4_() {return Value4._execute_();}
virtual string _Value5_() {return Value5._execute_();}
virtual string _Value6_() {return Value6._execute_();}
virtual string _Value7_() {return Value7._execute_();}
virtual string _Value8_() {return Value8._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
/* Inputs, modified into the code must be set here every time */
ObjY = 24;
Title = (string)c::ea_name;
ObjCorner = (int)CORNER_RIGHT_UPPER;
ObjTitleFontColor = (color)clrGold;
ObjLabelsFontColor = (color)clrDarkGray;
ObjFontColor = (color)clrWhite;
FormatTime1 = (int)EMPTY_VALUE;
FormatTime2 = (int)EMPTY_VALUE;
FormatNumber3 = (int)EMPTY_VALUE;
FormatTime3 = (int)EMPTY_VALUE;
FormatNumber4 = (int)EMPTY_VALUE;
FormatTime4 = (int)EMPTY_VALUE;
FormatNumber5 = (int)EMPTY_VALUE;
FormatTime5 = (int)EMPTY_VALUE;
FormatNumber6 = (int)EMPTY_VALUE;
FormatTime6 = (int)EMPTY_VALUE;
FormatNumber7 = (int)EMPTY_VALUE;
FormatTime7 = (int)EMPTY_VALUE;
FormatNumber8 = (int)EMPTY_VALUE;
FormatTime8 = (int)EMPTY_VALUE;
}
};
/************************************************************************************************************************/
/************************************************************************************************************************/
double AccountBalanceAtStart()
{
static double memory = 0;
if (memory == 0)
{
memory = NormalizeDouble(AccountInfoDouble(ACCOUNT_BALANCE), 2);
}
return memory;
}
double AlignLots(string symbol, double lots, double lowerlots = 0.0, double upperlots = 0.0)
{
double LotStep = SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
double LotSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_CONTRACT_SIZE);
double MinLots = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
double MaxLots = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX);
if (LotStep > MinLots) MinLots = LotStep;
if (lots == EMPTY_VALUE) {lots = 0.0;}
lots = MathRound(lots / LotStep) * LotStep;
if (lots < MinLots) {lots = MinLots;}
if (lots > MaxLots) {lots = MaxLots;}
if (lowerlots > 0.0)
{
lowerlots = MathRound(lowerlots / LotStep) * LotStep;
if (lots < lowerlots) {lots = lowerlots;}
}
if (upperlots > 0.0)
{
upperlots = MathRound(upperlots / LotStep) * LotStep;
if (lots > upperlots) {lots = upperlots;}
}
return lots;
}
double AlignStopLoss(
string symbol,
int type,
double price,
double slo = 0.0, // original sl, used when modifying
double sll = 0.0,
double slp = 0.0,
bool consider_freezelevel = false
)
{
double sl = 0.0;
if (MathAbs(sll) == EMPTY_VALUE) {sll = 0.0;}
if (MathAbs(slp) == EMPTY_VALUE) {slp = 0.0;}
if (sll == 0.0 && slp == 0.0)
{
return 0.0;
}
if (price <= 0.0)
{
Print(__FUNCTION__ + " error: No price entered");
return -1;
}
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
slp = slp * PipValue(symbol) * point;
int bs = 1;
if (
type == OP_SELL
|| type == OP_SELLSTOP
|| type == OP_SELLLIMIT
)
{
bs = -1;
}
double askbid = price;
double bidask = price;
if (type < 2)
{
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
askbid = ask;
bidask = bid;
if (bs < 0)
{
askbid = bid;
bidask = ask;
}
}
if (sll == 0.0 && slp != 0.0) {sll = price;}
if (sll > 0.0) {sl = sll - slp * bs;}
if (sl < 0.0)
{
return -1;
}
sl = NormalizeDouble(sl, digits);
slo = NormalizeDouble(slo, digits);
if (sl == slo)
{
return sl;
}
double minstops = (double)SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL);
if (consider_freezelevel == true)
{
double freezelevel = (double)SymbolInfoInteger(symbol, SYMBOL_TRADE_FREEZE_LEVEL);
if (freezelevel > minstops) {minstops = freezelevel;}
}
minstops = NormalizeDouble(minstops * point,digits);
double sllimit = bidask - minstops * bs; // SL min price level
if (sl > 0.0 && sl != slo)
{
if ((bs > 0 && sl > askbid) || (bs < 0 && sl < askbid))
{
string abstr = "";
if (bs > 0) {abstr = "Bid";} else {abstr = "Ask";}
Print(
"Error: Invalid SL requested (",
FBFB::DoubleToStr(sl, digits),
" for ", abstr, " price ",
bidask,
")"
);
return -1;
}
else if ((bs > 0 && sl > sllimit) || (bs < 0 && sl < sllimit))
{
if (USE_VIRTUAL_STOPS)
{
return sl;
}
Print(
"Warning: Too short SL requested (",
FBFB::DoubleToStr(sl, digits),
" or ",
FBFB::DoubleToStr(MathAbs(sl - askbid) / point, 0),
" points), minimum will be taken (",
FBFB::DoubleToStr(sllimit, digits),
" or ",
FBFB::DoubleToStr(MathAbs(askbid - sllimit) / point, 0),
" points)"
);
sl = sllimit;
return sl;
}
}
double ticksize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
sl = MathRound(sl / ticksize) * ticksize;
return sl;
}
double AlignTakeProfit(
string symbol,
int type,
double price,
double tpo = 0.0, // original tp, used when modifying
double tpl = 0.0,
double tpp = 0.0,
bool consider_freezelevel = false
)
{
double tp = 0.0;
if (MathAbs(tpl) == EMPTY_VALUE) {tpl = 0.0;}
if (MathAbs(tpp) == EMPTY_VALUE) {tpp = 0.0;}
if (tpl == 0.0 && tpp == 0.0)
{
return 0.0;
}
if (price <= 0.0)
{
Print(__FUNCTION__ + " error: No price entered");
return -1;
}
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
tpp = tpp * PipValue(symbol) * point;
int bs = 1;
if (
type == OP_SELL
|| type == OP_SELLSTOP
|| type == OP_SELLLIMIT
)
{
bs = -1;
}
double askbid = price;
double bidask = price;
if (type < 2)
{
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
askbid = ask;
bidask = bid;
if (bs < 0)
{
askbid = bid;
bidask = ask;
}
}
if (tpl == 0.0 && tpp != 0.0) {tpl = price;}
if (tpl > 0.0) {tp = tpl + tpp * bs;}
if (tp < 0.0)
{
return -1;
}
tp = NormalizeDouble(tp, digits);
tpo = NormalizeDouble(tpo, digits);
if (tp == tpo)
{
return tp;
}
double minstops = (double)SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL);
if (consider_freezelevel == true)
{
double freezelevel = (double)SymbolInfoInteger(symbol, SYMBOL_TRADE_FREEZE_LEVEL);
if (freezelevel > minstops) {minstops = freezelevel;}
}
minstops = NormalizeDouble(minstops * point,digits);
double tplimit = bidask + minstops * bs; // TP min price level
if (tp > 0.0 && tp != tpo)
{
if ((bs > 0 && tp < bidask) || (bs < 0 && tp > bidask))
{
string abstr = "";
if (bs > 0) {abstr = "Bid";} else {abstr = "Ask";}
Print(
"Error: Invalid TP requested (",
FBFB::DoubleToStr(tp, digits),
" for ", abstr, " price ",
bidask,
")"
);
return -1;
}
else if ((bs > 0 && tp < tplimit) || (bs < 0 && tp > tplimit))
{
if (USE_VIRTUAL_STOPS)
{
return tp;
}
Print(
"Warning: Too short TP requested (",
FBFB::DoubleToStr(tp, digits),
" or ",
FBFB::DoubleToStr(MathAbs(tp - askbid) / point, 0),
" points), minimum will be taken (",
FBFB::DoubleToStr(tplimit, digits),
" or ",
FBFB::DoubleToStr(MathAbs(askbid - tplimit) / point, 0),
" points)"
);
tp = tplimit;
return tp;
}
}
double ticksize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
tp = MathRound(tp / ticksize) * ticksize;
return tp;
}
template<typename T>
bool ArrayEnsureValue(T &array[], T value)
{
int size = ArraySize(array);
if (size > 0)
{
if (InArray(array, value))
{
return false; // no value added
}
}
ArrayResize(array, size+1);
array[size] = value;
return true; // value added
}
template<typename T>
int ArraySearch(T &array[], T value)
{
int index = -1;
int size = ArraySize(array);
for (int i = 0; i < size; i++)
{
if (array[i] == value)
{
index = i;
break;
}
}
return index;
}
template<typename T>
bool ArrayStripKey(T &array[], int key)
{
int x = 0;
int size = ArraySize(array);
for (int i=0; i<size; i++)
{
if (i != key)
{
array[x] = array[i];
x++;
}
}
if (x < size)
{
ArrayResize(array, x);
return true; // stripped
}
return false; // not stripped
}
template<typename T>
bool ArrayStripValue(T &array[], T value)
{
int x = 0;
int size = ArraySize(array);
for (int i=0; i<size; i++)
{
if (array[i] != value)
{
array[x] = array[i];
x++;
}
}
if (x < size)
{
ArrayResize(array, x);
return true; // stripped
}
return false; // not stripped
}
double Bet1326(
string group,
string symbol,
int pool,
double initialLots,
bool reverse = false
) {
double info[];
GetBetTradesInfo(info, group, symbol, pool, false);
double lots = info[0];
double profitOrLoss = info[1]; // 0 - unknown, 1 - profit, -1 - loss
double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
if (initialLots < minLot)
{
initialLots = minLot;
}
if (lots == 0)
{
lots = initialLots;
}
else
{
if (
(reverse == false && profitOrLoss == 1)
|| (reverse == true && profitOrLoss == -1)
) {
double div = lots / initialLots;
if (div < 1.5) {lots = initialLots * 3;}
else if (div < 2.5) {lots = initialLots * 6;}
else if (div < 3.5) {lots = initialLots * 2;}
else {lots = initialLots;}
}
else
{
lots = initialLots;
}
}
return lots;
}
double BetDalembert(
string group,
string symbol,
int pool,
double initialLots,
double reverse = false
) {
double info[];
GetBetTradesInfo(info, group, symbol, pool, false);
double lots = info[0];
double profitOrLoss = info[1]; // 0 - unknown, 1 - profit, -1 - loss
double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
if (initialLots < minLot)
{
initialLots = minLot;
}
if (lots == 0)
{
lots = initialLots;
}
else
{
if (
(reverse == 0 && profitOrLoss == 1)
|| (reverse == 1 && profitOrLoss == -1)
) {
lots = lots - initialLots;
if (lots < initialLots) {lots = initialLots;}
}
else
{
lots = lots + initialLots;
}
}
return lots;
}
double BetFibonacci(
string group,
string symbol,
int pool,
double initialLots
) {
double info[];
GetBetTradesInfo(info, group, symbol, pool, false);
double lots = info[0];
double profitOrLoss = info[1]; // 0 - unknown, 1 - profit, -1 - loss
double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
if (initialLots < minLot)
{
initialLots = minLot;
}
if (lots == 0)
{
lots = initialLots;
}
else
{
int fibo1 = 1;
int fibo2 = 0;
int fibo3 = 0;
int fibo4 = 0;
double div = lots / initialLots;
if (div <= 0) {div = 1;}
while (true)
{
fibo1 = fibo1 + fibo2;
fibo3 = fibo2;
fibo2 = fibo1 - fibo2;
fibo4 = fibo2 - fibo3;
if (fibo1 > NormalizeDouble(div, 2))
{
break;
}
}
if (profitOrLoss == 1)
{
if (fibo4 <= 0) {fibo4 = 1;}
lots = initialLots * fibo4;
}
else
{
lots = initialLots * fibo1;
}
}
lots = NormalizeDouble(lots, 2);
return lots;
}
double BetLabouchere(
string group,
string symbol,
int pool,
double initialLots,
string listOfNumbers,
double reverse = false
) {
double info[];
GetBetTradesInfo(info, group, symbol, pool, false);
double lots = info[0];
double profitOrLoss = info[1]; // 0 - unknown, 1 - profit, -1 - loss
static string memGroup[];
static string memList[];
static long memTicket[];
int startAgain = false;
int id = ArraySearch(memGroup, group);
if (id == -1)
{
startAgain = true;
if (listOfNumbers == "") {listOfNumbers = "1";}
id = ArraySize(memGroup);
ArrayResize(memGroup, id+1, id+1);
ArrayResize(memList, id+1, id+1);
ArrayResize(memTicket, id+1, id+1);
memGroup[id] = group;
memList[id] = listOfNumbers;
}
if (memTicket[id] == (long)FBFB::OrderTicket())
{
memList[id] = listOfNumbers;
}
memTicket[id] = (long)FBFB::OrderTicket();
int list[];
string listS[];
StringExplode(",", memList[id], listS);
ArrayResize(list, ArraySize(listS));
for (int s = 0; s < ArraySize(listS); s++)
{
list[s] = (int)StringToInteger(StringTrim(listS[s]));
}
int size = ArraySize(list);
double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
if (initialLots < minLot)
{
initialLots = minLot;
}
if (lots == 0)
{
startAgain = true;
}
if (startAgain == true)
{
if (size == 1)
{
lots = initialLots * list[0];
}
else {
lots = initialLots * (list[0] + list[size-1]);
}
}
else
{
if (
(reverse == 0 && profitOrLoss == 1)
|| (reverse == 1 && profitOrLoss == -1)
) {
size = size - 2;
if (size < 0) {
size = 0;
}
if (size == 0) {
StringExplode(",", listOfNumbers, listS);
ArrayResize(list, ArraySize(listS));
for (int s = 0; s < ArraySize(listS); s++)
{
list[s] = (int)StringToInteger(StringTrim(listS[s]));
}
size = ArraySize(list);
}
else {
for (int pos = 0; pos < ArraySize(list) - 1; pos++) {
list[pos] = list[pos+1];
}
ArrayResize(list, size);
}
int rightNum = (size > 1) ? list[size - 1] : 0;
lots = initialLots * (list[0] + rightNum);
if (lots < initialLots) {lots = initialLots;}
}
else
{
size = size + 1;
ArrayResize(list, size);
int rightNum = (size > 2) ? list[size - 2] : 0;
list[size - 1] = list[0] + rightNum;
lots = initialLots * (list[0] + list[size - 1]);
if (lots < initialLots) {lots = initialLots;}
}
}
Print("Labouchere (for group "
+ (string)id
+ ") current list of numbers: "
+ StringImplode(",", list)
);
size=ArraySize(list);
if (size == 0)
{
ArrayStripKey(memGroup, id);
ArrayStripKey(memList, id);
ArrayStripKey(memTicket, id);
}
else {
memList[id] = StringImplode(",", list);
}
return lots;
}
double BetMartingale(
string group,
string symbol,
int pool,
double initialLots,
double multiplyOnLoss,
double multiplyOnProfit,
double addOnLoss,
double addOnProfit,
int resetOnLoss,
int resetOnProfit
) {
double info[];
GetBetTradesInfo(info, group, symbol, pool, true);
double lots = info[0];
double profitOrLoss = info[1]; // 0 - unknown, 1 - profit, -1 - loss
double consecutive = info[2];
if (lots == 0)
{
lots = initialLots;
}
else
{
if (profitOrLoss == 1)
{
if (resetOnProfit > 0 && consecutive >= resetOnProfit)
{
lots = initialLots;
}
else
{
if (multiplyOnProfit <= 0)
{
multiplyOnProfit = 1;
}
lots = (lots * multiplyOnProfit) + addOnProfit;
}
}
else
{
if (resetOnLoss > 0 && consecutive >= resetOnLoss)
{
lots = initialLots;
}
else
{
if (multiplyOnLoss <= 0)
{
multiplyOnLoss = 1;
}
lots = (lots * multiplyOnLoss) + addOnLoss;
}
}
}
return lots;
}
double BetSequence(
string group,
string symbol,
int pool,
double initialLots,
string sequenceOnLoss,
string sequenceOnProfit,
bool reverse = false
) {
double info[];
GetBetTradesInfo(info, group, symbol, pool, false);
double lots = info[0];
double profitOrLoss = info[1]; // 0 - unknown, 1 - profit, -1 - loss
static string memGroup[];
static string memLossList[];
static string memProfitList[];
static long memTicket[];
int id = ArraySearch(memGroup, group);
if (id == -1)
{
if (sequenceOnLoss == "") {sequenceOnLoss = "1";}
if (sequenceOnProfit == "") {sequenceOnProfit = "1";}
id = ArraySize(memGroup);
ArrayResize(memGroup, id+1, id+1);
ArrayResize(memLossList, id+1, id+1);
ArrayResize(memProfitList, id+1, id+1);
ArrayResize(memTicket, id+1, id+1);
memGroup[id] = group;
memLossList[id] = sequenceOnLoss;
memProfitList[id] = sequenceOnProfit;
}
bool lossReset = false;
bool profitReset = false;
if (profitOrLoss == -1 && memLossList[id] == "")
{
lossReset = true;
memProfitList[id] = "";
}
if (profitOrLoss == 1 && memProfitList[id] == "")
{
profitReset = true;
memLossList[id] = "";
}
if (profitOrLoss == 1 || memLossList[id] == "")
{
memLossList[id] = sequenceOnLoss;
if (lossReset) {
memLossList[id] = "1," + memLossList[id];
}
}
if (profitOrLoss == -1 || memProfitList[id] == "")
{
memProfitList[id] = sequenceOnProfit;
if (profitReset) {
memProfitList[id] = "1," + memProfitList[id];
}
}
if (memTicket[id] == (long)FBFB::OrderTicket())
{
memLossList[id] = sequenceOnLoss;
memProfitList[id] = sequenceOnProfit;
}
memTicket[id] = (long)FBFB::OrderTicket();
int s = 0;
double listLoss[];
double listProfit[];
string listS[];
StringExplode(",", memLossList[id], listS);
ArrayResize(listLoss, ArraySize(listS), ArraySize(listS));
for (s = 0; s < ArraySize(listS); s++)
{
listLoss[s] = (double)StringToDouble(StringTrim(listS[s]));
}
StringExplode(",", memProfitList[id], listS);
ArrayResize(listProfit, ArraySize(listS), ArraySize(listS));
for (s = 0; s < ArraySize(listS); s++)
{
listProfit[s] = (double)StringToDouble(StringTrim(listS[s]));
}
double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
if (initialLots < minLot)
{
initialLots = minLot;
}
if (lots == 0)
{
lots = initialLots;
}
else
{
if (
(reverse == false && profitOrLoss ==1)
|| (reverse == true && profitOrLoss == -1)
) {
lots = initialLots * listProfit[0];
int size = ArraySize(listProfit);
for(int pos = 0; pos < size-1; pos++)
{
listProfit[pos] = listProfit[pos+1];
}
if (size > 0)
{
ArrayResize(listProfit, size-1, size-1);
memProfitList[id] = StringImplode(",", listProfit);
}
}
else
{
lots = initialLots * listLoss[0];
int size = ArraySize(listLoss);
for(int pos = 0; pos < size-1; pos++)
{
listLoss[pos] = listLoss[pos+1];
}
if (size > 0)
{
ArrayResize(listLoss, size-1, size-1);
memLossList[id] = StringImplode(",", listLoss);
}
}
}
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 = clrNONE,
datetime expiration = 0
)
{
return OrderCreate(
symbol,
OP_BUY,
lots,
0,
sll,
tpl,
slp,
tpp,
slippage,
magic,
comment,
arrowcolor,
expiration
);
}
int CheckForTradingError(int error_code=-1, string msg_prefix="")
{
if (error_code<0) {
error_code=FBFB::GetLastError();
}
int retval=0;
static int tryouts=0;
switch(error_code)
{
case 0:
retval=0;
break;
case 1: // No error returned
FBFB::RefreshRates();
retval=1;
break;
case 4: //ERR_SERVER_BUSY
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
Sleep(1000);
FBFB::RefreshRates();
retval=1;
break;
case 6: //ERR_NO_CONNECTION
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
while(!FBFB::IsConnected()) {Sleep(100);}
while(FBFB::IsTradeContextBusy()) {Sleep(50);}
FBFB::RefreshRates();
retval=1;
break;
case 128: //ERR_TRADE_TIMEOUT
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
FBFB::RefreshRates();
retval=1;
break;
case 129: //ERR_INVALID_PRICE
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
if (!FBFB::IsTesting()) {while(FBFB::RefreshRates()==false) {Sleep(1);}}
retval=1;
break;
case 130: //ERR_INVALID_STOPS
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
if (!FBFB::IsTesting()) {while(FBFB::RefreshRates()==false) {Sleep(1);}}
retval=1;
break;
case 135: //ERR_PRICE_CHANGED
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
if (!FBFB::IsTesting()) {while(FBFB::RefreshRates()==false) {Sleep(1);}}
retval=1;
break;
case 136: //ERR_OFF_QUOTES
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
if (!FBFB::IsTesting()) {while(FBFB::RefreshRates()==false) {Sleep(1);}}
retval=1;
break;
case 137: //ERR_BROKER_BUSY
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
Sleep(1000);
retval=1;
break;
case 138: //ERR_REQUOTE
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Waiting for a new tick to retry.."));}
if (!FBFB::IsTesting()) {while(FBFB::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(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
FBFB::RefreshRates();
retval=1;
break;
case 143: //This code should be processed in the same way as error 128.
if (msg_prefix!="") {Print(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
FBFB::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(FBFB::StringConcatenate(msg_prefix,": ",ErrorMessage(error_code),". Retrying.."));}
while(FBFB::IsTradeContextBusy()) {Sleep(50);}
FBFB::RefreshRates();
retval=1;
break;
default:
if (msg_prefix!="") {Print(FBFB::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 #"+(string)tryouts+" of 10");
}
}
return(retval);
}
bool CloseTrade(ulong ticket, ulong slippage = 0, color arrowcolor = CLR_NONE)
{
bool success = false;
bool exists = false;
for (int i = 0; i < FBFB::OrdersTotal(); i++)
{
if (!FBFB::OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (FBFB::OrderTicket() == ticket)
{
exists = true;
break;
}
}
if (exists == false)
{
return false;
}
while (true)
{
WaitTradeContextIfBusy();
success = FBFB::OrderClose((int)ticket, FBFB::OrderLots(), FBFB::OrderClosePrice(), (int)(slippage * PipValue(FBFB::OrderSymbol())), arrowcolor);
if (success == true)
{
if (USE_VIRTUAL_STOPS) {
VirtualStopsDriver("clear", ticket);
}
expirationWorker.RemoveExpiration(ticket);
OnTrade();
return true;
}
int erraction = CheckForTradingError(FBFB::GetLastError(), "Closing trade #" + (string)ticket + " error");
switch(erraction)
{
case 0: break; // no error
case 1: continue; // overcomable error
case 2: break; // fatal error
}
break;
}
return false;
}
template<typename DT1, typename DT2>
bool CompareValues(string sign, DT1 v1, DT2 v2)
{
if (sign == ">") return(v1 > v2);
else if (sign == "<") return(v1 < v2);
else if (sign == ">=") return(v1 >= v2);
else if (sign == "<=") return(v1 <= v2);
else if (sign == "==") return(v1 == v2);
else if (sign == "!=") return(v1 != v2);
else if (sign == "x>") return(v1 > v2);
else if (sign == "x<") return(v1 < v2);
return false;
}
string CurrentSymbol(string symbol = "")
{
static string memory = "";
if (symbol != "")
{
memory = symbol;
}
else if (memory == "")
{
memory = Symbol();
}
return memory;
}
ENUM_TIMEFRAMES CurrentTimeframe(ENUM_TIMEFRAMES timeframe = -1)
{
static ENUM_TIMEFRAMES memory = 0;
if (timeframe >= 0) {memory = timeframe;}
return memory;
}
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 == 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;
}
i++;
if (i >= size)
{
i = 0;
}
if (i == start_i) {break;}
}
}
i = size;
size = size + 1;
ArrayResize(symbols, size);
ArrayResize(points, size);
symbols[i] = symbol;
points[i] = 0;
last_symbol = symbol;
last_i = i;
string rules[];
StringExplode(",", POINT_FORMAT_RULES, rules);
int rules_count = ArraySize(rules);
if (rules_count > 0)
{
string rule[];
for (int r = 0; r < rules_count; r++)
{
StringExplode("=", rules[r], rule);
if (ArraySize(rule) != 2) {continue;}
double from = StringToDouble(rule[0]);
double to = StringToDouble(rule[1]);
if (to <= 0) {continue;}
if (from == 0 && StringLen(rule[0]) > 0)
{
string s_from = rule[0];
int pos = StringFind(s_from, "?");
if (pos < 0) // ? not found
{
if (StringFind(symbol, s_from) == 0) {points[i] = to;}
}
else if (pos == 0) // ? is the first symbol => match the second symbol
{
if (StringFind(symbol, FBFB::StringSubstr(s_from, 1), 3) == 3)
{
points[i] = to;
}
}
else if (pos > 0) // ? is the second symbol => match the first symbol
{
if (StringFind(symbol, FBFB::StringSubstr(s_from, 0, pos)) == 0)
{
points[i] = to;
}
}
}
if (from == 0) {continue;}
if (SymbolInfoDouble(symbol, SYMBOL_POINT) == from)
{
points[i] = to;
}
}
}
if (points[i] == 0)
{
points[i] = SymbolInfoDouble(symbol, SYMBOL_POINT);
}
last_point = points[i];
return last_point;
}
bool DeleteOrder(ulong ticket, color arrowcolor=clrNONE)
{
bool success=false;
if (!FBFB::OrderSelect((int)ticket,SELECT_BY_TICKET,MODE_TRADES)) {return(false);}
while(true)
{
WaitTradeContextIfBusy();
success=FBFB::OrderDelete((int)ticket,arrowcolor);
if (success==true) {
if (USE_VIRTUAL_STOPS) {
VirtualStopsDriver("clear",ticket);
}
OnTrade();
return(true);
}
int erraction=CheckForTradingError(FBFB::GetLastError(), "Deleting order #"+(string)ticket+" error");
switch(erraction)
{
case 0: break; // no error
case 1: continue; // overcomable error
case 2: break; // fatal error
}
break;
}
return(false);
}
void DrawSpreadInfo()
{
static bool allow_draw = true;
if (allow_draw==false) {return;}
if (MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_VISUAL_MODE)) {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 custom_point = CustomPoint(Symbol());
double current_spread = 0;
if (custom_point > 0) {
current_spread = (SymbolInfoDouble(Symbol(),SYMBOL_ASK)-SymbolInfoDouble(Symbol(),SYMBOL_BID))/custom_point;
}
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;
if (passed == false)
{
passed=true;
name="fxd_spread_current_label";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+1);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 18);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "Spread:");
}
name="fxd_spread_max_label";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+148);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+17);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrOrangeRed);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "max:");
}
name="fxd_spread_avg_label";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+148);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+9);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "avg:");
}
name="fxd_spread_min_label";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+148);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrGold);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "min:");
}
name="fxd_spread_current";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+93);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 18);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "0");
}
name="fxd_spread_max";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+173);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+17);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrOrangeRed);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "0");
}
name="fxd_spread_avg";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+173);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+9);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrDarkOrange);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "0");
}
name="fxd_spread_min";
if (FBFB::ObjectFind(0, name)==-1) {
FBFB::ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x+173);
FBFB::ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y+1);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 7);
FBFB::ObjectSetInteger(0, name, OBJPROP_COLOR, clrGold);
FBFB::ObjectSetString(0, name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetString(0, name, OBJPROP_TEXT, "0");
}
}
FBFB::ObjectSetString(0, "fxd_spread_current", OBJPROP_TEXT, FBFB::DoubleToStr(current_spread,2));
FBFB::ObjectSetString(0, "fxd_spread_max", OBJPROP_TEXT, FBFB::DoubleToStr(max_spread,2));
FBFB::ObjectSetString(0, "fxd_spread_avg", OBJPROP_TEXT, FBFB::DoubleToStr(avg_spread,2));
FBFB::ObjectSetString(0, "fxd_spread_min", OBJPROP_TEXT, FBFB::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;
if (passed == false)
{
passed = true;
name="fxd_status_title";
FBFB::ObjectCreate(0,name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0,name, OBJPROP_BACK, false);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0,name, OBJPROP_XDISTANCE, x);
FBFB::ObjectSetInteger(0,name, OBJPROP_YDISTANCE, y+17);
FBFB::ObjectSetString(0,name, OBJPROP_TEXT, "Status");
FBFB::ObjectSetString(0,name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetInteger(0,name, OBJPROP_FONTSIZE, 7);
FBFB::ObjectSetInteger(0,name, OBJPROP_COLOR, clrGray);
name="fxd_status_text";
FBFB::ObjectCreate(0,name, OBJ_LABEL, 0, 0, 0);
FBFB::ObjectSetInteger(0,name, OBJPROP_BACK, false);
FBFB::ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_LOWER);
FBFB::ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(0,name, OBJPROP_XDISTANCE, x+2);
FBFB::ObjectSetInteger(0,name, OBJPROP_YDISTANCE, y+1);
FBFB::ObjectSetString(0,name, OBJPROP_FONT, "Arial");
FBFB::ObjectSetInteger(0,name, OBJPROP_FONTSIZE, 12);
FBFB::ObjectSetInteger(0,name, OBJPROP_COLOR, clrAqua);
}
if (text != memory) {
memory=text;
FBFB::ObjectSetString(0,"fxd_status_text", OBJPROP_TEXT, text);
}
return(text);
}
double DynamicLots(string symbol, string mode="balance", double value=0, double sl=0, string align="align", double RJFR_initial_lots=0)
{
double size=0;
double LotStep=FBFB::MarketInfo(symbol,MODE_LOTSTEP);
double LotSize=FBFB::MarketInfo(symbol,MODE_LOTSIZE);
double MinLots=FBFB::MarketInfo(symbol,MODE_MINLOT);
double MaxLots=FBFB::MarketInfo(symbol,MODE_MAXLOT);
double TickValue=FBFB::MarketInfo(symbol,MODE_TICKVALUE);
double point=FBFB::MarketInfo(symbol,MODE_POINT);
double ticksize=FBFB::MarketInfo(symbol,MODE_TICKSIZE);
double margin_required=FBFB::MarketInfo(symbol,MODE_MARGINREQUIRED);
if (mode=="fixed" || mode=="lots") {size=value;}
else if (mode=="block-equity") {size=(value/100)*FBFB::AccountEquity()/margin_required;}
else if (mode=="block-balance") {size=(value/100)*FBFB::AccountBalance()/margin_required;}
else if (mode=="block-freemargin") {size=(value/100)*FBFB::AccountFreeMargin()/margin_required;}
else if (mode=="equity") {size=(value/100)*FBFB::AccountEquity()/(LotSize*TickValue);}
else if (mode=="balance") {size=(value/100)*FBFB::AccountBalance()/(LotSize*TickValue);}
else if (mode=="freemargin") {size=(value/100)*FBFB::AccountFreeMargin()/(LotSize*TickValue);}
else if (mode=="equityRisk") {size=((value/100)*FBFB::AccountEquity())/(sl*((TickValue/ticksize)*point)*PipValue(symbol));}
else if (mode=="balanceRisk") {size=((value/100)*FBFB::AccountBalance())/(sl*((TickValue/ticksize)*point)*PipValue(symbol));}
else if (mode=="freemarginRisk") {size=((value/100)*FBFB::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") {
static double RJFR_start_lots=0;
static double RJFR_delta=0;
static double RJFR_units=1;
static double RJFR_target_lower=0;
static double RJFR_target_upper=0;
if (RJFR_start_lots<=0) {RJFR_start_lots=value;}
if (RJFR_start_lots<MinLots) {RJFR_start_lots=MinLots;}
if (RJFR_delta<=0) {RJFR_delta=sl;}
if (RJFR_target_upper<=0) {
RJFR_target_upper=FBFB::AccountEquity()+(RJFR_units*RJFR_delta);
Print("Fixed Ratio MM: Units=>",RJFR_units,"; Delta=",RJFR_delta,"; Upper Target Equity=>",RJFR_target_upper);
}
if (FBFB::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 (",FBFB::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 (FBFB::AccountEquity()<RJFR_target_upper) {break;}
}
}
else if (FBFB::AccountEquity()<=RJFR_target_lower)
{
while(true) {
if (FBFB::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 | ", FBFB::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;
}
if (size==EMPTY_VALUE) {size=0;}
size=MathRound(size/LotStep)*LotStep;
static bool alert_min_lots=false;
if (size<MinLots && alert_min_lots==false) {
alert_min_lots=true;
Alert("You want to trade ",size," lot, but your broker's minimum is ",MinLots," lot. The trade/order will continue with ",MinLots," lot instead of ",size," lot. The same rule will be applied for next trades/orders with desired lot size lower than the minimum. You will not see this message again until you restart the program.");
}
if (align=="align") {
if (size<MinLots) {size=MinLots;}
if (size>MaxLots) {size=MaxLots;}
}
return (size);
}
string ErrorMessage(int error_code=-1)
{
string e = "";
if (error_code < 0) {error_code = FBFB::GetLastError();}
switch(error_code)
{
case 0: return("");
case 1: e = "No error returned"; break;
case 2: e = "Common error"; break;
case 3: e = "Invalid trade parameters"; break;
case 4: e = "Trade server is busy"; break;
case 5: e = "Old version of the client terminal"; break;
case 6: e = "No connection with trade server"; break;
case 7: e = "Not enough rights"; break;
case 8: e = "Too frequent requests"; break;
case 9: e = "Malfunctional trade operation (never returned error)"; break;
case 64: e = "Account disabled"; break;
case 65: e = "Invalid account"; break;
case 128: e = "Trade timeout"; break;
case 129: e = "Invalid price"; break;
case 130: e = "Invalid Sl or TP"; break;
case 131: e = "Invalid trade volume"; break;
case 132: e = "Market is closed"; break;
case 133: e = "Trade is disabled"; break;
case 134: e = "Not enough money"; break;
case 135: e = "Price changed"; break;
case 136: e = "Off quotes"; break;
case 137: e = "Broker is busy (never returned error)"; break;
case 138: e = "Requote"; break;
case 139: e = "Order is locked"; break;
case 140: e = "Only long trades allowed"; break;
case 141: e = "Too many requests"; break;
case 145: e = "Modification denied because order too close to market"; break;
case 146: e = "Trade context is busy"; break;
case 147: e = "Expirations are denied by broker"; break;
case 148: e = "Amount of open and pending orders has reached the limit"; break;
case 149: e = "Hedging is prohibited"; break;
case 150: e = "Prohibited by FIFO rules"; break;
case 4000: e = "No error"; break;
case 4001: e = "Wrong function pointer"; break;
case 4002: e = "Array index is out of range"; break;
case 4003: e = "No memory for function call stack"; break;
case 4004: e = "Recursive stack overflow"; break;
case 4005: e = "Not enough stack for parameter"; break;
case 4006: e = "No memory for parameter string"; break;
case 4007: e = "No memory for temp string"; break;
case 4008: e = "Not initialized string"; break;
case 4009: e = "Not initialized string in array"; break;
case 4010: e = "No memory for array string"; break;
case 4011: e = "Too long string"; break;
case 4012: e = "Remainder from zero divide"; break;
case 4013: e = "Zero divide"; break;
case 4014: e = "Unknown command"; break;
case 4015: e = "Wrong jump"; break;
case 4016: e = "Not initialized array"; break;
case 4017: e = "dll calls are not allowed"; break;
case 4018: e = "Cannot load library"; break;
case 4019: e = "Cannot call function"; break;
case 4020: e = "Expert function calls are not allowed"; break;
case 4021: e = "Not enough memory for temp string returned from function"; break;
case 4022: e = "System is busy"; break;
case 4050: e = "Invalid function parameters count"; break;
case 4051: e = "Invalid function parameter value"; break;
case 4052: e = "String function internal error"; break;
case 4053: e = "Some array error"; break;
case 4054: e = "Incorrect series array using"; break;
case 4055: e = "Custom indicator error"; break;
case 4056: e = "Arrays are incompatible"; break;
case 4057: e = "Global variables processing error"; break;
case 4058: e = "Global variable not found"; break;
case 4059: e = "Function is not allowed in testing mode"; break;
case 4060: e = "Function is not confirmed"; break;
case 4061: e = "Send mail error"; break;
case 4062: e = "String parameter expected"; break;
case 4063: e = "Integer parameter expected"; break;
case 4064: e = "Double parameter expected"; break;
case 4065: e = "Array as parameter expected"; break;
case 4066: e = "Requested history data in update state"; break;
case 4099: e = "End of file"; break;
case 4100: e = "Some file error"; break;
case 4101: e = "Wrong file name"; break;
case 4102: e = "Too many opened files"; break;
case 4103: e = "Cannot open file"; break;
case 4104: e = "Incompatible access to a file"; break;
case 4105: e = "No order selected"; break;
case 4106: e = "Unknown symbol"; break;
case 4107: e = "Invalid price parameter for trade function"; break;
case 4108: e = "Invalid ticket"; break;
case 4109: e = "Trade is not allowed in the expert properties"; break;
case 4110: e = "Longs are not allowed in the expert properties"; break;
case 4111: e = "Shorts are not allowed in the expert properties"; break;
case 4200: e = "Object is already exist"; break;
case 4201: e = "Unknown object property"; break;
case 4202: e = "Object is not exist"; break;
case 4203: e = "Unknown object type"; break;
case 4204: e = "No object name"; break;
case 4205: e = "Object coordinates error"; break;
case 4206: e = "No specified subwindow"; break;
case 4207: e = "Graphical object error"; break;
case 4210: e = "Unknown chart property"; break;
case 4211: e = "Chart not found"; break;
case 4212: e = "Chart subwindow not found"; break;
case 4213: e = "Chart indicator not found"; break;
case 4220: e = "Symbol select error"; break;
case 4250: e = "Notification error"; break;
case 4251: e = "Notification parameter error"; break;
case 4252: e = "Notifications disabled"; break;
case 4253: e = "Notification send too frequent"; break;
case 4260: e = "FTP server is not specified"; break;
case 4261: e = "FTP login is not specified"; break;
case 4262: e = "FTP connection failed"; break;
case 4263: e = "FTP connection closed"; break;
case 4264: e = "FTP path not found on server"; break;
case 4265: e = "File not found in the MQL4\\Files directory to send on FTP server"; break;
case 4266: e = "Common error during FTP data transmission"; break;
case 5001: e = "Too many opened files"; break;
case 5002: e = "Wrong file name"; break;
case 5003: e = "Too long file name"; break;
case 5004: e = "Cannot open file"; break;
case 5005: e = "Text file buffer allocation error"; break;
case 5006: e = "Cannot delete file"; break;
case 5007: e = "Invalid file handle (file closed or was not opened)"; break;
case 5008: e = "Wrong file handle (handle index is out of handle table)"; break;
case 5009: e = "File must be opened with FILE_WRITE flag"; break;
case 5010: e = "File must be opened with FILE_READ flag"; break;
case 5011: e = "File must be opened with FILE_BIN flag"; break;
case 5012: e = "File must be opened with FILE_TXT flag"; break;
case 5013: e = "File must be opened with FILE_TXT or FILE_CSV flag"; break;
case 5014: e = "File must be opened with FILE_CSV flag"; break;
case 5015: e = "File read error"; break;
case 5016: e = "File write error"; break;
case 5017: e = "String size must be specified for binary file"; break;
case 5018: e = "Incompatible file (for string arrays-TXT, for others-BIN)"; break;
case 5019: e = "File is directory, not file"; break;
case 5020: e = "File does not exist"; break;
case 5021: e = "File cannot be rewritten"; break;
case 5022: e = "Wrong directory name"; break;
case 5023: e = "Directory does not exist"; break;
case 5024: e = "Specified file is not directory"; break;
case 5025: e = "Cannot delete directory"; break;
case 5026: e = "Cannot clean directory"; break;
case 5027: e = "Array resize error"; break;
case 5028: e = "String resize error"; break;
case 5029: e = "Structure contains strings or dynamic arrays"; break;
case 5200: e = "Invalid URL"; break;
case 5201: e = "Failed to connect to specified URL"; break;
case 5202: e = "Timeout exceeded"; break;
case 5203: e = "HTTP request failed"; break;
default: e = "Unknown error";
}
e = FBFB::StringConcatenate(e, " (", error_code, ")");
return e;
}
datetime ExpirationTime(string mode="GTC",int days=0, int hours=0, int minutes=0, datetime custom=0)
{
datetime now = TimeCurrent();
datetime expiration = now;
if (mode == "GTC" || mode == "") {expiration = 0;}
else if (mode == "today") {expiration = (datetime)(MathFloor((now + 86400.0) / 86400.0) * 86400.0);}
else if (mode == "specified")
{
expiration = 0;
if ((days + hours + minutes) > 0)
{
expiration = now + (86400 * days) + (3600 * hours) + (60 * minutes);
}
}
else
{
if (custom <= now)
{
if (custom < 31557600)
{
custom = now + custom;
}
else
{
custom = 0;
}
}
expiration = custom;
}
return expiration;
}
class ExpirationWorker
{
private:
struct CachedItems
{
int orderType;
long ticket;
datetime expiration;
};
CachedItems cachedItems[];
long chartID;
string chartObjectPrefix;
string chartObjectSuffix;
template<typename T>
void ArrayClone(T &dest[], T &src[])
{
int size = ArraySize(src);
ArrayResize(dest, size);
for (int i = 0; i < size; i++)
{
dest[i] = src[i];
}
}
void InitialDiscovery()
{
ArrayResize(cachedItems, 0);
int total = FBFB::OrdersTotal();
for (int index = 0; index <= total; index++)
{
long ticket = GetTicketByIndex(index);
if (ticket == 0) continue;
datetime expiration = GetExpirationFromObject(ticket);
if (expiration > 0)
{
if (FBFB::OrderSelect((int)ticket, SELECT_BY_TICKET, MODE_TRADES)) {
SetExpirationInCache(FBFB::OrderType(), ticket, expiration);
}
}
}
}
long GetTicketByIndex(int index)
{
long ticket = 0;
if (FBFB::OrderSelect(index, SELECT_BY_POS, MODE_TRADES))
{
if (FBFB::OrderType() <= OP_SELL) ticket = (long)FBFB::OrderTicket();
}
return ticket;
}
datetime GetExpirationFromObject(long ticket)
{
datetime expiration = (datetime)0;
string objectName = chartObjectPrefix + IntegerToString(ticket) + chartObjectSuffix;
if (FBFB::ObjectFind(chartID, objectName) == chartID)
{
expiration = (datetime)FBFB::ObjectGetInteger(chartID, objectName, OBJPROP_TIME);
}
return expiration;
}
bool RemoveExpirationObject(long ticket)
{
bool success = false;
string objectName = "";
objectName = chartObjectPrefix + IntegerToString(ticket) + chartObjectSuffix;
success = FBFB::ObjectDelete(chartID, objectName);
return success;
}
void RemoveExpirationFromCache(long ticket)
{
int size = ArraySize(cachedItems);
CachedItems newItems[];
int newSize = 0;
bool itemRemoved = false;
for (int i = 0; i < size; i++)
{
if (cachedItems[i].ticket == ticket)
{
itemRemoved = true;
}
else
{
newSize++;
ArrayResize(newItems, newSize);
newItems[newSize - 1].orderType = cachedItems[i].orderType;
newItems[newSize - 1].ticket = cachedItems[i].ticket;
newItems[newSize - 1].expiration = cachedItems[i].expiration;
}
}
if (itemRemoved) ArrayClone(cachedItems, newItems);
}
void SetExpirationInCache(int orderType, long ticket, datetime expiration)
{
bool alreadyExists = false;
int size = ArraySize(cachedItems);
for (int i = 0; i < size; i++)
{
if (cachedItems[i].ticket == ticket)
{
cachedItems[i].orderType = orderType;
cachedItems[i].expiration = expiration;
alreadyExists = true;
break;
}
}
if (alreadyExists == false)
{
ArrayResize(cachedItems, size + 1);
cachedItems[size].orderType = orderType;
cachedItems[size].ticket = ticket;
cachedItems[size].expiration = expiration;
}
}
bool SetExpirationInObject(int orderType, long ticket, datetime expiration)
{
if (!FBFB::OrderSelect((int)ticket, SELECT_BY_TICKET)) return false;
string objectName = chartObjectPrefix + IntegerToString(ticket) + chartObjectSuffix;
double price = FBFB::OrderOpenPrice();
if (FBFB::ObjectFind(chartID, objectName) == chartID)
{
FBFB::ObjectSetInteger(chartID, objectName, OBJPROP_TIME, expiration);
FBFB::ObjectSetDouble(chartID, objectName, OBJPROP_PRICE, price);
}
else
{
FBFB::ObjectCreate(chartID, objectName, OBJ_ARROW, 0, expiration, price);
}
FBFB::ObjectSetInteger(chartID, objectName, OBJPROP_ARROWCODE, 77);
FBFB::ObjectSetInteger(chartID, objectName, OBJPROP_HIDDEN, true);
FBFB::ObjectSetInteger(chartID, objectName, OBJPROP_ANCHOR, ANCHOR_TOP);
FBFB::ObjectSetInteger(chartID, objectName, OBJPROP_COLOR, clrRed);
FBFB::ObjectSetInteger(chartID, objectName, OBJPROP_SELECTABLE, false);
FBFB::ObjectSetInteger(chartID, objectName, OBJPROP_TIMEFRAMES, OBJ_NO_PERIODS);
FBFB::ObjectSetString(chartID, objectName, OBJPROP_TEXT, TimeToString(expiration));
return true;
}
bool TradeExists(long ticket)
{
bool exists = false;
for (int i = 0; i < FBFB::OrdersTotal(); i++)
{
if (!FBFB::OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (FBFB::OrderType() > OP_SELL) continue;
if (FBFB::OrderTicket() == ticket)
{
exists = true;
break;
}
}
return exists;
}
bool PendingOrderExists(long ticket)
{
bool exists = false;
for (int i = 0; i < FBFB::OrdersTotal(); i++)
{
if (!FBFB::OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (FBFB::OrderType() <= OP_SELL || FBFB::OrderType() > OP_SELLSTOP) continue;
if (FBFB::OrderTicket() == ticket)
{
exists = true;
break;
}
}
return exists;
}
public:
ExpirationWorker()
{
chartID = 0;
chartObjectPrefix = "#";
chartObjectSuffix = " Expiration Marker";
InitialDiscovery();
}
void SetExpiration(long ticket, datetime expiration)
{
if (expiration <= 0)
{
RemoveExpiration(ticket);
}
else
{
int orderType = FBFB::OrderType();
SetExpirationInObject(orderType, ticket, expiration);
SetExpirationInCache(orderType, ticket, expiration);
}
}
datetime GetExpiration(long ticket)
{
datetime expiration = (datetime)0;
int size = ArraySize(cachedItems);
for (int i = 0; i < size; i++)
{
if (cachedItems[i].ticket == ticket)
{
expiration = cachedItems[i].expiration;
break;
}
}
return expiration;
}
void RemoveExpiration(long ticket)
{
RemoveExpirationObject(ticket);
RemoveExpirationFromCache(ticket);
}
void Run()
{
int count = ArraySize(cachedItems);
if (count > 0)
{
datetime timeNow = TimeCurrent();
for (int i = 0; i < count; i++)
{
if (timeNow >= cachedItems[i].expiration)
{
int orderType = cachedItems[i].orderType;
long ticket = cachedItems[i].ticket;
bool removeExpiration = false;
if (orderType < 2 && TradeExists(ticket))
{
if (CloseTrade(ticket))
{
Print("close #", ticket, " by expiration");
removeExpiration = true;
}
}
else if (orderType >= 2 && PendingOrderExists(ticket))
{
if (DeleteOrder(ticket))
{
Print("delete #", ticket, " by expiration");
removeExpiration = true;
}
}
else
{
removeExpiration = true;
}
if (removeExpiration)
{
RemoveExpiration(ticket);
count = ArraySize(cachedItems);
i--;
}
}
}
}
}
};
ExpirationWorker expirationWorker;
bool FilterOrderBy(
string group_mode = "all",
string group = "0",
string market_mode = "all",
string market = "",
string BuysOrSells = "both",
string LimitsOrStops = "both",
int TradesOrders = 0,
bool onTrade = false
) {
static string markets[];
static string market0 = "-";
static int markets_size = 0;
static string groups[];
static string group0 = "-";
static int groups_size = 0;
bool type_pass = false;
bool market_pass = false;
bool group_pass = false;
int i, type, magic_number;
string symbol;
if (onTrade == false)
{
type = FBFB::OrderType();
magic_number = FBFB::OrderMagicNumber();
symbol = FBFB::OrderSymbol();
}
else
{
type = e_attrType();
magic_number = e_attrMagicNumber();
symbol = e_attrSymbol();
}
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;
}
}
else if (TradesOrders == 1)
{
if (
(BuysOrSells == "both" && (type == OP_BUYLIMIT || type == OP_BUYSTOP || type == OP_SELLLIMIT || type == OP_SELLSTOP))
|| (BuysOrSells == "buys" && (type == OP_BUYLIMIT || type == OP_BUYSTOP))
|| (BuysOrSells == "sells" && (type == OP_SELLLIMIT || type == OP_SELLSTOP))
)
{
if (
(LimitsOrStops == "both" && (type == OP_BUYSTOP || type == OP_SELLSTOP || type == OP_BUYLIMIT || type == OP_SELLLIMIT))
|| (LimitsOrStops == "stops" && (type == OP_BUYSTOP || type == OP_SELLSTOP))
|| (LimitsOrStops == "limits" && (type == OP_BUYLIMIT || type == OP_SELLLIMIT))
)
{
type_pass = true;
}
}
}
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;
}
if (group_mode == "group")
{
if (group == "")
{
if (magic_number == MagicStart)
{
group_pass = true;
}
}
else
{
if (group0 != group)
{
group0 = group;
StringExplode(",", group,groups);
groups_size = ArraySize(groups);
for(i = 0; i < groups_size; i++)
{
groups[i] = FBFB::StringTrimRight(groups[i]);
groups[i] = FBFB::StringTrimLeft(groups[i]);
if (groups[i] == "") {groups[i] = "0";}
}
}
for(i = 0; i < groups_size; i++)
{
if (magic_number == (MagicStart+(int)groups[i]))
{
group_pass = true;
break;
}
}
}
}
else if (group_mode == "all" || (group_mode == "manual" && magic_number == 0))
{
group_pass = true;
}
if (group_pass == false)
{
return false;
}
if (market_mode == "all")
{
market_pass = true;
}
else
{
if (symbol == market)
{
market_pass = true;
}
else
{
if (market0 != market)
{
market0 = market;
if (market == "")
{
markets_size = 1;
ArrayResize(markets, 1);
markets[0] = Symbol();
}
else
{
StringExplode(",", market, markets);
markets_size = ArraySize(markets);
for(i = 0; i < markets_size; i++)
{
markets[i] = FBFB::StringTrimRight(markets[i]);
markets[i] = FBFB::StringTrimLeft(markets[i]);
if (markets[i] == "") {markets[i] = Symbol();}
}
}
}
for(i = 0; i < markets_size; i++)
{
if (symbol == markets[i])
{
market_pass = true;
break;
}
}
}
}
if (market_pass == false)
{
return false;
}
return true;
}
/**
* This overload works for numeric values and for boolean values
*/
template<typename T>
string FormatValueForPrinting(
T value,
int digits,
int timeFormat
) {
string outputValue = "";
string typeName = typename(value);
if (typeName == "double" || typeName == "float")
{
if (digits >= -16 && digits <= 8)
{
if (value > -1.0 && value < 1.0)
{
/**
* Find how many zeroes are after the point, but before the first non-zero digit.
* For example 0.000195 has 3 zeroes
* The function would return negative value for values bigger than 0
*
* @see
*/
int zeroesAfterPoint = (int)-MathFloor(MathLog10(MathAbs(value)) + 1);
digits = zeroesAfterPoint + digits;
}
T normalizedValue = NormalizeDouble(value, digits);
outputValue = DoubleToString(normalizedValue, digits);
}
else
{
outputValue = (string)NormalizeDouble(value, 8);
}
}
else {
outputValue = IntegerToString((long)value);
}
return outputValue;
}
/**
* Bool overload
*/
string FormatValueForPrinting(
bool value,
int digits,
int timeFormat
) {
return (value) ? "true" : "false";
}
/**
* Datetime overload
*/
string FormatValueForPrinting(
datetime value,
int digits,
int timeFormat
) {
if (
timeFormat == (int)EMPTY_VALUE
|| timeFormat == EMPTY_VALUE
) timeFormat = TIME_DATE|TIME_MINUTES;
return TimeToString(value, timeFormat);
}
/**
* String overload
*/
string FormatValueForPrinting(
string value,
int digits,
int timeFormat
) {
return value;
}
void GetBetTradesInfo(
double &output[],
string group,
string symbol,
int pool, // 0: try running trades first and then history trades, 1: try running only, 2: try history only
bool findConsecutive = false
) {
if (ArraySize(output) < 4)
{
ArrayResize(output, 4);
ArrayInitialize(output, 0.0);
}
double lots = output[0]; // will be the lot size of the first loaded trade
double profitOrLoss = output[1]; // 0 is initial value, 1 is profit, -1 is loss
double consecutive = output[2]; // the number of consecutive profitable or losable trades
double profit = output[3]; // will be the profit of the first loaded trade
bool historyTrades = (pool == 2) ? true : false;
int total = (historyTrades) ? HistoryTradesTotal() : TradesTotal();
for (int pos = total - 1; pos >= 0; pos--)
{
if (
(!historyTrades && TradeSelectByIndex(pos, "group", group, "symbol", symbol))
|| (historyTrades && HistoryTradeSelectByIndex(pos, "group", group, "symbol", symbol))
) {
if (
((pool == 0 || pool == 1) && TimeCurrent() - FBFB::OrderOpenTime() < 3) // skip for brand new trades
||
(
!historyTrades
&& FBFB::OrderExpiration() > 0
&& FBFB::OrderExpiration() <= FBFB::OrderCloseTime()
)
) {
continue;
}
if (lots == 0.0)
{
lots = FBFB::OrderLots();
}
profit = FBFB::OrderClosePrice() - FBFB::OrderOpenPrice();
profit = NormalizeDouble(profit, SymbolDigits(FBFB::OrderSymbol()));
if (profit == 0.0)
{
continue;
}
if (IsOrderTypeSell())
{
profit = -1 * profit;
}
if (profitOrLoss == 0)
{
profitOrLoss = (profit < 0.0) ? -1 : 1;
consecutive++;
if (findConsecutive == false) break;
}
else
{
if (
(profitOrLoss > 0.0 && profit < 0.0)
|| (profitOrLoss < 0.0 && profit > 0.0)
) {
break;
}
consecutive++;
}
}
}
output[0] = lots;
output[1] = profitOrLoss;
output[2] = consecutive;
output[3] = profit;
if (pool == 0 && (findConsecutive || profitOrLoss == 0))
{
pool = 2;
GetBetTradesInfo(output, group, symbol, pool, findConsecutive);
}
}
bool HistoryTradeSelectByIndex(
int index,
string group_mode = "all",
string group = "0",
string market_mode = "all",
string market = "",
string BuysOrSells = "both"
) {
if (FBFB::OrderSelect((int)index, SELECT_BY_POS, MODE_HISTORY) && FBFB::OrderType() < 2)
{
if (FilterOrderBy(
group_mode,
group,
market_mode,
market,
BuysOrSells)
) {
return true;
}
}
return false;
}
int HistoryTradesTotal(datetime from_date=0, datetime to_date=0)
{
return FBFB::OrdersHistoryTotal();
}
template<typename T>
bool InArray(T &array[], T value)
{
int size = ArraySize(array);
if (size > 0)
{
for (int i = 0; i < size; i++)
{
if (array[i] == value)
{
return true;
}
}
}
return false;
}
bool IsOrderTypeBuy()
{
int type = FBFB::OrderType();
return (type == OP_BUY || type == OP_BUYSTOP || type == OP_BUYLIMIT);
}
bool IsOrderTypeSell()
{
int type = FBFB::OrderType();
return (type == OP_SELL || type == OP_SELLSTOP || type == OP_SELLLIMIT);
}
bool ModifyOrder(
long ticket,
double op,
double sll = 0,
double tpl = 0,
double slp = 0,
double tpp = 0,
datetime exp = 0,
color clr = clrNONE,
bool ontrade_event = true
) {
int bs = 1;
if (
FBFB::OrderType() == OP_SELL
|| FBFB::OrderType() == OP_SELLSTOP
|| FBFB::OrderType() == OP_SELLLIMIT
)
{bs = -1;} // Positive when Buy, negative when Sell
while (true)
{
uint time0 = GetTickCount();
WaitTradeContextIfBusy();
if (!FBFB::OrderSelect((int)ticket, SELECT_BY_TICKET))
{
return false;
}
string symbol = FBFB::OrderSymbol();
int type = FBFB::OrderType();
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
double stoplevel = point * SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL);
double freezelevel = point * SymbolInfoInteger(symbol, SYMBOL_TRADE_FREEZE_LEVEL);
if (FBFB::OrderType() < 2) {op = FBFB::OrderOpenPrice();} else {op = NormalizeDouble(op,digits);}
sll = NormalizeDouble(sll, digits);
tpl = NormalizeDouble(tpl, digits);
if (op < 0 || op >= EMPTY_VALUE || sll < 0 || slp < 0 || tpl < 0 || tpp < 0)
{
break;
}
if (type == OP_BUYLIMIT)
{
if (ask - op < stoplevel) {op = ask - stoplevel;}
if (ask - op <= freezelevel) {op = ask - freezelevel - point;}
}
else if (type == OP_BUYSTOP)
{
if (op - ask < stoplevel) {op = ask + stoplevel;}
if (op - ask <= freezelevel) {op = ask + freezelevel + point;}
}
else if (type == OP_SELLLIMIT)
{
if (op - bid < stoplevel) {op = bid + stoplevel;}
if (op - bid <= freezelevel) {op = bid + freezelevel + point;}
}
else if (type == OP_SELLSTOP)
{
if (bid - op < stoplevel) {op = bid - stoplevel;}
if (bid - op < freezelevel) {op = bid - freezelevel - point;}
}
op = NormalizeDouble(op, digits);
double sl = 0, tp = 0, vsl = 0, vtp = 0;
sl = AlignStopLoss(symbol, type, op, attrStopLoss(), sll, slp);
if (sl < 0) {break;}
tp = AlignTakeProfit(symbol, type, op, attrTakeProfit(), tpl, tpp);
if (tp < 0) {break;}
if (USE_VIRTUAL_STOPS)
{
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);
ResetLastError();
if (USE_VIRTUAL_STOPS)
{
if (vsl != attrStopLoss() || vtp != attrTakeProfit())
{
VirtualStopsDriver("set", ticket, vsl, vtp, toPips(MathAbs(op-vsl), symbol), toPips(MathAbs(vtp-op), symbol));
}
}
bool success = false;
if (
(FBFB::OrderType() > 1 && op != NormalizeDouble(FBFB::OrderOpenPrice(),digits))
|| sl != NormalizeDouble(FBFB::OrderStopLoss(),digits)
|| tp != NormalizeDouble(FBFB::OrderTakeProfit(),digits)
|| exp != OrderExpirationTime()
) {
success = FBFB::OrderModify((int)ticket, op, sl, tp, exp, clr);
}
int erraction = CheckForTradingError(FBFB::GetLastError(), "Modify error");
switch(erraction)
{
case 0: break; // no error
case 1: continue; // overcomable error
case 2: break; // fatal error
}
if (success == true)
{
if (!FBFB::IsTesting() && !FBFB::IsVisualMode())
{
Print("Operation details: Speed " + (string)(GetTickCount()-time0) + " ms");
}
if (ontrade_event == true)
{
OrderModified(ticket);
OnTrade();
}
if (FBFB::OrderSelect((int)ticket,SELECT_BY_TICKET)) {}
return true;
}
break;
}
return false;
}
int OCODriver()
{
static int last_known_ticket = 0;
static int orders1[];
static int orders2[];
int i, size;
int total = FBFB::OrdersTotal();
for (int pos=total-1; pos>=0; pos--)
{
if (FBFB::OrderSelect(pos,SELECT_BY_POS,MODE_TRADES))
{
int ticket = FBFB::OrderTicket();
if (ticket == last_known_ticket) {break;}
if (pos == total-1) {
last_known_ticket = ticket;
}
if (FBFB::OrderType() <= OP_SELL) {continue;}
if (FBFB::StringSubstr(FBFB::OrderComment(), 0, 5) == "[oco:")
{
int ticket_oco = FBFB::StrToInteger(FBFB::StringSubstr(FBFB::OrderComment(), 5, StringLen(FBFB::OrderComment())-1));
bool found = false;
size = ArraySize(orders2);
for (i=0; i<size; i++)
{
if (orders2[i] == ticket_oco) {
found = true;
break;
}
}
if (found == false) {
ArrayResize(orders1, size+1);
ArrayResize(orders2, size+1);
orders1[size] = ticket_oco;
orders2[size] = ticket;
}
}
}
}
size = ArraySize(orders1);
int dbremove = false;
for (i=size-1; i>=0; i--)
{
if (FBFB::OrderSelect(orders1[i], SELECT_BY_TICKET, MODE_TRADES) == false || FBFB::OrderType() <= OP_SELL)
{
if (FBFB::OrderSelect(orders2[i], SELECT_BY_TICKET, MODE_TRADES)) {
if (DeleteOrder(orders2[i],clrWhite))
{
dbremove = true;
}
}
else {
dbremove = true;
}
if (dbremove == true)
{
ArrayStripKey(orders1, i);
ArrayStripKey(orders2, i);
}
}
}
size = ArraySize(orders2);
dbremove = false;
for (i=size-1; i>=0; i--)
{
if (FBFB::OrderSelect(orders2[i], SELECT_BY_TICKET, MODE_TRADES) == false || FBFB::OrderType() <= OP_SELL)
{
if (FBFB::OrderSelect(orders1[i], SELECT_BY_TICKET, MODE_TRADES)) {
if (DeleteOrder(orders1[i],clrWhite))
{
dbremove = true;
}
}
else {
dbremove = true;
}
if (dbremove == true)
{
ArrayStripKey(orders1, i);
ArrayStripKey(orders2, i);
}
}
}
return true;
}
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;
}
class OnTradeEventDetector
{
private:
struct EventValues
{
string reason,
detail;
long magic,
ticket;
int type;
datetime timeClose,
timeOpen,
timeExpiration;
double commission,
priceOpen,
priceClose,
profit,
stopLoss,
swap,
takeProfit,
volume;
string comment,
symbol;
};
struct Position
{
int type;
long magic,
ticket;
datetime timeClose,
timeExpiration,
timeOpen;
double commission,
priceCurrent,
priceOpen,
profit,
stopLoss,
swap,
takeProfit,
volume;
string comment,
symbol;
};
struct PendingOrder
{
int type;
long magic,
ticket;
datetime timeClose,
timeExpiration,
timeOpen;
double priceCurrent,
priceOpen,
stopLoss,
takeProfit,
volume;
string comment,
symbol;
};
struct PositionExpirationTimes
{
long ticket;
datetime timeExpiration;
};
bool debug;
bool isRepeat;
int eventValuesQueueIndex;
EventValues eventValues[];
PendingOrder previousPendingOrders[];
PendingOrder pendingOrders[];
Position previousPositions[];
Position positions[];
PositionExpirationTimes positionExpirationTimes[];
/**
* Like ArrayCopy(), but for any type.
*/
template<typename T>
void CopyList(T &dest[], T &src[])
{
int size = ArraySize(src);
ArrayResize(dest, size);
for (int i = 0; i < size; i++)
{
dest[i] = src[i];
}
}
/**
* Overloaded method 1 of 2
*/
int MakeListOf(PendingOrder &list[])
{
ArrayResize(list, 0);
int count = FBFB::OrdersTotal();
int howManyAdded = 0;
for (int index = 0; index < count; index++)
{
if (FBFB::OrderSelect(index, SELECT_BY_POS) == false) continue;
if (FBFB::OrderType() < OP_BUYLIMIT) continue;
howManyAdded++;
ArrayResize(list, howManyAdded);
int i = howManyAdded - 1;
list[i].type = FBFB::OrderType();
list[i].magic = FBFB::OrderMagicNumber();
list[i].ticket = FBFB::OrderTicket();
list[i].timeClose = FBFB::OrderCloseTime();
list[i].timeExpiration = FBFB::OrderExpiration();
list[i].timeOpen = FBFB::OrderOpenTime();
list[i].priceCurrent = FBFB::OrderClosePrice();
list[i].priceOpen = FBFB::OrderOpenPrice();
list[i].stopLoss = FBFB::OrderStopLoss();
list[i].takeProfit = FBFB::OrderTakeProfit();
list[i].volume = FBFB::OrderLots();
list[i].comment = FBFB::OrderComment();
list[i].symbol = FBFB::OrderSymbol();
}
return howManyAdded;
}
/**
* Overloaded method 2 of 2
*/
int MakeListOf(Position &list[])
{
ArrayResize(list, 0);
int count = FBFB::OrdersTotal();
int howManyAdded = 0;
for (int index = 0; index < count; index++)
{
if (FBFB::OrderSelect(index, SELECT_BY_POS) == false) continue;
if (FBFB::OrderType() > OP_SELL) continue;
howManyAdded++;
ArrayResize(list, howManyAdded);
int i = howManyAdded - 1;
list[i].type = FBFB::OrderType();
list[i].magic = FBFB::OrderMagicNumber();
list[i].ticket = FBFB::OrderTicket();
list[i].timeClose = FBFB::OrderCloseTime();
list[i].timeExpiration = (datetime)0;
list[i].timeOpen = FBFB::OrderOpenTime();
list[i].commission = FBFB::OrderCommission();
list[i].priceCurrent = FBFB::OrderClosePrice();
list[i].priceOpen = FBFB::OrderOpenPrice();
list[i].profit = FBFB::OrderProfit();
list[i].stopLoss = FBFB::OrderStopLoss();
list[i].swap = FBFB::OrderSwap();
list[i].takeProfit = FBFB::OrderTakeProfit();
list[i].volume = FBFB::OrderLots();
list[i].comment = FBFB::OrderComment();
list[i].symbol = FBFB::OrderSymbol();
list[i].timeExpiration = expirationWorker.GetExpiration(list[i].ticket);
if (USE_VIRTUAL_STOPS)
{
list[i].stopLoss = VirtualStopsDriver("get sl", list[i].ticket);
list[i].takeProfit = VirtualStopsDriver("get tp", list[i].ticket);
}
}
return howManyAdded;
}
/**
* This method loops through 2 lists of items and finds a difference. This difference is the event.
* "Items" are either pending orders or positions.
*
* Returns true if an event is detected or false if not.
*/
template<typename ITEMS_TYPE>
bool DetectEvent(ITEMS_TYPE &previousItems[], ITEMS_TYPE ¤tItems[])
{
ITEMS_TYPE item;
string reason = "";
string detail = "";
int countBefore = ArraySize(previousItems);
int countNow = ArraySize(currentItems);
if (reason == "") {
for (int index = 0; index < countBefore; index++) {
item = FindMissingItem(previousItems, currentItems);
if (item.ticket > 0) {
DeleteItem(previousItems, item);
reason = "close";
break;
}
}
}
if (reason == "") {
for (int index = 0; index < countNow; index++) {
item = FindMissingItem(currentItems, previousItems);
if (item.ticket > 0) {
if (
item.type < 2 // it's a running trade
&& item.ticket != attrTicketParent(item.ticket)
) {
reason = "decrement";
}
else {
reason = "new";
}
PushItem(previousItems, item);
break;
}
}
}
if (reason == "") {
if (countBefore != countNow) {
Print("OnTrade event detector: Uncovered situation reached");
}
for (int index = 0; index < countNow; index++) {
int previousIndex = -1;
ITEMS_TYPE current = currentItems[index];
ITEMS_TYPE previous;
previous.ticket = 0;
for (int j = 0; j < countBefore; j++) {
if (current.ticket == previousItems[j].ticket) {
previousIndex = j;
previous = previousItems[j];
break;
}
}
if (current.ticket != previous.ticket) {
Print("OnTrade event detector: Uncovered situation reached (2)");
}
if (previous.volume < current.volume) {
previousItems[previousIndex].volume = current.volume;
item = previousItems[previousIndex];
reason = "increment";
break;
}
if (previous.volume > current.volume) {
previousItems[previousIndex].volume = current.volume;
item = previousItems[previousIndex];
reason = "decrement";
break;
}
if (
previous.stopLoss != current.stopLoss
&& previous.takeProfit != current.takeProfit
) {
previousItems[previousIndex].stopLoss = current.stopLoss;
previousItems[previousIndex].takeProfit = current.takeProfit;
item = previousItems[previousIndex];
reason = "modify";
detail = "sltp";
break;
}
else if (previous.stopLoss != current.stopLoss) {
previousItems[previousIndex].stopLoss = current.stopLoss;
item = previousItems[previousIndex];
reason = "modify";
detail = "sl";
break;
}
else if (previous.takeProfit != current.takeProfit) {
previousItems[previousIndex].takeProfit = current.takeProfit;
item = previousItems[previoПоказано первые 50% кода (символов: 308375)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.