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

xBest Rv3.47

xbest v3.47 ea@lifeindreamsworld.mq4

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

fxcoregold ea full.mq4MQL4 / MetaTrader 4 · 2 общих теговfxcoregold v9 mq4 (2).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, реализующий стратегию сеточного хеджирования с двумя независимыми движками: движок A работает на покупку, движок B — на продажу. Советник анализирует рыночные цены с помощью скользящей средней и индикатора HILO, формирует торговые сигналы и управляет сеткой ордеров с настраиваемым увеличением лота. Продукт предоставляет визуальную панель на графике с отображением текущей цены, спреда, прибыли и времени.

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

НастройкаОписание
Version__ Разделитель версии — Текстовый разделитель
Version1__ Название версии — Текстовый заголовок версии продукта
Version2__ Разделитель версии — Текстовый разделитель
InpChartDisplay__ Разделитель отображения — Текстовый разделитель
InpChartDisplay Отображение информации — Включает или отключает вывод информационной панели на график
InpDisplayInpBackgroundColor Фон панели — Включает или отключает отображение цветного фона информационной панели
InpBackgroundColor Цвет фона — Цвет фона информационной панели
Switches Переключатели — Текстовый разделитель
InpManualInitGrid Ручной запуск сетки — Включает ручной запуск сетки ордеров при нажатии кнопок на графике
InpOpenNewOrders Новые ордера — Разрешает открытие новых ордеров по сигналам
OpenNewOrdersGrid Сетка ордеров — Включает или отключает открытие ордеров в сетку
InpCloseAllNow Закрыть все ордера — Немедленно закрывает все открытые ордера по обоим движкам
Magic Разделитель магических номеров — Текстовый разделитель
Magic_ Описание магических номеров — Текстовый разделитель
InpEnableEngineA Движок A (BUY) — Включает торговый движок A для открытия позиций на покупку
InpMagic Магический номер A — Уникальный идентификатор ордеров для движка A
InpEnableEngineB Движок B (SELL) — Включает торговый движок B для открытия позиций на продажу
InpMagic2 Магический номер B — Уникальный идентификатор ордеров для движка B
ConfigLOTE__ Настройки лота — Текстовый разделитель
InpLotMode Режим лота — Режим расчёта размера лота: фиксированный или процентный
InpFixedLot Фиксированный лот — Фиксированный размер лота при фиксированном режиме
InpPercentLot Процент лота — Процент от баланса для расчёта размера лота
InpTakeProfit Тейк-профит — Уровень фиксированной прибыли в пипсах для установки на ордера
XBEST_ConfigGrid__ Настройки сетки — Текстовый разделитель
TypeGridLot Тип увеличения лота — Способ увеличения размера лота в сетке: фиксированный, суммарный, мартингейл или по шагу
InpGridSize Шаг сетки — Размер шага сетки в пипсах
InpGridFactor Коэффициент сетки — Множитель увеличения лота при использовании режима мартингейл
InpGridStepLot Шаг лота — Интервал увеличения лота при режиме Step Lot
InpMaxLot Максимальный лот — Максимально допустимый размер лота
InpHedgex Уровень хеджирования — Количество убыточных ордеров одного направления для переключения на противоположное
GridAllDirect Двусторонняя сетка — Включает открытие сетки в обоих направлениях одновременно
FilterOpenOneCandle__ Фильтр свечи — Текстовый разделитель
InpOpenOneCandle Один ордер за свечу — Ограничивает открытие одного ордера за одну свечу
InpTimeframeBarOpen Таймфрейм свечи — Таймфрейм для определения новой свечи при фильтре одного ордера
MinimalProfitClose__ Минимальная прибыль — Текстовый разделитель
InpEnableMinProfit Минимальная прибыль — Включает автоматическое закрытие прибыльных ордеров при достижении минимальной прибыли
MinimalProfitProtectGrid Защита сетки — Включает защиту сетки путём закрытия при достижении общей прибыли
MinProfit Минимальная сумма — Порог минимальной прибыли для закрытия или защиты сетки
QtdTradesMinProfit Количество сделок — Минимальное количество сделок для срабатывания фильтра минимальной прибыли
Config__ Общие настройки — Текстовый разделитель
InpHedge Уровень хеджирования — Количество убыточных ордеров для активации хеджирования
InpDailyTarget Дневная цель — Целевая дневная прибыль в денежном выражении для закрытия всех ордеров
MovingAverageConfig__ Скользящая средняя — Текстовый разделитель
InpMaFrame Таймфрейм MA — Таймфрейм для расчёта скользящей средней
InpMAFilterInverter Инверсия MA — Инвертирует сигнал скользящей средней
InpMaPeriod Период MA — Период расчёта скользящей средней
InpMaMethod Метод MA — Метод расчёта скользящей средней
InpMaPrice Цена MA — Тип цены для расчёта скользящей средней
InpMaShift Сдвиг MA — Горизонтальный сдвиг скользящей средней
HILOConfig__ HILO индикатор — Текстовый разделитель
EnableSinalHILO Сигнал HILO — Включает использование индикатора HILO для формирования сигналов
InpHILOFilterInverter Инверсия HILO — Инвертирует сигнал индикатора HILO
InpHILOFrame Таймфрейм HILO — Таймфрейм для расчёта индикатора HILO
InpHILOPeriod Период HILO — Период расчёта индикатора HILO
InpHILOMethod Метод HILO — Метод расчёта индикатора HILO
InpHILOShift Сдвиг HILO — Горизонтальный сдвиг индикатора HILO
TrailingStop__ Трейлинг-стоп — Текстовый разделитель
InpUseTrailingStop Трейлинг-стоп — Включает автоматическое перемещение стоп-лосса в прибыльную зону
InpTrailStart Начало трейлинга — Расстояние в пипсах от текущей цены для начала трейлинга
InpTrailStop Шаг трейлинга — Расстояние в пипсах для шага трейлинг-стопа
BreakEven Безубыточность — Текстовый разделитель
InpUseBreakEven Безубыточность — Включает перемещение стоп-лосса в точку безубыточности
InpBreakEvenStart Начало безубыточности — Расстояние в пипсах от цены входа для активации безубыточности
InpBreakEvenStep Шаг безубыточности — Расстояние в пипсах для фиксации безубыточного уровня
TakeEquitySTOP__ Стоп по средствам — Текстовый разделитель
InpUseTakeEquityStop Стоп по средствам — Включает автоматическое закрытие всех ордеров при достижении заданной прибыли
InpProfitCloseandSTOP Цель по прибыли — Размер прибыли в долларах для полного закрытия всех ордеров
FilterSpread__ Фильтр спреда — Текстовый разделитель
InpMaxSpread Максимальный спред — Максимально допустимый спред в пипсах для открытия ордеров
EquityCaution__ Предупреждение по средствам — Текстовый разделитель
InpUseEquityCaution Фильтр средств — Включает предупреждение при достижении заданного процента убытка от средств
InpTotalEquityRiskCaution Риск предупреждения — Процент убытка от средств для срабатывания предупреждения
InpTimeframeEquityCaution Таймфрейм средств — Таймфрейм для расчёта фильтра предупреждения по средствам
EquitySTOP__ Стоп по средствам — Текстовый разделитель
InpUseEquityStop Стоп средств — Включает полное закрытие всех ордеров при достижении заданного процента убытка
InpTotalEquityRisk Риск стопа — Процент убытка от средств для полного останова торгов
InpAlertPushEquityLoss Уведомление об убытке — Отправляет push-уведомление при срабатывании стопа по средствам
InpCloseAllEquityLoss Закрыть при стопе — Автоматически закрывает все ордера при достижении стопового уровня средств
FFCall__ Фильтр новостей — Текстовый разделитель
InpMinsBeforeNews До новости — Минуты до экономического события, в течение которых торговля приостанавливается
InpMinsAfterNews После новости — Минуты после экономического события, в течение которых торговля приостанавливается
InpUseFFCall Фильтр новостей — Включает фильтр экономических новостей
InpIncludeHigh Высокие новости — Включает учёт высокоимпактных новостей в фильтр
TimeFilter__ Фильтр времени — Текстовый разделитель
InpUtilizeTimeFilter Фильтр времени — Включает фильтрацию торгов по времени суток и дням недели
InpTrade_in_Monday Понедельник — Разрешает торговлю в понедельник
InpTrade_in_Tuesday Вторник — Разрешает торговлю во вторник
InpTrade_in_Wednesday Среда — Разрешает торговлю в среду
InpTrade_in_Thursday Четверг — Разрешает торговлю в четверг
InpTrade_in_Friday Пятница — Разрешает торговлю в пятницу
InpStartHour Время начала — Время начала торговой сессии
InpEndHour Время окончания — Время окончания торговой сессии
_Visor1_ Визор — Текстовый разделитель
Visor1_Show_the_Time Показать время — Отображает текущее время на графике
Visor1_Show_the_Price Показать цену — Отображает текущую цену Bid на графике
Visor1_Price_Up_Color Цвет роста — Цвет отображения цены при росте
Visor1_Price_Down_Color Цвет падения — Цвет отображения цены при падении
Visor1_Price_X_Position Позиция цены X — Горизонтальная позиция ценового ярлыка на графике
Visor1_Price_Y_Position Позиция цены Y — Вертикальная позиция ценового ярлыка на графике
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 = false;
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.71