A Google Ads Script to Catch High-CPA Spikes

This script will scan all active ad groups in your account, calculate their performance over the last 7 days, and send you a summary email if any of them exceed your 200€ CPA threshold.

How to use this script:

  1. In Google Ads, go to Tools > Bulk Actions > Scripts.
  2. Click the + button to create a new script.
  3. Paste the code below, replacing your-email@example.com with your actual email address.
  4. Click Authorize and then Run (or set a daily schedule).
function main() {
const EMAIL_ADDRESS = 'your-email@example.com'; // Change this
const CPA_THRESHOLD = 200;
const DATE_RANGE = 'LAST_7_DAYS';
// Array to hold ad groups that exceed the threshold
let alerts = [];
// Query ad groups with costs > 0 to avoid empty data
let adGroupSelector = AdsApp.adGroups()
.withCondition("Status = ENABLED")
.withCondition("CampaignStatus = ENABLED")
.withCondition("Cost > 0")
.forDateRange(DATE_RANGE);
let iterator = adGroupSelector.get();
while (iterator.hasNext()) {
let adGroup = iterator.next();
let stats = adGroup.getStatsFor(DATE_RANGE);
let cost = stats.getCost();
let conversions = stats.getConversions();
// Calculate CPA (Cost / Conversions)
// We check if conversions > 0 to avoid dividing by zero
let cpa = conversions > 0 ? (cost / conversions) : cost;
if (cpa > CPA_THRESHOLD) {
alerts.push({
name: adGroup.getName(),
campaign: adGroup.getCampaign().getName(),
conversions: conversions.toFixed(2),
cost: cost.toFixed(2),
cpa: cpa.toFixed(2)
});
}
}
// Send the email if alerts were found
if (alerts.length > 0) {
sendAlertEmail(alerts, EMAIL_ADDRESS);
} else {
Logger.log("No ad groups exceeded the " + CPA_THRESHOLD + "€ CPA threshold.");
}
}
function sendAlertEmail(alerts, email) {
let subject = 'Google Ads Alert: Ad Group CPA over 200€';
let body = 'The following ad groups have exceeded the CPA threshold in the last 7 days:\n\n';
alerts.forEach(function(item) {
body += "Campaign: " + item.campaign + "\n";
body += "Ad Group: " + item.name + "\n";
body += "Conversions: " + item.conversions + "\n";
body += "Cost: " + item.cost + "€\n";
body += "Current CPA: " + item.cpa + "€\n";
body += "--------------------------------------\n";
});
MailApp.sendEmail(email, subject, body);
Logger.log("Alert email sent to " + email);
}

Important Logic Notes:

  • Zero Conversion Protection: If an ad group has spent money but has 0 conversions, the script treats the total cost as the “CPA” for that period. This ensures you get an alert if an ad group is spending heavily (e.g., spent 250€) without generating any results.
  • Currency: The script uses the numerical value 200. If your account is set to Euro, it will naturally reflect that.
  • Frequency: I recommend scheduling this to run daily. This gives you a rolling 7-day lookback so you catch spikes as soon as they happen.

Leave a Reply

Discover more from rosenberger.marketing

Subscribe now to keep reading and get access to the full archive.

Continue reading