← К каталогу
Исходный код · ID 2779

xBest Rv3.47

fxcoregold v9 mq4 (2).mq4

Похожие материалы по тегам

fxcoregold ea full.mq4MQL4 / MetaTrader 4 · 2 общих теговxbest v3.47 ea@lifeindreamsworld.mq4MQL4 / MetaTrader 4 · 2 общих теговfxcoregold v9 mq4@amazing_owner.mq4MQL4 / MetaTrader 4 · 2 общих теговthe gold reaper v4.1 mt5.mq4MQL4 / MetaTrader 4 · 1 общих теговquantum queen x 4.3 (1).mq5MQL5 / MetaTrader 5 · 1 общих теговlizard_1.85.mq4MQL4 / MetaTrader 4 · 1 общих тегов
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

xBest Rv3.47 — торговый советник для MetaTrader 4, реализующий стратегию сеточной торговли с хеджированием. Советник открывает циклы сделок BUY/SELL на основе сигналов скользящей средней и индикатора HILO, увеличивая объём позиции на каждом шаге сетки. Поддерживается четыре режима формирования лота: фиксированный, процентный, мартингейл и пошаговый.

В состав входят встроенные фильтры: по спреду, новостям (через внешний индикатор FFCal), по времени (день недели и часовой диапазон), а также контроль рисков по эквити (EquityCaution и EquityStop). Реализованы функции трейлинг-стопа, брейк-эвен, фиксации минимальной прибыли и дневной цели по прибыли. При достижении условий советник закрывает все ордера по символу.

Советник отображает на графике информационную панель с текущей ценой, символом, спредом, временем и процентом изменения. Доступна ручная инициализация сетки через кнопки на графике. Работает с двумя независимыми движками (A — BUY, B — SELL), каждый со своим магическим числом.

Настройки программы

НастройкаОписание
Version__ Версия — Версия xBest Rv3.47
Version1__ Версия — Версия xBest Rv3.47
Version2__ Версия — Версия xBest Rv3.47
InpChartDisplay__ Display Info — Группа настроек отображения информации
Display Info (InpChartDisplay) Отображать информацию — Отображать информацию
Display background color (InpDisplayInpBackgroundColor) Отображать цвет фона — Отображать цвет фона
background color (InpBackgroundColor) Цвет фона — Цвет фона
Switches Switches — Группа переключателей
Start MANUAL Order Grid (Only if A / B Enable) (InpManualInitGrid) Запустить ручную сетку ордеров — Запустить ручную сетку ордеров (только при включённых движках A/B)
Open New Orders ? (InpOpenNewOrders) Открывать новые ордера — Открывать новые ордера
Enable Grid ? (OpenNewOrdersGrid) Включить сетку — Включить сетку
closes all orders now (InpCloseAllNow) Закрыть все ордера сейчас — Закрыть все ордера сейчас
Magic Magic Number Engine — Группа магических чисел движка
Magic_ Magic Number для мотора buy/sell — Группа магических чисел для мотора buy/sell при отключённых движках
Enable Engine A [BUY] (InpEnableEngineA) Включить движок A [BUY] — Включить движок A [BUY]
Magic Number A (InpMagic) Магическое число A — Магическое число A
Enable Engine B [SELL] (InpEnableEngineB) Включить движок B [SELL] — Включить движок B [SELL]
Magic Number B (InpMagic2) Магическое число B — Магическое число B
ConfigLOTE__ Config Lot INIT — Группа настроек конфигурации лота INIT
Lot Mode (InpLotMode) Режим лота — Режим лота
Fixed Lot (InpFixedLot) Фиксированный лот — Фиксированный лот
Percent Lot (InpPercentLot) Процентный лот — Процентный лот
Take Profit in Pips (InpTakeProfit) Тейк-профит в пипсах — Тейк-профит в пипсах
XBEST_ConfigGrid__ Config Grid — Группа настроек конфигурации сетки
Type Grid Lot (TypeGridLot) Тип сеточного лота — Тип сеточного лота
Step Size in Pips (InpGridSize) Размер шага в пипсах — Размер шага в пипсах
Grid Increment Factor (If Martingale) (InpGridFactor) Коэффициент увеличения сетки (при мартингейле) — Коэффициент увеличения сетки (при мартингейле)
STEP LOT (If Step Lot) (InpGridStepLot) Шаг лота (при пошаговом режиме) — Шаг лота (при пошаговом режиме)
Max Lot (InpMaxLot) Максимальный лот — Максимальный лот
After Level Change Lot A to B (Necessari all Engine Enable) (InpHedgex) После уровня изменить лот A на B (необходимо включить все движки) — После уровня изменить лот A на B (необходимо включить все движки)
Enable Grid Dual Side (GridAllDirect) Включить сетку на обе стороны — Включить сетку на обе стороны
FilterOpenOneCandle__ Filter One Order by Candle — Группа настроек фильтра одного ордера по свече
Open one order by candle (InpOpenOneCandle) Открывать один ордер по свече — Открывать один ордер по свече
Timeframe OpenOneCandle (InpTimeframeBarOpen) Таймфрейм для открытия одного ордера по свече — Таймфрейм для открытия одного ордера по свече
MinimalProfitClose__ Minimal Profit Close — Группа настроек минимальной прибыли для закрытия
Enable Minimal Profit Close (InpEnableMinProfit) Включить минимальную прибыль для закрытия — Включить минимальную прибыль для закрытия
Enable Protect Grid from Profit Orders MinProfit (MinimalProfitProtectGrid) Защищать сетку от прибыльных ордеров по минимальной прибыли — Защищать сетку от прибыльных ордеров по минимальной прибыли
Minimal Profit Close /Protect Grid (MinProfit) Минимальная прибыль для закрытия/защиты сетки — Минимальная прибыль для закрытия/защиты сетки
Qtd Trades to Minimal Profit Close/ Protect Grid (QtdTradesMinProfit) Количество ордеров для минимальной прибыли/защиты сетки — Количество ордеров для минимальной прибыли/защиты сетки
Config__ Config — Группа настроек конфигурации
Hedge After Level (InpHedge) Хеджирование после уровня — Хеджирование после уровня
Daily Target in Money (InpDailyTarget) Дневная цель в деньгах — Дневная цель в деньгах
MovingAverageConfig__ Moving Average Config — Группа настроек скользящей средней
Moving Average TimeFrame (InpMaFrame) Таймфрейм скользящей средней — Таймфрейм скользящей средней
If True Sinal Moving Average Filter (InpMAFilterInverter) Если true, инвертировать сигнал фильтра скользящей средней — Если true, инвертировать сигнал фильтра скользящей средней
Moving Average Period (InpMaPeriod) Период скользящей средней — Период скользящей средней
Moving Average Method (InpMaMethod) Метод скользящей средней — Метод скользящей средней
Moving Average Price (InpMaPrice) Цена скользящей средней — Цена скользящей средней
Moving Average Shift (InpMaShift) Сдвиг скользящей средней — Сдвиг скользящей средней
HILOConfig__ HILO Config — Группа настроек HILO
Enable Sinal HILO (EnableSinalHILO) Включить сигнал HILO — Включить сигнал HILO
If True Invert Filter (InpHILOFilterInverter) Инвертировать фильтр HILO — Инвертировать фильтр HILO
HILO TimeFrame (InpHILOFrame) Таймфрейм HILO — Таймфрейм HILO
HILO Period (InpHILOPeriod) Период HILO — Период HILO
HILO Method (InpHILOMethod) Метод HILO — Метод HILO
HILO Shift (InpHILOShift) Сдвиг HILO — Сдвиг HILO
TrailingStop__ Trailing Stop — Группа настроек трейлинг-стопа
Use Trailling Stop??? (InpUseTrailingStop) Использовать трейлинг-стоп — Использовать трейлинг-стоп
TraillingStart (InpTrailStart) Начало трейлинг-стопа — Начало трейлинг-стопа
Size Trailling stop (InpTrailStop) Размер трейлинг-стопа — Размер трейлинг-стопа
BreakEven Break Even — Группа настроек Break Even
Use Break Even ? (InpUseBreakEven) Использовать брейк-эвен — Использовать брейк-эвен
Break Even Start (InpBreakEvenStart) Начало брейк-эвен — Начало брейк-эвен
Break Even Step (InpBreakEvenStep) Шаг брейк-эвен — Шаг брейк-эвен
TakeEquitySTOP__ Take Equity STOP — Группа настроек Take Equity Stop
Usar Take EquityStop? (InpUseTakeEquityStop) Использовать Take Equity Stop — Использовать Take Equity Stop
Closes all orders once Float hits this $ amount (InpProfitCloseandSTOP) Закрыть все ордера при достижении указанной прибыли в долларах — Закрыть все ордера при достижении указанной прибыли в долларах
FilterSpread__ Filter Max Spread — Группа настроек фильтра максимального спреда
Max Spread in Pips (InpMaxSpread) Максимальный спред в пипсах — Максимальный спред в пипсах
EquityCaution__ Equity Caution — Группа настроек предупреждения об эквити
EquityCaution? (InpUseEquityCaution) Использовать EquityCaution — Использовать EquityCaution
Total % Risk to EquityCaution (InpTotalEquityRiskCaution) Общий процент риска для EquityCaution — Общий процент риска для EquityCaution
Timeframe as EquityCaution (InpTimeframeEquityCaution) Таймфрейм для EquityCaution — Таймфрейм для EquityCaution
EquitySTOP__ Equity STOP — Группа настроек стоп-эквити
Usar EquityStop? (InpUseEquityStop) Использовать EquityStop — Использовать EquityStop
Total % Risk to EquityStop (InpTotalEquityRisk) Общий процент риска для EquityStop — Общий процент риска для EquityStop
Send Alert to Celular (InpAlertPushEquityLoss) Отправлять уведомление при убытке по эквити — Отправлять уведомление при убытке по эквити
Close all orders in TotalEquityRisk (InpCloseAllEquityLoss) Закрыть все ордера при достижении лимита убытка по эквити — Закрыть все ордера при достижении лимита убытка по эквити
FFCall__ Filter News FFCall — Группа настроек фильтра новостей FFCall
mins before an event to stay out of trading (InpMinsBeforeNews) Минут до события, чтобы не торговать — Минут до события, чтобы не торговать
mins after an event to stay out of trading (InpMinsAfterNews) Минут после события, чтобы не торговать — Минут после события, чтобы не торговать
InpUseFFCall Использовать фильтр новостей FFCall — Использовать фильтр новостей FFCall
InpIncludeHigh Включить высокое — Включить высокое
TimeFilter__ Time Filter — Группа настроек фильтра времени
InpUtilizeTimeFilter Использовать фильтр времени — Использовать фильтр времени
InpTrade_in_Monday Торговля в понедельник — Торговля в понедельник
InpTrade_in_Tuesday Торговля во вторник — Торговля во вторник
InpTrade_in_Wednesday Торговля в среду — Торговля в среду
InpTrade_in_Thursday Торговля в четверг — Торговля в четверг
InpTrade_in_Friday Торговля в пятницу — Торговля в пятницу
InpStartHour Начальный час торговли — Начальный час торговли
InpEndHour Конечный час торговли — Конечный час торговли
_Visor1_ Visor 1 — Группа настроек Visor 1
Visor1_Show_the_Time Показывать время — Показывать время
Visor1_Show_the_Price Показывать цену — Показывать цену
Visor1_Price_Up_Color Цвет цены при росте — Цвет цены при росте
Visor1_Price_Down_Color Цвет цены при снижении — Цвет цены при снижении
Visor1_Price_X_Position Горизонтальная позиция цены — Горизонтальная позиция цены
Visor1_Price_Y_Position Вертикальная позиция цены — Вертикальная позиция цены
Visor1_Price_Size Размер шрифта цены — Размер шрифта цены
Получить полный код

Поиск по коду файла

#property version "3.47"
#property description "xBest Rv3.47 - Grid Hedging Expert Advisor  "
#property description "This EA init a cycle of buy or sell depending of signaling, it start with the base"
#property description "lot and increase the size at every step by its factor and set a global take profit,"
#property description "if daily target profit is hit then close all orders, also have a time filtering,"
#property description "you can enable hedging after especified quantity of loss orders."
#property description "Coder init: xJhamil, Mail: y**********o*@gmail.com"
#property description "Alter  2018-03-25: Rmorais, Mail: r**************o*@gmail.com"
#property strict

enum ENUM_LOT_MODE
{
  LOT_MODE_FIXED = 1,   // Fixed Lot
  LOT_MODE_PERCENT = 2, // Percent Lot
};

enum ENUM_TYPE_GRID_LOT
{
  fix_lot = 0,    // Fixed Start Lot 0.01 / 0.01 / 0.01 / 0.01 / 0.01 /.............
  Summ_lot = 1,   // Summ Sart Lot   0.01 / 0.02 / 0.03 / 0.04 / 0.05 /.............
  Martingale = 2, // Martingale Lot  0.01 / 0.02 / 0.04 / 0.08 / 0.16 /.............
  Step_lot = 3    // Step Lot        0.01 / 0.01 / 0.01 / 0.02 / 0.02 / 0.02 / 0.03 / 0.03 / 0.03 / 0.04 / 0.04 / 0.04 /............
};

extern string Version__ = "----------------------------------------------------------------";
extern string Version1__ = "-----------------xBest   Rv3.47 --------------------------------";
extern string Version2__ = "----------------------------------------------------------------";

extern string InpChartDisplay__ = "------------------------Display Info--------------------";
extern bool InpChartDisplay = true;              // Display Info
extern bool InpDisplayInpBackgroundColor = TRUE; // Display background color
extern color InpBackgroundColor = Black;          // background color

extern string Switches = "--------------------------- Switches --------------------------- ";
extern bool InpManualInitGrid = FALSE; // Start MANUAL Order  Grid  (Only if A / B Enable)
extern bool InpOpenNewOrders = TRUE;  // Open New Orders ?
extern bool OpenNewOrdersGrid = TRUE; // Enable Grid ?
extern bool InpCloseAllNow = false;   // closes all orders now
extern string Magic = "--------Magic Number Engine---------";
extern string Magic_ = "--------If all the engines are disabled runs a motor in buy and sell ---------";
input bool InpEnableEngineA = TRUE; // Enable Engine A   [BUY]
input int InpMagic = 7799;           // Magic Number  A
input bool InpEnableEngineB = TRUE; // Enable Engine B   [SELL]
input int InpMagic2 = 9977;          // Magic Number  B
extern string ConfigLOTE__ = "---------------------------Config Lot INIT--------------------------------------";
input ENUM_LOT_MODE InpLotMode = LOT_MODE_PERCENT; // Lot Mode
input double InpFixedLot = 0.01;                   // Fixed Lot
input double InpPercentLot = 0.03;                 // Percent Lot
input int InpTakeProfit = 30;                    // Take Profit in Pips

extern string XBEST_ConfigGrid__ = "---------------------------Config Grid--------------------------------------";
input ENUM_TYPE_GRID_LOT TypeGridLot = Martingale; // Type Grid Lot
input int InpGridSize = 3;                         // Step Size in Pips
input double InpGridFactor = 1.3;                  // Grid Increment Factor (If Martingale)
input int InpGridStepLot = 4;                      // STEP LOT (If  Step Lot)
input double InpMaxLot = 99;                      // Max Lot
input int InpHedgex =6;                           // After Level Change Lot A to B (Necessari all Engine Enable)
input bool GridAllDirect = false;                  // Enable Grid Dual Side

extern string FilterOpenOneCandle__ = "--------------------Filter One Order by Candle--------------";
input bool InpOpenOneCandle = true;                         // Open one order by candle
input ENUM_TIMEFRAMES InpTimeframeBarOpen = PERIOD_CURRENT; // Timeframe OpenOneCandle

extern string MinimalProfitClose__ = "--------------------Minimal Profit Close/ Protect Grid --------------";
input bool InpEnableMinProfit = true;  // Enable  Minimal Profit Close
input bool  MinimalProfitProtectGrid  = true; // Enable Protect Grid from Profit Orders MinProfit
input double MinProfit = 3;        // Minimal Profit Close /Protect Grid
input int QtdTradesMinProfit = 3;      // Qtd Trades to Minimal Profit Close/ Protect Grid
extern string Config__ = "---------------------------Config--------------------------------------";
input int InpHedge = 0;        // Hedge After Level
input int InpDailyTarget = 50; // Daily Target in Money

extern string MovingAverageConfig__ = "-----------------------------Moving Average-----------------------";
input ENUM_TIMEFRAMES InpMaFrame = PERIOD_CURRENT; // Moving Average TimeFrame
input bool InpMAFilterInverter = true;            // If True Sinal Moving Average Filter
input int InpMaPeriod = 34;                         // Moving Average Period
input ENUM_MA_METHOD InpMaMethod = MODE_EMA;       // Moving Average Method
input ENUM_APPLIED_PRICE InpMaPrice = PRICE_OPEN;  // Moving Average Price
input int InpMaShift = 0;                          // Moving Average Shift

extern string HILOConfig__ = "-----------------------------HILO--------------------";
input bool EnableSinalHILO = true;                   //Enable Sinal  HILO
input bool InpHILOFilterInverter = false;            // If True Invert Filter
input ENUM_TIMEFRAMES InpHILOFrame = PERIOD_CURRENT; // HILO TimeFrame
input int InpHILOPeriod = 3;                         // HILO Period
input ENUM_MA_METHOD InpHILOMethod = MODE_EMA;       // HILO Method
input int InpHILOShift = 0;                          // HILO Shift

double indicator_low;
double indicator_high;
double diff_highlow;
bool isbidgreaterthanima;

extern string TrailingStop__ = "--------------------Trailling Stop--------------";
extern bool InpUseTrailingStop = false; // Use Trailling Stop???
extern int InpTrailStart = 20;          //   TraillingStart
extern int InpTrailStop = 20;           // Size Trailling stop

extern string BreakEven = "--------------------Break Even--------------";
extern bool InpUseBreakEven = true; // Use Break Even ?
extern int InpBreakEvenStart = 15;   //   Break Even Start
extern int InpBreakEvenStep = 3;    //  Break Even Step

extern string TakeEquitySTOP__ = "------------------------Take  Equity STOP ---------------";
extern bool InpUseTakeEquityStop = true;   // Usar Take EquityStop?
extern double InpProfitCloseandSTOP = 50.0; // Closes all orders once Float hits this $ amount

extern string FilterSpread__ = "----------------------------Filter Max Spread--------------------";
input int InpMaxSpread = 24; // Max Spread in Pips

extern string EquityCaution__ = "------------------------Filter Caution of Equity ---------------";
extern bool InpUseEquityCaution = TRUE;                       //  EquityCaution?
extern double InpTotalEquityRiskCaution = 20;                 // Total % Risk to EquityCaution
extern ENUM_TIMEFRAMES InpTimeframeEquityCaution = PERIOD_D1; // Timeframe as EquityCaution

extern string EquitySTOP__ = "------------------------Filter  Equity STOP ---------------";
extern bool InpUseEquityStop = true;        // Usar EquityStop?
extern double InpTotalEquityRisk = 60.0;    // Total % Risk to EquityStop
extern bool InpAlertPushEquityLoss = false; //Send Alert to Celular
extern bool InpCloseAllEquityLoss = false;  // Close all orders in TotalEquityRisk

extern string FFCall__ = "----------------------------Filter News FFCall------------------------";

extern int InpMinsBeforeNews = 60; // mins before an event to stay out of trading
extern int InpMinsAfterNews = 20;  // mins after  an event to stay out of trading
extern bool InpUseFFCall = true;
extern bool InpIncludeHigh = true;

extern string TimeFilter__ = "-------------------------Filter DateTime---------------------------";
extern bool InpUtilizeTimeFilter = true;
extern bool InpTrade_in_Monday = true;
extern bool InpTrade_in_Tuesday = true;
extern bool InpTrade_in_Wednesday = true;
extern bool InpTrade_in_Thursday = true;
extern bool InpTrade_in_Friday = true;

extern string InpStartHour = "00:00";
extern string InpEndHour = "23:59";

extern string _Visor1_ = "-----------------------------Visor 1 --------------------";
extern bool Visor1_Show_the_Time = True;
extern bool Visor1_Show_the_Price = True;

extern color Visor1_Price_Up_Color = LawnGreen;
extern color Visor1_Price_Down_Color = Tomato;
extern int Visor1_Price_X_Position = 10;
extern int Visor1_Price_Y_Position = 10;
extern int Visor1_Price_Size = 20;
double Visor1_Old_Price;

extern int Visor1_Porcent_X_Position = 10;
extern int Visor1_Porcent_Y_Position = 70;
extern int Visor1_Porcent_Size = 20;

extern int Visor1_Symbol_X_Position = 10;
extern int Visor1_Symbol_Y_Position = 40;
extern int Visor1_Symbol_Size = 20;

extern int Visor1_Chart_Timezone = -5;
extern color Visor1_Time_Color = Yellow;
extern int Visor1_Time_Size = 17;
extern int Visor1_Time_X_Position = 10;
extern int Visor1_Time_Y_Position = 10;

extern int Visor1_Spread_Size = 10;
extern int Visor1_Spread_X_Position = 10;
extern int Visor1_Spread_Y_Position = 100;

color Visor1_FontColor = Black;

int Visor1_Sinal = 0;

int SlipPage = 3;
bool GridAll = false;

bool m_hedging1, m_target_filter1;
int m_direction1, m_current_day1, m_previous_day1;
double m_level1, m_buyer1, m_seller1, m_target1, m_profit1;
double m_pip1, m_size1, m_take1;
datetime m_datetime_ultcandleopen1;
datetime m_time_equityrisk1;
double m_mediaprice1, profit1;
int m_orders_count1;
double m_lastlot1;

bool m_hedging2, m_target_filter2;
int m_direction2, m_current_day2, m_previous_day2;
double m_level2, m_buyer2, m_seller2, m_target2, m_profit2;
double m_pip2, m_size2, m_take2;
datetime m_datetime_ultcandleopen2;
datetime m_time_equityrisk2;
double m_mediaprice2;
int m_orders_count2;
double m_lastlot2, profit2;

string m_symbol;
bool m_news_time;
double m_spreadX;
double Spread;
bool m_initpainel;
string m_filters_on;
double m_profit_all;
datetime m_time_equityriskstopall;

int OnInit()
{
      // код доступен только после оплаты
   }

void OnDeinit(const int reason)
{
  ObjectDelete("Market_Price_Label");
  ObjectDelete("Time_Label");
  ObjectDelete("Porcent_Price_Label");
  ObjectDelete("Spread_Price_Label");
  ObjectDelete("Simbol_Price_Label");

}

void Informacoes()
{

  string Ls_64;

  int Li_84;

  if (!IsOptimization())
  {
    Visor1Handling();
    Ls_64 = "\n\n  ";
    Ls_64 = Ls_64 + "==========================\n";
    Ls_64 = Ls_64 + " " + " xBest FULL Hedge v3.47 2018-03-26 " + "\n";
    Ls_64 = Ls_64 + "==========================\n";

    Ls_64 = Ls_64 + "  Time of Broker:" + TimeToStr(TimeCurrent(), TIME_DATE | TIME_SECONDS) + "\n";

    Ls_64 = Ls_64 + "  Grid Size : " + (string)InpGridSize + " Pips \n";
    Ls_64 = Ls_64 + "  TakeProfit: " + (string)InpTakeProfit + " Pips \n";
    Ls_64 = Ls_64 + "  Lot Mode : " + (string)InpLotMode + "  \n";
    Ls_64 = Ls_64 + "  Exponent Factor: " + (string)InpGridFactor + " pips\n";
    Ls_64 = Ls_64 + "  Daily Target: " + (string)InpDailyTarget + "\n";

    Ls_64 = Ls_64 + "  InpMaxSpread: " + (string)InpMaxSpread + " pips\n";
    Ls_64 = Ls_64 + "==========================\n";

    Ls_64 = Ls_64 + "  Equity:      " + DoubleToStr(AccountEquity(), 2) + " \n";
    Ls_64 = Ls_64 + "  Last Lot : | A : " + DoubleToStr(m_lastlot1, 2) + " | B : " + DoubleToStr(m_lastlot2, 2) + " \n";
    Ls_64 = Ls_64 + "  Orders Opens :   " + string(CountTrades()) + " | A : " + (string)m_orders_count1 + " | B : " + (string)m_orders_count2 + " \n";
    Ls_64 = Ls_64 + "  Profit/Loss: " + DoubleToStr(m_profit_all, 2) + " | A : " + DoubleToStr(CalculateProfit(InpMagic), 2) + " | B : " + DoubleToStr(CalculateProfit(InpMagic2), 2) + " \n";
    Ls_64 = Ls_64 + " ==========================\n";
    Ls_64 = Ls_64 + " EquityCautionFilter : " + (string)InpUseEquityCaution + " \n";
    Ls_64 = Ls_64 + " TotalEquityRiskCaution : " + DoubleToStr(InpTotalEquityRiskCaution, 2) + " % \n";
    Ls_64 = Ls_64 + " EquityStopFilter : " + (string)InpUseEquityStop + " \n";
    Ls_64 = Ls_64 + " TotalEquityRiskStop : " + DoubleToStr(InpTotalEquityRisk, 2) + " % \n";
    Ls_64 = Ls_64 + " NewsFilter : " + (string)InpUseFFCall + " \n";
    Ls_64 = Ls_64 + " TimeFilter : " + (string)InpUtilizeTimeFilter + " \n";
    Ls_64 = Ls_64 + " ==========================\n";
    Ls_64 = Ls_64 + m_filters_on;

    Comment(Ls_64);

    Li_84 = 16;
    if (InpDisplayInpBackgroundColor)
    {
      if (m_initpainel || Seconds() % 5 == 0)
      {
        m_initpainel = FALSE;
        for (int count_88 = 0; count_88 < 12; count_88++)
        {
          for (int count_92 = 1; count_92 < Li_84; count_92++)
          {
            ObjectDelete("background" + (string)count_88 + (string)count_92);
            ObjectDelete("background" + (string)count_88 + ((string)(count_92 + 1)));
            ObjectDelete("background" + (string)count_88 + ((string)(count_92 + 2)));
            ObjectCreate("background" + (string)count_88 + (string)count_92, OBJ_LABEL, 0, 0, 0);
            ObjectSetText("background" + (string)count_88 + (string)count_92, "n", 30, "Wingdings", InpBackgroundColor);
            ObjectSet("background" + (string)count_88 + (string)count_92, OBJPROP_XDISTANCE, 20 * count_88);
            ObjectSet("background" + (string)count_88 + (string)count_92, OBJPROP_YDISTANCE, 23 * count_92 + 9);
          }
        }
      }
    }
    else
    {
      if (m_initpainel || Seconds() % 5 == 0)
      {
        m_initpainel = FALSE;
        for (int count_88 = 0; count_88 < 9; count_88++)
        {
          for (int count_92 = 0; count_92 < Li_84; count_92++)
          {
            ObjectDelete("background" + (string)count_88 + (string)count_92);
            ObjectDelete("background" + (string)count_88 + ((string)(count_92 + 1)));
            ObjectDelete("background" + (string)count_88 + ((string)(count_92 + 2)));
          }
        }
      }
    }
  }
}

void OnTick()
{
      // код доступен только после оплаты
   }

void xBest(string Id, int Sinal, bool TradeNow, double LotsHedge, int vInpMagic, int &m_orders_count, double &m_mediaprice, bool &m_hedging, bool &m_target_filter,
           int &m_direction, int &m_current_day, int &m_previous_day,
           double &m_level, double &m_buyer, double &m_seller, double &m_target, double &m_profit,
           double &m_pip, double &m_size, double &m_take, datetime &vDatetimeUltCandleOpen,
           datetime &m_time_equityrisk, double &profit)
{

  int index, orders_total, order_ticket, order_type, ticket, hour;
  double volume_min, volume_max, volume_step, lots;
  double account_balance, margin_required, risk_balance;
  double order_open_price, order_lots;

  int buy_ticket = 0, sell_ticket = 0, orders_count = 0, buy_ticket2 = 0, sell_ticket2 = 0;
  int buyer_counter = 0, seller_counter = 0;
  bool was_trade = false, close_filter = false;
  bool long_condition = false, short_condition = false;
  double orders_profit = 0.0, level = 0.0;
  double buyer_lots = 0.0, seller_lots = 0.0;
  double buyer_sum = 0.0, seller_sum = 0.0, sell_lot = 0, buy_lot = 0;
  ;
  double buy_price = 0.0, sell_price = 0.0;
  double bid_price = Bid, ask_price = Ask;
  double close_price = iClose(NULL, 0, 0);
  double open_price = iOpen(NULL, 0, 0);
  datetime time_current = TimeCurrent();
  bool res = false;
  m_spreadX = 2.0 * m_pip;

  account_balance = AccountBalance();
  volume_min = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_MIN);
  volume_max = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_MAX);
  volume_step = SymbolInfoDouble(m_symbol, SYMBOL_VOLUME_STEP);
  lots = volume_min;

  if (InpLotMode == LOT_MODE_FIXED)
    lots = InpFixedLot;
  else if (InpLotMode == LOT_MODE_PERCENT)
  {
    risk_balance = InpPercentLot * AccountBalance() / 100.0;
    margin_required = MarketInfo(m_symbol, MODE_MARGINREQUIRED);
    lots = MathRound(risk_balance / margin_required, volume_step);
    if (lots < volume_min)
      lots = volume_min;
    if (lots > volume_max)
      lots = volume_max;
  }

  m_current_day = TimeDayOfWeek(time_current);
  if (m_current_day != m_previous_day)
  {
    m_target_filter = false;
    m_target = 0.0;
  }
  m_previous_day = m_current_day;

  orders_total = OrdersTotal();
  m_mediaprice = 0;
  double BuyProfit = 0;
  double SellProfit = 0;
  int countFirts = 0;
  double Firts2SellProfit = 0;
  double Firts2BuyProfit = 0;
  int Firtsticket[50];
  double LastSellProfit = 0;
  double LastBuyProfit = 0;
  int Lastticket = 0;

  int
      BuyPriceMaxTic = 0, BuyPriceMinTic = 0,
      SelPriceMaxTic = 0, SelPriceMinTic = 0;

  double
      BuyPriceMax = 0, BuyPriceMin = 0, BuyPriceMaxLot = 0, BuyPriceMinLot = 0,
      SelPriceMin = 0, SelPriceMax = 0, SelPriceMinLot = 0, SelPriceMaxLot = 0;

string Grid = Id;

  for (index = orders_total - 1; index >= 0; index--)
  {
    if (!OrderSelect(index, SELECT_BY_POS, MODE_TRADES))
      continue;
    if (OrderMagicNumber() != vInpMagic || OrderSymbol() != m_symbol)
      continue;
    order_open_price = OrderOpenPrice();
    order_ticket = OrderTicket();
    order_type = OrderType();
    order_lots = OrderLots();

    if (order_type == OP_BUY)
    {

      if (order_ticket > buy_ticket)
      {

        buy_price = order_open_price;
        buy_ticket = order_ticket;
        LastBuyProfit = OrderProfit() + OrderCommission() + OrderSwap();
        Lastticket = order_ticket;
        buy_lot = order_lots;

      }

     if (order_open_price > BuyPriceMax || BuyPriceMax == 0)
            {
              BuyPriceMax = order_open_price;
              BuyPriceMaxLot = order_lots;
              BuyPriceMaxTic = order_ticket;
                Grid = order_ticket;
            }

    if (order_open_price < BuyPriceMin || BuyPriceMin == 0)
            {
              BuyPriceMin = order_open_price;
              BuyPriceMinLot = order_lots;
              BuyPriceMinTic = order_ticket;

            }

      buyer_sum += (order_open_price - m_spreadX) * order_lots;

      buyer_lots += order_lots;
      buyer_counter++;
      orders_count++;
      m_mediaprice += order_open_price * order_lots;
      if (OrderProfit() > 0)
        BuyProfit += OrderProfit() + OrderCommission() + OrderSwap();
    }

    if (order_type == OP_SELL)
    {

      if (order_ticket > sell_ticket)
      {

        sell_price = order_open_price;
        sell_ticket = order_ticket;
        LastSellProfit = OrderProfit() + OrderCommission() + OrderSwap();
        Lastticket = order_ticket;
        sell_lot = order_lots;

      }

          if (order_open_price > SelPriceMax || SelPriceMax == 0)
            {
              SelPriceMax = order_open_price;
              SelPriceMaxLot = order_lots;
              SelPriceMaxTic = order_ticket;

            }
            if (order_open_price < SelPriceMin || SelPriceMin == 0)
            {
               Grid = order_ticket;
              SelPriceMin = order_open_price;
              SelPriceMinLot = order_lots;
              SelPriceMinTic = order_ticket;
            }

      seller_sum += (order_open_price + m_spreadX) * order_lots;

      seller_lots += order_lots;
      seller_counter++;
      orders_count++;
      m_mediaprice += order_open_price * order_lots;
      if (OrderProfit() > 0)
        SellProfit += OrderProfit() + OrderCommission() + OrderSwap();
    }

    orders_profit += OrderProfit() + OrderCommission() + OrderSwap();
  }

  int l_hist_total_4 = OrdersHistoryTotal();

    double profitHist= 0;

    for (int l_pos_24 = 0; l_pos_24 < l_hist_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_HISTORY);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != vInpMagic)
            continue;

       if(OrderComment() == Grid){
           profitHist += OrderProfit() + OrderCommission() + OrderSwap();
       }

    }

    if(MinimalProfitProtectGrid && (orders_profit + profitHist ) > MinProfit   && orders_count > QtdTradesMinProfit) 
       CloseThisSymbolAll(vInpMagic);

  m_orders_count = orders_count;
  m_profit = orders_profit;
  if ((seller_counter + buyer_counter) > 0)
    m_mediaprice = NormalizeDouble(m_mediaprice / (buyer_lots + seller_lots), Digits);

  color avgLine = Blue;
  if (seller_lots > 0)
    avgLine = Red;

  if (buyer_lots > 0 || seller_lots > 0)
    SetHLine(avgLine, "Avg" + Id, m_mediaprice, 0, 3);
  else
    ObjectDelete("Avg" + Id);

  if (InpUseTrailingStop)
    TrailingAlls(InpTrailStart, InpTrailStop, m_mediaprice, vInpMagic);

  if (InpUseBreakEven)
    BreakEvenAlls(InpBreakEvenStart, InpBreakEvenStep, m_mediaprice, vInpMagic);

  if (orders_count == 0)
  {
    m_target += m_profit;
    m_hedging = false;
  }
  profit = m_target + orders_profit;

  if (InpDailyTarget > 0 && m_target + orders_profit >= InpDailyTarget)
    m_target_filter = true;

  if (m_hedging && ((m_direction > 0 && bid_price >= m_level) || (m_direction < 0 && ask_price <= m_level)))
    close_filter = true;

  if (m_target_filter || close_filter)
  {

    CloseThisSymbolAll(vInpMagic);

    return;
  }

  if (!m_hedging)
  {
    if (orders_count > 0 && !GridAll)
    {
      if (OpenNewOrdersGrid == true && TradeNow)
      {
        if (m_time_equityrisk1 != iTime(NULL, InpTimeframeEquityCaution, 0))
        {
          if (GridAllDirect)
          {
            if (buyer_counter > 0 && ask_price - buy_price >= m_size)
              long_condition = true;
            if (seller_counter > 0 && sell_price - bid_price >= m_size)
              short_condition = true;
          }
          if (buyer_counter > 0 && buy_price - ask_price >= m_size)
            long_condition = true;
          if (seller_counter > 0 && bid_pric

Показано первые 50% кода (символов: 45595)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
4 559,50₽ ≈ $55.73