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

SureForexHedging

sureforexhedging.mq4
Вы автор или правообладатель?

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

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

О программе

SureForexHedging — торговый советник для MetaTrader 4, реализующий стратегию хеджирования. Советник открывает начальную позицию в заданном направлении и при появлении открытых позиций размещает встречные ордера на определённом расстоянии. Объём последующих хеджирующих сделок увеличивается с помощью множителей лота.

Советник поддерживает фиксированный лот или расчёт объёма от баланса, а также позволяет ограничить торговлю по дневной прибыли в абсолютном значении или в процентах. Стоплосс и тейкпрофит задаются для всех сделок, с возможной корректировкой на спред. Поддерживается режим рыночного исполнения для ECN и STP счетов.

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

НастройкаОписание
initial_deal Направление начальной сделки — 0 — покупка, 1 — продажа, другие значения — открытие новых позиций отключено
stoploss Стоплосс — Стоплосс для всех сделок в пунктах или точках
takeprofit Тейкпрофит — Тейкпрофит для всех сделок в пунктах или точках
fixed_lot Фиксированный лот — Если больше 0, начальная сделка открывается с этим объёмом
deposit_lot Лот от депозита — Если fixed_lot равен 0 и deposit_lot больше 0, начальная сделка открывается с объёмом Balance / deposit_lot
martin_koeff1 Множитель лота 1 — Множитель лота для первой хеджирующей сделки
martin_koeff2 Множитель лота 2+ — Множитель лота для второй, третьей и последующих хеджирующих сделок
enable_daily_profit Включить ограничение дневной прибыли — Останавливает торговлю, если дневная прибыль превышает заданные значения
daily_profit Дневная прибыль — Целевая дневная прибыль в валюте счёта
daily_profit_percent Дневная прибыль в процентах — Дневная прибыль как процент от баланса на начало дня
distance0 Расстояние 1 — Расстояние для размещения первой хеджирующей сделки
distance1 Расстояние 2 — Расстояние для размещения второй хеджирующей сделки
distance2 Расстояние 3 — Расстояние для размещения третьей хеджирующей сделки
distance3 Расстояние 4 — Расстояние для размещения четвёртой хеджирующей сделки
distance4 Расстояние 5 — Расстояние для размещения пятой хеджирующей сделки
distance5 Расстояние 6 — Расстояние для размещения шестой хеджирующей сделки
distance6 Расстояние 7 — Расстояние для размещения седьмой хеджирующей сделки
distance7 Расстояние 8 — Расстояние для размещения восьмой хеджирующей сделки
distance8 Расстояние 9 — Расстояние для размещения девятой хеджирующей сделки
distance9 Расстояние 10 — Расстояние для размещения десятой хеджирующей сделки
normal_spread Корректировка спреда — Значение в пипсах, вычитаемое из тейкпрофита SELL и добавляемое к стоплоссу SELL
sep0 Разделитель настроек — Текстовый разделитель в панели настроек
params_digits Количество знаков — 4 — стоплосс, тейкпрофит и расстояния задаются в 4-знаковых пунктах, 5 — в 5-знаковых
initial_magic Начальный магический номер — Магический номер для начальной сделки; хеджирующие сделки добавляют 1 к этому числу
market_execution Рыночное исполнение — Установите 1 для ECN и STP счетов (стоплосс и тейкпрофит корректируются только после отправки ордера)
command_attempts Количество попыток — Количество одновременных попыток отправки запросов брокеру при ошибке
max_slippage Максимальный проскальзывание — Допустимое максимальное проскальзывание при открытии рыночных ордеров
Получить полный код

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

#include <stderror.mqh>

#define sec_wait_context 10
#define max_errors 30
#define wait_error 1000
#define busysleep 100
#define EB_NEXTTRY 0
#define EB_WAITTRY 1
#define EB_TERMINATE 2
#define StoplevelAdd 0

extern int initial_deal = 0 ; // Direction of initial deal: 0 - buy deal, 1 - sell deal, other values - new opening disabled
extern double stoploss = 60 ; // Stoploss for all deals
extern double takeprofit = 30 ; // takeprofit for all deals
extern double fixed_lot = 0.1 ; // If > 0, the initial deal will be opened with this lot
extern double deposit_lot = 0 ; // If fixed_lot is 0 and deposit_lot > 0, initial deal will be opened with volume Balance / deposit_lot lots
extern double martin_koeff1 = 3 ; // Lot multiplier for first hedging deal
extern double martin_koeff2 = 2 ; // Lot multiplier for second, third and further hedging deals
extern int enable_daily_profit = 0 ; // Enable option to stop trading if a daily profit exceeds following values (it considers profit for ALL currencies)
extern double daily_profit = 0 ; // Daily profit in the account currency
extern double daily_profit_percent = 0 ; // Daily profit as a percent to Balance of start of the day
extern double distance0 = 30 ; // If > 0, distance for placing 1-st hedging deal
extern double distance1 = 0 ; // If > 0, distance for placing 2-nd hedging deal
extern double distance2 = 0 ; // If > 0, distance for placing 3-rd hedging deal
extern double distance3 = 0 ; // If > 0, distance for placing 4-th hedging deal
extern double distance4 = 0 ; // If > 0, distance for placing 5-th hedging deal
extern double distance5 = 0 ; // If > 0, distance for placing 6-th hedging deal
extern double distance6 = 0 ; // If > 0, distance for placing 7-th hedging deal
extern double distance7 = 0 ; // If > 0, distance for placing 8-th hedging deal
extern double distance8 = 0 ; // If > 0, distance for placing 9-th hedging deal
extern double distance9 = 0 ; // If > 0, distance for placing 10-th hedging deal
extern double normal_spread = 0 ; // This value in pips is substracted from SELL takeprofit and added to SELL stoploss to consider the spread
extern string sep0 = " common EA settings " ;
extern int params_digits = 4 ; // If = 4, then stoploss, takeprofit and distances are specified in 4-digit points, if = 5, then in 5-digit pips
extern int initial_magic = 123000 ; // Initial magic number for 1-st deal. Hedging deals add 1 to this number
extern int market_execution = 0 ; // Set to 1 for ECN and STP accounts (stoploss and takeprofit are modified only after an order is sent)
extern int command_attempts = 5 ; // Number of simultaneous attempts of sending broker requests (if some error occurs)
extern int max_slippage = 10 ; // Maximum slippage

int go = true ;
double point, d_stoplevel, d_freezelevel, d_buystop, d_sellstop, d_buytake, d_selltake ;
int errors = 0 ;
int lotsdigits ;

double dist [10] ;

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

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

int ErrorBlock (int err, int ms)
{
   string str = "" ;
   int res = EB_TERMINATE ;

   switch (err)
   {
      case ERR_NO_ERROR:
         str = "No error" ;

         break ;
      case ERR_NO_RESULT:
         str = "Unknown result" ;

         break ;
      case ERR_COMMON_ERROR:
         str = "Common error. Probably the signal was rejected by user or trade direction is denied in expert settings" ;

         break ;
      case ERR_INVALID_TRADE_PARAMETERS:
         str = "Wrong trade function parameters" ;

         break ;
      case ERR_SERVER_BUSY:
         str = "Server is busy. Waiting..." ;
         res = EB_WAITTRY ;

         break ;
      case ERR_OLD_VERSION:
         str = "Old version of client terminal" ;

         break ;
      case ERR_NO_CONNECTION:
         str = "No connection with trade server. Waiting..." ;
         res = EB_WAITTRY ;

         break ;
      case ERR_NOT_ENOUGH_RIGHTS:
         str = "Not enough rights" ;

         break ;   
      case ERR_TOO_MANY_REQUESTS:
      case ERR_TOO_FREQUENT_REQUESTS:
         str = "To many requests" ;

         break ;
      case ERR_MALFUNCTIONAL_TRADE:
         str = "Malfunctional trade" ;

         break ;
      case ERR_ACCOUNT_DISABLED:
         str = "The account is blocked" ;

         break ;
      case ERR_INVALID_ACCOUNT:
         str = "Invalid account" ;

         break ;
      case ERR_TRADE_TIMEOUT:
         str = "Trade timeout exceeded" ;
         res = EB_NEXTTRY ;

         break ;
      case ERR_INVALID_PRICE:
         str = "Wrong price" ;
         res = EB_NEXTTRY ;

         break ;
      case ERR_INVALID_STOPS:
         str = "Invalid stops" ;

         break ;
      case ERR_INVALID_TRADE_VOLUME:
         str = "Invalid trade volume" ;

         break ;
      case ERR_MARKET_CLOSED:
         str = "The market is closed" ;

         break ;
      case ERR_TRADE_DISABLED:
         str = "Trade is disabled" ;

         break ;
      case ERR_NOT_ENOUGH_MONEY:
         str = "Not enough money to complete operation" ;

         break ;
      case ERR_PRICE_CHANGED:
         str = "The price has changed, trying again" ;
         res = EB_NEXTTRY ;

         break ;
      case ERR_OFF_QUOTES:
         str = "The broker sent offquotes. Trying again" ;
         res = EB_NEXTTRY ;

         break ;
      case ERR_BROKER_BUSY:
         str = "The broker is budy. Waiting..." ;
         res = EB_WAITTRY ;

         break ;
      case ERR_REQUOTE:
         str = "The broker sent requote. Trying again" ;
         res = EB_WAITTRY ;

         break ;
      case ERR_ORDER_LOCKED:
         str = "The order is already processing" ;

         break ;
      case ERR_LONG_POSITIONS_ONLY_ALLOWED:
         str = "Only long positions allowed" ;

         break ;
      case ERR_TRADE_MODIFY_DENIED:
         str = "Modification is denied because the order is too close to the price" ;
         res = EB_WAITTRY ;

         break ;
      case ERR_TRADE_CONTEXT_BUSY: 
         if (_IsNotTradeContextBusy () >= 0)
         {
            res = EB_NEXTTRY ;
         }
         return (res) ;

      case ERR_TRADE_EXPIRATION_DENIED:
         str = "Expiration date usage is denied by the broker" ;

         break ;
      case ERR_TRADE_TOO_MANY_ORDERS:
         str = "Too many orders" ;

         break ;
      case ERR_TRADE_HEDGE_PROHIBITED:
         str = "Hedging is denied by broker" ;

         break ;
      case ERR_TRADE_PROHIBITED_BY_FIFO:
         str = "Cannot close a deal because FIFO order is violated" ;

         break ;
      case 4107:
         str = "Wrong price for OrderSend function" ;

         break ;      
      case 4051:
         str = "Wrong takeprofit for OrderModify function" ;
      default:

         str = "Unknown error ¹" + DoubleToStr (err, 0) ;
   }  
   str = StringConcatenate (str, " (the request is processed by broker in ", DoubleToStr (GetTickCount () - ms, 0), " ms)") ;

   Print (str) ;
   return (res) ;
}

int _IsNotTradeContextBusy()
  {

	  if(IsTradeContextBusy())
	    {
		     int StartWaitingTime = GetTickCount();
		     Print("Trade context is busy. Waiting...");

		     while(true)
		       {

			        if(GetTickCount() - StartWaitingTime > sec_wait_context * 1000)
			          {
				           Print("Waiting limit exceeded (" + sec_wait_context + " sec.)!");
				           return(-2);
			          }

			        if(!IsTradeContextBusy())
			          {

				           return(0);
			          }

			        Sleep( busysleep );
		       }
	    }
	  else
	    {

		     return(1);
	    }
  }

int MarketModify (int tick, double stop, double take)
{
   if (! OrderSelect (tick, SELECT_BY_TICKET) || OrderType () >= 2 || OrderCloseTime () > 0)
   {
      Print ("Wrong ticket for MarketModify function") ;
      return (-3) ;  
   }
   double use_sl = 0, use_tp = 0 ;

   if (stop > 0)
   {
      if (OrderType () == OP_BUY)
      {
         use_sl = OrderOpenPrice () - stop ;
      }
      else
      {
         use_sl = OrderOpenPrice () + stop ;
      }
   }
   if (stop < 0)
   {
      use_sl = -stop ;
   }
   if (take > 0)
   {
      if (OrderType () == OP_BUY)
      {
         use_tp = OrderOpenPrice () + take ;
      }
      else
      {
         use_tp = OrderOpenPrice () - take ;
      }
   }
   if (take < 0)
   {
      use_tp = -take ;
   }
   if (MathAbs (OrderStopLoss () - use_sl) < Point && MathAbs (use_tp - OrderTakeProfit ()) < Point)
   {
      Print ("There was an attempt to modify market order without changes to TP and SL") ;
      return (-3) ;
   }

   int attempt = 1 ;
   bool result = false ;

   while (attempt <= command_attempts && ! result)
   {/*
      if ((OrderType () == OP_BUY && (MarketInfo (OrderSymbol (), MODE_BID) - use_sl < d_stoplevel || use_tp - MarketInfo (OrderSymbol (), MODE_BID) < d_stoplevel)) || 
          (OrderType () == OP_SELL && (use_sl - MarketInfo (OrderSymbol (), MODE_ASK) < d_stoplevel || MarketInfo (OrderSymbol (), MODE_ASK) - use_tp < d_stoplevel)))
      {
         Print ("Couldn''t modify order ", tick, " because of broker stops level") ;
         return (-2) ;
      }
      if ((OrderType () == OP_BUY && (MarketInfo (OrderSymbol (), MODE_BID) - use_sl < d_freezelevel || use_tp - MarketInfo (OrderSymbol (), MODE_BID) < d_freezelevel)) || 
          (OrderType () == OP_SELL && (use_sl - MarketInfo (OrderSymbol (), MODE_ASK) < d_freezelevel || MarketInfo (OrderSymbol (), MODE_ASK) - use_tp < d_freezelevel)))
      {
         Print ("Couldn''t modify order ", tick, " because its level is too close to the price") ;
         return (-2) ;
      }*/

      int ms = GetTickCount () ;

      Print ("Attempt #", attempt, " to modify market order ", tick, " to stoploss ", DoubleToStr (use_sl, Digits), " and takeprofit ", DoubleToStr (use_tp, Digits)) ;
      result = OrderModify (tick, OrderOpenPrice (), use_sl, use_tp, 0) ;

      if (! result)
      {
         errors ++ ;

         int err = GetLastError () ;

         switch (ErrorBlock (err, ms))
         {
            case 0: // continue

               break ;
            case 1: // wait and continue
               Sleep (wait_error) ;

               break ;
            case 2: // terminate
               return (-1) ;
         }
      }
      else
      {
         errors = 0 ;
         Print ("Order successfully modified in ", GetTickCount () - ms, " ms") ;
      }
      if (errors > max_errors)
      {
         Print ("Exceeded maximum errors count while trying to send trading command.") ;
         Print ("To continue you should restart terminal or the EA") ; 
         return (-1) ;
      }
      attempt ++ ;

      if (attempt > command_attempts && ! result)
      {
         return (-1) ;
      }      
   }      
   return (1) ;
}

int PendingSend (int type, double lots, double price, double stop, double take, int magic_number, string comm)
{
   if (type < 2 || type > 5)
   {
      Print ("Error in type of pending order!") ;
      return (-3) ;
   }
   bool price_err = false, sltp_err = false ;

   RefreshRates () ;
   double use_sl = 0, use_tp = 0 ;

   if (stop > 0 && stop < d_stoplevel)
   {
      Print ("Stoploss for sending pending order is lesser that stops level!") ;
      return (-3) ;
   }
   if (take > 0 && take < d_stoplevel)
   {
      Print ("Takeprofit for sending pending order is lesser that stops level!") ;
      return (-3) ;
   }
   switch (type)
   {
      case OP_BUYLIMIT:
         if (Ask - price < d_stoplevel)
         {
            price_err = true ;
         }
         if (stop != 0)
         {
            if (stop > 0)
            {
               use_sl = price - stop ;
            }           
            else
            {
               use_sl = -stop ;

               if (price - use_sl < d_stoplevel)
               {
                  Print ("Stoploss for sending pending order is lesser that stops level!") ;
                  return (-3) ;
               }
            }
         }
         if (take != 0)
         {
            if (take > 0)
            {
               use_tp = price + take ;
            }           
            else
            {
               use_tp = -take ;

               if (use_tp - price < d_stoplevel)
               {
                  Print ("Takeprofit for sending pending order is lesser that stops level!") ;
                  return (-3) ;
               }
            }
         }
         break ;

      c

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

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

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

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

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

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

Стоимость полного кода
2 107,40₽ ≈ $25.76