Back to Catalog

Discord AI trading assistant with proper position sizing (metatrader5)

Cj Elijah GarayCj Elijah Garay
113 views
2/3/2026
Official Page

AI Trading Assistant with Metatrader5 and position sizing capabilities

Trade or buy/sell forex and xauusd/gold assets with this n8n template. It demonstrates an AI-powered Discord bot that monitors trading commands in a private server channel and automatically executes them on MetaTrader 5, using natural language processing to parse flexible trade syntax and manage signal queues with correct position sizing for lot sizes.

Use cases are many:

Try creating a private Discord trading room where you can execute MT5 trades with simple messages like "buy EU 1% 30 pip SL 3R TP", building a shared trading server where team members can post signals that auto-execute on everyone's MT5, or developing a trading journal bot that logs and executes your strategy calls in real-time!

Good to know

  • Always test on demo accounts first - this bot executes real trades based on Discord messages, so thorough testing is critical
  • Requires OpenAI API key for natural language processing (GPT-4o-mini model) - costs approximately $0.0001-0.0003 per trade command
  • Discord OAuth2 authentication required - you'll need to create a Discord application and configure webhook permissions
  • The workflow polls Discord every 7 seconds by default - adjust the Schedule Trigger interval to balance responsiveness vs. API rate limits
  • Only processes messages from specified users without emoji reactions - prevents duplicate processing and allows filtering by username
  • MT5 Trading Signal Handler workflow must be running - this bot sends orders to the webhook endpoints from the companion workflow
  • Supports both market orders (instant execution) and limit orders (pending at specific price)
  • Uses two-stage parsing: regex-based parser for speed, with LLM fallback for complex or ambiguous commands
  • No message history - only processes the most recent Discord message per polling cycle
  • Built-in signal management commands - users can check pending signals or clear the queue via natural language

How it works

  • Scheduled Polling: The Schedule Trigger fires every 7 seconds, setting Discord server ID and channel ID credentials, then fetching the most recent message from the specified channel
  • Message Filtering: The workflow filters messages to only process those from the specified username (e.g., "elijahfx") that haven't been reacted to yet, preventing duplicate processing
  • Processing Indicator: Once a valid message is detected, the bot reacts with a πŸ”„ emoji to show it's working, providing immediate user feedback
  • AI Classification: The first LLM (GPT-4o-mini) classifies the message intent into six categories: trade_execution, trade_inquiry, signal_query, signal_clear, help_request, or off_topic
  • Regex Parsing: For trade execution messages, a JavaScript Code node attempts to extract parameters using regex patterns, detecting order type (market vs limit), direction (buy/sell), asset shortcuts (EUβ†’EURUSD, GUβ†’GBPUSD), risk percentage, stop loss, and take profit
  • LLM Fallback: If the regex parser can't confidently extract all required parameters (needs_llm_review: true), a second LLM validates completeness and extracts missing fields, ensuring flexible syntax handling
  • Parameter Validation: The workflow checks if all required parameters are present - market orders need direction, asset, risk%, and SL pips; limit orders additionally require entry price
  • Order Type Routing: A Switch node routes complete orders to the appropriate HTTP endpoint - market orders to /webhook/mt5-market-order, limit orders to /webhook/mt5-limit-order
  • MT5 Execution: HTTP Request nodes send the parsed parameters to your local MT5 webhook endpoints, which execute the trades via the companion MT5 Trading Signal Handler workflow
  • Response Handling: The workflow receives confirmation from MT5, then posts a Discord message confirming successful execution or reporting errors with details
  • Signal Management: For signal_query commands, the bot fetches and displays pending signals from the MT5 queue; for signal_clear commands, it purges all pending signals via HTTP request
  • Help System: When users request help, the bot posts comprehensive instructions covering trade syntax, asset shortcuts, required parameters, and example commands
  • Query Handling: Non-trade questions about trading are answered directly by the AI, providing a conversational assistant experience

How to use

  • Create a Discord bot application at discord.com/developers and obtain OAuth2 credentials with message read/write and reaction permissions
  • Configure Discord OAuth2 credentials in all Discord nodes (use the same credential across all nodes for consistency)
  • Set your OpenAI API key in the three "4o mini" nodes for LLM processing
  • Update the "set credentials and params" node with your Discord server ID and channel ID (right-click in Discord with Developer Mode enabled to copy IDs)
  • Ensure the MT5 Trading Signal Handler workflow is imported, activated, and running on the same n8n instance (default: localhost:5678)
  • Activate this workflow and verify the Schedule Trigger is set to your desired polling interval (7 seconds default)
  • In the "only get user's message that has no reacts" Filter node, change the username from "elijahfx" to your Discord username
  • Post "help" in your Discord channel to test connectivity and receive the command reference guide
  • Try a test market order: buy EU 1% 30 pip SL 3R TP and watch for the πŸ”„ reaction and confirmation message
  • Test a limit order: buy limit EU at 1.0850 1% risk 30 pip SL 2R TP
  • Query pending signals: show me pending signals or any open signals?
  • Clear the queue: clear all pending signals or cancel all signals

Requirements

  • n8n instance running locally or on a private VPS (cloud-hosted n8n may have network restrictions for localhost webhooks)
  • Discord bot application with OAuth2 credentials and appropriate permissions (read messages, send messages, add reactions)
  • OpenAI API account with access to GPT-4o-mini model (approximately $0.15 per 1 million input tokens)
  • MT5 Trading Signal Handler workflow running on the same n8n instance (provides webhook endpoints)
  • Discord server where you have admin permissions to add the bot
  • MetaTrader 5 terminal with the custom EA running and polling the signal queue
  • Basic understanding of Discord bot setup, n8n workflows, and trading concepts

Customising this workflow

  • Add multiple user support by removing the username filter or converting it to a whitelist of approved traders
  • Implement authentication by checking for specific Discord roles before processing trade commands (prevents unauthorized trading)
  • Add trade logging by inserting a database node (PostgreSQL, Airtable) after successful execution to maintain a trade journal
  • Create Discord embeds instead of plain text responses using Discord's embed formatting for richer, more professional replies
  • Add risk limits in a Code node before HTTP requests to cap maximum position sizes or enforce daily loss limits
  • Build a dashboard by connecting to Google Sheets or Notion to track all executed trades, win rates, and performance metrics
  • Implement approval workflows where limit orders post to a separate channel for review before execution
  • Add TradingView alerts as an alternative input by creating a webhook trigger that accepts TradingView JSON payloads
  • Create strategy templates where users can save and recall complete trade setups with a single command like "execute strategy A"
  • Enable multi-account trading by routing orders to different MT5 instances based on user roles or command prefixes
  • Try a popular use-case such as building a signal subscription service where premium Discord members get auto-execution while free members only see the signals!

Purchasing this N8N workflow comes with the Metatrader5 and N8N Integration for Forex and Gold Trading via Webhooks Workflow too so it is sold together and vice versa as well along with the MQL code for the ExpertAdvisor listener all for the price of 120 usd total

Questions?

If you have questions or need help with this workflow, feel free to reach out:

  • elijahmamuri@gmail.com
  • elijahfxtrading@gmail.com

Important Disclaimer: This workflow is provided for educational purposes and demo account testing only. It demonstrates how to build Discord bots with AI-powered natural language processing and webhook integrations. Always test thoroughly on demo accounts, implement proper authentication and security measures, and understand that automated trading involves substantial risk. The bot executes trades based on Discord messages - ensure only authorized users have access. No warranties, financial advice, or guarantees are provided. See the full disclaimer in the workflow for complete terms.

n8n Workflow: Discord AI Trading Assistant with Position Sizing (MetaTrader 5)

This n8n workflow automates the process of receiving trading signals from an AI model, applying proper position sizing, and sending trade execution commands to MetaTrader 5 (MT5) via a custom API, while also providing real-time updates to Discord.

It acts as a bridge between an AI trading strategy and your MT5 trading account, ensuring that trades are executed with calculated risk management and transparently communicated.

What it does

  1. Triggers on a Schedule: The workflow starts at predefined intervals, likely to poll for new trading signals or to perform regular checks.
  2. Fetches Trading Signals: It makes an HTTP request to an external API (presumably your AI trading model or a service providing signals) to retrieve potential trade recommendations.
  3. Filters Valid Signals: The workflow then filters these signals, likely checking for specific conditions or valid data before proceeding.
  4. Processes Signals with AI (LangChain): Valid signals are passed to an AI model (OpenAI Chat Model via LangChain) to further process or interpret the signal, potentially generating a trading decision or refining the signal's parameters.
  5. Calculates Position Size: It uses a Code node to implement custom logic for calculating the appropriate position size based on risk management rules, account balance, and the signal's parameters.
  6. Determines Trade Action: A Switch node routes the workflow based on the AI's output or the processed signal, deciding whether to execute a 'BUY' or 'SELL' trade.
  7. Executes Trade via MT5 API: It sends an HTTP request to a custom API endpoint connected to MetaTrader 5, instructing it to open a trade with the calculated position size and other parameters.
  8. Posts Updates to Discord: Regardless of the trade outcome (or at various stages), it sends messages to a Discord channel, providing real-time updates on signals received, decisions made, and trade executions.

Prerequisites/Requirements

  • n8n Instance: A running n8n instance to host the workflow.
  • OpenAI API Key: For the OpenAI Chat Model node to process trading signals.
  • Custom MetaTrader 5 (MT5) API: An external API endpoint that can receive trade commands and execute them on your MetaTrader 5 account. This API is crucial for trade execution.
  • Discord Webhook/Bot: A Discord server and a configured Discord bot or webhook to send notifications.
  • Trading Signal Source: An external API or service that provides trading signals, which the initial HTTP Request node will query.
  • Basic JavaScript Knowledge: For understanding and potentially customizing the Code node used for position sizing.

Setup/Usage

  1. Import the Workflow: Download the JSON provided and import it into your n8n instance.
  2. Configure Credentials:
    • OpenAI Chat Model: Set up your OpenAI API credentials.
    • Discord: Configure your Discord credentials (e.g., Bot Token or Webhook URL) for the Discord node.
  3. Customize HTTP Request Nodes:
    • Trading Signal API (HTTP Request 1): Update the URL and any necessary headers/authentication for your trading signal source.
    • MT5 Trade Execution API (HTTP Request 2): Update the URL and payload for your custom MetaTrader 5 API to execute trades. Ensure the payload matches what your MT5 API expects (e.g., symbol, type, volume, stop loss, take profit).
  4. Adjust Code Node for Position Sizing:
    • Open the Code node.
    • Modify the JavaScript code to implement your specific position sizing logic. This will likely involve:
      • Accessing data from previous nodes (e.g., account balance, risk percentage, signal parameters).
      • Calculating lot size based on your risk management rules.
  5. Configure Filter and Switch Nodes:
    • Review and adjust the conditions in the Filter node to ensure only valid signals proceed.
    • Review and adjust the cases in the Switch node to correctly route 'BUY' and 'SELL' signals to their respective execution paths.
  6. Customize Discord Messages:
    • Modify the messages in the Discord nodes to provide the desired level of detail and formatting for your notifications.
  7. Activate the Workflow: Once configured, activate the workflow to start automating your trading assistant.

Related Templates

Add Project Tasks to Google Sheets with GPT-4.1-mini Chat Assistant

Let your team create, track, and manage project tasks through natural conversation. This workflow uses an AI Project Manager Agent that chats with users, gathers the task details it needs, and automatically adds them to a Google Sheet. --- βœ… What this template does Lets you chat naturally with an AI to add new project tasks Automatically detects if the user wants to create or update an item (updates coming soon) Collects Task, Description, and Status fields β€” allows β€œdon’t know” responses Appends new entries directly into your connected Google Sheets Provides real-time confirmation when the task is added > Trigger: n8n Chat Trigger > Integrations: OpenAI GPT-4.1-mini + Google Sheets (OAuth2) --- 🧠 How it works The Chat Trigger starts a chat with the user. The AI Project Manager Agent asks guiding questions to gather the task name, description, and status. When all fields are complete (all Info = Yes), the data is passed to the Google Sheets node. The task is automatically added to your project tracker sheet. The AI confirms completion in chat. --- βš™οΈ Setup instructions Connect OpenAI Go to OpenAI Platform β†’ copy your API key. In n8n, create New Credentials β†’ OpenAI API and paste your key. Ensure your account has active billing under OpenAI Billing. Connect Google Sheets (OAuth2) In n8n β†’ Credentials β†’ New β†’ Google Sheets (OAuth2) Sign in with your Google account and grant access. Select your spreadsheet and tab (e.g., β€œTasks”) when prompted. Example sheet: https://docs.google.com/spreadsheets/d/1pbK-B-Q9p8fVjxJIsjEVrAfRgqEPCeYw8rZojZPAb84/edit Test your chat Click Execute Workflow, then start chatting: > β€œAdd a task for reviewing the project report tomorrow.” The agent will ask questions if needed, then add the record to your sheet. --- 🧩 Customization ideas Add a Date Added or Assigned To column to the Google Sheet Integrate with Slack or Outlook to message assigned users Extend the agent to support task updates and deletes Replace Google Sheets with Airtable or Notion if preferred --- πŸͺ„ Requirements n8n version β‰₯ 1.100 OpenAI API key Google Sheets account --- πŸ“¬ Contact Need help customizing this (e.g., adding deadlines, linking to Notion, or Slack notifications)? πŸ“§ robert@ynteractive.com πŸ”— Robert Breen 🌐 ynteractive.com

Robert BreenBy Robert Breen
10823

Translate documents to multiple languages with Google Drive and DeepL

Who's it for This workflow is perfect for content creators, international teams, and businesses that need to translate documents into multiple languages automatically. Whether you're localizing documentation, translating marketing materials, or creating multilingual content, this workflow saves hours of manual work. What it does Automatically monitors a Google Drive folder for new documents (PDF, DOCX, TXT, or Markdown) and translates them into multiple languages using DeepL API. Each translated document is saved with a language-specific filename (e.g., documenten.pdf, documentzh.pdf) in a designated folder. You receive an email notification when all translations are complete. How it works Monitors a Google Drive folder for new files Detects file format (PDF/DOCX/TXT/Markdown) and extracts text Translates the content into your chosen languages (default: English, Chinese, Korean, Spanish, French, German) Saves translated files with language codes in the filename Sends an email notification with translation summary Optional: Records translation history in Notion database Set up instructions Requirements Google Drive account (for file storage) DeepL API key (free tier: 500,000 characters/month) Gmail account (for notifications) Notion account (optional, for tracking translation history) Setup steps Create Google Drive folders: Create a "Source" folder for original files Create a "Translated" folder for output Copy the folder IDs from the URLs Get DeepL API key: Sign up at DeepL API Copy your API key Configure the workflow: Open the "Configuration (Edit Here)" node (yellow node) Replace folder IDs with your own Set your notification email Choose target languages Set up credentials: Add Google Drive OAuth2 credentials Add DeepL API credentials Add Gmail OAuth2 credentials Activate the workflow and upload a test file! Customization options Change target languages: Edit the targetLanguages array in the Configuration node (supports 30+ languages) Adjust polling frequency: Change trigger from "every minute" to hourly or daily for batch processing Enable Notion tracking: Set enableNotion to true and provide your database ID Add more file formats: Extend the Switch node to handle additional file types Filter by file size: Add conditions to skip files larger than a certain size Supported languages EN (English), ZH (Chinese), KO (Korean), JA (Japanese), ES (Spanish), FR (French), DE (German), IT (Italian), PT (Portuguese), RU (Russian), and 20+ more. Performance Short files (1 page): ~30 seconds for 6 languages Medium files (10 pages): ~2 minutes for 6 languages Large files (100 pages): ~15 minutes for 6 languages Technical Details Trigger: Google Drive folder monitoring (1-minute polling) Translation: DeepL API with automatic source language detection Loop implementation: Split Out + Aggregate pattern for parallel translation Error handling: Catches API failures and sends email alerts Storage: Original file format preserved in translated outputs Notes DeepL free tier provides 500,000 characters/month (approximately 250 pages) For high-volume translation, consider upgrading to DeepL Pro The workflow creates new files instead of overwriting, preserving translation history Google Docs are automatically converted to the appropriate format before translation What You'll Learn This workflow demonstrates several n8n patterns: File format detection and routing (Switch node) Loop implementation with Split Out + Aggregate Binary data handling for file operations Conditional logic with IF nodes (optional features) Cross-node data references Error handling and user notifications Perfect for learning automation best practices while solving a real business problem!

Daiki TakayamaBy Daiki Takayama
341

Create & publish affiliate product videos with Sora-2, GPT & YouTube

πŸš€ Affiliate AI-Powered Video Funnel Fully Automated Product Video Creation & Publishing Turn your affiliate links or product catalog into a 24/7 AI video marketing machine. This n8n workflow auto-creates human-presenter promo videos using AI and publishes them directly to YouTube with SEO β€” completely hands-free. βœ… --- 🎯 What This Automation Does πŸ”„ Fetches product or affiliate data from Google Sheets / Airtable / Database πŸŽ™οΈ Generates human-presenter video prompts (Sora-style) using AI Agents 🎬 Renders promotional videos automatically via AI video generation ⏳ Polls render completion & handles errors safely πŸ“€ Uploads videos to YouTube (draft, unlisted, or public) 🧠 Auto-generates SEO metadata (titles, descriptions, tags, hashtags) βœ… Human approval flow before public publishing πŸ“ Updates catalog status to prevent duplicates ⏱️ Runs daily, weekly, or per request via form or trigger This workflow eliminates all repetitive editing, uploading, and SEO work β€” your channel grows while you sleep. πŸ˜΄πŸ“ˆ --- πŸ§‘β€πŸ« Step-by-Step Video Tutorial πŸŽ₯ Complete Implementation Demo πŸ‘‰ https://youtu.be/pOxcVbYdr0w πŸ“Œ Covers full setup, rendering, approval, publishing, and automation scheduling. --- 🌐 Useful Links πŸ› οΈ n8n Hosting / Setup Support: https://syncbricks.com πŸ“š YouTube Data API Docs: https://developers.google.com/youtube/v3 πŸ€– Kai / AI Render Service: (any Sora-style provider you choose)* 🧠 AI Prompt Docs (OpenAI etc.): https://platform.openai.com/docs/api-reference --- πŸ›  Prerequisites βœ… n8n (Self-Hosted or Cloud) βœ… AI Agent inside n8n configured βœ… YouTube API credentials βœ… Product/Affiliate data source: Google Sheets OR Airtable OR Database βœ… AI Video Rendering: Sora-style provider API πŸ“ Recommended product fields: > Title, Summary, Brand, Landing Page, Affiliate Link (if using monetization) --- πŸ“‹ How This Workflow Works β€” Step by Step 1️⃣ Product Input & Filtering Fetch unpublished product/item Skip rows marked β€œPublished” or with error codes Ideal for drip publishing content every day 2️⃣ AI Promo Script + Presenter Prompt Converts product benefits β†’ human script Adds overlays + camera movement + style cues Presenter looks professional, friendly & trusted 3️⃣ AI Video Rendering Send prompt, wait for result Retry & timeout safety built-in 4️⃣ YouTube Upload Uploads automatically as Unlisted βœ… Sends Human-In-The-Loop (HITL) approval After approval β†’ Public Publish 5️⃣ SEO Enhancement Generates tags, hashtags & optimized titles Inserts affiliate link into description Updates video via YouTube API 6️⃣ Mark As Published Saves record in sheet/db Avoids duplicate publishing --- πŸ’° Affiliate / Monetization Features πŸ›’ Add PartnerStack / Amazon Associates links πŸ”— Auto-insert affiliate URLs per product 🧩 Optional dynamic UTM tracking πŸ“ˆ Ready for performance dashboards (CTR, views) You create zero videos, yet grow daily affiliate revenue. πŸ”₯ --- πŸ’‘ Advanced Customizations | Idea | Benefit | | ------------------------------- | ------------------------------- | | Multi-platform publishing | Expand reach beyond YouTube | | Multi-language voice & captions | Increase global audience | | Category-based styles | Better storytelling per product | | Bulk overnight generation | Boost weekly content output | | Analytics integration | Track growth & ROI easily | --- ⚠️ Troubleshooting | Issue | Fix | | ----------------- | ------------------------------ | | No video returned | Check AI render provider quota | | Upload fails | Verify YouTube OAuth scopes | | Duplicate uploads | Confirm Published tag update | | Video quality | Adjust prompt style profile | --- πŸ™Œ Why This Template You can scale affiliate & product-based video content without editing tools, creators, or extra headcount: βœ… Saves hours per video βœ… Builds traffic and trust automatically βœ… Generates recurring affiliate income βœ… Turns your product list into a money-making content engine --- πŸš€ Get Started in Minutes Import the workflow β†’ Connect APIs β†’ Approve β†’ Publish β†’ Earn πŸ’Έ πŸ‘‰ More AI + n8n Workflows & Support https://syncbricks.com πŸ‘‰ Subscribe for Tutorials https://youtube.com/@syncbricks πŸ‘‰ Connect with the creator (Amjid Ali) https://linkedin.com/in/amjidali --- πŸ”– Knowledge Base Tags aivideoautomation, affiliatemarketing, youtubeapi, handsfreeautomation, ecommercevideomarketing, n8naiagents, socialvideoautomation, productvideogenerator, workflowautomation, marketing_scaling

Amjid AliBy Amjid Ali
292