Page 1 of 1

deas & Code: How to actually use AI LLMs for Forex Scalping in MT4

Posted: Mon Aug 10, 2026 3:29 pm
by PTScalper
Hey everyone,

I’ve been experimenting with bridging Large Language Models (like ChatGPT or local Llama models) with MetaTrader 4. A lot of people are asking if an LLM can be used for scalping. The short answer is: Yes, but not the way you probably think.

The Elephant in the Room: Latency
Scalping is a latency game. To scalp effectively, your execution round-trip time needs to be under 50 milliseconds. LLMs are incredibly smart, but they are slow. Generating tokens takes hundreds of milliseconds to several seconds. If you feed tick data into an LLM and wait for it to reply "BUY," the price you wanted will be long gone, resulting in massive slippage.The Solution: Do not use the LLM for tick-by-tick execution. Use MT4 for the reflexes (execution) and the LLM for the brain (context and parameters).

3 Ideas for LLM-Assisted Scalping
Pre-Session Regime Filtering: Every hour, an external script feeds the LLM the latest economic calendar events, major news headlines, and the H1/M15 market structure. The LLM classifies the market regime (e.g., "High Volatility Trending" or "Low Volatility Ranging"). Your MT4 scalper reads this state and turns specific high-frequency strategies on or off accordingly.

Dynamic Parameter Tuning: Instead of hardcoding a 5-pip Stop Loss and 10-pip Take Profit, have the LLM analyze recent market behavior and output optimized parameters for the current session. MT4 fetches these updated risk parameters every few minutes.

Sentiment Check for Breakouts: If your MT4 scalper detects a breakout setup on EUR/USD, it pauses for a fraction of a second to check the current LLM sentiment score (scraped from Twitter or financial news). If the technical setup is long but the LLM reads a highly bearish macro sentiment, the EA skips the trade.

Basic MT4 ImplementationMQL4 cannot run LLMs natively. The best architecture is a REST API Bridge. You run a lightweight Python web server locally (or on your VPS) that handles the heavy lifting with the LLM, and MT4 simply asks that server for instructions using WebRequest().

Step 1: The Python API (Flask + OpenAI)

Save this as server.py and run it on your machine. It creates a local endpoint that MT4 can talk to.

Code: Select all

from flask import Flask, request, jsonify
import openai

app = Flask(__name__)
# Replace with your actual API key or local LLM endpoint
openai.api_key = "YOUR_OPENAI_API_KEY"

@app.route('/get_context', methods=['POST'])
def get_context():
    data = request.json
    market_data = data.get("market_data", "")
    
    # Prompt the LLM for a bias based on data
    prompt = f"Act as a forex analyst. Based on this data: {market_data}. Reply with ONLY one word: BULLISH, BEARISH, or NEUTRAL."
    
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=10,
            temperature=0.1
        )
        bias = response.choices[0].message.content.strip().upper()
        return jsonify({"status": "success", "bias": bias})
        
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)})

if __name__ == '__main__':
    # Runs locally on port 5000
    app.run(host='127.0.0.1', port=5000)
Step 2: The MT4 EA (MQL4)
In MT4, you must first allow WebRequests. Go to Tools > Options > Expert Advisors, check "Allowed WebRequest for listed URL", and add [http://127.0.0.1](http://127.0.0.1).

Here is the MQL4 snippet to fetch the LLM's bias:

Code: Select all

//+------------------------------------------------------------------+
//| Function to call Python LLM API                                  |
//+------------------------------------------------------------------+
string GetLLMBias(string recentPriceAction) {
    string url = "http://127.0.0.1:5000/get_context";
    string cookie = NULL;
    string headers = "Content-Type: application/json\r\n";
    int timeout = 5000; // 5 second timeout
    
    // Create the JSON payload
    string jsonPayload = "{\"market_data\": \"" + recentPriceAction + "\"}";
    char postData[];
    StringToCharArray(jsonPayload, postData, 0, WHOLE_ARRAY, CP_UTF8);
    
    // Remove the null terminator added by StringToCharArray
    ArrayResize(postData, ArraySize(postData) - 1);
    
    char resultData[];
    string resultHeaders;
    
    // Send the HTTP POST request
    int res = WebRequest("POST", url, headers, timeout, postData, resultData, resultHeaders);
    
    if(res == 200) {
        string response = CharArrayToString(resultData, 0, WHOLE_ARRAY, CP_UTF8);
        // Note: You would normally parse the JSON here. 
        // For simplicity, we are just printing the raw JSON response.
        Print("LLM Response: ", response);
        return response;
    } else {
        Print("WebRequest failed. Error code: ", GetLastError());
        return "ERROR";
    }
}

//+------------------------------------------------------------------+
//| EA OnTick Function                                               |
//+------------------------------------------------------------------+
void OnTick() {
    // DO NOT call this every tick! WebRequest is synchronous and will freeze your EA.
    // Use a timer (OnTimer) or check only once per new bar.
    
    static datetime lastCheck = 0;
    if(Time[0] != lastCheck) {
        string data = "EURUSD M15 closed bullish above moving average.";
        string bias = GetLLMBias(data);
        
        // Use the bias for your scalping logic here...
        
        lastCheck = Time[0];
    }
}
Key Takeaway for Developers

Notice the warning in OnTick(). Because WebRequest() is synchronous, it forces MT4 to wait for the LLM to reply before it processes the next tick. Never fire an LLM request directly on a scalping entry trigger. Fetch the data on a separate chart or on a slower timeframe (like OnTimer every 5 minutes), save the state to a global variable, and let your high-speed scalping logic read that variable instantly. Has anyone else played around with hooking up OpenAI or local models to their platforms? Would love to hear how you are handling the latency!

Re: deas & Code: How to actually use AI LLMs for Forex Scalping in MT4

Posted: Mon Aug 10, 2026 3:31 pm
by PTScalper
And here i prepare it for MT5 traders :-)

Basic MT5 Implementation
MQL5 cannot run LLMs natively. The best architecture is a REST API Bridge. You run a lightweight Python web server locally (or on your VPS) that handles the heavy lifting with the LLM, and MT5 simply asks that server for instructions using WebRequest().

Step 1: The Python API (Flask + OpenAI)
Save this as server.py and run it on your machine. It creates a local endpoint that MT5 can talk to.

Code: Select all

from flask import Flask, request, jsonify
import openai

app = Flask(__name__)
# Replace with your actual API key or local LLM endpoint
openai.api_key = "YOUR_OPENAI_API_KEY"

@app.route('/get_context', methods=['POST'])
def get_context():
    data = request.json
    market_data = data.get("market_data", "")
    
    # Prompt the LLM for a bias based on data
    prompt = f"Act as a forex analyst. Based on this data: {market_data}. Reply with ONLY one word: BULLISH, BEARISH, or NEUTRAL."
    
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=10,
            temperature=0.1
        )
        bias = response.choices[0].message.content.strip().upper()
        return jsonify({"status": "success", "bias": bias})
        
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)})

if __name__ == '__main__':
    # Runs locally on port 5000
    app.run(host='127.0.0.1', port=5000)
Step 2: The MT5 EA (MQL5)
In MT5, you must first allow WebRequests. Go to Tools > Options > Expert Advisors, check "Allowed WebRequest for listed URL", and add [http://127.0.0.1](http://127.0.0.1).

Here is the MQL5 snippet to fetch the LLM's bias:

Code: Select all

//+------------------------------------------------------------------+
//| Function to call Python LLM API                                  |
//+------------------------------------------------------------------+
string GetLLMBias(string recentPriceAction) {
    string url = "http://127.0.0.1:5000/get_context";
    string headers = "Content-Type: application/json\r\n";
    int timeout = 5000; // 5 second timeout
    
    // Create the JSON payload
    string jsonPayload = "{\"market_data\": \"" + recentPriceAction + "\"}";
    char postData[];
    StringToCharArray(jsonPayload, postData, 0, WHOLE_ARRAY, CP_UTF8);
    
    // Remove the null terminator added by StringToCharArray to ensure valid JSON
    ArrayResize(postData, ArraySize(postData) - 1);
    
    char resultData[];
    string resultHeaders;
    
    // Send the HTTP POST request
    int res = WebRequest("POST", url, headers, timeout, postData, resultData, resultHeaders);
    
    if(res == 200) {
        string response = CharArrayToString(resultData, 0, WHOLE_ARRAY, CP_UTF8);
        // Note: You would normally parse the JSON here using a library like JAson. 
        // For simplicity, we are just printing the raw JSON response.
        Print("LLM Response: ", response);
        return response;
    } else {
        Print("WebRequest failed. Error code: ", GetLastError());
        return "ERROR";
    }
}

//+------------------------------------------------------------------+
//| EA OnTick Function                                               |
//+------------------------------------------------------------------+
void OnTick() {
    // DO NOT call this every tick! WebRequest is synchronous and will freeze your EA.
    // Use a timer (OnTimer) or check only once per new bar.
    
    // Example: Only check once per new M15 bar
    static datetime lastCheck = 0;
    datetime currentBarTime = iTime(_Symbol, PERIOD_M15, 0);
    
    if(currentBarTime != lastCheck) {
        string data = "EURUSD M15 closed bullish above moving average.";
        string bias = GetLLMBias(data);
        
        // Use the bias for your scalping logic here...
        
        lastCheck = currentBarTime;
    }
}

Re: deas & Code: How to actually use AI LLMs for Forex Scalping in MT4

Posted: Mon Aug 10, 2026 3:32 pm
by PTScalper
And here it is for IC traders:

Basic cTrader Implementation (Native Python)
One of the massive advantages of cTrader over MT4/MT5 is that it supports Python natively. You don't need to run a clunky local Flask web server. You can write your cBot directly in Python and import libraries like openai straight into your trading script. The trick is to use threading. Because the OpenAI call takes a few seconds, if you run it on the main thread, it will completely freeze your cTrader interface and block your tick execution.Here is a basic template to get you started:

Code: Select all

import cTrader
from cTrader.API import *
import openai
import threading

class LLMScalper(cTrader.cBot):
    def OnStart(self):
        # Setup your API key (can be OpenAI, or a local server running Llama/Gemma)
        openai.api_key = "YOUR_OPENAI_API_KEY"
        self.current_bias = "NEUTRAL"
        
        # Start a timer to check LLM every 5 minutes (300 seconds)
        self.Timer.Start(300)
        
        # Run an initial check immediately 
        self.OnTimer()

    def OnTimer(self):
        # We use a background thread because the API call takes seconds.
        # This prevents the cBot from freezing and missing fast tick executions!
        threading.Thread(target=self.UpdateLLMBias).start()

    def UpdateLLMBias(self):
        try:
            # Gather some context, like recent M15 structure or news
            prompt = "Act as a forex analyst. The EURUSD just broke the Asian session high. Reply ONLY with BULLISH, BEARISH, or NEUTRAL."
            
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[{"role": "user", "content": prompt}],
                max_tokens=10,
                temperature=0.1
            )
            self.current_bias = response.choices[0].message.content.strip().upper()
            self.Print(f"Updated LLM Bias: {self.current_bias}")
            
        except Exception as e:
            self.Print(f"LLM Error: {e}")

    def OnTick(self):
        # Your sub-50ms scalping logic goes here!
        # It executes instantly on the main thread, completely unbothered by the slow LLM.
        
        # Simple Example: Only scalp long if the LLM says BULLISH and price is below an SMA
        if self.current_bias == "BULLISH":
            # Execute your high-speed IC Markets scalping logic here...
            pass
Key Takeaway for Developers
Never fire an LLM request directly on a scalping entry trigger. Fetch the data in the background on a slower timeframe using threading, save the state to a variable (self.current_bias), and let your high-speed scalping logic read that variable instantly.

Has anyone else played around with hooking up OpenAI or local models to their cBots? Would love to hear how you are handling the prompts!