# API reference — UN Comtrade Export Market Finder

## One dataset item (the demo's Germany row, every field)

```json
{
  "itemId": "610910:IND:DEU:2025",
  "name": "Germany · HS 610910",
  "url": "https://comtradeplus.un.org/TradeFlow?Frequency=A&Flows=M&CommodityCodes=610910&Partners=all&Reporters=276&period=2025&AggregateBy=none&BreakdownMode=plus",
  "hsCode": "610910",
  "hsDescription": "T-shirts, singlets and other vests; of cotton, knitted or crocheted",
  "exporterCountry": "India",
  "exporterCountryCode": "IND",
  "marketCountry": "Germany",
  "marketCountryCode": "DEU",
  "marketComtradeCode": 276,
  "latestPeriod": "2025",
  "periods": [
    "2022",
    "2023",
    "2024",
    "2025"
  ],
  "newestPeriod": "2025",
  "importValueUsd": 3434767879,
  "growth1yPct": 16.6,
  "cagrPct": -0.9,
  "exporterValueUsd": 295419949,
  "exporterSharePct": 8.6,
  "topSuppliers": [
    {
      "country": "Bangladesh",
      "countryCode": "BGD",
      "valueUsd": 1509632406,
      "sharePct": 43.95,
      "unitValueUsdPerKg": 16.9
    },
    {
      "country": "Türkiye",
      "countryCode": "TUR",
      "valueUsd": 408303309,
      "sharePct": 11.89,
      "unitValueUsdPerKg": 33.13
    },
    {
      "country": "China",
      "countryCode": "CHN",
      "valueUsd": 208456884,
      "sharePct": 6.07,
      "unitValueUsdPerKg": 33.93
    }
  ],
  "unitValueUsdPerKg": 22.26,
  "unitValueUsdPerUnit": 3.7,
  "quantityUnit": "u",
  "exporterUnitValueUsdPerKg": 20.46,
  "exporterWorldUnitValueUsdPerKg": 35.46,
  "mirror": false,
  "mirrorOnly": false,
  "dataSource": "list",
  "mfnDutyPct": null,
  "preferentialDuty": null,
  "tariffYear": null,
  "tariffSource": null,
  "figureBasis": "importValueUsd: the market's imports from World in 2025; exporterSharePct and supplier shares: value ÷ that World total, same year; growth1yPct: 2025 vs the year before; cagrPct: 2022 → 2025",
  "landedUnitValueUsdPerKg": null,
  "flags": [],
  "targetFlagsMatched": [],
  "ruleScore": 70,
  "score": 70,
  "label": "hot",
  "fitScore": null,
  "scoreReasons": [],
  "summary": "",
  "generatedText": "Germany imported $3.43 B of HS 610910 in 2025, -0.9 % a year since 2022 (+16.6 % on the year before). India supplied $295.42 M (8.6 % share). Top supplier: Bangladesh with 44.0 %; the market pays $22.26/kg on average.",
  "recommendedNextStep": "Find importers in Germany who buy from Bangladesh (44.0 % at $16.90/kg) and quote against that price.",
  "aiModel": null,
  "assessedBy": "rules",
  "chargedEvent": "demo",
  "billedAs": "qualified-export-market-basic",
  "dedupeKey": "610910:IND:DEU:2025",
  "source": {
    "mode": "list",
    "query": "610910"
  },
  "scrapedAt": "2026-10-23T04:20:00+00:00"
}
```

## `OUTPUT` keys

| Key | Type | What it holds |
|---|---|---|
| `mode` | string | `demo` · `live` · `list` · `dataset` |
| `modeReason` | string | which rule picked the mode (the untouched sample, typed terms + `autoSwitchToLive`, `sourceMode`) — also the run log's first line |
| `qualified`, `candidates` | integer | markets delivered, markets that passed the free filters |
| `summary`, `summaryBy` | string | the run summary (LLM-3, ≤ 80 words) and who wrote it (`rules` = the top-5 list) |
| `topMarkets` | object[] | market, hsCode, score, importValueUsd, exporterSharePct, url — the top 10 |
| `hsCodes`, `hsResolved` | string[], object[] | the run's HS codes; per product: hsCode, heading, confidence, method, flagged |
| `exporter` | object | country, comtradeCode |
| `periodsUsed` | object | HS code → the periods read |
| `comtradeRecords`, `comtradeCalls`, `rawRowsRead` | integer | the UN Comtrade records this run read (≈ 4,730 per HS code, measured) and the calls made |
| `comtradeRecordsKeyless` | integer | the account's running keyless total — the licence counter: the status warns at 70,000, keyless runs stop at 95,000 and ask for your free `comtradeKey` |
| `termsFromGoal` | string[] | the product searched from `goalDescription` when no HS code or product was typed |
| `stats` | object | the funnel: discovered, skipped_* per reason, ai_* counts |
| `chargedEvents`, `chargeSplit`, `freeTierRemaining` | object, object, integer | what was billed |
| `skips` | object | reason → the market names each free rule dropped (`below_min_import_value`, `outside_markets`, `excluded_market`, `exporter_own_country`); `allowList` keeps a market the size rule dropped |
| `tariffs` | object | `{markets, withMfn, withPreference, calls, errors}` of the WITS duty read |
| `digestEmailed`, `digestSlack`, …, `digestDeliveredTo`, `digestCharge` | bool, string[], string | where the digest went; `digest-delivered` is charged only when `digestDeliveredTo` is not empty |
| `aiCoverage`, `aiTokens`, `aiError` | object, object, string | AI-assessed vs rule-scored, tokens per market, why the AI was off |
| `timing` | object | sourceSecs, tariffSecs, aiSecs, aiSecsPerUnit, totalSecs |
| `trend`, `history` | object, object[] | vs the last run of this search; every run of it |
| `ok`, `outcome`, `sourceError`, `sourceStatus` | bool, string, string, object | the run outcome (README → Run outcomes); `sourceStatus.codesNotRead` = the HS codes the keyless hourly quota left for the next run |
| `attribution` | string | "Data: UN Comtrade …" |

**The AI reserve:** while the AI is unavailable, rule-scored markets use your free ones too — except the last 5, kept
for your first AI-assessed markets (`chargeSplit.freeKeptForAi`). The status says only "N free markets left".

## Webhook bodies

`{"event": "export_market.qualified", "export_market": {…one item…}, "runId": "…"}` per market
(`webhookBatchSize: 1`), or `{"event": "export_markets.qualified", "export_markets": [{…}], "runId": "…"}` per batch.
A 429 / 5xx is retried once after 2 s; a failed POST is re-POSTed next run, never charged again — a webhook failure
never fails the run. `webhookSecret` signs each POST (`X-Signature: sha256=<HMAC of the raw body>`).

## Which call runs what

The mode that runs = `sourceMode`, except `{}` = the free demo. Over the API nothing switches the mode; only a Console
run whose untouched sample rows sit next to a typed HS code starts the live search (`autoSwitchToLive`, Console only).

| Input shape | `OUTPUT.mode` | Can it charge? |
|---|---|---|
| `{}` or the untouched form (the sample rows) | `demo` | no — sample rows are `chargedEvent: demo` |
| Console only: the sample rows + your HS code, product or goal typed next to them | `live` | yes — per ranked market |
| `sourceMode: "live"` (older alias `"actor"`) + `hsCodes` / `products` | `live` | yes — per ranked market |
| `sourceMode: "list"` + your own `itemsList` rows | `list` | yes — per ranked market |
| `sourceMode: "dataset"` + `datasetId` | `dataset` | yes — per ranked market |

`OUTPUT.modeReason` names the rule that picked the mode; the run log's first line repeats it.

## Flags

| Flag | Meaning |
|---|---|
| `fast_growing` | imports grow 10 % a year or more (CAGR, else the last year), no figure negative |
| `shrinking` | imports fell on both figures: the CAGR and the last year |
| `untapped` | your country sells nothing there yet |
| `foothold` | you already sell there, under 5 % share — room to grow |
| `you_lead` | your country is the market's biggest supplier already |
| `price_competitive` | your price per kg is at least 10 % below what the market pays on average |
| `premium_market` | the market pays at least 20 % more per kg than your price |
| `concentrated_supply` | one supplier holds 50 % or more of the market |
| `mirror_data` | your figures come from your own country's export report (the importer did not report them) |
| `stale_period` | the market's newest published year is older than other markets' |
| `no_weight_data` | no weight reported, so no price per kg |
| `hs_guessed` | the HS code was matched from your product description with low confidence — check it |
| `duty_advantage` | you enter on a preferential duty below the market's standard (MFN) rate |
| `duty_disadvantage` | you pay 10 % duty or more there (no preference) — it eats your price edge |

## Include and exclude lists — the merge rule

`markets` (and PortLess's code-only alias `countries`) is the include list: both are merged (union). `excludeCountries`
(ISO codes / names, never read — no Comtrade call) and `suppressionList` (names, ISO codes or dedupe keys, never
output) are the exclude lists. **An exclude always wins** — over `markets` and over `allowList`. `allowList` only
stops the size rule (`minImportValueUsd`) from dropping a market; `minScore` still applies.

## Tested combinations

Each input below is a test input of the Actor (tests/ and storage-example/); anything else is untested.

| Call | Input JSON |
|---|---|
| Free demo | `{}` |
| Live search, rules only | `{"sourceMode": "live", "hsCodes": ["610910"], "exporterCountry": "IN", "enableAi": false, "maxQualified": 30}` |
| Live search, capped probe | `{"sourceMode": "live", "hsCodes": ["610910"], "exporterCountry": "IN", "enableAi": false, "maxQualified": 5, "maxDiscoveryChargeUsd": 0.05}` |
| Live, product description | `{"products": ["frozen shrimp"], "exporterCountry": "IN"}` |
| Own rows | `{"sourceMode": "list", "itemsList": [<Comtrade rows>], "hsCodes": ["610910"], "exporterCountry": "IN"}` |
| Dataset | `{"sourceMode": "dataset", "datasetId": "<id>", "exporterCountry": "IN"}` |
| AI with an own key | `{"hsCodes": ["610910"], "exporterCountry": "IN", "llmProvider": "byok", "llmApiKey": "<key>"}` |
| Include / exclude | `{"hsCodes": ["610910"], "exporterCountry": "IN", "markets": ["DE", "FR"], "excludeCountries": ["FR"]}` |
| Monthly | `{"hsCodes": ["610910"], "exporterCountry": "IN", "frequency": "M", "months": 12}` |

## Run time per mode

The measured table is the README FAQ "How long does a run take?" — `OUTPUT.timing` (sourceSecs, tariffSecs, aiSecs)
measures every run.

## Monthly series, origins and duties (PortLess A.26, A.35)

| Field / input | What it is |
|---|---|
| `frequency: "M"`, `months` (12) | the newest published month and the `months` − 1 before it, plus the same month a year earlier; one Comtrade call per month and HS code |
| `monthly[]` | `{period, importValueUsd, netWeightMt, unitValueUsdPerMt}` per month read, oldest first (null on annual rows) |
| `origins[]` | every supplying country of the latest period, biggest first (up to `rivalSuppliers`): `{country, countryCode, valueUsd, netWeightMt, unitValueUsdPerMt, sharePct, indiaPriceAdvantagePct, dataPeriod}` — `indiaPriceAdvantagePct` = how much cheaper the exporter (`exporterCountry`) is than that origin, in % of its price |
| `dataPeriod`, `exporterUnitValueUsdPerMt` | the period of every figure in the row; the exporter's price per tonne (to this market, else to the world) |
| `excludeCountries` | markets never read or charged — no Comtrade call is spent on them (merge rule above) |
| `includeTariffs` (true) | `mfnDutyPct`, `preferentialDuty {agreement, ratePct, dataYear}`, `tariffYear`, `tariffSource` and `landedUnitValueUsdPerKg` for the top `maxQualified` markets, read before the AI and the ranking, from the World Bank's WITS API (UNCTAD TRAINS, simple average over the tariff lines in the HS6; newest of the last 6 years with data). `preferentialDuty: null` = the exporter pays MFN; `agreement` is named for an Indian exporter only (WITS names none) |
| `OUTPUT.tariffs` | `{markets, withMfn, withPreference, calls, errors}` |

## Supplier flows view (`view: flows`, 0.3.0)

One row per importer × supplier × HS code × period, from each importer's own official source:

| Importer | Source | Currency → USD | Key |
|---|---|---|---|
| EU members, `EU27` (in `markets`) | Eurostat Comext DS-045409, `flow=1`, value + `QUANTITY_IN_100KG` × 100 = kg | EUR at Eurostat `ert_bil_eur_m` monthly average (annual = mean of the months) | none |
| `GB` | UK HMRC OTS API, FlowTypeId 1 + 3 (EU + non-EU imports), ≤ 60 requests a minute | GBP at the cross rate USD/EUR ÷ GBP/EUR from the same Eurostat table | none |
| `US` | US Census International Trade API, general imports, customs value (`GEN_VAL_MO`; December's `GEN_VAL_YR` = the year) | USD | `censusApiKey` (free: api.census.gov/data/key_signup.html) |
| every other | UN Comtrade through the Actor's client (≤ 1 request a second, the keyless licence counter) | USD | `comtradeKey` recommended; keyless preview otherwise |

The ECB API is never called (its robots.txt disallows ClaudeBot). ≥ 1 s between calls to one host, one retry on 429 /
5xx honouring `Retry-After`, no proxy.

**Inputs (API only unless noted):** `view` (form) · `censusApiKey` (form, secret) · `flowFrequency` `M` (default) / `A`
· `flowPeriods` 1–24 (default 1: the newest period per importer) · `years` (with `A`: those years) · `topSuppliers`
(default 15, 0 = all; your row always kept) · `minSharePct` (default 0) · `includeMirror` (default true) · `markets`
(importers; `EU27` allowed here; empty = the 10 biggest importers of the HS code by UN Comtrade's newest year) ·
`maxQualified` caps the tables.

**Billing:** one `qualified-export-market-basic` per table (importer × HS × period × source), on its first row; the
table's other rows carry `chargedEvent: same-unit` and `billedAs` of the first. Free tier, demo, spend cap and
`dedupeAcrossRuns` (memory key `flows:<hs>:<importer>:<period>:<source>`) work as in the ranked view.

**Row** (HS 090411, Germany ← India, 2024, Eurostat):

```json
{
  "itemId": "6f1c1c8b3f0e2a41", "name": "Germany ← India · HS 090411 · 2024", "view": "flows",
  "url": "https://ec.europa.eu/eurostat/api/comext/dissemination/statistics/1.0/data/DS-045409?format=JSON&…",
  "reporter": "DE", "reporterName": "Germany", "partner": "IN", "partnerName": "India",
  "hsCode": "090411", "hsDescription": "Pepper of the genus Piper; neither crushed nor ground", "period": "2024",
  "frequency": "A", "dataPeriod": "2024 (year, Eurostat)",
  "valueUsd": 5927890.21, "valueNative": 5479276.0, "currency": "EUR", "fxRate": 1.081875,
  "fxSource": "Eurostat ert_bil_eur_m (monthly average)", "valueBasis": "CIF",
  "quantity": 876873.0, "unit": "kg", "netWeightKg": 876873.0, "weightEstimated": false,
  "unitValueUsdPerMt": 6760.33, "unitValueNativePerMt": 6248.65, "sharePct": 4.22, "rank": 5, "mirror": false,
  "source": "eurostat", "sourceUrl": "…the same call…", "attribution": "Source: Eurostat (DS-045409, …)",
  "exporterCountry": "IN",
  "market": {"totalValueUsd": 140452180.4, "totalNetWeightKg": 23762243.0, "suppliers": 62, "exporterSharePct": 4.22,
             "exporterRank": 5, "topSupplier": {"partner": "VN", "sharePct": 55.47}, "exporterPriceGapPct": 14.37,
             "changePct": null, "latestPeriod": "2024"},
  "flags": ["foothold", "concentrated_supply"], "flowFlags": ["exporter"],
  "dedupeKey": "090411:DE:IN:2024:eurostat", "chargedEvent": "same-unit"
}
```

(`valueUsd` / `fxRate` above are illustrative of the shape; the run computes them from the published 2024 rates.)

**Flags:** `flags` holds the ranked view's names with their definitions (`untapped`, `foothold`, `you_lead`,
`price_competitive`, `premium_market`, `concentrated_supply`, `mirror_data`, `stale_period`, `no_weight_data`);
`flowFlags` the flows markers: `exporter` · `mirror_data` (partners' exports, FOB) · `estimated_weight` (no price per
tonne) · `no_weight` · `concentrated_supply` (top supplier ≥ 60 %) · `exporter_gaining` / `exporter_losing` (share ± 2
points vs the period before) · `premium_price` (your $/t ≥ 15 % above the market average) · `stale_period` (newest
period > 18 months old, not on pinned `years`).

**`market`:** `totalValueUsd`, `totalValueNative`, `totalNetWeightKg`, `suppliers`, `exporterSharePct`, `exporterRank`,
`exporterValueUsd`, `exporterUnitValueUsdPerMt`, `exporterShareChangePts`, `topSupplier`, `cheapestSupplierUsdPerMt`
(suppliers ≥ 1 %), `meanUnitValueUsdPerMt` (value ÷ weight over suppliers with a weight), `exporterPriceGapPct`,
`changePct` (the importer's total vs the period before, in the source currency), `latestPeriod`.

**`OUTPUT`:** `ok`, `outcome`, `view`, `mode`, `hsCodes`, `reporters`, `routes`, `rows`, `markets`, `refused[]`
(`reporter`, `source`, `reason`, `fallback`), `notes`, `queries[]` (every call, no key), `sources` (calls, records,
latest period per source), `attributions`, `censusNotice`, `comtradeRecords`, `comtradeRecordsKeyless`,
`marketSummaries`, `chargedEvents`, `costUsd`, `skippedAsDelivered`.

**Attributions:** Source: Eurostat — Eurostat is not responsible for the use of these data · Contains public sector
information licensed under the Open Government Licence v3.0 (HM Revenue & Customs) · This product uses the Census
Bureau Data API but is not endorsed or certified by the Census Bureau · UN Comtrade.

## AI sample (the same market, AI on)

The README's before/after: Netherlands, HS 610910, India, `aiModel: google:gemini-3.5-flash-lite` (the own-key
default), run 2026-10-23 on the AI example.

```json
{
  "name": "Netherlands · HS 610910",
  "ruleScore": 66,
  "fitScore": 76,
  "score": 76,
  "label": "hot",
  "assessedBy": "ai",
  "scoreReasons": ["India holds a 6.48 % share ($86.78 M) with a price of $20.65 per kg", "Top supplier Bangladesh holds 23.07 % share at $13.04 per kg"],
  "generatedText": "The Netherlands is a massive $1.34 B market that grew 11.4 % in 2025, offering a strong foothold where India already holds a 6.48 % share ($86.78 M). …",
  "recommendedNextStep": "Verify distributor margins for Indian cotton T-shirts against Bangladesh's $13.04 per kg price point before outreach.",
  "aiModel": "google:gemini-3.5-flash-lite"
}
```
