Greetings. I've watched the competent video "From MQL4 to MQL5 - how to rewrite EAs for Metatrader 5". Many thanks to the author. I have decided to try it myself. I decided to try it myself. The idea is as follows: 1. I set dtriger = 1 in the inputs - Buy opens. 2. I set dtriger = -1 - Sell opens. 3. I set dtriger = 0 - all open ones are closed. I read in the MT5 manuals that it is not possible to hold opposite positions, and I have them. Question: How can I correctly prescribe the closing of an open position The question is: How to correctly register the closure of an existing position at opening a reverse one? Many thanks.
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\OrderInfo.mqh>
CPositionInfo o_position;
CTrade o_trade;
CSymbolInfo o_symbol;
COrderInfo o_order;
inputint triger = 0;
inputdouble StartLot = 0.01;
inputdouble lpos_volume = 1.0;
inputint Step = 10;
inputint MagicNumber = 12345; // Magic nuaberinputint Slippage = 30; // slippageint dtriger;
int dStep;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
dStep = Step ;
dtriger = triger ;
if (!o_symbol.Name(Symbol()))
return(INIT_FAILED);
RefreshRates();
o_trade.SetExpertMagicNumber(MagicNumber) ;
if (IsFillingTypeAllowed(o_symbol.Name(), SYMBOL_FILLING_FOK))
{
o_trade.SetTypeFilling(ORDER_FILLING_FOK);
}
elseif (IsFillingTypeAllowed(o_symbol.Name(), SYMBOL_FILLING_IOC))
{
o_trade.SetTypeFilling(ORDER_FILLING_IOC);
}
else
{
o_trade.SetTypeFilling(ORDER_FILLING_RETURN);
}
o_trade.SetDeviationInPoints(Slippage);
if (o_symbol.Digits() == 3 || o_symbol.Digits() == 5 )
{
dStep = 10 ;
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
}
//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+voidOnTick()
{
datetime lpos_time = 0;
double lpos_price_open = 0.0;
ENUM_POSITION_TYPE lpos_type = -1;
int pos_count = 0;
double sum_profit = 0;
for (int i = PositionsTotal() - 1; i>=0; i--)
{
if (o_position.SelectByIndex(i))
{
if (o_position.Symbol() == o_symbol.Name() && o_position.Magic() == MagicNumber)
{
if (o_position.Time() > lpos_time)
{
lpos_time = o_position.Time(); //OrderOpenTime();
lpos_price_open = o_position.PriceOpen(); //OrderOpenPrice();
lpos_type = o_position.PositionType() ; //OrderTipe();
}
pos_count++;
sum_profit = sum_profit + o_position.Commission() + o_position.Swap() + o_position.Profit() ;
}
}
}
// Считаем кол-во отложенных ордеровint stop_count=0;
for (int i=OrdersTotal()-1; i >=0; i--)
{
if (o_order.SelectByIndex(i))
{
if (o_order.Symbol() == o_symbol.Name() && o_order.Magic() == MagicNumber)
stop_count++;
}
}
if (!RefreshRates())
return ;
if(dtriger == 0 )
{
CloseAll();
return;
}
// + ----- Откраваем Первый ордер ++++++++++if (pos_count == 0 && stop_count == 0 )
{
if ( dtriger == -1 && lpos_type != POSITION_TYPE_SELL)
{
o_trade.Sell(StartLot * lpos_volume , o_symbol.Name()); // S E L L 11111
}
if ( dtriger == 1 && lpos_type != POSITION_TYPE_BUY )
{
o_trade.Buy(StartLot * lpos_volume , o_symbol.Name()); // B U Y 11111
}
}
// + ----- Переворот ++++++++++++++++++++++++++++ if (pos_count>0)
{
if(lpos_type == POSITION_TYPE_BUY )
{
if ( dtriger == -1 )
{
o_trade.Sell(StartLot * lpos_volume , o_symbol.Name()); // S E L L +++++
}
}
if (lpos_type==POSITION_TYPE_SELL )
{
if ( dtriger == 1 )
{
o_trade.Buy(StartLot * lpos_volume , o_symbol.Name()); // B U Y +++++
}
}
}
if(pos_count>0 && stop_count>0)
DeleteStopOrders() ;
}
//-----------------------------------------------------------bool RefreshRates()
{
if (!o_symbol.RefreshRates())
return(false) ;
if (o_symbol.Ask() == 0 || o_symbol.Bid() == 0)
return(false);
return(true);
}
//--- --------------------------------------------------------- bool IsFillingTypeAllowed (string symbol, int fill_type)
{
int filling = (int)SymbolInfoInteger(symbol, SYMBOL_FILLING_MODE);
return((filling && fill_type) == fill_type) ;
}
// -------------------------------------------------- void CloseAll()
{
for (int index = PositionsTotal()-1; index >=0; index--)
{
if (o_position.SelectByIndex(index))
{
if (o_position.Symbol() == o_symbol.Name() && o_position.Magic() == MagicNumber)
{
o_trade.PositionClose(o_position.Ticket());
}
}
}
}
//----------------------------------------------------------- // Delete all pending orders//-------------------------------------void DeleteStopOrders()
{
for (int i = OrdersTotal() - 1; i >= 0; i-- )
{
if (o_order.SelectByIndex(i))
if(o_order.Symbol() == o_symbol.Name() && o_order.Magic() == MagicNumber)
o_trade.OrderDelete(o_order.Ticket());
}
}
//+------------------------------------------------------------------+
Greetings. I have watched the helpful clip "From MQL4 to MQL5 - how to rewrite EAs for Metatrader 5". I would like to congratulate the author. I have decided to try it myself. I wrote it. My idea is the following: 1. I set dtriger = 1 - opens Buy. 2. I set dtriger = -1 - Sell opens. 3. I set dtriger = 0 - all open ones are closed. I read in the MT5 manuals that it is not possible to hold opposite positions, and I have them. Question: how to correctly prescribe the closing of an existing position The question is: How to correctly register the closure of an existing position at opening a reverse one? Many thanks.
You must have been very inattentive when reading the fact sheet.
Перед тем как приступить к изучению торговых функций платформы, необходимо создать четкое представление об основных терминах: ордер, сделка и позиция. — это распоряжение брокерской компании купить или продать финансовый инструмент. Различают два основных типа ордеров: рыночный и отложенный. Помимо них существуют специальные ордера Тейк Профит...
1. dtriger = 1 - Buy opens. 2. dtriger = -1 - Sell opens. 3. dtriger = 0 - all open ones are closed.
The Expert Advisor should do the following:
if you need to open BUY - you should first close SELL (issue a command to close SELL positions - it does not matter whether they are there or not)
if you need to open SELL - then first you need to close BUY (a command for closing BUY positions will be issued, no matter whether they are there or not)
if the client needs to close all - then just close all positions (no matter whether they BUY or SELL)
Two algorithms are needed for implementation (the magic number also contributes here) - it can be disabled.
//+------------------------------------------------------------------+//| Close positions |//+------------------------------------------------------------------+void ClosePositions(constENUM_POSITION_TYPE pos_type)
{
for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current positionsif(m_position.SelectByIndex(i)) // selects the position by index for further access to its propertiesif(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
if(m_position.PositionType()==pos_type) // gets the position type
m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
}
и
//+------------------------------------------------------------------+//| Close all positions |//+------------------------------------------------------------------+void CloseAllPositions(void)
{
for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of current positionsif(m_position.SelectByIndex(i)) // selects the position by index for further access to its propertiesif(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol
}
The general idea is to loop around all positions fromPositionsTotal()-1 to 0. It's from PositionsTotal()-1 to 0, not from zero to PositionsTotal()-1. This is important.
Also a word of advice: when working in MetaTrader 5, an order is a REMOVED ORDER. Therefore it is highly recommended that you do not even bring up the word "order" at this initial stage, so as not to create confusion in your mind.
Vladimir Karputov: Also a word of advice: when working in MetaTrader 5, an order is a REMOVED ORDER. Therefore it is highly recommended that you do not even remember the word "order" at this initial stage, so as not to create confusion in your mind.
There are also market orders Buy and Sell, as well as CloseBy orders.
Торговая деятельность в платформе связана с формированием и отсылкой рыночных и отложенных ордеров для исполнения брокером, а также с управлением текущими позициями путем их модификации или закрытия. Платформа позволяет удобно просматривать торговую историю на счете, настраивать оповещения о событиях на рынке и многое другое. Открытие позиций...
Greetings. I've watched the competent video "From MQL4 to MQL5 - how to rewrite EAs for Metatrader 5".
Many thanks to the author. I have decided to try it myself. I decided to try it myself. The idea is as follows:
1. I set dtriger = 1 in the inputs - Buy opens.
2. I set dtriger = -1 - Sell opens.
3. I set dtriger = 0 - all open ones are closed.
I read in the MT5 manuals that it is not possible to hold opposite positions,
and I have them.
Question: How can I correctly prescribe the closing of an open position
The question is: How to correctly register the closure of an existing position at opening a reverse one?
Many thanks.
Greetings. I have watched the helpful clip "From MQL4 to MQL5 - how to rewrite EAs for Metatrader 5".
I would like to congratulate the author. I have decided to try it myself. I wrote it. My idea is the following:
1. I set dtriger = 1 - opens Buy.
2. I set dtriger = -1 - Sell opens.
3. I set dtriger = 0 - all open ones are closed.
I read in the MT5 manuals that it is not possible to hold opposite positions,
and I have them.
Question: how to correctly prescribe the closing of an existing position
The question is: How to correctly register the closure of an existing position at opening a reverse one?
Many thanks.
You must have been very inattentive when reading the fact sheet.
Reference:General principles - Trading operations.
Bottom line: MetaTrader 5 has bothNetting and Hedgingsystems .
I would formulate your task differently:
1. dtriger = 1 - Buy opens.
2. dtriger = -1 - Sell opens.
3. dtriger = 0 - all open ones are closed.
The Expert Advisor should do the following:
Two algorithms are needed for implementation (the magic number also contributes here) - it can be disabled.
и
The general idea is to loop around all positions fromPositionsTotal()-1 to 0. It's from PositionsTotal()-1 to 0, not from zero to PositionsTotal()-1. This is important.
Also a word of advice: when working in MetaTrader 5, an order is a REMOVED ORDER. Therefore it is highly recommended that you do not even remember the word "order" at this initial stage, so as not to create confusion in your mind.
There are also market orders Buy and Sell, as well as CloseBy orders.
Thank you very much, just like music.
Thank you very much, just like music.
Well, if you would be so kind, more then.
I've put in the entries and prescribed a pre-close, but again the orders are hanging there and there.
Well, if you would be so kind, more then.
I have inserted the entries and prescribed a pre-close, but again there are hanging orders here and there.
Thank you very much, just like the notes.
What is the signal to open? Because the code is not complete - only closing positions, but I also need to open positions...
Trade command.mq5
#property version "1.000"
So far it only performs three actions: