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   

Viet Currency - Phan 21

  Trading technique with ADX        Trong western T/A nó có 4 cái indicators chính mà trên hầu hết các trading desks trên thế giới đều xài. Đó là: MACD, RSI, ADX, và gần đây nữa là CCI. Bên stocks thì MACD là dẫn đầu. MACD, nếu biết xài, thì có thể nói nó đúng chừng 80% trở lên trong US stocks. VN thì tôi không biết. RSI thì tôi không rành lém. Tôi thấy thằng Q đó quờ quạng làm sao ấy. Nhưng có rất nhiều người thề sống chít với nó. Và họ đều là cao thủ hơn tôi, nên tôi không dám chê thằng Q đó nhiều. Vì trong đời tôi gặp ít nhất là 5 cụ. Cụ ở đây có nghĩa là ít gì cũng 50 năm (yeah..50 years on the Street). Cụ nào cũng khen nó còn hơn thuốc Tiên. Có 2 lão dám nói là chỉ cần nhìn RSI thui, không cần nhìn giá mà vẫn trade được như thường. Anyway, thằng thứ 3 là ADX. ADX ở tại Mỹ, nhất là các trading desks mà tôi làm việc khi xưa, đều xài nó cho Currency market. Xin mở dấu hoặc ở đây để phân biệt được cái gọi là currency market và cái gọi là forex marke...

Viet Currency - Phan 22

    5. STOCHASTIC:  Anh VC cho Q hoỉ, nếu nhìn lại năm 2006, 2/8 là đáy, nhưng trong suốt xu hướng giảm giá Momentum giao động thấp nhất là -100. Còn VNI hiện tại, dù chưa giảm nhiều như vậy, nhưng Momentum đã <-100 và đang từ dưới đi lên, điều đó trong PTKT có phản ánh điều gì không?      Momentum nó khác với giá. Nó là sự thay đổi của giá QUA thời gian. Trong một khoảng thời gian nhất định nào đó nếu giá thay đổi nhiều thì momentum sẽ đi xuống và ngược lại. Tôi không xài momentum vì trong giai đoạn này tôi chỉ nhìn trend qua các điểm reactionary points để xác định hướng đi của nó. Khi trend được xác định rồi thì tôi mới xài momentum để dò la sức mạnh của nó. Như cái chart của tôi phía trên, nếu giá đi lên khỏi 1155 hay đi xuống điểm thấp nhất của VNI hôm tuần trước thì lúc đó mới lấy momentum ra đo. Vì lúc đó nó sẽ nói cho tôi biết cái break out (trên 1155) và cái break down có thật sự mạnh hay không? Còn bây giờ chỉ số này chỉ trade trong ...