Daily rank tracking with the standard queue

Track a domain's Google positions for a keyword list every day at the standard queue price, collecting results with tasks_ready and storing them in SQLite.
Open as Markdown

This script posts one task per keyword to the standard queue, collects the results as they finish, and records where your domain ranks. Run it once a day from cron.

Cost: $0.00054 per keyword at depth 10, or $0.0054 at depth 100 (10 pages of 10). 500 keywords at depth 100 is $2.70 a day. With auto_upgrade: false, a task whose included sources fail costs $0 instead of falling back to the live price.

You need: Python 3.9+, requests, and DATAFORGAIO_API_KEY in the environment.

rank_tracker.py
import datetime as dt
import os
import sqlite3
import time
 
import requests
 
BASE = "https://api.dataforgaio.com/v1"
AUTH = ("api", os.environ["DATAFORGAIO_API_KEY"])
DOMAIN = "example.com"          # the domain you track
LOCATION_CODE = 2840            # United States
LANGUAGE = "en"
DEPTH = 100
KEYWORDS = [
    "trail running shoes",
    "waterproof hiking boots",
    "lightweight running vest",
]
 
db = sqlite3.connect("ranks.db")
db.execute("""create table if not exists ranks (
    day text, keyword text, position integer, url text,
    cost real, fetched_at text, cache_hit integer,
    primary key (day, keyword))""")
 
today = dt.date.today().isoformat()
 
 
def post_tasks():
    """Queue today's tasks; return {task_id: keyword}."""
    done = {row[0] for row in db.execute("select keyword from ranks where day = ?", (today,))}
    todo = [k for k in KEYWORDS if k not in done]
    ids = {}
    for i in range(0, len(todo), 100):
        tasks = [{
            "keyword": kw,
            "location_code": LOCATION_CODE,
            "language_code": LANGUAGE,
            "depth": DEPTH,
            "priority": 1,
            "auto_upgrade": False,
            "tag": f"{today}:{kw}"[:255],
        } for kw in todo[i:i + 100]]
        body = requests.post(f"{BASE}/serp/google/organic/task_post", auth=AUTH, json=tasks, timeout=60).json()
        if body["status_code"] != 20000:
            raise SystemExit(f'{body["status_code"]}: {body["status_message"]}')
        for t in body["tasks"]:
            if t["status_code"] == 20100:
                ids[t["id"]] = t["data"]["keyword"]
            else:
                print("not queued:", t["data"].get("keyword"), t["status_code"], t["status_message"])
    return ids
 
 
def record(keyword, task):
    result = (task.get("result") or [{}])[0]
    hit = next((i for i in result.get("items") or [] if (i.get("domain") or "").endswith(DOMAIN)), None)
    db.execute(
        "insert or replace into ranks values (?, ?, ?, ?, ?, ?, ?)",
        (today, keyword, hit["rank_absolute"] if hit else None, hit["url"] if hit else None,
         task["cost"], result.get("fetched_at"), int(task["cache_hit"])),
    )
    db.commit()
 
 
def collect(ids, timeout_s=3600):
    deadline = time.time() + timeout_s
    while ids and time.time() < deadline:
        ready = requests.get(f"{BASE}/serp/google/organic/tasks_ready", auth=AUTH, timeout=60).json()
        for row in ready["tasks"][0]["result"] or []:
            if row["id"] not in ids:
                continue  # someone else's run on the same key
            got = requests.get(f"{BASE}/serp/google/organic/task_get/advanced/{row['id']}",
                               auth=AUTH, timeout=60).json()
            record(ids.pop(row["id"]), got["tasks"][0])
        # Failed tasks never appear in tasks_ready: check stragglers directly.
        for task_id in list(ids)[:20]:
            got = requests.get(f"{BASE}/serp/google/organic/task_get/advanced/{task_id}",
                               auth=AUTH, timeout=60).json()["tasks"][0]
            if got["status_code"] in (40601, 40602):
                continue
            if got["status_code"] == 20000:
                record(ids.pop(task_id), got)
            else:
                print("failed:", ids.pop(task_id), got["status_code"], got["status_message"])
        if ids:
            time.sleep(30)
    if ids:
        print(f"{len(ids)} tasks still running; rerun the script later to collect them.")
 
 
if __name__ == "__main__":
    collect(post_tasks())
    for row in db.execute("select keyword, position, url from ranks where day = ? order by keyword", (today,)):
        print(row)

How it works

  • Standard queue, priority: 1. The lowest SERP price. Results may come from the shared cache if the same query ran in the last 6 hours; cache_hit and fetched_at are stored so you can tell.
  • auto_upgrade: false. Keeps every task at the queue price. Drop it if you'd rather pay the live price than miss a day.
  • tag. day:keyword makes each task recognizable in tasks_ready and postbacks.
  • Rerunnable. Keywords already recorded today are skipped, so a second run only posts what's missing. Tasks posted by an earlier run that weren't collected stay in tasks_ready until collected; extend collect to look them up by tag if you rerun often.
  • No polling at all: set "postback_url": "https://your-app.example/hooks/serp/SECRET?id=$id" on each task and move record into your webhook handler. See Handling webhooks securely.

Schedule it

# crontab -e: every day at 06:15
15 6 * * * cd /opt/rank-tracker && /usr/bin/python3 rank_tracker.py >> run.log 2>&1

Reference: POSTGoogle Organic SERP: Task Post, GETGoogle Organic SERP: Tasks Ready, GETGoogle Organic SERP: Task Get Advanced.