Skip to main content

Send alerts from Tradingview to Googlesheet via Webhook

 

Of course. Here is your current script, updated to include the ticker-based sheet routing logic.

This version maintains your existing structure and logic for the "Alerts" sheet while adding the new capability to automatically sort each alert into a separate sheet named after its ticker.

Updated Google Apps Script

Replace your current script in the Apps Script editor with this new version.

JavaScript
/**
 * Handles POST requests from TradingView webhooks.
 * It logs every alert to a master "Alerts" sheet.
 * It then finds or creates a ticker-specific sheet and logs the data there as well.
 */
function doPost(e) {
  // Get the main spreadsheet object to work with multiple sheets.
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();

  try {
    // --- MASTER SHEET LOGIC (from your original script) ---
    
    // Get the sheet named "Alerts". This will be our master log.
    const masterSheet = spreadsheet.getSheetByName("Alerts");

    // Check if the sheet was found to prevent errors.
    if (!masterSheet) {
      throw new Error("Sheet named 'Alerts' not found. Please check spelling.");
    }

    // Parse the JSON data from the TradingView alert.
    const data = JSON.parse(e.postData.contents);
    
    // Check for the ticker name, which is essential for routing.
    const tickerName = data.ticker;
    if (!tickerName) {
      throw new Error("Webhook data is missing the 'ticker' field.");
    }
    
    // Prepare a new row with the correct structure and placeholders for signals.
    const newRow = [
      new Date(),           // Timestamp (Column A)
      data.ticker,          // Ticker (Column B)
      data.interval,        // Interval (Column C)
      data.indicator_type,  // Indicator Name (Column D)
      '',                   // Trend (Column E) - Placeholder
      '',                   // Confirm (Column F) - Placeholder
      '',                   // Entry (Column G) - Placeholder
      ''                    // Exit (Column H) - Placeholder
    ];

    // Place the signal in the correct column based on the indicator name.
    switch(data.indicator_type) {
      case 'CTS-Trend':
        newRow[4] = data.signal; // Puts signal in Trend column (E)
        break;
      case 'CTS-RSI':
        newRow[5] = data.signal; // Puts signal in Confirm column (F)
        break;
      case 'CTS-Stochastic':
        newRow[6] = data.signal; // Puts signal in Entry column (G)
        break;
      case 'CTS-Exit':
        newRow[7] = data.signal; // Puts signal in Exit column (H)
        break;
    }

    // Append the fully constructed row to the master "Alerts" sheet.
    masterSheet.appendRow(newRow);

    // --- NEW: TICKER-SPECIFIC SHEET ROUTING LOGIC ---

    // Find a sheet with the name of the ticker (e.g., "BTCUSDT").
    let tickerSheet = spreadsheet.getSheetByName(tickerName);
    
    // If no sheet with that name exists, create and format it.
    if (!tickerSheet) {
      tickerSheet = spreadsheet.insertSheet(tickerName);
      // Define and set the header row for the new sheet.
      const headers = [
        "Timestamp", "Ticker", "Interval", "Indicator", "Trend", "Confirm", "Entry", "Exit"
      ];
      tickerSheet.appendRow(headers);
      // Format headers for better readability.
      tickerSheet.getRange("A1:H1").setFontWeight("bold");
      tickerSheet.setFrozenRows(1);
    }
    
    // Append the same data row to the ticker's specific sheet.
    tickerSheet.appendRow(newRow);

    // --- RESPONSE ---
    
    // Return a success message indicating data was logged in both places.
    return ContentService
      .createTextOutput(JSON.stringify({ "status": "success", "message": `Data logged to 'Alerts' and '${tickerName}'` }))
      .setMimeType(ContentService.MimeType.JSON);

  } catch (error) {
    // Log any errors for debugging and return an error message.
    Logger.log(error.toString());
    return ContentService
      .createTextOutput(JSON.stringify({ "status": "error", "message": error.toString() }))
      .setMimeType(ContentService.MimeType.JSON);
  }
}

What We Changed:

  1. Spreadsheet Variable: The script now gets the entire spreadsheet object at the beginning, allowing it to interact with any sheet, not just "Alerts".

  2.  Variable: It now requires the ticker from your TradingView message and will throw an error if it's missing, as it's crucial for the new logic.

  3. Master Log: Your original logic remains intact. The script first posts the formatted row to your main "Alerts" sheet.

  4. Sheet Creation/Discovery: The new section then checks if a sheet named after the ticker already exists.

    • If not, it creates one, adds a formatted header row, and freezes it.

    • If it does exist, it simply prepares to write to it.

  5. Append to Ticker Sheet: The script appends the same newRow to the ticker-specific sheet.

  6. Updated Success Message: The response sent back to TradingView now confirms that the data was logged to both the master sheet and the specific ticker sheet.

Required Actions:

  1. Save and Deploy: Save this new script and, most importantly, re-deploy it by going to Deploy > New deployment.

  2. Copy New Webhook URL: This deployment will generate a new webhook URL.

  3. Update in TradingView: You must update all of your TradingView alerts to use this new URL for the changes to take effect.

Comments

Popular posts from this blog

Viet Currency - Phan 20

  BASIC INDICATORS   

[VC20] Momentum indicator RSI, ADX

  I. Nguyên Tắc Nền Tảng: Xu Hướng Là Vua Bài Học Sống Còn:  Nguyên tắc quan trọng nhất là phải xác định và đi theo  xu hướng chính (Trend) . Công việc của nhà giao dịch là "dò sóng" và "nương theo sóng", không phải chống lại nó. Tránh Bắt Đỉnh, Dò Đáy:  Đừng cố gắng tìm điểm mua thấp nhất (bottom) và điểm bán cao nhất (top). Thay vào đó, hãy tập trung kiếm lợi nhuận ở  "khúc giữa" của xu hướng  để đảm bảo sự an toàn và bền vững. II. Định Nghĩa Cốt Lõi: Phân Biệt Rõ Trend và Momentum Trend (Xu hướng):  Là  hướng đi  của thị trường (lên, xuống, hoặc đi ngang). Đây là yếu tố quyết định cho việc mua hay bán. Momentum (Động lượng):  Là  Rate of Change  (Tốc độ/Cường độ thay đổi) của giá. Nó được dùng để đo lường  SỨC MẠNH (Strength)  của giá, chứ  không thể dùng để đo hướng đi . III. Cách Sử Dụng Các Chỉ Báo Kỹ Thuật Một Cách Hiệu Quả Luô...

VietCurrency Lesson - Summary version

  Contents LESSON 1 . 1 LESSON 2 . 4 LESSON 3 . 7 LESSON 4 . 10 LESSON 5 . 13 LESSON 6 . 16 LESSON 7 . 18 LESSON 8 . 21     LESSON 1 TÓM TẮT KIẾN THỨC PHÂN TÍCH KỸ THUẬT & THỊ TRƯỜNG (MARKET ANALYSIS) 1. PHÂN LOẠI CHỈ BÁO KỸ THUẬT Các chỉ báo kỹ thuật thường dùng trong trading được chia làm 6 nhóm chính: 1. Chỉ báo biến động (Volatility Indicators) Đo mức độ dao động giá/lợi suất: ATR (Average True Range), Bollinger Bands, Std Deviation, Chalkin's Volatility v.v. 2. Chỉ báo xung lượng (Momentum Indicators) Đo tốc độ, sức mạnh, động lực giá: RSI, CCI, MACD, Stochastic, Williams %R, Momentum v.v. 3. Chỉ báo chu kỳ (Cycle Indicators) Nhận diện tính chu kỳ chuyển động giá: Fibonacci, Detrended Oscillator, Cycle Lines… 4. Chỉ báo cường độ thị trường (Market Strength) Đặc biệt quan tâm đến volume, lực mua bán và các dòng vốn: OBV, MFI, Accumulation/Distribution, Chaikin Mo...