Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1420

 

What is the correct way to use OnSetColorBackground for a CButton object? I need to colour the button from OnTick depending on the conditions. No clicking on the button is expected.

I declare and use the "colouring" function like this:


public:
bool              OnSetClrButtonMA(void);

---------------

bool CControlsDialog::OnSetClrButtonMA(void)
  {
   if(CL>MA)
      m_button_MA.ColorBackground(colBtn_Pos);
   else
      m_button_MA.ColorBackground(colBtn_Neg);
     return(true);
  }

void OnTick{
................

	 OnSetClrButtonMA();

}

Is there an example where this is implemented in the code? I haven't found it in the library.

Документация по MQL5: Стандартная библиотека / Панели и диалоги / CButton / OnSetColorBackground
Документация по MQL5: Стандартная библиотека / Панели и диалоги / CButton / OnSetColorBackground
  • www.mql5.com
OnSetColorBackground - CButton - Панели и диалоги - Стандартная библиотека - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 

Hello!

Can you tell me why the script for changing stop loss does not work and gives error 4756?

At the same time, the same script for changing take profit works fine.

//+------------------------------------------------------------------+
//|                                                    Modify SL.mq5 |
//|                                                                  |
//+------------------------------------------------------------------+
#property description "Скрипт"
#property script_show_inputs
input  int Magic_Number = 0;
input double Price_of_New_Stop_Loss = 0.0;
//--------------------------------------------------------------------
MqlTick tick;
MqlTradeRequest request;
MqlTradeResult result;
MqlTradeCheckResult check;
MqlDateTime tm;
//--------------------------------------------------------------------
void OnStart()
{  
   double Position_SL;
   ulong  Position_Magic = 0;
   for(int i=0; i<PositionsTotal(); i++)
   {
      if(_Symbol == PositionGetSymbol(i))
      {
         Position_Magic = PositionGetInteger(POSITION_MAGIC);
         if(Position_Magic == Magic_Number)
         {
            ZeroMemory(request);
            ZeroMemory(result);
            request.position = PositionGetInteger(POSITION_TICKET);
            Position_SL = PositionGetDouble(POSITION_SL);

            if (Position_SL != Price_of_New_Stop_Loss)
            {
               request.action = TRADE_ACTION_SLTP;
               request.sl = NormalizeDouble(Price_of_New_Stop_Loss,_Digits);
               Print(TimeToString(TimeCurrent()), " Modify ", request.position,
                     " with Position_Magic ", IntegerToString(Position_Magic));
               Print("  SL ", DoubleToString(Position_SL,_Digits),
                     " -> ", DoubleToString(request.sl,_Digits));
               if(!OrderSend(request,result)) Print("error ",GetLastError());
            }
         }
      }  
   }
   //--- cycle until the script is not halted
   while(!IsStopped()) Comment("Сделано");
   Comment("");
}
// End OnStart()
//+------------------------------------------------------------------+
 
Transslator #:

Hello!

Can you tell me why the script for changing stop loss doesn't work and gives error 4756?

At the same time, the same script for changing take profit works fine.

There is a good example on this topic in the manual

         request.action  =TRADE_ACTION_SLTP; // тип торговой операции
         request.position=position_ticket;   // тикет позиции
         request.symbol=position_symbol;     // символ 
         request.sl      =sl;                // Stop Loss позиции
         request.tp      =tp;                // Take Profit позиции
         request.magic=EXPERT_MAGIC;         // MagicNumber позиции

Structure of a trade request

SL & TP Modification

Trade order for modification of StopLoss and/or TakeProfit levels. Requires specifying 4 fields:

  • action
  • symbol
  • sl
  • tp
  • position

When modifying or closing a position in the hedging system, be sure to specify its ticket (MqlTradeRequest::position). In the netting system the ticket can also be specified, but the position is identified by the symbol name.


https://www.mql5.com/ru/docs/constants/structures/mqltraderequest

Документация по MQL5: Константы, перечисления и структуры / Структуры данных / Структура торгового запроса
Документация по MQL5: Константы, перечисления и структуры / Структуры данных / Структура торгового запроса
  • www.mql5.com
Структура торгового запроса - Структуры данных - Константы, перечисления и структуры - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
2022.08.31 13:15:39.943 2012.01.08 23:24:00   failed market sell 0.2 EURJPY [Market closed]
Can you tell me how to check that the market is not closed ?
 
Vladimir Deryagin #:

The handbook has a good example on this topic

When modifying or closing a position in a hedging system, be sure to specify its ticket (MqlTradeRequest::position). In the netting system, the ticket can also be specified, but the position is identified by the symbol name.


https://www.mql5.com/ru/docs/constants/structures/mqltraderequest

Thanks for the answer!

Reworked the script like this:

//+------------------------------------------------------------------+
//|                                                 Modify SL TP.mq5 |
//|                                                                  |
//+------------------------------------------------------------------+
#property description "Скрипт"
#property script_show_inputs
input  int Magic_Number = 0;
input double Price_of_New_Take_Profit = 0.0;
input double Price_of_New_Stop_Loss = 0.0;
//--------------------------------------------------------------------
//--- объявление запроса и результата
//MqlTick tick;
MqlTradeRequest request;
MqlTradeResult result;
//MqlTradeCheckResult check;
//MqlDateTime tm;
//--------------------------------------------------------------------
void OnStart()
{  
//   double Position_SL,Position_TP;
//   ulong  Position_Magic = 0;
   //--- перебор всех открытых позиций
   for(int i=0; i<PositionsTotal(); i++)
   {
      if(_Symbol == PositionGetSymbol(i))
      {
         //--- параметры ордера
         ulong  Position_Ticket = PositionGetTicket(i);// тикет позиции
         string Position_Symbol = PositionGetString(POSITION_SYMBOL); // символ 
         int    Symbol_Digits = (int)SymbolInfoInteger(Position_Symbol,SYMBOL_DIGITS); // количество знаков после запятой
         ulong  Position_Magic = PositionGetInteger(POSITION_MAGIC); // MagicNumber позиции
         double Position_Volume = PositionGetDouble(POSITION_VOLUME);    // объем позиции
         double Position_SL = PositionGetDouble(POSITION_SL);  // Stop Loss позиции
         double Position_TP = PositionGetDouble(POSITION_TP);  // Take Profit позиции
         ENUM_POSITION_TYPE Position_Type=(ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);  // тип позици   
         if(Position_Magic == Magic_Number)
         {
            if (Position_SL != Price_of_New_Stop_Loss || Position_TP != Price_of_New_Take_Profit)
            {
               //--- обнуление значений запроса и результата
               ZeroMemory(request);
               ZeroMemory(result);
               //--- установка параметров операции
               request.action   = TRADE_ACTION_SLTP; // тип торговой операции
               request.position = Position_Ticket;   // тикет позиции
               request.symbol   = Position_Symbol;     // символ 
               request.sl       = NormalizeDouble(Price_of_New_Stop_Loss,_Digits); // Stop Loss позиции
               request.tp       = NormalizeDouble(Price_of_New_Take_Profit,_Digits); // Take Profit позиции
               request.magic    = Position_Magic;         // MagicNumber позиции
               //--- вывод информации о модификации
               Print(TimeToString(TimeCurrent()), " Modify ", request.position,
                     " with Position_Magic ", IntegerToString(Position_Magic));
               Print("  SL ", DoubleToString(Position_SL,_Digits), " -> ", DoubleToString(request.sl,_Digits),
                     ";  TP ", DoubleToString(Position_TP,_Digits), " -> ", request.tp);
               //--- отправка запроса и вывод информации об ошибке, если отправить запрос не удалось
               if(!OrderSend(request,result)) PrintFormat("OrderSend error %d",GetLastError());
               //--- информация об операции   
               PrintFormat("retcode=%u  deal=%I64u  order=%I64u", result.retcode, result.deal, result.order);
            }
         }
      }  
   }
   //--- Цикл, пока скрипт не будет прерван
   while(!IsStopped()) Comment("Сделано");
   Comment("");
}
// End OnStart()
//+------------------------------------------------------------------+

Take profit changes fine. But when trying to change the stop loss with an explicitly set value, error 4756 is generated, and in the log it is:


 
Transslator #:

Take profit changes perfectly. But when trying to change the stop loss with an explicitly set value, error 4756 is generated, and in the log it is:


What is the Ask price equal to at this moment?
 
Sergey Gridnev #:
What is the Ask price equal to at this moment?
The position is open at the price of 0.85098. The same story on other pairs, and at different distances to the stop.
 
Transslator #:
The position was opened at the price of 0.85098. The same story is true for other pairs, and at different distances to the stop.
It does not matter at what price the position is opened, the price at the moment of stop modification is important. For a sell position it is the Ask price.
 
Sergey Gridnev #:
It does not matter at what price the position is opened, it is the price at the moment of stop modification that matters. For a sell position, this is the Ask price.
This is forex, the current price is constantly changing, but it is obviously far away from the stop being placed.
 
Transslator #:
This is forex, the current price is constantly changing, but is deliberately far away from the stop being placed.
So print the prices before attempting to modify the position, and we will see if they are far from the stop.