Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 415

 
Ekburg:


OrderProfit()

If you need exactly the last order to open, then go through all the orders and choose the one with the latest open time, then use the above function, which will return to you the net profit of this order


How I get an answer just in time, just at the moment when I find a solution. :)
Pips_Proffit_Last_Pos = p - PriceOpenLastPos;
But thanks anyway!
 

Ekburg К сожалению времени и возможности написать Вам готовый код нет, так как я на работе нахожусь))

You do not search by history, but by current positions, here is a logical chain based on which you can try to write code:

[block of working with muwings and placing an order]

1 remember the ticket and the magic number of the placed order

2 monitor the number of orders and if there are no orders in the market (it means that our order has been closed), then go to point3 or monitor this specific order until its close time is more than zero, in which case we exclude points 3 and 4

3 find our order

4 find out if it is closed

5 find out how it was closed

6 if it was closed through a stop, set another order different from it in the direction


//+------------------------------------------------------------------+
//|                                                          123.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"


extern double Lots = 0.1;
extern double TakeProfit = 100;
extern double StopLoss = 100;       
extern double TrailingStop = 50;
extern double Margincutoff = 100;   
extern double MagicNumber = 12345;
extern double TradeSizePercent = 5;
extern int Slippage = 10;


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
  
  int Crossed (double line1, double line2)
  {
  static int last_direction=0;
  static int current_direction=0;
  
  if (line1>line2)current_direction=1;// пересечение вверх
  if (line1<line2)current_direction=2;// пересечение вниз
  
  if (current_direction!=last_direction)//изменения произошли
  {
  last_direction=current_direction;
  return(last_direction);
  }
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
    int cnt, ticket, total, totalhistory, memoryticket;
    double shortEMA, longEMA;
    
    if(Bars<100) 
     {
     Print("Bars less than 100");
     return(0);
     }
     shortEMA=iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0);
     longEMA=iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0);
     int isCrossed=Crossed(shortEMA, longEMA);
//----
   total=OrdersTotal();
   if(total<1) 
     {
      // нет открытых ордеров
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // проверяем пересечение МА для открытия позиции на покупку
      if(isCrossed==1)
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-StopLoss*Point,Ask+TakeProfit*Point,"МА",12345,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
            memoryticket= OrderTicket();// запомнили тикет
            Print("BUY order opened : ",OrderOpenPrice());
           }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
        //проверяем пересечение МА для открытия позиции на продажу
        if(isCrossed==2)
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+StopLoss*Point,Bid-TakeProfit*Point,"MA",12345,0,Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
            memoryticket= OrderTicket();// запомнили тикет
            Print("SELL order opened : ",OrderOpenPrice());
           }
         else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
         return(0); 
        }  
//----начинаем искать закрытые ордера

         //инициализация параметров
  
  int old_order_type;
 
   
  RefreshRates();
  
  //нет открытых ордеров - ищем в истории закрытых ордеров последний закрытый именно этим советником ордер 
  for ( totalhistory = OrdersHistoryTotal() - 1; totalhistory >= 0; totalhistory-- ) 
  {
     if ( OrderSelect(totalhistory, SELECT_BY_TICKET, MODE_HISTORY) && OrderTicket() == memoryticket && OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol() )
     {
         old_order_type = OrderType();
         if ( OrderProfit()<0 ) //последний закрытый советником ордер был убыточным, значит, следующий ордер открываем в направлении, противоположном закрытому с убытком
         {
                break; //прекращаем поиск
         }
     }
  }
  //если раньше покупали, то теперь продаем
  if ( old_order_type == OP_BUY )
  {
  ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+StopLoss*Point,Bid-TakeProfit*Point,"MA",12345,0,Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
            memoryticket= OrderTicket();// запомнили тикет
            Print("SELL order opened : ",OrderOpenPrice());
           }
         else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
 //если раньше продавали, то теперь покупаем
  if ( old_order_type == OP_SELL )
  {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-StopLoss*Point,Ask+TakeProfit*Point,"МА",12345,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
            memoryticket= OrderTicket();// запомнили тикет
            Print("BUY order opened : ",OrderOpenPrice());
           }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
   return(0);
  }
//+------------------------------------------------------------------+
This is what I have. It really opens 3 lots. I am really screwed. Can you correct the code? What's wrong?
 
I'm sick and tired of asking these questions (incredibly nerve-wracking, pi****, sorry (fucking variables I can't find (mostly annoying, what I can't find myself))).

Which variable is responsible for the current price value?
I searched documentation, there's nothing except Bid, Ask, POINT_HIGH, POINT_LOW.
Does such variable even exist?
 
Link_x:
I'm sick and tired of asking these questions (incredibly nerve-wracking, pi****, sorry (fucking variables I can't find (mostly annoying, what I can't find myself))).

Which variable is responsible for the current price value?
I searched documentation, there's nothing except Bid, Ask, POINT_HIGH, POINT_LOW.
Does such variable even exist?
Have you noticed how the price changes in the "Market Watch" window? You can see there the Bid and Ask prices. The first one is used to sell and the second one to buy.
 
Link_x:

How timely I get an answer, just when I find a solution. :)
The solution is: "Take your time to ask questions". And, considering that you don't always get competent answers... :)))
 
khorosh:
Have you noticed how the price changes in the Market Watch window? There you can see the Bid and Ask - these are the current prices. The first is used to sell and the second to buy.

Exactly!
Forgot such a little thing!
 
TarasBY:
The solution is: "Don't rush to ask questions". And, considering that you don't always get competent answers... :)))
Yes, yes. :)
 
Link_x:
That's right!!!
Forgot such a little thing!!!

You answer correctly, like a real student in an exam: you can't say I don't know - you have to say I forgot))).
 
Link_x:
Yeah, yeah. :)

Maybe you should try answering other people's questions rather than asking your own. The benefits are much greater (Up to a point), certainly the benefits to yourself
 
Vinin:

Maybe you should try answering other people's questions rather than asking your own. The benefits are much greater (up to a point), of course the benefits to yourself
I have to know everything in this field (like you or Yury) in order to answer questions from beginners.
If I do not give the right answer, I will be "beaten". :)

khorosh:
You answer correctly, like a real student in an exam:- you can't say I don't know - you have to say I forgot))).

I laughed. :)
Reason: