hft scalper.mq5
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «hft scalper.mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Торговый советник для MetaTrader 5, созданный в конструкторе fxDreema. Советник работает по тиковой модели, обрабатывает входящие тики и выполняет торговые операции. В коде предусмотрены виртуальные стопы, которые отображаются как горизонтальные линии на графике и активируются при достижении ценой заданного уровня. Также реализован сбор тиковых данных и подсчёт тиков в секунду. Советник имеет ограничение по времени работы: при запуске после указанной даты выводится предупреждение и программа удаляется с графика. Входные параметры позволяют настроить управление капиталом, стоп-лосс, тейк-профит, трейлинг-стоп, параметры сетки ордеров и магическое число. Все настройки считываются в статические поля класса и используются в дальнейшей работе. Виртуальные стопы управляются через объекты на графике и могут быть отключены при оптимизации. Советник не содержит пользовательских индикаторов и не предоставляет публичных библиотечных функций. Основное назначение — автоматическая торговля с использованием отложенных ордеров и виртуальных уровней закрытия.
Настройки программы
| Настройка | Описание |
|---|---|
| Autolots (Autolots) | Автоматический лот — Автоматический расчёт объёма позиции. Значение 0.0 отключает автоматический расчёт. |
| SL (SL) | Стоп-лосс — Размер стоп-лосса в пунктах. Значение 0.0 означает отсутствие стоп-лосса. |
| TP (TP) | Тейк-профит — Размер тейк-профита в пунктах. Значение 0.0 означает отсутствие тейк-профита. |
| Use_Trailing_Stops (Use_Trailing_Stops) | Использовать трейлинг-стоп — Включить или отключить использование трейлинг-стопа. По умолчанию включено. |
| Stops (Stops) | Стопы — Размер стопов в пунктах. Значение 0.0 означает отсутствие стопов. |
| Steps (Steps) | Шаг — Шаг сетки ордеров в пунктах. Значение 0.0 означает отсутствие шага. |
| Starts (Starts) | Начало — Начальное значение для сетки ордеров. Значение 0.0 означает отсутствие значения. |
| Bar_Count (Bar_Count) | Количество баров — Количество баров для анализа. Значение 0.0 означает отсутствие ограничения. |
| Bar_Size (Bar_Size) | Размер бара — Размер бара в пунктах, используемый в торговых правилах. |
| STR (STR) | Параметр STR, используемый в торговых правилах. Значение 0.0 означает отсутствие значения. |
| Gridsize (Gridsize) | Размер сетки — Размер сетки отложенных ордеров в пунктах. |
| Trail_Pen (Trail_Pen) | Трейлинг-стоп — Величина трейлинг-стопа в пунктах. Значение 0.0 означает отсутствие трейлинга. |
| Stops_Only (Stops_Only) | Только стоп-ордера — Разрешить использование только стоп-ордеров. По умолчанию выключено. |
| Limits_Only (Limits_Only) | Только лимитные ордера — Разрешить использование только лимитных ордеров. По умолчанию включено. |
| Magic Number, kind of... (MagicStart) | Магическое число — Начальное значение магического числа для идентификации ордеров советника. |
Поиск по коду файла
#property description " Risk Warning: Trading financial products on margin carries a high degree of risk and is not suitable for all investors. Losses can exceed the initial investment. Please ensure you fully understand the risks and take appropriate care to manage your risk. \n\nContact Directly : t.me/fxdreemaTUT\nThis Will Expire on 2022.30.08"
#property version "1.0"
#property strict
/************************************************************************************************************************/
/************************************************************************************************************************/
#define PROJECT_ID "mt5-7049"
#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 false
#define ENABLE_STATUS false
#define ENABLE_TEST_INDICATORS false
#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 1 // 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_TIMER_PERIOD 60 // Timer event period (in seconds)
#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_FIRSTLEVEL 806
#define OBJPROP_TIME1 807
#define OBJPROP_TIME2 808
#define OBJPROP_TIME3 809
#define OBJPROP_PRICE1 810
#define OBJPROP_PRICE2 811
#define OBJPROP_PRICE3 812
#define OBJPROP_BARSHIFT1 813
#define OBJPROP_BARSHIFT2 814
#define OBJPROP_BARSHIFT3 815
#define SEL_CURRENT 0
#define SEL_INITIAL 1
input double Autolots = 0.0; // Autolots
input double SL = 0.0; // SL
input double TP = 0.0; // TP
input bool Use_Trailing_Stops = true; // Use_Trailing_Stops
input double Stops = 0.0; // Stops
input double Steps = 0.0; // Steps
input double Starts = 0.0; // Starts
input double Bar_Count = 0.0; // Bar_Count
input double Bar_Size = 0.0; // Bar_Size
input double STR = 0.0; // STR
input double Gridsize = 0.0; // Gridsize
input double Trail_Pen = 0.0; // Trail_Pen
input bool Stops_Only = false; // Stops_Only
input bool Limits_Only = true; // Limits_Only
input int MagicStart = 7049; // Magic Number, kind of...
class c
{
public:
static double Autolots;
static double SL;
static double TP;
static bool Use_Trailing_Stops;
static double Stops;
static double Steps;
static double Starts;
static double Bar_Count;
static double Bar_Size;
static double STR;
static double Gridsize;
static double Trail_Pen;
static bool Stops_Only;
static bool Limits_Only;
static int MagicStart;
};
double c::Autolots;
double c::SL;
double c::TP;
bool c::Use_Trailing_Stops;
double c::Stops;
double c::Steps;
double c::Starts;
double c::Bar_Count;
double c::Bar_Size;
double c::STR;
double c::Gridsize;
double c::Trail_Pen;
bool c::Stops_Only;
bool c::Limits_Only;
int c::MagicStart;
class v
{
public:
};
string fxdBlocksLookupTable[];
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 USE_VIRTUAL_STOPS = VIRTUAL_STOPS_ENABLED;
string FXD_CURRENT_SYMBOL = "";
int FXD_BLOCKS_COUNT = 13;
datetime FXD_TICKSKIP_UNTIL = 0;
int FXD_ICUSTOM_HANDLES_IDS[]; // only used in MQL5
string FXD_ICUSTOM_HANDLES_KEYS[]; // only used in MQL5
struct fxd_onchart
{
int id;
long lparam;
double dparam;
string sparam;
};
fxd_onchart FXD_ONCHART;
/************************************************************************************************************************/
/************************************************************************************************************************/
int OnInit()
{
// код доступен только после оплаты
}
void OnTick()
{
// код доступен только после оплаты
}
void OnTrade()
{
if (false) OnTradeEventDetector * dummy = new OnTradeEventDetector();
}
void OnTimer()
{
}
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;
int blocks_to_run[] = {9,11};
for (int i=0; i<ArraySize(blocks_to_run); i++) {
_blocks_[blocks_to_run[i]].run();
}
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();
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,typename T6,typename T7>
class MDL_ImpulseUp: public BlockCalls
{
public: /* Input Parameters */
T1 SignalType;
T2 QuietBarsCount;
T3 QuietBarsMinRange;
T4 ImpulseStrength;
T5 ImpulseShift;
T6 Symbol;
T7 Period;
/* Static Parameters */
double QBrange;
datetime BarTime;
datetime BarTime2;
double InpOpen;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_ImpulseUp()
{
SignalType = (string)"continuous";
QuietBarsCount = (int)3;
QuietBarsMinRange = (double)10.0;
ImpulseStrength = (double)3.0;
ImpulseShift = (int)0;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
/* Static Parameters (initial value) */
QBrange = -1;
BarTime = 0;
BarTime2 = 0;
InpOpen = 0;
}
public: /* The main method */
virtual void _execute_()
{
int i = 0;
double MaxSize = 0;
bool NewBarComes = false;
bool pass = false;
if (BarTime < iTime(Symbol,Period,1) || QBrange == -1)
{
BarTime = (int)iTime(Symbol,Period,1);
QBrange = 0;
for (i=0; i < QuietBarsCount; i++)
{
int shift = i + 1 + ImpulseShift;
MaxSize = iHigh(Symbol,Period,shift) - iLow(Symbol,Period,shift);
if (MaxSize > QBrange)
{
QBrange = MaxSize;
}
}
InpOpen = iOpen(Symbol,Period,ImpulseShift);
NewBarComes = true;
}
if (
(SignalType == "continuous" || BarTime2 < iTime(Symbol,Period,1))
&& ((ImpulseShift == 0 && InpOpen > 0) || NewBarComes == true)
&& QBrange > toDigits(QuietBarsMinRange, Symbol)
)
{
double ImpSize = iClose(Symbol,Period,ImpulseShift) - InpOpen;
if (ImpSize >= QBrange * ImpulseStrength)
{
if (SignalType != "continuous")
{
BarTime2 = (int)iTime(Symbol,Period,1);
}
pass = true;
}
}
if (pass == true) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename _T5_,typename T6,typename T7,typename T8,typename T9,typename T10,typename T11,typename T12,typename T13,typename T14,typename T15,typename _T15_,typename T16,typename T17,typename T18,typename T19,typename T20,typename T21,typename T22,typename _T22_,typename T23,typename _T23_,typename T24,typename _T24_,typename T25,typename T26,typename T27,typename T28,typename _T28_,typename T29,typename _T29_,typename T30,typename _T30_,typename T31,typename T32,typename T33,typename T34,typename T35,typename T36,typename T37,typename T38,typename T39,typename _T39_,typename T40,typename T41,typename T42>
class MDL_GridPendingBuys2: public BlockCalls
{
public: /* Input Parameters */
T1 Group;
T2 Symbol;
T3 GridOrdersCount;
T4 GridStart;
T5 fGridStart; virtual _T5_ _fGridStart_(){return(_T5_)0;}
T6 GridStartOffset;
T7 GridStartRoundNumberPips;
T8 GridSize;
T9 VolumeMode;
T10 VolumeSize;
T11 VolumeSizeRisk;
T12 VolumeRisk;
T13 VolumePercent;
T14 VolumeBlockPercent;
T15 dVolumeSize; virtual _T15_ _dVolumeSize_(){return(_T15_)0;}
T16 FixedRatioUnitSize;
T17 FixedRatioDelta;
T18 VolumeUpperLimit;
T19 gSLmode;
T20 StopLossPips;
T21 GridSizeSL;
T22 dlStopLoss; virtual _T22_ _dlStopLoss_(){return(_T22_)0;}
T23 dpStopLoss; virtual _T23_ _dpStopLoss_(){return(_T23_)0;}
T24 ddStopLoss; virtual _T24_ _ddStopLoss_(){return(_T24_)0;}
T25 gTPmode;
T26 TakeProfitPips;
T27 GridSizeTP;
T28 dlTakeProfit; virtual _T28_ _dlTakeProfit_(){return(_T28_)0;}
T29 dpTakeProfit; virtual _T29_ _dpTakeProfit_(){return(_T29_)0;}
T30 ddTakeProfit; virtual _T30_ _ddTakeProfit_(){return(_T30_)0;}
T31 GridLevelsGradation;
T32 GridVolumesGradation;
T33 GridSLgradation;
T34 GridTPgradation;
T35 ExpMode;
T36 ExpDays;
T37 ExpHours;
T38 ExpMinutes;
T39 dExp; virtual _T39_ _dExp_(){return(_T39_)0;}
T40 Slippage;
T41 MyComment;
T42 ArrowColorBuy;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_GridPendingBuys2()
{
Group = (string)"";
Symbol = (string)CurrentSymbol();
GridOrdersCount = (int)3;
GridStart = (string)"ask";
GridStartOffset = (double)0.0;
GridStartRoundNumberPips = (double)0.0;
GridSize = (double)25.0;
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;
VolumeUpperLimit = (double)0.0;
gSLmode = (string)"fixed";
StopLossPips = (double)50.0;
GridSizeSL = (double)100.0;
gTPmode = (string)"fixed";
TakeProfitPips = (double)50.0;
GridSizeTP = (double)100.0;
GridLevelsGradation = (double)100.0;
GridVolumesGradation = (double)100.0;
GridSLgradation = (double)100.0;
GridTPgradation = (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 op=0;
if (GridStart == "ask") {op = SymbolAsk(Symbol);}
else if (GridStart == "bid") {op = SymbolBid(Symbol);}
else if (GridStart == "mid") {op = (SymbolAsk(Symbol) + SymbolBid(Symbol))/2;}
else if (GridStart == "function") {op = _fGridStart_();}
op = op + toDigits(GridStartOffset, Symbol);
if (GridStartRoundNumberPips != 0)
{
double grid_start_round_number = toDigits(GridStartRoundNumberPips, Symbol);
op = MathCeil(op / grid_start_round_number) * grid_start_round_number;
}
double sll = 0, slp = 0, tpl = 0, tpp = 0;
if (gSLmode == "fixed") {slp = StopLossPips;}
else if (gSLmode == "gridsize") {slp = GridSize * (GridSizeSL / 100);}
else if (gSLmode == "dynamicPips") {slp = _dpStopLoss_();}
else if (gSLmode == "dynamicDigits") {slp = toPips(_ddStopLoss_(), Symbol);}
else if (gSLmode == "dynamicLevel") {sll = _dlStopLoss_();}
else if (gSLmode == "dynamicLevelAll") {sll = _dlStopLoss_();}
if (gTPmode == "fixed") {tpp = TakeProfitPips;}
else if (gTPmode == "gridsize") {tpp = GridSize * (GridSizeTP / 100);}
else if (gTPmode == "dynamicPips") {tpp = _dpTakeProfit_();}
else if (gTPmode == "dynamicDigits") {tpp = toPips(_ddTakeProfit_(), Symbol);}
else if (gTPmode == "dynamicLevel") {tpl = _dlTakeProfit_();}
else if (gTPmode == "dynamicLevelAll") {tpl = _dlTakeProfit_();}
double lots = 0;
double pre_sll = sll;
if (pre_sll == 0) {pre_sll = op;}
double pre_sl_pips = toPips(op - (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_();}
lots = AlignLots(Symbol, lots, 0, VolumeUpperLimit);
datetime exp = ExpirationTime(ExpMode, ExpDays, ExpHours, ExpMinutes, _dExp_());
long ticket = 0;
double gSize = GridSize;
double gSL = slp;
double gTP = tpp;
if (sll > 0)
{
gSL = toPips(op - sll, Symbol);
if (gSLmode == "dynamicLevelAll")
{
gSL = 0;
}
else if (gSLmode != "dynamicLevelAll")
{
sll = 0;
}
}
if (tpl > 0)
{
gTP = toPips(tpl-op, Symbol);
if (gTPmode == "dynamicLevelAll")
{
gTP = 0;
}
else if (gTPmode != "dynamicLevelAll")
{
tpl = 0;
}
}
for (int cnt = 1; cnt <= GridOrdersCount; cnt++)
{
if (cnt == 1)
{
if (gSLmode == "gridsize") gSL = gSize * (GridSizeSL / 100);
if (gTPmode == "gridsize") gTP = gSize * (GridSizeTP / 100);
}
else
{
if (GridLevelsGradation > 0) gSize = gSize * (GridLevelsGradation / 100);
lots = lots * (GridVolumesGradation / 100);
if (gSLmode == "gridsize") gSL = gSize * (GridSizeSL / 100);
gSL = gSL * (GridSLgradation / 100);
if (gTPmode == "gridsize") gTP = gSize * (GridSizeTP / 100);
gTP = gTP * (GridTPgradation / 100);
}
op = op + toDigits(gSize, Symbol);
double lotsAligned = AlignLots(Symbol, lots, 0, VolumeUpperLimit);
ticket = BuyLater(Symbol, lotsAligned, op, sll, tpl, gSL, gTP, Slippage, exp, (MagicStart + (int)Group), MyComment, ArrowColorBuy);
}
if (ticket > 0) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename _T5_,typename T6,typename T7,typename T8,typename T9,typename T10,typename T11,typename T12,typename T13,typename T14,typename T15,typename _T15_,typename T16,typename T17,typename T18,typename T19,typename T20,typename T21,typename T22,typename _T22_,typename T23,typename _T23_,typename T24,typename _T24_,typename T25,typename T26,typename T27,typename T28,typename _T28_,typename T29,typename _T29_,typename T30,typename _T30_,typename T31,typename T32,typename T33,typename T34,typename T35,typename T36,typename T37,typename T38,typename T39,typename _T39_,typename T40,typename T41,typename T42>
class MDL_GridPendingSells2: public BlockCalls
{
public: /* Input Parameters */
T1 Group;
T2 Symbol;
T3 GridOrdersCount;
T4 GridStart;
T5 fGridStart; virtual _T5_ _fGridStart_(){return(_T5_)0;}
T6 GridStartOffset;
T7 GridStartRoundNumberPips;
T8 GridSize;
T9 VolumeMode;
T10 VolumeSize;
T11 VolumeSizeRisk;
T12 VolumeRisk;
T13 VolumePercent;
T14 VolumeBlockPercent;
T15 dVolumeSize; virtual _T15_ _dVolumeSize_(){return(_T15_)0;}
T16 FixedRatioUnitSize;
T17 FixedRatioDelta;
T18 VolumeUpperLimit;
T19 gSLmode;
T20 StopLossPips;
T21 GridSizeSL;
T22 dlStopLoss; virtual _T22_ _dlStopLoss_(){return(_T22_)0;}
T23 dpStopLoss; virtual _T23_ _dpStopLoss_(){return(_T23_)0;}
T24 ddStopLoss; virtual _T24_ _ddStopLoss_(){return(_T24_)0;}
T25 gTPmode;
T26 TakeProfitPips;
T27 GridSizeTP;
T28 dlTakeProfit; virtual _T28_ _dlTakeProfit_(){return(_T28_)0;}
T29 dpTakeProfit; virtual _T29_ _dpTakeProfit_(){return(_T29_)0;}
T30 ddTakeProfit; virtual _T30_ _ddTakeProfit_(){return(_T30_)0;}
T31 GridLevelsGradation;
T32 GridVolumesGradation;
T33 GridSLgradation;
T34 GridTPgradation;
T35 ExpMode;
T36 ExpDays;
T37 ExpHours;
T38 ExpMinutes;
T39 dExp; virtual _T39_ _dExp_(){return(_T39_)0;}
T40 Slippage;
T41 MyComment;
T42 ArrowColorSell;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_GridPendingSells2()
{
Group = (string)"";
Symbol = (string)CurrentSymbol();
GridOrdersCount = (int)3;
GridStart = (string)"bid";
GridStartOffset = (double)0.0;
GridStartRoundNumberPips = (double)0.0;
GridSize = (double)25.0;
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;
VolumeUpperLimit = (double)0.0;
gSLmode = (string)"fixed";
StopLossPips = (double)50.0;
GridSizeSL = (double)100.0;
gTPmode = (string)"fixed";
TakeProfitPips = (double)50.0;
GridSizeTP = (double)100.0;
GridLevelsGradation = (double)100.0;
GridVolumesGradation = (double)100.0;
GridSLgradation = (double)100.0;
GridTPgradation = (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 op=0;
if (GridStart == "ask") {op = SymbolAsk(Symbol);}
else if (GridStart == "bid") {op = SymbolBid(Symbol);}
else if (GridStart == "mid") {op = (SymbolAsk(Symbol) + SymbolBid(Symbol)) / 2;}
else if (GridStart == "function") {op = _fGridStart_();}
op = op - toDigits(GridStartOffset, Symbol);
if (GridStartRoundNumberPips != 0)
{
double grid_start_round_number = toDigits(GridStartRoundNumberPips, Symbol);
op = MathFloor(op / grid_start_round_number) * grid_start_round_number;
}
double sll = 0, slp = 0, tpl = 0, tpp = 0;
if (gSLmode == "fixed") {slp = StopLossPips;}
else if (gSLmode == "gridsize") {slp = GridSize * (GridSizeSL / 100);}
else if (gSLmode == "dynamicPips") {slp = _dpStopLoss_();}
else if (gSLmode == "dynamicDigits") {slp = toPips(_ddStopLoss_(), Symbol);}
else if (gSLmode == "dynamicLevel") {sll = _dlStopLoss_();}
else if (gSLmode == "dynamicLevelAll") {sll = _dlStopLoss_();}
if (gTPmode == "fixed") {tpp = TakeProfitPips;}
else if (gTPmode == "gridsize") {tpp = GridSize * (GridSizeTP / 100);}
else if (gTPmode == "dynamicPips") {tpp = _dpTakeProfit_();}
else if (gTPmode == "dynamicDigits") {tpp = toPips(_ddTakeProfit_(), Symbol);}
else if (gTPmode == "dynamicLevel") {tpl = _dlTakeProfit_();}
else if (gTPmode == "dynamicLevelAll") {tpl = _dlTakeProfit_();}
double lots = 0;
double pre_sll = sll;
if (pre_sll == 0) {pre_sll = op;}
double pre_sl_pips = toPips((pre_sll + toDigits(slp, Symbol)) - op, 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_();}
lots = AlignLots(Symbol, lots, 0, VolumeUpperLimit);
datetime exp = ExpirationTime(ExpMode, ExpDays, ExpHours, ExpMinutes, _dExp_());
long ticket = 0;
double gSize = GridSize;
double gSL = slp;
double gTP = tpp;
if (sll > 0)
{
gSL = toPips(sll - op, Symbol);
if (gSLmode == "dynamicLevelAll")
{
gSL = 0;
}
else if (gSLmode != "dynamicLevelAll")
{
sll = 0;
}
}
if (tpl > 0)
{
gTP = toPips(op - tpl, Symbol);
if (gTPmode == "dynamicLevelAll")
{
gTP = 0;
}
else if (gTPmode != "dynamicLevelAll")
{
tpl = 0;
}
}
for (int cnt = 1; cnt <= GridOrdersCount; cnt++)
{
if (cnt == 1)
{
if (gSLmode == "gridsize") gSL = gSize * (GridSizeSL / 100);
if (gTPmode == "gridsize") gTP = gSize * (GridSizeTP / 100);
}
else
{
if (GridLevelsGradation > 0) gSize = gSize * (GridLevelsGradation / 100);
lots = lots * (GridVolumesGradation / 100);
if (gSLmode == "gridsize") gSL = gSize * (GridSizeSL / 100);
gSL = gSL * (GridSLgradation / 100);
if (gTPmode == "gridsize") gTP = gSize * (GridSizeTP / 100);
gTP = gTP * (GridTPgradation / 100);
}
op = op - toDigits(gSize, Symbol);
double lotsAligned = AlignLots(Symbol, lots, 0, VolumeUpperLimit);
ticket = SellLater(Symbol, lotsAligned, op, sll, tpl, gSL, gTP, Slippage, exp, (MagicStart + (int)Group), MyComment, ArrowColorSell);
}
if (ticket > 0) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7>
class MDL_ImpulseDn: public BlockCalls
{
public: /* Input Parameters */
T1 SignalType;
T2 QuietBarsCount;
T3 QuietBarsMinRange;
T4 ImpulseStrength;
T5 ImpulseShift;
T6 Symbol;
T7 Period;
/* Static Parameters */
double QBrange;
datetime BarTime;
datetime BarTime2;
double InpOpen;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_ImpulseDn()
{
SignalType = (string)"continuous";
QuietBarsCount = (int)3;
QuietBarsMinRange = (double)10.0;
ImpulseStrength = (double)3.0;
ImpulseShift = (int)0;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
/* Static Parameters (initial value) */
QBrange = -1;
BarTime = 0;
BarTime2 = 0;
InpOpen = 0;
}
public: /* The main method */
virtual void _execute_()
{
int i = 0;
double MaxSize = 0;
bool NewBarComes = false;
bool pass = false;
if (BarTime < iTime(Symbol,Period,1) || QBrange == -1)
{
BarTime = (int)iTime(Symbol,Period,1);
QBrange = 0;
for (i=0; i < QuietBarsCount; i++)
{
int shift = i + 1 + ImpulseShift;
MaxSize = iHigh(Symbol,Period,shift) - iLow(Symbol,Period,shift);
if (MaxSize > QBrange)
{
QBrange = MaxSize;
}
}
InpOpen = iOpen(Symbol,Period,ImpulseShift);
NewBarComes = true;
}
if (
(SignalType == "continuous" || BarTime2 < iTime(Symbol,Period,1))
&& ((ImpulseShift == 0 && InpOpen > 0) || NewBarComes == true)
&& QBrange > toDigits(QuietBarsMinRange, Symbol)
)
{
double ImpSize = InpOpen - iClose(Symbol,Period,ImpulseShift);
if (ImpSize >= QBrange * ImpulseStrength)
{
if (SignalType != "continuous")
{
BarTime2 = (int)iTime(Symbol,Period,1);
}
pass = true;
}
}
if (pass == true) {_callback_(1);} else {_callback_(0);}
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,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 T21,typename _T21_,typename T22>
class MDL_TrailingStopAvgPrice: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 Symbol;
T4 BuysOrSells;
T5 TrailWhat;
T6 TrailingStopMode;
T7 tStopPips;
T8 ftStop; virtual _T8_ _ftStop_(){return(_T8_)0;}
T9 tStopMoney;
T10 TrailingStepMode;
T11 tStepPips;
T12 tStepPercentTS;
T13 TrailingStartMode;
T14 tStartPips;
T15 tStartPercentTS;
T16 ftStart; virtual _T16_ _ftStart_(){return(_T16_)0;}
T17 resetOnTrade;
T18 TrailingTPmode;
T19 tTPpips;
T20 tTPpercentTS;
T21 ftTP; virtual _T21_ _ftTP_(){return(_T21_)0;}
T22 LevelColor;
/* Static Parameters */
double avg_lots0;
double group_stop;
string change_detect0;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_TrailingStopAvgPrice()
{
GroupMode = (string)"group";
Group = (string)"";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
TrailWhat = (int)1;
TrailingStopMode = (string)"fixed";
tStopPips = (double)40.0;
tStopMoney = (double)10.0;
TrailingStepMode = (string)"fixed";
tStepPips = (double)1.0;
tStepPercentTS = (double)10.0;
TrailingStartMode = (string)"none";
tStartPips = (double)10.0;
tStartPercentTS = (double)100.0;
resetOnTrade = (bool)true;
TrailingTPmode = (string)"none";
tTPpips = (double)20.0;
tTPpercentTS = (double)200.0;
LevelColor = (color)clrDeepPink;
/* Static Parameters (initial value) */
avg_lots0 = 0;
group_stop = 0;
change_detect0 = "";
}
public: /* The main method */
virtual void _execute_()
{
int index = 0;
double avg_price = 0;
double avg_load = 0;
double avg_lots = 0; // Average sum of lots - it can be negative
double profit = 0;
double askbid = 0;
double bidask = 0;
int trades_count = 0; // Count of Trades to work with
bool resetSL = false;
ulong tickets[]; ArrayResize(tickets, 0); // Array with tickets to modify
string change_detect = "";
int total = TradesTotal();
for (index = 0; index < total; index++)
{
if (!TradeSelectByIndex(index, GroupMode, Group, "symbol", Symbol, BuysOrSells)) {continue;}
if (OrderType() == 0)
{
avg_load = avg_load + (OrderOpenPrice() * OrderLots());
avg_lots = avg_lots + OrderLots();
}
else
{
avg_load = avg_load - (OrderOpenPrice() * OrderLots());
avg_lots = avg_lots - OrderLots();
}
ArrayEnsureValue(tickets, (ulong)OrderTicket());
profit = profit + NormalizeDouble(OrderProfit() + OrderCommission() + OrderSwap(), 2);
change_detect = (string)OrderTicket() + change_detect;
trades_count++;
}
avg_price = 0;
if (avg_lots != 0)
{
avg_price = avg_load / avg_lots;
}
if (change_detect0 != change_detect)
{
if (trades_count == 0)
{
avg_lots0 = 0;
group_stop = 0;
}
else
{
group_stop = 0;
if (resetOnTrade == true)
{
avg_lots0 = avg_lots;
resetSL = true;
}
}
change_detect0 = change_detect;
}
if (avg_lots != 0)
{
int polarity = 0;
if (avg_lots > 0)
{
polarity = 1;
askbid = SymbolAsk(Symbol);
bidask = SymbolBid(Symbol);
}
else
{
polarity = -1;
askbid = SymbolBid(Symbol);
bidask = SymbolAsk(Symbol);
}
double t_stop = 0;
if (TrailingStopMode == "fixed") {t_stop = tStopPips;}
else if (TrailingStopMode == "dynamicSize") {t_stop = _ftStop_();}
else if (TrailingStopMode == "function")
{
t_stop = _ftStop_();
t_stop = toPips(MathAbs(askbid-t_stop), Symbol);
}
else if (TrailingStopMode == "money")
{
double tick_value = SymbolInfoDouble(Symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(Symbol, SYMBOL_TRADE_TICK_SIZE);
double point = SymbolInfoDouble(Symbol, SYMBOL_POINT);
double tickvalue = ((tick_value / tick_size) * point);
t_stop = tStopMoney;
t_stop = t_stop / ((MathAbs(avg_lots) * PipValue(Symbol)));
t_stop = t_stop / tickvalue;
}
double t_start = 0;
if (TrailingStartMode == "none") {t_start = -EMPTY_VALUE;}
else if (TrailingStartMode == "zero") {t_start = 0;}
else if (TrailingStartMode == "fixed") {t_start = tStartPips;}
else if (TrailingStartMode == "percentTS") {t_start = t_stop * (tStartPercentTS / 100);}
else if (TrailingStartMode == "function") {t_start = _ftStart_();}
double t_step = 0;
if (TrailingStepMode == "fixed") {t_step = tStepPips;}
else if (TrailingStepMode == "percentTS") {t_step = t_stop * (tStepPercentTS / 100);}
double t_opp = -1;
if (TrailingTPmode == "none") {t_opp = -1;}
else if (TrailingTPmode == "clear") {t_opp = 0;}
else if (TrailingTPmode == "fixed") {t_opp = MathAbs(toPips(avg_price - group_stop, Symbol));}
else if (TrailingTPmode == "percentTS") {t_opp = MathAbs(toPips(avg_price - t_stop, Symbol)) * (tTPpercentTS/100);}
else if (TrailingTPmode == "function") {t_opp = _ftTP_();}
bool go_modify = false;
if (polarity == 1 && TrailWhat * (askbid - avg_price) > toDigits(t_start, Symbol))
{
if ((TrailWhat * (askbid - group_stop) >= toDigits(t_stop + t_step, Symbol)) || group_stop==0 || resetSL == true)
{
group_stop = (askbid - TrailWhat * toDigits(t_stop, Symbol));
go_modify = true;
}
}
else if (polarity == -1 && TrailWhat * (avg_price - askbid) > toDigits(t_start, Symbol))
{
if ((TrailWhat * (group_stop - askbid) >= toDigits(t_stop + t_step, Symbol)) || group_stop == 0 || resetSL == true)
{
group_stop = (askbid + TrailWhat * toDigits(t_stop, Symbol));
go_modify = true;
}
}
if (go_modify==true)
{
for (index = ArraySize(tickets) - 1; index >= 0; index--)
{
if (TradeSelectByTicket(tickets[index]))
{
bool success = true;
double stopslevel = (double)SymbolInfoInteger(OrderSymbol(), SYMBOL_TRADE_STOPS_LEVEL);
stopslevel = toDigits(stopslevel / PipValue(OrderSymbol()), OrderSymbol());
double fsl = MathAbs(group_stop); // future SL
double limit = 0;
if (OrderType() == 0)
{
limit = bidask - stopslevel * TrailWhat;
if (fsl > limit) {fsl = limit;}
}
else
{
limit = bidask + stopslevel * TrailWhat;
if (fsl < limit) {fsl = limit;}
}
if (TrailWhat == 1)
{
if (t_opp < 0) {t_opp = attrTakeProfit();}
if (
attrStopLoss() == 0
|| (OrderType() == 0 && (attrStopLoss() < fsl || resetSL == true))
|| (OrderType() == 1 && (attrStopLoss() > fsl || resetSL == true))
)
{
success = ModifyStops(OrderTicket(), group_stop, t_opp, LevelColor);
}
}
else
{
if (t_opp < 0) {t_opp = attrStopLoss();}
if (
attrTakeProfit() == 0
|| (OrderType() == 0 && (attrTakeProfit() > fsl || resetSL == true))
|| (OrderType() == 1 && (attrTakeProfit() < fsl || resetSL == true))
)
{
success = ModifyStops(OrderTicket(), t_opp, group_stop, LevelColor);
}
}
}
}
}
}
_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 _T14_,typename T15,typename _T15_,typename T16,typename T17,typename T18,typename T19,typename T20,typename T21,typename T22,typename T23,typename T24,typename _T24_,typename T25,typename _T25_,typename T26,typename T27,typename T28,typename T29,typename _T29_,typename T30>
class MDL_TrailingStop2: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
T6 TrailWhat;
T7 TrailingReferencePrice;
T8 TrailingStopMode;
T9 tStopPips;
T10 tStopMoney;
T11 tStopMultiple;
T12 tStopPercentTP;
T13 tStopPercentProfit;
T14 ftStop; virtual _T14_ _ftStop_(){return(_T14_)0;}
T15 ftDigits; virtual _T15_ _ftDigits_(){return(_T15_)0;}
T16 TrailingStepMode;
T17 tStepPips;
T18 tStepPercentTS;
T19 TrailingStartMode;
T20 tStartPips;
T21 tStartPercentTS;
T22 tStartPercentSL;
T23 tStartPercentTP;
T24 ftStart; virtual _T24_ _ftStart_(){return(_T24_)0;}
T25 ftStartFraction; virtual _T25_ _ftStartFraction_(){return(_T25_)0;}
T26 TrailingTPmode;
T27 tTPpips;
T28 tTPpercentTS;
T29 ftTP; virtual _T29_ _ftTP_(){return(_T29_)0;}
T30 LevelColor;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_TrailingStop2()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
TrailWhat = (int)1;
TrailingReferencePrice = (int)0;
TrailingStopMode = (string)"fixed";
tStopPips = (double)40.0;
tStopMoney = (double)10.0;
tStopMultiple = (string)"20/5, 30/10";
tStopPercentTP = (double)100.0;
tStopPercentProfit = (double)50.0;
TrailingStepMode = (string)"fixed";
tStepPips = (double)1.0;
tStepPercentTS = (double)10.0;
TrailingStartMode = (string)"none";
tStartPips = (double)10.0;
tStartPercentTS = (double)100.0;
tStartPercentSL = (double)10.0;
tStartPercentTP = (double)10.0;
TrailingTPmode = (string)"none";
tTPpips = (double)20.0;
tTPpercentTS = (double)200.0;
LevelColor = (color)clrDeepPink;
}
public: /* The main method */
virtual void _execute_()
{
int total = TradesTotal();
for (int index = 0; index < total; index++)
{
if (TradeSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells))
{
string symbol = OrderSymbol();
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double stopslevel = (double)SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
int polarity = 1; // 1 = buy, -1 = sell
double askbid = ask; // could be Ask or Bid
double bidask = bid; // the opposite of askbid
double sltp = 0; // could be SL or TP
double tpsl = 0; // the opposite of sltp
double fsl = 0; // Freeze Level
double limit = 0;
double t_stop = 0; // trailing STOP
double t_start = 0; // trailing START
double t_step = 0; // trailing STEP
double t_opp = 0; // trailing Opposite (TP when trailing SL or SL when trailing TP)
if (TrailWhat > 0) {
sltp = attrStopLoss();
tpsl = attrTakeProfit();
}
else {
sltp = attrTakeProfit();
tpsl = attrStopLoss();
}
if (OrderType() == 0) {
polarity = 1;
if (TrailingReferencePrice == 1)
{
askbid = bid;
bidask = ask;
}
}
else if (OrderType() == 1) {
polarity = -1;
askbid = bid;
bidask = ask;
if (TrailingReferencePrice == 1) {
askbid = ask;
bidask = bid;
}
}
if (TrailingReferencePrice == 2) {
askbid = (ask + bid) / 2;
bidask = (ask + bid) / 2;
}
if (TrailingStopMode == "fixed") {t_stop = toDigits(tStopPips, symbol);}
else if (TrailingStopMode == "percentTP") {t_stop = (MathAbs(OrderOpenPrice() - tpsl)) * (tStopPercentTP / 100);}
else if (TrailingStopMode == "percentProfit") {t_stop = (MathAbs(askbid - OrderOpenPrice())) * (tStopPercentProfit / 100);}
else if (TrailingStopMode == "dynamicSize") {t_stop = toDigits(_ftStop_(), symbol);}
else if (TrailingStopMode == "dynamicDigits") {t_stop = _ftDigits_();}
else if (TrailingStopMode == "dynamic")
{
t_stop = _ftStop_();
t_stop = (polarity == 1) ? ask - t_stop : t_stop - bid;
}
else if (TrailingStopMode == "money")
{
t_stop = tStopMoney;
double lotsize = SymbolInfoDouble(symbol, SYMBOL_TRADE_CONTRACT_SIZE);
double tickvalue = (SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE) / SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE)) * SymbolInfoDouble(symbol, SYMBOL_POINT);
t_stop = t_stop / (OrderLots() * PipValue(symbol));
t_stop = toDigits(t_stop / tickvalue, symbol);
}
if (TrailingStartMode == "none") {t_start = -EMPTY_VALUE;}
else if (TrailingStartMode == "zero") {t_start = 0;}
else if (TrailingStartMode == "fixed") {t_start = toDigits(tStartPips, symbol);}
else if (TrailingStartMode == "percentTS") {t_start = t_stop * (tStartPercentTS / 100);}
else if (TrailingStartMode == "percentTP") {t_start = (MathAbs(OrderOpenPrice() - tpsl)) * (tStartPercentTP / 100);}
else if (TrailingStartMode == "percentSL") {t_start = (MathAbs(OrderOpenPrice() - sltp)) * (tStartPercentSL / 100);}
else if (TrailingStartMode == "function") {t_start = toDigits(_ftStart_(), symbol);}
else if (TrailingStartMode == "functionFraction") {t_start = _ftStartFraction_();}
if (TrailingStepMode == "fixed") {t_step = toDigits(tStepPips, symbol);}
else if (TrailingStepMode == "percentTS") {t_step = t_stop * (tStepPercentTS / 100);}
if (TrailingTPmode == "none") {t_opp = tpsl;}
else if (TrailingTPmode == "clear") {t_opp = 0;}
else if (TrailingTPmode == "fixed") {t_opp = TrailWhat * (OrderOpenPrice() + (polarity * toDigits(tTPpips, symbol)));}
else if (TrailingTPmode == "percentTS") {t_opp = TrailWhat * (OrderOpenPrice() + (polarity * toDigits(t_stop * (tTPpercentTS / 100), symbol)));}
else if (TrailingTPmode == "function") {t_opp = _ftTP_();}
if (TrailingStopMode == "multiple")
{
bool next = false;
string tmp1[];
string tmp2[];
StringExplode(",", tStopMultiple, tmp1);
for (int i = ArraySize(tmp1)-1; i >= 0; i--)
{
StringExplode("/", tmp1[i], tmp2);
if (ArraySize(tmp2) != 2) {continue;}
double new_start = toDigits(StringToDouble(StringTrim(tmp2[0])), symbol);
if (new_start < t_start) {continue;}
double diff = NormalizeDouble(askbid - OrderOpenPrice(), digits);
if (polarity * TrailWhat * diff >= new_start)
{
t_start = new_start;
t_stop = polarity * TrailWhat * diff - toDigits(StringToDouble(StringTrim(tmp2[1])), symbol);
next = true;
break;
}
}
if (next == false) {continue;}
}
stopslevel = stopslevel * SymbolInfoDouble(symbol, SYMBOL_POINT);
if (t_stop <= 0) {continue;}
if (OrderType() == 0 && TrailWhat * (askbid - OrderOpenPrice()) > t_start)
{
if ((TrailWhat * (askbid - sltp) >= t_stop + t_step) || sltp == 0)
{
fsl = MathAbs(askbid - t_stop);
limit = bidask - stopslevel * TrailWhat;
if (fsl > limit) {fsl = limit;}
if (TrailWhat == 1) // trail SL
{
if (sltp == 0 || sltp < fsl) {
ModifyStops(OrderTicket(), askbid - t_stop, t_opp, LevelColor);
}
}
else { // trail TP
if (sltp == 0 || sltp > fsl) {
ModifyStops(OrderTicket(), t_opp, askbid + t_stop, LevelColor);
}
}
}
}
else if (OrderType() == 1 && TrailWhat * (OrderOpenPrice() - askbid) > t_start)
{
if ((TrailWhat * (sltp - askbid) >= t_stop + t_step) || sltp == 0)
{
fsl = MathAbs(askbid + t_stop);
limit = bidask + stopslevel * TrailWhat;
if (fsl < limit) {fsl = limit;}
if (TrailWhat == 1)
{ // trail SL
if (sltp == 0 || sltp > fsl)
{
ModifyStops(OrderTicket(), askbid + t_stop, t_opp, LevelColor);
}
}
else
{ // trail TP
if (sltp == 0 || sltp < fsl)
{
ModifyStops(OrderTicket(), t_opp, askbid - t_stop, LevelColor);
}
}
}
}
}
}
_callback_(1);
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename T7,typename T8,typename T9,typename _T9_,typename T10,typename _T10_,typename T11,typename _T11_,typename T12>
class MDL_TrailingPendingOrders: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
T6 LimitsOrStops;
T7 TrailingDistanceMode;
T8 tDistancePips;
T9 dtDistancePips; virtual _T9_ _dtDistancePips_(){return(_T9_)0;}
T10 dtDistanceDigits; virtual _T10_ _dtDistanceDigits_(){return(_T10_)0;}
T11 dtLevel; virtual _T11_ _dtLevel_(){return(_T11_)0;}
T12 tStepPips;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_TrailingPendingOrders()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
LimitsOrStops = (string)"both";
TrailingDistanceMode = (string)"fixed";
tDistancePips = (double)30.0;
tStepPips = (double)1.0;
}
public: /* The main method */
virtual void _execute_()
{
for (int index = OrdersTotal()-1; index >= 0; index--)
{
if (PendingOrderSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells, LimitsOrStops))
{
string symbol = OrderSymbol();
double price = (IsOrderTypeBuy()) ? SymbolAsk(symbol) : SymbolBid(symbol);
double distance = 0;
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
if (TrailingDistanceMode == "fixed") distance = toDigits(tDistancePips, symbol);
else if (TrailingDistanceMode == "dynamic") distance = price - _dtLevel_();
else if (TrailingDistanceMode == "dynamicPips") distance = toDigits(_dtDistancePips_(), symbol);
else if (TrailingDistanceMode == "dynamicDigits") distance = _dtDistanceDigits_();
distance = NormalizeDouble(MathAbs(distance), digits);
double old_op = 0, old_sl = 0, old_tp = 0;
double new_op = 0, new_sl = 0, new_tp = 0;
if (MathAbs(price - OrderOpenPrice()) >= MathAbs(distance + toDigits(tStepPips, symbol)))
{
old_sl = attrStopLoss();
old_tp = attrTakeProfit();
old_op = OrderOpenPrice();
if (IsOrderTypeBuy() == true)
{
new_op = IsOrderTypeStop() ? price + distance : price - distance;
if (old_sl > 0) new_sl = new_op - (old_op - old_sl);
if (old_tp > 0) new_tp = new_op + (old_tp - old_op);
}
else
{
new_op = IsOrderTypeStop() ? price - distance : price + distance;
if (old_sl > 0) new_sl = new_op + (old_sl - old_op);
if (old_tp > 0) new_tp = new_op - (old_op - old_tp);
}
ModifyOrder(OrderTicket(), new_op, new_sl, new_tp, 0, 0, OrderExpiration(), clrBlack);
}
}
}
_callback_(1);
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6>
class MDL_NoPendingOrders: public BlockCalls
{
public: /* Input Parameters */
T1 GroupMode;
T2 Group;
T3 SymbolMode;
T4 Symbol;
T5 BuysOrSells;
T6 LimitsOrStops;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_NoPendingOrders()
{
GroupMode = (string)"group";
Group = (string)"";
SymbolMode = (string)"symbol";
Symbol = (string)CurrentSymbol();
BuysOrSells = (string)"both";
LimitsOrStops = (string)"both";
}
public: /* The main method */
virtual void _execute_()
{
bool exist = false;
for (int index = OrdersTotal()-1; index >= 0; index--)
{
if (PendingOrderSelectByIndex(index, GroupMode, Group, SymbolMode, Symbol, BuysOrSells, LimitsOrStops))
{
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;}
T2 compare;
T3 Ro; virtual _T3_ _Ro_(){return(_T3_)0;}
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_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;}
T17 FormatNumber1;
T18 FormatTime1;
T19 Label2;
T20 Value2; virtual _T20_ _Value2_(){return(_T20_)0;}
T21 FormatNumber2;
T22 FormatTime2;
T23 Label3;
T24 Value3; virtual _T24_ _Value3_(){return(_T24_)0;}
T25 FormatNumber3;
T26 FormatTime3;
T27 Label4;
T28 Value4; virtual _T28_ _Value4_(){return(_T28_)0;}
T29 FormatNumber4;
T30 FormatTime4;
T31 Label5;
T32 Value5; virtual _T32_ _Value5_(){return(_T32_)0;}
T33 FormatNumber5;
T34 FormatTime5;
T35 Label6;
T36 Value6; virtual _T36_ _Value6_(){return(_T36_)0;}
T37 FormatNumber6;
T38 FormatTime6;
T39 Label7;
T40 Value7; virtual _T40_ _Value7_(){return(_T40_)0;}
T41 FormatNumber7;
T42 FormatTime7;
T43 Label8;
T44 Value8; virtual _T44_ _Value8_(){return(_T44_)0;}
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(ObjectFind(ObjChartID, nametitle) < 0)
{
if (!ObjectCreate(ObjChartID, nametitle, OBJ_LABEL, subwindow, 0, 0, 0, 0))
{
Print(__FUNCTION__, ": failed to create text object! Error code = ", GetLastError());
}
else
{
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_FONTSIZE, (int)(ObjTitleFontSize));
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_COLOR, ObjTitleFontColor);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_BACK, 0);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_SELECTABLE, 1);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_SELECTED, 0);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_HIDDEN, 1);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_CORNER, ObjCorner);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_ANCHOR, ObjAnchor);
ObjectSetString(ObjChartID, nametitle, OBJPROP_FONT, ObjTitleFont);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_XDISTANCE, ObjX);
ObjectSetInteger(ObjChartID, nametitle, OBJPROP_YDISTANCE, ObjY);
}
}
else
{
ObjX = (int)ObjectGetInteger(ObjChartID, nametitle, OBJPROP_XDISTANCE);
ObjY = (int)ObjectGetInteger(ObjChartID, nametitle, OBJPROP_YDISTANCE);
}
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)
{
ObjectDelete(ObjChartID, namelbl);
ObjectDelete(ObjChartID, name);
}
continue;
}
if (ObjectFind(ObjChartID, name) < 0)
{
if (textlbl == "")
{
continue;
}
if (ObjectCreate(ObjChartID, namelbl, OBJ_LABEL, subwindow, 0, 0, 0, 0))
{
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_CORNER, ObjCorner);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_ANCHOR, ObjAnchor);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_BACK, 0);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_SELECTABLE, 0);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_SELECTED, 0);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_HIDDEN, 1);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_FONTSIZE, ObjLabelsFontSize);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_COLOR, ObjLabelsFontColor);
ObjectSetString(ObjChartID, namelbl, OBJPROP_FONT, ObjLabelsFont);
}
else
{
Print(__FUNCTION__, ": failed to create text object! Error code = ", GetLastError());
}
if (ObjectCreate(ObjChartID, name, OBJ_LABEL, subwindow, 0, 0, 0, 0))
{
ObjectSetInteger(ObjChartID, name, OBJPROP_CORNER, ObjCorner);
ObjectSetInteger(ObjChartID, name, OBJPROP_ANCHOR, ObjAnchor);
ObjectSetInteger(ObjChartID, name, OBJPROP_BACK, 0);
ObjectSetInteger(ObjChartID, name, OBJPROP_SELECTABLE, 0);
ObjectSetInteger(ObjChartID, name, OBJPROP_SELECTED, 0);
ObjectSetInteger(ObjChartID, name, OBJPROP_HIDDEN, 1);
ObjectSetInteger(ObjChartID, name, OBJPROP_FONTSIZE, ObjFontSize);
ObjectSetInteger(ObjChartID, name, OBJPROP_COLOR, ObjFontColor);
ObjectSetString(ObjChartID, name, OBJPROP_FONT, ObjFont);
}
else
{
Print(__FUNCTION__, ": failed to create text object! Error code = ", GetLastError());
}
}
else
{
if (textlbl == "")
{
ObjectDelete(ObjChartID, namelbl);
ObjectDelete(ObjChartID, name);
continue;
}
}
ObjY = (int)(ObjY + ObjFontSize + ObjFontSize/2);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_XDISTANCE, ObjX);
ObjectSetInteger(ObjChartID, namelbl, OBJPROP_YDISTANCE, ObjY);
ObjectSetString(ObjChartID, namelbl, OBJPROP_TEXT, (string)textlbl);
int x = 0;
int xsizelbl = (int)ObjectGetInteger(ObjChartID, namelbl, OBJPROP_XSIZE);
if (xsizelbl == 0) {
xsizelbl = (int)(StringLen((string)textlbl) * ObjFontSize / 1.5 + ObjFontSize / 2);
}
x = ObjX + (xsizelbl + ObjFontSize/2);
ObjectSetInteger(ObjChartID, name, OBJPROP_XDISTANCE, x);
ObjectSetInteger(ObjChartID, name, OBJPROP_YDISTANCE, ObjY);
ObjectSetString(ObjChartID, name, OBJPROP_TEXT, (string)text);
}
ChartRedraw();
}
initialized = true;
}
_callback_(1);
}
};
template<typename T1,typename T2,typename T3,typename T4,typename T5,typename T6,typename _T6_,typename T7,typename T8,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>
class MDL_ChartDrawButton: public BlockCalls
{
public: /* Input Parameters */
T1 ObjectPerBar;
T2 ObjectUpdate;
T3 ObjName;
T4 ObjX;
T5 ObjY;
T6 ObjText; virtual _T6_ _ObjText_(){return(_T6_)0;}
T7 ObjFont;
T8 ObjFontSize;
T9 ObjXsize;
T10 ObjYsize;
T11 ObjBgColor;
T12 ObjBorderColor;
T13 ObjCorner;
T14 ObjState;
T15 ObjColor;
T16 ObjBack;
T17 ObjSelectable;
T18 ObjSelected;
T19 ObjHidden;
T20 ObjZorder;
T21 ObjChartSubWindow;
/* Static Parameters */
int count;
datetime time0;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDL_ChartDrawButton()
{
ObjectPerBar = (bool)false;
ObjectUpdate = (bool)true;
ObjName = (string)"";
ObjX = (int)10;
ObjY = (int)10;
ObjFont = (string)"Arial";
ObjFontSize = (int)10;
ObjXsize = (int)100;
ObjYsize = (int)20;
ObjBgColor = (color)clrWhite;
ObjBorderColor = (color)clrNONE;
ObjCorner = (int)CORNER_LEFT_UPPER;
ObjState = (bool)false;
ObjColor = (color)clrDeepPink;
ObjBack = (bool)false;
ObjSelectable = (bool)false;
ObjSelected = (bool)false;
ObjHidden = (bool)false;
ObjZorder = (int)0;
ObjChartSubWindow = (string)"";
/* Static Parameters (initial value) */
count = 0;
time0 = 0;
}
public: /* The main method */
virtual void _execute_()
{
string ObjNamePrefix = "fxd_button_";
long ObjChartID = 0;
int subwindow_id = WindowFindVisible(ObjChartID, ObjChartSubWindow);
if (subwindow_id >= 0)
{
string name = "";
string name_base = "";
bool get_new_name = false;
bool do_update = true;
if (ObjectPerBar == true)
{
datetime time = iTime(Symbol(),0,1);
if (time0 < time)
{
time0 = time;
get_new_name = true;
}
else
{
if (ObjectUpdate == false) {do_update = false;}
}
}
else
{
if (ObjectUpdate == false) {get_new_name = true;}
}
if (do_update)
{
if (ObjName != "") {name_base = ObjName;} else {name_base = ObjNamePrefix + __block_user_number + "_";}
if (get_new_name == false)
{
name = name_base + IntegerToString(count);
}
else
{
while (true)
{
count++;
name = name_base + IntegerToString(count);
if (ObjectFind(ObjChartID,name) < 0) {break;}
}
}
if (ObjName != "" && count == 0) {name = ObjName;}
if (ObjectFind(ObjChartID,name) < 0 && !ObjectCreate(ObjChartID,name,OBJ_BUTTON,subwindow_id,0,0))
{
Print(__FUNCTION__,": failed to create button object! Error code = ",GetLastError());
}
ObjectSetInteger(ObjChartID,name,OBJPROP_XDISTANCE,ObjX);
ObjectSetInteger(ObjChartID,name,OBJPROP_YDISTANCE,ObjY);
ObjectSetInteger(ObjChartID,name,OBJPROP_XSIZE,ObjXsize);
ObjectSetInteger(ObjChartID,name,OBJPROP_YSIZE,ObjYsize);
ObjectSetInteger(ObjChartID,name,OBJPROP_BGCOLOR,ObjBgColor);
ObjectSetInteger(ObjChartID,name,OBJPROP_BORDER_COLOR,ObjBorderColor);
ObjectSetInteger(ObjChartID,name,OBJPROP_CORNER,ObjCorner);
ObjectSetString(ObjChartID,name,OBJPROP_FONT,ObjFont);
ObjectSetInteger(ObjChartID,name,OBJPROP_FONTSIZE,ObjFontSize);
ObjectSetInteger(ObjChartID,name,OBJPROP_STATE,ObjState);
ObjectSetString(ObjChartID,name,OBJPROP_TEXT,(string)_ObjText_());
ObjectSetInteger(ObjChartID,name,OBJPROP_COLOR,ObjColor);
ObjectSetInteger(ObjChartID,name,OBJPROP_BACK,ObjBack);
ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTABLE,ObjSelectable);
ObjectSetInteger(ObjChartID,name,OBJPROP_SELECTED,ObjSelected);
ObjectSetInteger(ObjChartID,name,OBJPROP_HIDDEN,ObjHidden);
ObjectSetInteger(ObjChartID,name,OBJPROP_ZORDER,ObjZorder);
ChartRedraw();
}
}
_callback_(1);
}
};
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 (CopyOpen(Symbol,Period,cID,1,O) > -1) retval = O[0];
}
else if (iOHLC == "iHigh")
{
if (CopyHigh(Symbol,Period,cID,1,H) > -1) retval = H[0];
}
else if (iOHLC == "iLow")
{
if (CopyLow(Symbol,Period,cID,1,L) > -1) retval = L[0];
}
else if (iOHLC == "iClose")
{
if (CopyClose(Symbol,Period,cID,1,C) > -1) retval = C[0];
}
else if (iOHLC == "iVolume" || iOHLC == "iTickVolume")
{
if (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 (CopyTime(Symbol,Period,cID,1,T) > -1) retval = (double)T[0];
return retval;
}
else if (iOHLC == "iMedian")
{
if (
CopyLow(Symbol,Period,cID,1,L) > -1
&& CopyHigh(Symbol,Period,cID,1,H) > -1
)
{
retval = ((L[0]+H[0])/2);
}
}
else if (iOHLC == "iTypical")
{
if (
CopyLow(Symbol,Period,cID,1,L) > -1
&& CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
)
{
retval = ((L[0]+H[0]+C[0])/3);
}
}
else if (iOHLC == "iAverage")
{
if (
CopyLow(Symbol,Period,cID,1,L) > -1
&& CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
)
{
retval = ((L[0]+H[0]+C[0]+C[0])/4);
}
}
else if (iOHLC=="iTotal")
{
if (
CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyLow(Symbol,Period,cID,1,L) > -1
)
{
retval = toPips(MathAbs(H[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBody")
{
if (
CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
)
{
retval = toPips(MathAbs(C[0]-O[0]),Symbol);
}
}
else if (iOHLC == "iUpperWick")
{
if (
CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& 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 (
CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& 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 (
CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID+1,1,C) > -1
)
{
retval = toPips(MathAbs(O[0]-C[0]),Symbol);
}
}
else if (iOHLC == "iBullTotal")
{
if (
CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyLow(Symbol,Period,cID,1,L) > -1
&& C[0] > O[0]
)
{
retval = toPips((H[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBullBody")
{
if (
CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] > O[0]
)
{
retval = toPips((C[0]-O[0]),Symbol);
}
}
else if (iOHLC == "iBullUpperWick")
{
if (
CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] > O[0]
)
{
retval = toPips((H[0]-C[0]),Symbol);
}
}
else if (iOHLC == "iBullBottomWick")
{
if (
CopyLow(Symbol,Period,cID,1,L) > -1
&& CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] > O[0]
)
{
retval = toPips((O[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBearTotal")
{
if (
CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyLow(Symbol,Period,cID,1,L) > -1
&& C[0] < O[0]
)
{
retval = toPips((H[0]-L[0]),Symbol);
}
}
else if (iOHLC == "iBearBody")
{
if (
CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] < O[0]
)
{
retval = toPips((O[0]-C[0]),Symbol);
}
}
else if (iOHLC == "iBearUpperWick")
{
if (
CopyHigh(Symbol,Period,cID,1,H) > -1
&& CopyOpen(Symbol,Period,cID,1,O) > -1
&& CopyClose(Symbol,Period,cID,1,C) > -1
&& C[0] < O[0]
)
{
retval = toPips((H[0]-O[0]),Symbol);
}
}
else if (iOHLC == "iBearBottomWick")
{
if (
CopyLow(Symbol,Period,cID,1,L) > -1
&& CopyOpen(Symbol,Period,cID,1,O) > -1
&& 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;
int ModeTimeShift;
int TimeShiftYears;
int TimeShiftMonths;
int TimeShiftWeeks;
double TimeShiftDays;
double TimeShiftHours;
double TimeShiftMinutes;
int TimeShiftSeconds;
bool TimeSkipWeekdays;
/* Static Parameters */
datetime retval;
datetime retval0;
int ModeTime0;
int smodeshift;
int years0;
int months0;
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;
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;
ModeTime0 = 0;
smodeshift = 0;
years0 = 0;
months0 = 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);
CopyTime(TimeMarket,TimeCandleTimeframe,TimeCandleID,1,Time);
retval = Time[0];
}
if (ModeTimeShift > 0)
{
int sh = 1;
if (ModeTimeShift == 1) {sh = -1;}
if (
ModeTimeShift != smodeshift
|| TimeShiftYears != years0
|| TimeShiftMonths != months0
)
{
years0 = TimeShiftYears;
months0 = TimeShiftMonths;
if (TimeShiftYears > 0 || TimeShiftMonths > 0)
{
int year = 0, month = 0, week = 0, day = 0, hour = 0, minute = 0, second = 0;
if (ModeTime == 3)
{
year = TimeComponentYear;
month = TimeComponentYear;
day = (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 = TimeYear(retval);
month = TimeMonth(retval);
day = TimeDay(retval);
hour = TimeHour(retval);
minute = TimeMinute(retval);
second = TimeSeconds(retval);
}
year = year + TimeShiftYears * sh;
month = month + TimeShiftMonths * sh;
if (month < 0) {month = 12 - month;}
else if (month > 12) {month = month - 12;}
retval = 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 = TimeDayOfWeek(retval);
if (sh > 0) { // forward
if (weekday == 0) {retval = retval + 86400;}
else if (weekday == 6) {retval = retval + 172800;}
}
else if (sh < 0) { // back
if (weekday == 0) {retval = retval - 172800;}
else if (weekday == 6) {retval = retval - 86400;}
}
}
}
smodeshift = ModeTimeShift;
ModeTime0 = ModeTime;
return (datetime)retval;
}
};
class MDLIC_indicators_iSAR
{
public: /* Input Parameters */
double Step;
double Maximum;
string Symbol;
ENUM_TIMEFRAMES Period;
int Shift;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_indicators_iSAR()
{
Step = (double)0.02;
Maximum = (double)0.2;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
Shift = (int)0;
}
public: /* The main method */
double _execute_()
{
return iSAR(Symbol, Period, Step, Maximum, Shift + FXD_MORE_SHIFT);
}
};
class MDLIC_value_points
{
public: /* Input Parameters */
double Value;
int ModeValue;
string Symbol;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_value_points()
{
Value = (double)10.0;
ModeValue = (int)1;
Symbol = (string)CurrentSymbol();
}
public: /* The main method */
double _execute_()
{
double retval = 0;
if (ModeValue == 0) {retval = Value;}
else if (ModeValue == 1) {retval = Value*SymbolInfoDouble(Symbol,SYMBOL_POINT)*PipValue(Symbol);}
return retval;
}
};
class MDLIC_boolean_boolean
{
public: /* Input Parameters */
bool Boolean;
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_boolean_boolean()
{
Boolean = (bool)true;
}
public: /* The main method */
bool _execute_()
{
return Boolean;
}
};
class MDLIC_account_AccountCompany
{
public: /* Input Parameters */
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_account_AccountCompany()
{
}
public: /* The main method */
string _execute_()
{
return AccountInfoString(ACCOUNT_COMPANY);
}
};
class MDLIC_account_AccountServer
{
public: /* Input Parameters */
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_account_AccountServer()
{
}
public: /* The main method */
string _execute_()
{
return AccountInfoString(ACCOUNT_SERVER);
}
};
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_AccountProfit
{
public: /* Input Parameters */
virtual void _callback_(int r) {return;}
public: /* Constructor */
MDLIC_account_AccountProfit()
{
}
public: /* The main method */
double _execute_()
{
return NormalizeDouble(AccountInfoDouble(ACCOUNT_PROFIT), 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_ImpulseUp<string,int,double,double,int,string,ENUM_TIMEFRAMES>
{
public: /* Constructor */
Block0() {
__block_number = 0;
__block_user_number = "1";
_beforeExecuteEnabled = true;
int ___outbound_blocks[2] = {2,4};
ArrayCopy(__outbound_blocks, ___outbound_blocks);
SignalType = "once";
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 0) {
_blocks_[4].run(0);
}
else if (value == 1) {
_blocks_[2].run(0);
}
}
virtual void _beforeExecute_()
{
QuietBarsCount = (int)c::Bar_Count;
QuietBarsMinRange = (double)c::Bar_Size;
ImpulseStrength = (double)c::STR;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
}
};
class Block1: public MDL_GridPendingBuys2<string,string,int,string,MDLIC_candles_candles,double,double,double,double,string,double,double,double,double,double,MDLIC_value_value,double,double,double,double,string,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,double,double,double,double,string,int,int,int,MDLIC_value_time,datetime,ulong,string,color>
{
public: /* Constructor */
Block1() {
__block_number = 1;
__block_user_number = "3";
_beforeExecuteEnabled = true;
fGridStart.iOHLC = "iOpen";
fGridStart.TimeStamp = "";
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;
Group = "1";
GridOrdersCount = 1;
GridStart = "mid";
VolumeMode = "balance";
MyComment = "HFT Scalper";
}
public: /* Custom methods */
virtual double _fGridStart_() {
fGridStart.Symbol = CurrentSymbol();
fGridStart.Period = CurrentTimeframe();
return fGridStart._execute_();
}
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();
GridSize = (double)c::Gridsize;
VolumePercent = (double)c::Autolots;
StopLossPips = (double)c::SL;
TakeProfitPips = (double)c::TP;
ArrowColorBuy = (color)clrBlue;
}
};
class Block2: public MDL_GridPendingSells2<string,string,int,string,MDLIC_candles_candles,double,double,double,double,string,double,double,double,double,double,MDLIC_value_value,double,double,double,double,string,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,string,double,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,double,double,double,double,string,int,int,int,MDLIC_value_time,datetime,ulong,string,color>
{
public: /* Constructor */
Block2() {
__block_number = 2;
__block_user_number = "4";
_beforeExecuteEnabled = true;
fGridStart.iOHLC = "iOpen";
fGridStart.TimeStamp = "";
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;
Group = "1";
GridOrdersCount = 1;
GridStart = "mid";
VolumeMode = "balance";
MyComment = "HFT Scalper";
}
public: /* Custom methods */
virtual double _fGridStart_() {
fGridStart.Symbol = CurrentSymbol();
fGridStart.Period = CurrentTimeframe();
return fGridStart._execute_();
}
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();
GridSize = (double)c::Gridsize;
VolumePercent = (double)c::Autolots;
StopLossPips = (double)c::SL;
TakeProfitPips = (double)c::TP;
ArrowColorSell = (color)clrRed;
}
};
class Block3: public MDL_ImpulseDn<string,int,double,double,int,string,ENUM_TIMEFRAMES>
{
public: /* Constructor */
Block3() {
__block_number = 3;
__block_user_number = "5";
_beforeExecuteEnabled = true;
int ___outbound_blocks[2] = {1,4};
ArrayCopy(__outbound_blocks, ___outbound_blocks);
SignalType = "once";
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 0) {
_blocks_[4].run(3);
}
else if (value == 1) {
_blocks_[1].run(3);
}
}
virtual void _beforeExecute_()
{
QuietBarsCount = (int)c::Bar_Count;
QuietBarsMinRange = (double)c::Bar_Size;
ImpulseStrength = (double)c::STR;
Symbol = (string)CurrentSymbol();
Period = (ENUM_TIMEFRAMES)CurrentTimeframe();
}
};
class Block4: public MDL_TrailingStopAvgPrice<string,string,string,string,int,string,double,MDLIC_value_value,double,double,string,double,double,string,double,double,MDLIC_value_value,double,bool,string,double,double,MDLIC_value_value,double,color>
{
public: /* Constructor */
Block4() {
__block_number = 4;
__block_user_number = "6";
_beforeExecuteEnabled = true;
ftStop.Value = 40.0;
ftStart.Value = 0.0;
ftTP.Value = 40.0;
Group = "1";
TrailingStartMode = "fixed";
resetOnTrade = false;
}
public: /* Custom methods */
virtual double _ftStop_() {return ftStop._execute_();}
virtual double _ftStart_() {return ftStart._execute_();}
virtual double _ftTP_() {return ftTP._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
TrailWhat = (int)c::Use_Trailing_Stops;
tStopPips = (double)c::Stops;
tStepPips = (double)c::Steps;
tStartPips = (double)c::Starts;
LevelColor = (color)clrDeepPink;
}
};
class Block5: public MDL_TrailingStop2<string,string,string,string,string,int,int,string,double,double,string,double,double,MDLIC_indicators_iSAR,double,MDLIC_value_points,double,string,double,double,string,double,double,double,double,MDLIC_value_value,double,MDLIC_value_value,double,string,double,double,MDLIC_value_value,double,color>
{
public: /* Constructor */
Block5() {
__block_number = 5;
__block_user_number = "7";
_beforeExecuteEnabled = true;
ftDigits.Value = 40.0;
ftStart.Value = 0.0;
ftStartFraction.Value = 0.001;
ftTP.Value = 0.0;
Group = "1";
TrailingReferencePrice = 1;
TrailingStartMode = "fixed";
}
public: /* Custom methods */
virtual double _ftStop_() {
ftStop.Symbol = CurrentSymbol();
ftStop.Period = CurrentTimeframe();
return ftStop._execute_();
}
virtual double _ftDigits_() {
ftDigits.Symbol = CurrentSymbol();
return ftDigits._execute_();
}
virtual double _ftStart_() {return ftStart._execute_();}
virtual double _ftStartFraction_() {return ftStartFraction._execute_();}
virtual double _ftTP_() {return ftTP._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
TrailWhat = (int)c::Use_Trailing_Stops;
tStopPips = (double)c::Stops;
tStepPips = (double)c::Steps;
tStartPips = (double)c::Starts;
LevelColor = (color)clrDeepPink;
}
};
class Block6: public MDL_TrailingPendingOrders<string,string,string,string,string,string,string,double,MDLIC_value_value,double,MDLIC_value_value,double,MDLIC_value_value,double,double>
{
public: /* Constructor */
Block6() {
__block_number = 6;
__block_user_number = "8";
_beforeExecuteEnabled = true;
dtDistancePips.Value = 30.0;
dtDistanceDigits.Value = 0.0030;
Group = "1";
tStepPips = 0.10;
}
public: /* Custom methods */
virtual double _dtDistancePips_() {return dtDistancePips._execute_();}
virtual double _dtDistanceDigits_() {return dtDistanceDigits._execute_();}
virtual double _dtLevel_() {return dtLevel._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
tDistancePips = (double)c::Trail_Pen;
}
};
class Block7: public MDL_NoPendingOrders<string,string,string,string,string,string>
{
public: /* Constructor */
Block7() {
__block_number = 7;
__block_user_number = "9";
_beforeExecuteEnabled = true;
int ___outbound_blocks[4] = {0,3,5,6};
ArrayCopy(__outbound_blocks, ___outbound_blocks);
Group = "1";
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 0) {
_blocks_[5].run(7);
_blocks_[6].run(7);
}
else if (value == 1) {
_blocks_[0].run(7);
_blocks_[3].run(7);
}
}
virtual void _beforeExecute_()
{
Symbol = (string)CurrentSymbol();
}
};
class Block8: public MDL_Condition<MDLIC_boolean_boolean,bool,string,MDLIC_boolean_boolean,bool,int>
{
public: /* Constructor */
Block8() {
__block_number = 8;
__block_user_number = "19";
int ___outbound_blocks[1] = {7};
ArrayCopy(__outbound_blocks, ___outbound_blocks);
compare = "==";
}
public: /* Custom methods */
virtual bool _Lo_() {return Lo._execute_();}
virtual bool _Ro_() {
Ro.Boolean = c::Limits_Only;
return Ro._execute_();
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[7].run(8);
}
}
};
class Block9: public MDL_Pass
{
public: /* Constructor */
Block9() {
__block_number = 9;
__block_user_number = "21";
int ___outbound_blocks[1] = {10};
ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[10].run(9);
}
}
};
class Block10: public MDL_CommentEx<string,string,int,int,int,string,color,int,string,color,int,string,color,int,string,MDLIC_account_AccountCompany,string,int,int,string,MDLIC_account_AccountServer,string,int,int,string,MDLIC_account_AccountBalance,double,int,int,string,MDLIC_account_AccountProfit,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>
{
public: /* Constructor */
Block10() {
__block_number = 10;
__block_user_number = "22";
_beforeExecuteEnabled = true;
Value5.Text = "";
Value6.Text = "";
Value7.Text = "";
Value8.Text = "";
Title = "HFT Scalper";
Label1 = "Broker";
Label2 = "Server";
Label3 = "Balance";
Label4 = "Profit";
}
public: /* Custom methods */
virtual string _Value1_() {return Value1._execute_();}
virtual string _Value2_() {return Value2._execute_();}
virtual double _Value3_() {return Value3._execute_();}
virtual double _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;
ObjCorner = (int)CORNER_LEFT_UPPER;
ObjTitleFontColor = (color)clrGold;
ObjLabelsFontColor = (color)clrDarkGray;
ObjFontColor = (color)clrWhite;
FormatNumber1 = (int)EMPTY_VALUE;
FormatTime1 = (int)EMPTY_VALUE;
FormatNumber2 = (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;
}
};
class Block11: public MDL_Pass
{
public: /* Constructor */
Block11() {
__block_number = 11;
__block_user_number = "24";
int ___outbound_blocks[1] = {12};
ArrayCopy(__outbound_blocks, ___outbound_blocks);
}
public: /* Callback & Run */
virtual void _callback_(int value) {
if (value == 1) {
_blocks_[12].run(11);
}
}
};
class Block12: public MDL_ChartDrawButton<bool,bool,string,int,int,MDLIC_text_text,string,string,int,int,int,color,color,int,bool,color,bool,bool,bool,bool,int,string>
{
public: /* Constructor */
Block12() {
__block_number = 12;
__block_user_number = "25";
_beforeExecuteEnabled = true;
ObjText.Text = "HFT Scalper";
ObjX = 225;
ObjY = 163;
ObjFont = "Georgia";
ObjFontSize = 20;
ObjXsize = 550;
ObjYsize = 80;
ObjBack = true;
}
public: /* Custom methods */
virtual string _ObjText_() {return ObjText._execute_();}
public: /* Callback & Run */
virtual void _callback_(int value) {
}
virtual void _beforeExecute_()
{
ObjBgColor = (color)clrGreen;
ObjBorderColor = (color)clrMediumBlue;
ObjCorner = (int)CORNER_LEFT_UPPER;
ObjColor = (color)clrCrimson;
}
};
/************************************************************************************************************************/
/************************************************************************************************************************/
double AccountBalance()
{
return NormalizeDouble(AccountInfoDouble(ACCOUNT_BALANCE), 2);
}
double AccountBalanceAtStart()
{
static double memory = 0;
if (memory == 0)
{
memory = NormalizeDouble(AccountInfoDouble(ACCOUNT_BALANCE), 2);
}
return memory;
}
double AccountEquity()
{
return AccountInfoDouble(ACCOUNT_EQUITY);
}
double AccountFreeMargin()
{
return AccountInfoDouble(ACCOUNT_FREEMARGIN);
}
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 == ORDER_TYPE_SELL
|| type == ORDER_TYPE_SELL_STOP
|| type == ORDER_TYPE_SELL_LIMIT
|| type == ORDER_TYPE_SELL_STOP_LIMIT
)
{
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 (",
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 (",
DoubleToStr(sl, digits),
" or ",
DoubleToStr(MathAbs(sl - askbid) / point, 0),
" points), minimum will be taken (",
DoubleToStr(sllimit, digits),
" or ",
DoubleToStr(MathAbs(askbid - sllimit) / point, 0),
" points)"
);
sl = sllimit;
return sl;
}
}
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 == ORDER_TYPE_SELL
|| type == ORDER_TYPE_SELL_STOP
|| type == ORDER_TYPE_SELL_LIMIT
|| type == ORDER_TYPE_SELL_STOP_LIMIT
)
{
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 (",
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 (",
DoubleToStr(tp, digits),
" or ",
DoubleToStr(MathAbs(tp - askbid) / point, 0),
" points), minimum will be taken (",
DoubleToStr(tplimit, digits),
" or ",
DoubleToStr(MathAbs(askbid - tplimit) / point, 0),
" points)"
);
tp = tplimit;
return tp;
}
}
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
}
long BuyLater(
string symbol,
double lots,
double price,
double sll = 0, // SL level
double tpl = 0, // TP level
double slp = 0, // SL adjust in points
double tpp = 0, // TP adjust in points
double slippage = 0,
datetime expiration = 0,
int magic = 0,
string comment = "",
color arrowcolor = clrNONE,
bool oco = false
)
{
double ask = SymbolInfoDouble(symbol,SYMBOL_ASK);
ENUM_ORDER_TYPE type = 0;
if (price == ask) {type = ORDER_TYPE_BUY;}
else if (price < ask) {type = ORDER_TYPE_BUY_LIMIT;}
else if (price > ask) {type = ORDER_TYPE_BUY_STOP;}
return OrderCreate(
symbol,
type,
lots,
price,
sll,
tpl,
slp,
tpp,
slippage,
magic,
comment,
arrowcolor,
expiration,
oco
);
}
int CheckForTradingError(int error_code=-1, string msg_prefix="")
{
int retval=0;
static int tryouts=0;
switch(error_code)
{
case 0:
retval=0;
break;
case TRADE_RETCODE_REQUOTE:
case TRADE_RETCODE_REJECT:
case TRADE_RETCODE_ERROR:
case TRADE_RETCODE_TIMEOUT:
case TRADE_RETCODE_INVALID_VOLUME:
case TRADE_RETCODE_INVALID_PRICE:
case TRADE_RETCODE_INVALID_STOPS:
case TRADE_RETCODE_INVALID_EXPIRATION:
case TRADE_RETCODE_PRICE_CHANGED:
case TRADE_RETCODE_PRICE_OFF:
case TRADE_RETCODE_TOO_MANY_REQUESTS:
case TRADE_RETCODE_NO_CHANGES:
case TRADE_RETCODE_CONNECTION:
retval=1;
break;
default:
retval=2;
break;
}
if (error_code > 0)
{
string msg = "";
if (retval == 1)
{
StringConcatenate(msg, msg_prefix,": ",ErrorMessage(error_code),". Retrying in 5 seconds..");
Sleep(500);
}
else if (retval == 2)
{
StringConcatenate(msg, msg_prefix,": ",ErrorMessage(error_code));
}
Print(msg);
}
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 deviation = 0, color clr = clrNONE)
{
while(true)
{
bool success = false;
if (!PositionSelectByTicket(ticket))
{
return false;
}
string symbol = PositionGetString(POSITION_SYMBOL);
long magic = PositionGetInteger(POSITION_MAGIC);
double volume = PositionGetDouble(POSITION_VOLUME);
double max_volume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX);
double part_volume = (volume > max_volume) ? max_volume : volume;
MqlTradeRequest request;
MqlTradeResult result;
MqlTradeCheckResult check_result;
ZeroMemory(request);
ZeroMemory(result);
ZeroMemory(check_result);
if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
request.type = ORDER_TYPE_SELL;
request.price = SymbolInfoDouble(symbol, SYMBOL_BID);
}
else
{
request.type = ORDER_TYPE_BUY;
request.price = SymbolInfoDouble(symbol, SYMBOL_ASK);
}
request.action = TRADE_ACTION_DEAL;
request.symbol = symbol;
request.volume = part_volume;
request.magic = magic;
request.deviation = (int)(deviation * PipValue(symbol));
request.position = ticket;
if (IsFillingTypeAllowed(symbol, SYMBOL_FILLING_FOK))
request.type_filling = ORDER_FILLING_FOK;
else if (IsFillingTypeAllowed(symbol, SYMBOL_FILLING_IOC))
request.type_filling = ORDER_FILLING_IOC;
else if (IsFillingTypeAllowed(symbol, ORDER_FILLING_RETURN)) // just in case
request.type_filling = ORDER_FILLING_RETURN;
else
request.type_filling = ORDER_FILLING_RETURN;
success = OrderSend(request, result);
if (!success || (result.retcode != TRADE_RETCODE_DONE && result.retcode != TRADE_RETCODE_PLACED && result.retcode != TRADE_RETCODE_DONE_PARTIAL))
{
string errmsgpfx = "Closing position/trade error";
int erraction = CheckForTradingError(result.retcode, errmsgpfx);
switch(erraction)
{
case 0: break; // no error
case 1: continue; // overcomable error
case 2: break; // fatal error
}
return false;
}
if (result.retcode == TRADE_RETCODE_DONE || result.retcode == TRADE_RETCODE_PLACED)
{
if (volume != part_volume)
{
continue; // continue the "while" loop, so that the whole volume could be closed
}
while (true)
{
if (MQLInfoInteger(MQL_TESTER) || !PositionSelectByTicket(ticket))
{
break;
}
Sleep(10);
}
}
if (success == true)
{
if (USE_VIRTUAL_STOPS)
{
VirtualStopsDriver("clear", ticket);
}
expirationWorker.RemoveExpiration(ticket);
}
break;
}
OnTrade();
return true;
}
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 tf=-1)
{
static ENUM_TIMEFRAMES memory=0;
if (tf>=0) {memory=tf;}
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;
striПоказано первые 50% кода (символов: 172841)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.