Questions from Beginners MQL5 MT5 MetaTrader 5 - page 73

 

Where is the position modification written?

Stop Loss and Take Profit details written before Buy and Sell conditions

   double Ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);            // лучшее предложение на покупку
   double Bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);            // лучшее предложение на продажу
   double SL  = NormalizeDouble(StopLoss,_Digits);
   double TP  = NormalizeDouble(TakeProfit,_Digits);
                        
   bool Buy_Condition_1=...;
   bool Buy_Condition_2=...;
   bool Buy_Condition_3=...;
а сам
 bool PositionModify(const string _Symbol,const double SL,const double TP)
   {
      if(PositionSelect(_Symbol)==true) // есть открытая позиция
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
         {
    Alert("SL!!!");
    return;    // закрыл 
         }
   MqlTradeRequest request={0};
   MqlTradeResult  result ={0};
        
       
   mrequest.action=TRADE_ACTION_SLTP;
   mrequest.symbol=_Symbol;
   mrequest.magic =EA_Magic; 
   mrequest.sl    =StopLoss;
   mrequest.tp    =TakeProfit;
   OrderSend(mrequest,mresult);
   if(mresult.retcode==10009 || mresult.retcode==10008) //запрос выполнен или ордер успешно помещен
           {
            Alert("Стопка прошла#:",mresult.order,"!!");
           }
         else
           {
            Alert("Стопка не прошла - код ошибки:",GetLastError());
            return(false);
           }
   return(true);
  }
//----------------------------------------------------------------- 
if(Buy_Close_1 || Buy_Close_2)
  
после отсылки ордера на покупку. Пока при компиляции борюсь с "лишними" скобками фигурными. Вопрос дубль 2 - правильно ли я расположил модификацию позиции? И вообще, "классический" ли он имеет код (при условии, что он верный)?
 
papaklass:

There is an error in the code:

Thank you. It's gone.

What about positioning?

The thing is, if I put curly brackets in places, at compilation it generates - 'PositionModify' - function can be declared only in the global scope

and this time I believe it, i.e. the 'position modifier' itself should be placed before int OnInit() and conditions (if) after the purchase section ?

 
papaklass:

Give me the code, I don't understand what you mean.

PS: You should describe the PositionModify() function on a global level, i.e. on the level where the functions are : OnInit(), OnTick(), OnDeinit().

Here is the code. It only has a stop to buy, as it has a stop to sell in the same way.
Files:
Aim.mq5  13 kb
 
papaklass:

Corrected. It compiles without errors. Didn't test it in the tester. Your code was not readable. Get used to code layout as in my corrected version.

Thank you (though I don't quite understand what has changed other than the layout).

What does "SMB" in line 2 mean and where is it defined by values? can't you write _Symbol ?

  mrequest.action   = TRADE_ACTION_SLTP;
      mrequest.symbol   = smb;
      mrequest.magic    = EA_Magic; 
      mrequest.sl       = SL;
      mrequest.tp       = TP;
 

Hi, can you tell me if the orders on the signals will be executed if I have my terminal computer switched off?

 

Good afternoon,

Can you advise how best to implement the following: Expert launches, when initialised it draws (in the chart area? somewhere else?), say, TextBox and Button. Expert handles ticks. If a user enters some value in TextBox and press Button, the tick handler sees this new data.

In other words - what is the correct (simpler, better) way to organize interactive exchange of user data with the Expert Advisor via Windows GUI elements? CChartObjectEdit and CChartObjectButton is, excuse me, some kind of "pornography".


Thank you. Sorry if the question is simple and please poke around where the answer is!

 
papaklass:

Cool.

1. the code now compiles. First change.

Too bad compiling and operability are not the same thing)

input int StopLoss=60;      // Stop Loss
input int TakeProfit=200;   // Take Profit
//--- глобальные переменные
double MFI[];// массив MFI
double DEMA[];// массив DEMA

 bool PositionModify(const string smb,const double SL,const double TP)
  {       
      MqlTradeRequest mrequest={0};
      MqlTradeResult  mresult ={0};
      
      mrequest.action   = TRADE_ACTION_SLTP;
      mrequest.symbol   = smb;
      mrequest.sl       = SL;
      mrequest.tp       = TP;
      
      OrderSend( mrequest, mresult );
      if( mresult.retcode == 10009 || mresult.retcode == 10008 )//запрос выполнен или ордер успешно помещен
      {          
         Alert( "Стопка прошла#:", mresult.order, "!!" );
      }
      else
      {
         Alert( "Стопка не прошла - код ошибки:", GetLastError() );
         return( false );
      }   
   return( true );
  }
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
  {
MFIHandle=iMFI(NULL,0,MFIPeriod,VolumeType);
DEMAHandle=iDEMA(NULL,0,PeriodDEMA,ShiftDEMA,MFIHandle);
if(BolBandsHandle<0 || MFIHandle<0 || DEMAHandle<0)
     {
      Alert("Ошибка при создании индикаторов - номер ошибки: ",GetLastError(),"!!");
      return(-1);
     }
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
 //+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
 ...
   double Ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);            // лучшее предложение на покупку
   double Bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);            // лучшее предложение на продажу
   double SL   = NormalizeDouble(PositionGetDouble(POSITION_SL),4);
   double TP   = NormalizeDouble(PositionGetDouble(POSITION_TP),4);
                        
   bool Buy_Condition_1
   
   bool Buy_Close_1=
   bool Sell_Condition_1=
   
   bool Sell_Close_1=
   
 if(Buy_Condition_1 || Buy_Condition_2)
     { 
       if(Buy_Condition_3 && Buy_Condition_4)
        {
         // есть ли в данный момент открытая позиция на покупку?
         if(Buy_opened)
           {
            Alert("Позиция на покупку имеется");
            return;    // не добавлять к открытой позиции на покупку
           }        
         mrequest.action = TRADE_ACTION_DEAL;    // немедленное исполнение
         mrequest.symbol = _Symbol;              // символ
         mrequest.magic = EA_Magic;              // Magic Number
         mrequest.volume = Lot;                  // количество лотов для торговли
         mrequest.type = ORDER_TYPE_BUY;         // ордер на покупку
         mrequest.type_filling = ORDER_FILLING_FOK;   // тип исполнения ордера - все или ничего

         //--- отсылаем ордер
         OrderSend(mrequest,mresult);
         
         
         
 //------------------------------------------------------------------------------
         PositionModify(Symbol(),NormalizeDouble(Bid - SL*_Point,4),TP*_Point);
 //-------------------------------------------------------------------------------
 
 
 
 
         // анализируем код возврата торгового сервера
         if(mresult.retcode==10009 || mresult.retcode==10008) //запрос выполнен или ордер успешно помещен
           {
            Alert("Buy успешно помещен, тикет ордера #:",mresult.order,"!!");
           }
         else
           {
            Alert("Запрос на установку ордера Buy не выполнен - код ошибки:",GetLastError());
            return;
           }
        }
      } 

if(Buy_Close_1 || Buy_Close_2)
     {
      if(Buy_Close_3)
        {
        // есть ли в данный момент открытая позиция на покупку?
          if(PositionSelect(_Symbol)==true) // есть открытая позиция
           {
            if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
                {
           Alert("Закрываю ордер BUY!!!");                  
                                  
         mrequest.action = TRADE_ACTION_DEAL; // немедленное исполнение
         mrequest.symbol = _Symbol;           // символ
         mrequest.magic = EA_Magic;           // Magic Number
         mrequest.volume = Lot;               // количество лотов для торговли
         mrequest.type = ORDER_TYPE_SELL; // ордер на продажу      
         mrequest.type_filling = ORDER_FILLING_FOK; // тип исполнения ордера - все или ничего
         //--- отсылаем ордер
         OrderSend(mrequest,mresult);
         // анализируем код возврата торгового сервера
         if(mresult.retcode==10009 || mresult.retcode==10008) //запрос выполнен или ордер успешно помещен
           {
            Alert("тикет закрытия Buy #:",mresult.order,"!!");
           }
         else
           {
            Alert("Запрос на установку ордера закрытия Buy не выполнен - код ошибки:",GetLastError());
            return;
           }
        }
      }
    }
  }
 ...
     return; 
}//+------------------------------------------------------------------+end PositionModify
 

Why in the tester the code sets stoplosses and profits but not on the chart?!

I'm starting to freak out as I go along)))

 
Lester:

Why in the tester the code sets stoplosses and profits but not on the chart?!

Starting to freak out along the way )))).

Lester:Zdes put a template, inside there is a modification, and showed how to polzuvatsya.

https://www.mql5.com/ru/forum/6343/page73

If you don't want to do it, you'll have to read the variables correctly.

Стоплос и тейкпрофит в пункти.*Понт = 0.002-ето тейк,ну надо и к добавит.

PositionModify(Symbol(),NormalizeDouble(Bid - SL*_Point,4),TP*_Point);

PositionModify(Symbol(),NormalizeDouble((Bid - SL*_Point),4),NormalizeDouble((Bid + TP*_Point),4));

 
Chino:

Hi, can you tell me if the orders on the signals will be executed if I have my terminal computer switched off?

The developers have promised such a possibility. Not yet.
Reason: