{
  "name": "AI Stock Analysis Reports — Main Orchestrator",
  "nodes": [
    {
      "id": "3d02c092-8d71-453c-9c15-630df4767690",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2048,
        -944
      ],
      "parameters": {
        "color": 5,
        "width": 1888,
        "height": 704,
        "content": "## Triggers \nThis workflow starts the analysis either on a weekly schedule for a predefined list of stocks or when you manually submit a single stock ticker through a form."
      },
      "typeVersion": 1
    },
    {
      "id": "fce7e223-d118-4501-b88b-91eb18109700",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -96,
        -944
      ],
      "parameters": {
        "color": 4,
        "width": 1984,
        "height": 704,
        "content": "## Stock Analysis (Main AI Agent) \nThis is the core AI agent that orchestrates the entire process, calling the other analysis tools to gather data and then synthesizing it all into a final, structured report."
      },
      "typeVersion": 1
    },
    {
      "id": "05ff2233-4353-4658-aae5-cb912bd3f191",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2016,
        -832
      ],
      "parameters": {
        "width": 416,
        "height": 256,
        "content": "### Scheduled Batch Trigger \nRuns a predefined list of stocks weekly. List of stocks can be changed"
      },
      "typeVersion": 1
    },
    {
      "id": "e8fb24ef-7cd0-4948-9cb6-4a6b8199a222",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3248,
        -272
      ],
      "parameters": {
        "color": 7,
        "width": 1040,
        "height": 832,
        "content": "# Workflow Description and Setup Guide\n\n### This template deploys a multi-agent system that fully automates advanced stock analysis. It uses a central AI orchestrator to call specialized sub-workflows, synthesizing technical, fundamental, and news sentiment data into a single, actionable report delivered to your inbox. **All API Keys can be acquired for free!**\n\n**How it Works**\n\n*   **Orchestration:** An AI Agent acts as the central \"brain,\" managing the analysis pipeline. It's triggered either on a schedule for a list of stocks or manually for a single ticker.\n*   **Specialist Agents (Tools):** The orchestrator invokes three sub-workflows as tools to gather intelligence:\n    1.  **Technical Analysis:** Fetches TA data (RSI, MACD, Bollinger Bands) and uses a vision-AI to analyze the stock's chart, identifying trends and patterns.\n    2.  **Fundamental Analysis:** Retrieves financial statements (Income, Balance Sheet) to generate a summary of the company's financial health and valuation.\n    3.  **News Sentiment Analysis:** Aggregates and analyzes market news to determine overall sentiment and identify key discussion topics.\n*   **Synthesis & Delivery:** The main agent synthesizes all findings to formulate a final recommendation (Buy, Hold, Sell), generates a professional HTML report, and delivers it via email.\n\n**Setup (Est. 10-15 mins)**\n\nThis is an advanced, multi-workflow template. Please follow the steps precisely.\n\n1.  **Split Modules:** Separate the 5 color-coded modules on this canvas into 5 new, individual workflows.\n2.  **Acquire APIs:** Acquire the 7 APIs needed for this workflow. These need Credentials: Gemini,, OpenRouter, SMTP, Alpaca. These just need to be pasted in: AlphaVantage, TwelveData, Chart-Img.\n3.  **Configure & Link:** Insert your API keys and email, then re-link the `Execute Workflow` and `Tool` nodes to connect your new workflows.\n4.  **Activate:** Toggle all 5 workflows to \"Active.\"\n\n➡️ **For the complete, detailed guide, visit: https://docs.google.com/document/d/1Ri_GfuIlc0QVm1aDrWJjRCg_2vWRCrw_SjRV9cBoKmw/edit?usp=sharing**\n"
      },
      "typeVersion": 1
    },
    {
      "id": "9018c6a6-9ae6-499a-894a-9765382ddd39",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1392,
        -544
      ],
      "parameters": {
        "width": 304,
        "height": 224,
        "content": "### Manual Single Trigger\nRun analysis for one stock instantly via a form."
      },
      "typeVersion": 1
    },
    {
      "id": "e9194ab1-2d1c-47fe-b756-3b7d6686d89e",
      "name": "Sticky Note8",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1104,
        -864
      ],
      "parameters": {
        "width": 416,
        "height": 224,
        "content": "### Optional: Complete paper trade in Alpaca"
      },
      "typeVersion": 1
    },
    {
      "id": "4898e4bb-4c18-4aa7-a3b8-87284dd832db",
      "name": "Sticky Note9",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1104,
        -624
      ],
      "parameters": {
        "width": 656,
        "height": 208,
        "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n### Generate report and send to email"
      },
      "typeVersion": 1
    },
    {
      "id": "846b7424-5e17-4284-ae0a-499d1311f14b",
      "name": "Sticky Note10",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1536,
        -448
      ],
      "parameters": {
        "color": 3,
        "height": 80,
        "content": "### Add SMTP Credentials and add your email"
      },
      "typeVersion": 1
    },
    {
      "id": "f30c0c6e-32ce-4a4e-bb6e-0a8b2d627bec",
      "name": "Sticky Note11",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        528,
        -512
      ],
      "parameters": {
        "width": 400,
        "height": 224,
        "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n### These 3 tools are 3 different sub-workflows, and each must be linked back to this"
      },
      "typeVersion": 1
    },
    {
      "id": "302a706d-3216-43cf-ae6a-35a6d22d9470",
      "name": "Sticky Note20",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        128,
        -336
      ],
      "parameters": {
        "color": 3,
        "width": 150,
        "height": 80,
        "content": "### Add Gemini Credential"
      },
      "typeVersion": 1
    },
    {
      "id": "ceb22483-fe52-45be-8328-daa972967d96",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -1968,
        -736
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 6,
              "triggerAtMinute": 20
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "1d48372f-ff05-429e-be00-e742cf3a4d9d",
      "name": "Stock List",
      "type": "n8n-nodes-base.set",
      "position": [
        -1744,
        -736
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "c0218624-9927-4cc1-bbaf-735dfe799510",
              "name": "tickers",
              "type": "array",
              "value": "[\"LLY\", \"UNH\", \"JPM\", \"V\", \"XOM\", \"HD\", \"CAT\", \"AAPL\", \"MSFT\", \"NVDA\", \"AMZN\", \"GOOGL\", \"META\", \"AVGO\", \"COST\"]"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "e1d3ff6f-33ec-4c92-aa8b-300d09adddea",
      "name": "Split Out",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        -1520,
        -736
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "tickers"
      },
      "typeVersion": 1
    },
    {
      "id": "f2fb1094-2dda-416c-bad5-43dbe8ab9716",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        -1296,
        -736
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "60d6e8bd-3ed4-498e-83ca-5e69148f9ee9",
      "name": "On form submission",
      "type": "n8n-nodes-base.formTrigger",
      "position": [
        -1296,
        -464
      ],
      "webhookId": "fbcfd3c3-f526-4305-9618-f6c8d95bcc9f",
      "parameters": {
        "options": {
          "appendAttribution": true,
          "respondWithOptions": {
            "values": {
              "formSubmittedText": "Success! Check your inbox (or spam folder) for your analysis report."
            }
          }
        },
        "formTitle": "Manual Entry: Stock Analysis",
        "formFields": {
          "values": [
            {
              "fieldLabel": "tickers",
              "placeholder": "TSLA",
              "requiredField": true
            }
          ]
        },
        "responseMode": "lastNode",
        "formDescription": "Please enter the company’s NASDAQ ticker symbol (e.g. AAPL) to get a weekly email with combined technical-and-news sentiment analysis from our AI agent"
      },
      "typeVersion": 2.2
    },
    {
      "id": "ed11160f-f107-4fb6-9e88-f9d3d76d2695",
      "name": "Set Ticker for AI Agent",
      "type": "n8n-nodes-base.set",
      "position": [
        -1072,
        -816
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "87e6b7de-d5c7-497a-8cb4-64eaeb2808a5",
              "name": "body.ticker",
              "type": "string",
              "value": "={{ $json.tickers }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "dab3cea6-6c4e-40a7-af5b-26d85e9e11f3",
      "name": "Execute Workflow",
      "type": "n8n-nodes-base.executeWorkflow",
      "position": [
        -848,
        -816
      ],
      "parameters": {
        "options": {
          "waitForSubWorkflow": true
        },
        "workflowId": {
          "__rl": true,
          "mode": "id",
          "value": ""
        },
        "workflowInputs": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "165454a5-3dcc-4913-a5fe-c96d2a64a6b5",
      "name": "If",
      "type": "n8n-nodes-base.if",
      "onError": "continueRegularOutput",
      "position": [
        -624,
        -816
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "or",
          "conditions": [
            {
              "id": "64dd4b1c-e3dd-499d-b730-00e933c33a7d",
              "operator": {
                "type": "string",
                "operation": "exists",
                "singleValue": true
              },
              "leftValue": "={{ $('Stock List').item.json.tickers }}",
              "rightValue": "={{ $('Set Ticker for AI Agent').item.json.body.ticker }}"
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "92b114d2-0e9c-4440-9e44-dff72fa20b1b",
      "name": "Wait",
      "type": "n8n-nodes-base.wait",
      "position": [
        -400,
        -736
      ],
      "webhookId": "2c94a162-4cd1-4971-b192-a3e045bb5507",
      "parameters": {
        "unit": "minutes",
        "amount": 5
      },
      "typeVersion": 1.1
    },
    {
      "id": "5b4e84d5-6d44-486c-a3e7-881852984827",
      "name": "When Executed by Another Workflow",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "position": [
        -48,
        -704
      ],
      "parameters": {
        "inputSource": "passthrough"
      },
      "typeVersion": 1.1
    },
    {
      "id": "8263204a-26ee-4ac7-9ef6-17f220c95c08",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        496,
        -704
      ],
      "parameters": {
        "text": "=Ticker = {{ $json.body.ticker }}",
        "options": {
          "systemMessage": "=You are an expert AI financial analyst. Your primary role is to act as an orchestrator: you will call specialized tools to gather raw data, and then you will synthesize that data into a complete, well-written, and structured report.\n\n# Instructions\nYour task is to follow this exact procedure step-by-step:\n\n1.  **Identify the Input:** The user will provide a stock symbol (e.g., \"AAPL\").\n\n2.  **Gather Data Using Tools (Mandatory Calls):**\n    You MUST use the provided tools to gather all necessary information. You cannot generate or invent any data yourself. Your ability to complete this task is entirely dependent on the outputs of these tools.\n    *   **First, call the `technical_analysis` tool:**\n        *   Invoke it using the syntax: `technical_analysis(stock_symbol=\"[IDENTIFIED_STOCK_SYMBOL]\")`\n    *   **Next, call the `trends_analysis` tool:**\n        *   Invoke it using the syntax: `trends_analysis(stock_symbol=\"[IDENTIFIED_STOCK_SYMBOL]\")`\n    *   **Finally, call the `fundamental_analysis` tool:**\n        *   Invoke it using the syntax: `fundamental_analysis(stock_symbol=\"[IDENTIFIED_STOCK_SYMBOL]\")`\n\n3.  **Synthesize, Write, and Formulate a Recommendation:**\n    Once you have received the outputs from ALL THREE tools, you must perform the following synthesis and writing tasks:\n    *   **Write the `technicalAnalysis` Text:** Analyze the raw data from the `technical_analysis` tool. Based on this data, write a professional, human-readable paragraph that synthesizes the most important technical indicators (like the trend, RSI, Bollinger Bands), states the resulting bias (e.g., bullish, bearish, neutral), and gives a final actionable takeaway. **This final output must be a single string wrapped in `<p>` tags.**\n    *   **Write the `recommendationText`:** Analyze the combined technical, news sentiment, and fundamental data. Formulate a clear investment recommendation (Buy, Hold, or Sell). Then, write a clear, professional paragraph explaining the \"why\" behind your recommendation, referencing key data points from all three analysis types.\n    *   Your default recommendation should be \"Hold\" unless there is a strong, data-driven signal for \"Buy\" or \"Sell\". Ensure all generated text is professional, clear, and written in English.\n\n4.  **Construct the Final Report:**\n    Finally, compile all the gathered data and your synthesized text into the JSON object specified in the Response Format. Ensure strict adherence to the schema.\n\n## Tools\n- **technical_analysis(stock_symbol: string)**: Retrieves comprehensive technical analysis data and a chart image URL for a given stock ticker.\n- **trends_analysis(stock_symbol: string)**: Fetches news sentiment, relevant articles, and identifies trending topics for a given stock ticker.\n- **fundamental_analysis(stock_symbol: string)**: Fetches fundamental financial data, including valuation, performance, and a summary of financial health.\n\n## Response Format\nYou must respond with a JSON object containing exactly the following keys. Pay close attention to the `technicalAnalysis` and `recommendationText` fields, which you must write yourself based on the tool data.\n\n{\n  \"stockSymbol\": \"STOCK_TICKER\",\n  \"analysisDate\": \"DD/MM/YYYY\",\n  \"recommendationClass\": \"positive/neutral/negative\",\n  \"recommendationTitle\": \"Concise Recommendation Title in English\",\n  \"recommendationText\": \"Detailed explanation of the recommendation in English that you have written.\",\n  \"bullishCount\": 0,\n  \"neutralCount\": 0,\n  \"bearishCount\": 0,\n  \"bullishHeight\": 0,\n  \"neutralHeight\": 0,\n  \"bearishHeight\": 0,\n  \"overallSentiment\": \"Bullish/Neutral/Bearish\",\n  \"Recommendation\": \"Buy/Hold/Sell\",\n  \"sentimentScore\": 0.00,\n  \"chartImageUrl\": \"URL_PLACEHOLDER\",\n  \"technicalAnalysis\": \"<p>Detailed technical analysis that you have written, using p tags for paragraphs.</p>\",\n  \"fundamentalAnalysis\": {\n    \"company_overview\": \"The company description extracted from the tool.\",\n    \"key_metrics\": {\n      \"market_cap\": \"The market cap extracted from the tool.\",\n      \"pe_ratio\": \"The P/E ratio extracted from the tool.\",\n      \"eps\": \"The EPS extracted from the tool.\"\n    },\n    \"financial_summary\": \"The financial summary paragraph from the tool.\"\n  },\n  \"topArticles\": [\n    {\n      \"title\": \"Article title in English\",\n      \"url\": \"URL of the article\",\n      \"source\": \"Source name in English\",\n      \"date\": \"DD/MM/YYYY\",\n      \"sentimentClass\": \"bullish/neutral/bearish\"\n    }\n  ],\n  \"hotTopics\": [\n    {\n      \"topic\": \"Topic name in English\",\n      \"article_count\": 0,\n      \"average_relevance\": \"0.00\"\n    }\n  ]\n}"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 1.7
    },
    {
      "id": "ec5ec2d6-69e0-41ff-92c1-ee9757699b96",
      "name": "Google Gemini Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        176,
        -480
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "googlePalmApi": {
          "id": "",
          "name": "Google PaLM API"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "42134d4d-fb13-454f-91f6-ac119faeb0f0",
      "name": "Think",
      "type": "@n8n/n8n-nodes-langchain.toolThink",
      "position": [
        432,
        -480
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "d0c7efce-3641-4c38-b7f9-2e1c0f9b7213",
      "name": "Structured Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        944,
        -480
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"stockSymbol\": \"STOCK_TICKER\",\n  \"analysisDate\": \"DD/MM/YYYY\",\n  \"recommendationClass\": \"positive/neutral/negative\",\n  \"recommendationTitle\": \"Concise Recommendation Title in English\",\n  \"recommendationText\": \"Detailed explanation of the recommendation in English.\",\n  \"bullishCount\": 0,\n  \"neutralCount\": 0,\n  \"bearishCount\": 0,\n  \"bullishHeight\": 0,\n  \"neutralHeight\": 0,\n  \"bearishHeight\": 0,\n  \"overallSentiment\": \"Bullish/Neutral/Bearish\",\n  \"Recommendation\": \"Buy/Hold/Sell\",\n  \"sentimentScore\": 0.00,\n  \"chartImageUrl\": \"URL_PLACEHOLDER\",\n  \"technicalAnalysis\": \"<p>Detailed technical analysis in English, using p tags for paragraphs.</p>\",\n  \"topArticles\": [\n    {\n      \"title\": \"Article title in English\",\n      \"url\": \"URL of the article\",\n      \"source\": \"Source name in English\",\n      \"date\": \"DD/MM/YYYY\",\n      \"sentimentClass\": \"bullish/neutral/bearish\"\n    }\n  ],\n  \"hotTopics\": [\n    {\n      \"topic\": \"Topic name in English\",\n      \"article_count\": 0,\n      \"average_relevance\": \"0.00\"\n    }\n  ]\n}"
      },
      "typeVersion": 1.2
    },
    {
      "id": "bde55ca0-baad-494f-8c72-12d8a0fbff21",
      "name": "Technical Analysis Tool",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        688,
        -480
      ],
      "parameters": {
        "name": "technical_analysis",
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "description": "Call this tool to get an analysis of a requested stock. It'll be obligatory to pass ticker.",
        "workflowInputs": {
          "value": {
            "ticker": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('ticker', ``, 'string') }}"
          },
          "schema": [
            {
              "id": "ticker",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "ticker",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "chart_style",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "chart_style",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "typeVersion": 2
    },
    {
      "id": "edf907ca-7ff3-4452-90c2-154810c98d37",
      "name": "Trends Analysis Tool",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        560,
        -480
      ],
      "parameters": {
        "name": "trends_analysis",
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "description": "Call this tool to get an analysis of a requested stock. It'll be obligatory to pass ticker.",
        "workflowInputs": {
          "value": {
            "ticker": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('ticker', ``, 'string') }}"
          },
          "schema": [
            {
              "id": "ticker",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "ticker",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "chart_style",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "chart_style",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "typeVersion": 2
    },
    {
      "id": "97e3693b-026e-4023-8d54-2738c0b4d20e",
      "name": "Fundamental Analysis Tool",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        816,
        -480
      ],
      "parameters": {
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "description": "Call this tool to get fundamental financial analysis for a stock, including its financial health, valuation metrics, and a summary. It is obligatory to pass the stock ticker.",
        "workflowInputs": {
          "value": {
            "ticker": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('ticker', ``, 'string') }}"
          },
          "schema": [
            {
              "id": "ticker",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "ticker",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "ticker"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "name": "fundamental_analysis"
      },
      "typeVersion": 2.2
    },
    {
      "id": "9cdc3298-1423-43fe-a718-3e118f8f51d8",
      "name": "Buy?",
      "type": "n8n-nodes-base.if",
      "position": [
        1152,
        -800
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "79344dab-5dc7-433a-8c85-7a3b55f29376",
              "operator": {
                "type": "string",
                "operation": "contains"
              },
              "leftValue": "={{ $json.output.recommendationTitle }}",
              "rightValue": "Buy"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "bb127a17-aa3b-4b41-be18-bd043e581d7d",
      "name": "Buy in Alpaca",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1376,
        -800
      ],
      "parameters": {
        "url": "https://paper-api.alpaca.markets/v2/orders",
        "method": "POST",
        "options": {},
        "jsonBody": "={\n  \"symbol\": \"{{ $('AI Agent').item.json.output.stockSymbol }}\",\n  \"notional\": 7000,\n  \"side\": \"buy\",\n  \"type\": \"market\",\n  \"time_in_force\": \"day\"\n}\n",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "APCA-API-KEY-ID"
            },
            {
              "name": "APCA-API-SECRET-KEY"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth"
      },
      "typeVersion": 4.2,
      "credentials": {
        "httpHeaderAuth": {
          "id": "",
          "name": "Alpaca API Key (Header Auth)"
        }
      }
    },
    {
      "id": "ebd87901-4f65-4e16-a15e-6dd9c55cd1fd",
      "name": "Generate HTML",
      "type": "n8n-nodes-base.html",
      "position": [
        1152,
        -608
      ],
      "parameters": {
        "html": "<!DOCTYPE html>\n<html dir=\"ltr\" lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Stock Analysis of {{ $('AI Agent').item.json.output.stockSymbol }}</title>\n</head>\n<body style=\"margin: 0; padding: 0; font-family: 'Segoe UI', 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: #f5f7fa; color: #333; line-height: 1.6; -webkit-font-smoothing: antialiased; font-size: 16px; text-align: left; direction: ltr;\">\n    <!-- Main Wrapper -->\n    <div style=\"max-width: 650px; margin: 0 auto; background-color: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 24px rgba(0,0,0,0.08); margin-top: 30px; margin-bottom: 30px; text-align: left; direction: ltr;\">\n        \n        <!-- Header -->\n        <div style=\"background: linear-gradient(135deg, #0057ff 0%, #00b2ff 100%); padding: 30px 40px; text-align: center; position: relative; overflow: hidden; margin-bottom: 20px;\">\n            <div style=\"position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-image: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC93MzA9cGF0dGVybj48L2RlZnM+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0idXJsKCNwYXR0ZXJuKSIvPjwvc3ZnPg=='); opacity: 0.2;\"></div>\n            <h1 style=\"color: #ffffff; font-weight: 700; font-size: 28px; margin: 0 0 5px 0; letter-spacing: -0.5px; position: relative;\">Stock Analysis of {{ $('AI Agent').item.json.output.stockSymbol }}</h1>\n            <div style=\"color: rgba(255,255,255,0.85); font-size: 15px; position: relative;\">Date: {{ $('AI Agent').item.json.output.analysisDate }}</div>\n        </div>\n        \n        <!-- Email Content -->\n        <div style=\"padding: 40px; text-align: left; direction: ltr;\">\n            \n            <!-- Recommendation Box -->\n            <div style=\"background-color: #f8fafc; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.04); padding: 25px; margin-bottom: 40px; position: relative; overflow: hidden; text-align: left;\">\n                <div style=\"position: absolute; left: 0; top: 0; bottom: 0; width: 6px; background-color: #f7b955;\"></div>\n                <div style=\"position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: linear-gradient(90deg, rgba(247, 185, 85, 0) 50%, rgba(247, 185, 85, 0.07) 100%);\"></div>\n                <div style=\"text-align: center; position: relative;\">\n                    <div style=\"display: inline-block; width: 40px; height: 40px; border-radius: 50%; margin-bottom: 10px; background-color: rgba(247, 185, 85, 0.15); text-align: center;\">\n                        <span style=\"font-size: 20px; line-height: 40px;\">⚖️</span>\n                    </div>\n                    <h2 style=\"margin: 0 0 10px 0; color: #f7b955; font-size: 22px; font-weight: 700; text-align: center;\">{{ $('AI Agent').item.json.output.recommendationTitle }}</h2>\n                    <p style=\"margin: 0; font-size: 16px; line-height: 1.6; color: #4a5568; text-align: left;\">{{ $('AI Agent').item.json.output.recommendationText }}</p>\n                    <div style=\"margin-top: 25px;\">\n                        <a style=\"display: inline-block; background-color: #29cc7a; color: white; font-weight: 600; font-size: 16px; padding: 12px 30px; border-radius: 8px; text-decoration: none; box-shadow: 0 4px 6px rgba(41, 204, 122, 0.25); transition: all 0.2s ease;\">{{ $('AI Agent').item.json.output.Recommendation }}</a>\n                    </div>\n                </div>\n            </div>\n\n            <!-- Technical Analysis -->\n            <div style=\"margin-bottom: 40px; text-align: left;\">\n                <h2 style=\"font-size: 20px; color: #1a202c; margin: 0 0 20px 0; padding-bottom: 12px; border-bottom: 1px solid #edf2f7; font-weight: 700; text-align: left;\">Technical Analysis</h2>\n                \n                <div style=\"background: #ffffff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); overflow: hidden; margin-bottom: 25px;\">\n                    <img src=\"data:image/png;base64,{{ $('AI Agent').item.json.output.chartImageUrl }}\" alt=\"Technical Chart {{ $('AI Agent').item.json.output.stockSymbol }}\" style=\"width: 100%; display: block; max-height: 450px; object-fit: contain;\">\n                </div>\n\n                <!-- Technical Analysis Description -->\n                <!-- Technical Analysis Description -->\n              <div style=\"background-color: #f8fafc; border-radius: 12px; padding: 25px; font-size: 15px; line-height: 1.6; color: #4a5568; text-align: left;\">\n                  {{ $('AI Agent').item.json.output.technicalAnalysis }}\n              </div>\n            </div>\n            \n            <!-- Fundamental Analysis -->\n            <div style=\"margin-bottom: 40px; text-align: left;\">\n                <h2 style=\"font-size: 20px; color: #1a202c; margin: 0 0 20px 0; padding-bottom: 12px; border-bottom: 1px solid #edf2f7; font-weight: 700; text-align: left;\">Fundamental Analysis</h2>\n                \n                <div style=\"background-color: #f8fafc; border-radius: 12px; padding: 25px; font-size: 15px; line-height: 1.6; color: #4a5568; text-align: left;\">\n                    \n                    <h3 style=\"font-size: 16px; color: #1a202c; margin: 0 0 10px 0; font-weight: 600;\">Company Overview</h3>\n                    <p style=\"margin: 0 0 20px 0;\">{{ $('AI Agent').item.json.output.fundamentalAnalysis.company_overview }}</p>\n                    \n                    <h3 style=\"font-size: 16px; color: #1a202c; margin: 0 0 15px 0; font-weight: 600;\">Key Metrics</h3>\n                    <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; margin-bottom: 20px;\">\n                        <tr>\n                            <td style=\"padding: 8px; border: 1px solid #e2e8f0; background-color: #ffffff; border-radius: 8px 0 0 8px;\"><strong>Market Cap</strong></td>\n                            <td style=\"padding: 8px; border: 1px solid #e2e8f0; text-align: right;\">{{ $('AI Agent').item.json.output.fundamentalAnalysis.key_metrics.market_cap }}</td>\n                        </tr>\n                        <tr>\n                            <td style=\"padding: 8px; border: 1px solid #e2e8f0; background-color: #ffffff;\"><strong>P/E Ratio</strong></td>\n                            <td style=\"padding: 8px; border: 1px solid #e2e8f0; text-align: right;\">{{ $('AI Agent').item.json.output.fundamentalAnalysis.key_metrics.pe_ratio }}</td>\n                        </tr>\n                        <tr>\n                            <td style=\"padding: 8px; border: 1px solid #e2e8f0; background-color: #ffffff; border-radius: 0 0 0 8px;\"><strong>EPS</strong></td>\n                            <td style=\"padding: 8px; border: 1px solid #e2e8f0; text-align: right;\">{{ $('AI Agent').item.json.output.fundamentalAnalysis.key_metrics.eps }}</td>\n                        </tr>\n                    </table>\n                    \n                    <h3 style=\"font-size: 16px; color: #1a202c; margin: 0 0 10px 0; font-weight: 600;\">Financial Summary</h3>\n                    <p style=\"margin: 0;\">{{ $('AI Agent').item.json.output.fundamentalAnalysis.financial_summary }}</p>\n                    \n                </div>\n            </div>\n          \n            <!-- Market Sentiment Analysis -->\n            <div style=\"margin-bottom: 40px; text-align: left;\">\n                <h2 style=\"font-size: 20px; color: #1a202c; margin: 0 0 20px 0; padding-bottom: 12px; border-bottom: 1px solid #edf2f7; font-weight: 700; text-align: left;\">Market Sentiment Analysis</h2>\n                \n                <!-- Sentiment Chart - using table instead of flex -->\n                <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; margin: 45px 0 30px 0;\">\n                    <tr valign=\"bottom\" align=\"center\">\n                        <td width=\"33%\" style=\"text-align: center; padding: 0 10px;\">\n                            <div style=\"font-weight: 600; margin-bottom: 10px; color: #29cc7a;\">{{ $('AI Agent').item.json.output.bullishCount }}</div>\n                            <div style=\"background-color: #29cc7a; border-radius: 8px 8px 0 0; width: 100%; height: {{ $('AI Agent').item.json.output.bullishHeight }}px; margin: 0 auto; opacity: 0.85;\"></div>\n                            <div style=\"font-size: 14px; color: #4a5568; margin-top: 10px;\">Bullish</div>\n                        </td>\n                        <td width=\"33%\" style=\"text-align: center; padding: 0 10px;\">\n                            <div style=\"font-weight: 600; margin-bottom: 10px; color: #f7b955;\">{{ $('AI Agent').item.json.output.neutralCount }}</div>\n                            <div style=\"background-color: #f7b955; border-radius: 8px 8px 0 0; width: 100%; height: {{ $('AI Agent').item.json.output.neutralHeight }}px; margin: 0 auto; opacity: 0.85;\"></div>\n                            <div style=\"font-size: 14px; color: #4a5568; margin-top: 10px;\">Neutral</div>\n                        </td>\n                        <td width=\"33%\" style=\"text-align: center; padding: 0 10px;\">\n                            <div style=\"font-weight: 600; margin-bottom: 10px; color: #f55e5e;\">{{ $('AI Agent').item.json.output.bearishCount }}</div>\n                            <div style=\"background-color: #f55e5e; border-radius: 8px 8px 0 0; width: 100%; height: {{ $('AI Agent').item.json.output.bearishHeight }}px; margin: 0 auto; opacity: 0.85;\"></div>\n                            <div style=\"font-size: 14px; color: #4a5568; margin-top: 10px;\">Bearish</div>\n                        </td>\n                    </tr>\n                </table>\n                \n                <div style=\"background-color: #f8fafc; border-radius: 10px; padding: 15px; text-align: center; font-size: 15px;\">\n                    The overall sentiment for <strong>{{ $('AI Agent').item.json.output.stockSymbol }}</strong> is \n                    <span style=\"font-weight: 600; color: #f7b955;\">{{ $('AI Agent').item.json.output.overallSentiment }}</span> \n                    with a score of <strong>{{ $('AI Agent').item.json.output.sentimentScore }}</strong>\n                </div>\n            </div>\n            \n            <!-- Influential Articles -->\n            <div style=\"margin-bottom: 40px; text-align: left;\">\n                <h2 style=\"font-size: 20px; color: #1a202c; margin: 0 0 20px 0; padding-bottom: 12px; border-bottom: 1px solid #edf2f7; font-weight: 700; text-align: left;\">Influential Articles</h2>\n                \n                <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse;\">\n                    <!-- Article 1 -->\n                    <tr>\n                        <td style=\"padding-bottom: 16px;\">\n                            <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; background-color: #f8fafc; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden;\">\n                                <tr>\n                                    <td width=\"4\" style=\"background-color: #f7b955;\"></td>\n                                    <td style=\"padding: 18px 22px;\">\n                                        <h3 style=\"margin: 0 0 8px 0; font-size: 16px; font-weight: 600; line-height: 1.4; text-align: left;\">\n                                            <a href=\"{{ $('AI Agent').item.json.output.topArticles[0].url }}\" target=\"_blank\" style=\"color: #2b6cb0; text-decoration: none;\">{{ $('AI Agent').item.json.output.topArticles[0].title }}</a>\n                                        </h3>\n                                        <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; margin-top: 10px;\">\n                                            <tr>\n                                                <td style=\"font-size: 13px; color: #718096; text-align: left;\">{{ $('AI Agent').item.json.output.topArticles[0].source }} | {{ $('AI Agent').item.json.output.topArticles[0].date }}</td>\n                                                <td style=\"text-align: right;\">\n                                                    <div style=\"display: inline-block; padding: 3px 10px; border-radius: 30px; font-weight: 500; font-size: 12px; background-color: rgba(247, 185, 85, 0.1); color: #f7b955;\">\n                                                        {{ $('AI Agent').item.json.output.topArticles[0].sentimentClass }}\n                                                    </div>\n                                                </td>\n                                            </tr>\n                                        </table>\n                                    </td>\n                                </tr>\n                            </table>\n                        </td>\n                    </tr>\n                    \n                    <!-- Article 2 -->\n                    <tr>\n                        <td style=\"padding-bottom: 16px;\">\n                            <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; background-color: #f8fafc; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden;\">\n                                <tr>\n                                    <td width=\"4\" style=\"background-color: #f7b955;\"></td>\n                                    <td style=\"padding: 18px 22px;\">\n                                        <h3 style=\"margin: 0 0 8px 0; font-size: 16px; font-weight: 600; line-height: 1.4; text-align: left;\">\n                                            <a href=\"{{ $('AI Agent').item.json.output.topArticles[1].url }}\" target=\"_blank\" style=\"color: #2b6cb0; text-decoration: none;\">{{ $('AI Agent').item.json.output.topArticles[1].title }}</a>\n                                        </h3>\n                                        <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; margin-top: 10px;\">\n                                            <tr>\n                                                <td style=\"font-size: 13px; color: #718096; text-align: left;\">{{ $('AI Agent').item.json.output.topArticles[1].source }} | {{ $('AI Agent').item.json.output.topArticles[1].date }}</td>\n                                                <td style=\"text-align: right;\">\n                                                    <div style=\"display: inline-block; padding: 3px 10px; border-radius: 30px; font-weight: 500; font-size: 12px; background-color: rgba(247, 185, 85, 0.1); color: #f7b955;\">\n                                                        {{ $('AI Agent').item.json.output.topArticles[1].sentimentClass }}\n                                                    </div>\n                                                </td>\n                                            </tr>\n                                        </table>\n                                    </td>\n                                </tr>\n                            </table>\n                        </td>\n                    </tr>\n                    \n                    <!-- Article 3 -->\n                    <tr>\n                        <td style=\"padding-bottom: 16px;\">\n                            <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; background-color: #f8fafc; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden;\">\n                                <tr>\n                                    <td width=\"4\" style=\"background-color: #f7b955;\"></td>\n                                    <td style=\"padding: 18px 22px;\">\n                                        <h3 style=\"margin: 0 0 8px 0; font-size: 16px; font-weight: 600; line-height: 1.4; text-align: left;\">\n                                            <a href=\"{{ $('AI Agent').item.json.output.topArticles[2].url }}\" target=\"_blank\" style=\"color: #2b6cb0; text-decoration: none;\">{{ $('AI Agent').item.json.output.topArticles[2].title }}</a>\n                                        </h3>\n                                        <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; margin-top: 10px;\">\n                                            <tr>\n                                                <td style=\"font-size: 13px; color: #718096; text-align: left;\">{{ $('AI Agent').item.json.output.topArticles[2].source }} | {{ $('AI Agent').item.json.output.topArticles[2].date }}</td>\n                                                <td style=\"text-align: right;\">\n                                                    <div style=\"display: inline-block; padding: 3px 10px; border-radius: 30px; font-weight: 500; font-size: 12px; background-color: rgba(247, 185, 85, 0.1); color: #f7b955;\">\n                                                        {{ $('AI Agent').item.json.output.topArticles[2].sentimentClass }}\n                                                    </div>\n                                                </td>\n                                            </tr>\n                                        </table>\n                                    </td>\n                                </tr>\n                            </table>\n                        </td>\n                    </tr>\n                    \n                    <!-- Article 4 -->\n                    <tr>\n                        <td style=\"padding-bottom: 16px;\">\n                            <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; background-color: #f8fafc; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden;\">\n                                <tr>\n                                    <td width=\"4\" style=\"background-color: #f7b955;\"></td>\n                                    <td style=\"padding: 18px 22px;\">\n                                        <h3 style=\"margin: 0 0 8px 0; font-size: 16px; font-weight: 600; line-height: 1.4; text-align: left;\">\n                                            <a href=\"{{ $('AI Agent').item.json.output.topArticles[3].url }}\" target=\"_blank\" style=\"color: #2b6cb0; text-decoration: none;\">{{ $('AI Agent').item.json.output.topArticles[3].title }}</a>\n                                        </h3>\n                                        <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; margin-top: 10px;\">\n                                            <tr>\n                                                <td style=\"font-size: 13px; color: #718096; text-align: left;\">{{ $('AI Agent').item.json.output.topArticles[3].source }} | {{ $('AI Agent').item.json.output.topArticles[3].date }}</td>\n                                                <td style=\"text-align: right;\">\n                                                    <div style=\"display: inline-block; padding: 3px 10px; border-radius: 30px; font-weight: 500; font-size: 12px; background-color: rgba(247, 185, 85, 0.1); color: #f7b955;\">\n                                                        {{ $('AI Agent').item.json.output.topArticles[3].sentimentClass }}\n                                                    </div>\n                                                </td>\n                                            </tr>\n                                        </table>\n                                    </td>\n                                </tr>\n                            </table>\n                        </td>\n                    </tr>\n                    \n                    <!-- Article 5 -->\n                    <tr>\n                        <td style=\"padding-bottom: 16px;\">\n                            <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; background-color: #f8fafc; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden;\">\n                                <tr>\n                                    <td width=\"4\" style=\"background-color: #f7b955;\"></td>\n                                    <td style=\"padding: 18px 22px;\">\n                                        <h3 style=\"margin: 0 0 8px 0; font-size: 16px; font-weight: 600; line-height: 1.4; text-align: left;\">\n                                            <a href=\"{{ $('AI Agent').item.json.output.topArticles[4].url }}\" target=\"_blank\" style=\"color: #2b6cb0; text-decoration: none;\">{{ $('AI Agent').item.json.output.topArticles[4].title }}</a>\n                                        </h3>\n                                        <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"border-collapse: collapse; margin-top: 10px;\">\n                                            <tr>\n                                                <td style=\"font-size: 13px; color: #718096; text-align: left;\">{{ $('AI Agent').item.json.output.topArticles[4].source }} | {{ $('AI Agent').item.json.output.topArticles[4].date }}</td>\n                                                <td style=\"text-align: right;\">\n                                                    <div style=\"display: inline-block; padding: 3px 10px; border-radius: 30px; font-weight: 500; font-size: 12px; background-color: rgba(247, 185, 85, 0.1); color: #f7b955;\">\n                                                        {{ $('AI Agent').item.json.output.topArticles[4].sentimentClass }}\n                                                    </div>\n                                                </td>\n                                            </tr>\n                                        </table>\n                                    </td>\n                                </tr>\n                            </table>\n                        </td>\n                    </tr>\n                </table>\n            </div>\n              \n    <!-- Hot Topics - improved mobile version -->\n    <div style=\"margin-bottom: 30px; text-align: left;\">\n        <h2 style=\"font-size: 20px; color: #1a202c; margin: 0 0 20px 0; padding-bottom: 12px; border-bottom: 1px solid #edf2f7; font-weight: 700; text-align: left;\">Hot Topics</h2>\n        \n        <div style=\"background-color: #f8fafc; border-radius: 12px; padding: 20px 25px; text-align: left;\">\n            <p style=\"margin: 0 0 15px 0; font-size: 15px; color: #4a5568; text-align: left;\">The main topics appearing in the news for {{ $('AI Agent').item.json.output.stockSymbol }}:</p>\n            \n            <!-- Topic 1 -->\n            <div style=\"margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #edf2f7;\">\n                <div style=\"display: table; width: 100%; margin-bottom: 8px;\">\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: left; font-weight: 600; font-size: 15px;\">\n                        {{ $('AI Agent').item.json.output.hotTopics[0].topic }}\n                    </div>\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: right; white-space: nowrap;\">\n                        <div style=\"display: inline-block; background-color: #edf2f7; border-radius: 30px; padding: 4px 12px; font-size: 13px; color: #4a5568; text-align: center;\">\n                            <strong>{{ $('AI Agent').item.json.output.hotTopics[0].article_count }}</strong> articles\n                        </div>\n                    </div>\n                </div>\n                <div style=\"background-color: #e2e8f0; height: 4px; width: 100%; border-radius: 2px; overflow: hidden;\">\n                    <div style=\"background-color: #4299e1; height: 100%; width: calc({{ $('AI Agent').item.json.output.hotTopics[0].average_relevance }} * 100%);\"></div>\n                </div>\n                <div style=\"text-align: right; font-size: 12px; color: #718096; margin-top: 4px;\">Relevance: {{ $('AI Agent').item.json.output.hotTopics[0].average_relevance }}</div>\n            </div>\n            \n            <!-- Topic 2 -->\n            <div style=\"margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #edf2f7;\">\n                <div style=\"display: table; width: 100%; margin-bottom: 8px;\">\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: left; font-weight: 600; font-size: 15px;\">\n                        {{ $('AI Agent').item.json.output.hotTopics[1].topic }}\n                    </div>\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: right; white-space: nowrap;\">\n                        <div style=\"display: inline-block; background-color: #edf2f7; border-radius: 30px; padding: 4px 12px; font-size: 13px; color: #4a5568; text-align: center;\">\n                            <strong>{{ $('AI Agent').item.json.output.hotTopics[1].article_count }}</strong> articles\n                        </div>\n                    </div>\n                </div>\n                <div style=\"background-color: #e2e8f0; height: 4px; width: 100%; border-radius: 2px; overflow: hidden;\">\n                    <div style=\"background-color: #4299e1; height: 100%; width: calc({{ $('AI Agent').item.json.output.hotTopics[1].average_relevance }} * 100%);\"></div>\n                </div>\n                <div style=\"text-align: right; font-size: 12px; color: #718096; margin-top: 4px;\">Relevance: {{ $('AI Agent').item.json.output.hotTopics[1].average_relevance }}</div>\n            </div>\n            \n            <!-- Topic 3 -->\n            <div style=\"margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #edf2f7;\">\n                <div style=\"display: table; width: 100%; margin-bottom: 8px;\">\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: left; font-weight: 600; font-size: 15px;\">\n                        {{ $('AI Agent').item.json.output.hotTopics[2].topic }}\n                    </div>\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: right; white-space: nowrap;\">\n                        <div style=\"display: inline-block; background-color: #edf2f7; border-radius: 30px; padding: 4px 12px; font-size: 13px; color: #4a5568; text-align: center;\">\n                            <strong>{{ $('AI Agent').item.json.output.hotTopics[2].article_count }}</strong> articles\n                        </div>\n                    </div>\n                </div>\n                <div style=\"background-color: #e2e8f0; height: 4px; width: 100%; border-radius: 2px; overflow: hidden;\">\n                    <div style=\"background-color: #4299e1; height: 100%; width: calc({{ $('AI Agent').item.json.output.hotTopics[2].average_relevance }} * 100%);\"></div>\n                </div>\n                <div style=\"text-align: right; font-size: 12px; color: #718096; margin-top: 4px;\">Relevance: {{ $('AI Agent').item.json.output.hotTopics[2].average_relevance }}</div>\n            </div>\n            \n            <!-- Topic 4 -->\n            <div style=\"margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #edf2f7;\">\n                <div style=\"display: table; width: 100%; margin-bottom: 8px;\">\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: left; font-weight: 600; font-size: 15px;\">\n                        {{ $('AI Agent').item.json.output.hotTopics[3].topic }}\n                    </div>\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: right; white-space: nowrap;\">\n                        <div style=\"display: inline-block; background-color: #edf2f7; border-radius: 30px; padding: 4px 12px; font-size: 13px; color: #4a5568; text-align: center;\">\n                            <strong>{{ $('AI Agent').item.json.output.hotTopics[3].article_count }}</strong> articles\n                        </div>\n                    </div>\n                </div>\n                <div style=\"background-color: #e2e8f0; height: 4px; width: 100%; border-radius: 2px; overflow: hidden;\">\n                    <div style=\"background-color: #4299e1; height: 100%; width: calc({{ $('AI Agent').item.json.output.hotTopics[3].average_relevance }} * 100%);\"></div>\n                </div>\n                <div style=\"text-align: right; font-size: 12px; color: #718096; margin-top: 4px;\">Relevance: {{ $('AI Agent').item.json.output.hotTopics[3].average_relevance }}</div>\n            </div>\n            \n            <!-- Topic 5 -->\n            <div style=\"margin-bottom: 0;\">\n                <div style=\"display: table; width: 100%; margin-bottom: 8px;\">\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: left; font-weight: 600; font-size: 15px;\">\n                        {{ $('AI Agent').item.json.output.hotTopics[4].topic }}\n                    </div>\n                    <div style=\"display: table-cell; vertical-align: middle; text-align: right; white-space: nowrap;\">\n                        <div style=\"display: inline-block; background-color: #edf2f7; border-radius: 30px; padding: 4px 12px; font-size: 13px; color: #4a5568; text-align: center;\">\n                            <strong>{{ $('AI Agent').item.json.output.hotTopics[4].article_count }}</strong> articles\n                        </div>\n                    </div>\n                </div>\n                <div style=\"background-color: #e2e8f0; height: 4px; width: 100%; border-radius: 2px; overflow: hidden;\">\n                    <div style=\"background-color: #4299e1; height: 100%; width: calc({{ $('AI Agent').item.json.output.hotTopics[4].average_relevance }} * 100%);\"></div>\n                </div>\n                <div style=\"text-align: right; font-size: 12px; color: #718096; margin-top: 4px;\">Relevance: {{ $('AI Agent').item.json.output.hotTopics[4].average_relevance }}</div>\n            </div>\n        </div>\n    </div>\n\t        \n        <!-- Footer -->\n        <div style=\"background-color: #f8fafc; padding: 25px 40px; text-align: center; border-top: 1px solid #edf2f7;\">\n            <div style=\"font-size: 13px; color: #718096; line-height: 1.6;\">\n                <p style=\"margin: 0 0 8px 0;\">This report is automatically generated and does not constitute investment recommendation.</p>\n                <p style=\"margin: 0;\">A licensed investment advisor should be consulted before making investment decisions.</p>\n            </div>\n        </div>\n        \n    </div>\n\n</body>\n</html>"
      },
      "typeVersion": 1.2
    },
    {
      "id": "dad97867-79a3-4c28-b139-33ef036264c1",
      "name": "Adjust HTML Colors",
      "type": "n8n-nodes-base.code",
      "position": [
        1376,
        -608
      ],
      "parameters": {
        "jsCode": "// New function to remove topics with only one article - ultra-simple approach\nfunction removeSingleArticleTopics(html) {\n  // First, see if there are any topics with exactly 1 article\n  if (!html.includes('<strong>1</strong> articles')) {\n    console.log('No topics with 1 article found');\n    return html;\n  }\n\n  // Find each line that contains the \"Topic\" comment\n  // and check if it has exactly 1 article mentioned\n  const lines = html.split('\\n');\n  const linesToRemove = [];\n\n  // For each line containing \"1 articles\", find the topic it belongs to\n  for (let i = 0; i < lines.length; i++) {\n    if (lines[i].includes('<strong>1</strong> articles')) {\n      console.log(`Found line ${i} with 1 article mention`);\n\n      // Go back to find the start of this topic\n      let startLine = -1;\n      for (let j = i; j >= 0; j--) {\n        if (lines[j].includes('<!-- Topic') ||\n            lines[j].includes('<div style=\"margin-bottom: 15px; padding-bottom: 15px; border-bottom:')) {\n          startLine = j;\n          break;\n        }\n      }\n\n      if (startLine === -1) {\n        console.log(`Couldn't find start of topic for line ${i}`);\n        continue;\n      }\n\n      // Go forward to find the end of this topic\n      let endLine = -1;\n      let divCount = 0;\n      for (let j = startLine; j < lines.length; j++) {\n        // Count opening divs\n        const openMatches = lines[j].match(/<div/g);\n        if (openMatches) {\n          divCount += openMatches.length;\n        }\n\n        // Count closing divs\n        const closeMatches = lines[j].match(/<\\/div>/g);\n        if (closeMatches) {\n          divCount -= closeMatches.length;\n        }\n\n        // When divCount returns to 0, we've found the end\n        if (divCount === 0 && j > startLine) {\n          endLine = j;\n          break;\n        }\n      }\n\n      if (endLine === -1) {\n        console.log(`Couldn't find end of topic for line ${i}`);\n        continue;\n      }\n\n      // Now we have the start and end lines of the topic\n      console.log(`Found topic from line ${startLine} to ${endLine}`);\n\n      // Mark these lines for removal\n      for (let j = startLine; j <= endLine; j++) {\n        linesToRemove.push(j);\n      }\n    }\n  }\n\n  // Remove the marked lines\n  const newLines = [];\n  for (let i = 0; i < lines.length; i++) {\n    if (!linesToRemove.includes(i)) {\n      newLines.push(lines[i]);\n    }\n  }\n\n  console.log(`Removed ${linesToRemove.length} lines in total`);\n  return newLines.join('\\n');\n}\n\n// Code for updating colors according to sentiment - for n8n\n\n// Define colors by sentiment type\nconst colors = {\n  positive: {\n    main: '#29cc7a',          // Green\n    background: 'rgba(41, 204, 122, 0.15)',\n    gradient: 'rgba(41, 204, 122, 0.07)',\n    accent: 'rgba(41, 204, 122, 0.1)'\n  },\n  neutral: {\n    main: '#f7b955',          // Orange\n    background: 'rgba(247, 185, 85, 0.15)',\n    gradient: 'rgba(247, 185, 85, 0.07)',\n    accent: 'rgba(247, 185, 85, 0.1)'\n  },\n  negative: {\n    main: '#f55e5e',          // Red\n    background: 'rgba(245, 94, 94, 0.15)',\n    gradient: 'rgba(245, 94, 94, 0.07)',\n    accent: 'rgba(245, 94, 94, 0.1)'\n  }\n};\n\n// Function to identify sentiment type from text (based on Alpha Vantage labels or AI recommendation)\nfunction getSentimentType(text) {\n  if (!text) return 'neutral';\n\n  const lowerText = text.toLowerCase();\n\n  // Primary checks for overall categories\n  if (lowerText.includes('very bearish') || lowerText.includes('somewhat-bearish') || lowerText.includes('bearish') || lowerText.includes('negative') || lowerText.includes('sell')) {\n    return 'negative';\n  }\n\n  if (lowerText.includes('very bullish') || lowerText.includes('somewhat-bullish') || lowerText.includes('bullish') || lowerText.includes('positive') || lowerText.includes('buy')) {\n    return 'positive';\n  }\n\n  // Default to neutral for \"neutral\" or \"hold\"\n  return 'neutral';\n}\n\n// Function to check if a specific text belongs to a sentiment - used for bug fixing\nfunction debugSentiment(text) {\n  console.log(`Sentiment check: \"${text}\" => ${getSentimentType(text)}`);\n}\n\n// New function to remove undefined articles from HTML\nfunction removeUndefinedArticles(html) {\n  // Find all article blocks\n  const articleBlocksRegex = /<tr>\\s*<td style=\"padding-bottom: 16px;\">\\s*<table[^>]*>[\\s\\S]*?<\\/table>\\s*<\\/td>\\s*<\\/tr>/g;\n  const articleBlocks = Array.from(html.matchAll(articleBlocksRegex));\n\n  // No articles found\n  if (!articleBlocks || articleBlocks.length === 0) {\n    console.log(\"No article blocks found\");\n    return html;\n  }\n\n  // Function to check if an article is fully undefined\n  function isFullyUndefinedArticle(articleHtml) {\n    // An article is considered fully undefined if:\n    // 1. It has href=\"undefined\"\n    // 2. It has link text that is \"undefined\"\n    // 3. It has \"undefined | undefined\" (source and date)\n    return articleHtml.includes('href=\"undefined\"') &&\n           articleHtml.includes('>undefined</a>') &&\n           articleHtml.includes('undefined | undefined');\n  }\n\n  // Identify blocks to remove\n  const blocksToRemove = [];\n  for (const match of articleBlocks) {\n    const block = match[0];\n    if (isFullyUndefinedArticle(block)) {\n      console.log(\"Found undefined article, will remove\");\n      blocksToRemove.push(match);\n    } else {\n      console.log(\"Found valid article, keeping it\");\n    }\n  }\n\n  // If no blocks to remove, return original HTML\n  if (blocksToRemove.length === 0) {\n    console.log(\"No undefined articles found to remove\");\n    return html;\n  }\n\n  console.log(`Found ${blocksToRemove.length} undefined articles to remove`);\n\n  // Create a new string by removing the matches from end to start (to avoid index shifting)\n  let cleanedHtml = html;\n  for (let i = blocksToRemove.length - 1; i >= 0; i--) {\n    const match = blocksToRemove[i];\n    cleanedHtml = cleanedHtml.slice(0, match.index) + cleanedHtml.slice(match.index + match[0].length);\n  }\n\n  return cleanedHtml;\n}\n\n// Get the HTML from the specified parameter\nconst html = $input.first().json.html;\nlet updatedHtml = html;\n\n// Debug checks - check several keywords that might appear\n// These are for testing the `getSentimentType` function during development.\n// They can be removed in a production environment.\ndebugSentiment(\"Bullish\");\ndebugSentiment(\"Bearish\");\ndebugSentiment(\"Neutral\");\ndebugSentiment(\"Very Bullish\");\ndebugSentiment(\"Very Bearish\");\ndebugSentiment(\"Somewhat-Bullish\");\ndebugSentiment(\"Somewhat-Bearish\");\ndebugSentiment(\"Buy\");\ndebugSentiment(\"Sell\");\ndebugSentiment(\"Hold\");\n\n\n// 1. Update colors in the recommendation title\nconst titleMatch = html.match(/<h2 style=\"[^\"]*color: #[a-f0-9]+;[^\"]*\">([^<]+)<\\/h2>/i);\nif (titleMatch) {\n  const titleText = titleMatch[1].trim();\n  const titleSentiment = getSentimentType(titleText);\n\n  // Update title color\n  updatedHtml = updatedHtml.replace(\n    /(<h2 style=\"[^\"]*color: )#[a-f0-9]+(;[^\"]*\">)/i,\n    `$1${colors[titleSentiment].main}$2`\n  );\n\n  // Update side bar color\n  updatedHtml = updatedHtml.replace(\n    /(<div style=\"position: absolute; right: 0; top: 0; bottom: 0; width: 6px; background-color: )#[a-f0-9]+(;\"><\\/div>)/i,\n    `$1${colors[titleSentiment].main}$2`\n  );\n\n  // Update gradient color\n  updatedHtml = updatedHtml.replace(\n    /(<div style=\"position: absolute; right: 0; top: 0; width: 100%; height: 100%; background: linear-gradient\\(90deg, )rgba\\([^)]+\\)( 0%, )rgba\\([^)]+\\)( 50%\\);\"><\\/div>)/i,\n    `$1${colors[titleSentiment].gradient}$2${colors[titleSentiment].gradient.replace('0.07', '0')}$3`\n  );\n\n  // Update icon background color\n  updatedHtml = updatedHtml.replace(\n    /(<div style=\"display: inline-block; width: 40px; height: 40px; border-radius: 50%; margin-bottom: 10px; background-color: )rgba\\([^)]+\\)(; text-align: center;\">)/i,\n    `$1${colors[titleSentiment].background}$2`\n  );\n}\n\n// 2. Update overall sentiment color\nconst sentimentMatch = updatedHtml.match(/<span style=\"[^\"]*font-weight: 600; color: #[a-f0-9]+;[^\"]*\">([^<]+)<\\/span>/i);\nif (sentimentMatch) {\n  const sentimentText = sentimentMatch[1].trim();\n  const sentimentType = getSentimentType(sentimentText);\n\n  updatedHtml = updatedHtml.replace(\n    /(<span style=\"[^\"]*font-weight: 600; color: )#[a-f0-9]+(;[^\"]*\">)/i,\n    `$1${colors[sentimentType].main}$2`\n  );\n}\n\n// 3. Update article colors\nconst articleBlocks = updatedHtml.match(/<tr>\\s*<td style=\"padding-bottom: 16px;\">\\s*<table[^>]*>[\\s\\S]*?<\\/table>\\s*<\\/td>\\s*<\\/tr>/g);\nif (articleBlocks) {\n  for (const block of articleBlocks) {\n    // Check if this is a fully undefined article before skipping\n    const isUndefined = block.includes('href=\"undefined\"') &&\n                        block.includes('>undefined</a>') &&\n                        block.includes('undefined | undefined');\n\n    // Skip if this is a completely undefined article\n    if (isUndefined) {\n      console.log(\"Skipping color update for undefined article\");\n      continue;\n    }\n\n    // Find sentiment within the block\n    const articleSentimentMatch = block.match(/<div style=\"[^\"]*padding: 3px 10px;[^\"]*\">([^<]+)<\\/div>/i);\n    if (articleSentimentMatch) {\n      const articleSentimentText = articleSentimentMatch[1].trim();\n      const articleSentimentType = getSentimentType(articleSentimentText);\n\n      // Debug check - log the identified sentiment\n      debugSentiment(articleSentimentText);\n\n      // Create updated block\n      let updatedBlock = block;\n\n      // Update side line color\n      updatedBlock = updatedBlock.replace(\n        /(<td width=\"4\" style=\"background-color: )#[a-f0-9]+(;\"><\\/td>)/i,\n        `$1${colors[articleSentimentType].main}$2`\n      );\n\n      // Update sentiment tag colors (background and text color)\n      updatedBlock = updatedBlock.replace(\n        /(<div style=\"[^\"]*background-color: )rgba\\([^)]+\\)(; color: )#[a-f0-9]+(;[^\"]*\">)/i,\n        `$1${colors[articleSentimentType].accent}$2${colors[articleSentimentType].main}$3`\n      );\n\n      // Replace the block with its updated version\n      updatedHtml = updatedHtml.replace(block, updatedBlock);\n    }\n  }\n}\n\n// 4. Update recommendation button color\nconst buttonMatch = updatedHtml.match(/<a style=\"[^\"]*background-color: #[a-f0-9]+;[^\"]*\">([^<]+)<\\/a>/i);\nif (buttonMatch) {\n  const buttonText = buttonMatch[1].trim();\n  let buttonSentiment = 'neutral'; // Default\n\n  // Determine sentiment based on button text (from AI's \"Recommendation\" field)\n  if (buttonText.includes(\"Buy\")) {\n    buttonSentiment = 'positive';\n  } else if (buttonText.includes(\"Sell\")) {\n    buttonSentiment = 'negative';\n  } else if (buttonText.includes(\"Hold\")) {\n    buttonSentiment = 'neutral';\n  }\n\n  // Update button background color\n  updatedHtml = updatedHtml.replace(\n    /(<a style=\"[^\"]*background-color: )#[a-f0-9]+(;[^\"]*\">)/i,\n    `$1${colors[buttonSentiment].main}$2`\n  );\n\n  // Update box-shadow color\n  const boxShadowRgba = `rgba(${parseInt(colors[buttonSentiment].main.substring(1, 3), 16)}, ${parseInt(colors[buttonSentiment].main.substring(3, 5), 16)}, ${parseInt(colors[buttonSentiment].main.substring(5, 7), 16)}, 0.25)`;\n  updatedHtml = updatedHtml.replace(\n    /(box-shadow: 0 4px 6px )rgba\\([^)]+\\)(;[^\"]*\">)/i,\n    `$1${boxShadowRgba}$2`\n  );\n}\n\n// 5. Remove undefined articles\nupdatedHtml = removeUndefinedArticles(updatedHtml);\n\n// 6. Remove topics with only one article\nupdatedHtml = removeSingleArticleTopics(updatedHtml);\n\n// Return updated HTML\nreturn { html: updatedHtml };"
      },
      "typeVersion": 2
    },
    {
      "id": "c8000caf-7568-48e5-b6e7-108243ffadb8",
      "name": "Send Stock Analysis",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        1600,
        -608
      ],
      "webhookId": "c51bf6f0-ab45-418f-b16e-d84ebe6a960d",
      "parameters": {
        "html": "={{ $json.html }}",
        "options": {},
        "subject": "=Review of {{ $('AI Agent').item.json.output.stockSymbol }}: {{ $('AI Agent').item.json.output.analysisDate }}",
        "toEmail": "=PASTE_YOUR_EMAIL_HERE",
        "fromEmail": "=PASTE_YOUR_EMAIL_HERE"
      },
      "credentials": {
        "smtp": {
          "id": "",
          "name": "SMTP"
        }
      },
      "executeOnce": false,
      "typeVersion": 2.1
    },
    {
      "id": "bcd124b8-96c3-408c-ad25-d8d77d4e00de",
      "name": "Window Buffer Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        304,
        -480
      ],
      "parameters": {
        "sessionKey": "=335458847",
        "sessionIdType": "customKey"
      },
      "typeVersion": 1.3
    }
  ],
  "connections": {
    "If": {
      "main": [
        [
          {
            "node": "Wait",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buy?": {
      "main": [
        [
          {
            "node": "Buy in Alpaca",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Think": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Buy?",
            "type": "main",
            "index": 0
          },
          {
            "node": "Generate HTML",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Out": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Stock List": {
      "main": [
        [
          {
            "node": "Split Out",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate HTML": {
      "main": [
        [
          {
            "node": "Adjust HTML Colors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [
          {
            "node": "Set Ticker for AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute Workflow": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Stock List",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Adjust HTML Colors": {
      "main": [
        [
          {
            "node": "Send Stock Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "On form submission": {
      "main": [
        [
          {
            "node": "Set Ticker for AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trends Analysis Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Window Buffer Memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Set Ticker for AI Agent": {
      "main": [
        [
          {
            "node": "Execute Workflow",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Technical Analysis Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "AI Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Fundamental Analysis Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "When Executed by Another Workflow": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  }
}