Saltar al contenido principal

Tracker campaign auto-optimization

A tracker campaign splits traffic between its targets — offers, PWAs, landings — by weights. Auto-optimization moves those weights by itself: the target that brings more money per visitor gets a bigger share, the weaker one gets less, and a target that collects visitors without a single deposit is switched off.

In Qubix this is not a separate screen with a fixed set of options. It is a script that runs on a schedule: you describe the rule in plain words to the AI assistant — which numbers to look at, over what period, how far a weight may move — the assistant writes the code, and every run of the script recalculates the weights and saves the campaign with the QubApp.mcp command. The script works with your rights: it can change only a campaign you can change in the panel yourself.

How it works​

Weights are read the same way as when you set them by hand: within a rule the traffic is split between the targets in proportion to their weights, and a target with the weight 0 gets no visitors while the rule has a target with weight — it is a reserve (Funnel and traffic distribution).

Returning visitors keep their target

A visitor who has already been to the campaign is sent to the same target again, as long as that target's weight is above zero. So new weights change the split of new visitors at once, and returning ones move only when their target gets the weight 0.

What you need​

  • A tracker campaign whose rule has two or more targets with weights — see Funnel and traffic distribution.
  • Deposits arriving by postback with an amount: the script compares targets by the money their visitors brought. A deposit counts when it is above the minimum deposit amount, the same as in the reports.
  • The right Gestionar campañas del tracker in the permission template of the script's owner, and the campaign has to be one this person may change. Which campaigns those are, the template decides — all of them, the team's or only their own, the same as when editing the campaign in the panel; an administrator may change any.
  • Statistics the owner can see. The script reads visits and deposits with an sql query, with its owner's rights. An administrator's script counts every visit of the campaign. For an owner who is not an administrator the query sees only the events of the ads this owner may see: a visit whose link carries no ad identifier, the identifier of an ad Qubix does not know, or of an ad outside the owner's reach, is not counted — and neither is its deposit. If the campaign gets such traffic, let an administrator create the script.
  • The MCP/API interface in the plan of the installation: QubApp.mcp works only then.

Setting it up step by step​

  1. Open the Scripts section and click + Crear script.

  2. Open the assistant panel of the window — the "AI" button in the title bar — and describe the task in your own words. For example:

    Write a script that optimizes tracker campaign 1e6ad6b8-edfe-4f6a-b3c0-361512348568. For each rule, count over the last 24 hours the visitors and the deposit revenue of every target, and set the weights in proportion to revenue per visitor. Each target keeps at least 10%. Leave a rule as it is while any of its targets has fewer than 20 visitors. Save the campaign with QubApp.mcp.campaign_save only when some weight moves by 5 points or more, and print what changed. Add a DRY_RUN switch that only prints the new weights.

    The identifier of a campaign is at the end of the address of its card in the Campañas section, after #/campaigns/.

    The code in the answer stands in a block; in the header of the block there is an insert icon with the tooltip Insertar en el editor: … — the dots stand for the screen. Click the icon: the code replaces the code in the editor. You can also paste the ready script from the section below instead of asking.

  3. Check the code: the campaign identifier, the window, the thresholds. What each setting means — in The script.

  4. Leave DRY_RUN = true, click Guardar and then Ejecutar. The console shows which weights the script would set and why — nothing is saved yet.

  5. When the numbers look right, set DRY_RUN = false and save the script.

  6. In the Programación section, enter */15 * * * * — every 15 minutes — and click +. Turn on the Activo toggle and save.

  7. Follow the result: every run with its console lines is kept in the Ejecuciones section of the script, and the current weights are in the campaign's own editor.

The Run now button changes the campaign

With DRY_RUN = false the Ejecutar button saves the new weights for real, just like a run on the schedule. Test new code with DRY_RUN = true.

The script: weights by revenue per visitor​

JavaScript
// Tracker campaign auto-optimization: each run shifts the traffic split of every rule
// toward the targets that bring more revenue per visitor.
const CAMPAIGN_ID = '1e6ad6b8-edfe-4f6a-b3c0-361512348568'; // the tracker campaign to optimize
const WINDOW_HOURS = 24; // how far back to count visitors and deposits
const MIN_VISITORS = 20; // a target with fewer visitors leaves its rule as it is
const MIN_WEIGHT = 10; // no target drops below this share: it keeps collecting data
const MIN_CHANGE = 5; // the split is saved only when some weight moves by this many points
const DRY_RUN = true; // true — only print the new weights; false — save them

function main() {
const row = sql`SELECT rules FROM campaigns FINAL WHERE campaign_id = ${CAMPAIGN_ID}`[0];
if (!row) {
console.log('campaign not found');
return;
}
const rules = JSON.parse(row.rules);

// Visitors and deposit revenue of each target over the window.
const stats = {};
sql`
WITH (SELECT threshold FROM v_deposits_min_revenue) AS dep_min
SELECT v.tid AS target_id, uniqExact(v.piuid) AS visitors, sum(d.revenue) AS revenue
FROM (SELECT piuid, any(target_id) AS tid FROM qubix_events
WHERE campaign_id = ${CAMPAIGN_ID} AND event IN ('campaign_visit', 'render')
AND target_id != '' AND event_time > now() - INTERVAL ${WINDOW_HOURS} HOUR
GROUP BY piuid) AS v
LEFT JOIN (SELECT piuid, sum(revenue_usd * if(edition = 'cancel', -1, 1)) AS revenue FROM qubix_events
WHERE event = 'dep' AND revenue_usd > dep_min
AND event_time > now() - INTERVAL ${WINDOW_HOURS} HOUR
GROUP BY piuid) AS d ON d.piuid = v.piuid
GROUP BY target_id`.forEach((r) => { stats[r.target_id] = r; });

let changed = false;
rules.forEach((rule, ri) => {
const live = (rule.targets || []).filter((t) => t.weight > 0); // weight 0 is a reserve: left alone
if (live.length < 2) return;
const epv = [];
for (let i = 0; i < live.length; i++) {
const s = stats[live[i].uuid];
if (!s || Number(s.visitors) < MIN_VISITORS) {
console.log('rule', ri + 1, '— not enough visitors yet');
return;
}
epv.push(Number(s.revenue) / Number(s.visitors));
}
const total = epv.reduce((a, b) => a + b, 0);
if (total <= 0) {
console.log('rule', ri + 1, '— no deposits yet');
return;
}
// Each target keeps the floor; the rest of the 100 points goes in proportion to revenue per visitor.
const floor = Math.min(MIN_WEIGHT, Math.floor(50 / live.length));
const free = 100 - floor * live.length;
const raw = epv.map((e) => floor + free * e / total);
const next = raw.map(Math.floor);
const rest = 100 - next.reduce((a, b) => a + b, 0);
raw.map((r, i) => [r - next[i], i]).sort((x, y) => y[0] - x[0]).slice(0, rest).forEach((p) => { next[p[1]]++; });
if (!live.some((t, i) => Math.abs(t.weight - next[i]) >= MIN_CHANGE)) {
console.log('rule', ri + 1, '— weights already fit');
return;
}
live.forEach((t, i) => {
console.log('rule', ri + 1, 'target', t.uuid.slice(0, 8), t.weight + '% →', next[i] + '%',
'revenue per visitor', epv[i].toFixed(2));
t.weight = next[i];
});
changed = true;
});

if (!changed) return;
if (DRY_RUN) {
console.log('dry run: nothing saved');
return;
}
const saved = QubApp.mcp.campaign_save({ id: CAMPAIGN_ID, rules: JSON.stringify(rules) });
console.log('saved:', saved.success);
}
SettingWhat it sets
CAMPAIGN_IDthe identifier of the tracker campaign
WINDOW_HOURSover how many recent hours visitors and deposits are counted
MIN_VISITORShow many visitors each target needs before its rule is recalculated: with fewer, chance decides more than the offer
MIN_WEIGHTthe share no target drops below, so that a weak target keeps getting visitors and can show it improved; with many targets the floor is lowered so that the floors together take no more than half of the traffic
MIN_CHANGEby how many points some weight must move for the campaign to be saved; smaller moves are noise, and the campaign is not re-saved every 15 minutes because of them
DRY_RUNtrue — only print; false — save

How the new weights are calculated:

  • only targets with a weight above zero take part; a target with the weight 0 stays a reserve, and the script does not bring it back;
  • revenue per visitor of a target is the sum of the deposits of its visitors over the window divided by the number of its visitors; one visitor is counted once, however many pages they saw;
  • every target gets the floor, and the rest of the 100 points is divided in proportion to revenue per visitor; rounding keeps the sum of the weights at exactly 100;
  • a rule is left as it is while any of its targets lacks visitors or none of them has deposits, and the console says which of the two it is.

The visitors and deposits are counted from the events of the campaign: its arrivals (campaign_visit and render) and the deposits (dep) of the same visitors — what each of these events means is in the event reference. The rules are read with an sql query and written back with QubApp.mcp.campaign_save together with the identifiers of the targets: the statistics of a target is tied to its identifier, so the script changes only the weights.

What a run shows​

A run that changed the split prints one line per target and the result of the save:

rule 1 target 7a616823 50% → 72% revenue per visitor 2.40
rule 1 target 263cbf1c 50% → 28% revenue per visitor 0.69
saved: true

A run that changed nothing names the reason: rule 1 — not enough visitors yet, rule 1 — no deposits yet or rule 1 — weights already fit.

On a test campaign with two offers at 50/50, 80 visitors and deposits of $500 on one offer against $50 on the other, the script moved the split to 82/18; of the next 200 visitors 165 went to the first offer.

The second script: switching off targets without deposits​

A different rule in words — "switch off a target that got 300 visitors over a day and not a single deposit, and give its share to the others" — gives a script like this:

JavaScript
// Switches off the targets that got enough visitors over the window and not a single deposit:
// their weight becomes 0, and their share goes to the other targets of the rule.
const CAMPAIGN_ID = '1e6ad6b8-edfe-4f6a-b3c0-361512348568'; // the tracker campaign to watch
const WINDOW_HOURS = 24; // how far back to count visitors and deposits
const OFF_AFTER_VISITORS = 300; // this many visitors without a deposit switch a target off
const DRY_RUN = true; // true — only print what would change; false — save it

function main() {
const row = sql`SELECT rules FROM campaigns FINAL WHERE campaign_id = ${CAMPAIGN_ID}`[0];
if (!row) {
console.log('campaign not found');
return;
}
const rules = JSON.parse(row.rules);

const stats = {};
sql`
WITH (SELECT threshold FROM v_deposits_min_revenue) AS dep_min
SELECT v.tid AS target_id, uniqExact(v.piuid) AS visitors, sum(d.revenue) AS revenue
FROM (SELECT piuid, any(target_id) AS tid FROM qubix_events
WHERE campaign_id = ${CAMPAIGN_ID} AND event IN ('campaign_visit', 'render')
AND target_id != '' AND event_time > now() - INTERVAL ${WINDOW_HOURS} HOUR
GROUP BY piuid) AS v
LEFT JOIN (SELECT piuid, sum(revenue_usd * if(edition = 'cancel', -1, 1)) AS revenue FROM qubix_events
WHERE event = 'dep' AND revenue_usd > dep_min
AND event_time > now() - INTERVAL ${WINDOW_HOURS} HOUR
GROUP BY piuid) AS d ON d.piuid = v.piuid
GROUP BY target_id`.forEach((r) => { stats[r.target_id] = r; });

let changed = false;
rules.forEach((rule, ri) => {
const live = (rule.targets || []).filter((t) => t.weight > 0);
const off = live.filter((t) => {
const s = stats[t.uuid];
return s && Number(s.visitors) >= OFF_AFTER_VISITORS && Number(s.revenue) === 0;
});
// At least one target keeps its weight: with every target at 0 the whole rule would go to the first of them.
if (off.length === 0 || off.length === live.length) return;
const keep = live.filter((t) => off.indexOf(t) < 0);
const freed = off.reduce((a, t) => a + t.weight, 0);
const kept = keep.reduce((a, t) => a + t.weight, 0);
off.forEach((t) => {
console.log('rule', ri + 1, 'target', t.uuid.slice(0, 8), t.weight + '% → 0%:',
stats[t.uuid].visitors, 'visitors, no deposits');
t.weight = 0;
});
let given = 0;
keep.forEach((t, i) => {
const add = i === keep.length - 1 ? freed - given : Math.floor(freed * t.weight / kept);
given += add;
console.log('rule', ri + 1, 'target', t.uuid.slice(0, 8), t.weight + '% →', (t.weight + add) + '%');
t.weight += add;
});
changed = true;
});

if (!changed) {
console.log('nothing to switch off');
return;
}
if (DRY_RUN) {
console.log('dry run: nothing saved');
return;
}
const saved = QubApp.mcp.campaign_save({ id: CAMPAIGN_ID, rules: JSON.stringify(rules) });
console.log('saved:', saved.success);
}

The freed share goes to the remaining targets in proportion to their weights: a split of 40/30/30 where the third target has no deposits becomes 57/43/0. A switched-off target gets no new visitors, and its returning visitors are moved to the targets with weight. To bring the target back, give it a weight in the campaign editor.

Run one script per campaign: each run saves the whole set of rules it read, so two scripts on the same campaign with the same schedule overwrite each other — a target the second one switched off can come back with the weight the first one read. To do both, ask the assistant for one script that first switches off and then shifts the weights.

Other rules — ask for them in words​

The assistant writes the code from a description, so the rule is yours to choose. Requests that change the scripts above:

  • "Compare the targets by deposits per visitor rather than by revenue" — when the payouts are equal and what matters is the number of deposits.
  • "Count over the last 6 hours, but only when there are at least 50 visitors on each target" — a faster reaction for high traffic.
  • "Do the same for all my active tracker campaigns, not for one" — then one run saves several campaigns: each save is one tool call, and one run may make as many calls as the Llamadas a herramientas por ejecución setting allows, 20 by default (see Qubix tools from code).
  • "Give at most 80% to a single target" — a cap on top of the floor.

Whatever the rule, start with DRY_RUN = true and look at the console: it shows the decision before it touches the campaign.

Limits and refusals​

  • The script saves the campaign with the rights of its owner. Without the Gestionar campañas del tracker right the save is refused with "You do not have the right to do this. …"; a campaign the owner sees but may not change, with "You are not allowed to edit this campaign."; a campaign the owner does not see is answered as one that does not exist. A refusal the code does not catch ends the run with an error.
  • QubApp.mcp works only in code the script's owner or an administrator changed and saved; an unsaved edit run with the Ejecutar button is refused too. All the refusals are listed in Qubix tools from code.
  • A run has a time limit, 30 seconds by default (Time limit of a run); one campaign and two queries fit into it with a large margin.

What's next​