Camovia Tray™

Blog · Knowledge

What Are Arrays in MQL4? (And Why Most Traders Get Them Wrong)

Camovia Tray Team · 2026-09-15

When I first started writing MQL4 scripts, I thought arrays were just fancy lists—nice to have, but not essential. I’d store price data in separate variables: high1, high2, high3... up to high20. It worked, sort of. Then I wanted to calculate the average high of the last 50 bars, and my code turned into a monster. That was my first wake-up call.

The real trap, though, isn't just about syntax. It's about when and why you use arrays in actual trading. Most tutorials teach you how to declare an array, but they don't tell you the painful lessons that come from using them wrong—especially when you're juggling multiple currency pairs, timeframes, or trying to keep your terminal responsive. Let's fix that.

What Actually Is an Array in MQL4?

In plain terms, an array is a block of memory that holds multiple values of the same type, all under one name. Instead of price1, price2, price3, you have price[0], price[1], price[2]. The number in brackets is the index, and in MQL4, it always starts at zero.

The beauty is that you can loop through them. Want to check if the current price broke above the highest high of the last 20 bars? With an array, that's a four-line loop. Without it, you're writing twenty if statements like it's 1999.

But arrays in MQL4 have a split personality. There are static arrays (fixed size, declared at compile time) and dynamic arrays (size can change while the program runs, using ArrayResize). Most beginners stick to static arrays because they're simpler. That's fine until you don't know how many elements you'll need—like when you're reading custom CSV files or processing variable-length indicator buffers.

The trap here is thinking you have to choose one or the other. You don't. You start with a dynamic array, resize it when you know the data size, and then work with it just like a static one. That flexibility is what makes MQL4 powerful for real-time market analysis.

The First Misconception: Arrays Are Just for Storing History

This is the mistake that eats CPU cycles. Many traders load an entire history of 1000 bars into an array, loop through it every tick, and wonder why their terminal stutters.

An array isn't a database. It's a temporary workspace. If you're reading Close[1], Close[2], Close[3] directly from MQL4's built-in timeseries arrays, you're already using arrays—just the efficient kind. The real question is: do you need a custom array at all?

You use custom arrays when you need to transform data. For example, calculating a moving average of the spread, storing order open prices for a basket strategy, or tracking the equity curve of your open positions. In these cases, arrays are perfect because you're creating new information that isn't directly available from the terminal.

The bad habit is copying the entire Close[] array into your own buffer just to run a calculation that MQL4 already provides natively (like iMA). That's redundant memory usage and slower execution. Instead, use CopyClose or CopyBuffer to pull exactly what you need, when you need it.

The Hidden Killer: Out-of-Bounds and Dynamic Sizing

Here's the scenario that ruined my first EA: I declared double myArray[10], then wrote a loop that went up to i<20. No error message. No warning. Just a silent crash when the EA hit that loop, because MQL4 doesn't automatically check array bounds in all contexts. The terminal froze, I forced a restart, and I spent hours debugging.

The solution is boring but non-negotiable: always use ArraySize to know your limits, and if you're using dynamic arrays, check the return value of ArrayResize. It returns -1 if it fails. Don't ignore it.

And here's the nuance that most guides skip: dynamic arrays lose their contents when resized unless you use the ArrayResize third parameter. That's right—ArrayResize(myArray, newSize, reserve) keeps existing values. Without that third argument, you're wiping your data. That's fine if you're starting fresh, but terrible if you're appending new tick data to an ongoing series.

The professional pattern is to pre-allocate with ArrayResize once based on your expected maximum, then use a separate counter variable to track how many elements are actually filled. That way, you avoid repeated resizing (which is slow) and keep your data intact.

When Arrays Become a Performance Trap

Every tick, your EA runs OnTick(). If inside that function you're declaring large arrays, resizing them, or copying massive buffers, you're burning milliseconds. On a volatile pair like GBPJPY during news, that latency can make your entry slip by several pips.

The better approach: declare your arrays globally (outside any function) so they're allocated once. Then inside OnTick(), just update the values you need. For indicator buffers, use SetIndexBuffer in init() to bind arrays directly to indicator lines—that way, MQL4 manages the memory for you.

Also, be mindful of ArrayCopy. It's convenient, but copying 500 elements every tick adds up. If you only need the last 20, copy just those. Use ArrayCopy(source, dest, 0, 0, 20) to limit the range.

The Real-World Trap: Mixing Timeframes and Symbols

Here's where arrays get genuinely tricky. You want to monitor EURUSD on M5 and GBPUSD on H1 simultaneously. You create two arrays for highs, two for lows, two for closes... and suddenly your code is a tangled mess of iHigh, iLow, iClose calls.

The clean solution: use a two-dimensional array priceData[symbolIndex][barIndex], or better, an array of structures. MQL4 supports structures (struct) that can hold multiple fields—so you can have struct PriceInfo { double high; double low; double close; }; and then an array of that struct.

But wait—there's a performance twist. Accessing a two-dimensional array is slightly slower than a one-dimensional one because of the double indexing. If speed is critical, flatten your data: use a single array where index i corresponds to bar number, and store all values sequentially. That's over-optimization for most strategies, but it's good to know when you're building high-frequency systems.

The MT4 Bridge Connection: What Arrays Have to Do with Camovia Tray

By now you might be thinking: "This is all great for coding, but I'm a trader, not a developer. Why should I care?"

Here's the practical angle. Let's say you've built an EA that uses arrays to track open positions, calculate average entry prices, or monitor floating P&L across a basket of orders. That's sophisticated logic—but it's still locked inside your MT4 terminal. Every time you want to check your overall exposure, you have to open the full platform, switch to the terminal window, and scroll through orders.

That's where Camovia Tray enters the picture. It's a tray tool that turns your MT5 or MT4 into a system-tray extension—so you can check live quotes and manage positions (view open positions + close them with a click) directly from the tray, without bringing the entire MT4 window to the foreground.

Why does that matter for arrays? Because Camovia Tray reads the same data structures your EA uses—the position arrays, the price arrays—but it does so without injecting code into your EA. It's a companion utility, not a competitor. You keep your custom array logic inside your EA for execution, and you use Camovia Tray for quick monitoring and management.

The real pain point is when you're running multiple EAs on different charts, each with its own internal arrays for tracking orders. To see your total risk, you'd normally have to switch charts, check each EA's output, or rely on MT4's built-in terminal which shows positions but not your custom calculated metrics (like average price per symbol or grouped exposure). Camovia Tray doesn't replace that—it solves a different problem: visual access without visual clutter.

If you're the type of trader who keeps MT4 minimized because you don't need to watch every tick, but you still want to know when a key level is breached or when your basket hits a certain P&L, Camovia Tray's floating order panel gives you that glanceable summary. It's not about arrays—it's about workflow. The arrays are doing the heavy lifting in the background; Camovia Tray is your heads-up display.

And because all data stays local—100% on your machine—there's no privacy concern. Your array-calculated metrics never leave your computer.

Practical Exercise: An Array Pattern That Won't Break

Let's walk through a typical use case: tracking the last 50 high values to determine if the current price is making a new high.

  1. Declare a global dynamic array: double highBuffer[];
  2. In OnInit(), set a reasonable size: ArrayResize(highBuffer, 50, 10); (the 10 reserves extra slots for future resizing without reallocation).
  3. In OnTick(), shift values: for(int i=49; i>0; i--) highBuffer[i] = highBuffer[i-1]; then assign highBuffer[0] = High[0];
  4. Check new high: if(High[0] > highBuffer[ArrayMaximum(highBuffer, 0, 50)]) — wait, ArrayMaximum returns the index, not the value. So you do: int maxIdx = ArrayMaximum(highBuffer, 0, 50); if(High[0] > highBuffer[maxIdx]) // new high detected

This pattern avoids the overhead of copying entire arrays and keeps your tick handler lightweight.

But what if you want to track highs for multiple symbols? Then you'd either loop through symbol names inside OnTick() or use a two-dimensional array. The golden rule: test your EA on historical data first. Run the Strategy Tester with visual mode off and watch the performance graph. If your EA takes longer than 20-30 milliseconds per tick, arrays are likely the bottleneck.

The Most Overlooked Feature: Array Functions

MQL4 has a rich set of array functions that most people ignore:

  • ArraySort – sorts ascending or descending.
  • ArrayMaximum / ArrayMinimum – find extremes without writing loops.
  • ArrayBsearch – binary search for sorted arrays (fastest way to find a value).
  • ArrayInsert / ArrayRemove – insert or delete elements in the middle (but be careful, these are slower than you think).

Using these correctly can reduce your code by 70% and make it more readable. The mistake is writing custom loops for things that are already optimized in the MQL4 runtime. Binary search, for example, is O(log n) compared to O(n) for a linear scan. If you're searching a 1000-element array on every tick, that's a massive difference.

Final Takeaway: Arrays Are Tools, Not Goals

Don't use arrays just because they're there. Use them when you need to maintain a state over time, compute aggregates, or compare current data with historical snapshots. For simple tasks—like checking the current close price—use MQL4's built-in timeseries variables (Close[0], Open[0]). For complex calculations—like a custom volatility measure across 200 bars—arrays are your friend.

And when your strategy scales to multiple instruments or complex position tracking, remember that the terminal itself is just one part of your toolkit. Tools like Camovia Tray can help you step back and monitor what matters, without cluttering your screen or risking accidental exposure. It's not about replacing code—it's about making the results of that code more accessible, in a private, local-first way.

If you're still writing price1, price2, price3... stop. Learn arrays properly, test them rigorously, and you'll wonder how you ever traded without them. Just don't forget: an array is only as good as the logic that fills it. Keep that logic clean, keep it fast, and keep your terminal responsive—because the market won't wait for your code to finish looping.

MT4/MT5 Tray Assistant

Silent tracking, one-click close - check quotes and manage positions right from the tray.

Download Camovia Tray

Frequently Asked Questions

Where are the privacy policy and user agreement?

The "Privacy" and "EULA" links in the footer of this site, with GDPR/CCPA information included.

What is Camovia Tray?

A tray assistant for MT4/MT5 - silent tracking, one-click close: hover the system tray to check the latest quotes and manage open positions (click an order to close it), hide the MT5/MT4 main window in one click, and keep quote and position data entirely on your computer.

Do I need MT5/MT4 installed? Does the terminal need to stay open?

Yes. Camovia Tray reads quote and position data from your locally running MT5/MT4 terminal, so the terminal must be installed, running, and logged in. MT5 connects directly with no EA; MT4 needs the bundled bridge EA attached once (one-click copy in Settings, then double-click in the Navigator - see the docs).

Are my quotes and positions uploaded anywhere?

No. Quote and position data is read 100% from your local MT5/MT4 terminal and never leaves your computer. See the privacy policy for details.

Popular Symbols Trading Hours

Open/close times, weekend hours & live market status: