# Prediction Market Arbitrage Scanner (Kalshi & Polymarket) (`jiro90/prediction-market-arb-scanner`) Actor

Cross-venue fee-adjusted, depth-verified arbitrage scanner for Kalshi and Polymarket prediction markets.

- **URL**: https://apify.com/jiro90/prediction-market-arb-scanner.md
- **Developed by:** [Jiro](https://apify.com/jiro90) (community)
- **Categories:** Business, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 market_pairs

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/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

## Prediction Market Arbitrage Scanner (Kalshi & Polymarket)

A high-precision, fee-adjusted, and order-book-verified cross-venue arbitrage scanner for **Kalshi** and **Polymarket**.

***

### Why Most Prediction Market "Arbitrage Finders" Fail

If you look at raw top-of-book prices across prediction markets, you will find dozens of apparent "arbitrage" opportunities. In reality, **99% of them are mirages that will lose you money**:

1. **Taker Fees Devour the Spread**: Both legs of an arbitrage trade cross the spread and pay taker fees.
   - On **Kalshi**, taker fees follow a quadratic formula: $\text{Fee} = 0.07 \times \text{Contracts} \times P \times (1 - P)$. At $P = $0.50$, you pay **~1.75¢ per contract** plus balance rounding fees.
   - On **Polymarket**, dynamic fee schedules apply to taker orders (up to 7% on crypto, 4–5% on politics/sports/finance).
   - *Result*: A apparent **2.0¢ price gap is an instant loss after fees**.
2. **Top-of-Book Illusion (Lack of Depth)**: A quote might show 10¢ on Polymarket and 15¢ on Kalshi, but only 3 contracts may exist at 10¢. If you attempt to trade 100 contracts, your average fill price (VWAP) slides deeper into the book.
3. **Semantic False Matches (Dangerous Unhedged Bets)**:
   - *Template Collisions*: Two markets might share 95% of their question words ("Will \[Candidate] win the next presidential election?") while referring to completely different people in different countries.
   - *Entity Collisions*: Two markets mention the same person ("Will Jensen Huang become a trillionaire?" vs "Will Jensen Huang rejoin Nvidia?"), but ask totally unrelated questions.
   - *Resolution Date Divergence*: A market resolving in 2026 cannot be hedged against a market resolving in 2028.

This Actor solves all three problems by **simulating real fills across live order books**, **netting both venues' exact fee schedules**, and **filtering with a multi-stage semantic matching engine**.

***

### Features

- **Exact Fee Accounting**: Subtracts Kalshi and Polymarket taker fee schedules, including rounding quirks and per-category rates.
- **Live Order Book Depth Walking**: Computes volume-weighted average fill prices (VWAP) for your chosen contract size (`notionalSize`).
- **Precision Matching Pipeline**:
  - **Entity Agreement Gate**: Prevents template collisions across candidates, parties, and jurisdictions.
  - **Leg Agreement Gate**: Resolves Kalshi multi-outcome event markets (using `custom_strike`) and prevents candidate bleeding.
  - **Subject Signature Gate**: Strips entities to verify that underlying propositions actually overlap.
  - **Threshold & Date Gates**: Rejects conflicting strike values, directional conditions (`above` vs `below`), and diverging resolution windows.
- **Pay-Per-Event Billing**: Seamless Apify Pay-Per-Event (PPE) integration (`market_pair` for matched pairs scanned, and `arbitrage_opportunity` for positive net-edge opportunities).
- **DNS Resilience**: Built-in support for custom DNS servers (`1.1.1.1, 8.8.8.8`) to bypass network-level DNS sinkholes on Polymarket CloudFront domains.

***

### How It Works

```
1. Fetch Open Markets (Kalshi Trade API + Polymarket Gamma API)
   ↓
2. Semantic Normalization & Slot Extraction (Thresholds, Dates, Entities, Legs)
   ↓
3. Inverted Index Candidate Generation & Hard Precision Gates
   ↓
4. Fetch Live Order Books (Kalshi Book + Polymarket CLOB)
   ↓
5. Walk Depth to Size → Calculate VWAP → Subtract Fees on Both Legs
   ↓
6. Output Verified Arbitrage Opportunities & Detailed Spread Analytics
```

***

### Input Settings

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `minNetEdgePct` | `number` | `0.002` | Minimum net edge (after fees) to flag as `arbitrage` (e.g. `0.002` = 0.2%). |
| `notionalSize` | `integer` | `100` | Target trade size in contracts per leg used when walking depth. |
| `useOrderbooks` | `boolean` | `true` | When enabled, pulls real order books to verify liquidity and calculate VWAP. |
| `minMatchScore` | `integer` | `42` | Match confidence threshold (20–95%). Raise for strict precision, lower for recall. |
| `maxKalshiEvents` | `integer` | `2000` | Max Kalshi events to scan. |
| `maxPolymarketMarkets`| `integer` | `4000` | Max Polymarket markets to scan (ordered by 24h volume). |
| `kalshiCategories` | `array` | `[]` | Optional category filter (e.g., `["Elections", "Politics", "Financials"]`). |
| `includePairs` | `boolean` | `true` | Include all matched pairs in output, even if spread does not cover fees. |
| `feeModel` | `string` | `"conservative"`| Polymarket fee formula (`conservative`, `docs`, `exponent`). |
| `dnsServers` | `string` | `"1.1.1.1,8.8.8.8"`| Custom DNS resolvers to avoid Polymarket CloudFront connectivity issues. |

***

### Output Dataset Schema

Each result pushed to the default dataset contains full trade execution mechanics:

```json
{
  "type": "arbitrage",
  "score": 0.568,
  "matchReasons": [
    "entity match: naftali bennett <-> naftali bennett",
    "leg match: naftali bennett",
    "subject overlap: next"
  ],
  "matchWarnings": [],
  "cheapVenue": "polymarket",
  "richVenue": "kalshi",
  "cheapLeg": "buy YES",
  "richLeg": "buy NO (hedge)",
  "cheapPrice": 0.058,
  "richPrice": 0.922,
  "costPerUnit": 0.980,
  "grossEdgePerContract": 0.020,
  "netEdgePerContract": 0.0072,
  "netEdgePct": 0.0073,
  "sizeUsed": 100,
  "depthLimited": false,
  "fees": {
    "kalshiFee": 0.49,
    "polymarketFee": 0.23,
    "totalFee": 0.72
  },
  "kalshi": {
    "ticker": "KXBIC-26",
    "question": "Will Naftali Bennett be the next Prime Minister of Israel",
    "yesBid": 0.07,
    "yesAsk": 0.078
  },
  "polymarket": {
    "id": "12345",
    "question": "Will Naftali Bennett be the next Prime Minister of Israel?",
    "yesBid": 0.048,
    "yesAsk": 0.058
  },
  "scannedAt": "2026-11-19T09:15:00.000Z"
}
```

A final record of `type: "summary"` reports aggregate run statistics (total markets scanned, matched pairs, order books queried, and count of viable opportunities).

***

### Automated Scheduling & Webhooks

To run this scanner as an automated recurring alert pipeline:

1. In Apify Console, configure a **Schedule** (e.g. `*/10 * * * *` for every 10 minutes).
2. Attach an Apify **Webhook** triggered on `Run succeeded`.
3. Route the webhook payload to your notification handler (Discord, Telegram, Slack, or automated execution bot).

***

### Development & Testing

```bash
## Run unit test suite (30 offline tests)
npm test

## Run live smoke probe against active Kalshi & Polymarket markets
node test/live-probe.js 100 0.42
```

# Actor input Schema

## `kalshiCategories` (type: `array`):

Restrict the Kalshi scan to these categories (e.g., Elections, Politics, Financials, Economics). Leave empty for all categories.

## `maxKalshiEvents` (type: `integer`):

How many Kalshi events to pull. Higher finds more matches but takes longer.

## `maxPolymarketMarkets` (type: `integer`):

How many Polymarket markets to pull, ordered by 24h volume.

## `minMatchScore` (type: `integer`):

Cross-venue pairs below this similarity score are discarded. Raise for higher precision, lower for more recall.

## `minNetEdgePct` (type: `number`):

Minimum fee-adjusted edge to report an arbitrage opportunity (e.g. 0.002 = 0.2%).

## `notionalSize` (type: `integer`):

Size used when walking the order books to verify real liquidity and VWAP fill price.

## `useOrderbooks` (type: `boolean`):

Fetch depth for matched pairs and calculate VWAP at realisable size. Far more accurate than top-of-book prices.

## `maxOpportunities` (type: `integer`):

Maximum number of arbitrage records to emit.

## `includePairs` (type: `boolean`):

Output all matched pairs and spreads even when trading fees eliminate the net edge.

## `feeModel` (type: `string`):

Which Polymarket fee formula to use. 'conservative' takes the higher of docs vs exponent formula.

## `dnsServers` (type: `string`):

Comma-separated DNS server IPs (e.g. '1.1.1.1,8.8.8.8') to bypass ISP/network DNS poisoning of Polymarket hosts.

## Actor input object example

```json
{
  "kalshiCategories": [],
  "maxKalshiEvents": 2000,
  "maxPolymarketMarkets": 4000,
  "minMatchScore": 42,
  "minNetEdgePct": 0.002,
  "notionalSize": 100,
  "useOrderbooks": true,
  "maxOpportunities": 200,
  "includePairs": true,
  "feeModel": "conservative",
  "dnsServers": "1.1.1.1,8.8.8.8"
}
```

# Actor output Schema

## `opportunities` (type: `string`):

Full dataset containing fee-adjusted arbitrage opportunities and matched market pairs across Kalshi and Polymarket.

## `summary` (type: `string`):

JSON record with aggregate scan counts, matched pairs, order books checked, and top opportunities.

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("jiro90/prediction-market-arb-scanner").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("jiro90/prediction-market-arb-scanner").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 '{}' |
apify call jiro90/prediction-market-arb-scanner --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,jiro90/prediction-market-arb-scanner"
        }
    }
}
```

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/XqTbwCB7AP0KOld5H/builds/rJD5Hcc5VzjeUGDlu/openapi.json
