This method of swap calculation is called rollover. You cannot know about it programmatically in MT4. Only indirectly after the midnight change of working market orders. There are a lot of such small, but rather unpleasant problems in MT4. In MT5 there are a little less, but they still exist.
These are the swap values in pips. They should be converted into the currency of the deposit, based on the volume of the market order. Then you will get the real swap size.
"There is no way to find out about it programmatically in MT4". - Thank you for your time and replies.
Good day! Dear forum users, please help me to understand the algorithm. The aim is to determine the price range in the specified period of time and set the buy and sell stops at max and min. Stoplosses are set on opposite orders, TakeProfit should be equal to StopLoss*2.
Then, after each closing by Stop Loss, the order is restored with the same Stop Loss and Take Profit as the closed one and the whole cycle is completed once one of the orders is closed by Take Profit. And all from the beginning we define the range and go.
But now he just does not place TP or rather he places it at the open price and stop loss is not on the range size, i.e. not on an oppositely directed order. I thank him in advance for his help.
staticint prevtime = 0;
int MagicNumber = 12345678;
inputint stoploss = 40;
inputint takeprofit = 50;
inputint padding = 5;
int a=1;
inputstring startTime = "14:35";
inputstring endTime = "18:35";
int expertBars;
double max, min;
bool isEndTime = true;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
//---//sendOrders();return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
//---
}
//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+#include <expert.mq4>
int start()
{
//Возвращает максимум и минимум за промежутокif(isTime()) getMaxMin();
// всё, что задается ниже - будет работать по "ценам открытия"//нового бара, т.е. будет срабатывать в момент его появления//на том графике, на кот. стоит советник
CheckEvents( MagicNumber );
if ( eventBuyClosed_SL > 0 ) {
Alert( _Symbol, OrderClosePrice(), ": Buy-позиция закрыта по СтопЛоссу!" );
double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
Alert("Минимальный стоп левел: ", minstoplevel);
OrderSend(_Symbol,OP_BUYSTOP,OrderLots(),OrderOpenPrice(),3,OrderStopLoss(),OrderTakeProfit(),"My order",MagicNumber,0,clrGreen);
}
if ( eventBuyClosed_TP > 0 ) {
Alert( _Symbol, OrderClosePrice(), ": Buy-позиция закрыта по ТейкПрофиту!" );
deleteAllPaddingOrders();
}
if ( eventSellClosed_SL > 0 ) {
Alert( _Symbol, OrderClosePrice(), ": Sell-позиция закрыта по СтопЛоссу!" );
double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
Alert("Минимальный стоп левел: ", minstoplevel);
OrderSend(_Symbol,OP_SELLSTOP,OrderLots(),OrderOpenPrice(),3,OrderStopLoss(),OrderTakeProfit(),"My order",MagicNumber,0,clrRed);
}
if ( eventSellClosed_TP > 0 ) {
Alert( _Symbol, OrderClosePrice(), ": Sell-позиция закрыта по ТейкПрофиту!" );
deleteAllPaddingOrders();
}
if ( eventBuyLimitOpened > 0 || eventBuyStopOpened > 0 ||
eventSellLimitOpened > 0 || eventSellStopOpened > 0 )
Alert( _Symbol, OrderType(), ": сработал отложенный ордер!" );
return(0);
}
//-----------------------------------------------------------------+void deleteAllPaddingOrders() {
int total = OrdersTotal();
for(int i=total-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
int type = OrderType();
if (OrderMagicNumber() != MagicNumber) continue;
if (OrderSymbol() != _Symbol) continue;
bool result = false;
switch(type)
{
//Close opened long positionscaseOP_BUY : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
break;
//Close opened short positionscaseOP_SELL : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
// break;//Close pending orders//case OP_BUYLIMIT ://case OP_SELLLIMIT :caseOP_BUYSTOP :
caseOP_SELLSTOP : result = OrderDelete( OrderTicket() );
}
if(result == false)
{
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
}
return;
}
return;
}
void sendOrders(bool isFirst) {
//--- получим минимальное значение Stop leveldouble minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
Print("Minimum Stop Level=",minstoplevel," points");
//--- BUYSTOP//--- вычисленные значения цен SL и TP должны быть нормализованы//--- размещаем рыночный ордер на покупку 1 лотаint ticketBuyStop, ticketSellStop;
if(!isFirst) {
ticketBuyStop=OrderSend(Symbol(),OP_BUYSTOP,1,Ask + padding * Point,20,Bid -padding*Point,Ask + padding * Point,"My order",MagicNumber,0,clrGreen);
ticketSellStop=OrderSend(Symbol(),OP_SELLSTOP,1,Bid - padding * Point,20,Ask + padding*Point,Bid - padding * Point,"My order",MagicNumber,0,clrRed);
} else {
ticketBuyStop=OrderSend(Symbol(),OP_BUYSTOP,1,max + padding * Point,20,min -padding*Point,max + (max - min + padding) * Point,"My order",MagicNumber,0,clrGreen);
ticketSellStop=OrderSend(Symbol(),OP_SELLSTOP,1,min - padding * Point,20,max + padding*Point,min - (max - min + padding)*Point,"My order",MagicNumber,0,clrRed);
}
if(ticketBuyStop<0)
{
Print("OrderSend завершилась с ошибкой #",GetLastError());
deleteAllPaddingOrders();
if(a <=5) {
//sendOrders(isFirst);
a= a+1;
}
}
elsePrint("Функция OrderSend успешно выполнена");
//---BUYSTOP//---SELLSTOP//--- вычисленные значения цен SL и TP должны быть нормализованы//--- размещаем рыночный ордер на покупку 1 лотаif(ticketSellStop<0)
{
deleteAllPaddingOrders();
if(a <= 5) {
//sendOrders();
a= a+1;
Print("a", a);
}
Print("OrderSend завершилась с ошибкой #",GetLastError());
}
elsePrint("Функция OrderSend успешно выполнена");
//---SELLSTOPreturn;
}
bool getMaxMin() {
int startIndex = iBarShift(_Symbol, 0, StrToTime(startTime), true);
min=iLow(NULL,0,iLowest(NULL,0,MODE_LOW,startIndex,0));
max=iHigh(NULL,0,iHighest(NULL,0,MODE_HIGH,startIndex,0));
Alert("Min: ", min);
Alert("Max: ", max);
sendOrders(true);
returntrue;
}
//===============================================================================+//======| возвращает true если временной диапозон кончился |//===============================================================================+bool isTime() {
if (TimeHour(StrToTime(startTime)) == Hour() && TimeMinute(StrToTime(startTime)) == Minute() && isEndTime) { Alert("Start Timeline"); isEndTime = false; deleteAllPaddingOrders();};
if(TimeHour(StrToTime(endTime)) == Hour() && TimeMinute(StrToTime(endTime)) <= Minute() && !isEndTime) { Alert("End Timeline"); isEndTime = true; returntrue;};
returnfalse;
}
//=====================================================================+//======| возвращает true если появился новый бар, иначе false |//=====================================================================+//bool isNewBar()//{//bool res=false;//if(expertBars!=iBars(Symbol(),0))//{//expertBars=iBars( Symbol (),0);//res=true;//}//return(res);//}
When testing in the log there is an error OrderSend error 130 - if I understand correctly it can only be related to stops or strokes,
The open prices of pending orders are also affected. That is why we need to check the distance between the current market price and the open price of the order. In this case: Price - Ask.
The opening price of pending orders also applies. Therefore we should also check the distance between the current market price and the opening price of the order. In this case: Price - Ask.
It's a bit complicated for me. Could you explain in which part of the code to add and what does it mean mn and mag_n? where should I put my EA medjic here?
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 method of swap calculation is called rollover. You cannot know about it programmatically in MT4. Only indirectly after the midnight change of working market orders. There are a lot of such small, but rather unpleasant problems in MT4. In MT5 there are a little less, but they still exist.
These are the swap values in pips. They should be converted into the currency of the deposit, based on the volume of the market order. Then you will get the real swap size.
"There is no way to find out about it programmatically in MT4". - Thank you for your time and replies.
Good day! Dear forum users, please help me to understand the algorithm. The aim is to determine the price range in the specified period of time and set the buy and sell stops at max and min. Stoplosses are set on opposite orders, TakeProfit should be equal to StopLoss*2.
Then, after each closing by Stop Loss, the order is restored with the same Stop Loss and Take Profit as the closed one and the whole cycle is completed once one of the orders is closed by Take Profit. And all from the beginning we define the range and go.
But now he just does not place TP or rather he places it at the open price and stop loss is not on the range size, i.e. not on an oppositely directed order. I thank him in advance for his help.
There is no need to duplicate questions in different threads.
Good afternoon!
When testing in the log I get OrderSend error 130 - if I understand correctly it can only be related to stops or strokes, please check what is wrong:
Good afternoon!
When testing in the log there is an error OrderSend error 130 - if I understand correctly it can only be related to stops or strokes,
The open prices of pending orders are also affected. That is why we need to check the distance between the current market price and the open price of the order. In this case: Price - Ask.
The opening price of pending orders also applies. Therefore we should also check the distance between the current market price and the opening price of the order. In this case: Price - Ask.
What does the Hour() function return ?
Returns the current hour. that's how I work: if the current hour is greater than 11 and less than 17,
but how?
It's a bit complicated for me. Could you explain in which part of the code to add and what does it mean mn and mag_n? where should I put my EA medjic here?
Before your condition put
mag_n - where do I put my EA's IG here?
I am writing: if the current hour is more than 11 and less than 17, how should it be?
I understand that the question is about the indicator. Instead ofHour() -> time[i]
I understand the question is about the indicator. Instead ofHour() -> time[i].
Yes, you helped that, now I want to limit the time. Exclude counting from 5pm to 11pm.