Новая версия платформы MetaTrader 5 build 2360: Расширение интеграции с SQLite - страница 8

 
Carl Schreiber:

Должна ли (!) Это быть открытая позиция или же это может быть противоположный лимитный ордер, чтобы получить лучшую цену и не обременять систему (или мое терпение) постоянным наблюдением и ожиданием?

Или эта форма CloseBy возможна только через OnTradeTransaction () - чтобы узнать, когда LimitOrder активирован, и только потом отправлять CloseBy?

Does(!) this have to be an open position or can't it also be an opposite limit order to get a better price and not burden the system (or my patience) with constant watching and waiting?

Or is this form of CloseBy only possible via OnTradeTransaction() - to recognize when the LimitOrder is activated and only then send the CloseBy?

Try to learn the sample from Trade Operation Types

Example of the TRADE_ACTION_CLOSE_BY trade operation for closing positions by opposite positions:

#define EXPERT_MAGIC 123456  // MagicNumber of the expert
//+------------------------------------------------------------------+
//| Close all positions by opposite positions                        |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- declare and initialize the trade request and result of trade request
   MqlTradeRequest request;
   MqlTradeResult  result;
   int total=PositionsTotal(); // number of open positions   
//--- iterate over all open positions
   for(int i=total-1; i>=0; i--)
     {
      //--- parameters of the order
      ulong  position_ticket=PositionGetTicket(i);                                    // ticket of the position
      string position_symbol=PositionGetString(POSITION_SYMBOL);                      // symbol 
      int    digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS);            // ticket of the position
      ulong  magic=PositionGetInteger(POSITION_MAGIC);                                // MagicNumber of the position
      double volume=PositionGetDouble(POSITION_VOLUME);                               // volume of the position
      double sl=PositionGetDouble(POSITION_SL);                                       // Stop Loss of the position
      double tp=PositionGetDouble(POSITION_TP);                                       // Take Profit of the position
      ENUM_POSITION_TYPE type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);  // type of the position
      //--- output information about the position
      PrintFormat("#%I64u %s  %s  %.2f  %s  sl: %s  tp: %s  [%I64d]",
                  position_ticket,
                  position_symbol,
                  EnumToString(type),
                  volume,
                  DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
                  DoubleToString(sl,digits),
                  DoubleToString(tp,digits),
                  magic);
      //--- if the MagicNumber matches
      if(magic==EXPERT_MAGIC)
        {
         for(int j=0; j<i; j++)
           {
            string symbol=PositionGetSymbol(j); // symbol of the opposite position
            //--- if the symbols of the opposite and initial positions match
            if(symbol==position_symbol && PositionGetInteger(POSITION_MAGIC)==EXPERT_MAGIC)
              {
               //--- set the type of the opposite position
               ENUM_POSITION_TYPE type_by=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
               //--- leave, if the types of the initial and opposite positions match
               if(type==type_by)
                  continue;
               //--- zeroing the request and result values
               ZeroMemory(request);
               ZeroMemory(result);
               //--- setting the operation parameters
               request.action=TRADE_ACTION_CLOSE_BY;                         // type of trade operation
               request.position=position_ticket;                             // ticket of the position
               request.position_by=PositionGetInteger(POSITION_TICKET);      // ticket of the opposite position
               //request.symbol     =position_symbol;
               request.magic=EXPERT_MAGIC;                                   // MagicNumber of the position
               //--- output information about the closure by opposite position
               PrintFormat("Close #%I64d %s %s by #%I64d",position_ticket,position_symbol,EnumToString(type),request.position_by);
               //--- send the request
               if(!OrderSend(request,result))
                  PrintFormat("OrderSend error %d",GetLastError()); // if unable to send the request, output the error code
 
               //--- information about the operation   
               PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Trade Operation Types
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Trade Operation Types
  • www.mql5.com
Trading is done by sending orders to open positions using the OrderSend() function, as well as to place, modify or delete pending orders. Each trade order refers to the type of the requested operation. Trading operations are described in the ENUM_TRADE_REQUEST_ACTIONS enumeration...
 
Rashid Umarov :

Try to learn the sample from Trade Operation Types

Example of the TRADE_ACTION_CLOSE_BY trade operation for closing positions by opposite positions:

Спасибо, но у меня нет проблем с закрытием открытой позиции (введите POSITION_TYPE_SELL или POSITION_TYPE_BUY) другой открытой позицией ! Это стандарт.

Я хочу сопоставить закрытие одной или нескольких открытых позиций ( типа POSITION_TYPE_SELL или POSITION_TYPE_BUY) одним противоположным лимит- ордером (например, ORDER_TYPE_BUY_LIMIT или ORDER_TYPE_SELL_LIMIT).

Это работает или это невозможно - это был / был мой вопрос?

Thanks, but I don't have a problem to close an open position (type either POSITION_TYPE_SELL or POSITION_TYPE_BUY) by another open position! That is the standard.

I would like to match for closing one or more open position(s) (type either POSITION_TYPE_SELL or POSITION_TYPE_BUY) by one opposite Limit-Order (types e.g. ORDER_TYPE_BUY_LIMIT or ORDER_TYPE_SELL_LIMIT).

Does this work or is it impossible - that is/was my question?
 
Carl Schreiber:

Thanks, but I don't have a problem to close an open position (type either POSITION_TYPE_SELL or POSITION_TYPE_BUY) by another open position! That is the standard.

I would like to match for closing one or more open position(s) (type either POSITION_TYPE_SELL or POSITION_TYPE_BUY) by one opposite Limit-Order (types e.g. ORDER_TYPE_BUY_LIMIT or ORDER_TYPE_SELL_LIMIT).

Does this work or is it impossible - that is/was my question?

Open by Market opposite position (order in terms of hedge system) and close by it  all other orders immediately. What is the matter?

Or place Limit opposite order (instead of Take Profit/Stop Loss) and after it triggered close all them.

No other options

 
Carl Schreiber:

Должна ли (!) Это быть открытая позиция или же это может быть противоположный лимитный ордер, чтобы получить лучшую цену и не обременять систему (или мое терпение) постоянным наблюдением и ожиданием?

Или эта форма CloseBy возможна только через OnTradeTransaction () - чтобы узнать, когда LimitOrder активирован, и только потом отправлять CloseBy?

Does(!) this have to be an open position or can't it also be an opposite limit order to get a better price and not burden the system (or my patience) with constant watching and waiting?

Or is this form of CloseBy only possible via OnTradeTransaction() - to recognize when the LimitOrder is activated and only then send the CloseBy?

Это должна быть именно позиция.

 
Rashid Umarov :

Open by Market opposite position (order in terms of hedge system) and close by it  all other orders immediately. What is the matter?

Or place Limit opposite order (instead of Take Profit/Stop Loss) and after it triggered close all them.

No other options

Позвольте мне предложить на будущее, что закрытие открытой позиции может быть обработано напрямую с помощью лимитного ордера, так что теперь нам не нужно ждать и проверять его срабатывание - что-то вроде пожара и забывания :)

May I then suggest for the future that closing an open position can be processed directly by a limit order, so onw don't has to wait and check for it being triggered - a kind of fire and forget :)

 
MetaQuotes:

Попробуйте фильтры в следующем жестком формате:


Так работает. Но это уже не простой фильтр...

 
Carl Schreiber:

Позвольте мне предложить на будущее, что закрытие открытой позиции может быть обработано напрямую с помощью лимитного ордера, так что теперь нам не нужно ждать и проверять его срабатывание - что-то вроде пожара и забывания :)

лимитный ордер может исполнится частично (или вообще может быть отклонён), поэтому не является полным эквивалентом TP/SL, т.е. присматривать за ним - необходимость

 
Carl Schreiber:

Позвольте мне предложить на будущее, что закрытие открытой позиции может быть обработано напрямую с помощью лимитного ордера, так что теперь нам не нужно ждать и проверять его срабатывание - что-то вроде пожара и забывания :)

May I then suggest for the future that closing an open position can be processed directly by a limit order, so onw don't has to wait and check for it being triggered - a kind of fire and forget :)

Не путайте неттинг и хеджинг. В неттинге всё именно так и работает. В хэджинге образуется противоположная позиция. Закрыть одну позицию другой можно в любое время, а не только когда образовалась одна из позиций.

Чтобы закрыть позицию, Вы можете выставить stop loss или take profit, для этого необязательно открывать противоположную позицию. И всё будет автоматом - "оторвать и выбросить"

Функция OrderCloseBy пришла из MT4

 

Хорошо, спасибо, я понимаю. Будет делать с TP.

Ok, thank you all! I understand. Will do with with TP.

 

Ставка маржи По умолчанию всегда возвращается 0

нет никакого способа, чтобы прочитать начальную ставку маржи и обслуживание маржинальной ставки

оба находятся в SymbolsInfoDouble

и вы должны прочитать это с

 SymbolInfoDouble ( _Symbol , SYMBOL_MARGIN_INITIAL );

но это всегда возвращает 0, на демо и на реальном счете.

я проверяю это с 2 брокерами, оба имеют это значение написано в


проблема в том, что он нужен для расчета, если у вас нет символов Форекс, а значение отличается от 1 или 0


Причина обращения: