# Taiwan Margin Trading & Short Selling Balance (TWSE + TPEx) (`chamarix/taiwan-margin-trading`) Actor

Daily margin trading (融資) and short selling (融券) balances for all 2,200+ Taiwan listed & OTC stocks. Official TWSE/TPEx data, normalized JSON for retail sentiment analysis, squeeze screening, and quant research.

- **URL**: https://apify.com/chamarix/taiwan-margin-trading.md
- **Developed by:** [chris](https://apify.com/chamarix) (community)
- **Categories:** AI, Developer tools, Other
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 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.

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — 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

## Taiwan Stock Margin Trading & Short Selling Balance (TWSE + TPEx)

Get structured JSON access to **daily margin trading (融資) and short selling (融券) balances for every Taiwan-listed stock** — both the main board (TWSE) and the OTC market (TPEx / 櫃買中心) in a single, normalized schema.

Margin data is Taiwan's classic **retail sentiment indicator**. Combined with our institutional flow Actors, you can see both sides of the market: what the pros are doing ([TWSE](https://apify.com/chamarix/twse-institutional-trades) / [TPEx Institutional Trades](https://apify.com/chamarix/tpex-institutional-trades)) and what leveraged retail is doing (this Actor).

### Why this data matters

- **Margin balance (融資餘額)** is the standard proxy for leveraged retail positioning — rising balances into a rally signal froth; forced margin calls accelerate sell-offs
- **Short balance (融券餘額)** feeds short-squeeze screens, especially around shareholder-meeting recall deadlines (股東會強制回補)
- **Margin usage vs limit** flags stocks approaching regulatory lending caps
- Day-over-day balance deltas are a widely used factor in Taiwan quant models

The data is public on the TWSE and TPEx websites but split across two sites with different formats and calendars. This Actor normalizes both into one clean JSON schema.

### Output

One record per stock per trading day, 18 normalized fields. All quantities are in **lots (張, 1 lot = 1,000 shares)**:

```json
{
  "date": "2026-07-27",
  "market": "TWSE",
  "stock_code": "2330",
  "stock_name": "台積電",
  "margin_buy": 504,
  "margin_sell": 490,
  "margin_redemption": 23,
  "margin_balance_prev": 31915,
  "margin_balance": 31906,
  "margin_limit": 6483092,
  "short_sell": 2,
  "short_buy": 4,
  "short_redemption": 1,
  "short_balance_prev": 67,
  "short_balance": 64,
  "short_limit": 6483092,
  "offset": 5,
  "note": ""
}
```

| Field | Meaning |
|---|---|
| `margin_buy` / `margin_sell` | 融資買進 / 融資賣出 (new margin longs / margin longs closed) |
| `margin_redemption` | 現金償還 (cash repayment) |
| `margin_balance_prev` / `margin_balance` | 前日/今日融資餘額 |
| `margin_limit` | 次一營業日限額 (next-day regulatory cap) |
| `short_sell` / `short_buy` | 融券賣出 / 融券買進 (new shorts / short covering) |
| `short_redemption` | 現券償還 (share repayment) |
| `short_balance_prev` / `short_balance` | 前日/今日融券餘額 |
| `offset` | 資券互抵 (same-day margin-short offset) |

Balances always satisfy the accounting identity `prev + buy - sell - redemption = balance` (margin side) and `prev + sell - buy - redemption = balance` (short side) — the Actor validates this at parse time.

### Input

| Field | Type | Description |
|---|---|---|
| `startDate` | string (required) | `YYYY-MM-DD` |
| `endDate` | string | `YYYY-MM-DD` inclusive; empty = single day |
| `market` | string | `both` (default), `twse`, or `tpex` |
| `stockCodes` | array | Optional filter, e.g. `["2330", "5274"]`. Empty = all (~2,200 stocks/day) |

Example — one month of TSMC, Hon Hai and ASPEED margin data:

```json
{
  "startDate": "2026-07-01",
  "endDate": "2026-07-27",
  "market": "both",
  "stockCodes": ["2330", "2317", "5274"]
}
```

### Pricing & cost control

Pay per result: **$0.50 / 1,000 records**.

- Full market (TWSE + TPEx), one day: ~2,200 records ≈ $1.10
- Filtered to 5 tickers, one month: ~220 records ≈ $0.11

Use `stockCodes` to keep costs minimal when you only track a watchlist.

### Data source & reliability

- Direct from TWSE's official MI\_MARGN feed and TPEx's official margin balance feed — no third-party intermediaries
- Historical data available back to at least 2024 (both markets verified)
- Weekends skipped automatically; market holidays return no rows and are skipped
- Column-count and balance-identity guards: if either exchange changes its schema, the run fails loudly instead of returning silently corrupted data

### Use cases

- Retail sentiment / leverage factor research on Taiwan equities
- Short-squeeze screeners (high short balance + shrinking margin limit)
- Margin-call risk dashboards for brokers and prop desks
- Financial newsletters and market-recap automation
- Academic research on leveraged retail behavior

### Related Actors

- [TWSE Institutional Trades](https://apify.com/chamarix/twse-institutional-trades) — daily foreign/trust/dealer flows, main board
- [TPEx Institutional Trades](https://apify.com/chamarix/tpex-institutional-trades) — same for the OTC market
- [Taiwan Shareholding Dispersion (TDCC)](https://apify.com/chamarix/tdcc-shareholding-dispersion) — weekly retail vs whale ownership
- [Taiwan Monthly Revenue](https://apify.com/chamarix/taiwan-monthly-revenue) — monthly revenue of all listed companies

# Actor input Schema

## `startDate` (type: `string`):

Start date in YYYY-MM-DD format.

## `endDate` (type: `string`):

End date in YYYY-MM-DD format (inclusive). Leave empty to scrape only the start date.

## `market` (type: `string`):

Which market to fetch: both (TWSE listed + TPEx OTC), twse only, or tpex only.

## `stockCodes` (type: `array`):

Optional list of stock codes to filter (e.g., \['2330', '5274']). Leave empty to get all stocks.

## Actor input object example

```json
{
  "startDate": "2026-07-27",
  "endDate": "",
  "market": "both",
  "stockCodes": [
    "2330",
    "2317",
    "5274"
  ]
}
```

# 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 = {
    "startDate": "2026-07-27",
    "market": "both",
    "stockCodes": [
        "2330",
        "2317",
        "5274"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("chamarix/taiwan-margin-trading").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 = {
    "startDate": "2026-07-27",
    "market": "both",
    "stockCodes": [
        "2330",
        "2317",
        "5274",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("chamarix/taiwan-margin-trading").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 '{
  "startDate": "2026-07-27",
  "market": "both",
  "stockCodes": [
    "2330",
    "2317",
    "5274"
  ]
}' |
apify call chamarix/taiwan-margin-trading --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=chamarix/taiwan-margin-trading",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/WrhaRrEMXEgv58WjK/builds/mizUZw9aFnpZ2rWO1/openapi.json
