# Shopify Best-Seller Rank Movement Tracker (`practical_ai_lab_jp/pal-shopify-bestseller-rank-movement-tracker`) Actor

Enter one Shopify store URL. The first run saves a best-selling rank baseline; every later run reports rank climbers, fallers, new entrants and drop-offs with severity, plus a CSV rank history.

- **URL**: https://apify.com/practical_ai_lab_jp/pal-shopify-bestseller-rank-movement-tracker.md
- **Developed by:** [Practical AI Lab](https://apify.com/practical_ai_lab_jp) (community)
- **Categories:** E-commerce, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $20.00 / 1,000 rank movement reports

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Shopify Best-Seller Rank Movement Tracker

Merchandising and competitive teams cannot see a rival Shopify brand's sales. The one public signal is the order of the store's collection feeds, which for many collections follows Shopify's best-selling sort. This Actor turns that signal into a repeatable report:

1. **First run:** you enter one store URL. The Actor saves a rank baseline and shows a sample of the current top ranks.
2. **Every later run:** it compares against the saved baseline and reports **rank climbers, fallers, new entrants and drop-offs** in one severity-ranked action list, plus a CSV rank history with source URLs.

> **Rank is a demand proxy, not sales proof.** The Actor never shows revenue, units sold or conversion. Treat every result as a lead to verify on the storefront.

### Quick start: one URL

The only required input is `storeUrl`.

```json
{
    "storeUrl": "https://your-rival-store.com"
}
```

Replace the example with the public HTTPS storefront you want to watch. The pre-filled sample URL in the Console is only a placeholder for a first test; use the rival you actually track.

What happens on the first run:

- Output status is `BASELINE_CREATED`. No movements are reported yet because nothing exists to compare against.
- The baseline is stored per store domain in a named key-value store (default `pal-shopify-rank-tracker-state`).
- You still receive a `rank_sample` set (the current top 10 of the store-wide collection) and a `REPORT` and `RANK_HISTORY_CSV` so you can check the data before relying on it.

### Scheduling later runs

Movement can only be detected when a run happens. This Actor does **not** monitor continuously and **does not send alerts**.

To get regular comparisons:

1. Save your input as an Apify **Task** for this Actor.
2. In the Apify Console open **Schedules**, create a schedule (for example daily) and add the task.
3. Keep the same `stateStoreName` on every run so each run finds the previous baseline.

Compare runs on a steady cadence. A daily or weekly schedule gives more interpretable movement than irregular manual runs. If you want notifications, connect your own Apify integration or webhook to the dataset; that is not part of this Actor.

### The four buyer outcomes

Every action record has an `outcome`, a `severity` (`high`, `medium`, `low`), a numeric `priority_score` and a plain-language `recommended_action`.

| Outcome | What it means | Typical use |
| --- | --- | --- |
| `climber` | Product moved up by at least `minRankChange` positions. | Push detection: check the rival's price, stock and promotion; decide whether to match or bundle. |
| `faller` | Product moved down by at least `minRankChange` positions. | Cooling detection: look for stock-outs or discounting and consider promoting your equivalent. |
| `new_entrant` | Product entered the tracked window. | Launch radar: review emerging products for assortment decisions. |
| `drop_off` | Product left the tracked window. | Exit watch: verify whether it was retired, sold out or just pushed deeper. |

One product appearing in several collections is joined into a single action. Additional signals add to the score:

- `sold_out_while_climbing`, `price_cut_while_climbing`, `price_increase_while_climbing`
- `discounting_while_falling`, `sold_out_while_falling`
- `sold_out_on_entry`
- `confirmed_in_N_collections`

#### Severity scoring

- Climbers and fallers: size of the move relative to the collection (at least 40 positions as the base), plus a bonus when the product enters or leaves the top tier (`topTierSize`, default 10) or sits in the top 3.
- New entrants and drop-offs: scored by the rank position (top 3 highest, then top tier, then twice the top tier).
- Score 60 and above is `high`, 35 to 59 is `medium`, below 35 is `low`.
- `confidence` (`low`, `medium`, `high`) is lowered for small collections (fewer than 20 ranked products), fewer than 3 stored snapshots, possible bulk re-orders, and rank sources other than the best-selling sort. The reasons are listed in each action's `caveats`.

### Output

**Dataset** (`overview` view): one `run_summary` record first, then severity-ranked `action` records (up to 200), then `rank_sample` records.

Run statuses:

| Status | Meaning |
| --- | --- |
| `BASELINE_CREATED` | Snapshot saved; no comparable earlier snapshot yet. |
| `CHANGES_DETECTED` | At least one movement action was found. |
| `NO_CHANGES` | Comparison done, nothing moved by the minimum threshold. |
| `NO_DATA` | Nothing could be read (errors, empty or malformed feeds). State is left untouched. |
| `ROBOTS_BLOCKED` | robots.txt does not allow the requested feeds. |
| `ROBOTS_UNAVAILABLE` | robots.txt could not be read reliably, so no store page was requested. |
| `UNSAFE_TARGET` | The host resolved to a non-public address. |

**Key-value store (default run store):**

- `OUTPUT`: the run summary.
- `REPORT`: the complete JSON action report (priority actions, outcome lists, per-collection status, skipped items, limitations).
- `RANK_HISTORY_CSV`: one row per snapshot, collection and ranked product with `rank`, `previous_rank`, `rank_change`, price, availability, `product_url` and the exact feed `source_url`. Text cells starting with spreadsheet formula characters are prefixed with an apostrophe.

Positive `rank_change` always means the product moved **up** the ranking (rank 12 to rank 1 is `+11`).

#### Illustrative action record (not from a real run)

```json
{
    "record_type": "action",
    "outcome": "climber",
    "severity": "high",
    "priority_score": 85,
    "confidence": "low",
    "product_title": "Item 12",
    "collection": "all",
    "rank_basis": "best_selling_sort",
    "previous_rank": 12,
    "current_rank": 1,
    "rank_change": 11,
    "price_change_percent": -25.0,
    "signals": ["price_cut_while_climbing"],
    "recommended_action": "Review this rival product now: check its price, stock and promotion, ...",
    "caveats": ["Small sample: only 12 ranked products in this collection, so rank moves are noisy."]
}
```

### Input options

| Field | Default | Purpose |
| --- | --- | --- |
| `storeUrl` (required) | none | One public HTTPS storefront URL. Only the host is used. |
| `collectionHandles` | empty | Specific collections to track. Empty means store-wide `all` plus the largest public collections. |
| `maxCollections` | 5 | Collections per run (1 to 20). |
| `maxProductsPerCollection` | 100 | Top positions ranked per collection (10 to 500). |
| `maxRequests` | 30 | Hard request cap per run, including robots.txt (5 to 100). |
| `minRankChange` | 3 | Smaller moves are ignored. |
| `topTierSize` | 10 | Top-tier boundary used for severity. |
| `rankBasisPolicy` | `auto` | `auto`, `best_selling_only` or `default_order_only`. |
| `historySnapshots` | 8 | Snapshots kept per store (2 to 12). |
| `requestDelaySeconds` | 1 | Pause between requests (0.5 to 10). |
| `stateStoreName` | `pal-shopify-rank-tracker-state` | Named key-value store holding baselines. |

#### About the rank source

Shopify's default `robots.txt` normally disallows URLs containing `sort_by`, which includes the best-selling sort. The Actor checks robots.txt before every request and never overrides it:

- `auto` (default): use the best-selling sort when permitted; otherwise use the collection's default order for that collection. Each record states its `rank_basis`: `best_selling_sort` or `collection_default_order`. A merchant may set the default order to best-selling, manual, newest or anything else, so default-order ranks reflect **merchant placement**, not necessarily demand, and confidence is capped.
- `best_selling_only`: never fall back; stores that block the sort return `ROBOTS_BLOCKED`.
- `default_order_only`: track merchant placement only.

If a collection's rank basis changes between runs, it is not compared; a new baseline is created and the report says so.

### Safety and public-data rules

- Only `https://` store URLs on the default port. IP addresses, credentials, internal and reserved host names are rejected.
- DNS answers must all be public addresses; the connection is pinned to the validated address, TLS certificates are verified, redirects are not followed (robots.txt may only redirect between the bare domain and its `www.` twin).
- robots.txt is read first and checked before **every** request. Missing robots.txt (HTTP 404/410) means allowed; any other failure, an HTML page instead of rules, or a block means refusal.
- Only public JSON feeds are read: the collection list and collection product feeds. No logins, no cart or checkout paths, no personal data, no proxies.
- Bounded pagination, per-response size limit, request budget, delay between requests, and a full stop after HTTP 429.
- Product handles and titles are stored only as product data. No customer, contact or reviewer data is read.

### Pricing event

The code defines one pay-per-event name, `rank-movement-report` (`src/pricing.py`), charged once through `Actor.charge` **only** when a repeat run delivers at least one rank movement action. Baseline runs, runs without changes, refused runs, runs without data and failed runs are never charged. **No payable plan or price is configured in this project;** pricing must be set up separately on the platform.

### Limitations and sample-size caveats

- Rank is a proxy. Public feeds show an ordering, not sales, and the ordering may be influenced by merchant settings, pinned products, promotions or stock status.
- Many stores block the best-selling sort in robots.txt. In that case results describe default order, not best-selling.
- Only the configured top window is ranked. A `drop_off` means the product left that window, not that it was discontinued. If a run's window differs from the previous one, only positions both runs could see are compared.
- Small collections (fewer than 20 ranked products) and short histories (fewer than 3 snapshots) produce noisy moves. Collections where most products shift at once are flagged as possible bulk re-orders.
- The first comparison covers one interval. Wait for several snapshots before judging a trend.
- Hidden products, variant-level and market-specific ordering are not visible.
- State is one record per domain. Two overlapping runs for the same store can overwrite each other's baseline. Run them one after another.
- A feed that returns zero products is treated as missing data, not as every product dropping off.
- The Actor reads Shopify-style public JSON endpoints. Stores that disable or customize them (headless storefronts, password pages) return `NO_DATA`.
- This build was written and unit-tested offline only. It has not been run against a live Shopify store or on the Apify platform.

### State storage note

Baselines are kept with the Apify SDK key-value store `get_value` and `set_value` calls, one record per store domain. A **named** store is used because each run's default store is discarded or isolated per run on the platform; the named store is what allows a later run to find the previous baseline. Deleting the named store resets all baselines.

### Local checks

Tests are fully offline and use only the Python standard library plus mocks:

```bash
python -m unittest discover -s tests -t .
```

# Actor input Schema

## `storeUrl` (type: `string`):

One public HTTPS storefront URL, for example the rival brand you want to watch. Only the host name is used; paths and query strings are ignored. Plain http://, IP addresses, ports and credentials in the URL are rejected.

## `collectionHandles` (type: `array`):

Track specific collections, for example <code>all</code> or <code>new-arrivals</code>. Leave empty to track the store-wide <code>all</code> collection plus the largest collections found in the public collection list.

## `maxCollections` (type: `integer`):

Upper bound on collections tracked per run, including the store-wide collection.

## `maxProductsPerCollection` (type: `integer`):

How many top positions of each collection are ranked and compared. Larger windows cost more requests and storage.

## `maxRequests` (type: `integer`):

Hard cap on requests to the store, including robots.txt. The run stops cleanly when it is reached.

## `minRankChange` (type: `integer`):

Smaller position changes are treated as noise and not reported.

## `topTierSize` (type: `integer`):

Positions 1 to this value count as the top tier. Entering or leaving the top tier raises severity.

## `rankBasisPolicy` (type: `string`):

<b>auto</b> uses the best-selling sort when the store's robots.txt allows it and otherwise falls back to the collection's default order (clearly labelled in the output). <b>best_selling_only</b> never falls back. <b>default_order_only</b> tracks merchant-controlled placement only.

## `historySnapshots` (type: `integer`):

How many snapshots per store are kept in persisted state and in the CSV rank history.

## `requestDelaySeconds` (type: `number`):

Minimum pause between requests to the store.

## `stateStoreName` (type: `string`):

Named key-value store that keeps one baseline per store domain so later runs can compare against it. Use the same name on every scheduled run. Deleting the store resets all baselines.

## Actor input object example

```json
{
  "storeUrl": "https://www.allbirds.com",
  "collectionHandles": [],
  "maxCollections": 5,
  "maxProductsPerCollection": 100,
  "maxRequests": 30,
  "minRankChange": 3,
  "topTierSize": 10,
  "rankBasisPolicy": "auto",
  "historySnapshots": 8,
  "requestDelaySeconds": 1,
  "stateStoreName": "pal-shopify-rank-tracker-state"
}
```

# Actor output Schema

## `results` (type: `string`):

Download rows from the latest run in JSON/CSV.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "storeUrl": "https://www.allbirds.com"
};

// Run the Actor and wait for it to finish
const run = await client.actor("practical_ai_lab_jp/pal-shopify-bestseller-rank-movement-tracker").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "storeUrl": "https://www.allbirds.com" }

# Run the Actor and wait for it to finish
run = client.actor("practical_ai_lab_jp/pal-shopify-bestseller-rank-movement-tracker").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "storeUrl": "https://www.allbirds.com"
}' |
apify call practical_ai_lab_jp/pal-shopify-bestseller-rank-movement-tracker --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,practical_ai_lab_jp/pal-shopify-bestseller-rank-movement-tracker"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/gSmsdJUyrCzGlWw47/builds/qbsSodKrUFFnjyFTT/openapi.json
