inputint InpTakeProfitPts = 0;
inputint InpStopLossPts = 0;
//// Standard inputs//inputdouble InpOrderSize = 0.01; // Order sizeinputstring InpTradeComment = __FILE__; // Trade commentinputint InpMagicNumber = 2000001; // Magic numberdouble TakeProfit;
double StopLoss;
bool CloseOpposite;
inputint RISk=3;
inputint SSP=9;
inputdouble AtrRatio=0.375;
conststring IndicatorName="Examples\\bykov-trend-nrtr";
constint IndexAAA=0;
constint IndexBBB=1;
int Handle;
double BufferAAA[3];
double BufferBBB[3];
//// Use CTrade, easier than doing our own coding//#include <Trade\Trade.mqh>
CTrade *Trade;
intOnInit() {
//// Create a pointer to a ctrade object//
Trade = new CTrade();
Trade.SetExpertMagicNumber(InpMagicNumber);
Handle=iCustom(Symbol(),Period(),IndicatorName,RISk,SSP,AtrRatio);
if(Handle==INVALID_HANDLE)
{
PrintFormat("Failed",GetLastError());
return(INIT_FAILED);
}
return(INIT_SUCCEEDED);
}
voidOnDeinit(constint reason) {
IndicatorRelease(Handle);
}
voidOnTick() {
int cnt=CopyBuffer(Handle,IndexAAA,0,3,BufferAAA);
if (cnt<1) return;
cnt=CopyBuffer(Handle,IndexBBB,0,3,BufferBBB);
double currentAAA=BufferAAA[1];
double currentBBB=BufferBBB[1];
double priorAAA=BufferAAA[0];
double priorBBB=BufferBBB[0];
bool buyCondition=(currentAAA<currentBBB);
bool sellCondition=(currentAAA>currentBBB);
double point = SymbolInfoDouble(Symbol(), SYMBOL_POINT);
TakeProfit = InpTakeProfitPts * point;
StopLoss = InpStopLossPts * point;
CloseOpposite = false;
return;
if (buyCondition) {
if (CloseOpposite) CloseAll(POSITION_TYPE_SELL);
OrderOpen(ORDER_TYPE_BUY, StopLoss, TakeProfit);
} elseif (sellCondition) {
if (CloseOpposite) CloseAll(POSITION_TYPE_BUY);
OrderOpen(ORDER_TYPE_SELL, StopLoss, TakeProfit);
}
//// Save any information for next time//return;
}
//// true/false has the bar changed//bool NewBar() {
staticdatetime priorTime = 0;
datetime currentTime = iTime(Symbol(), Period(), 0);
bool result = (currentTime!=priorTime);
priorTime = currentTime;
return(result);
}
//// Close all trades of the specified type - for strategies that call for closing the opposite side//void CloseAll(ENUM_POSITION_TYPE positionType) {
int cnt = PositionsTotal();
for (int i = cnt-1; i>=0; i--) {
ulong ticket = PositionGetTicket(i);
if (ticket>0) {
if (PositionGetString(POSITION_SYMBOL)==Symbol() && PositionGetInteger(POSITION_MAGIC)==InpMagicNumber && PositionGetInteger(POSITION_TYPE)==positionType) {
Trade.PositionClose(ticket);
}
}
}
}
//// Simple function to open a new order//int OrderOpen(ENUM_ORDER_TYPE orderType, double stopLoss, double takeProfit) {
double openPrice;
double stopLossPrice;
double takeProfitPrice;
//// Calculate the open price, take profit and stop loss prices based on the order type// if (orderType==ORDER_TYPE_BUY) {
openPrice = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_ASK), Digits());
stopLossPrice = (stopLoss==0.0) ? 0.0 : NormalizeDouble(openPrice - stopLoss, Digits());
takeProfitPrice = (takeProfit==0.0) ? 0.0 : NormalizeDouble(openPrice + takeProfit, Digits());
} elseif (orderType==ORDER_TYPE_SELL) {
openPrice = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_BID), Digits());
stopLossPrice = (stopLoss==0.0) ? 0.0 : NormalizeDouble(openPrice + stopLoss, Digits());
takeProfitPrice = (takeProfit==0.0) ? 0.0 : NormalizeDouble(openPrice - takeProfit, Digits());
} else {
// This function only works with type buy or sellreturn(-1);
}
Trade.PositionOpen(Symbol(), orderType, InpOrderSize, openPrice, stopLossPrice, takeProfitPrice, InpTradeComment);
return((int)Trade.ResultOrder());
}
This is the indicators:
//+------------------------------------------------------------------+//| BykovTrend_NRTR.mq5 |//| Ramdass - Conversion only |//| |//+------------------------------------------------------------------+//--- авторство индикатора#property copyright"Ramdass - Conversion only"//--- ссылка на сайт автора#property link""//--- номер версии индикатора#property version"1.10"//--- отрисовка индикатора в главном окне#property indicator_chart_window//---- количество индикаторных буферов 6#property indicator_buffers6//---- использовано всего шесть графических построений#property indicator_plots6//+----------------------------------------------+//| Параметры отрисовки индикатора |//+----------------------------------------------+//---- отрисовка индикатора в виде линии#property indicator_type1DRAW_LINE//---- в качестве окраски индикатора использован#property indicator_color1clrLime//---- линия индикатора - сплошная#property indicator_style1STYLE_SOLID//---- толщина линии индикатора равна 2#property indicator_width12//---- отображение метки сигнальной линии#property indicator_label1"NRTR Line Up"//+----------------------------------------------+//| Параметры отрисовки индикатора |//+----------------------------------------------+//---- отрисовка индикатора в виде линии#property indicator_type2DRAW_LINE//---- в качестве окраски индикатора использован#property indicator_color2clrMagenta//---- линия индикатора - сплошная#property indicator_style2STYLE_SOLID//---- толщина линии индикатора равна 2#property indicator_width22//---- отображение метки сигнальной линии#property indicator_label2"NRTR Line Down"//+----------------------------------------------+//| Параметры отрисовки индикатора |//+----------------------------------------------+//---- отрисовка индикатора в виде значка#property indicator_type3DRAW_ARROW//---- в качестве окраски индикатора использован#property indicator_color3clrLimeGreen//---- линия индикатора - сплошная#property indicator_style3STYLE_SOLID//---- толщина линии индикатора равна 2#property indicator_width32//---- отображение метки сигнальной линии#property indicator_label3"NRTR Up"//+----------------------------------------------+//| Параметры отрисовки индикатора |//+----------------------------------------------+//---- отрисовка индикатора в виде значка#property indicator_type4DRAW_ARROW//---- в качестве окраски индикатора использован#property indicator_color4clrDarkViolet//---- линия индикатора - сплошная#property indicator_style4STYLE_SOLID//---- толщина линии индикатора равна 2#property indicator_width42//---- отображение метки сигнальной линии#property indicator_label4"NRTR Down"//+----------------------------------------------+//| Параметры отрисовки бычьего индикатора |//+----------------------------------------------+//---- отрисовка индикатора 5 в виде значка#property indicator_type5DRAW_ARROW//---- в качестве цвета бычей линии индикатора использован цвет голубой#property indicator_color5clrDodgerBlue//---- линия индикатора 5 - непрерывная кривая#property indicator_style5STYLE_SOLID//---- толщина линии индикатора 5 равна 5#property indicator_width55//---- отображение бычьей метки индикатора#property indicator_label5"Buy BykovTrend signal"//+----------------------------------------------+//| Параметры отрисовки медвежьего индикатора |//+----------------------------------------------+//---- отрисовка индикатора 6 в виде значка#property indicator_type6DRAW_ARROW//---- в качестве цвета медвежьей линии индикатора использован цвет глубоко-розовый#property indicator_color6clrDeepPink//---- линия индикатора 6 - непрерывная кривая#property indicator_style6STYLE_SOLID//---- толщина линии индикатора 6 равна 5#property indicator_width65//---- отображение медвежьей метки индикатора#property indicator_label6"Sell BykovTrend signal"//+----------------------------------------------+//| объявление констант |//+----------------------------------------------+#define RESET 0// Константа для возврата терминалу команды на пересчёт индикатора//+----------------------------------------------+//| Входные параметры индикатора |//+----------------------------------------------+inputint RISK=3;
inputint SSP=9;
inputdouble AtrRatio=0.375;
//+----------------------------------------------+//--- объявление динамических массивов, которые в дальнейшем будут использованы в качестве индикаторных буферовdouble UpBuffer1[],DnBuffer1[];
double UpBuffer2[],DnBuffer2[];
double SellBuffer[],BuyBuffer[];
//---int K,WPR_Handle,ATR_Handle,min_rates_total;
//+------------------------------------------------------------------+//| Custom indicator initialization function |//+------------------------------------------------------------------+intOnInit()
{
//--- инициализация глобальных переменных
K=33-RISK;
int ATR_Period=15;
min_rates_total=int(MathMax(SSP,ATR_Period))+1;
//--- получение хендла индикатора ATR
WPR_Handle=iWPR(NULL,0,SSP);
if(WPR_Handle==INVALID_HANDLE)
{
Print(" Не удалось получить хендл индикатора iWPR");
return(INIT_FAILED);
}
//--- получение хендла индикатора ATR
ATR_Handle=iATR(NULL,0,ATR_Period);
if(ATR_Handle==INVALID_HANDLE)
{
Print(" Не удалось получить хендл индикатора ATR");
return(INIT_FAILED);
}
//--- превращение динамического массива в индикаторный буферSetIndexBuffer(0,UpBuffer1,INDICATOR_DATA);
//--- осуществление сдвига начала отсчета отрисовки индикатора 1PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,min_rates_total);
//---- запрет на отрисовку индикатором пустых значенийPlotIndexSetDouble(0,PLOT_EMPTY_VALUE,NULL);
//--- индексация элементов в буфере как в таймсерииArraySetAsSeries(UpBuffer1,true);
//--- превращение динамического массива в индикаторный буферSetIndexBuffer(1,DnBuffer1,INDICATOR_DATA);
//--- осуществление сдвига начала отсчета отрисовки индикатора 2PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,min_rates_total);
//---- запрет на отрисовку индикатором пустых значенийPlotIndexSetDouble(1,PLOT_EMPTY_VALUE,NULL);
//--- индексация элементов в буфере как в таймсерииArraySetAsSeries(DnBuffer1,true);
//--- превращение динамического массива в индикаторный буферSetIndexBuffer(2,UpBuffer2,INDICATOR_DATA);
//--- осуществление сдвига начала отсчета отрисовки индикатора 3PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,min_rates_total);
//--- символ для индикатораPlotIndexSetInteger(2,PLOT_ARROW,159);
//---- запрет на отрисовку индикатором пустых значенийPlotIndexSetDouble(2,PLOT_EMPTY_VALUE,NULL);
//--- индексация элементов в буфере как в таймсерииArraySetAsSeries(UpBuffer2,true);
//--- превращение динамического массива в индикаторный буферSetIndexBuffer(3,DnBuffer2,INDICATOR_DATA);
//--- осуществление сдвига начала отсчета отрисовки индикатора 4PlotIndexSetInteger(3,PLOT_DRAW_BEGIN,min_rates_total);
//--- символ для индикатораPlotIndexSetInteger(3,PLOT_ARROW,159);
//---- запрет на отрисовку индикатором пустых значенийPlotIndexSetDouble(3,PLOT_EMPTY_VALUE,NULL);
//--- индексация элементов в буфере как в таймсерииArraySetAsSeries(DnBuffer2,true);
//--- превращение динамического массива в индикаторный буферSetIndexBuffer(4,BuyBuffer,INDICATOR_DATA);
//--- осуществление сдвига начала отсчета отрисовки индикатора 5PlotIndexSetInteger(4,PLOT_DRAW_BEGIN,min_rates_total);
//--- символ для индикатораPlotIndexSetInteger(4,PLOT_ARROW,175);
//---- запрет на отрисовку индикатором пустых значенийPlotIndexSetDouble(4,PLOT_EMPTY_VALUE,NULL);
//--- индексация элементов в буфере как в таймсерииArraySetAsSeries(BuyBuffer,true);
//--- превращение динамического массива в индикаторный буферSetIndexBuffer(5,SellBuffer,INDICATOR_DATA);
//--- осуществление сдвига начала отсчета отрисовки индикатора 6PlotIndexSetInteger(5,PLOT_DRAW_BEGIN,min_rates_total);
//--- символ для индикатораPlotIndexSetInteger(5,PLOT_ARROW,175);
//---- запрет на отрисовку индикатором пустых значенийPlotIndexSetDouble(5,PLOT_EMPTY_VALUE,NULL);
//--- индексация элементов в буфере как в таймсерииArraySetAsSeries(SellBuffer,true);
//--- Установка формата точности отображения индикатораIndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//--- имя для окон данных и метка для подокон string short_name="BykovTrend";
IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- завершение инициализацииreturn(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Custom indicator iteration function |//+------------------------------------------------------------------+intOnCalculate(constint rates_total,
constint prev_calculated,
constdatetime &time[],
constdouble &open[],
constdouble &high[],
constdouble &low[],
constdouble &close[],
constlong &tick_volume[],
constlong &volume[],
constint &spread[])
{
//--- проверка количества баров на достаточность для расчетаif(BarsCalculated(WPR_Handle)<rates_total || BarsCalculated(ATR_Handle)<rates_total || rates_total<min_rates_total)
return(RESET);
//--- объявления локальных переменных int to_copy,limit,bar,trend;
double WPR[],ATR[],range,stop;
staticint oldtrend;
//--- расчеты необходимого количества копируемых данных и стартового номера limit для цикла пересчета баровif(prev_calculated>rates_total || prev_calculated<=0)// проверка на первый старт расчета индикатора
{
limit=rates_total-min_rates_total; // стартовый номер для расчета всех баров
oldtrend=0;
}
else
{
limit=rates_total-prev_calculated; // стартовый номер для расчета новых баров
}
to_copy=limit+1; // расчетное количество копируемых баров//--- копируем вновь появившиеся данные в массивы WPR[] и ATR[]if(CopyBuffer(WPR_Handle,0,0,to_copy,WPR)<=0) return(RESET);
if(CopyBuffer(ATR_Handle,0,0,to_copy,ATR)<=0) return(RESET);
//--- индексация элементов в массивах как в таймсериях ArraySetAsSeries(WPR,true);
ArraySetAsSeries(ATR,true);
ArraySetAsSeries(high,true);
ArraySetAsSeries(low,true);
//--- основной цикл расчета индикатораfor(bar=limit; bar>=0 && !IsStopped(); bar--)
{
BuyBuffer[bar]=SellBuffer[bar]=UpBuffer1[bar]=DnBuffer1[bar]=UpBuffer2[bar]=DnBuffer2[bar]=NULL;
//---
trend=oldtrend;
if(WPR[bar]<-100+K) trend=-1;
if(WPR[bar]>-K) trend=+1;
range=AtrRatio*ATR[bar];
//---if(oldtrend<0 && trend>0) BuyBuffer[bar]=low[bar]-range;
if(oldtrend>0 && trend<0) SellBuffer[bar]=high[bar]+range;
if(trend>0)
{
if(BuyBuffer[bar])
{
UpBuffer1[bar]=UpBuffer2[bar]=BuyBuffer[bar];
DnBuffer1[bar]=DnBuffer1[bar+1];
}
else
{
stop=low[bar]-range;
if(stop<UpBuffer1[bar+1]) stop=UpBuffer1[bar+1];
UpBuffer1[bar]=UpBuffer2[bar]=stop;
}
}
if(trend<0)
{
if(SellBuffer[bar])
{
DnBuffer1[bar]=DnBuffer2[bar]=SellBuffer[bar];
UpBuffer1[bar]=UpBuffer1[bar+1];
}
else
{
stop=high[bar]+range;
if(stop>DnBuffer1[bar+1]) stop=DnBuffer1[bar+1];
DnBuffer1[bar]=DnBuffer2[bar]=stop;
}
}
//---if(bar) oldtrend=trend;
}
//--- return(rates_total);
}
//+------------------------------------------------------------------+
Can someone tell me why this EA dose not open any trades?
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
This is the indicators:
Can someone tell me why this EA dose not open any trades?
The indicator name is "bykov-trend-nrtr"
it location:
MQL5\Indicators\Examples
No errors at all!