Universal EA
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «luke's universal ea.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Universal EA — торговый советник для MetaTrader 4, основанный на сигналах пользовательского индикатора. Советник считывает значения буферов индикатора для определения направления входа в позицию и автоматически открывает сделки на покупку или продажу.
Программа поддерживает два режима управления позициями: корзинный (Basket), при котором все позиции закрываются по общим параметрам, и индивидуальный (Individual), при котором каждая позиция управляется отдельно. Доступны настройки тейк-профита, стоп-лосса, трейлинга и безубыточности, выраженные в долларах.
Советник также предоставляет функции закрытия позиций по противоположному сигналу, принудительного закрытия пар сделок по заданному уровню и отображения информации о текущем уровне трейлинга на графике. Магический номер позволяет идентифицировать управляемые позиции.
Настройки программы
| Настройка | Описание |
|---|---|
| _I_ | Заголовок настроек — Текстовый параметр-заголовок для визуальной группировки настроек в интерфейсе советника. |
| TP Mode (TP_Mode) | Режим тейк-профита — Режим управления позициями: корзинный (Basket) — все позиции закрываются по общим параметрам, или индивидуальный (Individual) — каждая позиция управляется отдельно. |
| Lot Size (Lot_Size) | Размер лота — Размер лота для открытия каждой позиции. |
| TP ( IN $ ) (TP_money) | Тейк-профит (в $) — Тейк-профит в долларах для каждой позиции или корзины. |
| SL ( IN $ ) (SL_money) | Стоп-лосс (в $) — Стоп-лосс в долларах для каждой позиции или корзины. |
| Trail TP ( IN $ ) (Trail_TP) | Начало трейлинга (в $) — Уровень прибыли в долларах, при достижении которого активируется трейлинг. |
| Trail Step ( IN $ ) (Trail_Step) | Шаг трейлинга (в $) — Шаг трейлинга в долларах — величина отката, при которой позиции закрываются после активации трейлинга. |
| Break Even ( IN $ ) (Break_Even) | Безубыточность (в $) — Уровень безубыточности в долларах, при достижении которого позиции переводятся в режим безубыточности. |
| Custom Indicator Name (Custom_Ind_Name) | Имя пользовательского индикатора — Имя пользовательского индикатора, из которого советник получает торговые сигналы. |
| Buy Buffer NO (Buy_Buffer_NO) | Буфер покупки — Номер буфера пользовательского индикатора, соответствующий сигналу на покупку. |
| Sell Buffer NO (Sell_Buffer_NO) | Буфер продажи — Номер буфера пользовательского индикатора, соответствующий сигналу на продажу. |
| 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) | Стиль закрытия — Стиль закрытия пар позиций: безубыточность (BE) или прибыль (Profit). |
| Magic Number (Magic) | Магический номер — Магический номер для идентификации позиций, управляемых данным советником. |
Поиск по коду файла
/*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 = 100.0; // TP ( IN $ )
input double SL_money = 100.0; // SL ( IN $ )
input double Trail_TP = 250.0; // Trail TP ( IN $ )
input double Trail_Step = 50.0; // Trail Step ( IN $ )
input double Break_Even = 100.0; // Break Even ( IN $ )
input string Custom_Ind_Name = "X"; // Custom Indicator Name
input int Buy_Buffer_NO = 0; // Buy Buffer NO
input int Sell_Buffer_NO = 1; // Sell Buffer NO
input bool UseBreakEven = false; // Use Break Even
input bool UseTrailingStop = false; // 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 = 777; // Magic Number
/*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, 1 ); if( i_val > 0.0 && i_val != EMPTY_VALUE ) return( 1 );
i_val = i_custom( Sell_Buffer_NO, 1 ); 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();
}
}
void Check_SL_TP()
{
int
i = 0;
color
c = clrNONE;
double
sl = 0.0, tp = 0.0, sl_lev = 0.0, tp_lev = 0.0, comm_and_swap = 0.0, comm_swapПоказано первые 50% кода (символов: 25176)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.