• Latest
  • Trending
  • All
  • Market Updates
  • Cryptocurrency
  • Blockchain
  • Investing
  • Commodities
  • Personal Finance
  • Technology
  • Business
  • Real Estate
  • Finance
Soft Manager – Trading Ideas – 5 August 2025

Beyond OnTick(): Mastering the Full MQL5 Event Model – Trading Systems – 18 September 2025

September 18, 2025
CZ’s Giggle Academy Distances From GIGGLE Amid Price Swings

CZ’s Giggle Academy Distances From GIGGLE Amid Price Swings

November 4, 2025
No, ChatGPT hasn’t added a ban on giving legal and health advice

No, ChatGPT hasn’t added a ban on giving legal and health advice

November 4, 2025
The top 10 products readers bought in October (no. 1 is under $20)

The top 10 products readers bought in October (no. 1 is under $20)

November 4, 2025
Soft Manager – Trading Ideas – 5 August 2025

📊 Understanding Market Liquidity — The Hidden Force Behind Every Trade – Other – 4 November 2025

November 4, 2025
Institutional FX Volumes Hit Three-Month High as Dollar Volatility Drives October Trading

Institutional FX Volumes Hit Three-Month High as Dollar Volatility Drives October Trading

November 4, 2025
Palantir Execs Reveal What Truly Sets Company Apart In AI Race: ‘We Build Software That Works, Not Software That Ought To Work’ – Palantir Technologies (NASDAQ:PLTR)

Palantir Execs Reveal What Truly Sets Company Apart In AI Race: ‘We Build Software That Works, Not Software That Ought To Work’ – Palantir Technologies (NASDAQ:PLTR)

November 4, 2025
Stocks making the biggest moves premarket: IREN, KVUE, CIFR, NGD

Stocks making the biggest moves premarket: IREN, KVUE, CIFR, NGD

November 4, 2025
SNB's Tschudin: We will only use negative rates when necessary

SNB's Tschudin: We will only use negative rates when necessary

November 4, 2025
Head And Shoulders Pattern Says Bitcoin Price Is Headed Below $100,000

Head And Shoulders Pattern Says Bitcoin Price Is Headed Below $100,000

November 4, 2025
Stream Finance Launches Probe After Reporting $93M Loss

Stream Finance Launches Probe After Reporting $93M Loss

November 4, 2025
Which cloud storage service should you buy in 2025? I compared the best options, and here’s my pick

Which cloud storage service should you buy in 2025? I compared the best options, and here’s my pick

November 4, 2025
All Money Will Go On Blockchain

All Money Will Go On Blockchain

November 4, 2025
Tuesday, November 4, 2025
No Result
View All Result
InvestorNewsToday.com
  • Home
  • Market
  • Business
  • Finance
  • Investing
  • Real Estate
  • Commodities
  • Crypto
  • Blockchain
  • Personal Finance
  • Tech
InvestorNewsToday.com
No Result
View All Result
Home Investing

Beyond OnTick(): Mastering the Full MQL5 Event Model – Trading Systems – 18 September 2025

by Investor News Today
September 18, 2025
in Investing
0
Soft Manager – Trading Ideas – 5 August 2025
492
SHARES
1.4k
VIEWS
Share on FacebookShare on Twitter


Most MQL5 coders construct their buying and selling robots round a core trio of features: OnInit() , OnDeinit() , and OnTick() . Whereas this basis is important, it is like making an attempt to prepare dinner a gourmand meal with solely a pot, a pan, and a single burner. The MQL5 setting presents a wealthy occasion mannequin with specialised handlers that may make your Knowledgeable Advisors (EAs) and indicators extra environment friendly, interactive, and highly effective.

By venturing past the fundamentals, you possibly can construct EAs that do not depend on each single tick, create dynamic consumer interfaces instantly on the chart, and even monitor and react to buying and selling exercise from different sources. Let’s discover three of essentially the most highly effective—and underutilized—occasion handlers: OnTimer() , OnChartEvent() , and OnTradeTransaction() .

Ditch the Tick: Constructing EAs with OnTimer()

The OnTick() occasion handler is the default workhorse for many EAs, executing its logic each time a brand new value quote arrives. That is nice for high-frequency methods however is extremely inefficient and pointless for methods designed for larger timeframes like H1, H4, or D1. Why examine your logic a number of instances a second while you solely care in regards to the state of a brand new bar as soon as an hour?

The OnTimer() occasion handler solves this drawback. It permits you to create a customized, periodic set off in your code, fully impartial of incoming ticks. 🕒

How It Works

  1. Set the Timer: In your OnInit() perform, you name EventSetTimer(seconds) . This tells the terminal to start out producing a timer occasion each specified variety of seconds.

  2. Execute the Logic: You place your buying and selling logic contained in the OnTimer() perform. This perform will now be referred to as on the interval you outlined.

  3. Kill the Timer: In your OnDeinit() perform, you will need to name EventKillTimer() to cease the timer occasion when the EA is faraway from the chart. That is essential for stopping useful resource leaks.

Instance: A Non-Ticking EA for Larger Timeframes

Let’s construct a easy EA that checks for a brand new bar on the H1 timeframe each minute, reasonably than on each tick.




#property copyright "Copyright 2025, EAHQ"
#property hyperlink      "https://www.mql5.com/en/customers/michael4308"
#property model   "1.00"


datetime lastBarTime = 0;




int OnInit()
{
   
   EventSetTimer(60);
   Print("Timer EA Initialized. Checking for brand new H1 bar each minute.");
   
   return(INIT_SUCCEEDED);
}



void OnDeinit(const int motive)
{
   
   EventKillTimer();
   Print("Timer EA Eliminated. Timer stopped.");
}



void OnTimer()
{
   
   datetime newBarTime = (datetime)SeriesInfoInteger(_Symbol, PERIOD_H1, SERIES_LASTBAR_DATE);
   
   
   if(newBarTime > lastBarTime)
   {
      
      lastBarTime = newBarTime;
      
      Print("New H1 Bar Detected at: ", TimeToString(newBarTime));
      
      
      
   }
}



void OnTick()
{
  
}

Through the use of OnTimer() , this EA is way more environment friendly. It solely consumes CPU assets as soon as a minute, leaving your terminal extra responsive and decreasing the processing load, which is very vital when operating a number of EAs.


Making Charts Interactive with OnChartEvent()

Have you ever ever needed to let a consumer draw a line on a chart to set a take-profit degree or drag a rectangle to outline a buying and selling zone? The OnChartEvent() handler is your gateway to creating wealthy, interactive chart instruments. 🎨

This perform is a grasp listener that captures a variety of consumer interactions with the chart, reminiscent of mouse clicks, key presses, and—most powerfully—interactions with graphical objects.

How It Works

The OnChartEvent() perform receives a number of parameters, however a very powerful are:

  • id : The kind of occasion that occurred (e.g., a key was pressed, an object was created).

  • lparam , dparam , sparam : Parameters containing detailed details about the occasion. Their that means will depend on the id .

For object interactions, you may usually examine for these occasion IDs:

  • CHARTEVENT_OBJECT_CREATE : Fired when a consumer finishes drawing a brand new object.

  • CHARTEVENT_OBJECT_DRAG : Fired when a consumer drags an object throughout the chart.

  • CHARTEVENT_OBJECT_CLICK : Fired when a consumer clicks on an object.

Instance: Setting a Take-Revenue Stage with a Line

Let’s create an indicator that permits the consumer to attract a horizontal line. The indicator will then learn the worth degree of that line and print it to the Consultants log, simulating how an EA may use it to set a Take-Revenue.




#property copyright "Copyright 2025, EAHQ"
#property indicator_chart_window




void OnChartEvent(const int id,
                  const lengthy &lparam,
                  const double &dparam,
                  const string &sparam)
{
   
   if(id == CHARTEVENT_OBJECT_CREATE)
   {
      
      Print("Object Created: ", sparam);
      
      
      if(ObjectType(sparam) == OBJ_HLINE)
      {
         
         double priceLevel = ObjectGetDouble(0, sparam, OBJPROP_PRICE, 0);
         Print("Take-Revenue degree set by HLine '", sparam, "' at value: ", DoubleToString(priceLevel, _Digits));
         
         
      }
   }
   
   
   if(id == CHARTEVENT_OBJECT_DRAG)
   {
       
       if(ObjectType(sparam) == OBJ_HLINE)
       {
         double priceLevel = ObjectGetDouble(0, sparam, OBJPROP_PRICE, 0);
         Remark("Present TP Stage: ", DoubleToString(priceLevel, _Digits));
       }
   }
}

This easy instance opens up a world of potentialities for creating intuitive, user-friendly buying and selling instruments that bridge the hole between handbook evaluation and automatic execution.


The Final Watchdog: OnTradeTransaction()

What in case your EA must learn about the whole lot occurring in your buying and selling account? This contains handbook trades you place, trades executed by different EAs, and even actions taken by your dealer. The OnTradeTransaction() occasion handler is the last word watchdog, supplying you with real-time perception into all buying and selling exercise. 🕵️

This handler is triggered every time a commerce transaction happens on the account, reminiscent of inserting an order, modifying a stop-loss, closing a place, or a deal being executed.

How It Works

The OnTradeTransaction() perform receives three arguments:

  • trans : An MqlTradeTransaction construction containing detailed details about the transaction (sort, order ticket, value, quantity, and so on.).

  • request : The unique MqlTradeRequest that initiated this transaction.

  • consequence : The MqlTradeResult of executing the request.

You possibly can examine the trans.sort subject to grasp what sort of transaction simply occurred. A standard and really helpful sort is TRADE_TRANSACTION_DEAL_ADD , which alerts {that a} new deal has been added to the account historical past (i.e., a commerce was executed).

Instance: Monitoring and Logging All New Trades

This is an EA that does nothing however monitor the account. When any new commerce (deal) is executed—whether or not by this EA, one other EA, or manually—it logs the small print.




#property copyright "Copyright 2025, EAHQ"
#property model   "1.00"




void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &consequence)
{
   
   if(trans.sort == TRADE_TRANSACTION_DEAL_ADD)
   {
      
      ulong deal_ticket = trans.deal;
      
      
      if(HistoryDealSelect(deal_ticket))
      {
         lengthy deal_type = HistoryDealGetInteger(deal_ticket, DEAL_TYPE);
         lengthy deal_magic = HistoryDealGetInteger(deal_ticket, DEAL_MAGIC);
         double deal_volume = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
         string deal_symbol = HistoryDealGetString(deal_ticket, DEAL_SYMBOL);
         
         
         PrintFormat("New Deal Executed: Ticket #%d, Image: %s, Kind: %s, Quantity: %.2f, Magic: %d",
                     deal_ticket,
                     deal_symbol,
                     (deal_type == DEAL_TYPE_BUY ? "Purchase" : "Promote"),
                     deal_volume,
                     deal_magic);
                     
         
         
         
      }
   }
}


void OnInit() {}
void OnDeinit(const int motive) {}
void OnTick() {}

This handler is extremely highly effective. You possibly can construct:

  • A Commerce Supervisor: An EA that mechanically applies stop-loss and take-profit ranges to any commerce opened on the account, no matter its supply.

  • An Fairness Protector: An EA that displays for brand new offers and closes all open positions if the account drawdown exceeds a sure threshold.

  • A Synchronization Device: An EA that copies trades from one account to a different in real-time.

By mastering these superior occasion handlers, you elevate your MQL5 coding from easy automation to creating really clever, environment friendly, and interactive buying and selling techniques. Go forward and experiment—your buying and selling instruments won’t ever be the identical once more.



Source link

Tags: eventFullMasteringmodelMQL5OnTickSeptemberSystemstrading
Share197Tweet123
Previous Post

Stocks making the biggest moves premarket: NVDA, BABA, WDAY, NFLX

Next Post

Best Amazon Prime Day tablet deals 2025: My 12 favorite sales ahead of October

Investor News Today

Investor News Today

Next Post
Best Amazon Prime Day tablet deals 2025: My 12 favorite sales ahead of October

Best Amazon Prime Day tablet deals 2025: My 12 favorite sales ahead of October

  • Trending
  • Comments
  • Latest
Private equity groups prepare to offload Ensemble Health for up to $12bn

Private equity groups prepare to offload Ensemble Health for up to $12bn

May 16, 2025
The human harbor: Navigating identity and meaning in the AI age

The human harbor: Navigating identity and meaning in the AI age

July 14, 2025
Equinor scales back renewables push 7 years after ditching ‘oil’ from its name

Equinor scales back renewables push 7 years after ditching ‘oil’ from its name

February 5, 2025
Niels Troost has a staggering story to tell about how he got sanctioned

Niels Troost has a staggering story to tell about how he got sanctioned

December 14, 2024
Why America’s economy is soaring ahead of its rivals

Why America’s economy is soaring ahead of its rivals

0
Dollar climbs after Donald Trump’s Brics tariff threat and French political woes

Dollar climbs after Donald Trump’s Brics tariff threat and French political woes

0
Nato chief Mark Rutte’s warning to Trump

Nato chief Mark Rutte’s warning to Trump

0
Top Federal Reserve official warns progress on taming US inflation ‘may be stalling’

Top Federal Reserve official warns progress on taming US inflation ‘may be stalling’

0
CZ’s Giggle Academy Distances From GIGGLE Amid Price Swings

CZ’s Giggle Academy Distances From GIGGLE Amid Price Swings

November 4, 2025
No, ChatGPT hasn’t added a ban on giving legal and health advice

No, ChatGPT hasn’t added a ban on giving legal and health advice

November 4, 2025
The top 10 products readers bought in October (no. 1 is under $20)

The top 10 products readers bought in October (no. 1 is under $20)

November 4, 2025
Soft Manager – Trading Ideas – 5 August 2025

📊 Understanding Market Liquidity — The Hidden Force Behind Every Trade – Other – 4 November 2025

November 4, 2025

Live Prices

© 2024 Investor News Today

No Result
View All Result
  • Home
  • Market
  • Business
  • Finance
  • Investing
  • Real Estate
  • Commodities
  • Crypto
  • Blockchain
  • Personal Finance
  • Tech

© 2024 Investor News Today