EA for partial closing of open trade

 

Hello experts

I was looking for a way to set (manually) in advance target levels for an open trade on MT4 so it can be automatically partially closed and so far it seems it is not possible on MT4 itself unless I use and EA.

Being not a MQL4 programmer expert, I wrote this code and I would like to get some comment/feedback/corrections/improvements from anyone of you, experts.

Basic idea is:

  • once trade is already opened and add EA, you set manually ticket number
  • you can select if target criteria will be based on price or amount of PIPs
  • you can select if closing criteria will be based on lot size or percentage of total position

(there is a variable called "instanceID" and I took from IBFX EA that does this - but that only work on IBFX MT4 - but I have not figured out how to manage it. It is supposed to work on a way that if MT4 platform crashed, memory of what have been already done won't be lost)

I will just start to test if it works or not, but any  comment/feedback/corrections/improvements in advance will be more than welcome!!! 

 
rafo05:

Hello experts

I was looking for a way to set (manually) in advance target levels for an open trade on MT4 so it can be automatically partially closed and so far it seems it is not possible on MT4 itself unless I use and EA.

Being not a MQL4 programmer expert, I wrote this code and I would like to get some comment/feedback/corrections/improvements from anyone of you, experts.

I'm not an expert but I have some observations:

  • why is fnCheckTargetCriteria()  type bool when it actually returns nothing ?
  • you don't adjust for 4/5 Digit Brokers,  on a 4 Digit Broker a Pip is the last digit or point,  on a 5 Digit Broker a Pip = 10 points 
  • if you are selecting your order you can use OrderClosePrice() to close a Buy and a Sell so you can use the same code for both
  • make sure your OrderClose() has worked and report any errors if it failed:  What are Function return values ? How do I use them ?
  • you should use constants to make your code more readable,  for example  

#define TGT_CRITERIA_PRICE 1
#define TGT_CRITERIA_PIPS  2 

#define CLOSE_CRITERIA_LOT         1
#define CLOSE_CRITERIA_PERCENTAGE  2

// then use .  .  . 

if (TargetCriteria == TGT_CRITERIA_PRICE)  //Target Criteria: 1 = Price
         {
            if (priceBID >= TargetLevel_1 && TargetLevel == 0)

 This is nasty and won't work for a lotstep of 0.2 . . . 

lots = StrToDouble(DoubleToStr(dLots, lotdigits));

use some simple maths . . .  MathMod() would help, but it is broken . . .  https://www.mql5.com/en/forum/129832

 

Thanks for showing your code and asking for help with it,  it makes a nice change from those who just want someone else to learn for them and code for them and refuse to make any effort themselves :-) 

Reason: