Natural Language Processing NLP
- librerie
- Abhijay Tiwari
- Versione: 1.3
📘 Overview
AlgoNLP.mqh is a standalone MQL5 library that converts human-written trading instructions into structured trade intents that your Expert Advisor (EA) or indicator can understand.
Example input:
Buy gold at 2370 with TP 0.3% and SL 1%
Output intent:
Side: BUY | Type: LIMIT | Symbol: XAUUSD | Entry: 2370 | TP: 0.3% | SL: 1% | Lot: 0.00
This enables you to build chat-controlled or Telegram-integrated EAs that can interpret plain English commands and execute structured trades.
always sanitize incoming text and verify the trade intent fields.
Unfiltered user commands may lead to unintended order placement, symbol mismatches, or risk limit breaches.
⚠️ Use confirmation dialogs or verification layers in live trading environments.
➡️ Check my Articles for deatiled explaintion on how NLP works and implement it using mq5.
🌿 Do check out my Signals : https://www.mql5.com/en/signals/2340834 best to grow small accounts 50$.
⚙️ System Requirements
| Requirement | Details |
|---|---|
| Platform | MetaTrader 5 (Build ≥ 2750) |
| Language | MQL5 (strict mode enabled) |
| Encoding | Unicode-Safe |
| Dependencies | None (self-contained) |
| Execution Time | ≈ 0.2 ms for an average sentence (<30 tokens) |
| Memory Footprint | ≈ 20–30 KB per instance |
| Thread Safety | Single-threaded (EA/indicator safe) |
➡️ benchmarks may vary in real environments.
🧩 Library Structure
| Component | Type | Description |
|---|---|---|
| CNLP | Main Manager Class | Handles parsing, context binding, and listener dispatch. |
| CIntentDetector | Core Engine | Performs multi-pass number extraction and intent mapping. |
| CKeywordExtractor | Utility | Extracts keywords and filters stopwords. |
| CLexicon | Utility | Stores semantic word sets (buy/sell, order types). |
| CContext | Helper | Manages known symbols and last used instrument. |
| INLPListener | Interface | Callback interface for event-driven intent handling. |
| NLPUtil | Namespace | Text and timing utility functions. |
➡️ View in-depth architecture diagram:
📦 Core Data Types
SNLPIntent — Parsed Trade Object
| Field | Type | Description |
|---|---|---|
| valid | bool | True if parsed successfully |
| side | ENLPOrderSide | BUY, SELL, or UNKNOWN |
| type | ENLPOrderType | MARKET, LIMIT, STOP |
| symbol | string | Resolved trading symbol |
| price | double | Entry price (if provided) |
| tp, sl | double | Take-profit and stop-loss values |
| tp_is_percent, sl_is_percent | bool | True if % based |
| tp_is_pips, sl_is_pips | bool | True if in pips/points |
| qty_lots | double | Detected lot size |
| when | SNLPWhen | Time or breakout conditions |
| raw | string | Original message text |
| reason | string | Debugging or explanation field |
🔍 How It Works
- Normalization: Text is lowercased, cleaned, and synonyms replaced (take profit → tp).
- Tokenization: Words are split and stopwords filtered out.
- Lexical Matching: Detects intent direction using fuzzy Levenshtein distance ≤1.
- Number Context Extraction: Interprets numbers as price, TP/SL, or lot size via unit analysis.
- Timing Logic: Recognizes “at 09:15”, “in 15 min”, and breakout triggers.
- Symbol Resolution: Infers instruments like gold → XAUUSD.
- Intent Build: Constructs SNLPIntent and triggers listener callbacks.
⚠️ AlgoNLP.mqh uses deterministic text parsing and context-based heuristics — it does not employ AI or machine learning.
As a result, extremely ambiguous or grammatically incomplete sentences may yield undefined behavior or incomplete intents.
Always validate parsed results before executing real trades.
🧩 Example Integration
Safety
All INLPListener callbacks (such as OnOrderIntent , OnError , etc.) are executed synchronously from the main EA thread.
Heavy logic, API calls, or order operations inside these methods can block trading flow or cause lag.
It is recommended to delegate trade execution to asynchronous or timed functions instead of calling them directly in callbacks.
#include <AlgoNLP.mqh>
class CMyListener : public INLPListener
{
public:
void OnOrderIntent(const SNLPIntent &i) override
{
Print("✅ NLP Worked!");
Print("Side: ", EnumToString(i.side));
Print("Type: ", EnumToString(i.type));
Print("Symbol: ", i.symbol);
Print("TP: ", DoubleToString(i.tp, 2), " | SL: ", DoubleToString(i.sl, 2));
}
};
CMyListener listener;
CNLP nlp;
int OnInit()
{
nlp.AddSymbol("XAUUSDm");
nlp.AddListener(listener);
return(INIT_SUCCEEDED);
}
void OnStart()
{
string text="Buy gold at 2370 with TP 0.3% and SL 1%";
nlp.Dispatch(text);
}
🧮 Performance Metrics
| Test Case | Tokens | Parse Time | Accuracy |
|---|---|---|---|
| Short Command (“Buy BTC market”) | 5 | 0.09 ms | 100% |
| Full Sentence (“Buy gold at 2370 with TP 0.3% and SL 1%”) | 15 | 0.22 ms | 100% |
| Noisy Query (“Hey bot short nasdaq please 0.5 lot”) | 18 | 0.26 ms | >95% |
➡️ Benchmark performed on Intel i7-9700 / MT5 Build 3820.
🧭 Summary
AlgoNLP.mqh transforms ordinary text into actionable trade logic inside MetaTrader. It’s designed for developers who want their EAs to think like humans — understanding plain English instructions and executing trades intelligently. This isn’t a shortcut — it’s a full linguistic computation system written in native MQL5.
