Highlighted...if <0, then the lot of the losing trade is increased
if >0, then the lot of a profit trade is increased
Hi.
I have another question about your EA
when testing it on a demo account, the following happened:
When the EA reaches the specified parameters, it has shifted to the "stop" mode, i.e., the "start" button is lit, but trading has not stopped and trades are very short, literally one or two cents. Is this the way it should be?
I have also found out that the EA has closed some deals not at take or stop price and not at the money limit, but "for nothing" and the price has passed various amount of points before it was closed. At the same time, the Expert Advisor completely covers the previous losses, by a couple of cents, (for example, three deals in a row have (-15.59 $) a profitable deal = +15.62 $ and closed it immediately!)
when testing it on a demo, the following happened:
When the EA reaches the preset parameters, it switches to the "stop" mode, i.e. the "start" button is on, but the trading is not stopped, but very short trades are opened, just one or two cents. Is this the way it should be?
I have also found out that the EA has closed some deals not at take or stop price and not at the money limit, but "for nothing" and the price has passed various amount of points before it was closed. At the same time, the Expert Advisor completely covers the previous losses, by a couple of cents, (for example, three deals in a row have (-15.59 $) a profitable deal = +15.62 $ and closed it immediately!)
looked at the logs, no errors anywhere...
Please send us the code with your fixes. We will see.
Please advise which function and where to add to this simple EA,
In addition to existing ways to reset a lot to the initial one,
If you want to close the current position when a drawdown of the current position is reached, specified in the deposit currency, and then, when you open the next one, to reset the lot to the starting one?
//+-----------------------------------------------------------------------------------------------+//| Simple Moving Average.mq4 |//| Copyright 2016, Andrey Minaev |//| https://www.mql5.com/ru/users/id.scorpion |//+-----------------------------------------------------------------------------------------------+#property copyright"Copyright 2016, Andrey Minaev"#property link"https://www.mql5.com/ru/users/id.scorpion"#property version"1.00"#property strict// Параметры советникаexternstring sParametersEA = ""; // Параметры советникаexterndouble dLots = 0.01; // Количество лотовexternint iStopLoss = 30; // Уровень убытка (в пунктах)externint iTakeProfit = 30; // Уровень прибыли (в пунктах)externint iSlippage = 3; // Проскальзование (в пунктах)externint iMagic = 1; // Индентификатор советникаexterndouble K_Martin = 2.0;
externint OrdersClose = 5;
externint DigitsLot = 2;
// Параметры индикатораexternstring sParametersMA = ""; // Параметры индикатораexternint iPeriodMA = 14; // Период усреднения// Глобальные переменныеdouble dMA;
//+-----------------------------------------------------------------------------------------------+intOnInit()
{
// Если брокер использует 3 или 5 знаков после запятой, то умножаем на 10if(Digits == 3 || Digits == 5)
{
iStopLoss *= 10;
iTakeProfit *= 10;
iSlippage *= 10;
}
return(INIT_SUCCEEDED);
}
//+-----------------------------------------------------------------------------------------------+voidOnDeinit(constint reason)
{
}
//+-----------------------------------------------------------------------------------------------+voidOnTick()
{
// Получим значение индикатора
dMA = iMA(Symbol(), 0, iPeriodMA, 0, MODE_SMA, PRICE_CLOSE, 0);
// Если нет открытых ордеров, то входим в условиеif(bCheckOrders() == true)
{
// Если появился сигнал на покупку, то откроем ордер на покупкуif(bSignalBuy() == true)
vOrderOpenBuy();
// Если появился сигнал на продажу, то откроем ордер на продажуif(bSignalSell() == true)
vOrderOpenSell();
}
}
//+-----------------------------------------------------------------------------------------------+//| Функция проверки открытых оредров |//+-----------------------------------------------------------------------------------------------+bool bCheckOrders()
{
// Переберем в цикле ордера, для проверки открытых ордеров данным советникомfor(int i = 0; i <= OrdersTotal(); i++)
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
if(OrderSymbol() == Symbol() && OrderMagicNumber() == iMagic)
return(false);
return(true);
}
//+-----------------------------------------------------------------------------------------------+//| Функция поиска сигнала на покупку |//+-----------------------------------------------------------------------------------------------+bool bSignalBuy()
{
if(dMA > Open[1] && dMA < Close[1])
return(true);
return(false);
}
//+-----------------------------------------------------------------------------------------------+//| Функция поиска сигнала на продажу |//+-----------------------------------------------------------------------------------------------+bool bSignalSell()
{
if(dMA < Open[1] && dMA > Close[1])
return(true);
return(false);
}
//+-----------------------------------------------------------------------------------------------+//| Функция открытия ордера на покупку |//+-----------------------------------------------------------------------------------------------+void vOrderOpenBuy()
{
int iOTi = 0; // Тикет ордера
iOTi = OrderSend(Symbol(), OP_BUY, LOT(), Ask, iSlippage, 0, 0, "", iMagic, 0, clrNONE);
// Проверим открылся ли ордерif(iOTi > 0)
// Есди да, то выставим уровни убытка и прибыли
vOrderModify(iOTi);
else// Если нет, то получим ошибку
vError(GetLastError());
}
//+-----------------------------------------------------------------------------------------------+//| Функция открытия ордера на продажу |//+-----------------------------------------------------------------------------------------------+void vOrderOpenSell()
{
int iOTi = 0; // Тикет ордера
iOTi = OrderSend(Symbol(), OP_SELL, LOT(), Bid, iSlippage, 0, 0, "", iMagic, 0, clrNONE);
// Проверим открылся ли ордерif(iOTi > 0)
// Есди да, то выставим уровни убытка и прибыли
vOrderModify(iOTi);
else// Если нет, то получим ошибку
vError(GetLastError());
}
//+-----------------------------------------------------------------------------------------------+//| Функция модификации ордера |//+-----------------------------------------------------------------------------------------------+void vOrderModify(int iOTi)
{
int iOTy = -1; // Тип ордераdouble dOOP = 0; // Цена открытия ордераdouble dOSL = 0; // Стоп Лоссint iMag = 0; // Идентификатор советникаdouble dSL = 0; // Уровень убыткаdouble dTP = 0; // Уровень прибыли// Выберем по тикету открытый ордер, получим некоторые значенияif(OrderSelect(iOTi, SELECT_BY_TICKET, MODE_TRADES))
{
iOTy = OrderType();
dOOP = OrderOpenPrice();
dOSL = OrderStopLoss();
iMag = OrderMagicNumber();
}
// Если ордер открыл данный советник, то входим в условиеif(OrderSymbol() == Symbol() && OrderMagicNumber() == iMag)
{
// Если Стоп Лосс текущего ордера равен нулю, то модифицируем ордерif(dOSL == 0)
{
if(iOTy == OP_BUY)
{
dSL = NormalizeDouble(dOOP - iStopLoss * Point, Digits);
dTP = NormalizeDouble(dOOP + iTakeProfit * Point, Digits);
bool bOM = OrderModify(iOTi, dOOP, dSL, dTP, 0, clrNONE);
}
if(iOTy == OP_SELL)
{
dSL = NormalizeDouble(dOOP + iStopLoss * Point, Digits);
dTP = NormalizeDouble(dOOP - iTakeProfit * Point, Digits);
bool bOM = OrderModify(iOTi, dOOP, dSL, dTP, 0, clrNONE);
}
}
}
}
//+-----------------------------------------------------------------------------------------------+//| Функция обработки ошибок |//+-----------------------------------------------------------------------------------------------+void vError(int iErr)
{
switch(iErr)
{
case129: // Неправильная ценаcase135: // Цена измениласьcase136: // Нет ценcase138: // Новые ценыSleep(1000);
RefreshRates();
break;
case137: // Брокер занятcase146: // Подсистема торговли занятаSleep(3000);
RefreshRates();
break;
}
}
//+-----------------------------------------------------------------------------------------------+double LOT()
{
int n=0;
double OL=dLots;
for (int j = OrdersHistoryTotal()-1; j >= 0; j--)
{
if (OrderSelect(j, SELECT_BY_POS,MODE_HISTORY))
{
if (OrderSymbol() == Symbol() && OrderMagicNumber() == iMagic)
{
if (OrderProfit()<0)
{
if (n==0) OL=NormalizeDouble(OrderLots()*K_Martin,DigitsLot);
n++;
if (n>=OrdersClose) {Comment("1");return(dLots);}
}
else
{
if (n==0) {Comment("2");return(dLots);}
else {Comment("3");return(OL);}
}
}
}
}
return(OL);
}
//------------------------------------------------------------------
Thanks for the tip people , I did it this way, it says when it goes to stop loss or take profit
//--- get transaction type as enumeration valueENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is result of addition of the transaction in historyif(type==TRADE_TRANSACTION_DEAL_ADD)
{
long deal_entry =0;
double deal_profit =0.0;
double deal_volume =0.0;
string deal_symbol ="";
long deal_magic =0;
long deal_reason =-1;
if(HistoryDealSelect(trans.deal))
{
deal_entry=HistoryDealGetInteger(trans.deal,DEAL_ENTRY);
deal_profit=HistoryDealGetDouble(trans.deal,DEAL_PROFIT);
deal_volume=HistoryDealGetDouble(trans.deal,DEAL_VOLUME);
deal_symbol=HistoryDealGetString(trans.deal,DEAL_SYMBOL);
deal_magic=HistoryDealGetInteger(trans.deal,DEAL_MAGIC);
deal_reason=HistoryDealGetInteger(trans.deal,DEAL_REASON);
}
elsereturn;
if(deal_symbol==m_symbol.Name() && deal_magic==m_magic)
if(deal_entry==DEAL_ENTRY_OUT)
{
if(deal_reason==DEAL_REASON_SL)
SendNotification (" Закрыл позицию > StopLoss");
if(deal_reason==DEAL_REASON_TP)
SendNotification ("Закрыл позицию > TakeProfit");
}
}
}
and so on a new buy or sell
void OPENORDER(string ord)
{
double priceL=m_symbol.Ask();
if(ord=="Sell")
SendNotification (" открыл позицию > short");//--- check for free moneyif(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_BUY,my_lot,priceL)<0.0)
printf("We have no money. Free Margin = %f",m_account.FreeMargin());
elseif(!m_trade.Sell(my_lot,Symbol(),m_symbol.Bid(),my_SL,my_TP,""))
Print("BUY_STOP -> false. Result Retcode: ",m_trade.ResultRetcode(),
", description of Retcode: ",m_trade.ResultRetcodeDescription(),
", ticket of order: ",m_trade.ResultOrder()); // Если sell, то не открываемсяdouble priceS=m_symbol.Bid();
if(ord=="Buy")
SendNotification (" открыл позицию > long");//--- check for free moneyif(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_SELL,my_lot,priceS)<0.0)
printf("We have no money. Free Margin = %f",m_account.FreeMargin());
elseif(!m_trade.Buy(my_lot,Symbol(),m_symbol.Ask(),my_SL,my_TP,""))
Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
", description of result: ",m_trade.ResultRetcodeDescription(),
", ticket of deal: ",m_trade.ResultDeal());
I need to make an EA based on an indicator, so that the EA can work without the presence of an indicator. Is it possible to make the data of an indicator inscribed in it appear on the chart, so that these lines do not become objects?
I need to make an EA based on an indicator, so the EA can work without the indicator. Is it possible to display the data of the indicator written in it on the chart, so as not to make these lines as objects?
Highlighted...if <0, then the lot of the losing trade is increased
if >0, then the lot of a profit trade is increased
Hi.
I have another question about your EA
when testing it on a demo account, the following happened:
When the EA reaches the specified parameters, it has shifted to the "stop" mode, i.e., the "start" button is lit, but trading has not stopped and trades are very short, literally one or two cents. Is this the way it should be?
I have also found out that the EA has closed some deals not at take or stop price and not at the money limit, but "for nothing" and the price has passed various amount of points before it was closed. At the same time, the Expert Advisor completely covers the previous losses, by a couple of cents, (for example, three deals in a row have (-15.59 $) a profitable deal = +15.62 $ and closed it immediately!)
looked at the logs, no errors anywhere...
Hello.
I have another question about your Expert Advisor
when testing it on a demo, the following happened:
When the EA reaches the preset parameters, it switches to the "stop" mode, i.e. the "start" button is on, but the trading is not stopped, but very short trades are opened, just one or two cents. Is this the way it should be?
I have also found out that the EA has closed some deals not at take or stop price and not at the money limit, but "for nothing" and the price has passed various amount of points before it was closed. At the same time, the Expert Advisor completely covers the previous losses, by a couple of cents, (for example, three deals in a row have (-15.59 $) a profitable deal = +15.62 $ and closed it immediately!)
looked at the logs, no errors anywhere...
Please send us the code with your fixes. We will see.
Post your code with your fixes. We will see.
so I'm still testing the uncorrected one, your native one.
so I'm still testing the uncorrected one, your native one.
I don't see any errors...
Write what period, on what pair and what parameters were there when the errors occurred.
I don't see any errors...
write what period, on what pair and what parameters were present when the errors occurred.
these settings:
timeframe_RSI=0 period_RSI=14 level_buy=30 level_sell=70 Lot=0.01 K_Martin=1.6 Stoploss=200 Takeprofit=1000 CountLoss=100.0 CountProfit=25.0 Magic=777 DigitsLot=2 slippage=3
report is attached below.
there yellow lines with "unclear" closing, neither by stop, take profit, nor by money.
and blue - trades that were opened and closed almost immediately
Hello!
Please advise which function and where to add to this simple EA,
In addition to existing ways to reset a lot to the initial one,
If you want to close the current position when a drawdown of the current position is reached, specified in the deposit currency, and then, when you open the next one, to reset the lot to the starting one?
here are the settings:
timeframe_RSI=0 period_RSI=14 level_buy=30 level_sell=70 Lot=0.01 K_Martin=1.6 Stoploss=200 Takeprofit=1000 CountLoss=100.0 CountProfit=25.0 Magic=777 DigitsLot=2 slippage=3
report is attached below.
there yellow lines with "unclear" closing, neither by stop ,take, nor by money.
And blue lines represent deals that were opened and closed almost immediately.
On what timeframe?
and so on a new buy or sell
Greetings. Please advise on mt5.
I need to make an EA based on an indicator, so that the EA can work without the presence of an indicator.
Is it possible to make the data of an indicator inscribed in it appear on the chart, so that these lines do not become objects?
Greetings. Please advise me on mt5.
I need to make an EA based on an indicator, so the EA can work without the indicator.
Is it possible to display the data of the indicator written in it on the chart, so as not to make these lines as objects?
ChartIndicatorAdd()