int digits = (int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS); // number of decimal placesdouble point = SymbolInfoDouble(_Symbol,SYMBOL_POINT); // pointdouble ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK); // current price for closing SHORTdouble SL = ask-_SL*point; // unnormalized SL value
SL = NormalizeDouble(SL,digits); // normalizing Stop Lossdouble TP = ask+_TP*point; // unnormalized TP value
TP = NormalizeDouble(TP,digits); // normalizing Take Profitdouble open_price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
if(!trade.Buy(Volume,_Symbol,open_price,SL,TP,""))
{
//--- failure messagePrint("Sell() method failed. Return code=",trade.ResultRetcode(),
". Code description: ",trade.ResultRetcodeDescription());
return (false);
}
else
{
Print("Sell() method executed successfully. Return code=",trade.ResultRetcode(),
" (",trade.ResultRetcodeDescription(),")");
}
Please tell me, why in the strategy tester I don't set stop loss and profit and only open position at market price?
I am using CTrade (trade.Buy) to open a position.
I tried to open it with (trade.PositionOpen), the same thing, it opens and puts stops on demo, stops are 0 in the Strategy Tester, I don't know what may be the problem.
Hello, dear programmers. I think programmers are like gods - to create something working out of nothing, out of thin air and creating material things is just fantastic... I read an article about time, but it says nothing about setting a periodicity, not even periodicity, but enabling and disabling one Expert Advisor at certain times. I don't know if anyone has ever asked that question. I have to rename my EA to start and stop at different times, but since MT5 has only one pair - one EA, I have to switch between them manually. Thanks
Основное правило трейдера - дай прибыли расти, обрезай убытки! В статье рассматривается один из основных технических приемов, позволяющий следовать этому правилу - перемещение уровня защитной остановки (уровня Stoploss) вслед за растущей прибылью позиции, другими словами - скользящий стоп или трейлинг стоп (trailingstop). Приводится пошаговая процедура создания класса для трейлинг стопа на индикаторах SAR и NRTR, который каждый желающий сможет за 5 минут встроить в своего эксперта или использовать независимо для управления позициями на своем счете.
I set trailing bars, but they do not turn on and off at the right time, and they do not take into account the reversal. The idea is this: after trailing stop, usually at the end of a period, for example one hour or 15 minutes, wait a few minutes and let it turn on again and determine the layout by the indicator and move on to the next stop...:-))))
I'm trying to average a trade. But in the parameters.
PositionModify(Symbol,SL,ТР)
I cannot determine the opening price because I get the opening price and I want the price which was shifted as a result of averaging.
Or just through the order history to find out the price of the first and second order and already on the basis of these data to be averaged, I do not want this way it is too complicated for me!
datetime end=TimeCurrent(); // текущее серверное времяdatetime start=end-PeriodSeconds(PERIOD_D1);// установим начало на сутки назад//--- запросим в кэш программы нужный интервал торговой историиHistorySelect(start,end);
//--- получим количество сделок в историиint deals=HistoryDealsTotal();
//--- получим тикет сделки, имеющей последний индекс в спискеulong deal_ticket=HistoryDealGetTicket(deals-1);
if(deal_ticket>0) // получили в кэш сделку, работаем с ней
{
//--- тикет ордера, на основании которого была проведена сделкаulong order =HistoryDealGetInteger(deal_ticket,DEAL_ORDER);
long order_magic=HistoryDealGetInteger(deal_ticket,DEAL_MAGIC);
long pos_ID =HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID);
double priceh =HistoryDealGetInteger(deal_ticket,DEAL_PRICE); // не могу определить цену открытия
PrintFormat("Сделка #%d по ордеру #%d с ORDER_MAGIC=%d участвовала в позиции %d",
deals-1,order,order_magic,pos_ID);
}
else// неудачная попытка получения сделки
{
PrintFormat("Всего в истории %d сделок, не удалось выбрать сделку"+
" с индексом %d. Ошибка %d",deals,deals-1,GetLastError());
}
//--- получим общее количество позицийint positions=PositionsTotal();
//--- пробежим по списку ордеровfor(int i=0;i<positions;i++)
{
ResetLastError();
//--- скопируем в кэш позицию по ее номеру в спискеstring symbol=PositionGetSymbol(i); // попутно получим имя символа, по которому открыта позицияif(symbol!="") // позицию скопировали в кэш, работаем с ней
{
long pos_id =PositionGetInteger(POSITION_IDENTIFIER);
double price =PositionGetDouble(POSITION_PRICE_OPEN);
ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
long pos_magic =PositionGetInteger(POSITION_MAGIC);
string comment =PositionGetString(POSITION_COMMENT);
if(pos_magic==EA_Magic)
{
PositionModify(Symbol(),NormalizeDouble(( - StopLoss*_Point),4),
NormalizeDouble(( + TakeProfit*_Point),4)); // ну здесь еще через запрос в зависимости от типа ордера
}
PrintFormat("Позиция #%d по %s: POSITION_MAGIC=%d, цена=%G, тип=%s, комментарий=%s",
pos_id,symbol,pos_magic,price,EnumToString(type),comment);
}
else// вызов PositionGetSymbol() завершился неудачно
{
PrintFormat("Ошибка при получении в кэш позиции c индексом %d."+
" Код ошибки: %d", i, GetLastError());
}
}
Dear Sirs, help me out!!! Already getting discouraged at the last step, from a ready-made strategy. Can't average a trade, through
I'm trying to average a trade. But in the parameters.
I cannot determine the opening price because I get the opening price and I want the price which was shifted as a result of averaging.
Or just through the order history to find out the price of the first and second order and already on the basis of these data to be averaged, I do not want this way it is too complicated for me!
You should draw up a manual averaging algorithm first. Now you have a negative value of stoploss, and you should have the actual stoploss price. You should set these parameters according to your averaging algorithm.
The variable used to be of extern type, now it's input, but it's already a constant, extern is not displayed in the indicator menu now. Is it possible to do as before or is it necessary to create additional variables to be able to change these values?
For example, we have an EA with the OnTick event, which will open or close a position depending on the conditions. You can test the EA in the strategy tester where you can set the timeframe. I do not see how they are interlinked. Isn't the EA tested in the Strategy Tester, and it reacts to every tick? Or it reacts only to the selected timeframe in the Strategy Tester? I hope this question is clear
Please tell me, why in the strategy tester I don't set stop loss and profit and only open position at market price?
I am using CTrade (trade.Buy) to open a position.
I tried to open it with (trade.PositionOpen), the same thing, it opens and puts stops on demo, stops are 0 in the Strategy Tester, I don't know what may be the problem.
I understand that I can do it manually, but I need a robot to do it.
How do I create a function to modify an order?
https://www.mql5.com/ru/articles/134
Hi, can you tell me if there is a difference for an EA: a minimum deposit of 1000& (dollar account) or 1000rubles (ruble account)?
Dear Sirs, help me out!!! Already getting discouraged at the last step, from a ready-made strategy. Can't average a trade, through
I'm trying to average a trade. But in the parameters.
I cannot determine the opening price because I get the opening price and I want the price which was shifted as a result of averaging.
Or just through the order history to find out the price of the first and second order and already on the basis of these data to be averaged, I do not want this way it is too complicated for me!
Dear Sirs, help me out!!! Already getting discouraged at the last step, from a ready-made strategy. Can't average a trade, through
I'm trying to average a trade. But in the parameters.
I cannot determine the opening price because I get the opening price and I want the price which was shifted as a result of averaging.
Or just through the order history to find out the price of the first and second order and already on the basis of these data to be averaged, I do not want this way it is too complicated for me!
Hello, please clarify one thing.
For example, we have an EA with the OnTick event, which will open or close a position depending on the conditions. You can test the EA in the strategy tester where you can set the timeframe. I do not see how they are interlinked. Isn't the EA tested in the Strategy Tester, and it reacts to every tick? Or it reacts only to the selected timeframe in the Strategy Tester? I hope this question is clear