Watch how to download trading robots for free
Find us on Twitter!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Libraries

StrictJson: RFC 8259 JSON parser and writer for MQL5 - library for MetaTrader 5

George Ciprian Mandache
George Ciprian Mandache
Mostly writing code that does stuff...

User guides are on my blog. For questions or bugs, write in the product's Comments tab or send me a message.
Views:
17
Published:
\MQL5\Include\StrictJson\
StrictJson.mqh (57.08 KB) view
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

StrictJson reads and writes JSON in MQL5 and MQL4. It is one include file with no other dependencies: save your EA's settings and state to a file and load them on the next start, parse what a WebRequest returns, or build the JSON you send. Values are read by key, index or a dotted path, and documents are written compact or indented.

It follows RFC 8259 to the letter. Text that is not JSON fails with the line and column of the problem instead of being read into something half right, numbers come back exactly as they went in, and files are strict UTF-8.

#include <StrictJson\StrictJson.mqh>

Save your settings and state

An EA's panel settings and the state it tracks go into a file and come back on the next start. A key an older file does not have yet keeps its default, so the format can grow without breaking saved files.

void SaveSettings() {
    CJsonValue doc;
    doc.PutDouble("lots", g_lots);
    doc.PutLong("max_spread", g_maxSpread);
    doc.Set("alerts").SetObject().PutBool("push", g_alertPush);
    CJsonValue *panel = doc.Set("panel").SetObject();
    panel.PutLong("x", g_panelX);
    panel.PutString("theme", g_theme);
    doc.Set("state").SetObject().PutLong("buys", g_buys);
    if (doc.SaveFile("MyEA\\settings.json") != JSON_OK) {
        Print("settings not saved");
    }
}

void LoadSettings() {
    CJsonValue doc;
    string error;
    if (doc.LoadFile("MyEA\\settings.json", error) != JSON_OK) {
        return;                                          // first start: keep the defaults
    }
    g_lots = doc.GetDouble("lots", g_lots);
    g_maxSpread = doc.GetInt("max_spread", g_maxSpread);
    g_alertPush = doc.GetBool("alerts.push", g_alertPush);
    g_panelX = doc.GetInt("panel.x", g_panelX);
    g_theme = doc.GetString("panel.theme", g_theme);
    g_buys = doc.GetLong("state.buys", g_buys);
}

The attached example saves a settings object like this and the file looks the way you would write it by hand:

{
  "lots": 0.05,
  "max_spread": 30,
  "alerts": {
    "push": true,
    "sound": true
  },
  "panel": {
    "x": 340,
    "y": 30,
    "theme": "dark"
  },
  "symbols": [
    "US500",
    "XAUUSD",
    "EURUSD"
  ],
  "state": {
    "last_buy": "2026.11.24 16:30",
    "buys": 12
  }
}

Features

  • Strict parser: gets the same verdict as every y_ (must parse) and n_ (must fail) case of JSONTestSuite. Trailing commas, leading zeros, TRUE, .5 and a second document after the first are refused.
  • Errors that say where: "line 2 column 1: unexpected text after the value". A failed parse leaves the value as it was.
  • Exact numbers: doubles are written the way Python's json.dumps writes them (0.1 stays 0.1, 1.0 stays 1.0), and integers keep all 64 bits.
  • null, "", [] and {} stay four different things, and objects keep their keys in order.
  • Strict UTF-8 for files and WebRequest bytes, surrogate pairs included. A save writes a temporary file first, so it never leaves half a file.
  • Typed getters with a fallback, so a missing key needs no NULL check.
  • Every call that can fail returns JSON_OK or a JSON_ERROR_* code. Nothing prints by itself.

Example

#include <StrictJson\StrictJson.mqh>

void OnStart() {
    CJsonValue doc;
    string error;
    if (doc.Parse("{\"symbol\":\"US500\",\"days\":[\"Mon\",\"Wed\"],\"alerts\":{\"push\":true}}", error) != JSON_OK) {
        Print("parse failed: ", error);
        return;
    }
    string symbol = doc.GetString("symbol");    // "US500"
    string firstDay = doc.GetString("days.0");  // "Mon"
    bool push = doc.GetBool("alerts.push");     // true
    int spread = doc.GetInt("max_spread", 30);  // missing, so 30

    doc.PutDouble("lots", 0.01);
    doc.Set("levels").SetArray().AddDouble(1.5);
    doc.SaveFile("MyEA\\settings.json");        // indented UTF-8, directories made

    CJsonValue bad;
    bad.Parse("[1,]", error);
    Print(error);                               // line 1 column 4: unexpected character
}

The attached StrictJsonExample script saves and loads settings and state, then runs through reading, refusing and exact numbers, and prints this among its output:

refused text=[1,] error="line 1 column 4: unexpected character"
refused text=[01] error="line 1 column 3: expected ',' or ']'"
refused text=TRUE error="line 1 column 1: unexpected character"
refused text=[.5] error="line 1 column 2: unexpected character"
refused text={"a" 1} error="line 1 column 6: expected ':'"
round trip text={"price":0.1,"id":9223372036854775807,"none":null,"empty":"","obj":{}}

The saved settings.json and the Experts log of the example

API

Call What it does
Parse(text, error), ParseUtf8(bytes, error), LoadFile(path, error) Read JSON into the value; error says where it failed
Serialize(out, indent), ToString(indent), SaveFile(path, indent) Write it, compact (indent 0) or indented like json.dumps(indent=N)
Get(key), At(index), Find("a.0.b"), Size(), KeyAt(i), Has(key) Walk the tree; a missing part is NULL
GetString, GetDouble, GetLong, GetInt, GetBool (path, fallback) Read a value by path, or the fallback
AsString, AsDouble, AsLong, AsInt, AsBool (fallback), Type(), IsNull() and the other Is checks Read the value itself
SetString, SetDouble, SetLong, SetBool, SetNull, SetArray, SetObject Replace the value; each returns it, for chaining
Set(key), Append(), PutString and the other Put calls, AddString and the other Add calls Add or replace members and items
Remove(key), RemoveAt(i), CopyFrom(other) Delete parts, deep copy
StrictJsonErrorText(code) Describe an error code

A CJsonValue owns its children and deletes them; the pointers Get, Find, Set and Append return belong to the document.

Divergence Detector without repaint: RSI, MACD, Stochastic, CCI, Momentum Divergence Detector without repaint: RSI, MACD, Stochastic, CCI, Momentum

Regular and hidden divergences between price and RSI, MACD, Stochastic, CCI or Momentum. Swings confirmed on closed bars, signal on the confirmation bar, lines on oscillator and price. No repaint, buffers for EAs.

Key Levels: PDH/PDL, weekly and monthly levels, midnight open, Asian range, sweeps Key Levels: PDH/PDL, weekly and monthly levels, midnight open, Asian range, sweeps

Previous day, week and month high and low, New York midnight open, period opens and the Asian range, with sweep marks and one alert per level. Day from broker or New York time. No repaint, buffers for EAs.

Accelerator Oscillator (AC) Accelerator Oscillator (AC)

The Acceleration/Deceleration Indicator (AC) measures acceleration and deceleration of the current driving force.

MACD Signals MACD Signals

Indicator edition for new platform.