Automated ad rules
Pause, reactivate or rebudget campaigns, ad sets and ads automatically when their metrics cross a threshold, or get a webhook when they do.
An ad rule checks one ad account's campaigns, ad sets, ads, keywords or search terms on a schedule and acts on each that meets every condition.
It works on Meta, Google, TikTok, LinkedIn, Pinterest, X and Reddit (dashboard: Ads > Rules).
Start from a template
GET /v1/ads/rules/templates returns ready-made rules, each a full rule body.
Their goal groups them: protect (stop losers), scale (budget ladder, duplicate winners, shift budget to winners, Google target CPA room), schedule (night pause, morning restart, midnight reset) and alert.
- Pick one and set
name,accountIdandadAccountId. - Adjust the thresholds to the account: amounts are in its currency.
- Send it to
POST /v1/ads/rulesdisabled, preview it, then enable it.
platforms lists the networks a template works on (null means all). In the dashboard, the create form offers the same templates.
Create a rule
Call POST /v1/ads/rules. This one checks hourly and pauses every ad set with 7-day spend of at least 50 and cost per conversion above 25:
curl -X POST https://zernio.com/api/v1/ads/rules \
-H "Authorization: Bearer $ZERNIO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Pause expensive ad sets",
"accountId": "64f1c2e8a9b3d4e5f6a7b8c9",
"adAccountId": "act_1234567890",
"level": "adset",
"conditions": { "all": [
{ "metric": "cpa", "window": "last_7d", "op": ">", "value": 25 },
{ "metric": "spend", "window": "last_7d", "op": ">=", "value": 50 }
] },
"actions": [{ "type": "pause" }, { "type": "notify" }],
"schedule": { "everyMinutes": 60 },
"enabled": false
}'Returns 201 with the rule. Create it disabled, preview it, then enable it.
| Field | What it does |
|---|---|
accountId | The ads connection from GET /v1/accounts: platform metaads, googleads, tiktokads, linkedinads, pinterestads, xads or redditads. Never a posting account. |
adAccountId | The ad account inside it, from GET /v1/ads/accounts?accountId=<accountId>. Must have selected: true there. |
level | campaign, adset or ad; each object is checked on its own. |
campaignIds | Optional: only these campaigns or their ad sets. Omit for the whole ad account. |
filters | Optional: narrow by name or goal ({ "field": "name", "op": "contains", "value": "Prospecting" }), by id ({ "field": "campaign_id", "op": "not_in", "values": ["123"] }) by age ({ "field": "days_live", "op": ">=", "value": 3 }) by budget level ({ "field": "budget_level", "op": "equals", "value": "campaign" }), by Google campaign type (below) or by a recent change (below). Every filter must hold. |
conditions | all (every condition holds) or any (one is enough), 1 to 10 conditions. |
actions | What to do with each matching object. |
schedule.everyMinutes | Run interval: 15, 30, 60, 180, 360, 720 or 1440. Defaults to 60. |
schedule.times | Instead of an interval, set times each week in the ad account timezone, like [{ "days": ["mon", "fri"], "at": "09:00" }]. |
schedule.startsAt, schedule.endsAt | Optional: the rule only runs between these two times. |
schedule.quietHours | Optional: no runs between from and to each day in the ad account timezone, like { "from": "22:00", "to": "06:00" }. |
cooldownMinutes | Rest period per object after an action. Defaults to 1440. |
A condition compares one metric over one window with a number:
{ "metric": "cpa", "window": "last_7d", "op": ">", "value": 25 }- Metrics:
spend,impressions,clicks,conversions,ctr,cpc,cpm,cpa,roas,reach,frequency.ctris a percentage. Money is in the ad account currency. - Budget:
daily_budgetis the daily budget.budget_usedis spend as a percent of it per day of the window, sotoday>=200 means twice the budget spent. Campaigns and ad sets only. - Reach and frequency use the platform's de-duplicated reach, so they work on Meta and TikTok only. Elsewhere, summed daily reach would overstate both. On Google campaign rules,
frequencyreads Google's own figure (below). - Your own results:
result:<key>reads a metric you send or a formula over it, such asresult:cac_percent, on campaign rules only. A campaign with no value for it never matches. See Send your results per campaign. - Windows:
today,yesterday,last_3d,last_7d,last_14d,last_30d,this_month,last_month. Days follow the ad account's timezone;last_7dis the 7 full days before today, and onlytodayandthis_monthread the day in progress.this_monthruns from the 1st through today, andlast_monthis the whole previous month. - Custom windows:
<from>_to_<to>_days_ago, such as8_to_2_days_ago, reads full days in that range. Use it to skip recent days whose conversions are still arriving. At most 90 days back. - Calendar:
day_of_monthandworking_day_of_monthread today's date in the ad account's timezone. Use them to wait until a month's numbers mean something, such asworking_day_of_month>=5 (Monday to Friday, holidays not counted). They takewindow: "today"and nocompareTo.
This pauses a campaign once its spend this month passes 10,000, from the fifth working day on:
{ "all": [
{ "metric": "spend", "window": "this_month", "op": ">", "value": 10000 },
{ "metric": "working_day_of_month", "window": "today", "op": ">=", "value": 5 }
] }Send alerts through your own Slack and mailbox by listing them on notify:
{ "type": "notify", "send": [{ "accountId": "<slack account>", "channelId": "C0123" }, { "accountId": "<gmail account>", "to": "ops@acme.com" }] }Use op: "top" or "bottom" to act on the best or worst objects instead of a fixed threshold. This matches the 3 ad sets with the highest CPA over the last 7 days:
{ "metric": "cpa", "window": "last_7d", "op": "top", "value": 3 }Add compareTo to compare a metric with its own past. value is then a ratio: this fires when yesterday's CPC is at least twice its average over the 28 days before:
{ "metric": "cpc", "window": "yesterday", "op": ">=", "value": 2, "compareTo": "30_to_2_days_ago" }compareTo: "previous_period" uses the same number of days just before the window. For this_month it is the same days of last month, and for last_month the month before. Counts like spend are compared per day.
compareTo: "usual" compares with the median of the same days on the 4 previous weeks, for windows of up to 7 full days: yesterday against the same weekday.
"of": "usual" reads that usual value itself, to judge only campaigns big enough to matter:
{ "all": [
{ "metric": "conversions", "window": "yesterday", "op": "<=", "value": 0 },
{ "metric": "conversions", "window": "yesterday", "of": "usual", "op": ">=", "value": 2 }
] }compareTo: "usual_deviation" is how many median absolute deviations of the same 4 weeks the window sits from their median.
The deviation counts as at least 5% of the median, so weeks that barely vary (spend held by its budget) do not turn a 1% move into dozens of deviations.
Pair it with a ratio to ignore a campaign's normal swings:
{ "all": [
{ "metric": "spend", "window": "today_so_far", "op": ">=", "value": 1.6, "compareTo": "usual" },
{ "metric": "spend", "window": "today_so_far", "op": ">=", "value": 3, "compareTo": "usual_deviation" }
] }It never matches when those weeks all read 0. Hourly windows also take budget_used, spend as a percent of today's daily budget: today_so_far >= 80 is 80% of the budget spent already.
Hourly windows exist only on ad accounts the hourly sync covers: on any other, saving a rule that uses one returns 400. GET /v1/ads/rules/hourly-windows says which case an ad account is in.
Combine conditions with all and any, and nest groups up to 3 levels and 10 conditions in total.
This pauses an ad set whose CPC is above 2, or that spent 50 today with no conversion:
{
"any": [
{ "metric": "cpc", "window": "today", "op": ">", "value": 2 },
{ "all": [
{ "metric": "spend", "window": "today", "op": ">=", "value": 50 },
{ "metric": "conversions", "window": "today", "op": "<", "value": 1 }
] }
]
}The dashboard edits one all or any list. A rule with nested groups shows them there and is changed through the API.
| Action | What it does |
|---|---|
notify | Sends the ad_rule.triggered webhook with the matched objects. Subscribe an endpoint with POST /v1/webhooks/settings first, or a notify-only rule shows only its run history. |
notify with send | Also sends a short alert to a Slack channel or an email address, through a Slack account or a Gmail, Outlook or IMAP mailbox you connected. Up to 5. |
pause | Pauses the campaign, ad set or ad. |
activate | Reactivates what a rule paused, once the cooldown has passed. With includeManuallyPaused: true, also what you paused. |
adjust_budget | Changes the daily budget. direction: increase or decrease. percent: up to 100 up, 90 down. limit: increases never go above it, decreases never below. Not on ad-level rules. |
adjust_budget with amount | Sets the daily budget to exactly amount, such as a reset every midnight. Not with direction, percent and limit. |
duplicate | Copies the campaign or ad set with its ads, paused unless status is active. Meta and TikTok campaigns and ad sets, LinkedIn campaigns. |
adjust_bid | Moves a Meta ad set's bid cap or cost cap, by a step (direction, percent, limit) or to an exact amount. Ad sets without a cap are skipped. |
adjust_target | Moves a Google campaign's target: cpa (target CPA, in the ad account currency) or roas (target ROAS, a ratio: 3 is 300%), by a step or to an exact amount, inside the bid strategy the campaign is on. Portfolio strategies and strategies without that target are skipped. |
reallocate_budget | Moves daily budget from the matched objects ranked worst to those ranked best. See Move budget to what works. |
edit_name | Tags the name: add puts text like [WINNER] at the start (or the end with at: "end"), remove takes it out. Meta, TikTok and Reddit campaigns, ad sets and ads, and Google, LinkedIn and Pinterest campaigns and ad sets. Pair with a name filter so a second rule acts on tagged objects. |
pause, activate and adjust_budget take an optional maxChangesPerDay (1 to 100): the rule then changes at most that many objects in any 24 hours, across runs.
Every action that changes ads also takes an optional maxChangesPerObject (1 to 100): the rule changes one object at most that many times, counted over 400 days.
Matches over the limit are skipped with daily_limit_reached and tried again later.
Google Search impression share
A Google campaign rule can read the share of Search impressions a campaign won, and the share it lost to budget or ad rank, in percent over the window:
{ "metric": "search_budget_lost_impression_share", "window": "last_7d", "op": ">=", "value": 20 }- Metrics:
search_impression_share,search_budget_lost_impression_share,search_rank_lost_impression_share. A share lost to budget means the campaign runs out of budget before the day ends; a share lost to rank means its bids or ad quality lose auctions. frequencyon Google is the average number of times a person saw the campaign's ads over the window, as Google reports it for Display, Video and Demand Gen campaigns.- They are read live from Google, campaign rules only. They do not go in groups, budget moves or
usual, and a backtest does not replay them. - A campaign Google gives no value for (impression share on a Display campaign) never matches.
- Google reports a share under 10% as 9.99 and a lost share over 90% as 90.01, so a threshold under 10 on
search_impression_share, or over 90 on a lost share, returns400.
Pick campaign types with the channel_type filter, Google rules only:
{ "field": "channel_type", "op": "in", "values": ["DISPLAY", "VIDEO", "DEMAND_GEN"] }Types: SEARCH, DISPLAY, SHOPPING, HOTEL, VIDEO, MULTI_CHANNEL, LOCAL, SMART, PERFORMANCE_MAX, LOCAL_SERVICES, TRAVEL, DEMAND_GEN.
Watch keywords and search terms
On a Google Ads account, level: "keyword" checks each serving keyword and level: "search_term" each search term in each ad group. A keyword's ID is {adGroupId}~{criterionId}, as PATCH /v1/ads/keywords/{keywordId} takes it.
A rule that flags search terms spending without converting, leaving out those you already excluded:
{
"level": "search_term",
"filters": [
{ "field": "search_term_status", "op": "not_in", "values": ["EXCLUDED", "ADDED_EXCLUDED"] },
{ "field": "blocked_by_negative", "op": "equals", "value": false }
],
"conditions": { "all": [
{ "metric": "spend", "window": "last_30d", "op": ">=", "value": 50 },
{ "metric": "conversions", "window": "last_30d", "op": "<=", "value": 0 }
] },
"actions": [{ "type": "notify" }]
}compareTo: "campaign" divides the value by its campaign's over the same window. This one flags terms costing three times the campaign's average click:
{ "metric": "cpc", "window": "last_7d", "op": ">=", "value": 3, "compareTo": "campaign" }- Metrics:
spend,impressions,clicks,conversions,ctr,cpc,cpm,cpa,roas, over daily windows. A count compared with its campaign reads as a share of it. - Unseen: a keyword rule judges every serving keyword, one with no traffic at zero. Google lists only search terms that showed, so a search term rule takes
impressionswith>or>=only. - Filters:
match_type(EXACT,PHRASE,BROAD) andblocked_by_negativeon both, true when a negative on the ad group, campaign or a shared list stops it. Search terms also takesearch_term_status(ADDED,EXCLUDED,ADDED_EXCLUDED,NONE). - Actions: a keyword rule can
notifyandpause; a search term rule only notifies. - Data: Zernio keeps a daily history of each Google account's keywords and search terms. A day keeps its 50,000 rows that spent most. A new rule's first runs load its days a few at a time, and fail with "Loading ... history" until they are in.
- Windows: every daily window,
todayincluded. Today is refreshed at most once an hour, and past days while Google still restates conversions, up to 3 days after they end. - Paused keywords, and keywords in a paused ad group or campaign, are not judged.
- They take no groups, hourly windows,
usual,previous_period,toporbottom, and a backtest or undo does not apply to them. - A run records at most 200 matched objects;
matchedTotalon the run counts them all.
Skip campaigns that just changed
A new budget or bid strategy moves a campaign's numbers for a few days. The days_since_change filter reads the platform's change history, so a rule can wait those days out:
{ "field": "days_since_change", "change": "budget", "op": ">=", "value": 3 }change:budget,bidding,statusorgoal. On Meta, an edit of one of the campaign's ad sets counts for the campaign.op:>=keeps campaigns left alone that long;<picks the ones changed within that many days. A campaign with no change in the history passes>=, unless a very busy account's history was cut short before that many days.value: 1 to 27 days.
It works on campaign rules on Meta and Google. Google records an edit of conversion goals as a campaign update naming no field, so goal reads those.
On Google, a change to a shared (portfolio) bid strategy is not read as a bidding change of its campaigns: only edits on the campaign itself count.
A backtest has no change history, so a rule with this filter matches nothing there. A check that cannot read the history fails, and tries again on its next run.
Move budget to what works
reallocate_budget ranks the objects the rule matched by metric over window, takes budget from the worst from.count and gives it to the best to.count. The total daily budget stays the same.
{
"type": "reallocate_budget",
"metric": "roas",
"window": "last_7d",
"from": { "count": 2 },
"to": { "count": 2 },
"percent": 20,
"maxChangesPerDay": 4
}- How much.
percentof each giver's budget, oramountin all, taken evenly. Receivers share it evenly. - Best end. Lower is better for
cpa,cpc,cpm,frequencyand cost-type results (cost per sale, %CAC), higher otherwise. Setbesttohighestorlowestto change it. An object that spent with no result on a lower-is-better metric ranks worst and only gives. - Bounds. A giver keeps at least
minBudgetand a tenth of its budget. A receiver stays at or undermaxBudget; what receivers cannot take stays with the givers. - Who takes part. Only objects that hold a daily budget at the rule's level: on Meta, campaign rules move CBO budgets and ad set rules move ad set budgets. Google shared budgets are left out. With fewer ranked objects than
fromplusto, givers take at most half. - All or nothing. When
maxChangesPerDaywould hold back any change, none is made. Receivers are raised only after every giver's cut applied; otherwise they fail and the move is tried again on the next run. - Amounts. Moved in the currency's smallest unit: whole yen or won. A move counts as raising spend for the free ads allowance.
- Limits. Not with
lifecycleorgroups. Undo puts back one object's budget at a time.
Judge campaigns as groups
A campaign rule judges each campaign on its own numbers. To decide per product, channel or the whole account instead, add groups.
Each group is a name and filters. A group with no filters holds every campaign the rule checks.
"groups": [
{ "name": "MBA", "filters": [{ "field": "name", "op": "contains", "value": "MBA" }] },
{ "name": "Account total", "filters": [] }
]Each group's spend, conversions and your results are added up across its campaigns, and rates and formulas are computed on the totals.
If the MBA campaigns are at 10%, 75% and 100% %CAC, the MBA is at its total spend over its total revenue, not 75%.
The conditions are judged once per group, and a matching group acts on each of its campaigns, each keeping its own cooldown and daily cap.
- Paused campaigns count toward a group's totals; only the ones the rule may act on change.
- A campaign in several groups is acted on once per run, by the first matching group.
- A campaign with no results sent for the window counts as none: its spend is in the group's total and its revenue is 0. Send a row for every campaign, even with zeros, before a group rule reads your results.
- A rate you send as is (a percent or ratio with no formula) cannot be added up, so it reads as unknown for a group: define it as a formula over counts instead.
- Up to 20 groups. Reach, frequency and impression shares cannot be added up across campaigns, so they are not available with groups.
- The preview lists each group's totals under
groups, and each campaign with thegroupit was judged in.
With this_month, an account-wide spend ceiling is one rule: notify when the Account total group's spend this month passes your forecast.
Alerts instead of every run
Add lifecycle to act and notify once per episode. An object acts only after matching confirmChecks runs in a row, 1 to 5.
"lifecycle": { "confirmChecks": 2, "hold": { "all": [{ "metric": "cpa", "window": "today", "op": ">", "value": 35 }] } }The alert stays open while the conditions or hold match, and is critical while critical matches. It goes back to warning, without a notification, when critical stops matching.
The escalated webhook is sent once per alert. The alert resolves when both clear, after a pause or reactivation, a day after the object stops delivering (not_evaluated), or when the rule changes.
GET /v1/ads/rules/{ruleId}/alerts lists them, and automation.alert.* webhooks announce each change.
Sending lifecycle: null removes it and closes the rule's open alerts.
Preview before you enable
POST /v1/ads/rules/{ruleId}/preview runs the conditions on current metrics without acting. It returns, per object, whether it matches and each condition's actual value, plus the windows' timezone.
A matched object also lists readings: its spend, impressions and clicks over each window the conditions read, so a notification shows the volume behind a match without a condition asking for it.
Enable the rule
Send PATCH /v1/ads/rules/{ruleId} with enabled: true.
curl -X PATCH https://zernio.com/api/v1/ads/rules/RULE_ID \
-H "Authorization: Bearer $ZERNIO_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "enabled": true }'Read the run history
GET /v1/ads/rules/{ruleId}/runs lists runs from the last 31 days, newest first, each with an outcome:
| Outcome | Meaning |
|---|---|
triggered | Objects matched and the rule acted; actedObjectIds lists them. |
no_match | No object met every condition. |
cooldown | Objects matched, but all were in cooldown. |
daily_limit | Objects matched, but the rule had used its maxChangesPerDay. |
paused | The run did not happen: the team used its free automation runs with no payment method on file. |
failed | Metrics unreadable, every action failed, or a notify-only rule's webhook could not be sent. error says why. |
evaluation.notification.status:doneonce the webhook is queued for your subscribed endpoints. With none subscribed it is stilldone, but nothing is delivered.- Not queued:
notificationisfailedwith areason; a notify-only rule's run isfailedtoo. objectsEvaluated: 0: the rule's campaigns and filters matched nothing that is running.evaluation.unreadObjects: on ano_matchrun, how many objects had a value that could not be read. A campaign needs 3 of the 4 previous weeks of data beforeusualreads.
Undo a change
POST /v1/ads/rules/activity/{activityId}/undo puts back a pause, reactivation, budget, bid or target change, or name tag, using an id from GET /v1/ads/rules/activity. The undo shows in the activity feed as a change of its own.
It is refused with 409 when the change was already undone, is a copy, or the object changed since, for example a budget someone edited afterwards.
Write the rule as an automation
/v1/automations serves the same rules in the shape every Zernio automation shares: a trigger, the subjects, the conditions, the steps and the limits.
An automation created there is also an ad rule with the same id, and the reverse. The two name the same things differently:
/v1/ads/rules | /v1/automations |
|---|---|
enabled | status (active, paused) |
lifecycle | alert |
actions, approval | steps |
schedule, cooldownMinutes | trigger, limits.cooldown |
runs, objectsEvaluated | checks, evaluated |
object, objectId | subject |
This is the rule above:
curl -X POST https://zernio.com/api/v1/automations \
-H "Authorization: Bearer $ZERNIO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Pause expensive ad sets",
"trigger": { "type": "schedule", "every": "1h" },
"subjects": { "each": "adset", "adAccounts": [{ "accountId": "64f1c2e8a9b3d4e5f6a7b8c9", "adAccountId": "act_1234567890" }] },
"conditions": { "all": [
{ "metric": "cpa", "window": "last_7d", "op": ">", "value": 25 },
{ "metric": "spend", "window": "last_7d", "op": ">=", "value": 50 }
] },
"steps": [{ "type": "ads.pause" }, { "type": "notify.send" }],
"limits": { "cooldown": "1d" }
}'It starts paused. POST /v1/automations/preview shows what it would match before you save it, and POST /v1/automations/{automationId}/activate turns it on.
When something does not fit, the 400 lists each problem with its path in details.problems. To edit, send the fields you change to PATCH /v1/automations/{automationId} with the version you read as If-Match.
How it behaves
- Combining actions. A rule takes
notify, plus at most one ofpause,activate,adjust_budget,adjust_bid,adjust_target,reallocate_budget,duplicateandedit_name. Those needcooldownMinutesat least as long as the schedule. - Set times follow the ad account timezone, daylight saving included. Without a known timezone they read as UTC.
- End date. After
endsAtthe rule stays enabled but no longer runs. - Metric lag. Metrics are synced from the ad platform and can trail its own reporting.
- Empty rates. A rate with no denominator never matches: a
cpacondition skips objects with no conversions. - Your own pauses.
activateleaves them alone unless the action setsincludeManuallyPaused: true. But if you reactivate then pause an object between two runs, Zernio cannot tell your pause from the rule's and may reactivate it. - Google budgets. Ad groups have no budget, so
adjust_budgetneeds a campaign-level rule. - Batch size. A run changes at most 20 objects; the rest wait for the next run.
maxChangesPerDaycaps it further. - Failed actions get no cooldown, so the next run retries them.
- No ads access pauses all rules until access returns.
- Allowance. Past the free live-ads allowance without a payment method, reactivations and budget increases are skipped (
ads_allowance_exceeded). - Disabling stops runs until you re-enable.
If it fails
| Error | Cause | Fix |
|---|---|---|
403 ads_addon_required | The team has no ads access. | Enable ads on the plan. |
403 ad_account_not_selected | The ad account is not selected on the connection. | Add it in the dashboard picker, or via GET /v1/connect/{platform}/ads with adAccountIds (the full list: it replaces the selection). |
400 invalid_field_value on cooldownMinutes | Cooldown shorter than the schedule on a rule that changes objects. | Raise cooldownMinutes to at least schedule.everyMinutes, or the shortest gap between two schedule.times. |
400 invalid_field_value on actions | adjust_budget on an ad-level rule, or on a Google ad set rule. | Use level: "campaign" (or adset outside Google). |
400 invalid_field_value on conditions | reach or frequency on a network other than Meta or TikTok (Google takes frequency on campaign rules), an impression share off a Google campaign rule, or a result: metric on an ad set or ad rule. | Use another metric on that network, or level: "campaign" for results and Google metrics. |
403 ads_allowance_exceeded | Reactivating or budget-raising rule, team past its free live-ads allowance without a payment method. | Add a payment method. Pausing and lowering rules still work. |
400 invalid_field_value on conditions for a keyword or search term rule | Not a Google Ads account, a metric outside the list above, an hourly window, top or bottom, or a compareTo other than campaign. | Use a Google Ads account and the conditions under Watch keywords and search terms. |
400 invalid_field_value on actions for a keyword or search term rule | An action other than notify (and pause on keywords). | Notify, then act on the platform or through the keyword endpoints. |
| A keyword or search term run fails with "Loading ... history from Google" | A new rule's days are still being fetched, a few per run. | Wait for the next runs, or run it every hour while it loads. |
404 resource_not_found | No such rule, or another team's. | Check the ruleId. |