# UN Comtrade Trade Data Scraper - Bilateral Trade by HS Code (`thirdwatch/trade-data-scraper`) Actor

Scrape bilateral trade data from UN Comtrade. Get import/export values between any two countries at HS code level. Find top traded product categories, track trade trends over time. Covers 200+ countries, all HS codes.

- **URL**: https://apify.com/thirdwatch/trade-data-scraper.md
- **Developed by:** [Thirdwatch](https://apify.com/thirdwatch) (community)
- **Categories:** E-commerce, Automation, Lead generation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.90 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## UN Comtrade Trade Data Scraper

Scrape bilateral trade data between any two countries from the UN Comtrade database. Get import/export values broken down by HS (Harmonized System) product codes -- perfect for identifying top traded product categories and tracking trade trends over time.

### What data is available?

UN Comtrade is the world's largest repository of international trade statistics, maintained by the United Nations. This actor fetches:

- **Bilateral trade flows** between any two countries (200+ countries supported)
- **HS code level detail** -- from 2-digit chapters (e.g., "85 - Electrical machinery") down to 6-digit subheadings
- **Trade values** in USD, including CIF (cost, insurance, freight) for imports and FOB (free on board) for exports
- **Weight and quantity** data where available
- **Annual or monthly** data frequency
- **Multi-year data** for trend analysis

### Example use cases

- **Find top imports from China to India in electronics:** Set reporter=India, partner=China, hsCode=85, flow=imports
- **Track India-China trade trends over 4 years:** Set years=2020,2021,2022,2023
- **Identify what India exports to the USA:** Set reporter=India, partner=USA, flow=exports
- **Find specific product trade values:** Use 4 or 6-digit HS codes (e.g., 8517 for telecom equipment)

### Input

| Field | Description | Default |
|-------|-------------|---------|
| reporterCountry | The country reporting the trade | India |
| partnerCountry | The trade partner country | China |
| hsCode | HS code filter (2/4/6-digit). Empty = all chapters | (empty) |
| flow | Trade direction: "imports" or "exports" | imports |
| years | Year(s), comma-separated for trends | 2023 |
| frequency | "annual" or "monthly" | annual |
| maxResults | Max records to return | 100 |

### Output fields

| Field | Description |
|-------|-------------|
| hs_code | Harmonized System product code |
| hs_description | Human-readable product description |
| trade_value_usd | Total trade value in US dollars |
| cif_value_usd | CIF value (cost + insurance + freight, for imports) |
| fob_value_usd | FOB value (free on board, for exports) |
| net_weight_kg | Net weight in kilograms |
| quantity | Quantity in the reported unit |
| quantity_unit | Unit of measurement for quantity |
| year | Reference year |
| period | Period code (year for annual, YYYYMM for monthly) |
| reporter_country | Reporting country name |
| partner_country | Partner country name |
| flow | "import" or "export" |
| unit_price_usd | Calculated: trade_value / quantity (or weight) |

Results are sorted by trade_value_usd descending, so the biggest trade categories come first.

### Supported countries (top 20 trading nations)

India, China, USA, UK, Germany, Japan, South Korea, France, Italy, Canada, Australia, Brazil, Mexico, Indonesia, Thailand, Vietnam, Malaysia, Singapore, UAE, Saudi Arabia

You can also pass numeric M49 country codes directly for countries not in this list.

### Technical details

- Pure HTTP actor (no browser needed), runs on 256 MB memory
- Uses the UN Comtrade public preview API (no authentication required)
- Data typically lags 1-2 years behind current date
- No proxy needed -- UN Comtrade has no anti-bot protection

# Actor input Schema

## `reporterCountry` (type: `string`):

The reporting country (who reports the trade). Select from the list or enter a numeric M49 code.
## `partnerCountry` (type: `string`):

The trade partner country. Select from the list or enter a numeric M49 code.
## `hsCode` (type: `string`):

Harmonized System code to filter by. Use 2-digit chapter (e.g., '85' for electronics, '84' for machinery), 4-digit heading (e.g., '8517' for telecom equipment), or 6-digit subheading. Leave empty for all chapters.
## `flow` (type: `string`):

Direction of trade. 'imports' = goods coming INTO the reporter country FROM the partner. 'exports' = goods going OUT of the reporter TO the partner.
## `years` (type: `string`):

Year(s) to fetch data for. Single year: '2023'. Multiple years for trends: '2020,2021,2022,2023'. Available data typically lags 1-2 years.
## `frequency` (type: `string`):

Annual data gives yearly totals. Monthly data gives per-month breakdowns (more records).
## `maxResults` (type: `integer`):

Maximum number of trade records to return, sorted by trade value descending (top categories first).

## Actor input object example

```json
{
  "reporterCountry": "India",
  "partnerCountry": "China",
  "hsCode": "",
  "flow": "imports",
  "years": "2023",
  "frequency": "annual",
  "maxResults": 100
}
````

# 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 = {
    "reporterCountry": "India",
    "partnerCountry": "China",
    "hsCode": "",
    "flow": "imports",
    "years": "2023",
    "frequency": "annual",
    "maxResults": 100
};

// Run the Actor and wait for it to finish
const run = await client.actor("thirdwatch/trade-data-scraper").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 = {
    "reporterCountry": "India",
    "partnerCountry": "China",
    "hsCode": "",
    "flow": "imports",
    "years": "2023",
    "frequency": "annual",
    "maxResults": 100,
}

# Run the Actor and wait for it to finish
run = client.actor("thirdwatch/trade-data-scraper").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{
  "reporterCountry": "India",
  "partnerCountry": "China",
  "hsCode": "",
  "flow": "imports",
  "years": "2023",
  "frequency": "annual",
  "maxResults": 100
}' |
apify call thirdwatch/trade-data-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=thirdwatch/trade-data-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "UN Comtrade Trade Data Scraper - Bilateral Trade by HS Code",
        "description": "Scrape bilateral trade data from UN Comtrade. Get import/export values between any two countries at HS code level. Find top traded product categories, track trade trends over time. Covers 200+ countries, all HS codes.",
        "version": "1.0",
        "x-build-id": "L5t72x6cehZ8FQoSB"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/thirdwatch~trade-data-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-thirdwatch-trade-data-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/thirdwatch~trade-data-scraper/runs": {
            "post": {
                "operationId": "runs-sync-thirdwatch-trade-data-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/thirdwatch~trade-data-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-thirdwatch-trade-data-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "properties": {
                    "reporterCountry": {
                        "title": "Reporter Country",
                        "enum": [
                            "India",
                            "China",
                            "USA",
                            "UK",
                            "Germany",
                            "Japan",
                            "South Korea",
                            "France",
                            "Italy",
                            "Canada",
                            "Australia",
                            "Brazil",
                            "Mexico",
                            "Indonesia",
                            "Thailand",
                            "Vietnam",
                            "Malaysia",
                            "Singapore",
                            "UAE",
                            "Saudi Arabia"
                        ],
                        "type": "string",
                        "description": "The reporting country (who reports the trade). Select from the list or enter a numeric M49 code.",
                        "default": "India"
                    },
                    "partnerCountry": {
                        "title": "Partner Country",
                        "enum": [
                            "India",
                            "China",
                            "USA",
                            "UK",
                            "Germany",
                            "Japan",
                            "South Korea",
                            "France",
                            "Italy",
                            "Canada",
                            "Australia",
                            "Brazil",
                            "Mexico",
                            "Indonesia",
                            "Thailand",
                            "Vietnam",
                            "Malaysia",
                            "Singapore",
                            "UAE",
                            "Saudi Arabia"
                        ],
                        "type": "string",
                        "description": "The trade partner country. Select from the list or enter a numeric M49 code.",
                        "default": "China"
                    },
                    "hsCode": {
                        "title": "HS Code (optional)",
                        "type": "string",
                        "description": "Harmonized System code to filter by. Use 2-digit chapter (e.g., '85' for electronics, '84' for machinery), 4-digit heading (e.g., '8517' for telecom equipment), or 6-digit subheading. Leave empty for all chapters.",
                        "default": ""
                    },
                    "flow": {
                        "title": "Trade Flow",
                        "enum": [
                            "imports",
                            "exports"
                        ],
                        "type": "string",
                        "description": "Direction of trade. 'imports' = goods coming INTO the reporter country FROM the partner. 'exports' = goods going OUT of the reporter TO the partner.",
                        "default": "imports"
                    },
                    "years": {
                        "title": "Years",
                        "type": "string",
                        "description": "Year(s) to fetch data for. Single year: '2023'. Multiple years for trends: '2020,2021,2022,2023'. Available data typically lags 1-2 years.",
                        "default": "2023"
                    },
                    "frequency": {
                        "title": "Data Frequency",
                        "enum": [
                            "annual",
                            "monthly"
                        ],
                        "type": "string",
                        "description": "Annual data gives yearly totals. Monthly data gives per-month breakdowns (more records).",
                        "default": "annual"
                    },
                    "maxResults": {
                        "title": "Max Results",
                        "minimum": 1,
                        "maximum": 10000,
                        "type": "integer",
                        "description": "Maximum number of trade records to return, sorted by trade value descending (top categories first).",
                        "default": 100
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
