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

luke's universal ea.v2_powerlevel@lifeindreamsworld.mq4

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

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

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

О программе

Советник для MetaTrader 4, предназначенный для автоматической торговли на основе сигналов пользовательского индикатора. Сигналы формируются по значениям в буферах индикатора (buy и sell буферы) на заданной свече. Поддерживает два режима управления сделками: корзинный (все сделки закрываются по общим условиям) и индивидуальный (каждая сделка управляется отдельно).

Советник открывает рыночные ордера OP_BUY и OP_SELL через стандартный API OrderSend с контролем свободного маржи. При открытии позиции рассчитываются уровни стоп-лосса и тейк-профита в долларовой оценке с учётом комиссии и спреда. Реализована проверка максимального количества одновременно открытых сделок.

Предусмотрены функции трейлинг-стопа, перевода в безубыточность и принудительного закрытия пары сделок при достижении заданного уровня. Закрытие пары может выполняться по двум стилям: выбор двух сделок (buy и sell) с суммарным результатом, ближайшим к безубыточности, или с максимальной прибылью. Также реализовано закрытие противоположной позиции при получении нового сигнала.

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

НастройкаОписание
_I_ Разделитель — Текстовый разделитель группы входных параметров
TP Mode (TP_Mode) Режим тейк-профита — Режим управления сделками: корзинный или индивидуальный
Lot Size (Lot_Size) Размер лота — Размер лота для каждой сделки
TP ( IN $ ) (TP_money) Тейк-профит в $ — Уровень тейк-профита в долларовой оценке
SL ( IN $ ) (SL_money) Стоп-лосс в $ — Уровень стоп-лосса в долларовой оценке
Trail TP ( IN $ ) (Trail_TP) Трейлинг TP в $ — Уровень прибыли для начала трейлинга в долларах
Trail Step ( IN $ ) (Trail_Step) Шаг трейлинга в $ — Шаг трейлинга в долларах
Max. number of open trades (Max_Trades) Макс. сделок — Максимальное количество одновременно открытых сделок
Break Even ( IN $ ) (Break_Even) Безубыточность в $ — Уровень безубыточности в долларах
Custom Indicator Name (Custom_Ind_Name) Имя индикатора — Имя пользовательского индикатора-источника сигналов
Buy Buffer NO (Buy_Buffer_NO) Номер buy-буфера — Номер буфера buy-сигнала индикатора
Sell Buffer NO (Sell_Buffer_NO) Номер sell-буфера — Номер буфера sell-сигнала индикатора
Candle for signal (Candle_ID) Номер свечи — Номер свечи для формирования сигнала
Use Break Even (UseBreakEven) Безубыточность — Включает или выключает функцию перевода в безубыточность
Use Trailing Stop (UseTrailingStop) Трейлинг-стоп — Включает или выключает функцию трейлинг-стопа
Use Close On Opposite Signal (UseCloseOnOppSign) Закрытие на противоположный сигнал — Включает или выключает закрытие позиции при получении противоположного сигнала
Use Close Out (UseCloseOut) Принудительное закрытие пары — Включает или выключает функцию закрытия пары сделок при достижении уровня
Close Out Trades Level (CloseOutTradesLevel) Уровень закрытия пары — Количество сделок, при достижении которого запускается закрытие пары
Close Out Style (CloseOutStyle) Стиль закрытия пары — Стиль выбора пары для закрытия: по безубыточности или по максимальной прибыли
Magic Number (Magic) Магический номер — Магический номер для идентификации ордеров советника
Trade Comments (Comments) Комментарий — Комментарий, добавляемый к каждой сделке
Slippage Проскальзывание — Допустимое проскальзывание в пунктах
Получить полный код

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

/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx specification xxx//
   UNIVERSAL EA

   This EA is to be based on buying /selling via buffers. 
   This is based on the calling of a custom signal indicator. 
   Here are the INPUTS below and I will give a description of how each INPUT works. Please see below. 
   Source code needs to be provided on completion of project.

   EA INPUTS

   Variable                Value

   TP Mode                 Basket/Individual
   Lot Size                0.01
   TP (IN $)               100
   SL (IN $)               100
   Trail TP (IN $)         250
   Trail Step (IN $)       50
   Break Even (IN $)       100
   Custom Indicator Name   X
   Buy Buffer NO           0
   Sell Buffer NO          1
   Use Break Even          True/False
   Use Trailing Stop       True/False
   Use Close Out           True/false
   Close Out Trades Level  200
   Close Out Style         Break Even/Profit
   Magic Number            777

   TP Mode.
   BASKET means for ALL trades to close out based on the TP/SL- OR Trail SL OR Break Even... 
   Basically its basket and everything closes based on the INPUTS. These figures are based on $, not pips

   INDIVIDUAL means that ALL trades are closed out based on Individual circumstances of TP/SL/ Trail/ Breakeven etc etc. 
   These figures are based on $, not pips

   LOT Size.
   This is standard and needs for no explanation.

   TP (IN $)
   This means that all trades either in basket or individual will close out based on this $ amount. Simple

   SL (IN $)
   This means that all trades either in basket or individual will close out based on this $ amount. Simple

   Trail TP (IN $)
   This means that at this point of $ then the Trail of price will commence and will only be closed out be the Trail Step. 
   This is for basket or Individual.

   Trail Step (IN $)
   This means that when price in the Trail TP is reached. As price goes up or down, the Trail Step will close out trades based on this Step. 
   Example is.

   Trail TP is set to $350,
   Trail Step is set to $50,
   Profit in trades is at $350,
   Profit in trades falls back to $300.
   Trades close out.
   As profit rises then the step is rising with the profit at the same step level as the INPUT. SIMPLE. 
   This is seen as trailing the high water mark.

   Break Even (IN $)
   This means that either basket or individual will close out at this level.

   Custom Indicator Name
   This is where the custom indicator will go for this EA to call from the folder.

   Buy Buffer
   This is the number for the buffer for buying

   Sell Buffer
   This is the number for the buffer for selling

   Use Break Even
   This means the option to use break even feature or not

   Use Trailing Stop
   This means the option to use trailing stop feature or not

   Use Close Out
   This means the option to close out feature or not

   Close Out Trades Level
   This means for the trades to be closed out at this level based on the “Close Out Trades Style” INPUT.
   I have added this feature because most brokers only allow a set amount of trades or pending orders. 
   So in this case the trades will close out ONLY 2 at a time based on the STYLE INPUT BELOW. 
   Obviously, trades will continue to be taken based on the entry criteria and in this case the trades will continue to close at this level as well. 
   In this case we will have trades closing at this level and trades also being entered based on the entry criteria 
   and trades also being closed out based on all the other INPUTS of TP/SL/Trailing/or Breakeven- based on basket or individual.

   Close Out Trades Level
   This is the level at which the 2 trades to close out will commence. This might be ranging from 10 to 500. 
   Depending on broker and system I use this for. Point to make is that 2 trades close out at the same time based on the “CLOSE OUT STYLE” INPUT

   Close out Trades Style
   This is the STYLE in which the 2 trades will close out when the “CLOSE OUT TRADES LEVEL” is reached.

   Break Even. This means that the 2 trades to close should be the 2 trades closest to receiving a Break Even result. MUST BE A BUY AND SELL TRADE.  
   So a positive trade of $ 1.95 should be paired with the closest trade to receive a Break Even result. 
   This could be a negative trade of -$1.45. Either way the object is clear, the result to gain is that the 2 trades to close 
   give the closest to break even as possible.

   Profit. This means the same as above INPUT yet the 2 trades to close out give the biggest profit. MUST BE A BUY AND SELL TRADE. Simple. 
   Best 2 trades at the time of closing to give biggest PROFIT.

   Magic Number
   This is obvious.

#property strict

enum ENUM_TP_MODE { Basket = 0, Individual = 1 }; 
enum ENUM_CLOSE_OUT_STYLE { BE = 0/*Break_Even*/, Profit = 1 };

input string               _I_                 = "___ EA INPUTS ___";       //
input ENUM_TP_MODE         TP_Mode             = Individual;                // TP Mode
input double               Lot_Size            = 0.01;                      // Lot Size
input double               TP_money            = 50.0;                      // TP ( IN $ )
input double               SL_money            = 20.0;                      // SL ( IN $ )
input double               Trail_TP            = 1.0;                       // Trail TP ( IN $ )
input double               Trail_Step          = 1.0;                       // Trail Step ( IN $ )
input int                  Max_Trades          = 3;                         // Max. number of open trades
input double               Break_Even          = 100.0;                     // Break Even ( IN $ )
input string               Custom_Ind_Name     = "PowerLevel 2-3-4 Indicator"; // Custom Indicator Name
input int                  Buy_Buffer_NO       = 10;                        // Buy Buffer NO
input int                  Sell_Buffer_NO      = 11;                        // Sell Buffer NO
input int                  Candle_ID           = 0;                         // Candle for signal
input bool                 UseBreakEven        = false;                     // Use Break Even
input bool                 UseTrailingStop     = true;                     // Use Trailing Stop
input bool                 UseCloseOnOppSign   = false;                     // Use Close On Opposite Signal
input bool                 UseCloseOut         = false;                     // Use Close Out
input int                  CloseOutTradesLevel = 200;                       // Close Out Trades Level
input ENUM_CLOSE_OUT_STYLE CloseOutStyle       = BE;                        // Close Out Style
input int                  Magic               = 160723;                       // Magic Number
input string               Comments            = "";                        // Trade Comments
input int                  Slippage            = 10;                        // 
/*input*/ ENUM_TIMEFRAMES  Tf                  = PERIOD_CURRENT;            // 

datetime
timePrev;
double 
SL,TP,MaxProfitTrail,
TickSize,TickValue,Spread,StopLevel,MinLot,MaxLot,LotStep,Pnt;
int 
order_type,T,nT,T_CloseOut, 
nBO,nSO,nBS,nSS,nBL,nSL,nO,nS,nL,_nBO,_nSO,_nBS,_nSS,_nBL,_nSL,_nO,_nS,_nL,Slip;
bool 
IsProfitBE, CloseContinue,
Ans,_Ans,Activate,FatalError,FreeMarginAlert,IsModify,IsTester,IsVisual;
int
tickets[];

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

void OnDeinit( const int reason )
{
   Comment( "" );

   if( !IsTester )
   { 
      if( reason==0 || reason==1 )
      {
         GVD("MaxProfitTrail"); GVD("CloseContinue"); GVD("T_CloseOut"); GVD("IsProfitBE");

         if( ObjectFind( 0, "TSL_lev" ) >= 0 ) {  ObjectDelete( 0, "TSL_lev" );  ChartRedraw();  }

         ArrayFree( tickets );
      } 
   }

}

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

void Trade()
{
   int sign = GetSign();

   if( sign == 1 ) order_type = OP_BUY; else if( sign == -1 ) order_type = OP_SELL; else return;

      if( UseCloseOnOppSign )
      {
         getTickets(); _numbOrders();

         if(  ( sign == 1 && nSO > 0 )  ||  ( sign == -1 && nBO > 0 )  )
         {
            if(  ! ClosePos( sign == 1  ?  OP_SELL  :  OP_BUY )  )   return;
         }
      }

         if( MO( order_type, Lot_Size ) == -1 ) return;

            timePrev = iTime( _Symbol, Tf, 0 );

            if(  TP_Mode == Individual  &&  ( SL_money > 0.0 || TP_money > 0.0 )  )
             if(  tickValue() > 0.0  &&  tickSize() > 0.0  &&  point() > 0.0  )
             {
                double comm = fabs( commission( T ) );

                if( SL_money > 0.0 ) SL = ( SL_money - comm ) / ( tickValue() * Lot_Size ) * ( tickSize() / point() )/* + 1.0*/; else SL = 0.0;

                if( TP_money > 0.0 ) TP = ( TP_money + comm ) / ( tickValue() * Lot_Size ) * ( tickSize() / point() )/* + 1.0*/; else TP = 0.0;

                ModifyByTicket( T );
             }
}

int GetSign()
{
   if( timePrev == iTime( _Symbol, Tf, 0 ) ) return( 0 );

   double i_val = 0.0;

   i_val = i_custom( Buy_Buffer_NO,  Candle_ID );  if(  i_val > 0.0  &&  i_val != EMPTY_VALUE  ) return(  1 );

   i_val = i_custom( Sell_Buffer_NO, Candle_ID );  if(  i_val > 0.0  &&  i_val != EMPTY_VALUE  ) return( -1 );

   timePrev = iTime( _Symbol, Tf, 0 );
   return( 0 );
}

double i_custom( int buf, int bar ) { return(  iCustom( _Symbol, Tf, Custom_Ind_Name, buf, bar )  ); }

void CloseOut()
{
   if( nO < CloseOutTradesLevel || nBO <= 0 || nSO <= 0 ) return;

   int 
   i = 0, j = 0, t_buy = -1, t_sell = -1;
   double 
   pf = 0.0, pf_buy = 0.0, pf_sell = 0.0;

   if( CloseOutStyle == BE )
   {
      for( i = 0; i < nT; i++ )
      {
         if( ! OrderSelect( tickets[ i ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() != OP_BUY ) continue;

            pf_buy = ( OrderProfit() + OrderCommission() + OrderSwap() );

            for( j = 0; j < nT; j++ )
            {
               if( ! OrderSelect( tickets[ j ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() != OP_SELL ) continue;

                  pf_sell = ( OrderProfit() + OrderCommission() + OrderSwap() ); 

                  if( pf == 0 || fabs( pf_buy + pf_sell ) < pf )
                  {
                     pf = fabs( pf_buy + pf_sell );
                     t_buy  = tickets[ i ];
                     t_sell = tickets[ j ];
                  }
            }//for
      }//for
   }

   else
   if( CloseOutStyle == Profit )
   {
      for( i = 0; i < nT; i++ )
      {
         if( ! OrderSelect( tickets[ i ], SELECT_BY_TICKET ) || OrderCloseTime() > 0 || OrderType() > 1 ) continue;

            pf = ( OrderProfit() + OrderCommission() + OrderSwap() );

            if( OrderType() == OP_BUY && ( pf_buy == 0.0 || pf > pf_buy ) )
            {
               pf_buy = pf;
               t_buy = tickets[ i ];
            }

            else
            if( OrderType() == OP_SELL && ( pf_sell == 0.0 || pf > pf_sell ) )
            {
               pf_sell = pf;
               t_sell = tickets[ i ];
            }
      }
   }

   if( t_buy != -1 && t_sell != -1 )
   {
      if( CloseByTicket( t_buy ) )
      {
         if( CloseByTicket( t_sell ) ) 
         {
            if( T_CloseOut != -1 ) T_CloseOut = -1;
         }
         else
            T_CloseOut = t_sell;

         if( !IsTester ) { GVS( "T_CloseOut", (double) T_CloseOut ); GlobalVariablesFlush(); }

         getTickets();
         _numbOrders();
      }
   }

}

void Check_SL_TP_basket()
{
   double curr_result = GetCurrResultBasket();

   if(  ( SL_money != 0.0 && curr_result <= -fabs( SL_money ) )  ||  (  TP_money > 0.0 && curr_result >= TP_money )  )
   {
      CloseContinue = true;  if( ClosePos() ) CloseContinue = false;

      if( !IsTester ) { GVS( "CloseContinue", (double) CloseContinue ); GlobalVariablesFlush(); }

      getTickets();
      _numbOrders();

   }
}

void Breakeven_basket()
{ 
   if( !IsTester ) IsProfitBE = (bool)GVG( "IsProfitBE" ); 

   if( !IsProfitBE && GetCurrResultBasket() >= Break_Even ) 
   { 
      IsProfitBE = true;
      if( !IsTester ) { GVS( "IsProfitBE", (double) IsProfitBE ); GlobalVariablesFlush(); }  
   }

   else
   if( IsProfitBE )
   {
      double money_lev_be = 0.0, lots_diff = CurrLotsDiffBuySell_basket();

      if( lots_diff > 0.0 && tickValue() > 0.0 ) money_lev_be = tickValue() * lots_diff;

      if( GetCurrResultBasket() <= money_lev_be )
      {
         CloseContinue = true;  if( ClosePos() ) CloseContinue = false;

         if( !CloseContinue )
         {
            IsProfitBE = false;
            if( !IsTester ) { GVS( "IsProfitBE", (double) IsProfitBE ); GlobalVariablesFlush(); }  
         }

         if( !IsTester ) { GVS( "CloseContinue", (double) CloseContinue ); GlobalVariablesFlush(); }

         getTickets();
         _numbOrders();
      }
   }

}

void Trail_basket()
{
   if( !IsTester ) MaxProfitTrail = GVG( "MaxProfitTrail" ); 

   double curr_result_basket = GetCurrResultBasket();

   if( MaxProfitTrail <= 0.0 && curr_result_basket >= Trail_TP )
   {
      MaxProfitTrail = curr_result_basket;
      if( !IsTester ) { GVS( "MaxProfitTrail", MaxProfitTrail ); GlobalVariablesFlush(); }
   }

   else
   if( MaxProfitTrail > 0.0 && curr_result_basket > MaxProfitTrail )
   {
      MaxProfitTrail = curr_result_basket;
      if( !IsTester ) { GVS( "MaxProfitTrail", MaxProfitTrail ); GlobalVariablesFlush(); }
   }

   else
   if( MaxProfitTrail > 0.0 && curr_result_basket <= MaxProfitTrail - Trail_Step )
   {
      CloseContinue = true;  if( ClosePos() ) CloseContinue = false;

      if( !CloseContinue )
      {
         MaxProfitTrail = 0.0;
         if( !IsTester ) { GVS( "MaxProfitTrail", MaxProfitTrail ); GlobalVariablesFlush(); }  
      }

      if( !IsTester ) { GVS( "CloseContinue", (double) CloseContinue ); GlobalVariablesFlush(); }

      getTickets();
      _numbOrders

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

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

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

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

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

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

Стоимость полного кода
2 535₽ ≈ $30.98