Why doesn't work my EA ?

 

Hello ,

thanks in advance,

i don't know how to ask in the mql5 area!

ok this is a MQL5 code that i write with some example and copy from a similar code i tried to build a EA that Close Partial lot in determinate price , i use this for futures markets , 

specifically symbol, Micro Nasdaq, this should close half of my lot , but is not doing it !

Can you help to fix this code? 

thanks...

#include<Trade\Trade.mqh>

CTrade trade;
input int PartialClosePoint = 500;
input double PartialClosePercent = 0.5;
input double Lots = 2;


void OnTick()
 {
 
  double Ask,Bid; 
  ulong Spread; 
   Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK); 
   Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID); 
   Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD); 
   double posOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
//--- Output values in three lines 
  // Comment(StringFormat("Show prices\nAsk = %G\nBid = %G\nSpread = %d",Ask,Bid,Spread)); 
   Comment("Show prices\nAsk -parttialClose X point =",posOpenPrice-PartialClosePoint*_Point
   ,"\nBid mas PartialClose X Point=", posOpenPrice+PartialClosePoint*_Point,"\nSpread = ", Spread, "\n _Punto = ",_Point,"\n Punto()= ", Point(),
   "\n Ask = ",Ask,"\n Bid = ", Bid, "\n Open Price= ",posOpenPrice);
 
 
   // to buy position    
  Take_parte_position();

 }
 
 void Take_parte_position()
 {
 
 double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
 bid = NormalizeDouble(bid,_Digits);
 double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
 ask = NormalizeDouble(ask,_Digits);
 
 // from the number of positions count down to zero
 for (int i =PositionsTotal()-1; i>=0; i--)
  {
   // get the ticket number for the current position
   ulong pos_ticke=PositionGetTicket(i);
   
   if (PositionSelectByTicket(pos_ticke))
   {
      double posOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
      double posVolume = PositionGetDouble(POSITION_VOLUME);
      ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      
      
      if (posVolume == Lots) 
      {
           double lotsToClose = posVolume * PartialClosePercent;
           lotsToClose = NormalizeDouble(lotsToClose,2);
           
      if (posType == POSITION_TYPE_BUY)
      { 
       if(bid > posOpenPrice + PartialClosePoint*_Point)
       {
          if (trade.PositionClosePartial(pos_ticke,lotsToClose))
            {
             Comment("Pos", pos_ticke, "Was closed partially like Winner Trade");
            }
           
          }
        }
      
      else
       if (posType == POSITION_TYPE_SELL)
      {
       if(ask < posOpenPrice - PartialClosePoint*_Point)
       {
             
            if (trade.PositionClosePartial(pos_ticke,lotsToClose))
            {
              Comment("Pos", pos_ticke, "Was closed partially like Winner Trade");
            }
           
          }
          }
          }
       }
      }
   }
   
Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Symbol Properties
Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Symbol Properties
  • www.mql5.com
Symbol Properties - Environment State - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

Important parts are missing! Maybe you should start here:

Quickstart for newbies: https://www.mql5.com/en/articles/496
and: https://www.mql5.com/en/articles/100
cookbook: https://www.mql5.com/en/search#!keyword=cookbook
cookbook: https://www.mql5.com/en/search#!keyword=cookbook
or https://www.mql5.com/en/search#!keyword=Tips%20from%20a%20professional%20programmer&module=mql5_module_articles
https://www.mql5.com/en/forum/9950
Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5 and is ready for you - copy & paste the fastest way to program!
(BTW ChatCPT does the same)

Quick Start: Short Guide for Beginners
Quick Start: Short Guide for Beginners
  • www.mql5.com
Hello dear reader! In this article, I will try to explain and show you how you can easily and quickly get the hang of the principles of creating Expert Advisors, working with indicators, etc. It is beginner-oriented and will not feature any difficult or abstruse examples.
 
Carl Schreiber #:

Important parts are missing! Maybe you should start here:

Quickstart for newbies: https://www.mql5.com/en/articles/496
and: https://www.mql5.com/en/articles/100
cookbook: https://www.mql5.com/en/search#!keyword=cookbook
cookbook: https://www.mql5.com/en/search#!keyword=cookbook
or https://www.mql5.com/en/search#!keyword=Tips%20from%20a%20professional%20programmer&module=mql5_module_articles
https://www.mql5.com/en/forum/9950
Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5 and is ready for you - copy & paste the fastest way to program!
(BTW ChatCPT does the same)

Thanks, Carl Schreiber !

I will

 
You have to finish the for loop you have, so he knows how many Trades you have opened.
 
Here's where to start https://www.mql5.com/en/articles/100
Step-By-Step Guide to writing an Expert Advisor in MQL5 for Beginners
Step-By-Step Guide to writing an Expert Advisor in MQL5 for Beginners
  • www.mql5.com
The Expert Advisors programming in MQL5 is simple, and you can learn it easy. In this step by step guide, you will see the basic steps required in writing a simple Expert Advisor based on a developed trading strategy. The structure of an Expert Advisor, the use of built-in technical indicators and trading functions, the details of the Debug mode and use of the Strategy Tester are presented.
 
Carl Schreiber #:

Important parts are missing! Maybe you should start here:

Quickstart for newbies: https://www.mql5.com/en/articles/496
and: https://www.mql5.com/en/articles/100
cookbook: https://www.mql5.com/en/search#!keyword=cookbook
cookbook: https://www.mql5.com/en/search#!keyword=cookbook
or https://www.mql5.com/en/search#!keyword=Tips%20from%20a%20professional%20programmer&module=mql5_module_articles
https://www.mql5.com/en/forum/9950
Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5 and is ready for you - copy & paste the fastest way to program!
(BTW ChatCPT does the same)

Hello, today I learned this tutorial

Step-By-Step Guide to writing an Expert Advisor in MQL5 for Beginners

, I learned something, at least different functions of using them than in MQL4, and it turns out that the EA doesn't work either, because it didn't work I don't know, but I practiced my touch typing, :),

I'll try the Another tutorial and I'm going to try to code something different, to be able to get partial close, generally everyone uses the Trade class, but it didn't work for me! Thank you,

//+------------------------------------------------------------------+
//|                                                  My_First_EA.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//--- input parameters
input int      StopLoss=300;
input int      TakeProfit=300;
input int      ADX_Period=8;
input int      MA_Period=8;
input int      EA_Magic=12345;
input double   Adx_Min=22.0;
input double   Lot=0.5;

//---Others parameters

int adxHandle; // handle for our ADX indicator
int maHandle;   // handle for our Moving Average indicator
double plsDI[],minDI[],adxVal[];  // Dynamic arrays to hold the values of +DI, -DI and ADX values for each bars
double maVal[]; // Dynamic array to hold the values of Moving Average for each bars
double p_close;  // Variable to store the close value of a bar
int STP, TKP;     // To be used for Stop Loss & Take Profit values



//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Get handle for ADX indicator
   adxHandle=iADX(NULL,0,ADX_Period);
   //--- Get the handle for Moving Average indicator
   maHandle=iMA(_Symbol,_Period,MA_Period,0,MODE_EMA,PRICE_CLOSE);
   //--- What if handle returns Invalid Handle
   if(adxHandle<0 || maHandle<0)
   {
    Alert("Error Creatting Handles for indicator - errors: ",GetLastError(),"!!");  
   }
   
   //--- Let us handle currency pairs with 5 or 2 digit prices instead of 4
   STP = StopLoss;
   TKP = TakeProfit;
   if(_Digits==5 || _Digits==2)
    {
     STP = STP*10;
     TKP = TKP*10;
    }
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---Release our indicator handles 
   IndicatorRelease(adxHandle);
   IndicatorRelease(maHandle);
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
// Do we have enough bars to work with
  if(Bars(_Symbol,_Period)<60)// if total bars is less than 60 bars
   {
    Alert("We have less than 60 bars, EA will now exit!!");
    return;
   }
// We will use the static Old_Time variable to serve the bar time.
// At each OnTick execution we will check the current bar time with the saved one.
// If the bar time isn't equal to the saved time, it indicates that we have a new tick. 
   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;
   
// copying the last bar time to the element New_Time[0]   
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0)  // ok, the data has been copied successfully
    {
     if(Old_Time!=New_Time[0])// if old time isn't equal to new bar time
      {
       if(MQLInfoInteger(MQL_DEBUG)) Print("We have new bar here ",New_Time[0]," old time ",Old_Time);
       
       Old_Time=New_Time[0];   // saving bar time
       
      }
    }     
   else
    {
     Alert("Error in copiying historical times data, error =",GetLastError());
     ResetLastError();
     return;
    }
//--- EA should only check for new trade if we have a new bar
  if(IsNewBar==false)
   {
    return;
   }
    
//--- Do we have enough bars to work with
   int Mybars=Bars(_Symbol,_Period);
   if(Mybars<60)  // if total bars is less than 60 bars
    {
     Alert("We have less than 60 bars, EA will now exit!!");
     return;
    }  
    
//--- Define some MQL5 Structures we will use for our trade    
   MqlTick latest_price;      // To be used for getting recent/latest price quotes
   MqlTradeRequest mrequest;  // To be used for sending our trade requests
   MqlTradeResult mresult;    // To be used to get our trade results
   MqlRates mrate[];          // To be used to store the prices, volumes and spread of each bar
   ZeroMemory(mrequest);      // Initialization of mrequest structure
   
/*
   Let's make sure our arrays values for the Rates, ADX Values and Ma values
   is store serially similar to the timeseries array
*/      
// the rates arrays
   ArraySetAsSeries(mrate,true);
// the ADX DI+values array
   ArraySetAsSeries(plsDI,true);
// the ADX DI-values array
   ArraySetAsSeries(minDI,true);
// the ADX values arrays
   ArraySetAsSeries(adxVal,true);
// the MA-8 values arrays
   ArraySetAsSeries(maVal,true); 
   
//--- Get the last price quote using the MQL5 MqlTick Structure
   if(!SymbolInfoTick(_Symbol,latest_price))
    {
     Alert("Error getting the latest price quote - error:",GetLastError(),"!!");
     return;
    }                 
    
//--- Get the details of the latest 3 bars   
   if(CopyRates(_Symbol,_Period,0,3,mrate)<0)
    {
     Alert("Error copying rates/history data - error:" ,GetLastError(),"!!");
     return;
    }   
  
 //---Example The mrate[] array now contains all the price, time, volumes and spread information for bars 0 , 1 and 2. 
 //--- Therefore to get the details of any bar, we will use the following:
 // mrate[bar_number].bar_property
   
 // mrate[1].time  // Bar 1 Start time
 // mrate[1].open  // Bar 1 Open price
 // mrate[0].high  // Bar 0 (current bar) high price, etc
   
  
   
//--- Copy the new values of our indicators to buffers (arrays) using the handle  
   if(CopyBuffer(adxHandle,0,0,3,adxVal)<0  || CopyBuffer(adxHandle,1,0,3,plsDI)<0
      || CopyBuffer(adxHandle,2,0,3,minDI)<0) 
     {
      Alert("Error copying ADX indicator Buffers - error:",GetLastError(),"!!");
      return;
     }   
   if(CopyBuffer(maHandle,0,0,3,maVal)<0)
     {
      Alert("Error copying Moving Average indicator buffers - error:",GetLastError());
      return;
     } 
   
//--- we have no errors, so continue
//--- Do we have positions opened already?
   bool Buy_opened=false;   // variable to hold the result of Buy opened position
   bool Sell_opened=false;  // variable to hold the result of Sell opened position 
   
   if(PositionSelect(_Symbol)==true)  // we have an opened position
    {
     if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
      {
       Buy_opened = true; // it is a Buy
      }
      else
      {
       Sell_opened = true; // it is a Sell  
      }
    }
   
   
// Copy the bar close price for the previous bar prior to the current bar, that is Bar 1
   p_close=mrate[1].close;   // bar 1 close price
   
/*
    1. Check for a long/Buy Setup : MA-8 increasing upwards, 
    previous price close above it, ADX > 22, +DI > -DI
*/
//--- Declare bool type variables to hold our Buy Conditions

   bool Buy_Condition_1 = (maVal[0]>maVal[1]) && (maVal[1]>maVal[2]); // MA-8 Increasing upwards
   bool Buy_Condition_2 = (p_close > maVal[1]);                       // previuos price closed above MA-8
   bool Buy_Condition_3 = (adxVal[0]>Adx_Min);                        // Current ADX value greater than minimum value (22)  
   bool Buy_Condition_4 = (plsDI[0]>minDI[0]);                        // +DI greater than -DI
   
//--- Putting all together   
   if(Buy_Condition_1 && Buy_Condition_2)
      {
       if(Buy_Condition_3 && Buy_Condition_4)
         {
            //any opened Buy position?
            if(Buy_opened)
               {
                  Alert("We already have a Buy Position!!!");
                  return;  //Don't open a new Buy Position
               }
               mrequest.action = TRADE_ACTION_DEAL;                                 // immediate order execution
               mrequest.price = NormalizeDouble(latest_price.ask,_Digits);          // latest ask price
               mrequest.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits);// Stop Loss
               mrequest.tp = NormalizeDouble(latest_price.ask + TKP*_Point,_Digits);// Take Profit
               mrequest.symbol = _Symbol;                                           // currency pair
               mrequest.volume = Lot;                                               // number of lots to trade
               mrequest.magic = EA_Magic;                                           // Order Magic Number                                      
               mrequest.type = ORDER_TYPE_BUY;                                      // Buy Order                                     
               mrequest.type_filling = ORDER_FILLING_FOK;                           // Order execution type
               mrequest.deviation = 100;                                            // Deviation from current price
               //--- Send order
               OrderSend(mrequest,mresult);
      

 // get the result code
   if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
      {
         Alert("A Buy order has been sucessfully placed with Ticket#:",mresult.order,"!!");
      }
   else
      {
         Alert("The Buy order request could not be completedd -error:",GetLastError());
         ResetLastError();
         return;
      }  
      
     }
    } 
/*
    2. Check for a Short/Sell Setup : MA-8 decreasing downwards, 
    previous price close below it, ADX > 22, -DI > +DI
*/
//--- Declare bool type variables to hold our Sell Conditions
   bool Sell_Condition_1 = (maVal[0]<maVal[1]) && (maVal[1]<maVal[2]);         
   bool Sell_Condition_2 = (p_close <maVal[1]);
   bool Sell_Condition_3 = (adxVal[0]>Adx_Min);
   bool Sell_Condition_4 = (plsDI[0]>minDI[0]);

//--- Putting all together   
   if(Sell_Condition_1 && Sell_Condition_2)
      {
         if(Sell_Condition_3 && Sell_Condition_4)
         {
            if(Sell_opened)
            {
               Alert("We already have a Sell position!!!");
               return;  //Don't open a new Sell Position
            }
            mrequest.action = TRADE_ACTION_DEAL;                                 // immediate order execution
            mrequest.price = NormalizeDouble(latest_price.bid,_Digits);          // latest Bid price
            mrequest.sl = NormalizeDouble(latest_price.bid + STP*_Point,_Digits);// Stop Loss
            mrequest.tp = NormalizeDouble(latest_price.bid - TKP*_Point,_Digits);// Take Profit
            mrequest.symbol = _Symbol;                                           // currency pair
            mrequest.volume = Lot;                                               // number of lots to trade
            mrequest.magic = EA_Magic;                                           // Order Magic Number
            mrequest.type = ORDER_TYPE_SELL;                                     // Sell Order                                   
            mrequest.type_filling = ORDER_FILLING_FOK;                           // Order execution type
            mrequest.deviation = 100;                                            // Deviation from current price
            //--- Send order
            OrderSend(mrequest,mresult);   
      
   
 // get the result code
   if(mresult.retcode==10009 || mresult.retcode==10008)  //Request is completed or order placed
      {
       Alert("The Sell order has been succesfully placed with Ticket#:",mresult.order,"!!");
      }  
      else
         {
          Alert("The Sell order request could not be completed -error:",GetLastError());
          ResetLastError();
          return;
         }
        }
       }  
     }
              

//+------------------------------------------------------------------+


I leave you the EA, what did you recommend to do and I would also like to know why It does not work ?