Current Day: As the LLM's have improved both their 'intelligence' and context window size it is easier now to start developing trading bot with LLM's, such as Gemini Flash 2.0 while containing everything within an EA rather than run a separate operations.
What I have to offer is an EA template of sorts where I grabbed a few YouTube videos analysed them with Gemini (AI Studio) asked it to create a trading strategy.
Prompt:
"Analyse an provide a detailed analysis of the strategy and indictors used to replicate using as a mt5 terminal trading bot using Gemini Flash API to make calls to trade with by analysing the indicators and using the strategy.
Carefully look at the visual diagrams in the video and any drawings on the screen that describe how the indicators and strategy works."
There are additional comments one can add with the prompt such as optimise for 'forex', a certain timeframe etc that will help develop the overall starting point.
Reason for using Free Tier Gemini Flash 2.0 API:
- 15 requests per minute (RPM)
- 1,000,000 tokens per minute (TPM)
- 1,500 requests per day (RPD)
Example usage for a 5 minute timeframe / analysis:
- 288 calls per day is well below the free tier’s daily limit of 1,500 requests per day.
- Only 1 call every 5 minutes means only 1 call per 5-minute interval, which is far below the 15 RPM cap.
- Unless each call uses an extremely large number of tokens, you will not approach the 1,000,000 TPM limit with this call frequency.
Where This Leaves Usage:
- You are well within all free tier limits for the Gemini 2.0 Flash API.
- You could increase your call frequency significantly (up to 15 per minute, or 1,500 per day) and still remain within the free tier’s allowances.
Development:
Developing your own EA that has Gemini Flash 2.0 integrated is very simple. Just paste my EA into Gemini, if you have your own strategy add this below the EA, ask it to keep or remove parts of the EA you want and intergrade the new strategy, thus developing a new EA.
Using Gemini is fundamental for my EA development as it is free and has a large context window, thus pasting the EA into ChatGPT will not work as the code is too long, plus adding YouTube videos is very easy (this can be done in Google AI Studio too) to analyse strategies and convert these.
One Week Later...
Blah, blah, blah, Attached my EA to use and modify.
NOTE: Back testing will not work in the strategy tester as this relies on calling the API in Realtime to analyse and manage trades.
Remember to add in your own Gemini API Key e.g. "ABCDEFGHIJKLMNOP12345"
Line 43: input string InpFlashCommanderAPI_Key = "GEMINI_API_KEY"; // *** YOUR KEY ***
GeminiCommanderEA_v1.0: AI-Powered Trading Assistant for MT5
GeminiCommanderEA_v1.0 is an innovative Expert Advisor (EA) for MetaTrader 5 (MT5) designed to bridge the gap between advanced AI analysis and automated trading. It operates by sending detailed, real-time market data to Google's Gemini Flash AI model via its API. The EA then interprets the AI's response, which emulates a K-Nearest Neighbors (KNN) based signal, to execute and manage trades based on a predefined EMA Ribbon pullback strategy.
Trading Strategy
The core strategy employed by GeminiCommanderEA focuses on identifying and trading pullbacks within an established trend on the GBPUSD M15 timeframe.
- Trend Identification:
- Primary Trend: Determined by the relationship between the price, a fast EMA Ribbon (composed of 8 EMAs ranging from 20 to 55 periods by default), and a slow 200-period EMA.
- H1 Context: A 50-period Simple Moving Average (SMA) on the H1 chart provides a higher-level trend context.
- Uptrend Conditions: Price is above the 200 EMA, and the EMA Ribbon is "Green" (shorter EMAs above longer EMAs) and situated above the 200 EMA.
- Downtrend Conditions: Price is below the 200 EMA, and the EMA Ribbon is "Red" (shorter EMAs below longer EMAs) and situated below the 200 EMA.
- Entry Signal (KNN Emulation via Gemini):
- The EA seeks entry opportunities when the price pulls back towards the EMA Ribbon within the established trend.
- It sends a comprehensive snapshot of the current market state (OHLC, historical data, indicator values, ribbon state) to the Gemini AI.
- It specifically asks Gemini to emulate a K-Nearest Neighbours (KNN) analysis. This means the AI is tasked with assessing if the current market pattern (the pullback) closely resembles historical patterns that led to successful trade entries under similar trend conditions.
- RSI Confirmation: A 14-period Relative Strength Index (RSI) is used as a filter.
- For BUY signals, the RSI should ideally have recently (within the last 3 candles) dipped below the 40 (Oversold) level.
- For SELL signals, the RSI should have recently (within the last 3 candles) risen above the 60 (Overbought) level, but the current RSI should not be below 40.
- Trade Execution:
- If Gemini returns a "BUY" or "SELL" signal (and it passes the EA's internal filters like spread and open trade limits), the EA will execute a trade. "HOLD" signals result in no action.
EA Logic Flow
- Initialization (OnInit):
- Sets up the CTrade object for trade execution.
- Initializes all required indicators (EMA Ribbon, 200 EMA, RSI, ATR, H1 MA).
- Records the initial account balance for drawdown monitoring.
- If InpEnableFlashCommander is true, it performs a connection test to the Gemini API and sets up a timer (OnTimer).
- Timer (OnTimer):
- Periodically (defined by InpFlashPollIntervalSec), it triggers the FetchAndExecuteFlashCommands function, but only if AI trading is enabled and no trades are currently open (if InpMaxTotalOpenTrades is 1).
- Data Preparation & AI Polling (FetchAndExecuteFlashCommands):
- Calls PrepareGeminiKNNEmuData to gather current and historical M15 data, calculate indicator values, and determine the state of the EMA ribbon and its relation to price and the 200 EMA.
- Calls ConstructKNNEmulationPrompt to build a detailed, structured prompt containing all the market data and instructions for the Gemini AI.
- Calls SendAndProcessGeminiRequest to send this prompt to the specified Gemini API URL using MT5's WebRequest function.
- Response Handling (SendAndProcessGeminiRequest, ExtractGeminiTextResponse, ParseKNNEmulationResponse):
- Receives the JSON response from Gemini.
- Extracts the core "text" part of the response, which should contain the AI's signal.
- Parses this text to find the {"signal": "VALUE"} JSON, extracting "BUY", "SELL", or "HOLD".
- Signal Processing (ProcessFlashCommandSignal):
- If a "BUY" or "SELL" signal is received:
- Checks MT5 trading permissions and spread filters.
- Calculates the Stop Loss (SL) based on recent swing highs/lows or an ATR multiple (CalculateStrategySLPips).
- Calculates the Take Profit (TP) based on a Risk-to-Reward ratio (InpTakeProfit_RR).
- Calculates the Lot Size based on the chosen risk model (CalculateLotSize).
- Executes the trade using the CTrade object.
- Records the signal to prevent immediate re-entry on the same signal.
- If a "BUY" or "SELL" signal is received:
- Trade Management (OnTick, ManageAllOpenTrades):
- Continuously monitors open positions in OnTick.
- Checks for the maximum account drawdown limit.
- If InpUseBreakEven_RR is enabled, it moves the Stop Loss to a few pips in profit once the trade reaches a specified portion of its initial risk distance.
EA Input Settings (Setup)
Here's an explanation of the key input parameters you need to configure when setting up GeminiCommanderEA:
CORE SETTINGS
- InpMagicNumber: A unique number (777903) to identify trades opened by this specific EA instance. Essential for managing multiple EAs.
- InpTradeCommentaryBase: Base text ("GeminiKNN") for trade comments.
- InpMinRequiredLeverage: Minimum account leverage (30) required to operate.
MONEY MANAGEMENT & RISK
- InpDefaultRiskType: How the EA calculates lot sizes (RISK_LOW, RISK_MEDIUM, RISK_HIGH, RISK_PERCENTAGE, RISK_FIXED_LOT).
- InpDefaultFixedLotSize: Lot size to use if RISK_FIXED_LOT is selected (0.01).
- InpDefaultRiskPercentOfEquity: Percentage of equity to risk per trade if RISK_PERCENTAGE is selected (0.5%).
- InpMaxTotalOpenTrades: The maximum number of trades this EA can have open simultaneously (1).
- InpEnableAccountMaxDDStop: Enables (true) or disables the global account drawdown stop.
- InpMaxAccountDrawdownPercent: If enabled, the EA stops trading and closes all its positions if the account drawdown reaches this percentage (15.0%).
GOOGLE GEMINI AI COMMANDER INTEGRATION
- InpEnableFlashCommander: Crucial! Set to true to enable the AI integration and trading signals.
- InpFlashCommandAPI_URL: The URL for the Gemini API (https://generativelanguage.googleapi...enerateContent). Ensure this URL is added to your MT5's allowed WebRequest list.
- InpFlashCommanderAPI_Key: Crucial! You must replace "GEMINI_API_KEY" with your actual Google AI Studio API key.
- InpFlashPollIntervalSec: How often (in seconds) the EA queries the Gemini API for a new signal (900s = 15 minutes).
- InpFlashAPITimeoutMs: How long (in milliseconds) the EA will wait for a response from the API (20000ms = 20 seconds).
- InpPerformInitialAnalysis: If true, it tries to get a signal immediately on startup.
- InpHistoricalCandlesForAI: The number of past M15 candles to send to the AI for context (20).
STRATEGY INDICATORS (EMA Ribbon / KNN Emulation)
- InpEma200Period: Period for the main trend EMA (200).
- InpRibbonEma1 to InpRibbonEma8: Periods for the 8 EMAs forming the ribbon (20, 25, 30, 35, 40, 45, 50, 55).
- InpRsiPeriod: Period for the RSI indicator (14).
- InpRsiOverboughtLevel: RSI level considered "overbought" for sell setups (60.0).
- InpRsiOversoldLevel: RSI level considered "oversold" for buy setups (40.0).
- InpATRSignalPeriod: Period for the ATR indicator, used in SL calculation (14).
- InpH1MaPeriod: Period for the H1 Moving Average for trend context (50).
TRADE MANAGEMENT (EA's Internal Rules)
- InpTakeProfit_RR: Risk-to-Reward ratio for setting the Take Profit (2.0 = TP distance is 2x SL distance).
- InpUseBreakEven_RR: Enables (true) the Break-Even function.
- InpBreakEven_Trigger_RR: The fraction of the initial risk distance the price must move in profit to trigger Break-Even (0.25 = 25% of SL distance).
- InpBreakEvenSecurePips: How many pips in profit to set the SL when Break-Even triggers (2).
- InpStopLossPips_Fallback: A default SL in pips (50) if the primary calculation fails.
FILTERS
- InpTradeFriday_EA_Filter: Enables or disables trading on Fridays.
- InpSlippage: Maximum allowed slippage in points for trade execution (5).
- InpMaxSpreadPips_EA_Filter: Maximum allowed spread in pips to enter a trade (7).
Visual Inspection and Analysis Setup
To visually monitor the EA's behaviour and analyse its decisions, you should set up an MT5 chart as follows:
- Chart: Open a GBPUSD chart and set the timeframe to M15.
- Indicators: Add the following indicators to the chart, matching the EA's input parameters:
- Moving Average (EMA 200): Period 200, MA Method Exponential, Apply to Close. Choose a distinct color (e.g., Blue or White).
- Moving Average (EMA 20): Period 20, MA Method Exponential, Apply to Close. (e.g., Light Green).
- Moving Average (EMA 25): Period 25, MA Method Exponential, Apply to Close.
- Moving Average (EMA 30): Period 30, MA Method Exponential, Apply to Close.
- Moving Average (EMA 35): Period 35, MA Method Exponential, Apply to Close.
- Moving Average (EMA 40): Period 40, MA Method Exponential, Apply to Close.
- Moving Average (EMA 45): Period 45, MA Method Exponential, Apply to Close.
- Moving Average (EMA 50): Period 50, MA Method Exponential, Apply to Close.
- Moving Average (EMA 55): Period 55, MA Method Exponential, Apply to Close. (e.g., Dark Green/Red, depending on how you like to visualize ribbons). Tip: Use similar colours for the ribbon EMAs.
- Relative Strength Index (RSI): Period 14, Apply to Close. Add levels at 60 and 40.
- Average True Range (ATR): Period 14. (Optional, mainly for SL context).
- H1 Chart (Optional but Recommended): Open a GBPUSD H1 chart and add:
- Moving Average (SMA 50): Period 50, MA Method Simple, Apply to Close. This helps you see the H1 trend context the EA is considering.
MT5 Terminal Settings Required
For the GeminiCommanderEA to function correctly, you must configure your MT5 terminal:
- Enable WebRequest: Go to Tools -> Options -> Expert Advisors.
- Check Allow WebRequest for listed URL:: Make sure this box is ticked.
- Add Gemini API URL: Click the + button and add the exact URL: https://generativelanguage.googleapis.com
- Click OK.
Disclaimer: Trading with any EA, especially one involving external APIs and AI, carries significant risks. Always test thoroughly on a demo account before using real money. Ensure your API key is kept secure and that you understand the strategy and risks involved.
Attachments:
GeminiCommanderEA_v1.0.ex5
GeminiCommanderEA_v1.0.mq5
Charts that work accompany the EA - It is best to create your own that suit your strategy and EA for visual monitoring and analysis
GeminiCommanderEA_v1.0_GBPUSD_D1.tpl
GeminiCommanderEA_v1.0_GBPUSD_H1.tpl
GeminiCommanderEA_v1.0_GBPUSD_H4.tpl
GeminiCommanderEA_v1.0_GBPUSD_M15.tpl
Screenshots:
Currently shows my chart setup - I only am working with one pair, GPDUSD as this EA is optimised for this on M15.
MT5 Terminal Expert output - Showing current execution of a trade generated by the API and will be managed continuously.
Modifications and Development:
What I have found is get the EA to work first. Have charts with indictors setup and then to iteratively develop and improve the EA, just copy (or screenshot) the charts and output from EA in the Experts Tab and paste this into Gemini. It will analyse the screenshots etc and provide feedback.