Back to Catalog

AI trading assistant for Telegram using chatGPT-4o (with Position Sizing)

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

MT5 AI Trading Assistant - Telegram Bot Workflow with position sizing capabilities

Open trades for forex/xauusd/gold with this n8n template. It demonstrates how to automate MetaTrader 5 trading executions through natural language commands via Telegram, enabling hands-free trade management with AI-powered intent classification and parameter parsing.

Use cases are many

Try executing market orders right away when you see an opportunity using commands, setting up limit orders with precise entry points, or managing pending signals directly from your phone! This workflow handles everything from simple "buy EU 1% 30 pip SL and 3R TP" commands to complex limit orders with risk-reward calculations.

Good to know

  • This template is for educational purposes only - requires significant security hardening before live trading use
  • OpenAI API costs apply - approximately $0.0001-0.0005 per message depending on complexity
  • Webhook endpoints are NOT authenticated by default - you must add authentication before production deployment or if you want extra security
  • No built-in position size limits - add validation to cap maximum risk percentage
  • MT5 Expert Advisor required - this workflow only sends signals; you need a separate EA to execute trades
  • Local/VPS deployment recommended - not suitable for public cloud without security hardening
  • Always test with demo accounts first - automated trading involves substantial risk of loss

How it works

  • The Telegram Chat Trigger listens for incoming messages from authorized users in your Telegram bot
  • A reaction emoji (πŸ‘) is immediately sent to acknowledge message receipt using the Telegram API
  • The first AI classifier (GPT-4o mini) analyzes the message intent and categorizes it into six types: trade execution, trade inquiry, help request, signal query, signal clear, or off-topic
  • For trade execution commands, a regex-based parser extracts parameters (asset, direction, risk, stop loss, take profit) from natural language
  • If initial parsing is incomplete or confidence is low, an LLM fallback parser attempts to extract missing parameters with strict validation
  • Complete trade parameters are routed through a Switch node to determine order type (market vs limit)
  • Market orders trigger an HTTP POST to webhook/mt5-market-order with asset, direction, risk, SL, and TP parameters
  • Limit orders include an additional entry price parameter and route to webhook/mt5-limit-order
  • For signal queries, the workflow fetches pending signals from webhook/mt5-signals and formats the response
  • Signal clearing commands POST to webhook/mt5-clear-all to remove all pending orders
  • Trade execution success/failure is validated and appropriate confirmation messages are sent back to Telegram
  • Help requests receive multi-part instructional messages with command examples and formatting guidelines

How to use

  • Set up your Telegram bot via BotFather and obtain your bot token
  • Configure the Telegram credentials in both the Chat Trigger and all response nodes
  • Add your OpenAI API key to the three "4o mini" language model nodes
  • Deploy the four MT5 webhook endpoints (market-order, limit-order, signals, clear-all) on your local machine or VPS
  • Critical: Implement authentication on all webhook endpoints before connecting to live MT5 accounts
  • Test commands with demo account first: try "buy EU 1% 30 pip SL 3R TP" or "show pending signals"
  • Consider adding user ID whitelisting in the "set credentials and params" node for access control
  • Modify the AI prompts in the classifier nodes to adjust trading parameter validation rules

Requirements

  • Telegram Bot API account for receiving and sending messages
  • OpenAI API key for GPT-4o mini language model (intent classification and parameter parsing)
  • MetaTrader 5 platform with custom Expert Advisor that listens to webhook signals
  • n8n instance running locally or on VPS (self-hosted or cloud)
  • Basic understanding of forex trading concepts (pips, risk management, order types)

Customising this workflow

  • Add a user whitelist validation node after the Telegram trigger to restrict access to specific Telegram user IDs
  • Implement maximum risk percentage caps (e.g., 5%) in the parameter validation nodes
  • Create an asset whitelist to only allow specific currency pairs your broker supports
  • Add audit logging by storing trade commands and execution results to a database
  • Include trade confirmation mode: send preview before execution and wait for "confirm" message
  • Integrate with position sizing calculators based on account equity and volatility
  • Add webhook authentication headers (API keys or JWT tokens) to all HTTP request nodes
  • Create a scheduled workflow to auto-expire pending signals after a certain time period
  • Try a popular use-case such as connecting to TradingView alerts instead of manual Telegram commands

Important Security Disclaimer

⚠️ This workflow is NOT production-ready in its current form.

Before using with live trading:

  • Add authentication to all webhook endpoints
  • Implement input validation for risk limits, asset whitelists, and parameter ranges
  • Add rate limiting to prevent spam attacks
  • Set up user authorization to restrict who can execute trades
  • Test extensively with demo accounts for at least 3-6 months
  • Understand that automated trading involves substantial risk of loss

This template is provided for educational purposes only and does not constitute financial advice. You are solely responsible for implementing security measures, testing thoroughly, and accepting all trading risks.

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

n8n AI Trading Assistant for Telegram using GPT-4o with Position Sizing

This n8n workflow acts as an AI-powered trading assistant, allowing users to interact with a ChatGPT-4o model via Telegram to get trading advice, including position sizing recommendations.

What it does

This workflow automates the following steps:

  1. Listens for Telegram Messages: It triggers when a new message is received in a configured Telegram bot.
  2. Filters Specific Commands: It checks if the received message contains a specific command (e.g., /trade).
  3. Prepares AI Prompt: If the command is detected, it extracts the relevant part of the message to be used as a prompt for the AI.
  4. Invokes ChatGPT-4o: It sends the prepared prompt to a ChatGPT-4o model (via LangChain's Basic LLM Chain and OpenAI Chat Model) to generate trading advice.
  5. Sends AI Response to Telegram: It takes the AI's response and sends it back to the user in the Telegram chat.

Prerequisites/Requirements

To use this workflow, you will need:

  • n8n Instance: A running instance of n8n.
  • Telegram Bot Token: A Telegram bot token obtained from BotFather.
  • OpenAI API Key: An API key for OpenAI to access the ChatGPT-4o model.
  • LangChain Integration: Ensure the LangChain nodes are installed and configured in your n8n instance.

Setup/Usage

  1. Import the Workflow: Import the provided JSON into your n8n instance.
  2. Configure Telegram Trigger:
    • Open the "Telegram Trigger" node.
    • Select or create a new Telegram API credential using your bot token.
    • Set the "Update Type" to "Message".
  3. Configure OpenAI Chat Model:
    • Open the "OpenAI Chat Model" node (within the "Basic LLM Chain").
    • Select or create a new OpenAI API credential using your OpenAI API Key.
    • Ensure the model is set to gpt-4o or your preferred model.
  4. Configure Telegram Action:
    • Open the "Telegram" node.
    • Select the same Telegram API credential used in the trigger.
    • Set the "Chat ID" to the appropriate chat where the bot should respond (e.g., ={{ $json.chat.id }} to reply to the sender).
    • Ensure the "Text" field is configured to send the output from the AI model (e.g., ={{ $json.text }}).
  5. Activate the Workflow: Save and activate the workflow.

Once activated, your Telegram bot will listen for messages. When a message containing the configured command (e.g., /trade) is sent, the workflow will process it, generate an AI response, and send it back to the Telegram chat.

Related Templates

Generate song lyrics and music from text prompts using OpenAI and Fal.ai Minimax

Spark your creativity instantly in any chatβ€”turn a simple prompt like "heartbreak ballad" into original, full-length lyrics and a professional AI-generated music track, all without leaving your conversation. πŸ“‹ What This Template Does This chat-triggered workflow harnesses AI to generate detailed, genre-matched song lyrics (at least 600 characters) from user messages, then queues them for music synthesis via Fal.ai's minimax-music model. It polls asynchronously until the track is ready, delivering lyrics and audio URL back in chat. Crafts original, structured lyrics with verses, choruses, and bridges using OpenAI Submits to Fal.ai for melody, instrumentation, and vocals aligned to the style Handles long-running generations with smart looping and status checks Returns complete song package (lyrics + audio link) for seamless sharing πŸ”§ Prerequisites n8n account (self-hosted or cloud with chat integration enabled) OpenAI account with API access for GPT models Fal.ai account for AI music generation πŸ”‘ Required Credentials OpenAI API Setup Go to platform.openai.com β†’ API keys (sidebar) Click "Create new secret key" β†’ Name it (e.g., "n8n Songwriter") Copy the key and add to n8n as "OpenAI API" credential type Test by sending a simple chat completion request Fal.ai HTTP Header Auth Setup Sign up at fal.ai β†’ Dashboard β†’ API Keys Generate a new API key β†’ Copy it In n8n, create "HTTP Header Auth" credential: Name="Fal.ai", Header Name="Authorization", Header Value="Key [Your API Key]" Test with a simple GET to their queue endpoint (e.g., /status) βš™οΈ Configuration Steps Import the workflow JSON into your n8n instance Assign OpenAI API credentials to the "OpenAI Chat Model" node Assign Fal.ai HTTP Header Auth to the "Generate Music Track", "Check Generation Status", and "Fetch Final Result" nodes Activate the workflowβ€”chat trigger will appear in your n8n chat interface Test by messaging: "Create an upbeat pop song about road trips" 🎯 Use Cases Content Creators: YouTubers generating custom jingles for videos on the fly, streamlining production from idea to audio export Educators: Music teachers using chat prompts to create era-specific folk tunes for classroom discussions, fostering interactive learning Gift Personalization: Friends crafting anniversary R&B tracks from shared memories via quick chats, delivering emotional audio surprises Artist Brainstorming: Songwriters prototyping hip-hop beats in real-time during sessions, accelerating collaboration and iteration ⚠️ Troubleshooting Invalid JSON from AI Agent: Ensure the system prompt stresses valid JSON; test the agent standalone with a sample query Music Generation Fails (401/403): Verify Fal.ai API key has minimax-music access; check usage quotas in dashboard Status Polling Loops Indefinitely: Bump wait time to 45-60s for complex tracks; inspect fal.ai queue logs for bottlenecks Lyrics Under 600 Characters: Tweak agent prompt to enforce fuller structures like [V1][C][V2][B][C]; verify output length in executions

Daniel NkenchoBy Daniel Nkencho
601

Auto-reply & create Linear tickets from Gmail with GPT-5, gotoHuman & human review

This workflow automatically classifies every new email from your linked mailbox, drafts a personalized reply, and creates Linear tickets for bugs or feature requests. It uses a human-in-the-loop with gotoHuman and continuously improves itself by learning from approved examples. How it works The workflow triggers on every new email from your linked mailbox. Self-learning Email Classifier: an AI model categorizes the email into defined categories (e.g., Bug Report, Feature Request, Sales Opportunity, etc.). It fetches previously approved classification examples from gotoHuman to refine decisions. Self-learning Email Writer: the AI drafts a reply to the email. It learns over time by using previously approved replies from gotoHuman, with per-classification context to tailor tone and style (e.g., different style for sales vs. bug reports). Human Review in gotoHuman: review the classification and the drafted reply. Drafts can be edited or retried. Approved values are used to train the self-learning agents. Send approved Reply: the approved response is sent as a reply to the email thread. Create ticket: if the classification is Bug or Feature Request, a ticket is created by another AI agent in Linear. Human Review in gotoHuman: How to set up Most importantly, install the gotoHuman node before importing this template! (Just add the node to a blank canvas before importing) Set up credentials for gotoHuman, OpenAI, your email provider (e.g. Gmail), and Linear. In gotoHuman, select and create the pre-built review template "Support email agent" or import the ID: 6fzuCJlFYJtlu9mGYcVT. Select this template in the gotoHuman node. In the "gotoHuman: Fetch approved examples" http nodes you need to add your formId. It is the ID of the review template that you just created/imported in gotoHuman. Requirements gotoHuman (human supervision, memory for self-learning) OpenAI (classification, drafting) Gmail or your preferred email provider (for email trigger+replies) Linear (ticketing) How to customize Expand or refine the categories used by the classifier. Update the prompt to reflect your own taxonomy. Filter fetched training data from gotoHuman by reviewer so the writer adapts to their personalized tone and preferences. Add more context to the AI email writer (calendar events, FAQs, product docs) to improve reply quality.

gotoHumanBy gotoHuman
353

Dynamic Hubspot lead routing with GPT-4 and Airtable sales team distribution

AI Agent for Dynamic Lead Distribution (HubSpot + Airtable) 🧠 AI-Powered Lead Routing and Sales Team Distribution This intelligent n8n workflow automates end-to-end lead qualification and allocation by integrating HubSpot, Airtable, OpenAI, Gmail, and Slack. The system ensures that every new lead is instantly analyzed, scored, and routed to the best-fit sales representative β€” all powered by AI logic, sir. --- πŸ’‘ Key Advantages ⚑ Real-Time Lead Routing Automatically assigns new leads from HubSpot to the most relevant sales rep based on region, capacity, and expertise. 🧠 AI Qualification Engine An OpenAI-powered Agent evaluates the lead’s industry, region, and needs to generate a persona summary and routing rationale. πŸ“Š Centralized Tracking in Airtable Every lead is logged and updated in Airtable with AI insights, rep details, and allocation status for full transparency. πŸ’¬ Instant Notifications Slack and Gmail integrations alert the assigned rep immediately with full lead details and AI-generated notes. πŸ” Seamless CRM Sync Updates the original HubSpot record with lead persona, routing info, and timeline notes for audit-ready history, sir. --- βš™οΈ How It Works HubSpot Trigger – Captures a new lead as soon as it’s created in HubSpot. Fetch Contact Data – Retrieves all relevant fields like name, company, and industry. Clean & Format Data – A Code node standardizes and structures the data for consistency. Airtable Record Creation – Logs the lead data into the β€œLeads” table for centralized tracking. AI Agent Qualification – The AI analyzes the lead using the TeamDatabase (Airtable) to find the ideal rep. Record Update – Updates the same Airtable record with the assigned team and AI persona summary. Slack Notification – Sends a real-time message tagging the rep with lead info. Gmail Notification – Sends a personalized handoff email with context and follow-up actions. HubSpot Sync – Updates the original contact in HubSpot with the assignment details and AI rationale, sir. --- πŸ› οΈ Setup Steps Trigger Node: HubSpot β†’ Detect new leads. HubSpot Node: Retrieve complete lead details. Code Node: Clean and normalize data. Airtable Node: Log lead info in the β€œLeads” table. AI Agent Node: Process lead and match with sales team. Slack Node: Notify the designated representative. Gmail Node: Email the rep with details. HubSpot Node: Update CRM with AI summary and allocation status, sir. --- πŸ” Credentials Required HubSpot OAuth2 API – To fetch and update leads. Airtable Personal Access Token – To store and update lead data. OpenAI API – To power the AI qualification and matching logic. Slack OAuth2 – For sending team notifications. Gmail OAuth2 – For automatic email alerts to assigned reps, sir. --- πŸ‘€ Ideal For Sales Operations and RevOps teams managing multiple regions B2B SaaS and enterprise teams handling large lead volumes Marketing teams requiring AI-driven, bias-free lead assignment Organizations optimizing CRM efficiency with automation, sir --- πŸ’¬ Bonus Tip You can easily extend this workflow by adding lead scoring logic, language translation for follow-ups, or Salesforce integration. The entire system is modular β€” perfect for scaling across global sales teams, sir.

MANISH KUMARBy MANISH KUMAR
113