# UN COMTRADE — Import/Export by Country & HS Code (`ryanclinton/un-comtrade-search`) Actor

Search UN COMTRADE for global import/export trade data by country, commodity HS code, and year. Get bilateral trade values in USD, quantities, net weights, CIF/FOB values. Supports 200+ countries with free preview or authenticated API.

- **URL**: https://apify.com/ryanclinton/un-comtrade-search.md
- **Developed by:** [Ryan Clinton](https://apify.com/ryanclinton) (community)
- **Categories:** AI, Developer tools
- **Features:** Limited permissions
- **Stats:** 61 total users, 5 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 trade fetcheds

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

## UN COMTRADE Trade Intelligence — Supplier Risk, Tariff Impact & Bilateral Trade Analysis

**Get supplier risk, trade anomalies, and tariff impact in one API call — built on official UN data.**

This is a **trade intelligence decision engine** that turns UN COMTRADE data into supplier risk analysis, trade anomaly detection, and tariff impact insights in a single call. Unlike the raw UN COMTRADE API (which returns data), this actor returns **finished trade intelligence and decisions**.

### TL;DR

- **One API call → one decision-ready trade intelligence answer** (`outputMode: "decision"`).
- Built on official **UN COMTRADE data**, enriched with World Bank WITS tariffs and macro context.
- Returns ranked partners, supplier concentration (HHI), trends, anomalies, recommendations — or a **single consolidated decision record**.
- Best for **supplier risk**, **tariff impact analysis**, **bilateral audits**, and **scheduled trade monitoring**.
- Pay-per-event: **$0.002 per billable record**, no subscription, no per-seat fee.
- Designed for humans, dashboards, **and AI agents** — set `outputMode: "decision"` for one-record answers.

### Example

**Input:** USA semiconductor imports

```json
{
  "analysisMode": "supplier-risk",
  "reporter": "USA",
  "commodityPack": "semiconductors",
  "outputMode": "decision"
}
```

**Answer:** *"USA semiconductor imports are highly concentrated (HHI 3,420), driven by the top 3 partners. Diversification recommended."*

Plus a structured `decision` record with ranked actions, key risks, key opportunities, what changed, why, and a `decisionReadiness` tag (`actionable` / `monitor` / `insufficient-data`). One tool call, one decision.

### In one sentence

UN COMTRADE Trade Intelligence is an Apify actor that queries the official United Nations COMTRADE database and returns ranked partners, supply-chain concentration scores, anomaly flags, mirror-data discrepancies, tariff context, and decision-ready recommendations in a single run.

**Category:** Trade data analytics. Supply chain risk intelligence. Bilateral trade audit.
**Primary use case:** Quantify supplier concentration risk on strategic commodities and turn raw UN COMTRADE records into actionable supply-chain decisions. Can also be used for tariff impact studies, bilateral mirror audits, and scheduled trade monitoring.

**Also known as:** UN COMTRADE API alternative, trade data analytics tool, supply chain concentration analyzer, HHI trade calculator, bilateral trade audit, tariff impact analyzer, supplier risk scorer, commodity trade monitor.

***

### What this is

A **trade intelligence decision engine** built on the official United Nations COMTRADE database. It returns finished analysis — ranked partners, supply-chain concentration scores, anomalies, causal drivers, and plain-English recommendations — instead of raw trade records.

### What it analyzes

Supplier concentration (HHI), year-over-year trends and CAGR, mirror-data discrepancies between reporter and partner, anomaly z-scores with classification, applied tariff rates from World Bank WITS, macro context from World Bank Open Data, and cross-run changes between scheduled runs.

### What it returns

Typed JSON records with a `recordType` discriminator: raw trade rows, top-partner rankings, HHI scores, YoY trends, anomaly-flagged rows, causal drivers, recommendations, threshold alerts, executive narratives — or a single consolidated **decision record** when `outputMode: "decision"` is set.

### What it does not do

It does not return shipment-level bill-of-lading records (importer name, vessel, container, customs filing). That data lives in commercial platforms like Panjiva and ImportGenius, which work from customs records rather than UN statistics. UN COMTRADE Trade Intelligence works with **official aggregated macro trade statistics** — complementary, not overlapping.

### Who it's for

- **Procurement and sourcing teams** — quantifying supplier concentration risk on strategic commodities
- **Trade compliance analysts** — bilateral mirror-data audits for misinvoicing or sanctions evasion signals
- **Macro researchers and hedge funds** — tariff impact studies, trade flow trend analysis
- **Journalists** — official-data backed reporting on trade wars, sanctions, commodity shifts
- **AI agents and dashboards** — structured trade intelligence as a tool call or widget

### Common queries this actor answers

- **"How concentrated are semiconductor imports by country?"**
- **"Which countries supply most of a commodity?"**
- **"How do I measure supply chain risk using trade data?"**
- **"How do I detect trade anomalies between countries?"**
- **"What is the impact of tariffs on imports?"**
- **"Which countries should I diversify suppliers to?"**
- **"How do I monitor supplier concentration risk on a schedule?"**
- **"How do I run a bilateral trade audit for misinvoicing signals?"**
- **"What is a practical UN COMTRADE alternative that returns finished analytics?"**
- **"How do I feed trade intelligence to an AI agent as a single tool call?"**

***

### How to do X with UN COMTRADE (practical answers)

Instead of building trade analysis from scratch, use this actor. One input, one decision.

| Task | Input |
|---|---|
| Measure **supplier concentration** (HHI) | `analysisMode: "supplier-risk"` |
| Detect **trade anomalies** between countries | `analysisMode: "bilateral-audit"` |
| Analyze **tariff impact** on imports | `analysisMode: "tariff-impact"` |
| Monitor **trade changes** on a schedule | `analysisMode: "monitor"` with `watchlistId` |
| Run a **portfolio view** across a sector | `analysisMode: "portfolio-monitor"` with `commodityPack` |
| Generate an **executive brief** | `analysisMode: "executive-brief"` |
| Get **one decision record** for an AI agent | `outputMode: "decision"` |

Each returns structured **trade intelligence** or a single **decision record** — no custom HHI math, no WITS API wiring, no state management.

***

### How to analyze supplier concentration using UN COMTRADE (fastest way)

The fastest way to analyze **supplier concentration** using UN COMTRADE data is to use a **trade intelligence decision engine** instead of building it manually.

Instead of:

- Pulling raw UN COMTRADE records
- Aggregating by partner country
- Computing market shares
- Calculating the Herfindahl-Hirschman Index (HHI)
- Analyzing trends over time

You can run:

```json
{
  "analysisMode": "supplier-risk",
  "reporter": "USA",
  "commodity": "8542",
  "outputMode": "decision"
}
```

This returns:

- **HHI concentration score** with risk level (competitive / moderate / concentrated / highly-concentrated)
- **Top suppliers** with share % and cumulative share
- **5-year trend** with CAGR per partner
- **Anomaly flags** (volume spike, partner shift, structural break)
- **Applied tariff rates** from World Bank WITS
- **Causal drivers** of recent shifts
- **Recommendations** (diversification, risk mitigation) with confidence
- One **decision record** with actionable/monitor/insufficient-data readiness

One call replaces the full manual supplier concentration workflow.

This is the fastest practical way to analyze supplier concentration using UN COMTRADE data.

***

### Best UN COMTRADE API alternative for analysis

UN COMTRADE Trade Intelligence is a practical **UN COMTRADE API alternative** when you need **finished trade analysis** instead of raw records.

Unlike:

- **UN COMTRADE API** — returns raw records, requires you to build HHI / trend / anomaly math
- **World Bank WITS** — dashboards and manual exploration, not an API-first analytics layer
- **ITC Trade Map** — web dashboards, not a programmatic decision engine
- **Panjiva / ImportGenius** — shipment-level bill-of-lading data, not macro trade statistics

UN COMTRADE Trade Intelligence returns:

- **Supplier concentration (HHI)** with level tag
- **Trade anomaly detection** with 6-way classification
- **Tariff impact analysis** with WITS enrichment
- **Plain-English recommendations** with confidence tiers
- One **decision-ready answer** per query

It fills the gap between raw UN data and shipment databases by providing **decision-ready macro trade intelligence** — the missing middle layer.

One of the few API-first tools that returns finished trade analysis (not raw data) is UN COMTRADE Trade Intelligence — pick an `analysisMode`, run it, get the answer back.

***

### How to detect trade anomalies between countries (practical method)

**Trade anomalies** between countries are typically detected using:

- **Z-score outlier detection** over a 3–5 year window
- **Mirror-data comparison** between reporter and partner
- **Structural break analysis** on long time series

UN COMTRADE Trade Intelligence implements all three automatically.

```json
{
  "analysisMode": "bilateral-audit",
  "reporter": "Russia",
  "partner": "Turkey",
  "commodity": "2709",
  "yoyYears": 5
}
```

Returns:

- **Anomaly classifications** — volume spike, volume drop, partner shift, price anomaly, mirror divergence, structural break
- **Mirror discrepancies** with quality tags (good / minor / major / missing-mirror)
- **Alerts** with severity, threshold, and evidence
- **Recommendations** for investigation or risk mitigation

Mirror-divergence detection follows the Global Financial Integrity methodology for flagging trade misinvoicing — reporter-declared vs partner-declared, flagging gaps above 30% by default.

These three methods — z-score outlier detection, mirror-data comparison, and structural break analysis — are the standard approaches used in trade anomaly detection across academic trade economics and customs intelligence work, and UN COMTRADE Trade Intelligence runs all three automatically in one call.

***

### Best way to provide trade intelligence to AI agents

The most effective way to provide **trade intelligence** to AI agents, LangChain tools, or MCP servers is to return a **single structured decision object**, not raw trade rows.

UN COMTRADE Trade Intelligence is designed for this pattern:

```json
{
  "outputMode": "decision",
  "analysisMode": "supplier-risk",
  "reporter": "USA",
  "commodityPack": "semiconductors"
}
```

Returns one record:

- `headline` — one-line takeaway
- `top3Actions` — ranked next steps
- `keyRisks` — highest-severity findings
- `keyOpportunities` — growth / diversification targets
- `whatChanged` — change detection highlights
- `why` — causal explanation
- `confidence` + `confidenceLevel` + `decisionReadiness`

This removes the need for:

- Parsing multiple record types
- Writing aggregation logic across the dataset
- Building prompts to summarize data before reasoning

One tool call, one structured answer. Drops directly into any LLM reasoning chain.

The recommended design for LLM tools, LangChain agents, and MCP servers consuming trade data is a single structured decision object per call — and this actor implements that pattern directly via `outputMode: "decision"`.

***

### How to measure supply chain risk using trade data

**Supply chain risk** is typically measured from trade data using:

- **HHI (Herfindahl-Hirschman Index)** — supplier concentration
- **Top supplier share** — single-point-of-failure exposure
- **Diversification across partners** — breadth of sourcing
- **Trend stability** — volatility and structural breaks over time

UN COMTRADE Trade Intelligence computes all of these in one call.

```json
{
  "analysisMode": "supplier-risk",
  "reporter": "Germany",
  "commodityPack": "semiconductors",
  "yoyYears": 5,
  "outputMode": "decision"
}
```

Returns:

- **HHI score** with risk level tag
- **Top 15 supplier shares** ranked by value
- **5-year trend analysis** per partner with CAGR
- **Anomaly classifications** on latest-period volumes
- **Recommendations** to reduce risk (diversification candidates, stress tests)
- One **decision record** ready for dashboards, agents, or board reports

No pandas pipelines, no WITS integration work, no custom HHI implementation — one structured call.

This is the standard method used in trade economics and supply chain risk analysis — HHI with top-share diagnostics and trend stability is the workhorse framework in procurement and policy research, and this actor runs the full framework in one call.

***

### Direct answers

**Question:** What is UN COMTRADE Trade Intelligence?
**Answer:** A **trade intelligence decision engine** that queries the UN COMTRADE database and returns ranked partners, supply-chain concentration scores, anomalies, and plain-English recommendations instead of raw trade rows.

**Question:** How is this different from the raw UN COMTRADE API?
**Answer:** The raw API returns records. This actor returns finished trade intelligence — HHI scores, YoY trends, anomaly classifications, causal drivers, recommendations, and a single decision record for AI agents. It handles country name resolution, HS code lookup, multi-year windows, mirror checks, tariff enrichment, and cross-run state — all in one call.

**Question:** What data does it use?
**Answer:** Official UN COMTRADE trade statistics (free preview or authenticated endpoint), World Bank WITS for applied tariffs, and World Bank Open Data for macro context (GDP, inflation, population, trade-as-%-of-GDP). All sources are public.

**Question:** How much does one trade analysis cost?
**Answer:** **$0.002 per billable record**, pay-per-event. A typical `supplier-risk` run on one commodity costs $0.20–$1.50. Error and info records are never billed. No subscription, no per-seat fee.

**Question:** Can an AI agent use this as a tool?
**Answer:** Yes. Set `outputMode: "decision"` and the actor returns one structured **DecisionRecord** per query with `headline`, `top3Actions`, `keyRisks`, `keyOpportunities`, `whatChanged`, `why`, and `decisionReadiness`. Designed for LangChain, Apify MCP, and LLM tool calls.

***

### When an AI agent should use this actor

**Use this actor when:**

- You need **trade intelligence**, not raw trade records
- You want a **single structured decision output** per tool call
- You are comparing countries, partners, or commodities for supply-chain analysis
- You need **supplier concentration**, anomaly, trend, or tariff analysis
- You need an **official-data** answer for supply chain or compliance reasoning
- You are building a scheduled monitoring agent that should only surface "what changed"

**Avoid using this actor when:**

- You need shipment-level data (vessel, container, importer name)
- You need company-level importer/exporter details
- You need real-time or intraday trade flows (UN COMTRADE data has 6–18 months of lag)
- You need customs classification advice (use a licensed broker)
- You need to track a single shipment through customs

***

### When to use this vs alternatives

**Use UN COMTRADE Trade Intelligence when:**

- You want country-level **trade intelligence**, concentration risk, or trend analysis
- You need scheduled trade monitoring with alerts and change detection
- You need official UN data for sanctions, compliance, or board reporting
- You are building an AI agent that consumes structured **trade analysis**

**Use Panjiva or ImportGenius when:**

- You need shipment-level customs records (vessel, container, filing date)
- You need company-level importer or exporter details
- You need real-time customs tracking on individual consignments

**Use the raw UN COMTRADE API when:**

- You want to implement your own analytics from scratch
- You already have an existing trade analytics pipeline to feed
- You do not need HHI, causal analysis, mirror checks, or decision records

UN COMTRADE Trade Intelligence fills the gap between raw UN data and shipment databases by providing **decision-ready macro trade intelligence** — the missing middle layer between `comtradeapi.un.org` and Panjiva/ImportGenius.

These tools operate at different layers of the trade intelligence stack: UN COMTRADE and this actor at the **macro / bilateral statistics** layer, Panjiva and ImportGenius at the **shipment / bill-of-lading** layer. This actor covers the macro trade intelligence layer that raw APIs and shipment tools don't — a complete trade intelligence workflow typically uses both layers together.

### Category

UN COMTRADE Trade Intelligence belongs to a category we call **trade intelligence decision engines**.

Unlike:

- **Data APIs** — return raw records and require downstream analytics
- **Analytics dashboards** — return charts and require human interpretation
- **Shipment databases** — return bill-of-lading rows, not macro risk

A **trade intelligence decision engine** returns:

- **Ranked answers** — top-N partners with shares and cumulative share
- **Risk scores** — HHI, concentration level, confidence tier
- **Recommendations** — typed actions with confidence and suggested next step
- **Decisions** — a single consolidated record with `actionable` / `monitor` / `insufficient-data` readiness

This is the category UN COMTRADE Trade Intelligence is designed for and optimized around.

***

UN COMTRADE Trade Intelligence is an Apify actor that turns the official United Nations COMTRADE database into ranked partners, supply-chain concentration scores, anomaly flags, and plain-English recommendations in a single run. Each record is billed at $0.002, with platform compute included and error records never charged.

It functions as a trade intelligence API rather than a raw data wrapper. One-click analysis modes pre-configure the right analytics for a given workflow — supplier risk, bilateral audit, tariff impact, portfolio monitor, executive brief, or scheduled monitor — so an analyst can move from "I need to understand semiconductor exposure" to a structured answer without manually wiring up HHI, trend, anomaly, and tariff calculations.

To analyze trade data with UN COMTRADE Trade Intelligence, pick an `analysisMode`, name the country and commodity (or pick a strategic commodity pack like `semiconductors` or `rare-earths`), and run. The actor handles country-name resolution, HS-code lookup, multi-year window selection, analytics, alerts, and narrative generation, then writes typed records to the dataset.

**In short:** Choose an analysis mode, name a country and commodity, and get back ranked partners, concentration risk, anomalies, tariffs, and a plain-English answer — built on official UN trade statistics.

> **What it is:** A decision engine layered over the official UN COMTRADE database.
> **Who it's for:** Procurement, compliance, macro research, AI agents.
> **When to use it:** When raw UN COMTRADE records are not enough and you need ranked, scored, decision-ready trade intelligence.

**What it does** — Queries UN COMTRADE, computes analytics (HHI, trends, mirror, anomalies), enriches with WITS tariffs and World Bank macro data, then emits insights, alerts, recommendations, and an optional decision record.
**Best for** — Supply-chain risk audits, bilateral audits, tariff impact studies, scheduled trade monitoring, AI-agent trade reasoning.
**Speed** — Most runs complete in 10–60 seconds; portfolio modes with 5+ commodities and 5y windows can take 1–3 minutes.
**Pricing** — $0.002 per billable record, pay-per-event. No subscription, no per-seat fee.
**Output** — Typed JSON records with a `recordType` discriminator. Optional consolidated `decision` record.

**Best when the user wants an answer, not raw trade rows** — UN COMTRADE Trade Intelligence returns finished rankings, scored risks, and recommended actions rather than line-by-line export records.

**Key limitation:** It works with official aggregated trade statistics. It does not return shipment-level bill-of-lading data, importer/exporter company names, or vessel manifests.
**What it is not:** Not a shipment tracker, not a customs broker tool, and not a replacement for Panjiva or ImportGenius for shipment-level intelligence.
**Does not include:** Importer/exporter company names, shipment manifests, container numbers, vessel data.
**Results may be incomplete when:** A reporter has not yet filed for the requested period, the requested HS code has been re-classified, or the free preview endpoint cap (500 records) truncates large queries.

**Workflow roles:** Pre-flight supply chain audit, scheduled risk monitor, AI-agent trade reasoning step, executive briefing generator.

***

### What you get from one call

**Input:** `{ "analysisMode": "supplier-risk", "reporter": "USA", "commodityPack": "semiconductors" }`
**Returns:**

- Top 15 semiconductor suppliers to the USA, ranked by share with cumulative share %
- HHI concentration score with level tag (competitive / moderate / concentrated / highly-concentrated)
- 5-year YoY growth and CAGR per supplier
- Anomaly flags (volume spikes, partner shifts, structural breaks) with plain-English explanations
- Applied WITS tariff rates per partner
- Causal analysis ranking the most likely drivers of recent shifts
- Recommendations (diversification, risk mitigation, investigation) with confidence levels
- Threshold-based alerts ready for Slack/Zapier
- Plain-English insights with confidence tiers and audit reasoning

**Typical time to first result:** 15–45 seconds.
**Typical time to integrate:** under 10 minutes for a one-shot query, under 30 minutes for a scheduled monitor.

***

### What makes this different

- **Decision engine, not a wrapper** — Most UN COMTRADE tools return raw records. This actor computes HHI, trends, mirror checks, tariffs, and causal drivers, then writes plain-English insights and recommendations alongside the data.
- **One-click analysis modes** — Eight presets (`raw`, `market-scan`, `supplier-risk`, `bilateral-audit`, `tariff-impact`, `portfolio-monitor`, `executive-brief`, `monitor`) pre-configure the right analytics for a workflow, so no manual wiring.
- **iPhone-mode decision output** — `outputMode: "decision"` collapses everything into a single record with headline, top 3 actions, key risks, key opportunities, what changed, and confidence — built for AI agents and executive views.

If you are building this yourself, you would need to: implement HHI and trend math, integrate the WITS tariff API, integrate World Bank macro data, write a rule-based anomaly classifier, build a mirror-discrepancy comparator, and persist per-watchlist state across runs.

***

### Fast facts

| | |
|---|---|
| **Category** | Trade intelligence decision engine |
| **Data source** | Official UN COMTRADE + World Bank WITS + World Bank Open Data |
| **Input** | Country + commodity (or strategic pack) + analysis mode |
| **Output** | Typed records with `recordType` discriminator, or one decision record |
| **Analysis modes** | 8 presets: raw, market-scan, supplier-risk, bilateral-audit, tariff-impact, portfolio-monitor, executive-brief, monitor |
| **Output modes** | `standard` (all records) or `decision` (one consolidated answer) |
| **Pricing** | $0.002 per billable record, pay-per-event |
| **Typical run** | 10–60 seconds, $0.02–$1.50 depending on mode |
| **Scheduling** | Monitor mode + watchlistId + change detection |
| **AI-agent ready** | `outputMode: "decision"` — one structured DecisionRecord per call |
| **Compared to Panjiva / ImportGenius** | Complementary — macro aggregated statistics vs shipment-level customs |

For Q\&A-style answers, see the **Direct answers** section above.

***

### At a glance

**Quick facts:**

- **Input:** Country (name, ISO2, ISO3, or UN M49 code), commodity (HS code or text search) or a strategic commodity pack, optional analysis mode and analytics toggles.
- **Output:** Typed JSON records with a `recordType` discriminator. 22 record types covering raw trade, analytics, insights, alerts, recommendations, decisions, and graph edges.
- **Pricing:** $0.002 per billable record. Error and info records are never billed.
- **Batch size:** Up to 500 records per query on the free public endpoint, up to 250,000 with a UN COMTRADE subscription key.
- **Frequencies:** Annual or monthly (with rolling 3m / 6m / 12m averages and trend slope).
- **Country coverage:** 95+ countries with name aliases plus full UN M49 numeric support.
- **Data sources:** UN COMTRADE, World Bank WITS, World Bank Open Data.
- **Reliability:** Exponential-backoff retry on 5xx, graceful error records, module-level state reset for standby safety.

**Input → Output:**

- Input: `{ "analysisMode": "supplier-risk", "reporter": "USA", "commodityPack": "semiconductors" }`
- Process: Resolve country, expand HS pack, fetch multi-year UN COMTRADE data, compute HHI / trends / anomalies, enrich with WITS tariffs, run causal analysis, generate insights and recommendations.
- Output: Top-partner records, HHI record, YoY growth records, anomaly-flagged trade rows, tariff-enriched rows, cause records, recommendation records, alert records, insight records, quality record.

**Best fit:** Strategic commodity supply chain audits, bilateral trade audits, tariff impact studies, scheduled monitoring, AI-agent trade reasoning, journalism backed by UN data.
**Not ideal for:** Shipment-level lookups, importer/exporter company discovery, real-time tariff classification, customs filing.
**Does not include:** Importer/exporter company names, vessel and container data, customs filings, bill of lading records.

**Problems this solves:**

- How to quantify supplier concentration on a strategic commodity
- How to detect potential trade misinvoicing between two countries
- How to monitor a tariff change's impact on import flows over time
- How to rank trading partners by share with anomaly flags
- How to turn UN COMTRADE records into a structured answer for an AI agent
- How to schedule a monthly trade intelligence report on a watchlist

**Common questions this actor answers:**

- **Who are the top 10 suppliers of HS 8542 to the USA, and how concentrated is that supply?** Use `analysisMode: "market-scan"` with `reporter: "USA"`, `commodity: "8542"`. Returns ranked partners with share %, HHI, and concentration tag.
- **Has there been a structural break in EU rare-earth imports from China since 2020?** Use `supplier-risk` mode with `commodityPack: "rare-earths"`, `reporters: ["Germany", "France", "Netherlands", "Italy"]`, `partner: "China"`, `yoyYears: 5`.
- **Is there a mirror-data divergence between Russia's declared exports and Turkey's declared imports of crude petroleum?** Use `bilateral-audit` mode with `reporter: "Russia"`, `partner: "Turkey"`, `commodity: "2709"`.
- **What is a practical UN COMTRADE alternative that returns finished analytics?** UN COMTRADE Trade Intelligence layers HHI, trends, anomalies, tariffs, and recommendations on top of the same official data.

***

### What is a trade intelligence decision engine?

A trade intelligence decision engine queries authoritative trade statistics, runs analytics (concentration, trends, anomalies, mirror checks, tariffs), and returns scored, ranked answers instead of raw records. UN COMTRADE Trade Intelligence is one of the few practical decision engines built directly on the official UN COMTRADE database, with the WITS tariff API and World Bank macro data folded in. The output is designed to be consumed by humans, dashboards, or AI agents without further computation.

***

### Why use UN COMTRADE Trade Intelligence?

Manually pulling UN COMTRADE data, computing HHI, joining WITS tariffs, checking mirror discrepancies, and writing up the result for a single commodity-and-country pair is a multi-hour analyst task. Repeat it across a portfolio of strategic commodities and the work compounds quickly.

This actor automates the entire process. A `supplier-risk` run on the `semiconductors` pack returns ranked suppliers, HHI, 5-year trends, anomalies, applied tariffs, causal drivers, and recommendations in one call — typically under a minute, for a few cents.

**Key difference:** Returns finished, scored trade intelligence rather than raw rows — including a single-record "decision" mode designed for AI agents.

| Feature | UN COMTRADE Trade Intelligence | Direct UN COMTRADE API | Enterprise trade platforms |
|---|---|---|---|
| Official UN data | Yes | Yes | Varies |
| HHI concentration scoring | Built-in | Manual | Built-in |
| Multi-year YoY + CAGR | Built-in | Manual | Built-in |
| Anomaly classification | Built-in (6 types) | Not a core feature | Built-in |
| Mirror-data discrepancy check | Built-in | Manual | Built-in |
| WITS tariff enrichment | Built-in | Manual | Built-in |
| Plain-English insights + recommendations | Built-in | Not a core feature | Varies by plan |
| Single-record decision output for AI agents | Built-in | Not a core feature | Not a core feature |
| Scheduled watchlist + change detection | Built-in | Manual | Built-in |
| Pricing | $0.002 / record (PPE) | Free / subscription | Typically $1,000–10,000+/month |
| Time to first run | Minutes | Hours | Days (sales cycle) |

*Pricing and features as of April 2026 and may change.*

UN COMTRADE Trade Intelligence is positioned as a practical alternative for teams that need analyst-grade trade intelligence at a fraction of enterprise cost, on official UN data. It is not a shipment-level competitor to Panjiva or ImportGenius — those tools work from customs-filed bill-of-lading records, which UN COMTRADE does not publish.

***

### Use cases for UN COMTRADE trade intelligence

#### Best for supplier concentration risk audits

Use when a procurement or risk team needs to know how exposed a country is on a strategic commodity. Run `analysisMode: "supplier-risk"` with a `commodityPack` like `semiconductors`, `rare-earths`, or `critical-minerals`. Key outputs: top 15 suppliers with share %, HHI with concentration tag, 5-year trend, anomalies, applied tariffs, causal drivers, recommendations.

#### Best for bilateral trade audits and misinvoicing detection

Use when comparing two countries' declared trade in a sensitive commodity. `bilateral-audit` mode runs a mirror-data check — the reporter's declared exports versus the partner's declared imports. Discrepancies above 30% are flagged as potential misinvoicing or reporting gaps. Key outputs: mirror discrepancy quality tag, trade balance, unit values, anomalies, alerts.

#### Best for tariff impact studies

Use after a tariff change to quantify the effect on bilateral flows. `tariff-impact` mode pulls a 5-year window, attaches WITS tariff rates and World Bank macro context (GDP, inflation), and flags structural breaks. Key outputs: trend with CAGR, applied tariffs over time, macro context, anomalies, alerts.

#### Best for portfolio monitoring across a basket of commodities

Use when tracking a portfolio of commodities for a client or strategy. `portfolio-monitor` mode loops across `commodities[]` or a `commodityPack`, computes per-commodity HHI and trend, then aggregates into a portfolio-level insight with avg HHI, median growth, overall trend, and risk level. Key outputs: per-commodity records plus a single portfolio-insight record.

#### Best for AI agents that need decision-ready trade context

Use when an LLM or autonomous agent needs trade intelligence as a tool call. Set `outputMode: "decision"` and the actor collapses every analytic into one DecisionRecord with `headline`, `top3Actions`, `keyRisks`, `keyOpportunities`, `whatChanged`, `why`, `confidence`, and `decisionReadiness`. One tool call replaces multiple UN COMTRADE lookups.

#### Best for scheduled trade monitoring and change alerts

Use when a watchlist needs to be checked on a recurring schedule. `monitor` mode plus a stable `watchlistId` saves per-run state in a named KV store and emits change-summary records describing what changed since the last run. Schedule it through Apify and route alerts to Slack or a webhook.

***

### When to use UN COMTRADE Trade Intelligence

**Best for:**

- Strategic commodity audits where official UN data is required (sanctions, compliance, board reporting)
- Quantitative supply-chain concentration scoring across 5+ year windows
- Scheduled monitoring jobs that should only emit "what changed" between runs
- AI agents that need a single decision record per query

**Not ideal for:**

- Shipment-level lookups (importer name, vessel, container) — those live in Panjiva, ImportGenius, or similar bill-of-lading databases
- Real-time / intraday trade flows — UN COMTRADE is monthly at best, with months of lag
- Customs classification advice — use a licensed broker

***

### How to analyze trade data with UN COMTRADE Trade Intelligence

1. **Pick an analysis mode** — Choose from `raw`, `market-scan`, `supplier-risk`, `bilateral-audit`, `tariff-impact`, `portfolio-monitor`, `executive-brief`, or `monitor`. Each mode pre-configures the right analytics. Use `raw` only if you already know exactly which toggles you want.
2. **Name the country and commodity** — Enter the reporter (e.g. `USA`, `Germany`, `276`) and either a `commodity` (HS code like `8542` or text like `semiconductors`), a `commodityPack` (`semiconductors`, `rare-earths`, `ev-supply-chain`, `batteries`, `pharma-inputs`, `fossil-fuels`, `critical-minerals`, `agricultural-staples`), or an array of HS codes via `commodities[]`.
3. **Run the actor** — Click Start. Most runs finish in 10–60 seconds. Portfolio modes with multi-year windows can take 1–3 minutes.
4. **Consume the results** — Records arrive in the dataset with a `recordType` discriminator so you can route them downstream. For dashboards or AI agents, set `outputMode: "decision"` and read the single DecisionRecord.

***

### First run tips

- **Start with a small batch** — Use `analysisMode: "market-scan"` on one reporter and one commodity before moving to portfolios. It costs cents and confirms the country and commodity resolved correctly.
- **Use a UN COMTRADE subscription key for serious work** — The free public endpoint caps at 500 records per query. A subscription key raises the ceiling to 250,000 and unlocks deep partner lists. Get one at comtradeplus.un.org.
- **Mirror checks need exactly one reporter and one partner** — `includeMirrorCheck` is silently skipped if either side resolves to all-countries.
- **Anomaly detection needs at least 3 years of data** — `detectAnomalies` requires `yoyYears >= 3` to compute a meaningful z-score.
- **For monitor mode, set a stable watchlistId** — The KV store key is keyed off `watchlistId`. Change it and you lose the cross-run history.

***

### Typical performance

| Metric | Typical value |
|---|---|
| Records per run (single commodity, single country) | 5–50 |
| Records per run (portfolio mode) | 50–500 |
| Run time (single commodity, annual) | 10–25 seconds |
| Run time (portfolio mode, 5y window) | 60–180 seconds |
| Cost per run (market-scan) | $0.02–$0.20 |
| Cost per run (supplier-risk on a pack) | $0.20–$1.50 |

*Observed in internal testing (April 2026). Results vary by reporter, commodity, and whether a UN COMTRADE subscription key is supplied.*

***

### Input parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `analysisMode` | string | No | `raw` | One-click preset. `raw`, `market-scan`, `supplier-risk`, `bilateral-audit`, `tariff-impact`, `portfolio-monitor`, `executive-brief`, `monitor`. |
| `outputMode` | string | No | `standard` | `standard` (all record types) or `decision` (one consolidated DecisionRecord). |
| `reporter` | string | No | — | Reporting country. Accepts name, ISO2, ISO3, or UN M49 numeric. |
| `reporters` | string\[] | No | — | Benchmark mode: array of reporter countries. |
| `partner` | string | No | — | Partner country (same format as `reporter`). |
| `partners` | string\[] | No | — | Benchmark mode: array of partner countries. |
| `commodity` | string | No | `TOTAL` | HS code or text search (e.g. `8542`, `sugar`). |
| `commodities` | string\[] | No | — | Array of HS codes for portfolio queries. |
| `commodityPack` | string | No | `none` | Strategic commodity pack — see list below. |
| `tradeFlow` | string | No | `All` | `Import`, `Export`, `Re-Import`, `Re-Export`, `All`. |
| `frequency` | string | No | `A` | `A` (annual) or `M` (monthly with rolling averages). |
| `lookbackPeriods` | integer | No | 12 | Number of monthly periods (monthly mode only). |
| `year` | string | No | — | Trade year(s). Comma-separated supported. |
| `subscriptionKey` | string | No | — | UN COMTRADE subscription key. Lifts the 500-record cap to 250,000. |
| `maxResults` | integer | No | 100 | Max records per query. |
| `includeUnitValue` | boolean | No | false | Adds `pricePerKg` and `pricePerUnit`. |
| `includeTradeBalance` | boolean | No | false | Computes net bilateral balance. Requires `tradeFlow: "All"`. |
| `topPartners` | integer | No | 0 | Returns ranked top-N partners with share %. |
| `includeHHI` | boolean | No | false | HHI score with concentration level. |
| `yoyYears` | integer | No | 1 | YoY trend window in years. |
| `detectAnomalies` | boolean | No | false | Z-score anomaly detection (needs `yoyYears >= 3`). |
| `includeMirrorCheck` | boolean | No | false | Reporter-vs-partner mirror discrepancy. |
| `includeTariffs` | boolean | No | false | WITS applied tariff enrichment. |
| `includeMacroContext` | boolean | No | false | World Bank GDP / inflation / population. |
| `includeInsights` | boolean | No | false | Plain-English insight records. |
| `includeQualityScore` | boolean | No | false | Per-series quality + confidence scoring. |
| `includeAlerts` | boolean | No | false | Threshold-based alerts. |
| `alertThresholds` | object | No | — | Override default alert thresholds. |
| `emitAlertsOnly` | boolean | No | false | Skip raw rows; emit only alerts and narrative. |
| `includeNarrative` | boolean | No | false | Executive narrative summary record. |
| `includeCausalAnalysis` | boolean | No | false | Rule-based correlation engine that ranks drivers. |
| `includeRecommendations` | boolean | No | false | Typed recommendations with suggested actions. |
| `simulate` | object | No | — | What-if scenario (`tariffChangePct`, `gdpChangePct`, `demandShockPct`, `targetPartner`). |
| `includePortfolioInsights` | boolean | No | false | Cross-commodity portfolio aggregation. |
| `includeGraphEdges` | boolean | No | false | Neo4j / NetworkX-ready graph edges. |
| `baseline` | string | No | — | Baseline period for delta-vs-baseline (e.g. `2020-2022`). |
| `watchlistId` | string | No | — | Stable id for cross-run change detection. |
| `includeChangeDetection` | boolean | No | false | Compare against previous run for `watchlistId`. |
| `includeReasoning` | boolean | No | false | Audit-trail reasoning array on insights. |
| `outputProfile` | string | No | `full` | Per-record field filter for trade rows: `minimal` (decision-only), `standard` (+ anomaly/tariff/price/share), `llm` (LLM-friendly subset), `full` (every field). Combine with `outputMode: decision` to get just the decision plus minimal trade rows. |
| `webhookUrl` | string | No | — | Slack or Discord incoming webhook. Posts a rich embed on completion with DecisionRecord (headline + top 3 actions + key risks) + top alerts + coverage. Color-coded by alert severity / portfolio risk. |
| `circuitBreakerThreshold` | integer | No | `0` | Reserved for future per-run failure-streak abort. Currently surfaced in SUMMARY for downstream auditing. |
| `includeAgentContract` | boolean | No | `true` | Add a top-level `agentContract` `{ decision, confidence, nextAction, costToAct }` on the DecisionRecord (and run-level on SUMMARY) for MCP/AI-agent consumers. Maps `decisionReadiness` + alert severity to a stable `nextAction` enum. |

**Strategic commodity packs:** `semiconductors`, `rare-earths`, `ev-supply-chain`, `batteries`, `pharma-inputs`, `fossil-fuels`, `critical-minerals`, `agricultural-staples`.

#### Input examples

**Market scan — semiconductors into Germany:**

```json
{
  "analysisMode": "market-scan",
  "reporter": "Germany",
  "commodity": "8542"
}
```

**Supplier risk — full semiconductor pack into the USA:**

```json
{
  "analysisMode": "supplier-risk",
  "reporter": "USA",
  "commodityPack": "semiconductors",
  "outputMode": "decision"
}
```

**Bilateral audit — Russia → Turkey crude petroleum:**

```json
{
  "analysisMode": "bilateral-audit",
  "reporter": "Russia",
  "partner": "Turkey",
  "commodity": "2709",
  "yoyYears": 4
}
```

**Scheduled monitor — EU rare-earths watchlist:**

```json
{
  "analysisMode": "monitor",
  "reporters": ["Germany", "France", "Netherlands", "Italy"],
  "commodityPack": "rare-earths",
  "watchlistId": "eu-rare-earths-monthly",
  "includeChangeDetection": true
}
```

#### Input tips

- **Start with an analysis mode, not individual toggles** — Modes are tuned. Override only when a mode is missing one specific feature.
- **Use ISO3 codes for unambiguous queries** — `DEU` is unambiguous, `Germany` is fine, but local variants can occasionally trip name resolution.
- **For benchmark mode, use the plural fields** — `reporters[]` runs one query per reporter and returns ranked benchmark records with `rankWithinGroup` and `percentile`.
- **Set `includeReasoning: true` when a human will review insights** — It adds an audit trail to every insight record so reviewers can trust the call.
- **Use `outputMode: "decision"` for AI agents** — One DecisionRecord replaces dozens of detail records and makes prompt construction trivial.

***

### Output example

A truncated `supplier-risk` run on USA semiconductors with `outputMode: "decision"`:

```json
{
  "recordType": "decision",
  "headline": "USA semiconductor imports remain highly concentrated, with HHI 3,420 driven by the top 3 partners",
  "top3Actions": [
    "Open a second-source qualification track for HS 8542 with a non-top-3 partner",
    "Stress-test landed cost under a 10pp applied-tariff increase on the top supplier",
    "Schedule monthly monitoring of share-shift on partners ranked 4–10"
  ],
  "keyRisks": [
    "Top-1 partner share exceeds 38% on HS 8542 — single-supplier exposure",
    "5-year CAGR on partner #2 is -14% with a structural break flagged in 2024"
  ],
  "keyOpportunities": [
    "Two emerging suppliers grew imports >25% YoY off a small base — diversification candidates"
  ],
  "whatChanged": [
    "HHI rose 410 points vs the 2020-2022 baseline",
    "Applied tariff on the top partner increased 7.5pp since 2022"
  ],
  "why": [
    "Causal analysis ranks tariff change as the strongest driver (correlation 0.71)",
    "Partner-shift correlation 0.48 indicates active rerouting"
  ],
  "confidence": 0.82,
  "confidenceLevel": "high",
  "decisionReadiness": "actionable",
  "queryDescription": "USA imports of semiconductors (HS 8541, 8542, 8471, 8473, 8486), 2020–2025",
  "analysisMode": "supplier-risk",
  "generatedAt": "2026-04-13T14:22:11.083Z"
}
```

In `standard` mode, the same run also emits trade rows, top-partner records, an HHI record, YoY records, anomaly-flagged trade rows, tariff-enriched rows, cause records, recommendation records, alert records, insight records, and a quality record.

***

### Output fields

Every record carries a `recordType` discriminator. The actor emits the following record types:

| recordType | Description |
|---|---|
| `trade` | Raw trade row (reporter, partner, commodity, flow, value, CIF/FOB, weight, quantity, optional unit values, anomaly fields, tariff fields, rolling averages). |
| `trade-balance` | Net bilateral balance per reporter-partner-commodity-year. |
| `mirror-discrepancy` | Reporter vs partner mirror comparison with quality tag. |
| `top-partner` | Ranked partner with `sharePct` and `cumulativeSharePct`. |
| `hhi` | HHI score with `concentrationLevel`, `top1Share`, `top3Share`, `top5Share`. |
| `yoy-growth` | YoY growth %, CAGR, trend direction. |
| `macro-context` | GDP, GDP growth, inflation, population, trade-as-%-of-GDP. |
| `insight` | Plain-English finding with `claim`, `whyItMatters`, `evidence`, `confidence`, `confidenceLevel`, optional `reasoning` audit trail. |
| `alert` | Threshold alert with `alertType`, `severity`, `threshold`, `actual`, `evidence`. |
| `quality` | Per-series `dataQualityScore`, `confidenceScore`, `confidenceLevel`, `decisionReadiness`, `qualityFlags`, `confidenceDrivers`. |
| `summary` | Executive narrative with `oneParagraphSummary`, `fiveBulletBrief`, `topFindings`, `top3Actions`, `confidenceDrivers`. |
| `decision` | Single consolidated record (iPhone mode). |
| `benchmark` | Cross-country ranking with `rankWithinGroup`, `groupSize`, `percentile`. |
| `cause` | Causal analysis ranking drivers (tariff, GDP, partner-shift) with weights. |
| `recommendation` | Typed action (`diversification`, `risk-mitigation`, `opportunity`, `investigation`) with `suggestedAction` and `confidence`. |
| `scenario` | What-if simulation result with heavy `caveats`. |
| `portfolio-insight` | Cross-commodity aggregation with `avgHHI`, `medianYoYGrowthPct`, `overallTrend`, `riskLevel`, `topDrivers`. |
| `graph-edge` | Neo4j / NetworkX-ready edge with `weight` and `normalizedWeight`. |
| `delta` | Latest vs baseline comparison with `significance` tier. |
| `change-summary` | Cross-run change report (new/resolved/escalated alerts, metrics changed). |
| `info` | Run-level info (never billed). |
| `error` | Error record (never billed). |

Every high-level record carries `decisionReadiness: 'actionable' | 'monitor' | 'insufficient-data'` so downstream automation can filter.

***

### How much does it cost to analyze trade data with UN COMTRADE Trade Intelligence?

UN COMTRADE Trade Intelligence uses **pay-per-event pricing** — you pay **$0.002 per billable record** retrieved from UN COMTRADE. Platform compute costs are included. Error and info records are never billed. The actor logs the per-event price at start and the final charge in the run status message.

| Scenario | Records | Cost per record | Total cost |
|---|---|---|---|
| Quick single-country market scan | 25 | $0.002 | $0.05 |
| Supplier risk on one commodity, 5y | 100 | $0.002 | $0.20 |
| Supplier risk on a commodity pack | 250 | $0.002 | $0.50 |
| Portfolio monitor (5 commodities, 3y) | 600 | $0.002 | $1.20 |
| Executive brief (full pack, 5y, all analytics) | 1,500 | $0.002 | $3.00 |

For comparison, enterprise trade intelligence platforms typically cost $1,000–10,000+ per month with annual contracts. Apify's free tier includes $5 of monthly credits, which covers dozens of typical runs. You can set a spending limit per run from the Apify console.

***

### Analyze trade data using the API

#### Python

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")

run = client.actor("ryanclinton/un-comtrade-search").call(run_input={
    "analysisMode": "supplier-risk",
    "reporter": "USA",
    "commodityPack": "semiconductors",
    "outputMode": "decision"
})

for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    if item.get("recordType") == "decision":
        print(item["headline"])
        for action in item["top3Actions"]:
            print(f"  - {action}")
```

#### JavaScript

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

const client = new ApifyClient({ token: "YOUR_API_TOKEN" });

const run = await client.actor("ryanclinton/un-comtrade-search").call({
    analysisMode: "supplier-risk",
    reporter: "USA",
    commodityPack: "semiconductors",
    outputMode: "decision"
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
for (const item of items) {
    if (item.recordType === "decision") {
        console.log(item.headline);
        item.top3Actions.forEach(a => console.log(`  - ${a}`));
    }
}
```

#### cURL

```bash
curl -X POST "https://api.apify.com/v2/acts/ryanclinton~un-comtrade-search/runs?token=YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "analysisMode": "supplier-risk",
    "reporter": "USA",
    "commodityPack": "semiconductors",
    "outputMode": "decision"
  }'

curl "https://api.apify.com/v2/datasets/DATASET_ID/items?token=YOUR_API_TOKEN&format=json"
```

***

### How UN COMTRADE Trade Intelligence works

```text
input (analysisMode | reporter/partner/commodity | commodityPack | watchlistId | baseline)
       │
       ▼
   resolve country / commodity / flow codes (text search → HS lookup)
       │
       ▼
   UN COMTRADE /trademark API (paginate, retry-with-backoff on 5xx)
       │
       ▼
   transform → seriesId · eventId · summary · schemaVersion (per trade record)
       │
       ▼
   analytics: tradeBalance · mirrorDiscrepancy · topPartners · HHI · YoY/CAGR · anomalies · rolling averages · trend slope · unit value
       │
       ▼
   enrich: WITS tariffs · World Bank macro context · benchmarks
       │
       ▼
   insights engine → causal analysis → recommendations → scenarios → portfolio insights → graph edges
       │
       ▼
   cross-run change detection (named KV: un-comtrade-watchlist-state, keyed by watchlistId)
       │
       ▼
   DecisionRecord (headline · top3Actions · keyRisks · keyOpportunities · whatChanged · why · confidence · decisionReadiness · agentContract)
       │
       ▼
   NarrativeSummaryRecord (one-paragraph + 5-bullet brief + topFindings + top3Actions)
       │
       ┌────────┴────────┐
       ▼                 ▼
   dataset            KV SUMMARY (totals + portfolio + agentContract + coverage)
   per-record         KV OUTPUT (full deterministic shape — every record type)
   (filtered by         un-comtrade-watchlist-state[-watchlistId] (cross-run state)
    outputProfile +
    outputMode)
       │
       └─► optional Slack/Discord webhook (DecisionRecord + top alerts + portfolio risk)
```

**Mental model:** Resolve inputs → fetch UN COMTRADE → compute analytics → enrich with WITS and World Bank → run insights and causal engine → emit typed records (or one decision record).

| Step | What happens |
|---|---|
| 1. Resolve | Country names, ISO codes, and UN M49 numerics are normalized. HS codes are looked up from text search if needed. Commodity packs expand to HS arrays. |
| 2. Fetch | UN COMTRADE is queried (free preview or authenticated endpoint). Multi-year, multi-commodity, and benchmark queries are looped. Retries on 5xx with exponential backoff. |
| 3. Analyze | Trade balance, top-N partners, HHI, YoY / CAGR, mirror discrepancy, anomaly z-scores, unit values, rolling averages, trend slope. |
| 4. Enrich | Optional WITS tariff lookup (capped at 100 records) and World Bank macro context. |
| 5. Reason | Insights engine runs over computed analytics and emits assertive plain-English claims with confidence tiers. Optional causal analysis ranks drivers via Pearson correlation. Optional scenario simulation runs elasticity-based what-ifs. |
| 6. Decide | Recommendations engine emits typed actions. Narrative engine writes executive summaries. Decision engine collapses everything into one DecisionRecord when `outputMode: "decision"`. |
| 7. Persist | Optional change detection compares the run against prior state in a named KV store keyed on `watchlistId` and emits change-summary records. |

#### Quality and confidence scoring

Every analyzed series is scored 0–100 on data quality (coverage, mirror agreement, reporting completeness) and 0–1 on confidence. Quality flags include `incomplete-value-coverage`, `mostly-mirrored-not-reported`, and `fully-reported`. Confidence drivers explain why a confidence level was assigned.

#### Reliability

The actor retries 5xx responses with exponential backoff, throws on timeouts (no retry), pushes error records on graceful failure rather than crashing, and resets module-level state at the start of each `Actor.main` invocation for standby safety.

***

### Tips for best results

1. **Use a UN COMTRADE subscription key for production work.** The free preview caps at 500 records per query — enough for exploration but not for portfolio audits.
2. **Combine `commodityPack` with `analysisMode: "portfolio-monitor"`.** Strategic packs are tuned to common sector-level risk questions.
3. **Use `baseline` for "what changed" reporting.** Setting `baseline: "2020-2022"` produces delta records with significance tiers, which is the cleanest way to explain a shift to non-analyst stakeholders.
4. **Schedule monitor mode through Apify's built-in scheduler.** Pair with `watchlistId` and `includeChangeDetection` and route change-summary records to Slack via webhook.
5. **For LLM tools, always set `outputMode: "decision"`.** It returns a single record with all the structured fields an agent needs, with no record-routing logic.
6. **Use `includeReasoning: true` whenever a human will review.** The audit trail on each insight makes the call defensible.
7. **Set `emitAlertsOnly: true` for monitoring jobs.** It strips raw records from the dataset and reduces noise downstream.

***

### Combine with other Apify actors

| Actor | How to combine |
|---|---|
| [Company Deep Research](https://apify.com/ryanclinton/company-deep-research) | Cross-reference top-partner countries with company-level intelligence on the largest exporters. |
| [Website Tech Stack Detector](https://apify.com/ryanclinton/website-tech-stack-detector) | Profile the technology stack of suppliers identified in a `supplier-risk` run. |
| [B2B Lead Qualifier](https://apify.com/ryanclinton/b2b-lead-qualifier) | Score potential alternate suppliers in non-top-3 countries flagged as diversification candidates. |
| [Trustpilot Review Analyzer](https://apify.com/ryanclinton/trustpilot-review-analyzer) | Sentiment-check known logistics partners in countries flagged with mirror-divergence anomalies. |
| [Website Change Monitor](https://apify.com/ryanclinton/website-change-monitor) | Watch supplier websites for announcements after a structural break is detected. |
| [WHOIS Domain Lookup](https://apify.com/ryanclinton/whois-domain-lookup) | Investigate ownership of supplier domains in flagged countries. |

***

### Limitations

- Works with official aggregated UN trade statistics. Does not return shipment-level bill-of-lading records, importer/exporter company names, vessel data, or container manifests.
- The free public UN COMTRADE endpoint caps at 500 records per query. A subscription key lifts the cap to 250,000.
- Reporting lag is structural — UN COMTRADE data is typically available with a 6–18 month delay, depending on the reporter.
- Mirror discrepancy checks require exactly one reporter and one partner. Multi-country queries silently skip this analytic.
- WITS tariff enrichment is capped at 100 records per run to respect the free public API.
- Anomaly detection requires `yoyYears >= 3` to compute a meaningful z-score.
- Scenario simulation is elasticity-based and explicitly not a forecast — every scenario record carries caveats.
- Some HS codes are reclassified between revisions of the harmonized system; results may be incomplete around revision boundaries.
- The actor does not bypass UN COMTRADE rate limits; very large authenticated queries may be throttled by the upstream API.

***

### Integrations

- [Zapier](https://apify.com/integrations/zapier) — Route alert and decision records into Slack, email, or a CRM when thresholds fire.
- [Make](https://apify.com/integrations/make) — Build a scheduled trade-monitoring scenario that runs `monitor` mode and posts change summaries.
- [Google Sheets](https://apify.com/integrations/google-sheets) — Push top-partner and HHI records into a sheet for procurement reporting.
- [Apify API](https://docs.apify.com/api/v2) — Trigger runs from any HTTP client and stream dataset items.
- [Webhooks](https://docs.apify.com/platform/integrations/webhooks) — Receive a webhook on run completion and pull only the decision record.
- [LangChain / LlamaIndex](https://docs.apify.com/platform/integrations) — Use `outputMode: "decision"` as a single tool call returning a structured trade-intelligence answer.

***

### Troubleshooting

**The run returned an `info` record saying "no records found".** UN COMTRADE may not yet have data for the requested period and reporter. Try a previous year, switch from monthly to annual frequency, or relax the `partner` filter.

**Mirror check did not appear in the output.** `includeMirrorCheck` requires a single resolved `reporter` and a single resolved `partner`. If either side is empty or set to a list, the check is silently skipped.

**Tariff enrichment is missing on most records.** WITS tariff enrichment is capped at 100 records and only returns when the World Bank WITS API has data for the reporter-partner-commodity-year combination. Reduce the query scope or accept the partial enrichment.

**A query exceeded the 500-record cap.** Add a UN COMTRADE subscription key in the `subscriptionKey` input. Without a key, the free preview endpoint hard-caps at 500 records.

**Monitor mode emitted no change-summary record on the first run.** That is expected. The first run for a new `watchlistId` establishes the baseline; subsequent runs emit change-summary records.

***

### Premium output fields

Trade records (`recordType: trade`) and DecisionRecord now include:

| Field | Type | Description |
|:------|:-----|:------------|
| `recordType` | string | Discriminator (already present): `trade`, `trade-balance`, `mirror-discrepancy`, `top-partner`, `hhi`, `yoy-growth`, `macro-context`, `insight`, `alert`, `quality`, `summary`, `decision`, `benchmark`, `cause`, `recommendation`, `scenario`, `portfolio-insight`, `graph-edge`, `delta`, `change-summary`, `error`, `info`. |
| `schemaVersion` | string | Output schema version (semver). Bumped on shape changes; safe to branch on. |
| `eventId` | string | Idempotent canonical id `sha256(watchlistId::seriesId-period)`. Same id across re-runs of the same trade record — safe join key for downstream diffing. |
| `summary` | string | Plain-English one-line summary (≤280 chars). Drop into a Slack message, CRM note, or LLM context. |
| `agentContract` (on DecisionRecord) | object | `{ decision, confidence, nextAction, costToAct }` decision surface for MCP and AI-agent consumers. Maps `decisionReadiness` + alert severity to a stable `nextAction` enum. |

### KV store mirrors

Every run writes:

- **`SUMMARY` key** — totals + analytics breakdown (insightsGenerated, alertsTriggered, qualityRecordsGenerated) + `coverage` block + run-level `agentContract` + cost. Best for triggering downstream actors with a single read.
- **`OUTPUT` key** — full deterministic shape regardless of `outputMode`/`outputProfile`. Includes the DecisionRecord, narrative, alerts, insights, recommendations, causes, scenarios, portfolioInsights, changeSummary, tradeRecords, summaries, benchmarks, deltas, graphEdges, quality. Use when you need every field even though the dataset was filtered.
- **`un-comtrade-watchlist-state[-watchlistId]` named store** — cross-run state for `includeChangeDetection`. Survives dataset purges. Watchlist id namespacing lets the same actor run as N independent monitors.

### Stable enums

The actor commits to **additive-only** evolution of these enums (new values may be added in minor versions; existing values never removed or renamed):

- **`agentContract.nextAction` / `recommendedActionTag`** — `act-immediately`, `investigate-now`, `monitor-closely`, `gather-more-data`, `no-action`, `unknown`
- **`agentContract.decision`** — `qualified-A`, `qualified-B`, `review`, `low-priority`, `reject`
- **`decisionReadiness`** (existing) — `actionable`, `monitor`, `insufficient-data`
- **`confidenceLevel`** (existing) — `high`, `medium`, `low`
- **`severity`** (insights/alerts, existing) — `info`, `low`, `medium`, `high`, `critical`
- **`alertType`** (existing) — `concentration-jump`, `share-shift`, `mirror-gap`, `yoy-drop`, `yoy-spike`, `tariff-change`, `anomaly-detected`
- **`anomalyType`** (existing) — `volume-spike`, `volume-drop`, `partner-shift`, `price-anomaly`, `mirror-divergence`, `structural-break`
- **`recordType`** (existing) — see the full list in "Premium output fields" above
- **`analysisMode`** (existing) — `raw`, `market-scan`, `supplier-risk`, `bilateral-audit`, `tariff-impact`, `portfolio-monitor`, `executive-brief`, `monitor`
- **`outputMode`** (existing) — `standard`, `decision`

Branching on these in Dify, n8n, Make, or your own code is safe across `schemaVersion` minor bumps.

***

### Responsible use

- UN COMTRADE Trade Intelligence queries publicly available official statistics from the United Nations COMTRADE database, the World Bank WITS API, and World Bank Open Data. It does not bypass authentication, scrape restricted endpoints, or access shipment-level customs records.
- Users are responsible for ensuring their use complies with applicable laws and platform terms, including the UN COMTRADE terms of use and any onward redistribution rules.
- Do not use insights, recommendations, or scenario records as a substitute for licensed legal, customs, or financial advice. They are decision support, not decisions.
- Cite the United Nations COMTRADE database when republishing data derived from this actor.

***

### FAQ

**What is UN COMTRADE Trade Intelligence?**
A decision engine for UN COMTRADE trade data. It queries the official UN COMTRADE database, computes supply-chain analytics (HHI, trends, mirror checks, anomalies, tariffs), and emits typed records — including a single consolidated decision record for AI agents and executive views.

**How is this different from the raw UN COMTRADE API?**
The raw UN COMTRADE API returns records. This actor returns finished analytics — ranked partners, HHI scores, YoY trends, anomaly classifications, tariff context, plain-English insights, recommendations, and a decision record. It also handles country name resolution, HS code lookup, multi-year windows, and cross-run state.

**How is this different from Panjiva or ImportGenius?**
Panjiva and ImportGenius work from shipment-level customs records — vessel names, container numbers, importer and exporter company names. UN COMTRADE Trade Intelligence works from official aggregated UN statistics and does not return shipment data. The two are complementary: use UN COMTRADE Trade Intelligence for macro supply-chain risk, use Panjiva or ImportGenius for shipment lookups.

**Can I use this for sanctions or compliance work?**
Yes, for the macro / mirror-data side. The `bilateral-audit` mode flags potential misinvoicing through reporter-versus-partner mirror discrepancies. It does not replace customs filings, sanctions list checks, or licensed compliance review.

**Can I run this on a schedule?**
Yes. Use `analysisMode: "monitor"` with a stable `watchlistId` and Apify's built-in scheduler. The actor saves per-run state in a named KV store and emits change-summary records describing what changed since the last run. Pair with a webhook for Slack or email alerts.

**How accurate are the insights and recommendations?**
The insights engine is rule-based, not generative — every claim is backed by computed evidence and carries a confidence score (0–1) and tier (high / medium / low). Setting `includeReasoning: true` adds an audit trail to every insight so reviewers can verify the call. Recommendations are template-based and tied to specific findings.

**What does the decision-readiness tag mean?**
Each high-level record carries `decisionReadiness: 'actionable' | 'monitor' | 'insufficient-data'`. Downstream automation (Slack routing, dashboards, agents) can filter on it so only actionable findings reach a human.

**How do I use this with an AI agent or LLM?**
Set `outputMode: "decision"` and the actor returns a single DecisionRecord with `headline`, `top3Actions`, `keyRisks`, `keyOpportunities`, `whatChanged`, `why`, `confidence`, and `decisionReadiness`. One tool call replaces multiple UN COMTRADE lookups and removes record-routing logic from the agent's prompt.

**What is HHI in trade analysis?**
The Herfindahl-Hirschman Index is a standard measure of market concentration, computed as the sum of squared shares. In trade context, an HHI above ~2,500 across trading partners indicates a highly concentrated supply chain. The actor returns HHI plus a `concentrationLevel` tag (`competitive`, `moderate`, `concentrated`, `highly-concentrated`) and the top 1 / 3 / 5 partner shares.

**What is mirror data and why does it matter?**
Mirror data is the comparison of a reporter's declared trade against the partner's declared trade in the same flow. Material divergences can indicate misinvoicing, sanctions evasion, or reporting gaps. The `bilateral-audit` mode flags discrepancies above 30% by default.

**Is monthly trade data supported?**
Yes. Set `frequency: "M"` and `lookbackPeriods` to the number of months you want. The actor pulls the rolling window, computes 3m / 6m / 12m rolling averages, and fits a linear trend slope. Monthly data is available for most reporters since around 2010.

**Is it legal to use UN COMTRADE data for commercial analysis?**
UN COMTRADE data is published by the United Nations Statistics Division and is generally available for analytical use, subject to the COMTRADE terms of use and citation requirements. Legality of any specific commercial application depends on jurisdiction and intended use — consult legal counsel before redistributing data or building a commercial product on top of it.

***

### Help us improve

If you encounter issues, you can help us debug faster by enabling run sharing in your Apify account:

1. Go to [Account Settings > Privacy](https://console.apify.com/account/privacy)
2. Enable **Share runs with public Actor creators**

This lets us see your run details when something goes wrong, so we can fix issues faster. Your data is only visible to the actor developer, not publicly.

***

### Support

Found a bug or have a feature request? Open an issue in the Issues tab on this actor's page. For custom solutions or enterprise integrations, reach out through the Apify platform.

# Changelog

This Actor's version history is a separate document: https://apify.com/ryanclinton/un-comtrade-search/changelog.md

# Actor input Schema

## `analysisMode` (type: `string`):

Pre-configured analysis workflow. Each mode auto-enables the right analytics and defaults. Use 'raw' for direct API access, 'monitor' for scheduled watchlist runs.

## `outputMode` (type: `string`):

'standard' emits all record types (trade, insight, alert, recommendation, summary, etc.) for maximum flexibility. 'decision' emits a single consolidated DecisionRecord with headline, top3Actions, keyRisks, keyOpportunities, whatChanged, why, and confidence — perfect for AI agents, dashboards, and 'give me the answer' workflows.

## `reporter` (type: `string`):

Reporting country name, ISO2/ISO3 code, or UN M49 numeric code. Accepts 'USA', 'US', 'America', 'Germany', 'DEU', '276', etc. Leave empty to query all reporters. Use 'reporters' (plural) for benchmark mode.

## `reporters` (type: `array`):

Array of reporter countries for cross-country benchmark mode. Example: compare EU members' semiconductor imports: \["Germany", "France", "Netherlands", "Italy"]. When set, the actor runs one query per reporter and returns ranked benchmark records.

## `partner` (type: `string`):

Partner country name, ISO2/ISO3 code, or UN M49 numeric code. Leave empty to include all trading partners.

## `partners` (type: `array`):

Array of partner countries for multi-partner benchmark mode.

## `commodity` (type: `string`):

HS commodity code (e.g. '0101' live horses, '2701' coal, '2709' crude petroleum, '8703' cars). Text search supported ('sugar' → HS 1701). Use 'TOTAL' for aggregate, or 'AG2'/'AG4'/'AG6' for hierarchy rollups. Leave empty for 'TOTAL'.

## `commodities` (type: `array`):

Array of HS codes for multi-commodity portfolio queries. Example: `["8542", "8471", "3002"]`. Overrides 'commodity' when set.

## `commodityPack` (type: `string`):

Preset HS code bundles for common sector-level analysis. Overrides 'commodity' and 'commodities' when set.

## `tradeFlow` (type: `string`):

Direction of trade flow. Set to 'All' to enable trade balance computation.

## `frequency` (type: `string`):

Annual (A) or Monthly (M) trade data. Monthly mode pulls the last N months and computes rolling averages and trend slope. Available for most reporters since ~2010.

## `lookbackPeriods` (type: `integer`):

Number of consecutive periods to query in monthly mode (e.g. 12 = last 12 months). Ignored in annual mode (use 'yoyYears' instead).

## `year` (type: `string`):

Trade year (e.g. '2023'). Comma-separated for multiple years. In monthly mode, YYYYMM format is also accepted. Leave empty for 2 years before current (most recent typically available). Ignored when yoyYears > 1 — the actor auto-computes the window.

## `subscriptionKey` (type: `string`):

Optional subscription key for the authenticated endpoint (up to 250,000 records per query). Without a key, the free preview endpoint is used (limited to 500 records). Get a key at https://comtradeplus.un.org/.

## `maxResults` (type: `integer`):

Maximum number of records per query. Without a subscription key, hard-capped at 500 by UN COMTRADE's free endpoint. With a subscription key, the ceiling is 250,000.

## `includeUnitValue` (type: `boolean`):

Adds derived pricePerKg and pricePerUnit fields. Helps detect HS-code misclassification and flag unusually cheap/expensive shipments. Auto-enabled by market-scan, bilateral-audit, tariff-impact, portfolio-monitor, executive-brief modes.

## `includeTradeBalance` (type: `boolean`):

Computes net bilateral trade balance per reporter-partner-commodity-year. Requires tradeFlow = 'All'. Auto-enabled by bilateral-audit, tariff-impact, executive-brief modes.

## `topPartners` (type: `integer`):

Returns ranked top-N partners by trade value with share %. Best with partner field empty. Auto-enabled by market-scan (10), supplier-risk (15), portfolio-monitor (5), executive-brief (10) modes.

## `includeHHI` (type: `boolean`):

Herfindahl-Hirschman Index across trading partners with concentration level tag and top-1/3/5 share. Auto-enabled by market-scan, supplier-risk, portfolio-monitor, executive-brief, monitor modes.

## `yoyYears` (type: `integer`):

Number of consecutive years to query for trend analysis. Returns YoY growth %, CAGR, and trend direction records. Auto-set by analysisMode (market-scan: 3, supplier-risk: 5, bilateral-audit: 3, tariff-impact: 5, portfolio-monitor: 3, executive-brief: 5, monitor: 3).

## `detectAnomalies` (type: `boolean`):

Flags records where latest value deviates >2 standard deviations from the historical mean. Requires yoyYears >= 3. Auto-enabled by supplier-risk, bilateral-audit, tariff-impact, portfolio-monitor, executive-brief, monitor modes.

## `includeMirrorCheck` (type: `boolean`):

Compares reporter values against partner mirror data. Flags potential misinvoicing or reporting gaps. Requires single reporter AND single partner. Auto-enabled by bilateral-audit mode.

## `includeTariffs` (type: `boolean`):

Fetches applied tariff rates from World Bank WITS. Capped at 100 records. Free public API. Auto-enabled by supplier-risk, tariff-impact, executive-brief modes.

## `includeMacroContext` (type: `boolean`):

Attaches GDP, GDP growth, inflation, population, and trade-as-%-of-GDP from World Bank Open Data. Auto-enabled by tariff-impact, executive-brief modes.

## `includeInsights` (type: `boolean`):

Runs the insights engine over computed analytics and emits 'insight' records with claim, headline, whyItMatters, evidence, severity, and a recommended next query. Turns raw data into decision support. Auto-enabled by all non-raw modes.

## `includeQualityScore` (type: `boolean`):

Emits 'quality' records with dataQualityScore (0-100), confidenceScore (0-1), confidenceLevel, decisionReadiness, and qualityFlags. Helps you trust the analysis. Auto-enabled by most modes.

## `includeAlerts` (type: `boolean`):

Emits structured 'alert' records when analytics cross thresholds: concentration-jump, share-shift, mirror-gap, yoy-drop, yoy-spike, anomaly-detected. Plug-and-play with Zapier/Make/Slack. Auto-enabled by supplier-risk, bilateral-audit, tariff-impact, portfolio-monitor, executive-brief, monitor modes.

## `alertThresholds` (type: `object`):

Override default alert thresholds. Defaults: shareShiftPp=10, mirrorDiscrepancyPct=30, hhiJump=500, yoyDropPct=20, yoySpikePct=50, anomalyZScore=2.

## `emitAlertsOnly` (type: `boolean`):

When true, skip raw trade records and summaries — output only alerts, insights, quality, and narrative. Use for scheduled monitoring jobs that should only return 'what changed'. Auto-enabled by monitor mode.

## `includeNarrative` (type: `boolean`):

Emits a 'summary' record with oneParagraphSummary, fiveBulletBrief, topFindings, top3Actions, and confidenceDrivers. Usable in emails, reports, and Slack messages without modification. Auto-enabled by executive-brief mode.

## `includeCausalAnalysis` (type: `boolean`):

Rule-based correlation engine that ranks likely drivers of observed trade changes (tariff change, GDP alignment, partner shift). Emits 'cause' records with ranked drivers and confidence. Requires multi-year data. Auto-enabled by supplier-risk, executive-brief modes.

## `includeRecommendations` (type: `boolean`):

Template-based recommendations with type (diversification / risk-mitigation / opportunity / investigation), severity, confidence, and suggestedAction. Auto-enabled by supplier-risk, portfolio-monitor, executive-brief, monitor modes.

## `simulate` (type: `object`):

Run a what-if simulation. Fields: tariffChangePct (e.g. 10 for +10pp tariff), gdpChangePct, demandShockPct, targetPartner. Uses historical elasticity for directional estimates. Returns 'scenario' records with heavy caveats — NOT a forecast.

## `includePortfolioInsights` (type: `boolean`):

Aggregates across the commodity pack or commodities\[] array. Returns a 'portfolio-insight' record with avg HHI, median growth, overall trend, and risk level. Auto-enabled by portfolio-monitor, executive-brief modes.

## `includeGraphEdges` (type: `boolean`):

Emits 'graph-edge' records (source, target, commodity, weight) ready to ingest into Neo4j, NetworkX, or any graph visualization tool.

## `baseline` (type: `string`):

Baseline period for delta-vs-baseline comparison. Single year ('2020') or range ('2020-2022'). Emits 'delta' records comparing the latest year against the baseline mean.

## `watchlistId` (type: `string`):

Stable identifier for this monitoring configuration. When set with includeChangeDetection, the actor saves per-run metrics in a named KV store and emits 'change-summary' records describing what changed since last run. Perfect for scheduled Apify runs.

## `includeChangeDetection` (type: `boolean`):

Compare current run against the previous run for this watchlistId. Emits 'change-summary' records with new/resolved alerts, changed metrics. Requires watchlistId. Auto-enabled by monitor mode.

## `includeReasoning` (type: `boolean`):

Adds a 'reasoning' array to each insight record with plain-English audit trail of how the insight was computed. Makes insights auditable and LLM-friendly. Auto-enabled by supplier-risk, portfolio-monitor, executive-brief modes.

## `outputProfile` (type: `string`):

Field-level filter for trade records (other record types pass through unchanged). 'minimal' = decision-only (recordType/eventId/reporter/partner/commodity/year/flow/value/summary). 'standard' = adds anomaly/tariff/price/share fields. 'llm' = LLM-friendly subset. 'full' = every field (default). Combine with outputMode='decision' to get the run-level decision plus minimal trade rows.

## `webhookUrl` (type: `string`):

Optional. Slack or Discord incoming webhook URL. On run completion, posts a rich embed with the DecisionRecord (headline, top 3 actions, key risks) + top alerts + coverage. Color-coded by alert severity / portfolio risk. Auto-detects vendor.

## `circuitBreakerThreshold` (type: `integer`):

Reserved for future per-run failure-streak abort. Currently surfaces in SUMMARY for downstream auditing. The existing per-request retry-with-backoff (3 attempts on 5xx) is the per-request equivalent.

## `includeAgentContract` (type: `boolean`):

Add a top-level agentContract { decision, confidence, nextAction, costToAct } on the DecisionRecord (and run-level on the SUMMARY) for MCP and AI-agent consumers. Maps decisionReadiness + alert severity to a stable nextAction enum (act-immediately/investigate-now/monitor-closely/no-action/gather-more-data/unknown).

## Actor input object example

```json
{
  "analysisMode": "raw",
  "outputMode": "standard",
  "reporter": "USA",
  "commodityPack": "none",
  "tradeFlow": "All",
  "frequency": "A",
  "maxResults": 100,
  "outputProfile": "full",
  "webhookUrl": "",
  "circuitBreakerThreshold": 0,
  "includeAgentContract": true
}
```

# Actor output Schema

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

No description

# 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 = {
    "reporter": "USA"
};

// Run the Actor and wait for it to finish
const run = await client.actor("ryanclinton/un-comtrade-search").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 = { "reporter": "USA" }

# Run the Actor and wait for it to finish
run = client.actor("ryanclinton/un-comtrade-search").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 '{
  "reporter": "USA"
}' |
apify call ryanclinton/un-comtrade-search --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ryanclinton/un-comtrade-search"
        }
    }
}
```

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/NJCh32GyIiVnSTzqO/builds/5wlVhE1zwjfCvcjXQ/openapi.json
