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

scalperemaeasimple@lifeindreamsworld.mq4

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

#1.mtf_collider_h4_close_13_v18bar.mq4MQL4 / MetaTrader 4 · 1 общих теговea robofibo source v.11.2.mq4MQL4 / MetaTrader 4 · 1 общих теговsma crossover scalper ea for mt4.mq4MQL4 / MetaTrader 4 · 1 общих теговr15 pivot points expert advisor by @fundedmillionairess.mq4MQL4 / MetaTrader 4 · 1 общих теговnewstrader.mq5MQL5 / MetaTrader 5 · 1 общих теговmm3.0_flip_codepro_v3.1_with_cooldown@lifeindreamsworld.mq5MQL5 / MetaTrader 5 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

Перед открытием ордера советник проверяет допустимый объём сделки и наличие достаточных средств на счёте. Трейлинг-стоп обновляется с заданным интервалом времени, а также при достижении позиции определённого уровня прибыли. Закрытие хедж-позиций при положительной прибыли выполняется с повторными попытками при возникновении реквотирования.

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

НастройкаОписание
MAGICMA Магический номер — Уникальный идентификатор ордеров, размещённых данным советником, используется для фильтрации управляемых позиций.
Lot size for the orders (lotSize) Размер лота — Запрашиваемый объём сделки в лотах для каждого ордера.
periodEMAFast Период быстрой EMA — Период расчёта быстрой экспоненциальной скользящей средней, используемой в сигналах.
periodEMASlow Период медленной EMA — Период расчёта медленной экспоненциальной скользящей средней, используемой в сигналах.
strategy Стратегия — Выбранный режим торговой стратегии советника.
hedgeStrategy Стратегия хеджирования — Режим управления хедж-позициями: ProTrend — по тренду, ContraTrend — против тренда.
hedgeCloseStrategy Стратегия закрытия хеджа — Способ закрытия хедж-позиций: CloseASAP — немедленное закрытие при прибыли, TrailingStop — трейлинг-стоп.
distance Расстояние — Расстояние в пунктах для активации хедж-ордера относительно текущей цены или позиции.
stopLossDeltaPoints Дельта стоп-лосса в пунктах — Отступ в пунктах от цены открытия для установки начального стоп-лосса.
takeProfitActivationPoints Активация трейлинг-стопа в пунктах — Уровень прибыли в пунктах, при достижении которого активируется трейлинг-стоп.
trailingStopDeltaPoints Дельта трейлинг-стопа в пунктах — Расстояние в пунктах для трейлинг-стопа от текущей цены при его активации.
maxOpenBuyOrders Максимум открытых покупок — Максимально допустимое количество открытых ордеров на покупку одновременно.
maxOpenSellOrders Максимум открытых продаж — Максимально допустимое количество открытых ордеров на продажу одновременно.
AllOrders Все ордера — При false советник обрабатывает только ордера со своим магическим номером; при true — все ордера на символе.
Получить полный код

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

#include <stderror.mqh>
#include <stdlib.mqh>

#property version   "1.01"
#property strict

enum Strategy { SCALPEREMAs };
enum HedgeStrategy { ProTrend, ContraTrend };
enum HedgeCloseStrategy { CloseASAP, TrailingStop };

input int MAGICMA = 3937;
input double lotSize = 0.01; // Lot size for the orders
input int periodEMAFast = 39;
input int periodEMASlow = 740;
input Strategy strategy = SCALPEREMAs;
/*input*/ int stochasticK = 5;
/*input*/ int stochasticD = 5;
/*input*/ int stochasticSlowing = 5;
/*input*/ double overboughtLevel = 80;
/*input*/ double oversoldLevel = 20;
input HedgeStrategy hedgeStrategy = ProTrend;
input HedgeCloseStrategy hedgeCloseStrategy = TrailingStop;
input int distance = 10;
input int stopLossDeltaPoints = 50;
input int takeProfitActivationPoints = 10;
input int trailingStopDeltaPoints = 840;
input int maxOpenBuyOrders = 1;
input int maxOpenSellOrders = 1;
input bool AllOrders = false;

enum BarColor { GREEN_BAR, RED_BAR };
int maxBarsBack = 100;

double buySignalBuffer[];
double sellSignalBuffer[];
double barSizeBuffer[];
double distanceFromEmaBuffer[];
double retracementIndexBuffer[];
double stochasticIndexBuffer[];
double breakEMAFastIndexBuffer[];

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

void OnDeinit(const int reason)
  {

  }

datetime lastBarTime = 0; // Store the opening time of the last bar
datetime lastTrailingUpdateTime = 0; // Store the time of the last trailing stop update
int trailingStopIntervalMinutes = 5; // The minimum interval between trailing stop updates in minutes

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

void SetTrailingStop()
  {
   ResetLastError();
   int totalOrders = OrdersTotal();

   double currentProfit = AccountEquity() - AccountBalance();
   double newStopLossBuy = 0.0;
   double newStopLossSell = 0.0;

   if(hedgeCloseStrategy == TrailingStop || totalOrders == 1)
     {
      for(int i = 0; i < totalOrders; i++)
        {
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
           {
            if(OrderSymbol() == Symbol())
              {
               if(!AllOrders && OrderMagicNumber()!=MAGICMA)
                 {
                  continue;
                 }
               if(OrderType() == OP_BUY)
                 {
                  if(Bid > OrderOpenPrice() + takeProfitActivationPoints * Point)
                    {
                     newStopLossBuy = CheckStopLoss(Bid + trailingStopDeltaPoints, OP_BUY);

                    }
                  if((OrderStopLoss() == 0 && newStopLossBuy > 0) || (newStopLossBuy > 0 && newStopLossBuy > OrderStopLoss()))
                     if(OrderModify(OrderTicket(), 0, newStopLossBuy, OrderTakeProfit(), 0, clrNONE))
                       {
                        Print("OK modifying BUY order ticket", OrderTicket(), "!");
                       }
                     else
                       {
                        int error = GetLastError();
                        if(error == 1)
                          {
                           Print("Error 1 (ERR_NO_RESULT) while modifying BUY order. Details:");
                           Print("Details: ", ErrorDescription(error));
                           Print("Order Type: OP_BUY");
                           Print("Stop Loss: ", newStopLossBuy);
                           Print("Take Profit: ", OrderTakeProfit());
                          }
                        if(error == 130)
                          {
                           Print("Error 130 (ERR_INVALID_STOPS) while modifying BUY order. Details:");
                           Print("Details: ", ErrorDescription(error));
                           Print("Order Type: OP_BUY");
                           Print("Stop Loss: ", newStopLossBuy);
                           Print("Take Profit: ", OrderTakeProfit());
                          }
                        else
                          {
                           Print("Error modifying BUY order. Error code: ", error, " - ", ErrorDescription(error));
                          }
                       }
                 }
               else
                  if(OrderType() == OP_SELL)
                    {
                     if(Ask < OrderOpenPrice() - takeProfitActivationPoints * Point)
                       {
                        newStopLossSell = CheckStopLoss(Ask - trailingStopDeltaPoints, OP_SELL);

                       }
                     if((OrderStopLoss() == 0 && newStopLossSell > 0) || (newStopLossSell > 0 && newStopLossSell < OrderStopLoss()))
                        if(OrderModify(OrderTicket(), 0, newStopLossSell, OrderTakeProfit(), 0, clrNONE))
                          {
                           Print("OK modifying SELL order ticket", OrderTicket(), "!");
                          }
                        else
                          {
                           int error = GetLastError();
                           if(error == 1)
                             {
                              Print("Error 1 (ERR_NO_RESULT) while modifying SELL order. Details:");
                              Print("Details: ", ErrorDescription(error));
                              Print("Order Type: OP_SELL");
                              Print("Stop Loss: ", newStopLossSell);
                              Print("Take Profit: ", OrderTakeProfit());
                             }
                           if(error == 130)
                             {
                              Print("Error 130 (ERR_INVALID_STOPS) while modifying SELL order. Details:");
                              Print("Details: ", ErrorDescription(error));
                              Print("Order Type: OP_SELL");
                              Print("Stop Loss: ", newStopLossSell);
                              Print("Take Profit: ", OrderTakeProfit());
                             }
                           else
                             {
                              Print("Error modifying SELL order. Error code: ", error, " - ", ErrorDescription(error));
                             }
                          }
                    }
              }
           }
        }
     }
   else
      if(currentProfit > 0)
        {
         for(int i = 0; i < totalOrders; i++)
           {
            if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
              {
               if(OrderSymbol() == Symbol())
                 {
                  if(!AllOrders && OrderMagicNumber()!=MAGICMA)
                    {
                     continue;
                    }

                  RefreshRates();

                  double orderClosePrice = OrderClosePrice();
                  if(OrderType() == OP_BUY)
                     orderClosePrice = Bid;
                  else
                     if(OrderType() == OP_SELL)
                        orderClosePrice = Ask;
                  for(int retryCount = 0; retryCount < 3; retryCount++)
                    {
                     bool result = OrderClose(OrderTicket(), OrderLots(), orderClosePrice, 2, clrNONE);

                     if(result)
                       {
                        Print("Order closed successfully: ", OrderType(), " ", OrderLots(), " lots at price ", orderClosePrice);
                        break;
                       }
                     else
                       {
                        if(GetLastError() == 138)  // Requote error
                          {
                           orderClosePrice = MarketInfo(OrderSymbol(), MODE_BID) + MarketInfo(OrderSymbol(), MODE_POINT) * retryCount;
                           Sleep(1000); // Wait for a second before retrying
                          }
                        else
                          {
                           Print("Error closing order: ", GetLastError());
                           break;
                          }
                       }
                    }
                 }
              }
           }
        }

   RefreshRates();
   if(hedgeStrategy == ProTrend)
     {
      double Buys = CountBuys();
      double Sells = CountSells();

      if(Buys - Ask >= distance * Point)
         if(CanOpenOrder(OP_BUY))
           {
            OpenBuyOrder();
           }

      if(Bid - Sells >= distance * Point)
         if(CanOpenOrder(OP_SELL))
           {
            OpenSellOrder();
           }
     }
   if(hedgeStrategy == ContraTrend)
     {
      int lastOrderType = 0;
      double lastOrderOpenPrice = 0;
      double lastOrderLots = 0;
      GetLastOrderTypeAndOpenPrice(lastOrderType, lastOrderOpenPrice, lastOrderLots);
      if(lastOrderOpenPrice > 0 && lastOrderLots > 0)
        {
         if(lastOrderType == OP_BUY && lastOrderOpenPrice - Ask >= distance * Point)
           {
            if(totalOrders == 1)
              {
               if(CanOpenOrder(OP_SELL))
                 {
                  OpenSellOrder();
                 }
              }
            else
               if(CanOpenOrder(OP_BUY))
                 {
                  OpenBuyOrder();
                 }
           }
         if(lastOrderType == OP_SELL && Bid - lastOrderOpenPrice >= distance * Point)
           {
            if(totalOrders == 1)
              {
               if(CanOpenOrder(OP_BUY))
                 {
                  OpenBuyOrder();
                 }
              }
            else
               if(CanOpenOrder(OP_SELL))
                 {
                  OpenSellOrder();
                 }
           }
        }
     }
  }

double CountBuys()
  {
   double orderOpenPrice = Ask;
   int ticket_8 = 0;
   int ticket_20 = 0;
   for(int pos_24 = OrdersTotal() - 1; pos_24 >= 0; pos_24--)
     {
      if(OrderSelect(pos_24, SELECT_BY_POS, MODE_TRADES))
         if(!AllOrders && OrderMagicNumber()!=MAGICMA)
            continue;
      if(OrderSymbol() == Symbol() && OrderType() == OP_BUY)
        {
         ticket_8 = OrderTicket();
         if(ticket_8 > ticket_20)
           {
            orderOpenPrice = OrderOpenPrice();
            ticket_20 = ticket_8;
           }
        }
     }
   return (orderOpenPrice);
  }

double CountSells()
  {
   double orderOpenPrice = Bid;
   int ticket_8 = 0;
   int ticket_20 = 0;
   for(int pos_24 = OrdersTotal() - 1; pos_24 >= 0; pos_24--)
     {
      if(OrderSelect(pos_24, SELECT_BY_POS, MODE_TRADES))
         if(!AllOrders && OrderMagicNumber()!=MAGICMA)
            continue;
      if(OrderSymbol() == Symbol() && OrderType() == OP_SELL)
        {
         ticket_8 = OrderTicket();
         if(ticket_8 > ticket_20)
           {
            orderOpenPrice = OrderOpenPrice();
            ticket_20 = ticket_8;
           }
        }
     }
   return (orderOpenPrice);
  }

void GetLastOrderTypeAndOpenPrice(int& type, double& orderOpenPrice, double& orderLots)
  {
   int ticket_8 = 0;
   int ticket_20 = 0;
   for(int pos_24 = OrdersTotal() - 1; pos_24 >= 0; pos_24--)
     {
      if(OrderSelect(pos_24, SELECT_BY_POS, MODE_TRADES))
         if(!AllOrders && OrderMagicNumber()!=MAGICMA)
            continue;
      if(OrderSymbol() == Symbol())
        {
         ticket_8 = OrderTicket();
         if(ticket_8 > ticket_20)
           {
            type = OrderType();
            orderOpenPrice = OrderOpenPrice();
            orderLots = OrderLots();
            ticket_20

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

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

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

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

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

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

Стоимость полного кода
1 781,20₽ ≈ $21.77