{
  "id": "MIas2bpn3BBFDGq2",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Simple Investment Idea Generator",
  "tags": [],
  "nodes": [
    {
      "id": "a3c123d4-6033-4ce7-b2c5-807ff90d2e58",
      "name": "Fetch Trending Stocks",
      "type": "n8n-nodes-base.httpRequest",
      "onError": "continueRegularOutput",
      "position": [
        32,
        544
      ],
      "parameters": {
        "url": "=https://stock.indianapi.in/trending",
        "options": {},
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "httpMultipleHeadersAuth"
      },
      "credentials": {
        "httpMultipleHeadersAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "84379c76-8c9a-44c2-94af-1660d5cc99ca",
      "name": "Combine Market Data",
      "type": "n8n-nodes-base.merge",
      "position": [
        480,
        880
      ],
      "parameters": {
        "mode": "combine",
        "options": {},
        "combineBy": "combineByPosition"
      },
      "typeVersion": 3.2
    },
    {
      "id": "c49d0ee8-e00b-453f-9a96-ab3b8a0ac243",
      "name": "Format Data for AI",
      "type": "n8n-nodes-base.set",
      "position": [
        704,
        880
      ],
      "parameters": {
        "mode": "raw",
        "options": {},
        "jsonOutput": "=={{ {\n  market_summary: {\n    top_gainers: $json.trending_stocks.top_gainers.slice(0,3).map(stock => ({\n      name: stock.company_name,\n      price: stock.price,\n      change: stock.percent_change,\n      trend_short: stock.short_term_trends,\n      trend_long: stock.long_term_trends,\n      rating: stock.overall_rating\n    })),\n    top_losers: $json.trending_stocks.top_losers.slice(0,3).map(stock => ({\n      name: stock.company_name,\n      price: stock.price,\n      change: stock.percent_change,\n      trend_short: stock.short_term_trends,\n      trend_long: stock.long_term_trends,\n      rating: stock.overall_rating\n    }))\n  },\n  market_news: $items(\"getting latest 5 news\").map(item => ({\n  headline: item.json.title,\n  summary: item.json.contentSnippet.replace(/<[^>]*>/g, '')\n}))\n} }}"
      },
      "typeVersion": 3.4
    },
    {
      "id": "2ec8ad0c-db14-421f-a93b-a19072994dee",
      "name": "Generate Investment Ideas",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        992,
        880
      ],
      "parameters": {
        "text": "=You are a professional equity research analyst for the Indian stock market.\n\nContext:\n- You analyze market trends, news and stock momentum\n- You generate actionable, realistic investment ideas\n\nYou have access to a tool:\n- get_existing_ideas \u2192 fetches previously generated investment ideas from Google Sheets\n\nIMPORTANT:\n1. First, call the tool \"get_existing_ideas\"\n2. Analyze all previously generated ideas\n3. Do NOT repeat:\n   - Same stock\n   - Similar reasoning\n   - Same sector bias\n\nMarket Summary:\n{{ JSON.stringify($json.market_summary, null, 2) }}\n\nMarket News:\n{{ JSON.stringify($json.market_news, null, 2) }}\n\nMemory:\nContains recently generated ideas \u2014 avoid repeating them.\n\nAlso use the tool data (Google Sheets) to avoid historical duplicates.\n\nTask:\nGenerate 2\u20133 high-quality investment ideas.\n\nSTRICT RULES:\n- Avoid generic suggestions like \"strong company\" or \"good growth\"\n- Use data points (price movement, trend, news trigger)\n- Prefer sector-based reasoning (banking, IT, pharma, etc.)\n- Avoid penny stocks or unknown companies\n- Each idea must be clearly different\n- If similar to existing ideas, reject and regenerate\n\nUse ONLY the provided market data. Do not invent information.\n\nReject any idea that sounds generic or lacks clear reasoning.\n\nIf tool data is unavailable, rely on memory but still ensure diversity.\n\nOUTPUT REQUIREMENTS:\nEach idea must include:\n\n1. title \u2192 Specific and insight-driven  \n2. stock \u2192 Real company name  \n3. reason \u2192 Must include trend/news/sector logic  \n4. risk \u2192 High / Medium / Low  \n5. horizon \u2192 Short-term / Mid-term / Long-term  \n\nReturn ONLY valid JSON:\n[\n  {\n    \"title\": \"\",\n    \"stock\": \"\",\n    \"reason\": \"\",\n    \"risk\": \"\",\n    \"horizon\": \"\"\n  }\n]",
        "options": {},
        "promptType": "define"
      },
      "typeVersion": 3.1
    },
    {
      "id": "d676cdf3-21ee-4b81-8ab2-b287e9df5d46",
      "name": "Fetch Indian Market News",
      "type": "n8n-nodes-base.rssFeedRead",
      "position": [
        32,
        928
      ],
      "parameters": {
        "url": "https://news.google.com/rss/search?q=Indian stock market OR NSE OR BSE",
        "options": {}
      },
      "typeVersion": 1.2
    },
    {
      "id": "b26b3758-6933-4370-92b3-310b1ec4a32e",
      "name": "Format for Sheets",
      "type": "n8n-nodes-base.code",
      "position": [
        1616,
        976
      ],
      "parameters": {
        "jsCode": "let raw = $input.first().json.output;\n\n// Remove markdown\nraw = raw.replace(/```json/g, '').replace(/```/g, '').trim();\n\ntry {\n  const data = JSON.parse(raw);\n\n  return data.map(item => ({ json: item }));\n\n} catch (e) {\n  return [{\n  json: {\n    error_type: \"FORMAT_ERROR\",\n    message: \"Invalid AI JSON format\",\n    raw_output: raw,\n    stage: \"parsing\"\n  }\n}];\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "53c2dd3a-41ab-4d7a-83ce-8b4c7e591b1f",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -800,
        -48
      ],
      "parameters": {
        "width": 576,
        "height": 624,
        "content": "## Simple Investment Idea Generator\n\n## How it works:\n\nThis workflow automatically generates actionable investment ideas based on real-time Indian stock market data. It runs on a schedule, fetching trending stocks and the latest market news from external sources. The data is then validated, cleaned and structured into a consistent format for analysis. An AI agent processes this information along with previously generated ideas stored in Google Sheets to ensure each new idea is unique and avoids duplication. The workflow includes built-in validation to handle empty or incorrectly formatted AI responses, along with error-handling mechanisms for API and processing failures. Once validated, the final investment ideas are structured into defined fields and stored in Google Sheets, enabling easy tracking, review and reuse over time.\n\n## Setup steps:\n\n1. Add your Stock API credentials in the \u201cFetch Trending Stocks\u201d node.\n2. Connect your Google Sheets account (read and append access required).\n3. Configure your AI model credentials (Groq or OpenAI).\n4. Review and update fields in the Edit Fields (Set) node as needed.\n5. Run a test execution to verify data flow before enabling the schedule."
      },
      "typeVersion": 1
    },
    {
      "id": "a69b4c92-3b65-4f21-8929-e2ff5ea37c69",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -208,
        336
      ],
      "parameters": {
        "color": 7,
        "width": 576,
        "height": 736,
        "content": "## Trigger & Data Collection\n\nHandles scheduled execution and fetches real-time data including trending stocks and latest Indian market news for further processing. Checks if stock API response is valid. If data is missing or failed, routes the workflow to error handling."
      },
      "typeVersion": 1
    },
    {
      "id": "d8f9b8c0-18f0-4e39-b851-1157a94f76f6",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        464,
        688
      ],
      "parameters": {
        "color": 7,
        "width": 352,
        "height": 352,
        "content": "## Data Preparation \n\nCombines stock and news data, cleans unnecessary fields and structures it into a consistent JSON format for AI processing.\n"
      },
      "typeVersion": 1
    },
    {
      "id": "ab0a450e-b85a-4efd-b230-a04dc4c7e1e1",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1616,
        784
      ],
      "parameters": {
        "color": 7,
        "width": 644,
        "height": 352,
        "content": "## Data Formatting & Storage\n\nParses AI output into structured fields and appends the results into Google Sheets for tracking."
      },
      "typeVersion": 1
    },
    {
      "id": "b43c0045-2b87-41c4-a848-fd271b61a790",
      "name": "Groq Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatGroq",
      "position": [
        928,
        1104
      ],
      "parameters": {
        "model": "openai/gpt-oss-120b",
        "options": {}
      },
      "credentials": {
        "groqApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "785de364-25fa-4b9c-83ef-2556c999da80",
      "name": "getting latest 5 news",
      "type": "n8n-nodes-base.limit",
      "position": [
        256,
        928
      ],
      "parameters": {
        "maxItems": 5
      },
      "typeVersion": 1
    },
    {
      "id": "8bb1cc0f-6f65-490d-939e-f8405046d06b",
      "name": "Append row in sheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        2064,
        992
      ],
      "parameters": {
        "columns": {
          "value": {
            "Date": "={{ $today }}",
            "Stock": "={{ $json.stock }}",
            "Title": "={{ $json.title }}",
            "Reason": "={{ $json.reason }}",
            "Horizon": "={{ $json.horizon }}"
          },
          "schema": [
            {
              "id": "Date",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Title",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Title",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Stock",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Stock",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Reason",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Reason",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Horizon",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Horizon",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "Date"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1eDCUJ_9bhC9kFWbyQIjuzjx7B_-8woxSClgcEikLoBs/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1eDCUJ_9bhC9kFWbyQIjuzjx7B_-8woxSClgcEikLoBs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1eDCUJ_9bhC9kFWbyQIjuzjx7B_-8woxSClgcEikLoBs/edit?usp=drivesdk",
          "cachedResultName": "AI Investment Ideas \u2013 India"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "95d31dde-b307-4f32-b40a-92e1ff713c25",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        880,
        624
      ],
      "parameters": {
        "color": 7,
        "width": 624,
        "height": 640,
        "content": "## AI Idea Generation & Validation\n\nUses AI model with memory and Google Sheets tool to generate unique investment ideas while avoiding duplicates. Also ensures AI response is not empty and properly formatted before further processing.\n"
      },
      "typeVersion": 1
    },
    {
      "id": "e4bba3da-04fd-45c2-937c-01a96ebbb277",
      "name": "API Failed",
      "type": "n8n-nodes-base.set",
      "position": [
        1792,
        432
      ],
      "parameters": {
        "mode": "raw",
        "options": {},
        "jsonOutput": "{\n  \"error_type\": \"API_ERROR\",\n  \"message\": \"Failed to fetch trending stocks\",\n  \"stage\": \"stock_api\"\n}"
      },
      "typeVersion": 3.4
    },
    {
      "id": "f06bfd97-aa45-4d04-b5e3-0a2f6cc27785",
      "name": "Handle API Failure",
      "type": "n8n-nodes-base.if",
      "position": [
        256,
        544
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "c0d5d1cf-6eef-4451-97d0-bc67f09084f4",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $json.trending_stocks === undefined }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "baf90336-6927-4d9c-b1f8-f0e380a9674b",
      "name": "AI Failed",
      "type": "n8n-nodes-base.set",
      "position": [
        1792,
        592
      ],
      "parameters": {
        "mode": "raw",
        "options": {},
        "jsonOutput": "{\n  \"error_type\": \"AI_ERROR\",\n  \"message\": \"AI did not return output\",\n  \"stage\": \"ai_generation\"\n}"
      },
      "typeVersion": 3.4
    },
    {
      "id": "b3d13f63-0e9f-4d3c-afdf-44395109604e",
      "name": "Json Format Error Check",
      "type": "n8n-nodes-base.if",
      "position": [
        1840,
        976
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "d5fc3d00-9597-4c12-9f9d-9ffcc675d3c8",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              },
              "leftValue": "={{ $json.error_type !== \"FORMAT_ERROR\" }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "5db7fe89-db20-4bbf-bf15-22af66400258",
      "name": "Combine all the errors",
      "type": "n8n-nodes-base.merge",
      "position": [
        2064,
        560
      ],
      "parameters": {
        "numberInputs": 3
      },
      "typeVersion": 3.2
    },
    {
      "id": "762fbc2c-f150-43f3-a9fe-d39012c7c9a8",
      "name": "Send Error Message on Gmail",
      "type": "n8n-nodes-base.gmail",
      "position": [
        2256,
        576
      ],
      "parameters": {
        "sendTo": "",
        "message": "=Type: {{ $json.error_type }}\nStage: {{ $json.stage }}\nMessage: {{ $json.message }}\n\nTime: {{ $now }}",
        "options": {
          "appendAttribution": false
        },
        "subject": "Error occured during executing workflow",
        "emailType": "text"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "935485ca-c311-41ed-9b8e-9741131ae1b8",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1744,
        320
      ],
      "parameters": {
        "color": 7,
        "width": 688,
        "height": 448,
        "content": "## Error Handling & Alerts\n\nCaptures errors from API, AI or formatting stages and sends email notifications for monitoring."
      },
      "typeVersion": 1
    },
    {
      "id": "13343c88-75bb-4105-baa0-c22bf0348bf7",
      "name": "get_existing_ideas",
      "type": "n8n-nodes-base.googleSheetsTool",
      "position": [
        1232,
        1104
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1eDCUJ_9bhC9kFWbyQIjuzjx7B_-8woxSClgcEikLoBs/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1eDCUJ_9bhC9kFWbyQIjuzjx7B_-8woxSClgcEikLoBs",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1eDCUJ_9bhC9kFWbyQIjuzjx7B_-8woxSClgcEikLoBs/edit?usp=drivesdk",
          "cachedResultName": "AI Investment Ideas \u2013 India"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "bd36128e-eb73-405a-8cc1-1242b21fb18e",
      "name": "Simple Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        1072,
        1104
      ],
      "parameters": {
        "sessionKey": "investment-session",
        "sessionIdType": "customKey",
        "contextWindowLength": 15
      },
      "typeVersion": 1.3
    },
    {
      "id": "a2c8d919-eef3-49ed-9f07-a4abe6f4c4c4",
      "name": "Handle AI Failure",
      "type": "n8n-nodes-base.if",
      "position": [
        1392,
        864
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "or",
          "conditions": [
            {
              "id": "a484b752-8e7d-4ef3-88f8-4b8c3acbc342",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $json.output.isEmpty() }}",
              "rightValue": ""
            },
            {
              "id": "4721f0bb-b8f8-455b-b836-11be0033c88a",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $json.output === \"[]\" }}",
              "rightValue": ""
            },
            {
              "id": "66659a64-9822-4d4c-902b-f76bc51f97dd",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $json.output === \"\" }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "26fc1af4-6b90-4673-89b8-37f87be0e080",
      "name": "Executes Workflow Everyday at 9 AM",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -192,
        752
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 9
            }
          ]
        }
      },
      "typeVersion": 1.3
    }
  ],
  "active": false,
  "settings": {
    "binaryMode": "separate",
    "executionOrder": "v1"
  },
  "versionId": "5c70d574-b579-4cbc-aa5e-52704e74b45b",
  "connections": {
    "AI Failed": {
      "main": [
        [
          {
            "node": "Combine all the errors",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "API Failed": {
      "main": [
        [
          {
            "node": "Combine all the errors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "Generate Investment Ideas",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Groq Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Generate Investment Ideas",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Format for Sheets": {
      "main": [
        [
          {
            "node": "Json Format Error Check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Handle AI Failure": {
      "main": [
        [
          {
            "node": "AI Failed",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Format for Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Data for AI": {
      "main": [
        [
          {
            "node": "Generate Investment Ideas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Handle API Failure": {
      "main": [
        [
          {
            "node": "API Failed",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Combine Market Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "get_existing_ideas": {
      "ai_tool": [
        [
          {
            "node": "Generate Investment Ideas",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Combine Market Data": {
      "main": [
        [
          {
            "node": "Format Data for AI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Trending Stocks": {
      "main": [
        [
          {
            "node": "Handle API Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "getting latest 5 news": {
      "main": [
        [
          {
            "node": "Combine Market Data",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Combine all the errors": {
      "main": [
        [
          {
            "node": "Send Error Message on Gmail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Json Format Error Check": {
      "main": [
        [
          {
            "node": "Combine all the errors",
            "type": "main",
            "index": 2
          }
        ],
        [
          {
            "node": "Append row in sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Indian Market News": {
      "main": [
        [
          {
            "node": "getting latest 5 news",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Investment Ideas": {
      "main": [
        [
          {
            "node": "Handle AI Failure",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Executes Workflow Everyday at 9 AM": {
      "main": [
        [
          {
            "node": "Fetch Trending Stocks",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Indian Market News",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}