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

xBest Rv3.47

fxcoregold v9 mq4@amazing_owner.mq4

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

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

Продукт поддерживает два независимых торговых движка — Engine A (BUY) и Engine B (SELL), каждый со своим магическим числом. Доступны различные режимы управления лотами: фиксированный, процентный, мартингейл и пошаговый. Включено хеджирование после достижения заданного уровня убыточных ордеров.

Советник оснащён системой фильтрации: по спреду, времени, новостям (FFCal), уровню риска капитала (EquityStop и EquityCaution). Также реализованы функция трейлинг-стоп, брейк-эвен и защита сетки от убытков при достижении минимальной прибыли. На графике отображается информационная панель с ценой, временем, процентом изменения и спредом.

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

НастройкаОписание
Version__ Текстовый параметр версии.
Version1__ Текстовый параметр версии.
Version2__ Текстовый параметр версии.
InpChartDisplay__ Группа настроек отображения информации (Display Info).
InpChartDisplay Включение или отключение отображения информационной панели на графике.
InpDisplayInpBackgroundColor Отображение цветного фона на информационной панели.
InpBackgroundColor Цвет фона информационной панели.
Switches Группа настроек переключателей (Switches).
InpManualInitGrid Ручной запуск сетки ордеров (работает только при включённых движках A и B).
InpOpenNewOrders Включение или отключение открытия новых ордеров.
OpenNewOrdersGrid Включение или отключение сеточного открытия ордеров.
InpCloseAllNow Немедленное закрытие всех ордеров на текущем символе.
Magic Группа настроек магических чисел для торговых движков.
Magic_ Группа настроек дополнительного мотора (при отключении обоих движков торговля выполняется в направлениях BUY и SELL).
InpEnableEngineA Включение торгового движка A (BUY).
InpMagic Магическое число для торгового движка A (BUY).
InpEnableEngineB Включение торгового движка B (SELL).
InpMagic2 Магическое число для торгового движка B (SELL).
ConfigLOTE__ Группа настроек конфигурации лотов (Config Lot INIT).
InpLotMode Режим управления лотами: фиксированный или процентный.
InpFixedLot Фиксированный размер лота при ручном режиме управления лотами.
InpPercentLot Процент от баланса для расчёта размера лота при процентном режиме.
InpTakeProfit Тейк-профит в пунктах.
XBEST_ConfigGrid__ Группа настроек конфигурации сетки (Config Grid).
TypeGridLot Тип сеточного лота: фиксированный, суммарный, мартингейл или пошаговый.
InpGridSize Размер шага сетки в пунктах.
InpGridFactor Множитель увеличения размера лота в сетке (при использовании мартингейла).
InpGridStepLot Шаг изменения лота при пошаговом режиме управления лотами.
InpMaxLot Максимально допустимый размер лота.
InpHedgex Уровень убыточных ордеров, после которого размер лота меняется с A на B (требуется включение обоих движков).
GridAllDirect Включение двусторонней сетки (открытие сетки в обоих направлениях одновременно).
FilterOpenOneCandle__ Группа настроек фильтра одного ордера по свече (Filter One Order by Candle).
InpOpenOneCandle Открытие одного ордера за свечу.
InpTimeframeBarOpen Таймфрейм для фильтра открытия одного ордера по свече.
MinimalProfitClose__ Группа настроек закрытия при минимальной прибыли (Minimal Profit Close / Protect Grid).
InpEnableMinProfit Включение функции закрытия при достижении минимальной прибыли.
MinimalProfitProtectGrid Включение защиты сетки от закрытия прибыльных ордеров при достижении минимальной прибыли.
MinProfit Минимальная прибыль для закрытия ордеров или защиты сетки.
QtdTradesMinProfit Количество сделок, необходимое для активации закрытия при минимальной прибыли.
Config__ Группа настроек конфигурации (Config).
InpHedge Количество убыточных ордеров, после которого включается хеджирование.
InpDailyTarget Дневная цель по прибыли в деньгах. При достижении все ордера закрываются.
MovingAverageConfig__ Группа настроек скользящей средней (Moving Average).
InpMaFrame Таймфрейм для скользящей средней.
InpMAFilterInverter Инвертирование сигнала фильтра скользящей средней (при значении True сигнал меняется на противоположный).
InpMaPeriod Период скользящей средней.
InpMaMethod Метод расчёта скользящей средней (например, EMA).
InpMaPrice Тип цены для расчёта скользящей средней (например, открытие).
InpMaShift Сдвиг скользящей средней.
HILOConfig__ Группа настроек индикатора HILO.
EnableSinalHILO Включение или отключение сигнального фильтра HILO.
InpHILOFilterInverter Инвертирование сигнала фильтра HILO (при значении True сигнал меняется на противоположный).
InpHILOFrame Таймфрейм для индикатора HILO.
InpHILOPeriod Период индикатора HILO.
InpHILOMethod Метод расчёта индикатора HILO (например, EMA).
InpHILOShift Сдвиг индикатора HILO.
TrailingStop__ Группа настроек трейлинг-стопа (Trailing Stop).
InpUseTrailingStop Включение или отключение трейлинг-стопа.
InpTrailStart Начальная дистанция в пунктах для активации трейлинг-стопа.
InpTrailStop Размер трейлинг-стопа в пунктах.
BreakEven Группа настроек брейк-эвен (Break Even).
InpUseBreakEven Включение или отключение функции брейк-эвен.
InpBreakEvenStart Начальная дистанция в пунктах для активации брейк-эвен.
InpBreakEvenStep Шаг в пунктах для перемещения стоп-лосса при брейк-эвен.
TakeEquitySTOP__ Группа настроек Take Equity Stop.
InpUseTakeEquityStop Включение или отключение Take Equity Stop (закрытие при достижении целевой прибыли).
InpProfitCloseandSTOP Сумма прибыли в долларах, при достижении которой все ордера закрываются (Take Equity Stop).
FilterSpread__ Группа настроек фильтра максимального спреда (Filter Max Spread).
InpMaxSpread Максимально допустимый спред в пунктах. При превышении торговля блокируется.
EquityCaution__ Группа настроек предупреждения о риске капитала (Filter Caution of Equity).
InpUseEquityCaution Включение или отключение фильтра предупреждения о риске капитала (EquityCaution).
InpTotalEquityRiskCaution Процент риска капитала для предупреждения (EquityCaution).
InpTimeframeEquityCaution Таймфрейм для оценки риска капитала (EquityCaution).
EquitySTOP__ Группа настроек стопа по капиталу (Filter Equity STOP).
InpUseEquityStop Включение или отключение стопа по капиталу (EquityStop).
InpTotalEquityRisk Процент риска капитала для стопа по капиталу (EquityStop). При превышении убытка этого процента от капитала срабатывает защита.
InpAlertPushEquityLoss Отправка уведомления на мобильное устройство при убытке по капиталу.
InpCloseAllEquityLoss Автоматическое закрытие всех ордеров при достижении общего риска капитала.
FFCall__ Группа настроек фильтрации новостей (Filter News FFCall).
InpMinsBeforeNews Количество минут до новостного события, в течение которых торговля блокируется.
InpMinsAfterNews Количество минут после новостного события, в течение которых торговля блокируется.
InpUseFFCall Включение или отключение фильтра новостей (FFCall).
InpIncludeHigh Включение или исключение высокозначимых новостных событий в фильтре.
TimeFilter__ Группа настроек фильтра по дате и времени (Filter DateTime).
InpUtilizeTimeFilter Включение или отключение фильтра по времени торговли.
InpTrade_in_Monday Разрешение торговли по понедельникам.
InpTrade_in_Tuesday Разрешение торговли по вторникам.
InpTrade_in_Wednesday Разрешение торговли по средам.
InpTrade_in_Thursday Разрешение торговли по четвергам.
InpTrade_in_Friday Разрешение торговли по пятницам.
InpStartHour Время начала торговой сессии (формат ЧЧ:ММ).
InpEndHour Время окончания торговой сессии (формат ЧЧ:ММ).
_Visor1_ Группа настроек информационного дисплея (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% кода (символов: 45594)

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

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

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

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

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

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