Discussion of article "Step-by-Step Guide to Writing an Expert Advisor in MQL5 for Beginners" - page 29

 
The file inside the download is wrong, please fix it.
 

Hello everyone,

I currently have Samuel's EA running on a demo account and I am quite satisfied. Good programming!

It shows good trading from time to time, but it has a weakness:

SELL options pile up at turning points in the valley of the charts and the same at corresponding peaks with BUY options, which then first hit the books massively as negatives. I would like to reprogramme this, i.e. BUYs in the day, SELLs at the peak, and so far my attempts have failed. I also only have a rudimentary knowledge of MQL5.

Can anyone help me?

SG and many thanks!

 

This usually doesn't work because the other points at which the EA takes a profitable position are then also reversed ....

But read this:

EA-freelancer specifications : https://www.mql5.com/en/articles/4368
Indi : https://www.mql5.com/en/articles/4304
How to Order a Trading Robot in MQL5 and MQL4 : https://www.mql5.com/en/articles/117

With the hints there you can specify your idea more precisely, be it just for you to see if it works, or be it to ask someone to do it, with or without payment.

So formulieren Sie das Pflichtenheft eines Auftrages für einen Handelsroboter
So formulieren Sie das Pflichtenheft eines Auftrages für einen Handelsroboter
  • www.mql5.com
Handeln Sie nach Ihrer eigenen Strategie? Wenn Sie Ihre Handelsregeln formalisieren und als Algorithmus für ein Programm beschreiben können, wäre es doch besser, Ihren Handel einem automatisierten Expert Advisor anzuvertrauen. Ein Roboter braucht weder Schlaf noch Nahrung und ist keinen menschlichen Schwächen unterworfen. In diesem Artikel zeigen wir Ihnen, wie Sie, um einen Handelsroboter im Freelance-Service in Auftrag zu geben, das sogenannte Pflichtenheft erstellen.
 

Hello everyone (Especially the dear author)

I coded along with this article. I enjoyed it a lot and learned a lot from it. 

Thank you for writing such an informative article.

However I have a problem. My EA did not place any orders. I downloaded the author's code but it did not place any orders too.

Since the article is 13 years old, I assume that the code is now outdated. Can anyone help me out? 

My code is in the file below. Thanks anyone in advance.

Files:
myFirstEA.mq5  25 kb
 

Hello, I want to warn you that I am a beginner, so don't swear much if anything)

I wanted to create an Expert Advisor through the generator (and everything seems to be fine, but there is one but)

I would like to open a deal not immediately after the previous one closes, but for example after one candle,

I tried to write something, but in the end it gives an error.

Can anyone help with this, or indicate what the error and how to fix it?

and here is the actual code:


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

//| ParExpert.mq5 |

//| Copyright 2022, MetaQuotes Ltd. | |

//| https://www.mql5.com |

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

#property copyright "Copyright 2022, MetaQuotes Ltd."

#property link "https://www.mql5.com"

#property version "1.00"

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

//| Include |

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

#include <Expert\Expert.mqh>

//--- available signals

#include <Expert\Signal\SignalSAR.mqh>

//--- available trailing

#include <Expert\Trailing\TrailingFixedPips.mqh>

//--- available money management

#include <Expert\Money\MoneyFixedLot.mqh>

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

//| Inputs |

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

//--- inputs for expert

input string Expert_Title = "ParExpert"; // Document name

ulong Expert_MagicNumber = 24195; //

bool Expert_EveryTick = false; //

//--- inputs for main signal

input int Signal_ThresholdOpen = 10; // Signal threshold value to open [0...100]

input int Signal_ThresholdClose = 0; // Signal threshold value to close [0...100]

input double Signal_PriceLevel = 0.0; // Price level to execute a deal

input double Signal_StopLevel = 500; // Stop Loss level (in points)

input double Signal_TakeLevel = 70; // Take Profit level (in points)

input int Signal_Expiration = 4; // Expiration of pending orders (in bars)

input double Signal_SAR_Step = 0.02; // Parabolic SAR(0.02,0.2) Speed increment

input double Signal_SAR_Maximum = 0.2; // Parabolic SAR(0.02,0.2) Maximum rate

input double Signal_SAR_Weight = 0.6; // Parabolic SAR(0.02,0.2) Weight [0...1.0]

//--- inputs for trailing

input int Trailing_FixedPips_StopLevel = 0; // Stop Loss trailing level (in points)

input int Trailing_FixedPips_ProfitLevel= 10; // Take Profit trailing level (in points)

//--- inputs for money

input double Money_FixLot_Percent = 10.0; // Percent

input double Money_FixLot_Lots = 0.1; // Fixed volume

//--- inputs for trade cooldown

input int Expert_TradeCooldown = 1; // Cooldown period between trades (in bars)

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

//| Global expert object |

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

CExpert ExtExpert;

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

//| Initialisation function of the expert |

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

int OnInit()

{

//--- Initializing expert

if (!ExtExpert.Init(Symbol(), Period(), Expert_EveryTick, Expert_MagicNumber))

{

//--- failed

printf(__FUNCTION__ + ": error initializing expert");

ExtExpert.Deinit();

return (INIT_FAILED);

}


//--- Creating signal

CExpertSignal *signal = new CExpertSignal;

if (signal == NULL)

{

//--- failed

printf(__FUNCTION__ + ": error creating signal");

ExtExpert.Deinit();

return (INIT_FAILED);

}


//---

ExtExpert.InitSignal(signal);

signal.ThresholdOpen(Signal_ThresholdOpen);

signal.ThresholdClose(Signal_ThresholdClose);

signal.PriceLevel(Signal_PriceLevel);

signal.StopLevel(Signal_StopLevel);

signal.TakeLevel(Signal_TakeLevel);

signal.Expiration(Signal_Expiration);


//--- Creating filter CSignalSAR

CSignalSAR *filter0 = new CSignalSAR;

if (filter0 == NULL)

{

//--- failed

printf(__FUNCTION__ + ": error creating filter0");

ExtExpert.Deinit();

return (INIT_FAILED);

}

signal.AddFilter(filter0);


//--- Set filter parameters

filter0.Step(Signal_SAR_Step);

filter0.Maximum(Signal_SAR_Maximum);

filter0.Weight(Signal_SAR_Weight);


//--- Creation of trailing object

CTrailingFixedPips *trailing = new CTrailingFixedPips;

if (trailing == NULL)

{

//--- failed

printf(__FUNCTION__ + ": error creating trailing");

ExtExpert.Deinit();

return (INIT_FAILED);

}


//--- Add trailing to expert (will be deleted automatically))

if (!ExtExpert.InitTrailing(trailing))

{

//--- failed

printf(__FUNCTION__ + ": error initialising trailing");

ExtExpert.Deinit();

return (INIT_FAILED);

}


//--- Set trailing parameters

trailing.StopLevel(Trailing_FixedPips_StopLevel);

trailing.ProfitLevel(Trailing_FixedPips_ProfitLevel);


//--- Creation of money object

CMoneyFixedLot *money = new CMoneyFixedLot;

if (money == NULL)

{

//--- failed

printf(__FUNCTION__ + ": error creating money");

ExtExpert.Deinit();

return (INIT_FAILED);

}


//--- Add money to expert (will be deleted automatically))

if (!ExtExpert.InitMoney(money))

{

//--- failed

printf(__FUNCTION__ + ": error initialising money");

ExtExpert.Deinit();

return (INIT_FAILED);

}


//--- Set money parameters

money.Percent(Money_FixLot_Percent);

money.Lots(Money_FixLot_Lots);


//--- Check all trading objects parameters

if (!ExtExpert.ValidationSettings())

{

//--- failed

ExtExpert.Deinit();

return (INIT_FAILED);

}


//--- Tuning of all necessary indicators

if (!ExtExpert.InitIndicators())

{

//--- failed

printf(__FUNCTION__ + ": error initialising indicators");

ExtExpert.Deinit();

return (INIT_FAILED);

}


//--- Initialise last trade time variable

datetime lastTradeTime = 0;

ExtExpert.SetVariable("LastTradeTime", lastTradeTime);


//--- ok

return (INIT_SUCCEEDED);

}

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

//| Deinitialisation function of the expert |

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

void OnDeinit(const int reason)

{

ExtExpert.Deinit();

}

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

//| "Tick" event handler function |

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

void OnTick()

{

//--- Check time since last trade

datetime lastTradeTime = ExtExpert.GetVariable("LastTradeTime");

int cooldownBars = Bars - ExtExpert.GetBarShiftByTime(Symbol(), Period(), lastTradeTime);


if (cooldownBars < Expert_TradeCooldown)

{

//--- Trade cooldown period not elapsed, skip opening new trade

return;

}


ExtExpert.OnTrade();

}

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

//| "Trade" event handler function |

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

void OnTrade()

{

ExtExpert.OnTrade();

}

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

//| "Timer" event handler function |

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

void OnTimer()

{

ExtExpert.OnTimer();

}

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

Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2023.05.27
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 
Joosy #:

Hello everyone😊

@Mario31415927

This is simply because in the ticker, every time a new period or new bar (whatever) the variables:

are reset, regardless of whether positions are already open or not.

This can be found relatively quickly in the code.

However, the question arises as to whether this was intended, and if so, how are all positions closed again?

Perhaps I don't understand the TRADE_ACTION_DEAL order type in this context?

The trade order process could also simply be adapted to the trade class Trade. Like for example:

Best regards:-)

Read: https://www.mql5.com/en/articles/232

This explains the difference and the relationships between orders, positions and deals. The latter reflect the booking processes on the broker side.

Handelsereignisse in MetaTrader 5
Handelsereignisse in MetaTrader 5
  • www.mql5.com
Eine Überwachung des aktuellen Status eines Handels-Account bedeutet offene Positions und Order kontrollieren zu können. Bevor ein Handelssignal zu einem Abschluss wird, sollte es vom Client-Terminal als Anfrage zum Handels-Server geschickt werden, wo es in eine Order-Warteschlange gestellt wird und auf seine Bearbeitung wartet. Eine Anfrage vom Handels-Server annehmen, sie löschen, wenn sie abläuft oder auf ihrer Grundlage einen Abschluss ausführen - alle diese Handlungen haben Handelsereignisse zur Folge, und der Handels-Server informiert das Terminal entsprechend darüber.
 
Carl Schreiber #:

Read: https://www.mql5.com/en/articles/232

This explains the difference and the relationships between orders, positions and deals. The latter reflect the booking processes on the broker side.

Hello Carl,

thanks for the tip!

However, I must correct myself.

It is true that the variables are reset for each new time period:

   bool Buy_opened = false, Sell_opened = false; // variables to hold the result of the opened position

But they are subsequently set again if there is a position accordingly.

   if(PositionSelect(_Symbol) == true) { // we have an opened position

      if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {

         Buy_opened = true;  //It is a Buy

      }

      if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {

         Sell_opened = true; // It is a Sell

      }

   }

However, I am experiencing the phenomenon that the buy (POSITION_TYPE_BUY) is correctly queried, but not the sell (POSITION_TYPE_SELL). The variable is simply no longer set?

I have to debug the code step by step. This can only be a logical error😉

Einen Expert Advisor mit Hilfe des MQL5 Objekt-orientierten Programmieransatzes schreiben
Einen Expert Advisor mit Hilfe des MQL5 Objekt-orientierten Programmieransatzes schreiben
  • www.mql5.com
Dieser Beitrag beschäftigt sich mit dem Objekt-orientierten Ansatz, um das zu machen, was wir bereits im Artikel "Schrittweiser Leitfaden zum Schreiben eines Expert Advisors in MQL5 für Anfänger" getan haben - einen einfachen Expert Advisor erstellen. Die meisten Menschen glauben, das sei schwer, doch ich darf Ihnen versichern: wenn Sie diesen Beitrag gelesen haben, dann können Sie Ihren eigenen Objekt-orientierten Expert Advisor schreiben.
 
Joosy #:
Sell_opened = true; // It is a Sell

Oh dear, I'm so on the ball today.

It is only queried once. That's the error;-)

All positions should be searched as follows;

   bool Buy_opened = false, Sell_opened = false; // variables to hold the result of the opened position
   
   for(int i=0; i < PositionsTotal(); i++) {
      ticket = PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == EA_Magic) {
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) { 
            Buy_opened = true; 
         }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) { 
            Sell_opened = true; 
         }
      }   
   }
 

It was indeed an error, it seems to be a web file.

I rewrote it myself based on the content and uploaded it. I don't know if there are any details because I'm new to this. Hope it helps.

Files:
my_first_ea.mq5  12 kb
 

Tester - "Unsupported filling mode"

Tried on 3 different brokers. Whats the problem?