Pause DSA Targets on Negative Margin: Complete Google Ads Script

Learn how to automatically pause Dynamic Search Ad (DSA) targets based on negative 14-day contribution margin using custom Google Ads Scripts and automation.

By AdTurbo Team · 2026-11-30

Dynamic Search Ads (DSAs) can capture incremental search traffic that keyword campaigns miss. By crawling your website content or an uploaded page feed, Google dynamically pairs real-time user queries with matching landing pages and automatically generated headlines.

However, this algorithmic freedom introduces a major financial vulnerability: DSA targets routinely generate high conversion volume while systematically hemorrhaging net profit. Standard automated bidding strategies optimize toward top-line conversion value or target Return on Ad Spend (ROAS). If a product or category page has high fulfillment overhead, payment processing fees, and aggressive manufacturer wholesale costs, a 350% ROAS might still yield an operating loss.

To safeguard ad spend, advertisers need a robust framework to automatically evaluate dynamic ad targets on unit economics rather than gross revenue. This guide details how to implement an automated dynamic search ad optimization script designed to pause underperforming DSA targets based on a strict 14-day rolling contribution margin rule.

---

Why Dynamic Search Ads Bleed Profit Without Unit-Level Safeguards

Unlike traditional keyword ad groups where you can restrict matching to exact terms, DSA relies on two main targeting types: dynamically indexed landing pages (URL rules, page categories, or All Webpages) and specific URLs supplied via page feeds.

Because the landing page target is the bidding entity rather than an individual search term, cost data aggregates at the target level while query diversity fluctuates beneath it.

The Problem with Gross ROAS Optimization

Google's Smart Bidding optimizes for Gross Conversion Value by default. If your account sells a $400 industrial generator part that carries an 8% gross profit margin, a $50 conversion cost looks exceptional under standard target ROAS parameters (yielding an 800% ROAS). Yet, calculating true net contribution reveals the reality:

• Gross Revenue: $400

• Cost of Goods Sold (COGS): $368

• Gross Margin Before Ads: $32

• Ad Spend: $50

• Net Contribution Margin: -$18

When a dynamic target runs for several weeks under this dynamic, Google's algorithms continue driving volume because gross revenue metrics look healthy. Without an automated safeguard reading true margin thresholds, your budget systematically funds unprofitable sales.

Dissecting Query Bleed and Inventory Shifts

DSA targets also suffer from silent page composition shifts. If an e-commerce category target covers 40 product variations, and the high-margin bestsellers drop out of stock, the DSA target does not pause itself. It continues bidding on remaining low-margin or clearance inventory, funneling spend directly into items incapable of absorbing customer acquisition costs.

If you find your broader account struggling with similar inefficiencies, consult our guide on Google Ads not working to rule out broader campaign structural issues.

---

Dynamic Search Ads vs Day Trading Hotkey Scripts: Clearing the Confusion

If you have researched automated execution scripts or search strings around "pause dsa targets," you may have encountered search results discussing DAS Trader Pro hotkeys, stop-loss orders, and dynamic position sizing. This happens due to algorithmic conflation of the acronyms: DSA (Dynamic Search Ads in Google Ads) and DAS (Direct Access Software Trader Pro).

While the domains are entirely different, high-frequency equity trading hotkeys share the exact same risk mitigation philosophy as automated PPC bidding scripts. Examining these shared principles clarifies why hard stop thresholds are non-negotiable.

| Mechanism | DAS Trader Pro Day Trading Scripts | Google Ads Automated Margin Scripts |

| :--- | :--- | :--- |

| Entry Parameter | Market/Limit execution on technical breakout | Automated matching against indexed website target |

| Sizing Engine | Dynamic Risk-Based Position Sizing (e.g., $20 fixed loss risk) | Automated Bidding (tCPA / tROAS) based on conversion probability |

| Stop Loss Trigger | Order Trigger Orders (OTOs) attaching immediate exit stops | Automated script reading rolling 14-day contribution margin |

| Partial Scaling | Exit 50% at 2R and trail stop loss to breakeven | Lower target bid / demote budget when margin degrades below baseline |

| Discipline Safeguard | Enforcing strict rules to prevent emotional loss-holding | Removing human delay in pausing unprofitable inventory categories |

In both environments, survival depends on eliminating catastrophic downside. In PPC, letting an unprofitable DSA target run for an extra two weeks while waiting for monthly reporting is identical to a day trader refusing to honor a stop-loss order while hoping a tanking stock recovers. Automation provides emotionless execution.

---

The Mathematical Framework: Defining 14-Day Contribution Margin

Before writing an automated script, you must define the formula for contribution margin. Contribution margin reflects the incremental cash remaining after subtracting variable product costs and paid media expenditure from gross sales.

The Metric Definitions

$\text{Contribution Margin (CM)} = \text{Gross Revenue} - \text{COGS} - \text{Variable Fees} - \text{DSA Ad Spend}$

Where:

• Gross Revenue: The conversion value tracked in Google Ads directly attributable to that dynamic target over the trailing 14 calendar days.

• COGS (Cost of Goods Sold): The manufacturing or wholesale cost of the items purchased. This can be ingested dynamically via Google Analytics 4 purchase item parameters, calculated using a static category-level blended margin rate, or matched against an internal database.

• Variable Fees: Credit card gateway fees (typically 2.9% + $0.30 per transaction), warehouse pick/pack labor, and return reserves.

• DSA Ad Spend: The total cost consumed by the dynamic ad target during the exact same 14-day observation window.

Why a 14-Day Evaluation Window?

A single-day or 3-day evaluation window is too volatile for automated dynamic search ad optimization script execution. Conversion delay (lag between ad click and transaction completion) can artificially depress recent margin numbers, leading your script to prematurely pause targets that are generating pending transactions.

Conversely, a 30-day or 60-day window introduces too much lag. A target running an aggressive negative margin over 30 days can consume thousands of dollars in wasted ad spend before triggering an alert.

Fourteen days provides the statistical sweet spot: it dampens weekend variance, smooths standard 24-to-72 hour conversion attribution lag, and provides sufficient click volume to establish statistical significance.

---

Step-by-Step Architecture: How the Optimization Script Operates

Automating the pausing of DSA targets requires a script that connects directly to the Google Ads API via the Google Ads Scripts interface. The system operates on a 5-step procedural pipeline.

[Step 1: Daily Trigger (Schedule)]

│

▼

[Step 2: Query GAQL for Active DSA Targets (14-Day Window)]

│

▼

[Step 3: Extract Metrics (Cost, Conversion Value, Conversions)]

│

▼

[Step 4: Calculate Unit Economics (Revenue - Variable Costs - Spend)]

│

▼

┌─────────────────────────────┐

│ Is 14-Day CM < 0 AND Spend │

│ Minimum Threshold? │

└──────────────┬──────────────┘

│

┌────────┴────────┐

YES NO

│ │

▼ ▼

[Pause DSA Target], [Keep Target Active]

[Log to Sheet], [Document Metrics]

Core Logic Gates

1. Query Filter: The script looks across all enabled Dynamic Search Ad campaigns and extracts dynamic ad targets (adgroupadlabel, webpagecondition, or feeditemtarget) that have experienced spend in the last 14 days.

2. Minimum Spend Barrier: To prevent pausing brand-new targets after a single click, enforce a minimum qualification threshold (e.g., target spend must be greater than at least 1.5x your average target CPA, or a fixed baseline like $100).

3. Calculation Gate: The script calculates net profit. If Conversion Value minus Estimated Operating Expenses minus Ad Spend is less than zero, the condition is met.

4. Execution Action: The script changes the status of the target from ENABLED to PAUSED.

5. Labeling and Audit Logging: The script applies a custom label (e.g., AutoPausedNegativeMargin) and appends a row to an external Google Sheet detailing the timestamp, target URL rule, spend, conversions, gross revenue, and calculated contribution margin deficit.

---

The Complete Google Ads Script: Negative Margin DSA Target Pauser

To run this script, navigate to your Google Ads account, click Tools and Settings Bulk Actions Scripts, create a new script, paste the code below, and update the configuration variables to reflect your business economics.

javascript

/

• Google Ads Script: Pause DSA Targets on Negative 14-Day Contribution Margin

• Author: AdTurbo Operational Playbooks

• Description: Evaluates active dynamic ad targets over a rolling 14-day window.

• Pauses targets producing a negative net contribution margin.

/

const CONFIG = {

// Minimum spend required before evaluating margin (prevents pausing low-data targets)

MINSPENDTHRESHOLD: 75.00,

// Blended average variable margin percentage across inventory (e.g., 0.35 = 35% margin before ad spend)

// If gross revenue is $100, $35 remains after COGS and merchant fees.

ESTIMATEDGROSSMARGINRATE: 0.35,

// Set to true to log actions without actually pausing targets (recommended for initial 7 days)

DRYRUN: true,

// Label to attach to targets paused by this script for easy filtering

PAUSELABEL: 'AutoPausedNegMargin',

// Google Sheet URL for audit trail (leave blank if not using)

AUDITSHEETURL: ''

};

function main() {

ensureLabelExists(CONFIG.PAUSELABEL);

// Query dynamic ad targets active within the past 14 days

// Note: Using Google Ads GAQL via AdsApp.search

const query =

SELECT

adgroupcriterion.resourcename,

adgroupcriterion.criterionid,

adgroup.id,

adgroup.name,

campaign.id,

campaign.name,

adgroupcriterion.webpage.criterionname,

metrics.costmicros,

metrics.conversionsvalue,

metrics.conversions

FROM webpageview

WHERE

campaign.advertisingchanneltype = 'SEARCH'

AND adgroupcriterion.status = 'ENABLED'

AND metrics.costmicros 0

AND segments.date DURING LAST14DAYS

;

const report = AdsApp.search(query);

const targetsToPause = [];

while (report.hasNext()) {

const row = report.next();

const cost = row.metrics.costMicros / 1000000;

const conversionValue = row.metrics.conversionsValue || 0;

const conversions = row.metrics.conversions || 0;

const targetName = row.adGroupCriterion.webpage.criterionName || 'Entire Site';

const campaignName = row.campaign.name;

const adGroupName = row.adGroup.name;

// Verify minimum data baseline

if (cost < CONFIG.MINSPENDTHRESHOLD) {

continue;

}

// Compute financial economics

const grossProfitBeforeAds = conversionValue CONFIG.ESTIMATEDGROSSMARGINRATE;

const contributionMargin = grossProfitBeforeAds - cost;

// Evaluation: Did this target produce an absolute cash loss?

if (contributionMargin < 0) {

targetsToPause.push({

campaignId: row.campaign.id,

adGroupId: row.adGroup.id,

criterionId: row.adGroupCriterion.criterionId,

campaignName: campaignName,

adGroupName: adGroupName,

targetName: targetName,

cost: cost.toFixed(2),

revenue: conversionValue.toFixed(2),

contributionMargin: contributionMargin.toFixed(2),

conversions: conversions

});

}

}

Logger.log(Identified ${targetsToPause.length} DSA target(s) producing negative contribution margin.);

// Execute status adjustments

for (const item of targetsToPause) {

Logger.log(Target: "${item.targetName}" | Spend: ${item.cost} | Rev: ${item.revenue} | CM: -${Math.abs(item.contributionMargin)});

if (!CONFIG.DRYRUN) {

pauseDsaTarget(item.campaignId, item.adGroupId, item.criterionId);

} else {

Logger.log([DRY RUN] Would have paused criterion ${item.criterionId} in ad group "${item.adGroupName}");

}

}

if (CONFIG.AUDITSHEETURL && targetsToPause.length 0) {

logToSpreadsheet(targetsToPause);

}

}

function pauseDsaTarget(campaignId, adGroupId, criterionId) {

const webpageIterator = AdsApp.targeting()

.webpages()

.withIds([[adGroupId, criterionId]])

.get();

if (webpageIterator.hasNext()) {

const webpage = webpageIterator.next();

webpage.pause();

webpage.applyLabel(CONFIG.PAUSELABEL);

Logger.log(Successfully paused and labeled criterion: ${criterionId});

}

}

function ensureLabelExists(labelName) {

const labelIterator = AdsApp.labels().withCondition(Name = '${labelName}').get();

if (!labelIterator.hasNext()) {

AdsApp.createLabel(labelName, 'Dynamic targets auto-paused due to negative net margins', 'D9381E');

}

}

function logToSpreadsheet(records) {

try {

const ss = SpreadsheetApp.openByUrl(CONFIG.AUDITSHEETURL);

const sheet = ss.getActiveSheet();

const timestamp = new Date();

records.forEach(r = {

sheet.appendRow([

timestamp,

r.campaignName,

r.adGroupName,

r.targetName,

r.cost,

r.revenue,

r.contributionMargin,

r.conversions,

CONFIG.DRYRUN ? 'DRYRUN' : 'PAUSED'

]);

});

} catch (e) {

Logger.log(Error writing to spreadsheet: ${e.message});

}

}

---

Strategic Implementation and Configuration Best Practices

Deploying an execution script directly into an active account requires careful operational setup. If configured carelessly, you risk pausing core targets during standard seasonal fluctuations or reporting delays.

1. Run in Dry-Run Mode for 7 to 10 Days

Before switching DRYRUN: false, run the script daily in test mode. Review the execution logs in the Google Ads Scripts interface. Verify that the targets marked for pausing are genuinely unprofitable targets rather than top-funnel converters that had a single bad weekend.

2. Segment Margins by Campaign Architecture

E-commerce accounts rarely feature a uniform gross margin across the entire site. Electronics may have a 12% gross margin, while replacement accessories enjoy a 65% gross margin.

If you use a single blended margin rate across an entire account, the script will over-punish lower-margin categories and under-protect higher-margin categories. Structure your DSA campaigns by margin tiers, then run tailored script instances with campaign name filters and distinct ESTIMATEDGROSSMARGINRATE thresholds for each.

3. Exclude Search Query Anomalies via Negatives First

Often, an entire dynamic target is not fundamentally flawed; rather, a handful of hyper-expensive, misaligned search terms are draining the budget. Before letting the script pause an entire landing page category, check the underlying queries.

Reviewing our step-by-step walkthrough on how to find negative keywords and executing the strategies in our search terms report guide can rescue a high-potential DSA target before the script terminates it.

---

Common Pitfalls That Break Automated Ad Scripts

Automated scripts execute exact commands. Minor structural or analytical miscalculations can derail your automation:

• Ignoring Conversion Attribution Lag: If your typical sales cycle involves a 48-hour delay between click and checkout, evaluating the last 14 days without an offset window will penalize the most recent 2 days. For long sales cycles, modify the GAQL date segment to evaluate DURING LAST30DAYS or implement an offset query (segments.date BETWEEN '2026-03-01' AND '2026-03-15').

• Script Execution Timeouts: Google Ads Scripts feature a 30-minute maximum runtime per execution. In enterprise accounts with tens of thousands of webpage targets, querying all webpageview criteria simultaneously can cause a timeout. Add campaign name conditions (e.g., AND campaign.name LIKE '%DSA%') to narrow script scope.

• Failing to Create a Reactivation Protocol: The script pauses targets, but it does not automatically unpause them if product pricing or supply chain costs improve. Establish a bi-weekly optimization ritual using our Google Ads optimization checklist to review paused targets, fix root causes, and re-enable them for re-testing.

• Missing Account Authorization Revocations: Scripts run under the user credentials of the account administrator who authenticated them. If that employee leaves your organization or their Google account is modified, the script silently terminates without warning notifications.

---

Modernizing Dynamic Ad Optimization with AI Management

Custom JavaScript snippets deliver reliable protection for specific rule-based tasks. However, maintaining scripts across scaling accounts, modifying margin variables by category, and continuously updating negative keyword lists introduces ongoing overhead.

Modern paid search teams are increasingly transitioning from brittle, isolated code snippets to comprehensive Google Ads automation engines. Rather than managing isolated formulas for target pausing, automated systems continuously monitor full-funnel economics, balancing target exclusions, budget reallocations, and bid management simultaneously.

If your team is evaluating whether to rely solely on internal scripts or implement automated management systems, explore our platform overview on ppc management software or read our deep dive comparing an AI vs human Google Ads manager.

Specialized autonomous tools like AdTurbo (starting at $149/mo with a 7-day trial) eliminate the need to write and troubleshoot custom API scripts. By analyzing real-time conversion trends and unit margin inputs directly, intelligent management tools automatically throttle unprofitable targets and redistribute spend to profitable inventory categories without manual scripting.

---

Related Guides

• PPC Campaign Management: A Complete Guide for 2026

• PPC Audit Checklist: 12 Steps to Fix a Leaking Google Ads Account

• How to Use the Google Ads Search Terms Report to Cut Wasted Spend

---

Frequently Asked Questions

How often should this DSA negative margin script run?

Run the script once daily, preferably during early morning hours (between 2:00 AM and 4:00 AM account time). Daily execution ensures the script catches targets that slip into negative 14-day territory as soon as possible without hitting Google Ads API quota limits.

Can this script pause standard keyword ad groups too?

This specific script queries the webpageview resource, which applies exclusively to Dynamic Search Ad targets. To evaluate standard keyword campaigns on contribution margin, the GAQL query must be rewritten to query the keywordview resource and update adgroupcriterion.status for traditional search criteria.

Will pausing an underperforming dynamic ad target hurt account Quality Score?

No, pausing an unprofitable dynamic ad target does not negatively impact account Quality Score. In fact, cutting low-performing targets that suffer from poor user engagement, high bounce rates, or weak conversion rates preserves ad spend and directs budget toward your highest-performing assets.

How do I reactivate a dynamic target after fixing on-page conversion issues?

Filter your campaign by dynamic targets containing the custom label (AutoPausedNegMargin). Once you have resolved page performance issues, adjusted pricing, or added targeted negative keywords, simply remove the label and toggle the status back to ENABLED to restart testing.