preview
Building AI-Powered Trading Systems in MQL5 (Part 13): Letting the Assistant Execute Trades Behind an Approval Card

Building AI-Powered Trading Systems in MQL5 (Part 13): Letting the Assistant Execute Trades Behind an Approval Card

MetaTrader 5 — Integration |
2 153 0
Allan Munene Mutiiria
Allan Munene Mutiiria

Introduction

Our assistant can already see charts, read indicators, list open positions and history, and reason about setups. The remaining gap is execution: it can recommend trades but cannot act on them. Simply exposing an order tool without safeguards turns helpful analysis into an operational hazard, since one incorrect symbol, wrong volume, or blind "close all" could produce real, irreversible losses. This article is for MetaQuotes Language 5 (MQL5) developers who want a practical compromise: let the assistant initiate actions, such as opening, closing, modifying, and deleting orders and drawing on the chart, while keeping a single, auditable human decision before any account change.

In our previous article (Part 12), we gave the assistant vision and read-only tools. In this article, we make the acceptance criteria explicit. An acceptable human-in-the-loop design must pause the tool loop when an action is proposed, present an approval card that spells out the exact operation and the affected trades, normalize the volume to broker limits and run basic parameter checks before execution, leaving the remaining broker rules to the trade server, scope actions to the trades the assistant is allowed to touch, and resume the conversation so the model can react to the result. We implement that flow: action tools are advertised separately from read tools, action calls are queued and gated for approval, and every execution runs through a single validated executor that enforces limits and ownership. The approval gate holds while the "Action_AutoApprove" input stays off, which is its default. We will cover the following topics:

  1. Understanding Action Tools and the Approval Gate
  2. Defining the Action Tools
  3. Executing Actions Safely
  4. The Approval Card and the Paused Tool Loop
  5. Visualization
  6. Conclusion

By the end of this article, we will be able to:

  • Offer the model a set of action tools that place, close, modify, and delete trades and draw on the chart.
  • Execute each action safely, validating the request, sizing the volume to broker limits, and scoping it to the trades it is allowed to touch.
  • Hold every trade action behind an approval card while auto-approval is off, pausing the tool loop until we approve or reject, then resuming so the model can finish its turn.


Understanding Action Tools and the Approval Gate

The tools from the previous part all had one thing in common: they only ever read. Asking for open positions or an indicator value changes nothing, so the model could call them freely, and we could run them the instant they arrived. Action tools break that safety by design. A tool that places or closes a trade changes the account the moment it runs, and the model deciding to call it is no different, mechanically, from deciding to call a data tool. Left unguarded, an assistant that can read your positions and also close them will, sooner or later, close one you did not want closed. So the first idea of this part is a hard line between the two kinds of tool: reads execute immediately as before, while actions are treated as proposals, not commands.

That line is enforced by separating proposing from executing. When the model calls an action tool, we do not run it. Instead, we describe exactly what it wants to do (order type, size, stop, target, and affected trade) and present that as an approval card with two choices. With "Action_AutoApprove" off, which is the default, nothing reaches the trade server until we approve. Because the model may line up several actions at once, we hold them in a queue and raise one card at a time, so each decision is made on its own rather than swept along with the others. Approving runs that one action; rejecting refuses it; and either way, the conversation, which has been paused mid-turn, picks up where it left off so the model can react to what happened and finish its answer.

Two additional safeguards support this gate. Before any approved action runs, it passes a validation step that checks the request makes sense and sizes the volume to the broker's limits, so a malformed order is refused rather than sent. The remaining broker rules, such as the stop and freeze levels and the side of a pending price, are left to the trade server, which refuses a breaking order and reports why. Every trade is tagged with its origin (this program, another robot, or manual). This lets broad instructions (for example, 'close everything') be limited to the trades the assistant is allowed to touch. In practice, this means the assistant does the thinking and the reaching, while we keep the one thing that must stay human: the final yes on anything that moves money. See an illustration of our objectives below.

AI TRADING APPROVAL ROADMAP


Defining the Action Tools

Before the model can act, we have to offer it the actions. We extend the tool schema with the write tools, gated behind their own switch, and add a predicate that marks which tools change the account.

Advertising the Tools

First, we build the tool menu in one function and append the action tools only when actions are enabled.

//+------------------------------------------------------------------+
//| Build the tools schema advertised to the API                     |
//+------------------------------------------------------------------+
string AiToolsDefinitionJson()
  {
//--- Advertise nothing when both tool families are disabled
   if(!Enable_AI_Tools && !Enable_AI_Actions)
      return "";
   string t = "[";
   bool first = true;
//--- Advertise the read-only data tools
   if(Enable_AI_Tools)
     {
      //--- Append the six data tools as one comma-joined block
      t += "{\"type\":\"function\",\"function\":{\"name\":\"get_indicator\","
           "\"description\":\"Latest value of a standard indicator on the current or given timeframe.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"name\":{\"type\":\"string\",\"enum\":[\"RSI\",\"MA\",\"MACD\",\"ATR\",\"STOCH\"]},"
           "\"period\":{\"type\":\"integer\"},"
           "\"timeframe\":{\"type\":\"string\"}},\"required\":[\"name\"]}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"get_open_positions\","
           "\"description\":\"List all open positions.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{}}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"get_pending_orders\","
           "\"description\":\"List working pending orders with the tickets needed to modify or delete them.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{}}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"get_chart_objects\","
           "\"description\":\"List drawn chart objects (trendlines, lines, rectangles, fibos) with price levels.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{}}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"get_trade_history\","
           "\"description\":\"Summarize recent closed trades.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{\"days\":{\"type\":\"integer\"}}}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"get_economic_calendar\","
           "\"description\":\"Upcoming calendar events for the symbol's currencies.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{\"days\":{\"type\":\"integer\"}}}}}";
      first = false;
     }
//--- Advertise the trade action and drawing tools
   if(Enable_AI_Actions)
     {
      //--- Join onto any earlier block with a comma
      if(!first)
         t += ",";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"get_position_owners\","
           "\"description\":\"Count open positions by owner: this EA, manual trades or other robots. Call this before any bulk close, then ask the user which scope they mean.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"symbol\":{\"type\":\"string\"}}}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"place_order\","
           "\"description\":\"Place a market or pending order. Requires user approval before execution.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"symbol\":{\"type\":\"string\"},"
           "\"direction\":{\"type\":\"string\",\"enum\":[\"buy\",\"sell\"]},"
           "\"order_kind\":{\"type\":\"string\",\"enum\":[\"market\",\"limit\",\"stop\"]},"
           "\"lots\":{\"type\":\"number\",\"description\":\"Trade volume in lots.\"},"
           "\"price\":{\"type\":\"number\",\"description\":\"Absolute trigger price for pending orders, never a distance.\"},"
           "\"sl\":{\"type\":\"number\",\"description\":\"Stop loss as an absolute price level. Use sl_points instead when the user gives a distance.\"},"
           "\"tp\":{\"type\":\"number\",\"description\":\"Take profit as an absolute price level. Use tp_points instead when the user gives a distance.\"},"
           "\"sl_points\":{\"type\":\"integer\",\"description\":\"Stop distance from entry in broker points. The EA converts it, so pass the number the user said and never compute a price yourself.\"},"
           "\"tp_points\":{\"type\":\"integer\",\"description\":\"Target distance from entry in broker points. The EA converts it, so pass the number the user said and never compute a price yourself.\"},"
           "\"comment\":{\"type\":\"string\"}},\"required\":[\"direction\",\"lots\"]}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"modify_position\","
           "\"description\":\"Change the SL or TP of an open position, move it to breakeven or trail it.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"ticket\":{\"type\":\"integer\"},"
           "\"sl\":{\"type\":\"number\",\"description\":\"Stop loss as an absolute price level, never a distance.\"},"
           "\"tp\":{\"type\":\"number\",\"description\":\"Take profit as an absolute price level, never a distance.\"},"
           "\"sl_points\":{\"type\":\"integer\",\"description\":\"Stop distance from the entry price in broker points, converted by the EA.\"},"
           "\"tp_points\":{\"type\":\"integer\",\"description\":\"Target distance from the entry price in broker points, converted by the EA.\"},"
           "\"breakeven\":{\"type\":\"boolean\",\"description\":\"Move the stop loss to the entry price.\"},"
           "\"trail_points\":{\"type\":\"integer\",\"description\":\"Stop distance from current price in broker points. One pip is ten points on 5-digit and 3-digit symbols, so 20 pips is 200 points.\"}},"
           "\"required\":[\"ticket\"]}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"close_position\","
           "\"description\":\"Close a position by ticket, or sweep a symbol. A symbol sweep needs scope; call get_position_owners first to see who owns what, then ask the user before sweeping.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"ticket\":{\"type\":\"integer\"},"
           "\"symbol\":{\"type\":\"string\"},"
           "\"fraction\":{\"type\":\"number\",\"description\":\"Portion of the position to close as a decimal, so 0.5 is half.\"},"
           "\"lots\":{\"type\":\"number\",\"description\":\"Exact volume to close in lots, which overrides fraction.\"},"
           "\"scope\":{\"type\":\"string\",\"enum\":[\"this_ea\",\"manual\",\"other_eas\",\"everything\"],"
           "\"description\":\"Whose positions a symbol sweep may close. Required for a sweep and ignored when a ticket is given. Never assume it, ask the user first.\"}}}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"close_all\","
           "\"description\":\"Close open positions in bulk. Call get_position_owners first to see who owns what, then ask the user which scope to close before calling this tool.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"filter\":{\"type\":\"string\",\"enum\":[\"all\",\"profit_only\",\"loss_only\",\"chart_symbol\"],"
           "\"description\":\"Which results to include, independent of who owns the position.\"},"
           "\"scope\":{\"type\":\"string\",\"enum\":[\"this_ea\",\"manual\",\"other_eas\",\"everything\"],"
           "\"description\":\"Whose positions may be closed. this_ea is only trades this EA opened, manual is hand-placed trades, other_eas belongs to other robots. Never assume it, ask the user first.\"}},"
           "\"required\":[\"scope\"]}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"modify_order\","
           "\"description\":\"Change the price, SL or TP of a pending order.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"ticket\":{\"type\":\"integer\"},"
           "\"price\":{\"type\":\"number\",\"description\":\"New absolute trigger price.\"},"
           "\"sl\":{\"type\":\"number\",\"description\":\"Stop loss as an absolute price level, never a distance.\"},"
           "\"tp\":{\"type\":\"number\",\"description\":\"Take profit as an absolute price level, never a distance.\"}},"
           "\"required\":[\"ticket\"]}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"delete_order\","
           "\"description\":\"Delete a pending order by ticket.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"ticket\":{\"type\":\"integer\"}},\"required\":[\"ticket\"]}}},";
      t += "{\"type\":\"function\",\"function\":{\"name\":\"draw_on_chart\","
           "\"description\":\"Draw a horizontal level or a text label on the chart at a price.\","
           "\"parameters\":{\"type\":\"object\",\"properties\":{"
           "\"kind\":{\"type\":\"string\",\"enum\":[\"hline\",\"label\"]},"
           "\"price\":{\"type\":\"number\",\"description\":\"Absolute price level to draw at.\"},"
           "\"text\":{\"type\":\"string\"}},\"required\":[\"price\"]}}}";
     }
   t += "]";
   return t;

We keep the read-only data tools as they were and append the action block only when the "Enable_AI_Actions" input is on, so a build can ship with the assistant able to see but not touch. The action block also carries two tools that never wait for approval: "get_position_owners", which only reads, and "draw_on_chart", which only annotates the chart. Each action schema names its arguments and, in its description, tells the model how we expect it to behave, for instance, passing point distances rather than computing price levels itself, and calling "get_position_owners" before any bulk close so it asks us which trades it may sweep. The "close_all" schema requires a scope, so the model cannot sweep without naming one, and a symbol sweep through "close_position" that arrives without a scope is refused by the executor, which returns the owner breakdown instead. We lean on those descriptions to steer the model's judgement before an action ever reaches us. Advertising a tool is only half the story, since the loop still has to tell an action apart from a harmless read.

Marking a Tool as an Action

We add one predicate that answers the single question the tool loop turns on: does this call change the account?

//+------------------------------------------------------------------+
//| Check whether a tool name is a trade action                      |
//+------------------------------------------------------------------+
bool AiIsActionTool(const string toolName)
  {
//--- Match against the full trade-action tool set
   return (toolName == "place_order"
           || toolName == "modify_position"
           || toolName == "close_position"
           || toolName == "close_all"
           || toolName == "modify_order"
           || toolName == "delete_order");
  }

We define the "AiIsActionTool" function to return true for exactly the six executing tools and false for everything else, deliberately leaving "draw_on_chart" out since drawing a line changes nothing on the account. We treat this one test as the fork the whole safety model rests on: a call that fails it runs immediately like any data tool, while a call that passes it is held for approval. With the actions advertised and cleanly identified, we can build the executors that carry them out, which is handled in the next section.


Executing Actions Safely

An approved action still has to reach the trade server correctly, so before the executors, we build the small helpers they lean on: reading arguments, the safety gate, sizing to broker limits, and ownership scoping. We start with how an executor reads what the model sent.

Reading Tool Arguments

We read every argument through typed helpers that return a fallback when the key is missing, so a malformed call never crashes an executor.

//+------------------------------------------------------------------+
//| Read a numeric JSON field with a fallback                        |
//+------------------------------------------------------------------+
double AiJsonNum(JsonValue &obj, const string key, const double defVal)
  {
//--- Return the fallback when the key is absent
   JsonValue *v = obj.FindChildByKey(key);
   return (v == NULL) ? defVal : v.ToDouble();
  }

The "AiJsonNum" function looks up a key and returns either its number or the default we pass, and we add the siblings "AiJsonInt", "AiJsonText", "AiJsonFlag", and "AiJsonHas" with the same shape for integers, strings, booleans, and a bare presence test. Reading through these means an executor can ask for an optional stop or comment without first checking whether the model supplied it. With arguments safe to read, the next helper decides whether an action is even allowed.

The Safety Gate

Here, we put every action through one validator that enforces the user's limits before anything touches the trade server.

//+------------------------------------------------------------------+
//| Validate an action against the safety limits                     |
//+------------------------------------------------------------------+
string AiValidateAction(const string sym, const double lots, const bool opensExposure)
  {
//--- Block everything when actions are disabled
   if(!Enable_AI_Actions)
      return "AI trade actions are disabled in the EA inputs.";
//--- Enforce the chart-symbol restriction
   if(Action_ChartSymbolOnly && sym != Symbol())
      return "Actions are restricted to " + Symbol() + " by the EA inputs.";
//--- Reject symbols the terminal cannot select
   if(!SymbolSelect(sym, true))
      return "Unknown symbol '" + sym + "'.";
//--- Enforce the per-action lot ceiling
   if(lots > Action_MaxLots + 0.0000001)
      return "Requested " + AiFormatLots(sym, lots) + " lots exceeds the Action_MaxLots limit of "
             + AiFormatLots(sym, Action_MaxLots) + ".";
//--- Enforce the open-position ceiling for exposure-adding actions
   if(opensExposure && Action_MaxPositions > 0 && PositionsTotal() >= Action_MaxPositions)
      return "Open position limit (" + IntegerToString(Action_MaxPositions) + ") reached.";
//--- Report a clean pass
   return "";
  }

The "AiValidateAction" function returns an empty string on a clean pass and an explanatory message on any failure, checking the master switch, the chart-symbol restriction, the symbol's validity, the per-action lot ceiling, and the open-position limit in turn. Returning the reason as text rather than a bare flag lets the executor hand that reason straight back to the model and the card. The validator checks only the ceiling, since close actions call it with no volume at all, so the order executor checks the lower bound itself.

Sizing to Broker Limits

In this function, we snap any requested volume to what the broker will actually accept before sending it.

//+------------------------------------------------------------------+
//| Clamp a lot size to the symbol volume constraints                |
//+------------------------------------------------------------------+
double AiNormalizeLots(const string sym, double lots)
  {
//--- Pull the broker volume constraints
   const double minLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
   const double maxLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
   const double step   = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
//--- Snap to the volume step
   if(step > 0.0)
      lots = MathFloor(lots / step + 0.5) * step;
//--- Clamp into the allowed range
   if(lots < minLot)
      lots = minLot;
   if(lots > maxLot)
      lots = maxLot;
   return lots;
  }

The "AiNormalizeLots" function snaps a requested volume to the symbol's step and clamps it between the minimum and maximum the broker allows. Because that clamp would turn a zero or negative volume into the minimum lot, the executor rejects such a volume before it ever gets here. We keep this apart from the validator on purpose, since rounding can raise a volume, which is why the executor validates once, normalizes, then validates again. Before the executor runs, one more concern remains: whose trades an action is permitted to touch.

Ownership Scoping

We tag every trade by who opened it, then test a trade's owner against the scope an action asked for.

//+------------------------------------------------------------------+
//| Name the owner group a magic number belongs to                   |
//+------------------------------------------------------------------+
string AiOwnerGroup(const long magic)
  {
//--- Split trades into this EA, hand-placed orders and other robots
   if(magic == (long)MagicNumber)
      return "this_ea";
   if(magic == 0)
      return "manual";
   return "other_eas";
  }
//+------------------------------------------------------------------+
//| Test a position owner against a requested scope                  |
//+------------------------------------------------------------------+
bool AiScopeMatches(const string scope, const long magic)
  {
//--- Everything matches the widest scope
   if(scope == "everything")
      return true;
   return (AiOwnerGroup(magic) == scope);
  }

We define the "AiOwnerGroup" function to name a trade's owner from its magic number, this program, a manual trade, or another robot, and the "AiScopeMatches" function to test that owner against a requested scope, with "everything" matching all. We build the sweep-facing reader "AiOwnershipBreakdown" and the card line "AiTicketOwnerLine" on top of these, so a bulk close can report who owns what before we approve it. With the arguments, the gate, the sizing, and the scoping in place, we can write the executor that puts them to work.

//+------------------------------------------------------------------+
//| Execute a place_order action                                     |
//+------------------------------------------------------------------+
string AiActionPlaceOrder(JsonValue &args)
  {
//--- Read the order arguments with safe defaults
   const string sym = AiActionResolveSymbol(args);
   string dir  = AiJsonText(args, "direction", "");
   string kind = AiJsonText(args, "order_kind", "market");
   double lots = AiJsonNum(args, "lots", LotSize);
   double price = AiJsonNum(args, "price", 0.0);
   double sl = AiJsonNum(args, "sl", 0.0);
   double tp = AiJsonNum(args, "tp", 0.0);
   string comment = AiJsonText(args, "comment", "AI action");
   StringToUpper(dir);
   StringToUpper(kind);
//--- Resolve the trade direction
   const bool isBuy  = (StringFind(dir, "BUY") >= 0);
   const bool isSell = (StringFind(dir, "SELL") >= 0);
   if(!isBuy && !isSell)
      return "place_order needs direction buy or sell.";
//--- Reject a non-numeric or non-positive volume before any rounding
   if(!MathIsValidNumber(lots) || lots <= 0.0)
      return "Blocked: lots must be a positive number.";
//--- Treat a blank order kind as a market order
   if(StringLen(kind) == 0)
      kind = "MARKET";
//--- Reject any order kind outside the advertised set
   if(kind != "MARKET" && kind != "LIMIT" && kind != "STOP")
      return "Blocked: order_kind must be market, limit or stop.";
//--- Run the safety gate before touching the trade server
   string err = AiValidateAction(sym, lots, true);
   if(StringLen(err) > 0)
      return "Blocked: " + err;
//--- Re-check the ceiling after snapping, since broker limits can raise the volume
   const double askedLots = lots;
   lots = AiNormalizeLots(sym, lots);
   err = AiValidateAction(sym, lots, false);
   if(StringLen(err) > 0)
      return "Blocked: " + AiFormatLots(sym, askedLots) + " lots becomes "
             + AiFormatLots(sym, lots) + " after broker volume rounding. " + err;
//--- Map direction and kind onto the order type
   const bool isMarket = (kind == "MARKET");
   const bool isLimit  = (kind == "LIMIT");
   const bool isStop   = (kind == "STOP");
   ENUM_ORDER_TYPE type = isBuy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   if(isLimit)
      type = isBuy ? ORDER_TYPE_BUY_LIMIT : ORDER_TYPE_SELL_LIMIT;
   if(isStop)
      type = isBuy ? ORDER_TYPE_BUY_STOP  : ORDER_TYPE_SELL_STOP;
   if(!isMarket && price <= 0.0)
      return "Pending orders need a positive trigger price.";
//--- Resolve the price the stops are measured from
   const double refPx = isMarket
                        ? (isBuy ? SymbolInfoDouble(sym, SYMBOL_ASK) : SymbolInfoDouble(sym, SYMBOL_BID))
                        : price;
//--- Convert point distances into levels when no absolute level was given
   const long slPts = AiJsonInt(args, "sl_points", 0);
   const long tpPts = AiJsonInt(args, "tp_points", 0);
   if(sl <= 0.0 && slPts > 0)
      sl = AiLevelFromPoints(sym, refPx, slPts, isBuy);
   if(tp <= 0.0 && tpPts > 0)
      tp = AiLevelFromPoints(sym, refPx, tpPts, !isBuy);
//--- Normalize prices to the symbol digits
   const int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
   sl = NormalizeDouble(sl, digits);
   tp = NormalizeDouble(tp, digits);
   price = NormalizeDouble(price, digits);
//--- Reject stops that sit on the wrong side of the entry
   if(sl > 0.0 && (isBuy ? (sl >= refPx) : (sl <= refPx)))
      return "Blocked: the stop loss must be " + (isBuy ? "below" : "above") + " the entry price.";
   if(tp > 0.0 && (isBuy ? (tp <= refPx) : (tp >= refPx)))
      return "Blocked: the take profit must be " + (isBuy ? "above" : "below") + " the entry price.";
//--- Dispatch to a market or pending open
   bool ok = false;
   if(isMarket)
      ok = g_ai_trade.PositionOpen(sym, type, lots, 0.0, sl, tp, comment);
   else
      ok = g_ai_trade.OrderOpen(sym, type, lots, 0.0, price, sl, tp, ORDER_TIME_GTC, 0, comment);
   if(!ok)
      return "Trade server refused: " + g_ai_trade.ResultRetcodeDescription();
//--- Report the executed order
   return "Executed: " + Ai_OrderTypeLabel(type) + " " + AiFormatLots(sym, lots) + " " + sym
          + " ticket #" + IntegerToString((long)g_ai_trade.ResultOrder()) + ".";

Here, we define the "AiActionPlaceOrder" function to read its arguments through the typed helpers, default the symbol through "AiActionResolveSymbol", and reject a volume that is not a positive number or an order kind outside market, limit, and stop. A missing volume falls back to the "LotSize" input, which the gate still checks. We then run the gate, normalize the volume, validate again, and map the direction and kind onto an order type. Where the model passed point distances, we convert them to price levels with the "AiLevelFromPoints" function, reject any stop or target on the wrong side of the entry, and finally open a market or pending order, returning the outcome as plain text formatted through "AiFormatLots". We do not pre-check the broker's stop level, freeze level, trade mode, or the side of a pending price against the market. The trade server enforces those, and its refusal comes back to the model and the card as the "Trade server refused" message. The rest of the sibling executors follow this same validate-then-act skeleton. One place now has to route an approved call to the right one of them.

Routing to the Executor

We add the dispatcher that parses the argument JSON once and forwards to the matching executor by name.

//+------------------------------------------------------------------+
//| Execute an approved action by tool name                          |
//+------------------------------------------------------------------+
string AiExecuteAction(const string toolName, const string argsJson)
  {
//--- Parse the argument object
   JsonValue args;
   string a = argsJson;
   if(StringLen(a) == 0)
      a = "{}";
   int idx = 0;
   char buf[];
   int len = StringToCharArray(a, buf, 0, WHOLE_ARRAY, CP_UTF8);
   args.DeserializeFromArray(buf, len, idx);
//--- Route to the matching executor
   if(toolName == "place_order")
      return AiActionPlaceOrder(args);
   if(toolName == "modify_position")
      return AiActionModifyPosition(args);
   if(toolName == "close_position")
      return AiActionClosePosition(args);
   if(toolName == "close_all")
      return AiActionCloseAll(args);
   if(toolName == "modify_order")
      return AiActionModifyOrder(args);
   if(toolName == "delete_order")
      return AiActionDeleteOrder(args);
   return "Unknown action tool: " + toolName;
  }

The "AiExecuteAction" function deserializes the raw argument string once and matches the tool name to its executor, returning that executor's text. This is the single hinge the approval step calls once we say yes, and keeping it in one place means every action shares the same entry point. One tool remains that acts without touching the account: the drawing tool, so we handle it next.

Drawing on the Chart

We add the one non-account action, drawing a level or label, which runs inline like a data tool rather than waiting for approval. If you want to expand the drawing tools, you can add more. We added this specific one to illustrate that the toolset can be extended when needed.

//+------------------------------------------------------------------+
//| Tool: draw a level or label on the chart                         |
//+------------------------------------------------------------------+
string AiToolDrawOnChart(const string argsJson)
  {
//--- Parse the argument object
   JsonValue args;
   string aj = argsJson;
   if(StringLen(aj) == 0)
      aj = "{}";
   int pIdx = 0;
   char pBuf[];
   int pLen = StringToCharArray(aj, pBuf, 0, WHOLE_ARRAY, CP_UTF8);
   args.DeserializeFromArray(pBuf, pLen, pIdx);
//--- Read the drawing arguments
   string kind = AiJsonText(args, "kind", "hline");
   StringToLower(kind);
   const double price = AiJsonNum(args, "price", 0.0);
   const string text  = AiJsonText(args, "text", "AI level");
   if(price <= 0.0)
      return "draw_on_chart needs a positive price.";
//--- Build a unique object name
   static int drawId = 0;
   drawId++;
   const string name = "AI_Draw_" + IntegerToString(drawId) + "_" + IntegerToString((long)TimeCurrent());
//--- Create the requested object with the existing drawing helpers
   if(kind == "label")
      AiCreateTextLabel(name, TimeCurrent(), price, text, g_ai_accent, ANCHOR_LEFT);
   else
      AiCreateHLine(name, price, g_ai_accent, STYLE_DASH, text);
   ChartRedraw();
   return "Drawn " + kind + " at " + AiFormatPrice(Symbol(), price) + ".";
  }

Finally, we define the "AiToolDrawOnChart" function to read a kind, a price, and an optional text, then create either a labeled horizontal line or a text object through our existing "AiCreateHLine" and "AiCreateTextLabel" helpers, under a unique name. Because it only annotates the chart and never the account, "AiIsActionTool" leaves it out, and the loop runs it immediately. With every executor in place and cleanly separated from the reads, the remaining question is how an action pauses for our approval and how the conversation resumes afterward, which is what we handle in the next section.


The Approval Card and the Paused Tool Loop

Everything so far has prepared the ground; now we build the gate itself. An action call has to stop the loop, raise a card, and wait, then resume once we decide. We start with the state that remembers a paused turn.

//+------------------------------------------------------------------+
//| Pending AI Action State                                          |
//+------------------------------------------------------------------+
//--- Fixed first line of an approval card message used for detection
#define AI_ACTION_CARD_HEADER "Action approval required"
bool   g_ai_actionActive = false; // Approval card is awaiting a decision
string g_ai_actionCardText = "";  // Full text of the current approval card
int    g_ai_actionChatId = -1;    // Chat id that owns the pending approval

//+------------------------------------------------------------------+
//| Pending Action Queue                                             |
//+------------------------------------------------------------------+
string g_ai_actQueueIds[];       // Tool-call ids of the parked round
string g_ai_actQueueNames[];     // Tool names of the parked round
string g_ai_actQueueArgs[];      // Raw argument JSON of the parked round
string g_ai_actQueueResults[];   // Tool results filled as calls resolve
bool   g_ai_actQueueResolved[];  // Per-call resolution flags
int    g_ai_actionIndex = -1;    // Queue index of the card on screen
string g_ai_actionMessages = ""; // Parked messages JSON without the closing bracket
string g_ai_actionToolsJson = "";// Parked tools schema for the resumed loop
int    g_ai_actionRound = 0;     // Parked loop round of the interruption
double g_ai_actionTemp = 1.0;    // Parked sampling temperature
ulong  g_ai_actionShownMs = 0;   // Tick count when the current card appeared

First, we keep "g_ai_actionActive", "g_ai_actionCardText", and "g_ai_actionChatId" in the state module so the interface knows a card is active and which chat owns it. We also store the paused round in queue arrays, along with the loop position to resume from. Because the model can request multiple actions at once, the queue stores each call's id, name, arguments, and result, plus a resolved flag so we can process them one at a time. With somewhere to park a turn, we can write the card that we will be reading.

Building the Card

We find the next undecided action in the queue and compose its approval card from a fixed header and a plain-language description.

//+------------------------------------------------------------------+
//| Find the next unresolved queue index                             |
//+------------------------------------------------------------------+
int AiActionNextPending()
  {
//--- Scan the queue for the first unresolved call
   for(int i = 0; i < ArraySize(g_ai_actQueueResolved); i++)
      if(!g_ai_actQueueResolved[i])
         return i;
   return -1;
  }
//+------------------------------------------------------------------+
//| Build the approval card text for a queue index                   |
//+------------------------------------------------------------------+
void AiBuildActionCard(const int idx)
  {
//--- Guard against invalid indices
   if(idx < 0 || idx >= ArraySize(g_ai_actQueueNames))
     {
      g_ai_actionCardText = "";
      return;
     }
//--- Compose the header, tool line, description and footer
   g_ai_actionCardText = AI_ACTION_CARD_HEADER + "\n"
                         + "Tool: " + g_ai_actQueueNames[idx] + "\n"
                         + AiDescribeAction(g_ai_actQueueNames[idx], g_ai_actQueueArgs[idx]) + "\n"
                         + "Approve to execute or Reject to cancel.";
  }

Here, we define the "AiActionNextPending" function to return the first unresolved call in the queue, and the "AiBuildActionCard" function to compose its card from the fixed header, the tool name, a human-readable description, and the approve-or-reject footer. That description comes from the "AiDescribeAction" function, which spells out the order, its size, its stops, and whose trade it touches in plain terms, so what we approve is never a raw tool name. With a card ready to raise, the loop can park instead of executing.

Pausing the Tool Loop

Here, we rework the send loop so an action call parks the whole round and raises the card instead of running, returning a sentinel in place of an answer.

//+------------------------------------------------------------------+
//| Run the request loop with context, vision, tools and actions     |
//+------------------------------------------------------------------+
string AiRunToolLoop(string messages, string toolsJson, int startRound, int maxRounds, double temperature)
  {
//--- Keep the last tool outcome so a silent model turn still reports something
   string lastToolSummary = "";
//--- Iterate request rounds until a final text answer arrives
   for(int round = startRound; round <= maxRounds; round++)
     {
      //--- Existing logic builds, sends and parses the request for this round
      //--- Handle the tool-call round
      if(ncalls > 0 && round < maxRounds)
        {
         //--- Rebuild the assistant tool-call message and collect calls
         string asstCalls = "[";
         string callIds[];
         string callNames[];
         string callArgs[];
         string callResults[];
         bool   callResolved[];
         ArrayResize(callIds, ncalls);
         ArrayResize(callNames, ncalls);
         ArrayResize(callArgs, ncalls);
         ArrayResize(callResults, ncalls);
         ArrayResize(callResolved, ncalls);
         bool anyPending = false;
         for(int i = 0; i < ncalls; i++)
           {
            //--- Pull the id, name and arguments of this call
            JsonValue *tc = GetPointer(tcalls.m_children[i]);
            string id = AiJsonStr(tc, "id");
            JsonValue *fn = (tc == NULL) ? NULL : tc.FindChildByKey("function");
            string fname = AiJsonStr(fn, "name");
            string fargs = AiJsonStr(fn, "arguments");
            if(StringLen(fargs) == 0)
               fargs = "{}";
            callIds[i] = id;
            callNames[i] = fname;
            callArgs[i] = fargs;
            callResults[i] = "";
            callResolved[i] = false;
            if(i > 0)
               asstCalls += ",";
            asstCalls += "{\"id\":\"" + id + "\",\"type\":\"function\",\"function\":{\"name\":\""
                         + fname + "\",\"arguments\":\"" + AiJsonEscape(fargs) + "\"}}";
            //--- Resolve the call now unless it needs a human decision
            if(AiIsActionTool(fname))
              {
               //--- Auto-approved actions execute inline through the safety gate
               if(Action_AutoApprove)
                 {
                  callResults[i] = AiExecuteAction(fname, fargs);
                  callResolved[i] = true;
                 }
               //--- Approval-gated actions stay parked for the card
               else
                  anyPending = true;
              }
            else
              {
               //--- Data tools and drawing execute immediately
               callResults[i] = AiDispatchTool(fname, fargs);
               callResolved[i] = true;
              }
           }
         asstCalls += "]";
         string asstMsg = "{\"role\":\"assistant\",\"content\":null,\"tool_calls\":" + asstCalls + "}";
         string bodyMsgs = StringSubstr(messages, 0, StringLen(messages) - 1);
         //--- Park the round when any action awaits approval
         if(anyPending)
           {
            //--- Snapshot the queue arrays for the resume path
            ArrayResize(g_ai_actQueueIds, ncalls);
            ArrayResize(g_ai_actQueueNames, ncalls);
            ArrayResize(g_ai_actQueueArgs, ncalls);
            ArrayResize(g_ai_actQueueResults, ncalls);
            ArrayResize(g_ai_actQueueResolved, ncalls);
            for(int q = 0; q < ncalls; q++)
              {
               g_ai_actQueueIds[q] = callIds[q];
               g_ai_actQueueNames[q] = callNames[q];
               g_ai_actQueueArgs[q] = callArgs[q];
               g_ai_actQueueResults[q] = callResults[q];
               g_ai_actQueueResolved[q] = callResolved[q];
              }
            //--- Park the loop position and surface the first card
            g_ai_actionMessages = bodyMsgs + "," + asstMsg;
            g_ai_actionToolsJson = toolsJson;
            g_ai_actionRound = round;
            g_ai_actionTemp = temperature;
            g_ai_actionIndex = AiActionNextPending();
            g_ai_actionChatId = g_ai_currentChatId;
            AiBuildActionCard(g_ai_actionIndex);
            g_ai_actionShownMs = GetTickCount();
            g_ai_actionActive = true;
            return AI_ACTION_PENDING_SENTINEL;
           }
         //--- Keep a readable digest of this round in case the model then stays silent
         lastToolSummary = "";
         for(int sIdx = 0; sIdx < ncalls; sIdx++)
            if(StringLen(callResults[sIdx]) > 0)
               lastToolSummary += (StringLen(lastToolSummary) > 0 ? "\n" : "") + callResults[sIdx];
         //--- Append every tool result and continue the loop
         string toolResults = "";
         for(int r = 0; r < ncalls; r++)
            toolResults += ",{\"role\":\"tool\",\"tool_call_id\":\"" + callIds[r] + "\",\"content\":\""
                           + AiJsonEscape(callResults[r]) + "\"}";
         messages = bodyMsgs + "," + asstMsg + toolResults + "]";
         continue;
        }
      //--- Existing logic returns the final text answer for this turn
     }
   return "Error: tool-call loop exceeded " + IntegerToString(maxRounds) + " rounds.";

In the "AiRunToolLoop" function, we walk through each tool call and, through the "AiIsActionTool" test, run data tools and drawing at once while marking any approval-gated action as pending. When a round has anything pending, we snapshot the queue and the loop position into the parked globals, build the first card with the "AiBuildActionCard" function, set "g_ai_actionActive", and return the "AI_ACTION_PENDING_SENTINEL" rather than a reply. That sentinel is how the caller learns the turn stopped for us rather than finishing, and once we decide, another function has to feed the results back and continue.

The one exception is the "Action_AutoApprove" input. It is off by default, and while it stays off, every trade action waits for a card. Switching it on executes each action at once through "AiExecuteAction", so the symbol restriction, the lot ceiling, and the position limit still apply, but no human sees the action before it reaches the trade server. That suits unattended testing on a demo account, and we do not recommend it on a live account.

Resuming After the Decision

We rebuild the parked conversation with every tool result and run the loop again from where it stopped.

//+------------------------------------------------------------------+
//| Resume the parked request loop after approvals                   |
//+------------------------------------------------------------------+
string AiResumeToolLoop()
  {
//--- Reassemble the parked messages with every tool result
   string messages = g_ai_actionMessages;
   for(int i = 0; i < ArraySize(g_ai_actQueueIds); i++)
      messages += ",{\"role\":\"tool\",\"tool_call_id\":\"" + g_ai_actQueueIds[i] + "\",\"content\":\""
                  + AiJsonEscape(g_ai_actQueueResults[i]) + "\"}";
   messages += "]";
//--- Snapshot the parked loop position before clearing state
   const string toolsJson = g_ai_actionToolsJson;
   const int    nextRound = g_ai_actionRound + 1;
   const double temp      = g_ai_actionTemp;
//--- Clear the pending state so the resumed loop can park again cleanly
   AiActionReset();
//--- Existing logic clamps the tool-round budget
//--- Continue the shared request loop where it stopped
   return AiRunToolLoop(messages, toolsJson, nextRound, maxRounds, temp);
  }

Here, we define the "AiResumeToolLoop" function to append every parked result back into the assistant message, snapshot the loop position, and clear the pending state through the "AiActionReset" function before continuing. Resetting first is deliberate, since the resumed round may itself contain another action and needs a clean slate to park again. What actually fills those results and calls this is the handler that runs when we approve or reject.

Resolving Approve or Reject

We add the handler that executes or refuses the parked action, then raises the next card or resumes the loop.

//+------------------------------------------------------------------+
//| Resolve the on-screen approval card                              |
//+------------------------------------------------------------------+
void AiResolvePendingAction(const bool approved)
  {
//--- Guard against stale or foreign-chat clicks
   if(!g_ai_actionActive)
      return;
   if(g_ai_actionChatId != g_ai_currentChatId)
      return;
   const int idx = g_ai_actionIndex;
   if(idx < 0 || idx >= ArraySize(g_ai_actQueueNames))
      return;
//--- Ignore an already-decided call so a queued click cannot resolve it twice
   if(g_ai_actQueueResolved[idx])
      return;
//--- Ignore clicks queued before this card appeared so none is approved unseen
   if(GetTickCount() - g_ai_actionShownMs < AI_ACTION_ARM_DELAY_MS)
      return;
//--- Execute or refuse the parked action
   string result = "";
   if(approved)
      result = AiExecuteAction(g_ai_actQueueNames[idx], g_ai_actQueueArgs[idx]);
   else
      result = "Rejected by the user. The action was not executed.";
   g_ai_actQueueResults[idx] = result;
   g_ai_actQueueResolved[idx] = true;
//--- Log the decision alongside its outcome
   Print("AI Action ", g_ai_actQueueNames[idx], (approved ? " approved: " : " rejected: "), result);
   if(g_ai_logFileHandle != INVALID_HANDLE)
      FileWrite(g_ai_logFileHandle, "AI Action " + g_ai_actQueueNames[idx]
                + (approved ? " approved: " : " rejected: ") + result);
//--- Annotate the card in the transcript and notify via toast
   AiAnnotateActionCard(approved ? ("-> Approved. " + result) : "-> Rejected by the user.");
   Ai_ShowToast(approved ? "Action approved" : "Action rejected", false);
//--- Build a timestamp for the follow-up messages
   string timestamp = TimeToString(TimeCurrent(), TIME_MINUTES);
//--- Surface the next parked action as a fresh card
   const int nxt = AiActionNextPending();
   if(nxt >= 0)
     {
      //--- Point the card at the next call and append it to the chat
      g_ai_actionIndex = nxt;
      AiBuildActionCard(nxt);
      g_ai_actionShownMs = GetTickCount();
      g_ai_conversationHistory += "AI: " + g_ai_actionCardText + "\n" + timestamp + "\n\n";
      g_ai_chatScrollPin = true;
      AiUpdateCurrentHistory();
      Ai_RenderAll();
      ChartRedraw();
      return;
     }
//--- Show the thinking placeholder while the loop resumes
   g_ai_conversationHistory += AI_LOADING_PLACEHOLDER + "\n" + timestamp + "\n\n";
   g_ai_chatScrollPin = true;
   Ai_RenderAll();
   ChartRedraw();
//--- Resume the request loop and time it
   g_ai_startTimeMs = GetTickCount();
   string response = AiResumeToolLoop();
   ulong elapsedMs = GetTickCount() - g_ai_startTimeMs;
   string timeNote = "\n(Response in " + IntegerToString((int)(elapsedMs / 1000)) + "s)";
//--- Swap in the next approval card when the model chained another action
   if(response == AI_ACTION_PENDING_SENTINEL)
     {
      response = g_ai_actionCardText;
      timeNote = "";
     }
//--- Fall back to the action outcome when the model adds no words of its own
   StringTrimLeft(response);
   StringTrimRight(response);
   if(StringLen(response) == 0)
      response = result;
//--- Log the follow-up response
   Print("AI: ", response);
   if(g_ai_logFileHandle != INVALID_HANDLE)
      FileWrite(g_ai_logFileHandle, "AI: " + response);
//--- Publish the response, persist and repaint
   AiReplaceLoadingPlaceholder("AI: " + response + timeNote, timestamp);
   AiUpdateCurrentHistory();
   Ai_RenderAll();
   ChartRedraw();

We define the "AiResolvePendingAction" function to guard against stale, foreign-chat, and double-clicks, then either run the action through the "AiExecuteAction" function on approval or record a refusal, storing the outcome in the queue. When more actions wait, we raise the next card and stop; when the queue is clear, we call the "AiResumeToolLoop" function to feed the results back and let the model finish. The arm-delay guard matters here, since it ignores a click that lands in the moment the card appears, so nothing is ever approved unseen. All that remains is the button the click comes from.

The Approve and Reject Buttons

We route the two card buttons to the resolver and hit-test each against the rectangle the card render lays out.

  {
//--- Test approval approve button
   if(g_ai_apprR > g_ai_apprL
      && AiPointInRect(lx, ly, g_ai_apprL, g_ai_apprT,
                       g_ai_apprR - g_ai_apprL, g_ai_apprB - g_ai_apprT))
      return AI_HOV_ACTION_APPROVE;
//--- Test approval reject button
   if(g_ai_rejR > g_ai_rejL
      && AiPointInRect(lx, ly, g_ai_rejL, g_ai_rejT,
                       g_ai_rejR - g_ai_rejL, g_ai_rejB - g_ai_rejT))
      return AI_HOV_ACTION_REJECT;

//--- Approve button - execute the pending AI action
   if(hov == AI_HOV_ACTION_APPROVE)
     {
      AiResolvePendingAction(true);
      return;
     }
//--- Reject button - refuse the pending AI action
   if(hov == AI_HOV_ACTION_REJECT)
     {
      AiResolvePendingAction(false);
      return;
     }
  }

Finally, we hit-test the pointer against the approve and reject rectangles that the card render publishes, returning "AI_HOV_ACTION_APPROVE" or "AI_HOV_ACTION_REJECT", and on a click we call the "AiResolvePendingAction" function with true or false. The card render itself draws the two buttons and their hover states from the same rectangles and the new theme colors, so the loop, the card, and the buttons form one closed path. With the assistant able to propose an action, pause for our decision, and resume on our answer, the human-in-the-loop gate is complete, and we can see it work in the visualization.


Visualization

We compile the program, load it onto a chart, and put the assistant through the action flow to show the gate at work. The result is shown in the video below.

During testing, asking the assistant to place, close, or modify a trade raised an approval card that named the exact order, its size, its stops, and which trade it touched, and with auto-approval off, nothing reached the trade server until we chose. Approving executed the action and let the model report the outcome and finish its turn, while rejecting refused it and the conversation carried on. When the assistant lined up several actions at once, each surfaced as its own card in turn, and a request to close all positions raised a card that listed every position with its owner, so we saw whose trades it would close before approving.


To reproduce the flow, we ran the program on an Exness demo hedging account on BTCUSDm on the one-minute chart, with the action inputs at their defaults: actions on, auto-approval off, a ceiling of 0.10 lots, at most five open positions, and actions restricted to the chart symbol. The assistant used the default model input, gpt-4o, through the OpenAI chat completions endpoint at a temperature of 1.0, on MetaTrader 5 build 6230. The limits are demonstration values: we size "Action_MaxLots" from the risk we accept per trade on the account, "Action_MaxPositions" from the total exposure we allow, and the 350 millisecond arm delay only needs to outlast an accidental double-click. These are the requests from the recording and what each one did:

  • "Open a sell position of lot size 0.05, at current price" raised a place_order card. Rejecting it left the account untouched, and the model reported that the order was not confirmed. Asking again and approving opened the sell.
  • "Add sl at 5000 points and tp at r2r of 1:1" raised a modify_position card showing the entry, the new stop, and the new target, and approving it set both.
  • A request for a 0.05 lot buy with a 20000 point stop and target raised a card, and approving it opened the buy with both levels set.
  • "Close all of my positions." raised a close_all card listing two positions, one manual and one opened by this program, and approving it closed both.

The table below lists the protective checks in the code and how the program responds to each. The first seven run at execution, so the card still appears and the executor refuses the action once we approve it, while the last three guard the card itself.

Check Program response
Volume above 0.10 lots Blocked by the Action_MaxLots limit.
Volume of zero or below Blocked, since lots must be a positive number.
Order kind outside market, limit, and stop Blocked, naming the accepted kinds.
Symbol other than the chart symbol Blocked by the chart-symbol restriction.
Stop loss on the wrong side of the entry Blocked, naming the side the stop must be on.
Sixth position while five are open Blocked by the open-position limit.
Bulk close without a scope Blocked, and the owner breakdown goes back to the model.
Second click on a decided card Ignored, since the call is already resolved.
Click within 350 milliseconds of a card appearing Ignored, so no card is approved unseen.
Click while another chat is open Ignored, since the card belongs to the chat that raised it.


Conclusion

We moved the assistant from read-only to controlled action: it can now propose and, with our explicit approval, execute market and pending orders, modify or delete orders, close positions, and annotate the chart. Concretely, the implementation provides:

  • A distinct toolset, read-only versus action tools, with a predicate that identifies which calls change the account.
  • Action executors that follow a validate-then-act pattern, with a safety gate, volume normalization to broker limits, and stop and target consistency checks.
  • Ownership scoping, so bulk operations can be limited to the trades the assistant is permitted to touch.
  • An approval gate that parks the tool loop, surfaces a human-readable card for each proposed action, and processes a queue of proposals one at a time.
  • A resume path that injects the action results back into the conversation, so the model can finish its turn.

These pieces form a pipeline that meets the acceptance criteria: with auto-approval off, nothing reaches the trade server until we explicitly approve, malformed requests are rejected before execution, the trade server refuses any that break the broker's remaining rules, and the assistant can propose multiple actions while we keep final control. In the next part, we turn the plain-text approval card into a structured one, with titled rows and selectable choices, to make approvals faster and less error-prone. Stay tuned.


Attachments

S/N Name Type Description
1 AI Canvas Theme.mqh Include file Defines the layout constants, font sizes, glyph codes, and the dark and light color palettes, now including the approve and reject card colors
2 AI Canvas Primitives.mqh Include file Provides the low-level drawing primitives, the fast direct-buffer canvas, the text and glyph caches, and the vector logo and icon drawers
3 AI JSON FILE.mqh Include file Provides the JSON parser and serializer used by the chat persistence and the tool-call arguments
4 AI Canvas State.mqh Include file Holds the program-wide state and now the pending-action state and the approval-card fields the interface reads
5 AI Canvas Scrollbar.mqh Include file Defines the scrollbar state struct and the vertical and horizontal scroll helpers
6 AI Canvas Editor.mqh Include file Defines the multi-line text editor class with caret blinking, selection, word-wrap, click-to-position, and per-keystroke editing
7 AI Canvas Render.mqh Include file Renders the entire dashboard and now draws the approval card with its approve and reject buttons
8 AI Logic.mqh Include file Implements the request lifecycle and now the action tools, the validate-then-act executors, ownership scoping, and the paused tool loop with its approval resolution
9 AI Canvas Interact.mqh Include file Routes mouse and keyboard events to the right action and now hit-tests the approve and reject buttons
10 AI Canvas Shell.mqh Include file Owns the program lifecycle, canvas creation and destruction, layout recomputation, the new-bar auto-signal tick path, and the show-and-hide pair
11 AI EA PART 13.mq5 Expert Advisor The main program entry point that declares the user inputs, includes the ten module headers, and forwards each event to the matching shell function
12 MQL5.zip Compiled archive A ready-to-extract archive containing all 11 project files in a single folder. Unzip it into your MetaTrader 5 terminal data folder; the files will be placed under MQL5/Experts/ with every file in its correct location, ready to compile


The project is supported in MQL5 Algo Forge: https://forge.mql5.io/29210372/Article-24272-Building-AI-Powered-Trading-Systems-In-MQL5-Part-13

Attached files |
MQL5.zip (139.75 KB)
Which Economic Releases Actually Move Your Symbol, and by How Much? Which Economic Releases Actually Move Your Symbol, and by How Much?
A calendar release is not a category but a number against a consensus. In MQL5 we build a robust, standardized surprise (actual minus forecast scaled by each indicator's own dispersion), recover the broker's daylight saving schedule from price to anchor each release on the bar that moved, and regress price response by symbol and horizon. The result is a measurable profile in pips per sigma showing which events actually move your market.
Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5 Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5
This article builds a native MQL5 LOF engine without DLLs, ALGLIB or ONNX. Bars are mapped to five standardized features; k‑NN reachability and density produce a scale‑free LOF score, and the alarm level is a moving quantile of the reference cloud. The score gates only new entries in an EMA‑cross EA, with an indicator for charting and a script for independent checks on XAUUSD, EURUSD and GBPUSD.
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (SDformerFlow) Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (SDformerFlow)
The article presents an adaptation of the SDformerFlow spiking architecture for the task of dense analysis of price micro-movements. The spatio-temporal structure provides a high level of detail, while the spiking logic ensures computational efficiency and the ability to work with sparse, pulse-like data. As a result, traders gain access to a tool that detects even the slightest shifts in liquidity and provides the foundation for more accurate and consistent real-time decisions.
Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style) Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style)
The article builds an MQL5‑native weak‑labeling engine that infers per‑indicator trust from vote agreement, then fuses five noisy signals into P(Buy) using Expectation‑Maximization. We describe the EA architecture, rolling‑window refits, abstain handling, diagnostics, and a majority‑vote baseline used for comparison. Readers can reuse the EM library, swap in their own labeling functions, and obtain a transparent, probability‑based entry filter.