EA opening and closing

 

Hi all,

Need a help with this.
When the EA closes the first Buy trade, it goes crazy.
Am i missing something?

Thx a lot!



int TicketBuy10;
double Lots10 = 1.0;
double Buy10Profit = 200;  // 200.00 = 20.00 pips



int OnInit()
  {
  
   return(INIT_SUCCEEDED);
  }

   
void OnTick()
  {

       
       
         int    TotalBuy10 = 0;
     
       for(int i = OrdersTotal()-1; i >= 0; i--) 
        {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         {
         if(OrderMagicNumber() == 10 && OrderType() == OP_BUY)
          {                               
           TotalBuy10 = TotalBuy10 + 1;  
          }
         }  
        }    
       
        if(TotalBuy10 == 0)
          {
           int OpenBuy10 = OrderSend(Symbol(), OP_BUY, Lots10, Ask, 10, 0, 0,"Buy10", 10, 0, clrBlue);        
          }
         
     
    
      int TotalSell11 = 0;

     
      for(int i = OrdersTotal()-1; i >= 0; i--)
       {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         {
         if(OrderMagicNumber() == 11 && OrderType() == OP_SELL)
          {           
           TotalSell11 = TotalSell11 + 1;  
          }
         }  
       }    
       
       
        if(TotalSell11 == 0)
          {
           int OpenSell11 = OrderSend(Symbol(), OP_SELL, Lots10, Bid, 10, 0, 0,"Sell11", 11, 0, clrRed);        
          }
      
      
      
      
         double OpenPriceBuy10ForClose = 0;
               
          
        for(int i = OrdersTotal()-1; i >= 0; i--)
        {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         {
         if(OrderMagicNumber() == 10 && OrderType() == OP_BUY)
          
          TicketBuy10            = OrderTicket();
          OpenPriceBuy10ForClose = OrderOpenPrice();  
         }  
        }
      
       
          if(Ask > OpenPriceBuy10ForClose + Buy10Profit * Point)
            {
             bool CloseBuy10 = OrderClose(TicketBuy10, Lots10, Bid, 10, clrBlue);
            }
      
      
    }
 
  1. Amirio:
    Hi all,
    
    Need a help with this.
    When the EA closes the first Buy trade, it goes crazy.
    Am i missing something?
    
    Thx a lot!

    Please don't add text inside quoted text or CODE blocks, put it outside.
              MQL4 forum editor problem - MQL4 programming forum (2015)

  2.            int OpenSell11 = OrderSend(Symbol(), OP_SELL, Lots10, Bid, 10, 0, 0,"Sell11", 11, 0, clrRed);      

    Why did you post your MT4 question in the MT5 EA section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
    Next time, post in the correct place. The moderators will likely move this thread there soon.

  3. Check your return codes, and report your errors (including market prices and your variables). Don't look at GLE/LE unless you have an error. Don't just silence the compiler (MT5/MT4+strict), it is trying to help you.
              What are Function return values ? How do I use them ? - MQL4 programming forum (2012)

  4. "goes crazy" is meaningless — just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires — meaningless.
         How To Ask Questions The Smart Way. (2004)
              When asking about code
              Be precise and informative about your problem

    Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

  5.          if(OrderMagicNumber() == 10 && OrderType() == OP_BUY)
    ⋮
             if(OrderMagicNumber() == 11 && OrderType() == OP_SELL)

    Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number/symbol filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
              Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum (2013)
              PositionClose is not working - MQL5 programming forum (2020)
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
              Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
              Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)

    You need one Magic Number for each symbol/timeframe/strategy. Trade current timeframe, one strategy, and filter by symbol requires one MN.

  6.           if(Ask > OpenPriceBuy10ForClose + Buy10Profit * Point)
                {
                 bool CloseBuy10 = OrderClose(TicketBuy10, Lots10, Bid, 10, clrBlue);

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close to a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  7. Why are you checking for take profit and closing the order, instead of just setting it in the OrderSend and letting the server close it? Where is the equivalent for sells?

  8. Where is your SL?

    Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support.

    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)

    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
                Lot value calculation off by a factor of 100 - MQL5 programming forum (2019)