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

Process to dev google script

Since you are building a mission-critical application (trading signals), managing versions and bugs is essential to avoid "losing" orders or making execution errors. Here is the professional process you should follow to manage your Google Apps Script project. 1. Version Control: Stop Coding in the Browser Developing directly in the Google Script Editor is risky because there is no "Undo" for mistakes made yesterday. Use clasp (Command Line Apps Script Projects): This tool allows you to develop locally on your computer.[ 1 ][ 2 ][ 3 ][ 4 ] Git & GitHub: Once the code is on your computer, use Git. Workflow: Code locally      git commit (saves your progress)          clasp push (uploads to Google). Why? If a new update breaks your TradingView alert processing, you can revert to a previous working version in seconds. 2. Manage Environments (Dev vs. Production) Never test new code on the sa...

CTS-Entry plan

 Excellent. This is a classic and highly effective top-down analysis workflow. Using the higher timeframes for direction and the lower timeframes for precision is how many professional traders operate. Let's refine your entry process for the M15 and M5 charts. The Golden Rule for M15/M5 Entries You never use the M15 or M5 to decide on the trend direction. Their only purpose is to provide a low-risk entry point after your H1/M30 analysis has already given you the green light. You are zooming in to find the exact moment momentum is shifting in your favor. Price Action Entries on M15 / M5 Let's apply this to your trading plan. Primary Scenario: Selling (Short) You have already determined from H1/M30 that you are waiting for either a breakdown or a pullback. A) If you are waiting for the BREAKDOWN below 3,383.16 : Your H1 analysis is telling you "get ready to sell if 3,383.16 fails." Price on the H1 chart breaks and closes below 3,383.16 . This is your confirmation. N...

Moving Averages Part 2

  Moving Averages Part 2 Hi everyone, this is Ty Young with Surefire-Trading.com. In our last lesson, MA Method Part 1 , we demonstrated how Moving Averages could be incorporated to safely initiate a more conservative entry at the lower time frames. As you may remember, due to the lagging effects of the EMA, our primary strategy consisted of using retracements to signal high probability trades.  Though this is a great way to trade for those who like to capture quicker, yet, smaller gains from the market, there are those who prefer to remain with a trade for longer periods of time – extracting larger gains. This lesson addresses such a strategy.  Now, don’t get me wrong, the retracement approach also can be used to signal entries at the higher time frames, which I use frequently; however, generally speaking, if you wait for an EMA retracement on a long-term chart, a greater portion of your potential gains can or will be missed entirely.  And though I would love to say...