{
    "nodes": [
        {
            "parameters": {
                "httpMethod": "POST",
                "path": "crypto-indicators",
                "responseMode": "lastNode",
                "options": {}
            },
            "id": "3118f84f-8011-43fb-90a4-abf8e18cbad6",
            "name": "Webhook",
            "type": "n8n-nodes-base.webhook",
            "typeVersion": 2.1,
            "position": [
                -480,
                176
            ],
            "webhookId": "6caf407b-05cf-4473-a297-1222a724e549"
        },
        {
            "parameters": {
                "authentication": "apiKey",
                "model": "={{ $('Webhook').item.json.body.model }}",
                "messages": {
                    "message": [
                        {
                            "content": "={{ $json.prompt }}"
                        },
                        {
                            "role": "system",
                            "content": "You are a concise crypto market analyst. Provide a brief technical analysis based on the provided indicators. Keep response under 300 words."
                        }
                    ]
                },
                "options": {
                    "temperature": 0.4,
                    "max_tokens": 500
                }
            },
            "type": "n8n-nodes-agnic.agnicAI",
            "typeVersion": 1,
            "position": [
                272,
                336
            ],
            "id": "f6d34d1c-4d3b-4da1-b064-5065ba201567",
            "name": "AgnicAI",
            "credentials": {
                "agnicWalletApi": {
                    "id": "b0VYolgAKDoSfr4z",
                    "name": "AgnicPay Universal API Key"
                }
            }
        },
        {
            "parameters": {
                "authentication": "apiKey",
                "method": "POST",
                "url": "https://api.agnichub.xyz/v1/custom/trading-indicators/candles",
                "body": "={\n    \"coin\": \"{{ $json.coin }}\",\n    \"exchange\": \"{{ $json.exchange }}\",\n    \"interval\": \"{{ $json.timeframe }}\",\n    \"limit\": {{ $json.candleLimit }}\n  } "
            },
            "type": "n8n-nodes-agnic.agnicWalletX402Request",
            "typeVersion": 1,
            "position": [
                16,
                96
            ],
            "id": "f7b4ffa8-3ec5-47ae-aebf-1385bd7a4a02",
            "name": "AgnicWallet X402",
            "credentials": {
                "agnicWalletApi": {
                    "id": "b0VYolgAKDoSfr4z",
                    "name": "AgnicPay Universal API Key"
                }
            }
        },
        {
            "parameters": {
                "jsCode": "// Compute Technical Indicators\nconst input = $input.first().json;\n\nif (!input || !input.candles || input.candles.length === 0) {\n  return [{ json: { ...input, indicatorData: {} } }];\n}\n\nconst candles = input.candles;\nconst indicators = input.indicators || [];\nconst indicatorParams = input.indicatorParams || {};\n\n// Extract data series\nconst opens = candles.map(c => c.open);\nconst highs = candles.map(c => c.high);\nconst lows = candles.map(c => c.low);\nconst closes = candles.map(c => c.close);\nconst volumes = candles.map(c => c.volume);\n\n// --- HELPER FUNCTIONS ---\n\nfunction calculateSMA(data, period) {\n  if (data.length < period) return [];\n  const sma = [];\n  for (let i = period - 1; i < data.length; i++) {\n    const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);\n    sma.push(sum / period);\n  }\n  return sma;\n}\n\nfunction calculateEMA(data, period) {\n  if (data.length < period) return [];\n  const ema = [];\n  const multiplier = 2 / (period + 1);\n  \n  // First EMA is SMA\n  const firstSMA = data.slice(0, period).reduce((a, b) => a + b, 0) / period;\n  ema.push(firstSMA);\n  \n  // Calculate subsequent EMAs\n  for (let i = period; i < data.length; i++) {\n    const currentEMA = (data[i] - ema[ema.length - 1]) * multiplier + ema[ema.length - 1];\n    ema.push(currentEMA);\n  }\n  return ema;\n}\n\nfunction calculateStdDev(data, period, index) {\n  const slice = data.slice(index - period + 1, index + 1);\n  const mean = slice.reduce((a, b) => a + b, 0) / period;\n  const variance = slice.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / period;\n  return Math.sqrt(variance);\n}\n\nfunction calculateBollingerBands(data, period, stdDevMultiplier) {\n  if (data.length < period) return [];\n  const bands = [];\n  \n  for (let i = period - 1; i < data.length; i++) {\n    const slice = data.slice(i - period + 1, i + 1);\n    const sma = slice.reduce((a, b) => a + b, 0) / period;\n    const stdDev = calculateStdDev(data, period, i);\n    \n    bands.push({\n      upper: sma + (stdDevMultiplier * stdDev),\n      middle: sma,\n      lower: sma - (stdDevMultiplier * stdDev)\n    });\n  }\n  return bands;\n}\n\nfunction calculateRSI(data, period) {\n  if (data.length < period + 1) return [];\n  const rsi = [];\n  const changes = [];\n  for (let i = 1; i < data.length; i++) {\n    changes.push(data[i] - data[i - 1]);\n  }\n  \n  let avgGain = 0;\n  let avgLoss = 0;\n  \n  for (let i = 0; i < period; i++) {\n    if (changes[i] > 0) avgGain += changes[i];\n    else avgLoss += Math.abs(changes[i]);\n  }\n  \n  avgGain /= period;\n  avgLoss /= period;\n  \n  const rs = avgLoss === 0 ? 100 : avgGain / avgLoss;\n  rsi.push(100 - (100 / (1 + rs)));\n  \n  for (let i = period; i < changes.length; i++) {\n    const gain = changes[i] > 0 ? changes[i] : 0;\n    const loss = changes[i] < 0 ? Math.abs(changes[i]) : 0;\n    \n    avgGain = (avgGain * (period - 1) + gain) / period;\n    avgLoss = (avgLoss * (period - 1) + loss) / period;\n    \n    const currentRS = avgLoss === 0 ? 100 : avgGain / avgLoss;\n    rsi.push(100 - (100 / (1 + currentRS)));\n  }\n  \n  return rsi;\n}\n\nfunction calculateATR(highs, lows, closes, period) {\n  if (highs.length < period + 1) return [];\n  const trueRanges = [];\n  \n  for (let i = 1; i < highs.length; i++) {\n    const tr = Math.max(\n      highs[i] - lows[i],\n      Math.abs(highs[i] - closes[i - 1]),\n      Math.abs(lows[i] - closes[i - 1])\n    );\n    trueRanges.push(tr);\n  }\n  \n  const atr = [];\n  const firstATR = trueRanges.slice(0, period).reduce((a, b) => a + b, 0) / period;\n  atr.push(firstATR);\n  \n  for (let i = period; i < trueRanges.length; i++) {\n    const currentATR = (atr[atr.length - 1] * (period - 1) + trueRanges[i]) / period;\n    atr.push(currentATR);\n  }\n  \n  return atr;\n}\n\nfunction calculateMACD(data, fastPeriod, slowPeriod, signalPeriod) {\n  if (data.length < slowPeriod) return [];\n  const fastEMA = calculateEMA(data, fastPeriod);\n  const slowEMA = calculateEMA(data, slowPeriod);\n  \n  const macdLine = [];\n  // Align EMAs\n  for (let i = 0; i < slowEMA.length; i++) {\n    const fastVal = fastEMA[fastEMA.length - slowEMA.length + i];\n    const slowVal = slowEMA[i];\n    macdLine.push(fastVal - slowVal);\n  }\n  \n  const signalLine = calculateEMA(macdLine, signalPeriod);\n  const result = [];\n  for (let i = 0; i < signalLine.length; i++) {\n     result.push({\n       macd: macdLine[macdLine.length - signalLine.length + i],\n       signal: signalLine[i],\n       histogram: macdLine[macdLine.length - signalLine.length + i] - signalLine[i]\n     });\n  }\n  return result;\n}\n\nfunction calculateADX(highs, lows, closes, period) {\n  if (highs.length < period * 2) return [];\n  \n  const tr = [];\n  const dmPlus = [];\n  const dmMinus = [];\n  \n  for (let i = 1; i < highs.length; i++) {\n    tr.push(Math.max(highs[i]-lows[i], Math.abs(highs[i]-closes[i-1]), Math.abs(lows[i]-closes[i-1])));\n    const up = highs[i] - highs[i-1];\n    const down = lows[i-1] - lows[i];\n    dmPlus.push((up > down && up > 0) ? up : 0);\n    dmMinus.push((down > up && down > 0) ? down : 0);\n  }\n  \n  function smooth(data, p) {\n    if (data.length < p) return [];\n    const smoothed = [];\n    let sum = data.slice(0, p).reduce((a,b)=>a+b,0);\n    smoothed.push(sum);\n    for (let i=p; i<data.length; i++) {\n       smoothed.push(smoothed[smoothed.length-1] - (smoothed[smoothed.length-1]/p) + data[i]);\n    }\n    return smoothed;\n  }\n  \n  const trSmooth = smooth(tr, period);\n  const dmPlusSmooth = smooth(dmPlus, period);\n  const dmMinusSmooth = smooth(dmMinus, period);\n  \n  const dx = [];\n  const len = Math.min(trSmooth.length, dmPlusSmooth.length, dmMinusSmooth.length);\n  \n  for (let i=0; i<len; i++) {\n    const diPlus = 100 * (dmPlusSmooth[i] / trSmooth[i]);\n    const diMinus = 100 * (dmMinusSmooth[i] / trSmooth[i]);\n    const sum = diPlus + diMinus;\n    dx.push(sum === 0 ? 0 : 100 * Math.abs(diPlus - diMinus) / sum);\n  }\n  \n  const adx = [];\n  if (dx.length >= period) {\n      let firstADX = dx.slice(0, period).reduce((a,b)=>a+b,0) / period;\n      adx.push(firstADX);\n      for (let i=period; i<dx.length; i++) {\n          adx.push(((adx[adx.length-1] * (period-1)) + dx[i]) / period);\n      }\n  }\n  return adx;\n}\n\nfunction calculateOBV(closes, volumes) {\n  const obv = [0];\n  let currentOBV = 0;\n  for (let i = 1; i < closes.length; i++) {\n    if (closes[i] > closes[i-1]) currentOBV += volumes[i];\n    else if (closes[i] < closes[i-1]) currentOBV -= volumes[i];\n    obv.push(currentOBV);\n  }\n  return obv;\n}\n\nfunction calculateSupportResistance(highs, lows, lookback) {\n   const levels = [];\n   if(highs.length < lookback) return [];\n   for(let i=lookback; i<highs.length; i++) {\n       const hSlice = highs.slice(i-lookback, i);\n       const lSlice = lows.slice(i-lookback, i);\n       levels.push({\n           resistance: Math.max(...hSlice),\n           support: Math.min(...lSlice)\n       });\n   }\n   return levels;\n}\n\n// --- EXECUTION ---\nconst resultData = {};\n\nif (indicators.includes('sma')) resultData.sma = calculateSMA(closes, indicatorParams.sma?.period || 20);\nif (indicators.includes('ema')) resultData.ema = calculateEMA(closes, indicatorParams.ema?.period || 20);\nif (indicators.includes('bbands')) resultData.bbands = calculateBollingerBands(closes, indicatorParams.bbands?.period||20, indicatorParams.bbands?.stdDev||2);\nif (indicators.includes('rsi')) resultData.rsi = calculateRSI(closes, indicatorParams.rsi?.period||14);\nif (indicators.includes('atr')) resultData.atr = calculateATR(highs, lows, closes, indicatorParams.atr?.period||14);\nif (indicators.includes('macd')) {\n   const p = indicatorParams.macd || { fast: 12, slow: 26, signal: 9 };\n   resultData.macd = calculateMACD(closes, p.fast, p.slow, p.signal);\n}\nif (indicators.includes('adx')) {\n   resultData.adx = calculateADX(highs, lows, closes, indicatorParams.adx?.period||14);\n}\nif (indicators.includes('obv')) {\n   resultData.obv = calculateOBV(closes, volumes);\n}\nif (indicators.includes('support_resistance')) {\n    resultData.support_resistance = calculateSupportResistance(highs, lows, indicatorParams.support_resistance?.lookback||20);\n}\n\nreturn [{\n  json: {\n    ...input,\n    indicatorData: resultData\n  }\n}];"
            },
            "id": "7800fcf6-4dd6-4d5a-813a-e9176feb46fb",
            "name": "Compute Indicators",
            "type": "n8n-nodes-base.code",
            "typeVersion": 2,
            "position": [
                -288,
                336
            ]
        },
        {
            "parameters": {
                "jsCode": "// Build response JSON with complete structure\nconst inputJson = $input.first().json;\n\n// Determine source of data (Skip path or OpenAI path)\nlet insight = '';\nlet data = {};\n\nif (inputJson.skipOpenAI) {\n  // Came directly from Check OpenAI API Key (Skip path)\n  insight = inputJson.insight || 'No AI insight available';\n  // In this path, the input IS the data we preserved\n  data = inputJson;\n} else {\n  // Came from OpenAI Chat\n  // Robust extraction of OpenAI output\n  const rawOutput = inputJson;\n  insight = rawOutput.output || \n            rawOutput.text || \n            (rawOutput.message ? rawOutput.message.content : '') || \n            rawOutput.content || \n            (typeof rawOutput === 'string' ? rawOutput : '') ||\n            '';\n\n  // If still empty, provide debug info\n  if (!insight) {\n      insight = \"AI generation completed but no text was extracted. Debug: \" + JSON.stringify(rawOutput);\n  }\n  \n  // Fetch the preserved raw data (candles, coin, etc.) from the 'Build Insight Prompt' node\n  // because the OpenAI node input/output flow doesn't preserve it automatically in this structure\n  data = $('Build Insight Prompt').first().json;\n}\n\n// Extract accumulated data from the identified source\nconst candles = data.candles || [];\nconst indicatorData = data.indicatorData || {\n  sma: [],\n  ema: [],\n  bbands: [],\n  rsi: [],\n  atr: []\n};\nconst computedIndicatorData = data.computedIndicatorData || indicatorData;\nconst serviceIndicatorData = data.serviceIndicatorData || {};\nconst coin = data.coin || '';\nconst exchange = data.exchange || '';\nconst timeframe = data.timeframe || '';\nconst candleLimit = data.candleLimit || 0;\nconst indicatorSnapshot = data.indicatorSnapshot || [];\n\n// Calculate latest close\nconst latestClose = candles.length > 0 ? candles[candles.length - 1].close : null;\n\n// Build chart data\nconst labels = candles.map(c => c.timestamp);\nconst closeData = candles.map(c => c.close);\nconst smaData = indicatorData.sma || [];\nconst emaData = indicatorData.ema || [];\nconst bbandsData = {\n  upper: indicatorData.bbands?.map(b => b.upper) || [],\n  middle: indicatorData.bbands?.map(b => b.middle) || [],\n  lower: indicatorData.bbands?.map(b => b.lower) || []\n};\n\n// Build final response\nconst response = {\n  meta: {\n    coin: coin,\n    exchange: exchange,\n    timeframe: timeframe,\n    candleLimit: candleLimit\n  },\n  candles: candles.map(c => ({\n    timestamp: c.timestamp,\n    open: c.open,\n    high: c.high,\n    low: c.low,\n    close: c.close,\n    volume: c.volume\n  })),\n  indicatorData: {\n    sma: smaData,\n    ema: emaData,\n    bbands: {\n      upper: bbandsData.upper,\n      middle: bbandsData.middle,\n      lower: bbandsData.lower\n    },\n    rsi: indicatorData.rsi || [],\n    atr: indicatorData.atr || []\n  },\n  computedIndicatorData: computedIndicatorData,\n  serviceIndicatorData: serviceIndicatorData,\n  latestClose: latestClose,\n  insight: insight,\n  indicatorSnapshot: indicatorSnapshot,\n  chart: {\n    labels: labels,\n    close: closeData,\n    sma: smaData,\n    ema: emaData,\n    bbands: bbandsData\n  }\n};\n\nreturn [{ json: response }];"
            },
            "id": "20083a50-0904-44b7-b132-3042789710b1",
            "name": "Build Response JSON",
            "type": "n8n-nodes-base.code",
            "typeVersion": 2,
            "position": [
                560,
                240
            ]
        },
        {
            "parameters": {
                "jsCode": "// Build insight prompt from indicator data\nconst data = $input.first().json;\n\n// Extract data\nconst candles = data.candles || [];\nconst indicatorData = data.indicatorData || {};\nconst coin = data.coin || 'Unknown';\nconst exchange = data.exchange || 'Unknown';\nconst timeframe = data.timeframe || 'Unknown';\n\nif (candles.length === 0) {\n  return [{ json: { error: 'No candles available' } }];\n}\n\n// Get latest candle close price\nconst latestCandle = candles[candles.length - 1];\nconst latestClose = latestCandle.close;\n\n// Extract latest indicator values (last element of each array)\nconst sma = indicatorData.sma || [];\nconst ema = indicatorData.ema || [];\nconst bbands = indicatorData.bbands || [];\nconst rsi = indicatorData.rsi || [];\nconst atr = indicatorData.atr || [];\nconst macd = indicatorData.macd || [];\nconst adx = indicatorData.adx || [];\nconst obv = indicatorData.obv || [];\nconst supres = indicatorData.support_resistance || [];\n\nconst latestSMA = sma.length > 0 ? sma[sma.length - 1] : null;\nconst latestEMA = ema.length > 0 ? ema[ema.length - 1] : null;\nconst latestBBands = bbands.length > 0 ? bbands[bbands.length - 1] : null;\nconst latestRSI = rsi.length > 0 ? rsi[rsi.length - 1] : null;\nconst latestATR = atr.length > 0 ? atr[atr.length - 1] : null;\nconst latestMACD = macd.length > 0 ? macd[macd.length - 1] : null;\nconst latestADX = adx.length > 0 ? adx[adx.length - 1] : null;\nconst latestOBV = obv.length > 0 ? obv[obv.length - 1] : null;\nconst latestSupRes = supres.length > 0 ? supres[supres.length - 1] : null;\n\n// Create indicator snapshot array with formatted strings\nconst indicatorSnapshot = [];\n\nif (latestSMA !== null) {\n  indicatorSnapshot.push(`SMA(20): ${latestSMA.toFixed(2)}`);\n}\nif (latestEMA !== null) {\n  indicatorSnapshot.push(`EMA(20): ${latestEMA.toFixed(2)}`);\n}\nif (latestBBands !== null) {\n  indicatorSnapshot.push(`Bollinger Bands - Upper: ${latestBBands.upper.toFixed(2)}, Middle: ${latestBBands.middle.toFixed(2)}, Lower: ${latestBBands.lower.toFixed(2)}`);\n}\nif (latestRSI !== null) {\n  indicatorSnapshot.push(`RSI(14): ${latestRSI.toFixed(2)}`);\n}\nif (latestATR !== null) {\n  indicatorSnapshot.push(`ATR(14): ${latestATR.toFixed(2)}`);\n}\nif (latestMACD !== null) {\n  indicatorSnapshot.push(`MACD: ${latestMACD.macd.toFixed(2)}, Signal: ${latestMACD.signal.toFixed(2)}, Hist: ${latestMACD.histogram.toFixed(2)}`);\n}\nif (latestADX !== null) {\n  indicatorSnapshot.push(`ADX(14): ${latestADX.toFixed(2)}`);\n}\nif (latestOBV !== null) {\n  indicatorSnapshot.push(`OBV: ${latestOBV.toFixed(0)}`);\n}\nif (latestSupRes !== null) {\n  indicatorSnapshot.push(`Key Levels (20): Resistance=${latestSupRes.resistance.toFixed(2)}, Support=${latestSupRes.support.toFixed(2)}`);\n}\n\n// Build prompt with market data\nconst userPrompt = data.userPrompt || '';\nconst basePrompt = `Analyze the following cryptocurrency market data and provide trading insights:\\n\\nCoin: ${coin}\\nExchange: ${exchange}\\nTimeframe: ${timeframe}\\nLatest Close Price: ${latestClose.toFixed(2)}\\n\\nTechnical Indicators:\\n${indicatorSnapshot.join('\\\\n')}`;\n\nconst instruction = userPrompt ? `\\n\\nUser Question/Instruction: ${userPrompt}\\n\\nPlease address the user's specific request in your analysis.` : `\\n\\nProvide a brief analysis of the current market conditions and potential trading signals based on these indicators.`;\n\nconst prompt = basePrompt + instruction;\n\n// Return prompt and pass through all data\nreturn [{\n  json: {\n    ...data,\n    prompt: prompt,\n    indicatorSnapshot: indicatorSnapshot,\n    skipOpenAI: false\n  }\n}];"
            },
            "id": "07fc3441-6466-46e0-87f9-e334b02b6b64",
            "name": "Build Insight Prompt",
            "type": "n8n-nodes-base.code",
            "typeVersion": 2,
            "position": [
                -32,
                336
            ]
        },
        {
            "parameters": {
                "jsCode": "// Normalize candles from various input shapes\nconst input = $input.first().json;\nconst context = $('Normalize Input').first().json;\n\n// Get the original parameters from the context (Normalize Input node)\nconst indicators = context.indicators;\nconst indicatorParams = context.indicatorParams;\nconst coin = context.coin;\nconst exchange = context.exchange;\nconst timeframe = context.timeframe;\nconst candleLimit = context.candleLimit;\nconst userPrompt = context.userPrompt;\n\n// Extract candles from HTTP response (which is in the body field or root level)\nlet rawCandles;\nif (input.body && input.body.candles && Array.isArray(input.body.candles)) {\n  rawCandles = input.body.candles;\n} else if (input.body && input.body.data && Array.isArray(input.body.data)) {\n  rawCandles = input.body.data;\n} else if (input.body && Array.isArray(input.body)) {\n  rawCandles = input.body;\n} else if (input.candles && Array.isArray(input.candles)) {\n  rawCandles = input.candles;\n} else if (input.data && Array.isArray(input.data)) {\n  rawCandles = input.data;\n} else if (Array.isArray(input)) {\n  rawCandles = input;\n} else {\n  throw new Error('No candles found in HTTP response. Expected {body: {candles: []}}, {body: {data: []}}, {candles: []}, {data: []}, or direct array');\n}\n\nif (!rawCandles || rawCandles.length === 0) {\n  throw new Error('Candles array is empty');\n}\n\n// Normalize each candle\nconst normalizedCandles = rawCandles.map(candle => {\n  let timestamp, open, high, low, close, volume;\n  \n  // Handle different field naming conventions\n  if (Array.isArray(candle)) {\n    // Array format: [timestamp, open, high, low, close, volume]\n    timestamp = candle[0];\n    open = candle[1];\n    high = candle[2];\n    low = candle[3];\n    close = candle[4];\n    volume = candle[5];\n  } else {\n    // Object format with named fields\n    timestamp = candle.timestamp || candle.time;\n    open = candle.open;\n    high = candle.high;\n    low = candle.low;\n    close = candle.close;\n    volume = candle.volume;\n  }\n  \n  // Convert timestamp to milliseconds if it's in seconds\n  if (timestamp < 1e12) {\n    timestamp = timestamp * 1000;\n  }\n  \n  return {\n    timestamp,\n    open: parseFloat(open),\n    high: parseFloat(high),\n    low: parseFloat(low),\n    close: parseFloat(close),\n    volume: parseFloat(volume)\n  };\n});\n\n// Sort by timestamp ascending\nnormalizedCandles.sort((a, b) => a.timestamp - b.timestamp);\n\n// Construct Service Indicators Payload\nconst serviceIndicators = indicators.map(ind => {\n  const name = ind.toUpperCase();\n  const params = { ...(indicatorParams[ind] || {}) };\n  // Fix param key casing for BBANDS if needed (service expects stddev)\n  if (name === 'BBANDS' && params.stdDev) {\n    params.stddev = params.stdDev;\n    delete params.stdDev;\n  }\n  return { name, params };\n});\n\n// Pass through parameters from context\nconst output = {\n  userPrompt: userPrompt,\n  candles: normalizedCandles,\n  indicators: indicators,\n  indicatorParams: indicatorParams,\n  serviceIndicators: serviceIndicators,\n  coin: coin,\n  exchange: exchange,\n  timeframe: timeframe,\n  candleLimit: candleLimit\n};\n\nreturn [output];"
            },
            "id": "dc29c072-f691-4f5f-9a74-932c890101a8",
            "name": "Normalize Candles",
            "type": "n8n-nodes-base.code",
            "typeVersion": 2,
            "position": [
                304,
                96
            ]
        },
        {
            "parameters": {
                "jsCode": "// Normalize input from webhook\nconst body = $input.item.json.body || $input.item.json;\n\n// Default indicators\nconst indicators = body.indicators || ['sma', 'ema', 'rsi', 'bbands', 'atr'];\n\n// Default coin and uppercase it\nconst coin = (body.coin || 'BTC').toUpperCase();\n\n// Default exchange and map to API values\nconst exchangeMap = {\n  'Kraken': 'kraken',\n  'Coinbase': 'coinbase',\n  'CoinGecko': 'coingecko',\n  'KuCoin': 'kucoin',\n  'GateIO': 'gateio',\n  'kraken': 'kraken',\n  'coinbase': 'coinbase',\n  'coingecko': 'coingecko',\n  'kucoin': 'kucoin',\n  'gateio': 'gateio'\n};\nconst exchangeInput = body.exchange || 'Kraken';\nconst exchange = exchangeMap[exchangeInput] || exchangeInput.toLowerCase();\n\n// Default timeframe\nconst timeframe = body.timeframe || '1h';\n\n// Default candle limit\nconst candleLimit = body.candleLimit || 200;\n\n// Get API key from body only\nconst apiKey = body.apiKey;\nconst userPrompt = body.userPrompt;\n\n// Validate API key is provided\n// if (!apiKey) {\n//  throw new Error(\"API key is required. Please provide apiKey in // the request body.\");\n// }\n\n// Default indicator parameters\nconst defaultIndicatorParams = {\n  sma: { period: 20 },\n  ema: { period: 20 },\n  bbands: { period: 20, stdDev: 2 },\n  rsi: { period: 14 },\n  atr: { period: 14 },\n  macd: { fast: 12, slow: 26, signal: 9 },\n  adx: { period: 14 },\n  obv: {},\n  support_resistance: { lookback: 20 }\n};\n\n// Merge with provided indicator params\nconst indicatorParams = {\n  sma: { ...defaultIndicatorParams.sma, ...(body.indicatorParams?.sma || {}) },\n  ema: { ...defaultIndicatorParams.ema, ...(body.indicatorParams?.ema || {}) },\n  bbands: { ...defaultIndicatorParams.bbands, ...(body.indicatorParams?.bbands || {}) },\n  rsi: { ...defaultIndicatorParams.rsi, ...(body.indicatorParams?.rsi || {}) },\n  atr: { ...defaultIndicatorParams.atr, ...(body.indicatorParams?.atr || {}) },\n  macd: { ...defaultIndicatorParams.macd, ...(body.indicatorParams?.macd || {}) },\n  adx: { ...defaultIndicatorParams.adx, ...(body.indicatorParams?.adx || {}) },\n  obv: { ...defaultIndicatorParams.obv, ...(body.indicatorParams?.obv || {}) },\n  support_resistance: { ...defaultIndicatorParams.support_resistance, ...(body.indicatorParams?.support_resistance || {}) }\n};\n\n// Return normalized data\nreturn [{\n  json: {\n    indicators,\n    coin,\n    exchange,\n    timeframe,\n    candleLimit,\n    apiKey,\n    userPrompt,\n    indicatorParams\n  }\n}];"
            },
            "id": "130f1350-adac-4dd3-8fd1-e1043f2c8c2e",
            "name": "Normalize Input",
            "type": "n8n-nodes-base.code",
            "typeVersion": 2,
            "position": [
                -240,
                96
            ]
        }
    ],
    "connections": {
        "Webhook": {
            "main": [
                [
                    {
                        "node": "Normalize Input",
                        "type": "main",
                        "index": 0
                    }
                ]
            ]
        },
        "AgnicAI": {
            "main": [
                [
                    {
                        "node": "Build Response JSON",
                        "type": "main",
                        "index": 0
                    }
                ]
            ]
        },
        "AgnicWallet X402": {
            "main": [
                [
                    {
                        "node": "Normalize Candles",
                        "type": "main",
                        "index": 0
                    }
                ]
            ]
        },
        "Compute Indicators": {
            "main": [
                [
                    {
                        "node": "Build Insight Prompt",
                        "type": "main",
                        "index": 0
                    }
                ]
            ]
        },
        "Build Insight Prompt": {
            "main": [
                [
                    {
                        "node": "AgnicAI",
                        "type": "main",
                        "index": 0
                    }
                ]
            ]
        },
        "Normalize Candles": {
            "main": [
                [
                    {
                        "node": "Compute Indicators",
                        "type": "main",
                        "index": 0
                    }
                ]
            ]
        },
        "Normalize Input": {
            "main": [
                [
                    {
                        "node": "AgnicWallet X402",
                        "type": "main",
                        "index": 0
                    }
                ]
            ]
        }
    },
    "pinData": {},
    "meta": {
        "templateCredsSetupCompleted": true,
        "instanceId": "35fdb559a269365838a75ef7f0637433e50004454b8cba8e9dab8bce6c285d11"
    }
}