EA Integration
How to integrate your Expert Advisor with EA Safety Score
Overview
This guide explains how to integrate your Expert Advisor (EA) with the EA Safety Score Indicator.
Important: Indicator vs EA Permissions
| Action | Indicator | EA |
|---|---|---|
| Calculate safety score | ✅ Yes | ✅ Yes |
| Display dashboard | ✅ Yes | ❌ No |
| Send signals (Global Variables) | ✅ Yes | ✅ Yes |
| Open new trades | ❌ No | ✅ Yes |
| Close positions | ❌ No | ✅ Yes |
| Toggle AutoTrading | ✅ Yes | ✅ Yes |
| Send Telegram alerts | ✅ Yes | ✅ Yes |
Key Point: The indicator sends safety signals, but YOUR EA must read these signals and take action (close trades, stop opening new trades).
How It Works
┌─────────────────────┐ ┌─────────────────────┐
│ EA Safety Score │ │ Your Trading EA │
│ Indicator │ │ (Grid/Martingale) │
│ │ │ │
│ ┌─────────────────┐ │ │ ┌─────────────────┐ │
│ │ Calculate Score │ │ │ │ Read Signals │ │
│ │ (SAFE/CAUTION/ │ │ │ │ (Global Vars) │ │
│ │ DANGER) │ │ │ └────────┬────────┘ │
│ └────────┬────────┘ │ │ │ │
│ │ │ │ ▼ │
│ ▼ │ │ ┌─────────────────┐ │
│ ┌─────────────────┐ │ │ │ Should I close? │ │
│ │ Set Global Var │◄├─────────┤ │ Should I stop? │ │
│ │ (EAS_Status=2) │ │ │ └────────┬────────┘ │
│ └─────────────────┘ │ │ │ │
│ │ │ │ ▼ │
│ ▼ │ │ ┌─────────────────┐ │
│ │ │ Close Positions │ │
│ │ │ Stop New Trades │ │
│ │ └─────────────────┘ │
│ └─────────────────────┘Integration Methods
Method 1: Simple Integration (Recommended for Beginners)
Add just a few lines of code to your EA to check safety signals.
Step 1: Add These Functions to Your EA
Copy and paste this code at the top of your EA file (after #property directives):
//+------------------------------------------------------------------+
//| EA Safety Score Integration - Simple Functions |
//+------------------------------------------------------------------+
// Global Variable Names used by Safety Score
string EAS_GV_STATUS = "EAS_SafetyScore_Status";
string EAS_GV_CLOSE_ALL = "EAS_Close_All_Signal";
string EAS_GV_BLOCK_NEW = "EAS_Block_New_Trades";
string EAS_GV_TRADING_ALLOWED = "EAS_Trading_Allowed";
// Status values
int EAS_STATUS_SAFE = 0;
int EAS_STATUS_CAUTION = 1;
int EAS_STATUS_DANGER = 2;
//+------------------------------------------------------------------+
//| Check if Safety Score indicator is active |
//+------------------------------------------------------------------+
bool IsSafetyScoreActive()
{
return GlobalVariableCheck(EAS_GV_STATUS);
}
//+------------------------------------------------------------------+
//| Get current safety status (0=SAFE, 1=CAUTION, 2=DANGER) |
//+------------------------------------------------------------------+
int GetSafetyStatus()
{
if(!GlobalVariableCheck(EAS_GV_STATUS)) return EAS_STATUS_SAFE;
return (int)GlobalVariableGet(EAS_GV_STATUS);
}
//+------------------------------------------------------------------+
//| Check if we should close all positions NOW |
//+------------------------------------------------------------------+
bool ShouldCloseAllPositions()
{
if(!GlobalVariableCheck(EAS_GV_CLOSE_ALL)) return false;
return (GlobalVariableGet(EAS_GV_CLOSE_ALL) == 1);
}
//+------------------------------------------------------------------+
//| Check if new trades should be blocked |
//+------------------------------------------------------------------+
bool IsNewTradesBlocked()
{
if(!GlobalVariableCheck(EAS_GV_BLOCK_NEW)) return false;
return (GlobalVariableGet(EAS_GV_BLOCK_NEW) == 1);
}
//+------------------------------------------------------------------+
//| Check if trading is allowed |
//+------------------------------------------------------------------+
bool IsTradingAllowed()
{
if(!GlobalVariableCheck(EAS_GV_TRADING_ALLOWED)) return true;
return (GlobalVariableGet(EAS_GV_TRADING_ALLOWED) == 1);
}
//+------------------------------------------------------------------+
//| Acknowledge close signal (call after closing positions) |
//+------------------------------------------------------------------+
void AcknowledgeCloseSignal()
{
if(GlobalVariableCheck(EAS_GV_CLOSE_ALL))
GlobalVariableSet(EAS_GV_CLOSE_ALL, 0);
}
//+------------------------------------------------------------------+
//| Get status as text for logging |
//+------------------------------------------------------------------+
string GetSafetyStatusText()
{
int status = GetSafetyStatus();
switch(status)
{
case 0: return "SAFE";
case 1: return "CAUTION";
case 2: return "DANGER";
default: return "UNKNOWN";
}
}Step 2: Modify Your OnTick() Function
Find your OnTick() function and add the safety checks at the beginning:
void OnTick()
{
// ═══════════════════════════════════════════════════════════════
// STEP 1: Check Safety Score Signals (ADD THIS BLOCK)
// ═══════════════════════════════════════════════════════════════
// Check if we need to close all positions immediately
if(ShouldCloseAllPositions())
{
Print("Safety Score: Closing all positions due to risk signal");
CloseAllPositions(); // Your existing close function
AcknowledgeCloseSignal();
return; // Don't do anything else this tick
}
// Check if new trades are blocked
if(IsNewTradesBlocked())
{
// Manage existing positions only, don't open new ones
ManageExistingPositions(); // Your existing management function
return; // Skip opening new trades
}
// Check if trading is completely stopped
if(!IsTradingAllowed())
{
return; // Do nothing
}
// Log status change (optional)
static int last_status = -1;
int current_status = GetSafetyStatus();
if(current_status != last_status)
{
Print("Safety Score Status Changed: ", GetSafetyStatusText());
last_status = current_status;
}
// ═══════════════════════════════════════════════════════════════
// STEP 2: Your Normal Trading Logic (KEEP YOUR EXISTING CODE)
// ═══════════════════════════════════════════════════════════════
// Example: Check if we should open a new trade
if(ShouldOpenNewTrade()) // Your existing condition
{
OpenNewTrade(); // Your existing function
}
// Example: Manage existing positions
ManageExistingPositions(); // Your existing function
}Step 3: Add Input Parameter (Optional)
Let users choose whether to follow Safety Score signals:
input group "=== EA Safety Score Integration ==="
input bool Use_Safety_Score = true; // Enable Safety Score integrationThen wrap the checks:
void OnTick()
{
// Check Safety Score signals (if enabled)
if(Use_Safety_Score)
{
if(ShouldCloseAllPositions())
{
// ... close logic
}
// ... other checks
}
// Your normal trading logic...
}Method 2: Advanced Integration (Using Class)
For more control, use the provided interface class.
Step 1: Include the Interface File
- Download
EASafetyScore_EAInterface.mqhfrom our website - Copy it to your
MQL5/Include/folder - Add to your EA:
#include <EASafetyScore_EAInterface.mqh>Step 2: Create Instance and Use
// Global variable
CEASafetyScoreInterface g_safety;
int OnInit()
{
// Initialize Safety Score interface
if(!g_safety.Init())
{
Print("Warning: EA Safety Score indicator not detected");
Print("EA will run without safety protection");
}
else
{
Print("EA Safety Score integration active");
}
// Your existing initialization...
return INIT_SUCCEEDED;
}
void OnTick()
{
// Update safety status
g_safety.Update();
// Check for close signal
if(g_safety.ShouldCloseAllPositions())
{
CloseAllPositions();
g_safety.AcknowledgeCloseSignal();
return;
}
// Check if we can open new trades
if(!g_safety.ShouldOpenNewTrade())
{
// Only manage existing positions
ManageExistingPositions();
return;
}
// Your normal trading logic...
}Complete Working Example
Here's a complete example of a simple Grid EA with Safety Score integration:
//+------------------------------------------------------------------+
//| SimpleGridEA_Safety |
//| Example EA with Safety Score Integration |
//+------------------------------------------------------------------+
#property copyright "Your Name"
#property link "https://easafetyscore.com"
#property version "1.00"
// Input parameters
input group "=== Trading Settings ==="
input double LotSize = 0.01;
input int GridPips = 50;
input int TakeProfitPips = 100;
input group "=== EA Safety Score Integration ==="
input bool Use_Safety_Score = true;
input bool Close_On_Danger_Signal = true;
// Safety Score functions
string EAS_GV_STATUS = "EAS_SafetyScore_Status";
string EAS_GV_CLOSE_ALL = "EAS_Close_All_Signal";
string EAS_GV_BLOCK_NEW = "EAS_Block_New_Trades";
int EAS_STATUS_SAFE = 0;
int EAS_STATUS_CAUTION = 1;
int EAS_STATUS_DANGER = 2;
//+------------------------------------------------------------------+
//| Check Safety Score signals |
//+------------------------------------------------------------------+
bool ShouldCloseAllPositions()
{
if(!Use_Safety_Score) return false;
if(!GlobalVariableCheck(EAS_GV_CLOSE_ALL)) return false;
return (GlobalVariableGet(EAS_GV_CLOSE_ALL) == 1);
}
bool IsNewTradesBlocked()
{
if(!Use_Safety_Score) return false;
if(!GlobalVariableCheck(EAS_GV_BLOCK_NEW)) return false;
return (GlobalVariableGet(EAS_GV_BLOCK_NEW) == 1);
}
int GetSafetyStatus()
{
if(!Use_Safety_Score) return EAS_STATUS_SAFE;
if(!GlobalVariableCheck(EAS_GV_STATUS)) return EAS_STATUS_SAFE;
return (int)GlobalVariableGet(EAS_GV_STATUS);
}
void AcknowledgeCloseSignal()
{
if(GlobalVariableCheck(EAS_GV_CLOSE_ALL))
GlobalVariableSet(EAS_GV_CLOSE_ALL, 0);
}
//+------------------------------------------------------------------+
//| Close all positions |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
Print("Closing all positions due to Safety Score signal");
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
string symbol = PositionGetString(POSITION_SYMBOL);
// Only close positions for this symbol
if(symbol != _Symbol) continue;
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.action = TRADE_ACTION_DEAL;
request.position = ticket;
request.symbol = symbol;
request.volume = PositionGetDouble(POSITION_VOLUME);
request.deviation = 10;
request.comment = "Safety Score Close";
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
request.type = (pos_type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
request.price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK);
if(!OrderSend(request, result))
{
Print("Close failed for ticket ", ticket, " Error: ", GetLastError());
}
else
{
Print("Closed position ", ticket);
}
}
}
//+------------------------------------------------------------------+
//| Count open positions |
//+------------------------------------------------------------------+
int CountOpenPositions()
{
int count = 0;
for(int i = 0; i < PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetString(POSITION_SYMBOL) == _Symbol)
count++;
}
return count;
}
//+------------------------------------------------------------------+
//| Open new trade |
//+------------------------------------------------------------------+
void OpenTrade(ENUM_ORDER_TYPE order_type)
{
MqlTradeRequest request = {};
MqlTradeResult result = {};
double price = (order_type == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
double tp = (order_type == ORDER_TYPE_BUY) ? price + (TakeProfitPips * _Point) : price - (TakeProfitPips * _Point);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = LotSize;
request.type = order_type;
request.price = price;
request.tp = tp;
request.deviation = 10;
request.comment = "Grid EA";
if(!OrderSend(request, result))
{
Print("Trade failed. Error: ", GetLastError());
}
else
{
Print("Trade opened. Ticket: ", result.order);
}
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
if(Use_Safety_Score)
{
if(GlobalVariableCheck(EAS_GV_STATUS))
{
Print("✓ EA Safety Score integration active");
}
else
{
Print("⚠ Warning: Safety Score indicator not detected");
Print(" Please attach EA Safety Score indicator to a chart");
}
}
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// ═══════════════════════════════════════════════════════════════
// SAFETY SCORE CHECKS
// ═══════════════════════════════════════════════════════════════
// Check 1: Close all positions signal
if(ShouldCloseAllPositions())
{
Print("SAFETY SCORE: Close all signal received!");
CloseAllPositions();
AcknowledgeCloseSignal();
return; // Don't trade this tick
}
// Check 2: Block new trades
if(IsNewTradesBlocked())
{
static bool logged = false;
if(!logged)
{
Print("SAFETY SCORE: New trades blocked (managing existing only)");
logged = true;
}
// Don't return - we still want to manage existing positions
}
// Log status changes
static int last_status = -1;
int current_status = GetSafetyStatus();
if(current_status != last_status)
{
string status_text = (current_status == 0) ? "SAFE" : (current_status == 1) ? "CAUTION" : "DANGER";
Print("SAFETY SCORE: Status changed to ", status_text);
last_status = current_status;
}
// ═══════════════════════════════════════════════════════════════
// YOUR TRADING LOGIC
// ═══════════════════════════════════════════════════════════════
// Example: Simple grid - open buy if no positions
if(CountOpenPositions() == 0 && !IsNewTradesBlocked())
{
OpenTrade(ORDER_TYPE_BUY);
}
}What the Indicator Does vs What Your EA Does
Indicator Responsibilities:
- ✅ Calculate safety score based on market conditions
- ✅ Set global variables to communicate status
- ✅ Send Telegram alerts
- ✅ Toggle AutoTrading button (optional)
- ❌ Cannot close your positions
- ❌ Cannot open trades
Your EA Responsibilities:
- ✅ Read global variables from indicator
- ✅ Close positions when signal received
- ✅ Stop opening new trades when blocked
- ✅ Manage your specific trading logic
Testing Your Integration
Step 1: Install Both
- Attach EA Safety Score Indicator to one chart (e.g., EURUSD)
- Attach Your EA to the same or different chart
Step 2: Check Global Variables
In MT5, go to Tools → Global Variables. You should see:
EAS_SafetyScore_StatusEAS_Trading_AllowedEAS_Block_New_TradesEAS_Close_All_Signal
Step 3: Test Close Signal
- Open a small test position manually
- In your EA, temporarily add:
GlobalVariableSet(EAS_GV_CLOSE_ALL, 1); - Your EA should close the position
Step 4: Test Block Signal
- Enable trading in your EA
- Set:
GlobalVariableSet(EAS_GV_BLOCK_NEW, 1); - Your EA should stop opening new trades
Troubleshooting
Problem: My EA doesn't respond to Safety Score
Solution 1: Check if Safety Score is running
if(!GlobalVariableCheck("EAS_SafetyScore_Status"))
{
Print("Safety Score indicator not detected!");
}Solution 2: Verify variable names match exactly
- Correct:
"EAS_SafetyScore_Status" - Wrong:
"EAS_Safety_Score_Status"(extra underscore)
Solution 3: Check if your EA is checking in OnTick()
void OnTick()
{
// Must check every tick!
if(ShouldCloseAllPositions())
{
// ...
}
}Problem: Positions don't close
Solution: Make sure you have the close logic:
if(ShouldCloseAllPositions())
{
CloseAllPositions(); // <-- You need this function!
AcknowledgeCloseSignal(); // <-- Important!
}Problem: EA keeps opening trades in DANGER mode
Solution: Add the block check before opening:
if(IsNewTradesBlocked())
{
return; // Don't open new trades
}FAQ
Q: Do I need to modify my EA code? A: Yes. The indicator sends signals, but your EA must read and act on them.
Q: Can the indicator close my trades automatically? A: No. Only EAs can close trades. You must add the close logic to your EA.
Q: What if I don't want to modify my EA? A: You have two options:
- Use the AutoTrading toggle feature (stops new trades only)
- Ask your EA provider to add Safety Score integration
Q: Can I use this with any EA? A: Yes, but you need the EA's source code (.mq5 file) to add the integration. If you only have the compiled version (.ex5), you cannot modify it.
Q: What programming language is this? A: MQL5 - the language used by MetaTrader 5.
Quick Reference Card
Copy-Paste Code Block
// Add these at the top of your EA
string EAS_GV_CLOSE_ALL = "EAS_Close_All_Signal";
string EAS_GV_BLOCK_NEW = "EAS_Block_New_Trades";
bool ShouldCloseAllPositions() {
return (GlobalVariableCheck(EAS_GV_CLOSE_ALL) && GlobalVariableGet(EAS_GV_CLOSE_ALL) == 1);
}
bool IsNewTradesBlocked() {
return (GlobalVariableCheck(EAS_GV_BLOCK_NEW) && GlobalVariableGet(EAS_GV_BLOCK_NEW) == 1);
}
// Add this in OnTick()
void OnTick() {
if(ShouldCloseAllPositions()) {
CloseAllPositions(); // Your close function
GlobalVariableSet(EAS_GV_CLOSE_ALL, 0);
return;
}
if(IsNewTradesBlocked()) {
return; // Don't open new trades
}
// Your trading logic...
}Support
Need help integrating?
- Check our examples: Download sample EAs from our website
- Forum: Post questions in our community forum
- Contact: Email support@easafetyscore.com
Remember: The Safety Score indicator is your "co-pilot" - it watches the road and warns you of danger, but YOU (your EA) must steer the car and hit the brakes!