preview
Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color

Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color

MetaTrader 5 — Integration |
47 0
Sandro Begashvili
Sandro Begashvili

Contents


Introduction: the page after Part 3

Real documents need more than text. They also need headers, borders, colored panels, logos, and separators. These elements require a drawing system that can work alongside text rather than relying on it. After Part 3, the library can generate a valid, paginated PDF using four files: PdfBuffer.mqh (which manages bytes, with Length() returning the current offset), PdfWriter.mqh (which manages object numbers, recorded offsets, and the cross-reference table), PdfValidate.mqh (Part 2's validator), and PdfDefines.mqh (shared constants).

However, three limitations become apparent as soon as we want to create a properly designed page. Everything on the page is still text; coordinates are measured from the bottom-left corner, opposite to the coordinate system normally used in page layout; and all content is black unless a color is explicitly specified.

This part addresses all three limitations. The page adopts a top-left origin, with the y-coordinate increasing downward, and supports millimeters as a measurement unit. A path model provides the foundation for drawing lines and shapes, while a dedicated color type stores color components as bytes and writes them as fractions. The coordinate conversion follows one simple rule:

Flip the page once, at the top of the stream, and never flip a value again.

The implementation introduces four new files. CPdfSurface defines everything the library can draw, CPdfPage implements that interface by writing PDF content stream operators, CPdfDocument manages the pages and assembles the final file using the Part 3 writer, and PdfColor.mqh introduces the SPdfColor structure and a small color palette. In total, this adds three classes and one structure. The writer itself remains unchanged because all drawing operations are written into a content stream, which is simply a sequence of bytes measured by WriteStream().

Two existing files are modified, and four new files are added:

File Written in Changed here
PdfValidate.mqh Part 2 no
PdfWriter.mqh Part 3 no
PdfDefines.mqh Part 3 yes: units, enums, the Bezier constant
PdfBuffer.mqh Part 3 yes: five PutOp helpers
PdfColor.mqh Part 4 new
PdfSurface.mqh Part 4 new
PdfPage.mqh Part 4 new
PdfDocument.mqh Part 4 new

The take-away is a letterhead in your own brand color. Figure 1 is the other demo, a one-page sampler of the primitives, and there is not a single character of text on it — text is the whole of the next part.

Figure 1. The shapes from Demo04_Shapes.mq5, opened in a PDF viewer.


Units, coordinates and the single flip

PDF measures in points: one point is 1/72 of an inch, so an inch is 72 points and a millimeter is 72 / 25.4 = 2.8346 points. An A4 sheet of 210 × 297 millimeters is therefore:

  • width: 210 / 25.4 × 72 = 595.276 points
  • height: 297 / 25.4 × 72 = 841.890 points

Part 1 rounded these to 595 and 842 because a person was typing them; the library now uses the three-decimal values, which is as far as the writer formats a number.

The origin is the surprise. PDF puts (0,0) in the bottom-left corner with y growing upward — good for graphs, bad for documents, because a page is read from the top down and nearly every layout rule in print is stated from the top edge: "the header is 30 mm tall", "the first line starts 20 mm below the top edge".

Figure 2. One point on an A4 page, measured from two different corners.

In PDF's own system the point in Figure 2 is 72 points from the left and 741.89 points from the bottom; in the one this library gives you, 72 from the left and 100 from the top. The y value is the page height minus the other, and that subtraction is the whole problem: performed in every drawing call it fills the code with height - y, and every one is a place where a rectangle ends up upside down.

PDF has an operator that changes the coordinate system itself: cm, "concat matrix". It takes six numbers a b c d e f, and every coordinate (x, y) that follows is moved before anything is drawn:

  • x' = a·x + c·y + e
  • y' = b·x + d·y + f

With the six numbers 1 0 0 -1 0 841.89 that becomes:

  • x' = 1·x + 0·y + 0 = x
  • y' = 0·x − 1·y + 841.89 = 841.89 − y

The subtraction is now the viewer's job, done once for every coordinate in the stream. So the first line CPdfPage writes into every content stream is:

1 0 0 -1 0 841.89 cm

After that line 0 0 is the top-left corner and 72 100 is 72 points from the left and 100 from the top. Nothing in the library subtracts from the height again. That holds for what goes through the library; a stream written by hand, or coordinates taken from a y-up source, still have to be converted by whoever brings them in.

The flip is a matrix rather than an arithmetic rule because matrices compose: cm multiplies into the current matrix instead of replacing it, so a move to a center point followed by a rotation works in the system the previous line set up. Subtracting inside every call would need every matrix mirrored as well — a correction in many places instead of one.

Saving and restoring the state

A transformation stays in force to the end of the stream, so it needs an undo. q saves the complete graphics state — the current matrix, the colors, the line width, the dash pattern and the clip area — and Q restores the last saved one. They form a stack, so a rotated shape is written as:

q
1 0 0 1 452 424 cm
0.866 0.5 -0.5 0.866 0 0 cm
... the shape ...
Q

After the Q the rotation and the move are gone. This is also the only way to undo a clip, so the library wraps every temporary change in a q/Q pair. One cost comes with the flip: it turns text upside down too, and the next part pays that back with a second flip inside the text matrix.


By hand first: from operators to methods

Before any class, here is a drawing written by hand: a content stream that puts a blue band across the top of an A4 page and a red line under it.

0.122 0.435 0.922 rg
0 742 595 100 re
f
0.812 0.133 0.18 RG
4 w
72 700 m
523 700 l
S

Three fractions and rg set the fill color, re adds a rectangle to the path and f fills it; then RG sets the stroke color (uppercase for lines, lowercase for areas), w the line width, and m, l and S move the pen, add a line and stroke it. The next section takes the operators one group at a time.

Note the y = 742 on the second line: the band is 100 points tall and its bottom edge has to be 100 points below the top of an 842-point sheet. With the flip installed the same band is 0 0 595.276 100 re, which reads as what it is. You can try the stream without any new code — in Part 3's Demo03_HelloWriter.mq5, replace the five lines that build the content buffer with these eight, one content.PutLine() call each. Part 2's validator will still report no problems, which is a useful reminder: it checks the structure of the file and never looks inside a content stream, so it would say the same about a stream that drew the band in the wrong place.


Paths, painting and the two winding rules

Every shape in a PDF is drawn in two steps. First you build a path, and nothing appears while you do it; then one painting operator decides what happens to it. The construction operators are few:

Operator Operands What it adds to the path
m x y starts a new subpath at (x, y)
l x y a straight line to (x, y)
c x1 y1 x2 y2 x3 y3 a cubic Bezier curve to (x3, y3)
h none a straight line back to the start of the subpath
re x y w h a whole closed rectangle

And the painting operators:

Operator Result
S stroke: draw the outline with the stroke color and line width
f fill: paint the inside with the fill color
B fill, then stroke, in one operator
f*, B* the same, with the even-odd rule (next section)
n paint nothing, and end the path

Figure 3. The same four construction lines, ended by four painting operators.

All four columns of Figure 3 build the same triangle with m l l h; only the last operator differs. B draws the outline on top of the fill, and n draws nothing at all — which is what makes clipping possible. The sequence W n means "use this path as the new clip area and do not paint it", and from then on anything outside it is cut off; the sampler stops a set of stripes at the edge of a rounded box that way, and the letterhead stops a group of rings at the edge of its header band. A path may also hold several subpaths, since every m starts a new one, and the single operator at the end paints all of them — which is how the letterhead draws its three fold marks with one S.

Filling a rectangle is obvious; filling a path that crosses itself is not, because some areas are enclosed twice. The only difference between f and f* is which rule decides what counts as inside.

Figure 4. The same star path, filled by f on the left and by f* on the right.

Both rules draw a ray from the point being tested to somewhere outside the shape. The even-odd rule (f*) counts the edges it crosses: odd means inside, even means outside, so the center of the star in Figure 4 is crossed twice and becomes a pentagon-shaped hole. The nonzero rule (f) also looks at the direction of each edge, adding 1 for one direction and subtracting 1 for the other; the star is drawn by joining every second point of a pentagon, so both edges run the same way, 1 + 1 = 2, and the center is inside.

For a simple shape the two agree, and the library's default is the nonzero rule, which is also PDF's. The even-odd rule is the easy way to cut a hole: a large circle and a smaller one inside it as two subpaths of one path, filled with f*, give a ring. That is how a donut chart is drawn in a later part.


Strokes, and the circle that is not a circle

A stroke has more settings than its color. Four operators control its shape:

  • w sets the width in points. A width of 0 means "the thinnest line the device can draw", which is one pixel on screen and almost invisible on a good printer. Do not use it for anything you want to see.
  • J sets the cap: how an open line ends.
  • j sets the join: how two segments meet at a corner.
  • d sets the dash pattern.

Figure 5. Three caps and three joins, with the path shown as a thin line.

The thin white line inside each shape in Figure 5 is the path; the gray area is what the stroke paints around it. Butt (0 J) cuts the stroke flat at the end point, round (1 J) adds a half circle beyond it and square (2 J) half a square. Hence the number that surprises people: a 94-point line with a 9-point square cap covers 94 + 4.5 + 4.5 = 103 points, so a table grid drawn that way pokes out past its corners.

On the right, miter (0 j) extends the outer edges until they meet, round (1 j) puts a circle over the corner and bevel (2 j) cuts it flat; beyond a miter limit of 10 line widths PDF draws a bevel instead, so a sharp angle cannot grow an endless spike. The dash operator takes an array and a phase: [6 3] 0 d is "6 on, 3 off, start at the beginning", [] 0 d switches dashes off, and the library takes the two numbers of an on/off pair.

Round shapes are a different matter, because PDF has no circle operator and no arc operator either: it has straight lines and cubic Bezier curves, so every round shape drawn as a vector path is almost round. A cubic Bezier starts at P0, ends at P3 and is pulled toward the control points P1 and P2 without passing through them. For a quarter circle of radius 1 from (1, 0) to (0, 1) they sit on the tangent lines, P1 = (1, k) and P2 = (k, 1), and the only question is how large k must be.

Figure 6. The control points of a quarter circle, at k = 0.5523 of the radius.

We find it by making the middle of the curve land on the circle. At t = 0.5 the curve is at:

  • B(0.5) = (P0 + 3·P1 + 3·P2 + P3) / 8

Take the x coordinate: (1 + 3·1 + 3·k + 0) / 8 = (4 + 3k) / 8, and the middle of a quarter circle is at 45 degrees, where x = cos 45° = 0.70711:

  • (4 + 3k) / 8 = 0.70711
  • 4 + 3k = 5.65685
  • k = 1.65685 / 3 = 0.55228

The exact form is 4/3 × (√2 − 1) ≈ 0.55228475, and the library keeps it as PDF_KAPPA. The curve is then exactly on the circle at the start, the middle and the end, and between them it bulges outward by at most 0.0273% of the radius — 0.014 mm on a 50 mm radius. To confirm that bound rather than take it on trust, tabulate √(x(t)² + y(t)²) over a few thousand values of t: the maximum sits at t = (3 − √3)/6 ≈ 0.2113 and its mirror, where the radius is 1.00027253. Four such curves make a circle, and a rounded rectangle joins four straight edges with four of them.


Color, and the MQL5 trap

PDF has no color type either, only operators that take numbers between 0 and 1: rg three of them for red, green and blue, g one for gray, k four for a printing press. People think in bytes instead — #1F6FEB in a style guide, C'31,111,235' in MQL5 — so the library stores bytes and converts them only when it writes an operator:

  • 0x1F = 31, and 31 / 255 = 0.122
  • 0x6F = 111, and 111 / 255 = 0.435
  • 0xEB = 235, and 235 / 255 = 0.922

so PdfHex(0x1F6FEB) becomes 0.122 0.435 0.922 rg in the stream.

Figure 7. The same blue as a hex triplet and as an MQL5 color value.

Figure 7 shows the one trap in this conversion, and it is worth knowing before it costs you an afternoon. A hex triplet from a designer is written red first: 0x1F6FEB, with red in the high byte. The MQL5 color type stores the same blue blue first: C'31,111,235' is the integer 0xEB6F1F. The middle byte is the same in both, so the mistake is easy to miss — pass an MQL5 color to PdfHex() and the blue band comes out orange. Hence two functions, PdfHex() for hex triplets and PdfFromMql() for MQL5 colors, the second of which the letterhead uses on its color inputs. Their shifts are mirror images of each other:

//+------------------------------------------------------------------+
//|                                                     PdfColor.mqh |
//+------------------------------------------------------------------+
#ifndef PDF5_COLOR_MQH
#define PDF5_COLOR_MQH

#include "PdfDefines.mqh"

//+------------------------------------------------------------------+
//| SPdfColor                                                        |
//+------------------------------------------------------------------+
struct SPdfColor
  {
   uchar             r;   // red, 0..255
   uchar             g;   // green, 0..255
   uchar             b;   // blue, 0..255
  };

//+------------------------------------------------------------------+
//| PdfRgb                                                           |
//+------------------------------------------------------------------+
SPdfColor PdfRgb(const uchar red, const uchar green, const uchar blue)
  {
   SPdfColor c;
   c.r = red;
   c.g = green;
   c.b = blue;
   return(c);
  }

//+------------------------------------------------------------------+
//| PdfHex                                                           |
//+------------------------------------------------------------------+
SPdfColor PdfHex(const uint rrggbb)
  {
   SPdfColor c;
   c.r = (uchar)((rrggbb >> 16) & 0xFF);
   c.g = (uchar)((rrggbb >> 8) & 0xFF);
   c.b = (uchar)(rrggbb & 0xFF);
   return(c);
  }

//+------------------------------------------------------------------+
//| PdfFromMql                                                       |
//+------------------------------------------------------------------+
SPdfColor PdfFromMql(const color value)
  {
   SPdfColor c;
   c.r = (uchar)(value & 0xFF);
   c.g = (uchar)((value >> 8) & 0xFF);
   c.b = (uchar)((value >> 16) & 0xFF);
   return(c);
  }

The rest of the file is small, and the attachment prints it in full. PdfMix(a, b, t) blends two colors channel by channel, so PdfMix(PDF_WHITE, brand, 0.06) is the brand color at 6% strength — the pale fill in the letterhead's footer. PdfLuma() weights the channels 0.299, 0.587 and 0.114, because the eye is most sensitive to green and least to blue, and PdfContrastInk() compares that luma with 150 and answers black or white, which is how the logo tile stays visible on any band color. It is a one-threshold heuristic, not a contrast measurement: a design that has to meet an accessibility target needs a proper contrast-ratio check. A small palette closes the file — PDF_INK, PDF_PANEL, PDF_BLUE, PDF_GREEN, PDF_RED and a few more — so that the demos look consistent without inventing their own colors.


Architecture: the surface, the page and the document

Four files implement all of that. What follows is the shape of each one and the places where the code is not obvious from its name; the one-line bodies are named rather than printed, and the full sources are in the attachment.

PdfDefines.mqh and CPdfBuffer

PdfDefines.mqh gains the unit constants PDF_MM, PDF_CM and PDF_INCH, the Bezier constant PDF_KAPPA, and five enumerations: ENUM_PDF_PAGE_SIZE and ENUM_PDF_ORIENTATION for the paper, ENUM_PDF_PAINT for the painting operators, and ENUM_PDF_CAP and ENUM_PDF_JOIN for the stroke. The cap and join values are PDF's own numbers, so a value can be cast straight into the stream; ENUM_PDF_PAINT members map to operators instead, and CPdfPage::Paint() does that. The rounded page sizes from Part 3 stay for the Part 3 scripts.

A content stream is almost entirely one shape of line: a few numbers and an operator — 50 98 62 46 re, 0.122 0.435 0.922 rg. CPdfBuffer therefore gains five helpers, PutOp1 to PutOp6, one per number count. PutOp2 is the whole pattern: PutReal(a), a space, PutReal(b), then PutLine(" " + op). Every number goes through Part 3's PutReal(), which turns 595.2756 into 595.276 and 0.00001 into 0 rather than an exponent PDF cannot read.

CPdfSurface: the drawing seam

CPdfSurface is an abstract base class that lists everything the library can draw and draws nothing: the geometry of the drawing area, the graphics state, the three transforms, the four path primitives, Paint() and Clip(), and four shapes. It exists because a PDF page is not the only thing worth drawing on: a chart written against the surface will also draw on a raster backend added later as one new class. The methods are virtual with empty bodies rather than pure virtual, which keeps a partial backend compilable at the price of not being an interface in the strict sense — a backend that forgets a method still compiles and silently discards those calls, so a new surface is worth running against the sampler demo. IsVector() lets a caller ask what it is drawing on and simplify a chart for a raster target.

Six convenience methods — FillRect(), StrokeRect(), FillRoundRect(), Line(), HLine() and FillCircle() — are not virtual, because they are built from the primitives above and are the same for every backend. FillRect() is the whole idea in three calls: SetFillColor(c), Rect(x, y, w, h), Paint(PDF_PAINT_FILL). They are only as correct as the primitives underneath, but almost every line of the demos uses one of them.

CPdfPage: one operator per primitive

CPdfPage implements the surface for PDF. It owns one content stream and a copy of the page size, because the flip needs the height, and Content() hands that buffer to the document when the file is written. Init() clears the stream and installs the flip, so the cm from earlier is the first line of every page:

//+------------------------------------------------------------------+
//| CPdfPage::CPdfPage                                               |
//+------------------------------------------------------------------+
CPdfPage::CPdfPage(void)
  {
   m_width = 0.0;
   m_height = 0.0;
  }

//+------------------------------------------------------------------+
//| CPdfPage::Init                                                   |
//+------------------------------------------------------------------+
void CPdfPage::Init(const double width, const double height)
  {
   m_width = width;
   m_height = height;
   m_content.Clear();

   InstallFlip();
  }

//+------------------------------------------------------------------+
//| CPdfPage::InstallFlip                                            |
//+------------------------------------------------------------------+
void CPdfPage::InstallFlip(void)
  {
   m_content.PutOp6(1, 0, 0, -1, 0, m_height, "cm");
  }

For an A4 page that writes 1 0 0 -1 0 841.89 cm, and 792 instead of 841.89 for Letter. The graphics state methods are one line each:

//+------------------------------------------------------------------+
//| CPdfPage::Save                                                   |
//+------------------------------------------------------------------+
void CPdfPage::Save(void)
  {
   m_content.PutLine("q");
  }

//+------------------------------------------------------------------+
//| CPdfPage::Restore                                                |
//+------------------------------------------------------------------+
void CPdfPage::Restore(void)
  {
   m_content.PutLine("Q");
  }

//+------------------------------------------------------------------+
//| CPdfPage::SetFillColor                                           |
//+------------------------------------------------------------------+
void CPdfPage::SetFillColor(const SPdfColor &c)
  {
   m_content.PutOp3(c.r / 255.0, c.g / 255.0, c.b / 255.0, "rg");
  }

//+------------------------------------------------------------------+
//| CPdfPage::SetStrokeColor                                         |
//+------------------------------------------------------------------+
void CPdfPage::SetStrokeColor(const SPdfColor &c)
  {
   m_content.PutOp3(c.r / 255.0, c.g / 255.0, c.b / 255.0, "RG");
  }

//+------------------------------------------------------------------+
//| CPdfPage::SetLineWidth                                           |
//+------------------------------------------------------------------+
void CPdfPage::SetLineWidth(const double w)
  {
   m_content.PutOp1(w, "w");
  }

//+------------------------------------------------------------------+
//| CPdfPage::SetLineCap                                             |
//+------------------------------------------------------------------+
void CPdfPage::SetLineCap(const ENUM_PDF_CAP cap)
  {
   m_content.PutOp1((double)cap, "J");
  }

//+------------------------------------------------------------------+
//| CPdfPage::SetLineJoin                                            |
//+------------------------------------------------------------------+
void CPdfPage::SetLineJoin(const ENUM_PDF_JOIN join)
  {
   m_content.PutOp1((double)join, "j");
  }

This is where the bytes become fractions, c.r / 255.0; SetLineCap() and SetLineJoin() only cast the enum, which works because its values are PDF's own. The dash pattern is the one state call that is not a PutOp, because it writes an array:

//+------------------------------------------------------------------+
//| CPdfPage::SetDash                                                |
//+------------------------------------------------------------------+
void CPdfPage::SetDash(const double on, const double off)
  {
   if(on <= 0.0)
     {
      m_content.PutLine("[] 0 d");
      return;
     }

   m_content.PutText("[");
   m_content.PutReal(on);
   m_content.PutText(" ");
   m_content.PutReal(off);
   m_content.PutLine("] 0 d");
  }

SetDash(0, 0) writes [] 0 d, a solid line; the demos call it after every dashed section, because the pattern is part of the graphics state. The three transforms are the three most common matrices:

//+------------------------------------------------------------------+
//| CPdfPage::Translate                                              |
//+------------------------------------------------------------------+
void CPdfPage::Translate(const double dx, const double dy)
  {
   m_content.PutOp6(1, 0, 0, 1, dx, dy, "cm");
  }

//+------------------------------------------------------------------+
//| CPdfPage::Scale                                                  |
//+------------------------------------------------------------------+
void CPdfPage::Scale(const double sx, const double sy)
  {
   m_content.PutOp6(sx, 0, 0, sy, 0, 0, "cm");
  }

//+------------------------------------------------------------------+
//| CPdfPage::Rotate                                                 |
//+------------------------------------------------------------------+
void CPdfPage::Rotate(const double degrees)
  {
//--- In a y-down system this matrix turns clockwise on screen, which is
//--- what a caller who passes a positive angle expects
   double r = degrees * M_PI / 180.0;
   double c = MathCos(r);
   double s = MathSin(r);
   m_content.PutOp6(c, s, -s, c, 0, 0, "cm");
  }

Rotate() writes cos sin -sin cos 0 0, which turns counterclockwise in PDF's y-up world and therefore clockwise on screen after our flip — what most people expect from a positive angle in a y-down system. Since all three write a cm, they compose: translate to a center, then rotate, and the shape turns around that center. The four path primitives are one line each as well: MoveTo(), LineTo(), CurveTo() and ClosePath() append m, l, c and h with their coordinates in front, unchanged — the payoff of the flip, since there is no m_height - y anywhere in the class to forget. Painting and clipping are where something is decided:

//+------------------------------------------------------------------+
//| CPdfPage::Paint                                                  |
//+------------------------------------------------------------------+
void CPdfPage::Paint(const ENUM_PDF_PAINT how)
  {
//--- The starred operators use the even-odd rule instead of the nonzero
//--- rule. The difference only shows when a path overlaps itself:
//--- nonzero fills the overlap, even-odd leaves a hole. That is how a
//--- donut, a washer, or a letter O with a real counter is drawn.
   switch(how)
     {
      case PDF_PAINT_FILL:
         m_content.PutLine("f");
         break;
      case PDF_PAINT_STROKE:
         m_content.PutLine("S");
         break;
      case PDF_PAINT_BOTH:
         m_content.PutLine("B");
         break;
      case PDF_PAINT_FILL_EVENODD:
         m_content.PutLine("f*");
         break;
      case PDF_PAINT_BOTH_EVENODD:
         m_content.PutLine("B*");
         break;
      default:
         m_content.PutLine("n");
         break;
     }
  }

//+------------------------------------------------------------------+
//| CPdfPage::Clip                                                   |
//+------------------------------------------------------------------+
void CPdfPage::Clip(void)
  {
   m_content.PutLine("W n");
  }

Paint() is the one place where the enum becomes an operator. Clip() writes W n: W marks the current path as the new clip, n ends it without painting. Note that Paint(PDF_PAINT_NONE) writes only the n, which discards the path without painting and without clipping — a clip is always Clip(), never Paint(). The clip uses the nonzero rule, because the library writes no W*: a clip with a hole is still possible by winding the inner subpath the other way, but even-odd clipping is not available here. A clip can only get smaller, since the new one is the intersection of the old and the path, and the only way back is Restore() — hence the Save() before every clip. Of the shapes, the rectangle and the rounded rectangle show the whole technique:

//+------------------------------------------------------------------+
//| CPdfPage::Rect                                                   |
//+------------------------------------------------------------------+
void CPdfPage::Rect(const double x, const double y, const double w,
                    const double h)
  {
   m_content.PutOp4(x, y, w, h, "re");
  }

//+------------------------------------------------------------------+
//| CPdfPage::RoundRect                                              |
//+------------------------------------------------------------------+
void CPdfPage::RoundRect(const double x, const double y, const double w,
                         const double h, const double radius)
  {
//--- The radius cannot exceed half of either side; zero means square
//--- corners
   double r = radius;
   if(r > w * 0.5)
      r = w * 0.5;
   if(r > h * 0.5)
      r = h * 0.5;
   if(r <= 0.0)
     {
      Rect(x, y, w, h);
      return;
     }

   double k = r * PDF_KAPPA;
   double x2 = x + w;
   double y2 = y + h;

//--- Clockwise from the top edge: top, top-right corner, right edge, and
//--- so on around the box
   MoveTo(x + r, y);
   LineTo(x2 - r, y);
   CurveTo(x2 - r + k, y, x2, y + r - k, x2, y + r);
   LineTo(x2, y2 - r);
   CurveTo(x2, y2 - r + k, x2 - r + k, y2, x2 - r, y2);
   LineTo(x + r, y2);
   CurveTo(x + r - k, y2, x, y2 - r + k, x, y2 - r);
   LineTo(x, y + r);
   CurveTo(x, y + r - k, x + r - k, y, x + r, y);
   ClosePath();
  }

In the flipped system the corner of Rect() is the top-left one, with the height growing downward, which is what every caller means by a rectangle. RoundRect() is the first method that is more than one operator: it clamps the radius to half of the shorter side, then walks around the box clockwise with the control points r × PDF_KAPPA from the ends of each corner; a radius of zero falls back to a plain re. Ellipse() adds nothing new, and Circle(cx, cy, r) is Ellipse(cx, cy, r, r) — four c operators and an h, which is all a circle ever is.

CPdfDocument: pages in, a file out

The last new class is the one a caller creates first. This is its whole public surface:

//+------------------------------------------------------------------+
//|                                                  PdfDocument.mqh |
//+------------------------------------------------------------------+
#ifndef PDF5_DOCUMENT_MQH
#define PDF5_DOCUMENT_MQH

#include "PdfDefines.mqh"
#include "PdfBuffer.mqh"
#include "PdfWriter.mqh"
#include "PdfSurface.mqh"
#include "PdfPage.mqh"

//+------------------------------------------------------------------+
//| CPdfDocument                                                     |
//+------------------------------------------------------------------+
class CPdfDocument
  {
private:
   CPdfWriter        m_writer;       // assembles objects and the xref table

   CPdfPage          *m_pages[];      // pages, owned by the document
   int               m_page_count;   // number of pages

   double            m_page_w;       // page width for new pages, in points
   double            m_page_h;       // page height for new pages, in points

public:
                     CPdfDocument(void);
                    ~CPdfDocument(void);

   //--- lifecycle
   bool              Create(const ENUM_PDF_PAGE_SIZE size = PDF_PAGE_A4,
                            const ENUM_PDF_ORIENTATION orient = PDF_PORTRAIT);
   bool              CreateCustom(const double width, const double height);
   void              Destroy(void);
   bool              Save(const string filename);

   //--- pages
   CPdfPage          *AddPage(void);
   CPdfPage          *Page(const int index);
   CPdfPage          *LastPage(void);

   //--- properties
   int               PageCount(void)  const { return(m_page_count); }
   double            PageWidth(void)  const { return(m_page_w); }
   double            PageHeight(void) const { return(m_page_h); }
  };

A document is a list of pages and a page size, held as pointers rather than objects: AddPage() creates a page with new, gives it the current size — which installs the flip — and returns it to the caller, who keeps drawing on it. Destroy() deletes every page it allocated, checking CheckPointer() == POINTER_DYNAMIC first, and the destructor calls it. Create() turns a paper name into points, to three decimals, and treats landscape as the same sheet with the two numbers swapped.

One thing to know before pointing the class at unusual input: it trusts its caller. CreateCustom() accepts any width and height, so zero or negative dimensions produce a /MediaBox no viewer can interpret; SetLineWidth() takes a negative width; SetDash() checks only the "on" length; and Circle() and Ellipse() do not check their radii. RoundRect() is the exception, since a radius of zero or less falls back to Rect().

Save() is the Part 3 demo turned into a method, and it is the one body worth reading in full:

//+------------------------------------------------------------------+
//| CPdfDocument::Save                                               |
//+------------------------------------------------------------------+
bool CPdfDocument::Save(const string filename)
  {
   if(m_page_count <= 0)
     {
      Print("CPdfDocument: nothing to save, the document has no pages");
      return(false);
     }

   if(!m_writer.Begin())
      return(false);

//--- Reserve the object numbers: catalog, page tree, then one page and
//--- one content stream for each page
   int id_catalog = m_writer.NewObjectId();
   int id_pages = m_writer.NewObjectId();

   int id_page[];
   int id_content[];
   ArrayResize(id_page, m_page_count);
   ArrayResize(id_content, m_page_count);

   for(int i = 0; i < m_page_count; i++)
     {
      id_page[i] = m_writer.NewObjectId();
      id_content[i] = m_writer.NewObjectId();
     }

//--- The catalog
   m_writer.WriteDictionary(id_catalog,
                            "<< /Type /Catalog /Pages " +
                            IntegerToString(id_pages) + " 0 R >>");

//--- The page tree
   string kids = "";
   for(int i = 0; i < m_page_count; i++)
     {
      if(i > 0)
         kids += " ";
      kids += IntegerToString(id_page[i]) + " 0 R";
     }

//--- /MediaBox goes on the tree node rather than on each page. It is an
//--- inheritable attribute, so every page below the node sees it, and a
//--- long document carries one copy instead of one per page. /ProcSet is
//--- a leftover from PDF 1.0 that some old printers still look for; it
//--- costs 18 bytes and removes a whole class of complaints.
   m_writer.WriteDictionary(id_pages,
                            "<< /Type /Pages /Kids [" + kids + "] /Count " +
                            IntegerToString(m_page_count) +
                            " /MediaBox [0 0 " +
                            DoubleToString(m_page_w, 3) + " " +
                            DoubleToString(m_page_h, 3) + "]" +
                            " /Resources << /ProcSet [/PDF] >> >>");

//--- One page object and one content stream per page
   for(int i = 0; i < m_page_count; i++)
     {
      m_writer.WriteDictionary(id_page[i],
                               "<< /Type /Page /Parent " +
                               IntegerToString(id_pages) +
                               " 0 R /Contents " +
                               IntegerToString(id_content[i]) + " 0 R >>");

      CPdfBuffer *content = m_pages[i].Content();
      m_writer.WriteStream(id_content[i], content);
     }

//--- The xref table, the trailer, and the file itself
   if(!m_writer.Finish(id_catalog))
      return(false);

   if(!m_writer.Save(filename))
      return(false);

   PrintFormat("Pdf5: wrote %s - %d page(s), %d objects, %d bytes",
               filename, m_page_count, m_writer.ObjectCount(),
               m_writer.Length());
   return(true);
  }

#endif // PDF5_DOCUMENT_MQH
//+------------------------------------------------------------------+

The object numbers are reserved first — catalog, page tree, then a page object and a content stream per page — because the tree lists all the pages and can only be written once they have numbers. /MediaBox sits on the tree rather than on each page, since it is an inheritable attribute, and it is written with three decimals, so an A4 page gets [0 0 595.276 841.890]. /Resources holds only /ProcSet [/PDF], a leftover from PDF 1.0 that the next part extends with the fonts. Each content stream goes through WriteStream(), which measures it, and the closing PrintFormat reports the page count, the object count and the exact size of the file on every run.


Three demonstrations

The first demo checks the coordinate system against a real ruler, the second shows the drawing features on one page, and the third is the take-away tool. They are demonstrations rather than proofs: each exercises the library on one chosen example, which is enough to catch a missing flip or a wrong unit and not enough to say that every transform, clip and edge case is right. Only the fragments that show something new are printed here.

The ruler

Demo04_Ruler.mq5 draws a calibration sheet: a 10 mm grid, a heavier 50 mm grid, ticks along the top and left edges, a dashed margin box and two bars of known length. It takes the output file name and the margin in millimeters as inputs, and the page and both grids come out of a few lines:

//+------------------------------------------------------------------+
//| OnStart                                                          |
//+------------------------------------------------------------------+
void OnStart(void)
  {
   CPdfDocument doc;
   doc.Create(PDF_PAGE_A4, PDF_PORTRAIT);

   CPdfPage *page = doc.AddPage();
   if(CheckPointer(page) == POINTER_INVALID)
      return;

   double w = page.Width();
   double h = page.Height();

//--- PDF_MM converts millimeters to points. Everything below is written
//--- in millimeters, which is the purpose of the exercise: the library
//--- works in points, but the caller does not have to.
   double margin = InpMargin * PDF_MM;

//--- Fine grid, every 10 mm
   for(double mm = 0; mm * PDF_MM <= w; mm += 10)
      page.Line(mm * PDF_MM, 0, mm * PDF_MM, h, PdfHex(0xE4E8EC), 0.3);

   for(double mm = 0; mm * PDF_MM <= h; mm += 10)
      page.Line(0, mm * PDF_MM, w, mm * PDF_MM, PdfHex(0xE4E8EC), 0.3);

//--- Heavy grid, every 50 mm
   for(double mm = 0; mm * PDF_MM <= w; mm += 50)
      page.Line(mm * PDF_MM, 0, mm * PDF_MM, h, PdfHex(0xB9C0C8), 0.6);

   for(double mm = 0; mm * PDF_MM <= h; mm += 50)
      page.Line(0, mm * PDF_MM, w, mm * PDF_MM, PdfHex(0xB9C0C8), 0.6);

Every position in the script is written in millimeters and multiplied by PDF_MM, which is the point of the exercise: the library works in points and the caller does not have to. The edge ticks follow the same pattern — short every 5 mm, longer every 10, long and blue every 50 — and the interesting part comes after them:

//--- Dashed margin box
   page.SetStrokeColor(PDF_RED);
   page.SetLineWidth(0.8);
   page.SetDash(4, 3);
   page.Rect(margin, margin, w - margin * 2, h - margin * 2);
   page.Paint(PDF_PAINT_STROKE);
   page.SetDash(0, 0);

//--- Corner blocks, so the origin is unmistakable. The filled square is
//--- at (0, 0), which in this library is the TOP-left corner. The PDF
//--- origin is the bottom-left corner, and the outlined square there
//--- marks what the format would call (0, 0) if the page did not flip it.
   page.FillRect(0, 0, 26, 26, PDF_BLUE);
   page.StrokeRect(0, h - 26, 26, 26, PDF_INK_SOFT, 0.8);

//--- A 100 mm bar to measure with a real ruler, with a tick every 10 mm
   double bar_y = h * 0.5;
   page.FillRect(margin, bar_y, 100 * PDF_MM, 6, PDF_INK);

   for(int i = 0; i <= 10; i++)
      page.FillRect(margin + i * 10 * PDF_MM, bar_y - 6, 1.2, 6,
                    (i % 5 == 0) ? PDF_RED : PDF_INK_SOFT);

//--- A 1 inch bar below it, for the same test in imperial units
   page.FillRect(margin, bar_y + 18, PDF_INCH, 6, PDF_GREEN);

//--- Save the file and report the page size and output path
   if(doc.Save(file_path))
     {
      PrintFormat("A4 is %.3f x %.3f points, or %.1f x %.1f mm", w, h,
                  w / PDF_MM, h / PDF_MM);
      Print("Print at 100% and measure the black bar: it should be 100 mm.");
      Print("Open ", TerminalInfoString(TERMINAL_DATA_PATH),
            "\\MQL5\\Files\\", file_path);
     }
  }
//+------------------------------------------------------------------+

The filled blue square sits at (0, 0), which with the flip is the top-left corner, and the outlined square sits where PDF's own origin is; without the flip the two would swap places.

Figure 8. The ruler page: the origin square, the edge ticks and the 100 mm bar.

The real test is on paper. Print the page at 100% scale ("actual size", not "fit to page") and measure the black bar: it should be 100 mm, and the green bar under it one inch. If the measurement is off, the page is not necessarily wrong — the print driver, a scaling setting or the printer's margins can all change it. What the bar confirms is what it was drawn for: a millimeter in the script arrives as a millimeter on the sheet.

The sampler

Demo04_Shapes.mq5 is Figure 1: ten sections on one page, each marked by a short colored bar from the one-line Marker() helper, because there is no text yet. In order, they are a rectangle filled, stroked and both; the star of Figure 4 under both winding rules; the caps and joins of Figure 5; four dash patterns; five squares with a growing corner radius; an ellipse with four circles on top of it; stripes clipped by a rounded box; twelve rotated bars; one Bezier curve with its control handles; and a bar chart built from nothing but FillRect() and HLine(), on values from a sine formula so that the page is identical on every run. Everything except the clip and the transforms has already appeared above, so those two are the fragments worth printing:

//--- 7. Clipping. The stripes below extend far outside the rounded box.
//--- The clip path is what makes them stop at its edge, and Restore() is
//--- the only way to get the previous clip back.
   Marker(page, 50, 362, PDF_PURPLE);

   page.Save();
   page.RoundRect(50, 378, 232, 92, 14);
   page.Clip();

   for(int i = -3; i < 30; i++)
     {
      page.SetFillColor(PdfMix(PDF_WHITE, PDF_PURPLE,
                               ((i % 2) == 0) ? 0.14 : 0.32));
      page.MoveTo(50 + i * 13.0, 366);
      page.LineTo(50 + i * 13.0 + 9, 366);
      page.LineTo(50 + i * 13.0 - 17, 482);
      page.LineTo(50 + i * 13.0 - 26, 482);
      page.ClosePath();
      page.Paint(PDF_PAINT_FILL);
     }
   page.Restore();

//--- 8. Transforms: twelve bars rotated around one center point
   Marker(page, 340, 362, PDF_RED);

   for(int i = 0; i < 12; i++)
     {
      page.Save();
      page.Translate(452, 424);
      page.Rotate(i * 30.0);
      page.FillRect(0, -3.5, 64, 7, PdfMix(PDF_BLUE, PDF_RED, i / 11.0));
      page.Restore();
     }

The stripes are parallelograms that run far outside the rounded box, and the clip cuts them off at its edge, round corners included; Save() before and Restore() after keep the rest of the page unclipped. The twelve bars are all drawn in the same place, from (0, −3.5), 64 points long — only the coordinate system turns. Scale() is the one transform the sampler leaves out: it writes a cm of the same shape, and page.Scale(1.5, 1.0) inside such a pair stretches whatever follows along x. The file is about 8.5 KB with the attached code and none of it is an image, so every edge stays sharp at any zoom; the exact byte count of your own run is in the Experts log, printed by Save().

The letterhead

Demo04_Letterhead.mq5 is the take-away tool: a real letterhead to print and write on, or to keep as the background of the reports the series builds later. Its inputs are what make it a tool rather than a demo.

//+------------------------------------------------------------------+
//|                                            Demo04_Letterhead.mq5 |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2026, Sandro Begashvili"
#property link        "https://www.mql5.com/en/users/sandrobegashvil"
#property version     "1.00"
#property script_show_inputs
#property description "Building a PDF Creation Library in MQL5"
#property description "Part 4: Lines, Boxes, and Color"
#property description "Draws a letterhead in your brand color: header band, logo,"
#property description "accent rule, fold marks and a framed footer."

#include <MQLPDF/PdfDocument.mqh>

//--- Every article in the series writes under one shared root folder, with
//--- its own subfolder
#define PDF_ROOT_FOLDER  "MQLPDF"
#define PDF_SUB_FOLDER   "Part 04"

//--- Inputs
input ENUM_PDF_PAGE_SIZE InpPaper    = PDF_PAGE_A4;               // Paper size
input color              InpBrand    = C'31,111,235';             // Brand color
input color              InpAccent   = C'191,135,0';              // Accent color
input double             InpRadius   = 3.0;                       // Corner radius, mm
input double             InpMargin   = 18.0;                      // Side margin, mm
input string             InpFileName = "letterhead.pdf";  // Output file

string file_path = PDF_ROOT_FOLDER + "//" + PDF_SUB_FOLDER + "//" + InpFileName;
//+------------------------------------------------------------------+
//| Converts millimeters to points.                                  |
//+------------------------------------------------------------------+
double Mm(const double value)
  {
   return(value * PDF_MM);
  }

The paper size is an ENUM_PDF_PAGE_SIZE, so the terminal shows a drop-down list, and the two colors are MQL5 color inputs, so it shows its color picker; Mm() keeps the drawing code readable. The page begins with the band and the rings inside it:

//+------------------------------------------------------------------+
//| Script entry point.                                              |
//+------------------------------------------------------------------+
void OnStart(void)
  {
   CPdfDocument doc;
   doc.Create(InpPaper, PDF_PORTRAIT);

   CPdfPage *page = doc.AddPage();
   if(CheckPointer(page) == POINTER_INVALID)
      return;

   double w = page.Width();
   double h = page.Height();

//--- The inputs are MQL5 colors, stored as 0xBBGGRR. PdfFromMql puts
//--- the three bytes in the order PDF expects.
   SPdfColor brand = PdfFromMql(InpBrand);
   SPdfColor accent = PdfFromMql(InpAccent);

   double margin = Mm(InpMargin);
   double radius = Mm(InpRadius);

//--- 1. The header band
   double band_h = Mm(34);
   page.FillRect(0, 0, w, band_h, brand);

//--- 2. Rings in lighter shades of the brand color. The band is used as
//--- a clip path, so the rings stop at its edge and nothing spills onto
//--- the page. Restore() removes the clip again.
   page.Save();
   page.Rect(0, 0, w, band_h);
   page.Clip();
   for(int i = 0; i < 4; i++)
      page.FillCircle(w - Mm(24), Mm(6), Mm(46 - i * 10),
                      PdfMix(brand, PDF_WHITE, 0.08 + i * 0.07));
   page.Restore();

//--- 3. The logo, centered vertically in the band
   double logo = Mm(18);
   DrawLogo(page, margin, (band_h - logo) / 2, logo, radius, brand, accent);

//--- 4. The accent rule under the band
   page.FillRect(0, band_h, w, Mm(1.2), accent);

The rings are the clip at work in a real design: four circles, each smaller and lighter than the one before, centered near the top-right corner and mostly larger than the band. The band's rectangle becomes the clip first, so they are cut off at its lower edge and the page below stays clean.

//--- 5. Fold and punch marks on the left edge, at the positions the
//--- German DIN 5008 standard uses for business letters on A4: folds at
//--- 105 mm and 210 mm, the punch mark at 148.5 mm. Three subpaths, one
//--- stroke.
   page.SetStrokeColor(PDF_GREY);
   page.SetLineWidth(0.5);
   page.MoveTo(Mm(4), Mm(105));
   page.LineTo(Mm(9), Mm(105));
   page.MoveTo(Mm(4), Mm(148.5));
   page.LineTo(Mm(11), Mm(148.5));
   page.MoveTo(Mm(4), Mm(210));
   page.LineTo(Mm(9), Mm(210));
   page.Paint(PDF_PAINT_STROKE);

//--- 6. The footer frame: a rounded box, filled with a faint tint of the
//--- brand color and outlined in the full color, in one B operator
   double fh = Mm(16);
   double fy = h - Mm(12) - fh;
   double fw = w - margin * 2;

   page.SetFillColor(PdfMix(PDF_WHITE, brand, 0.06));
   page.SetStrokeColor(brand);
   page.SetLineWidth(0.8);
   page.RoundRect(margin, fy, fw, fh, radius);
   page.Paint(PDF_PAINT_BOTH);

The fold marks show why millimeters matter. A business letter in Germany, and much of Europe, follows DIN 5008, which puts the folds 105 mm and 210 mm from the top of an A4 sheet and the punch mark at 148.5 mm; with the flip and Mm() those numbers go into the code exactly as the standard states them, where without the flip each would need a subtraction from 841.89 points. The footer is one rounded rectangle, filled with a 6% tint and outlined in the full brand color by a single B. The rest of the script needs no new technique: two dashed dividers split the frame into three cells, an envelope, a globe and a small bar chart mark the start of each, and a thin strip of the brand color closes the page. Those icons and the logo are assembled from the same primitives, every size a fraction of the icon box, and the attachment prints them in full.

Figure 9. The letterhead page produced by Demo04_Letterhead.mq5.

The page is about 3.5 KB. Now change the inputs and run it again: a dark green brand color, a red accent, a radius of 0 for square corners, Letter paper. The band, the logo, the accent rule and the footer all follow, because their colors and their rounding come from the inputs. The layout is not fully fluid, though — several sizes inside the design are fixed, and the fold marks are the DIN 5008 positions for A4, so on Letter they are drawn where the code puts them rather than where another folding standard would.


Typical mistakes, and the cheat card

Everything after one shape is rotated, dashed or clipped. A Save() is missing, or its Restore() is. The graphics state lasts to the end of the stream, and the library does not count the depth of the stack, so neither a missing Restore() nor one too many is reported. Pair them in the same block, and set the dash pattern back with SetDash(0, 0).

The page is blank, but the validator says no problems. The structure is fine and the drawing is not. Usually a path was built and never painted — a Rect() with no Paint() draws nothing — or the drawing is outside the page, at y = 900 on a sheet 842 points tall.

A shape is upside down or at the bottom of the page. Something wrote coordinates in PDF's y-up system, for example a stream copied from another program. After the flip, height - y must never appear in drawing code.

A color looks as if red and blue were swapped. An MQL5 color was passed to PdfHex() instead of PdfFromMql().

A table line pokes out past its corner. The cap is round or square, which adds half the line width at each end. Use the default butt cap for grids.

A rounded box looks like a capsule. The radius is larger than half of the shorter side, and RoundRect() clamps it to exactly half.

Figure 10. The drawing calls of CPdfPage and the operator each one writes.

Figure 10 is the whole drawing API on one card, each call with the operator it writes, and not one of them takes a PDF coordinate. The line under it is the rule of this part.


Installation and sources

Unzip into MQL5\Scripts\ and MQL5\Include\, then compile the three scripts. Output appears in MQL5\Files\MQLPDF\Part 04\, and everything the article described rather than printed is in these files as the text explains it.

MQL5/
├── Scripts/
│    └── MQLPDF/
│        └── Part 04/
│            ├── Demo04_Ruler.mq5        // millimeter calibration sheet
│            ├── Demo04_Shapes.mq5       // every drawing feature on one page
│            └── Demo04_Letterhead.mq5   // letterhead in your brand colors
│
├── Include/
│    └── MQLPDF/
│        ├── PdfDefines.mqh          // Part 4 - units, enums, PDF_KAPPA added
│        ├── PdfBuffer.mqh           // Part 4 - PutOp helpers added
│        ├── PdfColor.mqh            // Part 4 - the color type and palette
│        ├── PdfSurface.mqh          // Part 4 - the drawing interface
│        ├── PdfPage.mqh             // Part 4 - the PDF implementation
│        ├── PdfDocument.mqh         // Part 4 - pages in, a file out
│        ├── PdfWriter.mqh           // Part 3 - carried over unchanged
│        └── PdfValidate.mqh         // Part 2 - carried over unchanged
│
└── Files/
     └── MQLPDF/
         └── Part 04/
             ├── ruler.pdf               // (output file)
             ├── shapes.pdf              // (output file)
             └── letterhead.pdf          // (output file)
# File
1 PdfValidate.mqh
2 PdfWriter.mqh
3 PdfDefines.mqh
4 PdfBuffer.mqh
5 PdfColor.mqh
6 PdfSurface.mqh
7 PdfPage.mqh
8 PdfDocument.mqh
9 Demo04_Ruler.mq5
10 Demo04_Shapes.mq5
11 Demo04_Letterhead.mq5
12 MQLPDF Library - Part 04.zip


Conclusion

In this part the library gained vector drawing, color, and a coordinate system whose origin is in the top-left corner. One cm operator at the start of every content stream is the whole of that change: after it, every coordinate the caller gives is used as it is, further matrices compose through the same operator, and q and Q save and restore the graphics state. On top of it sits the path model — build with m, l, c, h and re, then paint once with S, f, B or n — with the two winding rules, the stroke settings, and circles approximated by four Bezier curves.

Three classes and one structure carry it: CPdfSurface defines the common interface, CPdfPage turns calls into PDF operators, CPdfDocument assembles the pages with the unchanged writer from Part 3, and SPdfColor stores colors as bytes and converts them to fractions, including the blue-first conversion MQL5 needs. Three demonstrations show the result: a calibration ruler, a page of primitives, and a letterhead that takes its brand colors from the script inputs.

What the page still cannot do is speak. The next part puts words on it: text objects with BT and ET, the fourteen standard fonts every viewer has without embedding, positioning with Tf, Td and Tm, showing with Tj, the escaping a PDF string needs, and the second flip that makes the text read the right way up. The demo is a first account statement, deliberately crooked, because the library cannot measure text yet — which is the problem the part after it solves.

The project is supported on MQL5 Algo Forge. Each article in this series has its own release, containing exactly the source code explained in that part.

Part 4 is here: https://forge.mql5.io/SandroBegashvil/MQLPDF/releases/tag/part-04

Attached files |
PdfBuffer.mqh (14.91 KB)
PdfColor.mqh (6.77 KB)
PdfDefines.mqh (6.67 KB)
PdfDocument.mqh (12.24 KB)
PdfPage.mqh (21.17 KB)
PdfSurface.mqh (10.14 KB)
PdfValidate.mqh (22.72 KB)
PdfWriter.mqh (14.53 KB)
Demo04_Ruler.mq5 (6.17 KB)
Demo04_Shapes.mq5 (10.87 KB)
Aggregating Economic Calendar Events into a Structured MQL5 Data Feed Aggregating Economic Calendar Events into a Structured MQL5 Data Feed
The package builds a news feed from CalendarValueHistory(): it filters by impact and currency, maps events to a symbol universe, and stores them in a time‑sorted array with minutes to event. You can query GetNextEvent() and IsInNewsWindow() to implement deterministic news filtering in an EA. An abstract source and clock, plus terminal and fake implementations, enable testing when calendar functions are unavailable in the Strategy Tester.
Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model
We implement an MQL5 program that validates consolidations by counting edge switches, height capped to the typical candle, and net drift, then requires a buffered close beyond an edge and a move away before arming. Entry follows a return to the broken edge and a strong close back on the breakout side. The stop anchors beyond the retest extreme; the target is an R-multiple, and failed attempts can rearm the same range after a fresh breakout and retest.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5 Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5
We implement a multi‑timeframe aggregator that prevents mixing bars from different moments. It validates grid alignment, recency to the forming base bar, and closed‑bar end times, and returns either a complete bundle or a structured error. A re‑read guards against races with a new base bar, while a fake bar source powers fifteen reproducible tests and a demo indicator that plots on valid data only.