Hello,
I have implemented a script in order to control ad spend on an account which varies wildly from one day to the next, causing all kinds of sales headaches.
The site uses mainly shopping campaigns (although I'd want it to work for search & PMAX campaigns too).
The aim of the script would be to turn off a campaign if it overspent by 20% & then turn it back on the next day.
I'm running it every hour.
Yesterday, one of my campaigns spent twice its daily budget (which Google allows but which doesn't help the client). Can you let me know what might be wrong please?
Thanks
config = {
overdeliveryThreshold: '20%', // The maximum over budget the campaign can go before it gets paused
accounts: ['XXX-XXX-XXXX'] // The accounts in this MCC the script will run on, ignore if using on a single account - I have added the client's account number here
}
function main() {
try {
AdsManagerApp.accounts().withIds(config.accounts).executeInParallel('pauseOverspendingCampaigns');
} catch(e) {
pauseOverspendingCampaigns();
}
}
function pauseOverspendingCampaigns() {
var labelName = 'Paused - Budget Overdelivery';
// Unpause any campaigns that were previously paused
var date = Utilities.formatDate(new Date(), AdsApp.currentAccount().getTimeZone(), 'MMMM dd, yyyy HH:mm:ss Z');
var hour = parseFloat(date.split(' ')[3].substring(0, 2));
if (hour < 3) {
var campaigns = AdsApp.campaigns().withCondition('LabelNames CONTAINS_ANY ["' + labelName +'"]').get();
while (campaigns.hasNext()) {
var campaign = campaigns.next();
campaign.removeLabel(labelName);
campaign.enable();
}
}
// If the label already doesn't exist, create it
if (AdsApp.labels().withCondition('Name = "' + labelName + '"').get().totalNumEntities() === 0) AdsApp.createLabel(labelName);
// Iterate through campaigns and check for any that are overspending
var campaigns = AdsApp.campaigns().forDateRange('TODAY').withCondition('Cost > 0 AND Status = ENABLED').get();
while (campaigns.hasNext()) {
var campaign = campaigns.next();
var budget = campaign.getBudget().getAmount();
var cost = campaign.getStatsFor('TODAY').getCost();
var threshold = (parseFloat(config.overdeliveryThreshold.replace('%', '')) / 100) + 1;
var maxSpend = budget * threshold;
if (cost > maxSpend) {
campaign.applyLabel(labelName);
campaign.pause();
}
}
}