{
  "id": "YtPhfFCx9D9Eq9zi",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Tesla Quant Trading AI Agent n8n",
  "tags": [],
  "nodes": [
    {
      "id": "8677aed4-a1bf-4439-8b5e-57c283f81862",
      "name": "Telegram Trigger",
      "type": "n8n-nodes-base.telegramTrigger",
      "position": [
        -560,
        -100
      ],
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "fddcfaab-f575-4e72-b3f1-e0965e3c71b5",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        140,
        260
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "f6e5726a-1010-4a55-9d54-f6889eb780e1",
      "name": "Telegram",
      "type": "n8n-nodes-base.telegram",
      "position": [
        1380,
        -100
      ],
      "parameters": {
        "text": "={{ $json.message }}",
        "chatId": "={{ $('Telegram Trigger').item.json.message.chat.id }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "62f3f30c-47e4-4c86-828b-3ab4de28e6c3",
      "name": "User Authentication (Replace Telegram ID)",
      "type": "n8n-nodes-base.code",
      "position": [
        -300,
        -100
      ],
      "parameters": {
        "jsCode": "if ($input.first().json.message.from.id !== <<replace your ID here>>) { // Replace with your actual ID\n  return {unauthorized: true};\n} else {\n  // Return the original data when authorized\n  return $input.all();\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "5a79ae5f-583d-41a0-9055-914de6eaf341",
      "name": "Tesla Quant Trading AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        520,
        -100
      ],
      "parameters": {
        "text": "={{ $('Telegram Trigger').item.json.message.text }}",
        "options": {
          "systemMessage": "You are the **Tesla Quant Trading AI Agent**, responsible for generating structured, professional swing-trading reports for **TSLA** based on both **real-time technical analysis** and **curated sentiment data**.\n\n---\n\n### \ud83d\udd17 Connected Tools:\n\n1. **Tesla Financial Market Data Analyst Tool**  \n   - Aggregates multi-timeframe indicators + candlestick signals from:\n     \u2022 Tesla 15min Indicators Tool  \n     \u2022 Tesla 1h Indicators Tool  \n     \u2022 Tesla 1d Indicators Tool  \n     \u2022 Tesla Klines Tool (1h & 1d pattern/volume)  \n   - Uses Alpha Vantage indicators: **RSI, BBANDS, SMA, EMA, ADX, MACD**  \n   - Each tool returns the **20 most recent points**, cleaned and trimmed  \n   - Pattern logic: detects **Doji, Engulfing**, and **volume divergence**\n\n2. **Tesla News and Sentiment Analyst Tool**  \n   - Scrapes from trusted RSS sources: **Google News, Yahoo Finance, Electrek, CleanTechnica, TeslaNorth**  \n   - Returns:  \n     \u2022 **Sentiment score**: Bullish / Bearish / Neutral  \n     \u2022 **Summary**: 2\u20133 sentence narrative  \n     \u2022 **Top 3\u20135 Headlines** (with sources)\n\n---\n\n### \ud83d\udcca Responsibilities:\n\n1. **Ingest structured inputs** from the tools listed above:\n   - Indicator values and candlestick/volume behavior  \n   - News sentiment summaries and headlines\n\n2. **Perform technical analysis** across timeframes:\n   - **Short-Term**: 15m + 1h  \n   - **Long-Term**: 1d + 1h  \n   - Assess trend, support/resistance, divergence, and reversal signals  \n   - Confirm with lagging indicators and macro sentiment alignment\n\n3. **Generate two trade strategy sections**:\n\n<b>Spot Recommendations</b>  \n\u2022 Action: Buy / Sell / Hold  \n\u2022 Entry Price  \n\u2022 Stop Loss  \n\u2022 Take Profit  \n\u2022 Rationale:  \n\u2003- <b>Primary Signals</b>: e.g. candle pattern, breakout  \n\u2003- <b>Lagging Indicators</b>: RSI, BBANDS, etc.  \n\u2003- <b>Sentiment & Macro Analysis</b>: use news summary + headlines\n\n<b>Leveraged Recommendations</b>  \n\u2022 Position: Long / Short  \n\u2022 Leverage: 2x / 3x / 5x  \n\u2022 Entry Price  \n\u2022 Stop Loss  \n\u2022 Take Profit  \n\u2022 Rationale:  \n\u2003- <b>Primary Price Action Signals</b>  \n\u2003- <b>Lagging Indicator Confirmation</b>  \n\u2003- <b>Sentiment & Macro Analysis</b>\n\n4. **Score your signal strength**  \n\u2022 Confidence score (0\u2013100)  \n\u2022 Strength label: Low / Medium / High / Very High\n\n5. **Include sentiment and headlines** at the bottom of the report:  \n\u2022 A short <b>News Sentiment Summary</b>  \n\u2022 Top 3 Tesla-related headlines with bullet formatting\n\n---\n\n### \ud83e\uddfe Output Format (Telegram HTML)\n\nStart your message with:\n<b>TSLA Analysis</b>\n\n\nUse:\n\u2022 `<b>` for bold headers  \n\u2022 `\u2022` for bullet points  \n\u2022 Clean line breaks  \n\n---\n\n\u26a0\ufe0f DO NOT:\n\u2022 Fabricate or assume any data  \n\u2022 Repeat this prompt or system instructions  \n\u2022 Include raw JSON or raw API format in your output\n\nOnly use what is provided via structured input. Write like a seasoned quantitative analyst.\n"
        },
        "promptType": "define"
      },
      "typeVersion": 1.8
    },
    {
      "id": "966cf9b6-abd4-48a0-bd32-6c83985a33ac",
      "name": "Tesla Financial Market Data Analyst Tool",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        700,
        260
      ],
      "parameters": {
        "name": "Tesla_Financial_Market_Data_Analyst",
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "WmWhVZ3XkJdjTmME",
          "cachedResultName": "Work Drive \u2014 Tesla Financial Market Data Analyst"
        },
        "workflowInputs": {
          "value": {
            "message": "={{ $fromAI(\"message\",\"Populate this with a relevant message to this subagent\")}}",
            "sessionId": "={{ $json.sessionId }}"
          },
          "schema": [
            {
              "id": "message",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "message",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "sessionId",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "sessionId",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "dbf1bef5-044a-4594-af1b-1468d4cdc06a",
      "name": "Tesla News and Sentiment Analyst Tool",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        980,
        260
      ],
      "parameters": {
        "name": "Tesla_News_and_Sentiment_Analyst",
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "kOIhNsok4gtt6fD3",
          "cachedResultName": "Work Drive \u2014 Tesla News and Sentiment Analyst"
        },
        "workflowInputs": {
          "value": {
            "message": "={{ $fromAI(\"message\",\"Populate this with a relevant message to this subagent\")}}",
            "sessionId": "={{ $json.sessionId }}"
          },
          "schema": [
            {
              "id": "message",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "message",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "sessionId",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "sessionId",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "2109ef95-4256-4713-aa9d-8a8ecd40eff3",
      "name": "Add SessionId",
      "type": "n8n-nodes-base.set",
      "position": [
        260,
        -100
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "c9d7a6f2-7e01-46fb-a4ee-f0c3b248bd6b",
              "name": "sessionId",
              "type": "string",
              "value": "={{ $('Telegram Trigger').item.json.message.chat.id }}"
            },
            {
              "id": "d5929b35-1751-4a6a-bbee-d844cbb8e0aa",
              "name": "DateandTime",
              "type": "string",
              "value": "={{ $json.currentDate }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "0f45fae9-fef5-4595-97f0-04f974790cd3",
      "name": "Splits message is more than 4000 characters",
      "type": "n8n-nodes-base.code",
      "position": [
        1020,
        -100
      ],
      "parameters": {
        "jsCode": "// Input: assumes incoming message in `item.json.message`\nconst input = $json.output;\nconst chunkSize = 4000;\n\n// Function to split text\nfunction splitMessage(text, size) {\n  const result = [];\n  for (let i = 0; i < text.length; i += size) {\n    result.push(text.substring(i, i + size));\n  }\n  return result;\n}\n\n// Logic\nif (input.length <= chunkSize) {\n  return [{ json: { message: input } }];\n} else {\n  const chunks = splitMessage(input, chunkSize);\n  return chunks.map(chunk => ({ json: { message: chunk } }));\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "8e7dcfd4-7f2a-47b4-8e5a-1bc4d77fced7",
      "name": "Date & Time",
      "type": "n8n-nodes-base.dateTime",
      "position": [
        -20,
        -100
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 2
    },
    {
      "id": "f31dbe9c-25a2-4751-ba34-38ed0ae9e18c",
      "name": "Simple Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        420,
        260
      ],
      "parameters": {},
      "typeVersion": 1.3
    },
    {
      "id": "97dfa658-3a67-4ed7-9662-b62573e0958b",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -640,
        -340
      ],
      "parameters": {
        "color": 4,
        "height": 420,
        "content": "## Trigger Incoming Telegram Command\n\nThis node **listens for new Telegram messages** to initiate report generation."
      },
      "typeVersion": 1
    },
    {
      "id": "b7d99e5f-0f36-4963-aa2c-33db04689fc5",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -380,
        -340
      ],
      "parameters": {
        "color": 2,
        "width": 260,
        "height": 420,
        "content": "## Validate User Access\n\nEnsures only **authorized Telegram user IDs** can trigger the agent."
      },
      "typeVersion": 1
    },
    {
      "id": "9a4d6ba0-2d75-4453-8b05-bc4dedf81be5",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -80,
        -340
      ],
      "parameters": {
        "color": 5,
        "height": 420,
        "content": "## Capture Timestamp\n\nCaptures the **current system date and time** for session tracking and report stamping."
      },
      "typeVersion": 1
    },
    {
      "id": "157ba065-d228-41f0-a88f-ea8122fb5fa8",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        200,
        -340
      ],
      "parameters": {
        "height": 420,
        "content": "## Generate Session Metadata\n\nAssigns **sessionId based on Telegram chat ID** and stores current **date/time** for context continuity."
      },
      "typeVersion": 1
    },
    {
      "id": "6fe0bc11-94da-4c82-bf28-5fe6429d6e86",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        480,
        -340
      ],
      "parameters": {
        "color": 7,
        "width": 340,
        "height": 420,
        "content": "## Main AI Agent: Trading Report Generator\n\nUses **GPT model to combine technical and sentiment data** into a structured **TSLA swing-trading report**.\nCalls **Financial Market Analyst + Sentiment Analyst**.\n\n"
      },
      "typeVersion": 1
    },
    {
      "id": "7a1e3a33-713a-4a72-81c0-001e74af8f73",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        940,
        -340
      ],
      "parameters": {
        "color": 5,
        "width": 260,
        "height": 420,
        "content": "## Handle Telegram Message Limits\n\nChecks **output message length and splits into 4000-character** chunks if needed.\n\n"
      },
      "typeVersion": 1
    },
    {
      "id": "b5ac3bcb-baa5-4d39-9e44-6be888317089",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1300,
        -340
      ],
      "parameters": {
        "color": 4,
        "width": 260,
        "height": 420,
        "content": "## Send Final Report to Telegram\n\nSends **formatted HTML report (or split parts)** back to the **original Telegram user**."
      },
      "typeVersion": 1
    },
    {
      "id": "5df88223-3acc-4b27-b592-58d499a638dd",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        60,
        220
      ],
      "parameters": {
        "color": 2,
        "height": 400,
        "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n## GPT Model for Reasoning\nUses **OpenAI GPT (e.g., GPT-4o)** to process signal analysis and produce **final report** text."
      },
      "typeVersion": 1
    },
    {
      "id": "c7bcc5bc-48b9-464b-9a6b-062535810543",
      "name": "Sticky Note8",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        340,
        220
      ],
      "parameters": {
        "color": 3,
        "height": 400,
        "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Short-Term Memory Module\nMaintains **state during session**. Helps agent **track message history and previous context**.\n\n"
      },
      "typeVersion": 1
    },
    {
      "id": "b17ec86d-5d91-469f-bc9d-fb5e22ecbfaf",
      "name": "Sticky Note9",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        620,
        220
      ],
      "parameters": {
        "color": 6,
        "height": 400,
        "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Fetch Technical Indicator Insights\nCalls all **15m, 1h, 1d, and Klines sub-agents** via **webhook** to retrieve structured **market analysis**.\n\n"
      },
      "typeVersion": 1
    },
    {
      "id": "1eda1d9b-2b50-4cd1-8b83-6a7d37517d31",
      "name": "Sticky Note10",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        900,
        220
      ],
      "parameters": {
        "color": 6,
        "height": 400,
        "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Scrape Tesla News & Generate Sentiment\nPulls latest **Tesla-related headlines from trusted RSS feeds** and **returns structured sentiment** summary.\n\n"
      },
      "typeVersion": 1
    },
    {
      "id": "8e2ebe09-5488-4fb9-8175-b88ba68fcb9e",
      "name": "Sticky Note11",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1900,
        -1680
      ],
      "parameters": {
        "width": 1280,
        "height": 2300,
        "content": "\n# \ud83e\udde0 Tesla Quant Trading AI Agent \u2013 Full System Documentation\n\nA professional-grade AI-driven stock analysis system designed to deliver structured Tesla (TSLA) swing-trading insights based on real-time technical indicators and sentiment signals.\n\n---\n\n## \ud83e\udde9 Included Workflows\n\n> Download and install **all** of the following workflows for the system to function correctly.\n\n| Workflow Name                               | Function                                                                 |\n| ------------------------------------------- | ------------------------------------------------------------------------ |\n| \u2705 Tesla 15min Indicators Tool               | Pulls Alpha Vantage data for short-term signals (15m: RSI, BBANDS, etc.) |\n| \u2705 Tesla 1hour Indicators Tool               | Pulls Alpha Vantage data for medium-term signals (1h: RSI, BBANDS, etc.) |\n| \u2705 Tesla 1day Indicators Tool                | Pulls Alpha Vantage data for long-term signals (1d: RSI, BBANDS, MACD)   |\n| \u2705 Tesla 1hour & 1day Klines Tool            | Analyzes candlestick patterns and volume divergences (OHLCV)             |\n| \u2705 Tesla Quant Technical Indicators Webhooks | Webhook handlers that power the above 4 indicator-fetching tools         |\n| \u2705 Tesla Financial Market Data Analyst Tool  | Synthesizes multi-timeframe indicator + candle data                      |\n| \u2705 Tesla News and Sentiment Analyst Tool     | Scrapes Tesla news RSS + assigns sentiment with headlines                |\n| \u2705 Tesla Quant Trading AI Agent              | Final agent that generates Telegram-style trade reports                  |\n\n---\n\n## \u2699\ufe0f Installation Instructions\n\n### Step 1: Import Workflows\n\n1. Open your **n8n editor UI**.\n2. Import each workflow JSON file one by one.\n3. Make sure all workflows are **activated** or properly linked via `Execute Workflow` nodes.\n\n### Step 2: Set Up Credentials\n\n1. Go to **Credentials \u2192 HTTP Auth \u2192 Query Parameter Auth**.\n2. Create a credential named: `Alpha Vantage Premium`\n\n   * Add: `apikey=YOUR_API_KEY`\n3. Add your **OpenAI API** credentials (for GPT-4.1 or equivalent).\n\n### Step 3: Configure Webhooks\n\n1. Deploy the **Tesla Quant Technical Indicators Webhooks Tool**.\n2. Ensure that `/15minData`, `/1hourData`, `/1dayData`, and `/klinesData` routes are properly reachable.\n\n### Step 4: Set Up Execution\n\n1. Trigger the **Tesla Quant Trading AI Agent** manually or via a scheduler.\n2. The agent will:\n\n   * Call all technical + sentiment tools via workflow execution\n   * Format and analyze data\n   * Output full trading report in Telegram-HTML style\n\n---\n\n## \ud83d\udda5\ufe0f System Overview\n\n**Data Flow:**\n\n```\n[Webhook HTTP Trigger] \n\u2192 [Indicator Tool (15m, 1h, 1d)] \n\u2192 [Candlestick Tool (1h, 1d)]\n\u2192 [Financial Market Data Analyst] \n\u2192 [Sentiment Analyst] \n\u2192 [Final Report Generator]\n```\n\n**Output Example:**\n\n* Spot + Leverage trade entries\n* Confidence score (0\u2013100)\n* Reasoning: price action, indicators, and sentiment\n* Summary headlines and sentiment context\n\n---\n\n## \ud83d\udcec Output Format\n\n* Styled using Telegram HTML (`<b>`, `\u2022`, newlines)\n* Structured trade report with:\n\n  * Action type\n  * Entry/exit prices\n  * Rationale in 3 parts\n  * News sentiment and 3 headlines\n\n---\n\n## \ud83d\ude80 Support & Licensing\n\n\ud83d\udd17 **Don Jayamaha \u2013 LinkedIn**\n[http://linkedin.com/in/donjayamahajr](http://linkedin.com/in/donjayamahajr)\n\n\u00a9 2025 Treasurium Capital Limited Company. All rights reserved.\nThis AI workflow architecture, including logic, design, and prompt structures, is the intellectual property of **Treasurium Capital Limited Company**. Unauthorized reproduction, redistribution, or resale is prohibited under **U.S. copyright law**. Licensed use only.\n\n"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "b77078ba-b904-4315-aa13-f80fded7f9a9",
  "connections": {
    "Telegram": {
      "main": [
        []
      ]
    },
    "Date & Time": {
      "main": [
        [
          {
            "node": "Add SessionId",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add SessionId": {
      "main": [
        [
          {
            "node": "Tesla Quant Trading AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "Tesla Quant Trading AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Telegram Trigger": {
      "main": [
        [
          {
            "node": "User Authentication (Replace Telegram ID)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Tesla Quant Trading AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Tesla Quant Trading AI Agent": {
      "main": [
        [
          {
            "node": "Splits message is more than 4000 characters",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tesla News and Sentiment Analyst Tool": {
      "ai_tool": [
        [
          {
            "node": "Tesla Quant Trading AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Tesla Financial Market Data Analyst Tool": {
      "ai_tool": [
        [
          {
            "node": "Tesla Quant Trading AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "User Authentication (Replace Telegram ID)": {
      "main": [
        [
          {
            "node": "Date & Time",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Splits message is more than 4000 characters": {
      "main": [
        [
          {
            "node": "Telegram",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}