Strict JSON Parser and Writer for MQL4

Strict JSON Parser and Writer for MQL4
Download ALL MT4 scripts (429)
YouTube Video Thumbnail



Similar MetaTrader Tools

Strict JSON Parser and Writer for MQL4

Info

The Strict JSON Parser and Writer for MQL4 is a Script for MetaTrader 4 that strictjson is a library for reading and writing json data within mql4. It is provided as a single include file with no external dependencies, making it easy to integrate into your projects.

Usage

This tool is typically used for enhancing chart analysis and decision making.

Platform

This Script works exclusively on MetaTrader 4 (both build 600+ and newer versions).

Setup

Place the downloaded file in MQL4/Scripts folder via File ? Open Data Folder in MetaTrader 4.


How to Install and Use Strict JSON Parser and Writer for MQL4

1. Installation: Move your script file into the MQL/Scripts directory and restart the platform.

2. Execution: Drag the script onto a chart; it will perform a one-time action, such as closing all open orders or clearing chart objects.

3. Editing: Use MetaEditor (F4) to modify code, click "Compile," and verify no errors appear in the terminal before running.

4. Removing: Scripts stop automatically, but you can remove them manually by right-clicking the chart and choosing "Remove Script."

Frequently Asked Questions

Q: How are scripts different from EAs? A: Scripts execute a single action and then stop; EAs monitor the market and trade continuously.

Q: Can I assign a hotkey to a script? A: Yes, right-click the script in the Navigator, select "Set Hotkey," and define your preferred keyboard shortcut.

Q: Why did my script stop? A: Scripts are designed to stop immediately after finishing their programmed command; this is normal behavior.

What this tool does

StrictJson is a library for reading and writing JSON data within MQL4.

Typical Use Case

This Script excels in automated trading and technical analysis on MetaTrader 4.

Compatible Platform & Setup

This Script works on MetaTrader 4. Place the file in the MQL4/Scripts folder and restart the terminal.

Description & Settings

Related: multi buy orders - another powerful script for MetaTrader 4 traders.

StrictJson is a library for reading and writing JSON data within MQL4. It is provided as a single include file with no external dependencies, making it easy to integrate into your projects.

Also recommended: FATL-SATL Balance Indicator - similar script with strong performance on MetaTrader 4.


Use StrictJson to save and load your Expert Advisor's settings and state, process data received from WebRequest, or construct JSON data for sending.

You can access JSON values by their key, their position within a list, or by using a path like "panel.theme" or "days.0". The library supports writing JSON documents either on a single line or with indentation for improved readability.

Strict adherence to RFC 8259, the official JSON standard, is a core feature. The library rigorously validates JSON input, rejecting any non-compliant text with precise error messages indicating the line and column of the issue. Numbers are preserved exactly as they were input, and files are handled using UTF-8 encoding, which is the standard for JSON data.

Include the library with:
#include <StrictJson\StrictJson.mqh>

Save Your Settings and State

Expert Advisors often need to persist their settings and operational state. StrictJson allows you to save this data to a file and load it upon the next program start. If a key that existed in an older file is not present in the new data, its default value is retained, ensuring that your data format can evolve without breaking compatibility with older saved files.

Example of saving settings:
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");
}
}

Example of loading settings:
void LoadSettings() {
CJsonValue doc;
string error;
if (doc.LoadFile("MyEA\settings.json", error) != JSON_OK) {
return; // First start, use 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 demonstrates saving a settings object that results in a file structured as follows, which is easily human-readable:

{
"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

StrictJson refuses malformed JSON. Unlike some parsers that may partially read invalid data, StrictJson enforces the standard. It correctly identifies and rejects non-compliant JSON, such as trailing commas, numbers with leading zeros, non-standard boolean representations (e.g., TRUE), numbers starting with a decimal point, or multiple JSON documents within a single input. The library has been tested against JSONTestSuite, a comprehensive set of 318 test files, successfully accepting all 95 valid files and rejecting all 188 invalid ones.

Error reporting is precise, providing the exact line and column where a mistake occurred (e.g., "line 2 column 1: unexpected text after the value"). When parsing fails, the value being read remains unchanged.

Numerical precision is maintained. Values like 0.1 are stored as 0.1, not an approximation, and 1.0 remains 1.0. Whole numbers are handled with the full range of a long integer, up to 9,223,372,036,854,775,807.

Distinction between empty values is preserved. null, an empty string, an empty list, and an empty object are treated as distinct entities. Object keys maintain the order in which they were originally added.

UTF-8 encoding is used for reading and writing files and WebRequest results, ensuring that text in any language, including emojis, is processed correctly. File writing involves creating a temporary file first, which is then atomically replaced with the old one, preventing data loss from incomplete writes.

A default value can be provided for every getter. For instance, GetDouble("lots", 0.01) will return 0.01 if the "lots" key is not found, eliminating the need for explicit NULL checks.

All operations that can fail return a JSON_OK status code or a specific JSON_ERROR_* code. The library operates without generating any internal output or messages.

Example Usage

#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 created

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

The StrictJsonExample script demonstrates saving and loading settings, parsing, handling errors, and working with numbers. Its output includes:

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":{}}

API Reference

Call
What it does

Parse(text, error), ParseUtf8(bytes, error), LoadFile(path, error)
Read JSON into the value; error indicates failure location

Serialize(out, indent), ToString(indent), SaveFile(path, indent)
Write as a single line (indent 0) or with indentation specified in spaces

Get(key), At(index), Find("panel.theme"), Size(), KeyAt(i), Has(key)
Navigate objects and lists; a missing component results in NULL

GetString, GetDouble, GetLong, GetInt, GetBool (path, fallback)
Read a value by path, returning the fallback if not found

AsString, AsDouble, AsLong, AsInt, AsBool (fallback), Type(), IsNull() and other Is checks
Read the value itself or check its type

SetString, SetDouble, SetLong, SetBool, SetNull, SetArray, SetObject
Replace the current value; each returns the modified value for chaining

Set(key), Append(), PutString and other Put calls, AddString and other Add calls
Add or replace object members or array items

Remove(key), RemoveAt(i), CopyFrom(other)
Delete parts of the JSON structure, or perform a deep copy

StrictJsonErrorText(code)
Provide a descriptive string for an error code

Note: A CJsonValue manages its children; pointers returned by Get, Find, Set, and Append are owned by the document.

You may also like: cme futures download script - excellent alternative for script users on MetaTrader 4.

Source Code

#property copyright "RobotFX"
#property link "https://robotfx.org"
#property version "1.0"
#property description "This code is educational. Feel free to use, modify and upgrade as you wish. Visit ROBOTFX.ORG for professional trading tools"
#property strict
#include <StrictJson\StrictJson.mqh>
#define EXAMPLE_FILE "StrictJson\\settings.json"
#define EXAMPLE_INDENT 2
#define EXAMPLE_SPREAD_FALLBACK 30
#define EXAMPLE_SETTINGS "{\"symbol\": \"US500\", \"lots\": 0.01, \"days\": [\"Mon\", \"Wed\", \"Fri\"], \"alerts\": {\"push\": true}}"

.......

Leave your opinion, ask a question, share some knowledge

⚠ Limitations & Risk Warning

  • This tool is provided for educational and testing purposes only.
  • Past performance does not guarantee future results.
  • Trading involves substantial risk of loss. Use on a demo account first.
  • Results may vary depending on market conditions, broker, and settings.
  • We recommend thorough backtesting and forward testing before using with real funds.
© ROBOTFX Free educational tools by RobotFX. Use entirely at your own risk; we are not liable for any financial losses incurred.