Metadata-Version: 2.4
Name: veynor
Version: 1.5.8
Summary: Prediction market intelligence for agents and traders — Kalshi + Polymarket
Author-email: Veynor <hello@veynor.xyz>
License: MIT
Project-URL: Homepage, https://veynor.xyz
Project-URL: Repository, https://github.com/veynor/veynor-python
Project-URL: API Docs, https://veynor.xyz/agents
Keywords: prediction-markets,kalshi,polymarket,finance,trading,quant
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.28
Requires-Dist: click>=8.0
Provides-Extra: trade
Requires-Dist: py-clob-client-v2>=0.1; extra == "trade"
Requires-Dist: py-clob-client>=0.19; extra == "trade"
Requires-Dist: eth-account>=0.11; extra == "trade"
Requires-Dist: cryptography>=41.0; extra == "trade"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: mypy; extra == "dev"

# veynor

Python client for the [Veynor](https://veynor.xyz) prediction market intelligence API.

Cross-venue data and trading across Kalshi and Polymarket: whale trades, smart money signals, arb opportunities, market search, price history, and order execution — in a single `import`.

```python
pip install veynor
```

---

## Quickstart

```python
import veynor

client = veynor.Client(api_key="vey_sk_...")

# Whale trades across both venues
whales = client.whales(venue="all", min_notional=10_000)
for t in whales["trades"]:
    print(t["platform"], t["market"], t["side"], f"${t['notional']:,.0f}")

# Arb opportunities between Kalshi and Polymarket
arb = client.signals(signal_type="arb_opportunities")
for opp in arb["arb_opportunities"]:
    print(opp)
```

Get a free API key at [veynor.xyz/agents](https://veynor.xyz/agents).

---

## Authentication

Pass your key directly or via environment variable:

```python
# Option 1: direct
client = veynor.Client(api_key="vey_sk_...")

# Option 2: environment variable
# export VEYNOR_API_KEY=vey_sk_...
client = veynor.Client()
```

---

## Methods

### `client.whales()`

Recent large trades across Kalshi and Polymarket.

```python
whales = client.whales(
    venue="all",           # "all" | "kalshi" | "polymarket"
    min_notional=8_000,    # minimum trade size in USD
    category="Politics",   # "All" | "Sports" | "Politics" | "Other"
    limit=20,
)
# Returns: { summary, trades: [...], meta }
```

### `client.top_markets()`

Top markets by 24-hour volume.

```python
markets = client.top_markets(
    venue="all",
    category="All",
    limit=10,
)
# Returns: { summary, kalshi: [...], polymarket: [...], meta }
```

### `client.search()`

Search markets by keyword across both venues. Results include current YES price, 24-hour volume, end date, spread, and liquidity.

```python
results = client.search("fed rate", venue="all", limit=10)
# Returns: { summary, polymarket: [...], kalshi: [...], meta }
# Each market includes: title, yes_price, volume_24h, end_date, spread_cents, liquidity, url
```

### `client.market()`

Full details for a specific market.

```python
# Polymarket: use condition ID
m = client.market("polymarket", "0x1234...")

# Kalshi: use ticker
m = client.market("kalshi", "KXNBA-25-LAL")

# Returns: { summary, market: {...}, meta }
```

### `client.signals()`

Alpha signals: wide spreads, price movers, cross-venue arb.

```python
signals = client.signals(
    signal_type="all",   # "all" | "wide_spreads" | "price_movers" | "arb_opportunities"
    limit=10,
)
# Returns: { summary, wide_spreads, price_movers, arb_opportunities, meta }
```

### `client.positions()`

Open positions for a Polymarket wallet address. No private key required.

```python
for p in client.positions("0xabc..."):
    print(p["title"], p["cashPnl"])
```

### `client.intelligence()`

Natural-language prediction market query with AI synthesis. The most powerful single call — describe what you want to know and get back an AI-synthesized analysis plus matching markets across both venues.

```python
result = client.intelligence("what are markets saying about Iran?")
print(result["summary"])

for m in result["markets"]["kalshi"]:
    print(m["title"], m["yes_price"])

for m in result["markets"]["polymarket"]:
    print(m["question"], m["yes_price"])

# Returns: { summary, markets: { kalshi: [...], polymarket: [...] }, meta }
```

Intent is detected automatically:
- Topic queries (*"what are markets saying about Iran?"*) → matching markets + synthesis
- Signal queries (*"any unusual volume today?"*) → movers/spikes/spreads + signal summary
- Trade ideas (*"find edge in crypto"*) → markets + whale data + trade-angle analysis

---

### `client.pulse()`

AI-synthesized plain-English market briefing. Covers top markets by volume, whale activity, price movers, volume spikes, and wide spreads in a single call. Synthesis is powered by Claude Haiku on the server — no LLM setup needed on your end.

```python
pulse = client.pulse(
    venue="all",         # "all" | "kalshi" | "polymarket"
    category="All",      # "All" | "Sports" | "Politics" | "Other"
)
print(pulse["summary"])
# Returns: { summary (plain-English briefing), highlights, meta }
```

### `client.topic()`

Cross-venue market snapshot for a topic. Returns an AI-synthesized summary and a ranked list of markets with YES price and 24-hour volume — across both Kalshi and Polymarket in one call.

```python
data = client.topic(
    tag="crypto",       # crypto | geopolitics | trump | us_politics | macro | sports
    limit=20,
)
print(data["summary"])
for m in data["markets"]:
    print(m["title"], m["yes_price"], m["volume_24h"], m["platform"])
# Returns: { summary, markets: [...], meta: { total, kalshi_count, polymarket_count } }
```

### `client.usage()`

Check your credit balance. Always free.

```python
u = client.usage()
print(u["tier"], u["credits_remaining"])
```

---

## Credit costs

| Method              | Credits |
|---------------------|---------|
| `intelligence()`    | 5       |
| `pulse()`           | 5       |
| `signals()`         | 3       |
| `topic()`           | 3       |
| `whales()`          | 2       |
| `top_markets()`     | 1       |
| `search()`          | 1       |
| `market()`          | 1       |
| `price_history()`   | 1       |
| `usage()`           | 0       |

Free tier: 100 credits/month. Upgrade at [veynor.xyz/agents](https://veynor.xyz/agents).

---

## Exceptions

```python
from veynor import VeynorError, AuthError, RateLimitError

try:
    whales = client.whales()
except AuthError:
    print("Invalid or expired API key")
except RateLimitError:
    print("Rate limit hit — slow down or upgrade tier")
except VeynorError as e:
    print(f"API error {e.status_code}: {e}")
```

---

## REST API

All SDK methods map directly to REST endpoints at `https://api.veynor.xyz`. Pass your key via `X-API-Key` header.

```bash
# Natural-language intelligence query
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/intelligence?q=what+are+markets+saying+about+Iran" | jq .summary

curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/intelligence?q=any+unusual+volume+today"

# Whale trades
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/whale-trades?min_notional=10000&limit=10"

# Top markets by 24h volume
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/markets/top?limit=10"

# Search markets
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/markets/search?q=fed+rate"

# Specific market
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/markets/polymarket/0x1234..."
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/markets/kalshi/KXNBA-25-LAL"

# Price history (~1h rolling, 60s snapshots)
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/markets/polymarket/0x1234.../history"
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/markets/kalshi/KXNBA-25-LAL/history"

# Alpha signals
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/signals?signal_type=arb_opportunities"

# Market pulse (AI-synthesized briefing — top markets, whale flow, movers, spreads)
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/pulse" | jq .summary

# Filter by venue or category
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/pulse?venue=kalshi&category=Politics" | jq .summary

# Pull structured highlights for programmatic use
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/pulse" | jq '.highlights.whale_activity'
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/pulse" | jq '.highlights.top_markets[].title'

# Topic snapshot — ranked markets + AI summary for a topic
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/topic/crypto" | jq .summary
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/topic/geopolitics?limit=30" | jq '.markets[] | {title, yes_price, platform}'

# Credit usage
curl -s -H "X-API-Key: vey_sk_..." \
  "https://api.veynor.xyz/v1/usage"
```

| Endpoint | Params | Credits |
|----------|--------|---------|
| `GET /v1/intelligence` | `q` (required) — natural-language query | 5 |
| `GET /v1/whale-trades` | `venue`, `min_notional`, `category`, `limit` | 2 |
| `GET /v1/markets/top` | `venue`, `category`, `limit` | 1 |
| `GET /v1/markets/search` | `q` (required), `venue`, `limit` | 1 |
| `GET /v1/markets/:venue/:id` | — | 1 |
| `GET /v1/markets/:venue/:id/history` | — | 1 |
| `GET /v1/signals` | `signal_type`, `limit` | 3 |
| `GET /v1/pulse` | `venue`, `category` | 5 |
| `GET /v1/topic/:tag` | `limit` | 3 |
| `POST /v1/credentials/kalshi` | `kalshi_key_id`, `private_key` | 0 |
| `GET /v1/credentials/kalshi` | — | 0 |
| `DELETE /v1/credentials/kalshi` | — | 0 |
| `POST /v1/trade/kalshi` | `ticker`, `action`, `side`, `count`, `price` | 2 |
| `POST /v1/trade/submit` | `order`, `signature`, `wallet` | 2 |
| `GET /v1/usage` | — | 0 |

---

## CLI

Every API method is also available as a shell command. Set your key once:

```bash
export VEYNOR_API_KEY=vey_sk_...
```

### Search markets

```bash
veynor search "fed rate"
veynor search "bitcoin" --limit 20
veynor search "election" --venue kalshi
```

Output shows YES price, 24-hour volume, and platform for each result:

```
  [polymarket]  YES  62¢  $  1,234,567/24h  Will the Fed cut rates in June?
  [kalshi]      YES  58¢  $    412,300/24h  Fed rate cut — June 2025
```

Add `--json` for machine-readable output:

```bash
veynor search --json "bitcoin" | jq '.results[].yes_price'
```

### Whale trades

```bash
veynor whales
veynor whales --min-notional 50000
veynor whales --venue kalshi --limit 5
```

### Top markets

```bash
veynor top
veynor top --venue polymarket --limit 20
```

### Signals

```bash
veynor signals                          # all signals
veynor signals --type wide_spreads
veynor signals --type arb_opportunities
veynor signals --type price_movers
```

### Market detail

```bash
veynor market polymarket <condition_id>
veynor market kalshi KXNBA-25-LAL
veynor market kalshi KXNBA-25-LAL --json
```

### Market pulse

A plain-English briefing synthesized from live data — top markets, whale activity, price movers, volume spikes, and wide spreads in one shot:

```bash
veynor pulse
veynor pulse --venue kalshi
veynor pulse --category Sports
```

Sample output:

```
  Prediction Market Pulse — Wed May 13 2026
  Data as of: 2026-05-13 14:14:54

  Tennis markets are the real action right now: Pol Martin Tiffon collapsed
  66.5¢ in the last hour to 6.5¢ while Chris Rodesch surged 59¢ on Kalshi,
  indicating live match developments. Whale activity is NO-heavy at $178K
  total notional, anchored by a $34K Manchester City bet...

  Top markets
    Will Bitcoin hit $150k by June 30, 2026?           $5.8M  (POLYMARKET)
    Hantavirus pandemic in 2026?                       $1.1M  (POLYMARKET)
    Starmer out by May 15, 2026?                       $1.1M  (POLYMARKET)
  Whale flow     10 trades  $178K total  NO-heavy
  Biggest mover  Will Pol Martin Tiffon win the match…           -66.5¢ (1h)
  Volume spike   New York Yankees vs. Baltimore Orioles          164.8× ratio
  Wide spread    Will Lillestrøm SK vs. Viking FK end in a draw?  bid/ask 12¢ / 51¢

  5 credits used · veynor.xyz/agents to upgrade
```

### Intelligence query

Ask a natural-language question about prediction markets. Returns an AI-synthesized analysis and a ranked table of matching markets from both venues.

```bash
veynor intelligence "what are markets saying about Iran?"
veynor intelligence "any unusual volume or big movers today?"
veynor intelligence "find edge in crypto markets"
veynor intelligence "what is the market pricing on Fed rate cuts in 2026?"
veynor intelligence "show me whale activity on Trump markets"
```

Sample output:

```
  Intelligence — what are markets saying about Iran?
  18 markets found  ·  Kalshi: 9  Polymarket: 9

  Iran nuclear deal markets are trading between 5¢ and 12¢ across both venues,
  suggesting low probability of a near-term agreement. Kalshi's KXIRANUKE-26
  leads at $340K 24h volume. A notable $22K whale buy appeared on YES this
  morning, contrasting with the broader NO-heavy positioning.

  Market                                                                          Price    Vol/24h  Venue
  ------------------------------------------------------------------------------------------------------------------
  Will Iran sign a nuclear deal by end of 2026?                                     6¢    $340K  KALSHI
  Iran nuclear agreement before July 2026?                                          8¢    $210K  POLYMARKET
  ...

  5 credits used · veynor.xyz/agents to upgrade
```

Add `--json` for machine-readable output:

```bash
veynor intelligence --json "any arb between Kalshi and Polymarket?" | jq '.markets.kalshi[].title'
```

### Topic snapshot

Cross-venue market snapshot for a topic. Returns an AI-synthesized summary and a ranked table of the top markets — price, volume, and venue — across Kalshi and Polymarket in one shot.

```bash
veynor ask crypto
veynor ask geopolitics
veynor ask trump
veynor ask us_politics
veynor ask macro
veynor ask sports --limit 30
```

Sample output:

```
  Crypto — prediction market snapshot
  42 markets  ·  Kalshi: 18  Polymarket: 24

  Bitcoin is trading at 72¢ to hit $150k by June on Polymarket, up from 65¢
  last week. Ethereum ETF approval odds remain flat at 38¢. Kalshi shows
  heavier volume on BTC price level contracts vs. Polymarket's broader altcoin
  coverage...

  Market                                                                                                                          Price    Vol/24h  Venue
  ------------------------------------------------------------------------------------------------------------------
  Will Bitcoin reach $150,000 by June 30, 2026?                                                                                   72¢     $5.8M  POLYMARKET
  Will Ethereum ETF be approved by Q3 2026?                                                                                       38¢     $1.2M  POLYMARKET
  Bitcoin above $100k on May 31?                                                                                    [T100K]        65¢      $840K  KALSHI

  3 credits used · veynor.xyz/agents to upgrade
```

### Credit usage

```bash
veynor usage
```

---

## Use in a Jupyter notebook

```python
import veynor, pandas as pd

client = veynor.Client()
data   = client.whales(min_notional=15_000, limit=50)
df     = pd.DataFrame(data["trades"])
df[["market", "side", "notional", "platform"]].sort_values("notional", ascending=False)
```

---

## Kalshi order execution

Place orders on Kalshi directly using your personal API key pair. All signing happens locally — your private key never leaves your machine.

### 1. Install trade dependencies

```bash
pip install veynor[trade]
```

This adds `cryptography` (for RSA signing) on top of the base install.

### 2. Generate a key pair and register it

```bash
# Generate RSA key pair
openssl genrsa -out kalshi_key.pem 2048
openssl rsa -in kalshi_key.pem -pubout   # copy this output
```

Paste the public key at [kalshi.com/profile/api-keys](https://kalshi.com/profile/api-keys) and copy the resulting Key ID (a UUID).

### 3. Set credentials

```bash
export KALSHI_API_KEY_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
export KALSHI_PRIVATE_KEY_PATH=/path/to/kalshi_key.pem
```

Or pass the PEM text directly:

```bash
export KALSHI_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\n..."
```

### 4. Trade

```python
from veynor import KalshiTrader

trader = KalshiTrader()   # reads env vars automatically

# Account
print(trader.get_balance())    # { cash_usd, cash_cents, ... }
print(trader.get_positions())  # open positions

# Market buy — spend $50 on YES
result = trader.market_buy("KXNBA-25JUL05-T204", side="YES", amount_usd=50.0)
print(result["order_id"], result["status"])

# Limit buy — 100 contracts at 65¢
result = trader.limit_buy("KXNBA-25JUL05-T204", side="YES", price=0.65, count=100)

# Buy NO side
result = trader.limit_buy("KXNBA-25JUL05-T204", side="NO", price=0.40, count=50)

# Market sell
result = trader.market_sell("KXNBA-25JUL05-T204", side="YES", count=100)

# Limit sell
result = trader.limit_sell("KXNBA-25JUL05-T204", side="YES", price=0.72, count=100)

# Cancel an open order
trader.cancel_order(order_id)

# Open orders
orders = trader.get_open_orders()
orders = trader.get_open_orders(ticker="KXNBA-25JUL05-T204")
```

### Via the REST API

Register credentials once (encrypted at rest — never returned in any response):

```bash
curl -X POST https://api.veynor.xyz/v1/credentials/kalshi \
  -H "X-API-Key: vey_sk_..." \
  -H "Content-Type: application/json" \
  -d '{
    "kalshi_key_id": "your-uuid",
    "private_key": "-----BEGIN RSA PRIVATE KEY-----\n..."
  }'

# Check status
curl -H "X-API-Key: vey_sk_..." \
  https://api.veynor.xyz/v1/credentials/kalshi

# Remove stored credentials
curl -X DELETE -H "X-API-Key: vey_sk_..." \
  https://api.veynor.xyz/v1/credentials/kalshi
```

Then place orders against your own Kalshi account:

```bash
# Limit buy — 100 YES contracts at 65¢
curl -X POST https://api.veynor.xyz/v1/trade/kalshi \
  -H "X-API-Key: vey_sk_..." \
  -H "Content-Type: application/json" \
  -d '{"ticker": "KXNBA-25JUL05-T204", "action": "buy", "side": "YES", "count": 100, "price": 0.65}'

# Market sell
curl -X POST https://api.veynor.xyz/v1/trade/kalshi \
  -H "X-API-Key: vey_sk_..." \
  -d '{"ticker": "KXNBA-25JUL05-T204", "action": "sell", "side": "YES", "count": 100, "order_type": "market"}'
```

Each user's trades execute on their own Kalshi account. Credentials are AES-256-GCM encrypted at rest and scoped to your Veynor API key.

### Errors and troubleshooting

| Error | Fix |
|-------|-----|
| `No Kalshi credentials registered` | Call `POST /v1/credentials/kalshi` or set env vars |
| `cryptography package not installed` | Run `pip install veynor[trade]` |
| `Kalshi API error (401)` | Check that your Key ID matches the registered public key |
| `Kalshi API error (403)` | API key may be read-only — enable trading in Kalshi dashboard |

---

## Polymarket order execution

Place orders on Polymarket directly from Python. All signing happens locally — your private key never leaves your machine and is never sent to Veynor's servers.

Supports Polymarket V2 (live April 28, 2026): native EIP-712 signing, pUSD collateral, proxy wallet and plain EOA flows.

### 1. Install trade dependencies

```bash
pip install veynor[trade]
```

### 2. Set credentials

```bash
export POLYMARKET_PRIVATE_KEY=0x...   # required — your EOA private key
export POLYMARKET_ADDRESS=0x...       # optional — proxy wallet address (Magic users)
```

If you set `POLYMARKET_ADDRESS`, orders are placed via your proxy wallet (signatureType 1). Without it, your EOA signs directly (signatureType 0).

### 3. Trade

```bash
# Check pUSD balance
veynor trade balance

# Open positions
veynor trade positions

# Market buy $50 of YES shares
veynor trade buy <token_id> --amount 50

# Neg-risk market (most multi-outcome markets)
veynor trade buy <token_id> --amount 50 --neg-risk

# Sell 100 shares
veynor trade sell <token_id> --shares 100

# Copy the latest whale trade
veynor trade copy
veynor trade copy --min-notional 50000 --amount 200 --yes
```

### Python API

```python
from veynor import PolymarketTrader

trader = PolymarketTrader()
print(trader.get_balance())

result = trader.market_buy(token_id, amount_usdc=50.0, neg_risk=True)
result = trader.limit_buy(token_id, price=0.72, size=10.0)
result = trader.market_sell(token_id, amount_shares=10.0)
result = trader.limit_sell(token_id, price=0.80, size=10.0)
orders = trader.get_open_orders()
trader.cancel_order(order_id)
```

### Via the REST API (no-custody relay)

Sign the order with your wallet, pass the signature to Veynor. Your private key never touches our servers:

```bash
curl -X POST https://api.veynor.xyz/v1/trade/submit \
  -H "X-API-Key: vey_sk_..." \
  -H "Content-Type: application/json" \
  -d '{
    "order":     { ...eip712_order_fields... },
    "signature": "0x...",
    "wallet":    "0x...",
    "order_type": "GTC"
  }'
```

### Errors and troubleshooting

| Error | Fix |
|-------|-----|
| `No private key found` | Set `POLYMARKET_PRIVATE_KEY` |
| `Failed to derive API credentials` | Key must be a valid hex string starting with `0x` |
| `Trading requires extra packages` | Run `pip install veynor[trade]` |
| `Trading restricted in your region` | Polymarket geo-blocks certain IPs — use a non-restricted server |
| Order status `unmatched` | Insufficient liquidity — try a smaller amount |

---

## Whale following

`veynor follow` polls the whale feed on an interval and mirrors large trades directly to your Polymarket and/or Kalshi account.

### Setup

Polymarket credentials (required):
```bash
export POLYMARKET_PRIVATE_KEY=0x...
export POLYMARKET_ADDRESS=0x...
```

Kalshi credentials (optional — auto-detected if set):
```bash
export KALSHI_API_KEY_ID=<uuid>
export KALSHI_PRIVATE_KEY_PATH=/path/to/key.pem
# or inline:
export KALSHI_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\n..."
```

### Usage

```bash
# Start with a dry run first — see what would trade without spending anything
veynor follow --amount 2 --dry-run

# Follow with $5 per copied trade, minimum $15k whale size
veynor follow --amount 5 --min-notional 15000

# Use 2% of balance per trade, $50/day cap, Politics markets only
veynor follow --pct 2 --max-daily 50 --category Politics

# Follow both YES and NO sides, poll every 15 seconds
veynor follow --amount 10 --sides ALL --interval 15

# Explicit venue list (default: auto-detect from env)
veynor follow --amount 3 --venues polymarket --venues kalshi
```

### How it works

1. On startup, seeds all current whale trades as seen so no historical trades fire.
2. Every `--interval` seconds, fetches fresh whale trades from all active venues.
3. New trades (not seen before) are fingerprinted by `(platform, market, side, notional)` and persisted to `~/.veynor_seen_trades.json` so restarts don't re-fire.
4. Polymarket trades: looks up the market by name to resolve `token_id` and `neg_risk` flag, then executes a market buy.
5. Kalshi trades: extracts the ticker from the market URL, maps the side (handles team names like "NO KANSAS CITY"), and executes a market buy.
6. Daily spend is tracked in memory and resets at midnight. Use `--max-daily` to cap total exposure.

### Usage with exit rules and risk controls

```bash
# Auto-exit at +20c gain or -15c loss, force-close after 48 hours
veynor follow --kalshi-count 2 --venues kalshi \
  --take-profit 20 --stop-loss 15 --max-hold-hours 48

# Cap at 5 open positions, no single order over $10
veynor follow --amount 5 --max-open-positions 5 --max-position-size 10

# Get Slack alerts on every trade entry, exit, and error
veynor follow --amount 2 --webhook-url https://hooks.slack.com/services/YOUR/SLACK/URL

# Set webhook via env var (persists across sessions)
export VEYNOR_WEBHOOK_URL=https://discord.com/api/webhooks/YOUR/DISCORD/URL
veynor follow --amount 2
```

### Options

| Flag | Default | Description |
|------|---------|-------------|
| `--amount` | 2.0 | Fixed USD per copied trade |
| `--pct` | — | % of balance per trade (mutually exclusive with `--amount`) |
| `--kalshi-count` | — | Fixed contract count for Kalshi orders (overrides `--amount` on Kalshi) |
| `--min-notional` | 10000 | Only copy trades at or above this size |
| `--category` | All | Filter to Sports, Politics, or Other |
| `--sides` | ALL | YES, NO, or ALL |
| `--max-daily` | 0 | Daily USD spend cap (0 = no cap) |
| `--max-open-positions` | — | Skip new trades when N positions are already open |
| `--max-position-size` | — | Hard cap on any single order in USD |
| `--interval` | 30 | Poll interval in seconds |
| `--venues` | auto | `polymarket`, `kalshi`, or both (repeat flag) |
| `--take-profit` | — | Exit when price moves this many cents in your favor |
| `--stop-loss` | — | Exit when price moves this many cents against you |
| `--max-hold-hours` | — | Force-close positions older than this many hours |
| `--webhook-url` | — | HTTP endpoint for trade notifications (Slack, Discord, or custom). Also reads `VEYNOR_WEBHOOK_URL` env var |
| `--dry-run` | false | Log trades without executing |
| `--verbose` | false | Log every poll cycle, not just new trades |

---

## Portfolio and P&L

### `veynor portfolio`

Unified cross-venue portfolio view. Shows live balances and all open positions across Kalshi and Polymarket in a single command. Auto-detects credentials — shows whichever venues are configured.

```bash
veynor portfolio
```

```
  Veynor Portfolio
  ====================================================================

  BALANCES
  --------------------------------------------------------------------
  Kalshi            $5.78
  Polymarket       $42.15
  TOTAL            $47.93

  KALSHI POSITIONS (2)
  --------------------------------------------------------------------
  KXNBAGAME-26MAY19CLENYK-NYK      YES    5 ct  cost $2.25
  KXBTCD-26MAY20-T68K              YES    2 ct  cost $0.90

  POLYMARKET POSITIONS (1)
  --------------------------------------------------------------------
  Will Trump win the 2026 midterms?    YES   50.0 shares  avg 0.62  now 0.71  val $35.50  P&L +$4.50 (+14.5%)

  Unrealized P&L: +$4.50
```

Polymarket positions include avg price, current price, current value, and unrealized P&L from the CLOB. Kalshi positions show contract count and cost basis. Realized P&L is not shown — exchange position APIs only return open positions, so resolved markets drop off and any realized figure would be meaningless.

### `veynor positions`

Copy-trading journal for positions opened via `veynor follow`. Shows open positions with entry price and age, and closed positions with entry/exit price and realized P&L. Persisted to `~/.veynor_positions.json`.

```bash
veynor positions
```

### `veynor stats`

Unified P&L summary covering both discretionary and copy-trading activity. Pulls live balances and open positions from Kalshi and Polymarket APIs, then shows a full copy-trading journal with win rate and performance breakdowns.

```bash
veynor stats
```

```
  Veynor P&L Stats
  ============================================================

  ACCOUNT BALANCES
  ------------------------------------------------------------
  Kalshi             $5.78
  Polymarket        $42.15
  TOTAL CASH        $47.93

  KALSHI — OPEN POSITIONS (2)
  ------------------------------------------------------------
  KXNBAGAME-26MAY19CLENYK-NYK      YES     5 ct  cost $2.25
  KXBTCD-26MAY20-T68K              YES     2 ct  cost $0.90

  POLYMARKET — OPEN POSITIONS (1)
  ------------------------------------------------------------
  Current value:   $35.50
  Unrealized P&L:  +$4.50
  Will Trump win the 2026 midterms?    YES   50 sh  avg 0.62  now 0.71  P&L +$4.50 (+14.5%)

  COPY-TRADING JOURNAL (veynor follow)
  ------------------------------------------------------------
  Closed trades:    14
  Open positions:   2
  Net P&L:          +$8.4200
  Win rate:         64.3%  (9W / 5L)
  Best trade:       +$3.2000
  Worst trade:      -$1.1500

  BY TIME WINDOW
  ------------------------------------------------------------
  Last 7 days        5 trades  win  60.0%  net   +$2.1000  avg  +$0.4200
  Last 30 days      12 trades  win  66.7%  net   +$7.8000  avg  +$0.6500
  All time          14 trades  win  64.3%  net   +$8.4200  avg  +$0.6014

  BY VENUE
  ------------------------------------------------------------
  Kalshi             8 trades  win  75.0%  net   +$6.2000  avg  +$0.7750
  Polymarket         6 trades  win  50.0%  net   +$2.2200  avg  +$0.3700

  BY EXIT REASON
  ------------------------------------------------------------
  take-profit        6 trades  win 100.0%  net   +$9.6000  avg  +$1.6000
  stop-loss          5 trades  win   0.0%  net   -$4.7500  avg  -$0.9500
  time-limit         3 trades  win  33.3%  net   +$3.5700  avg  +$1.1900
```

The exit reason breakdown shows which rules are working. If take-profit exits are consistently profitable and stop-loss exits are not, your stop is set correctly. If time-limit exits are mixed, the hold window may be too wide.

---

## What's new in v1.5.6

- **`client.intelligence()` and `veynor intelligence`** — natural-language prediction market queries with AI synthesis. Ask anything in plain English: topic questions, signal scans, or trade idea requests. The engine auto-detects intent, loads relevant data, and returns an AI-written analysis alongside matching markets from both Kalshi and Polymarket. 5 credits. REST: `GET /v1/intelligence?q=...`

## What's new in v1.5.5

- **`veynor trade orders` fixed** — open limit orders now list correctly. The underlying issue was a 405 from the Polymarket CLOB API on `GET /orders` when using our custom HTTP layer. Root cause: the official client (`py_clob_client_v2`) uses a different internal routing for authenticated GET requests. Veynor now delegates all authenticated GET calls to `py_clob_client_v2` instead of rolling its own. Credential derivation also upgraded to try v2 first, fall back to v1.
- **`py-clob-client-v2` added to trade deps** — `pip install veynor[trade]` now pulls in the v2 CLOB client. If you're on an older install, run `pip install --upgrade veynor[trade]`.
- **`POLY_ADDRESS` auth header fixed** — was sending EOA address instead of proxy wallet address in L2 auth headers. Relevant for proxy/Magic wallet users.

## What's new in v1.5.1

- **`veynor stats` unified view** — now covers both discretionary and copy-trading activity in one command. Section 1 shows live balances and open positions pulled directly from Kalshi and Polymarket APIs. Section 2 shows the copy-trading journal with win rate and breakdowns by time window, venue, and exit reason.
- **Realized P&L removed** — exchange position APIs only return open positions; fully resolved markets drop off entirely, making any "realized P&L (all time)" figure misleading (always $0). Removed from both `veynor stats` and `veynor portfolio`. Copy-trading P&L in the journal section is still accurate since Veynor tracks entry and exit itself.

## What's new in v1.4.9

- **`veynor stats`** — P&L summary with win rate, avg P&L, best/worst trade, breakdowns by time window (7d/30d/all time), venue, and exit reason.
- **`--max-open-positions`** — skip new trades when N positions are already open.
- **`--max-position-size`** — hard cap on any single order in USD, regardless of `--amount` or `--pct`.

## What's new in v1.4.8

- **Webhook notifications** — `--webhook-url` (or `VEYNOR_WEBHOOK_URL` env var) posts JSON alerts to Slack, Discord, or any HTTP endpoint on trade entry, exit, order failure, and daily cap events.

## What's new in v1.4.7

- **`veynor portfolio`** — unified cross-venue portfolio view. Shows live balances and open positions across Kalshi and Polymarket in a single command. Auto-detects credentials; shows whichever venues are configured. Polymarket positions include avg price, current price, current value, and unrealized P&L. Kalshi positions show contract count and realized P&L.
- **`veynor positions`** — copy-trading journal for positions opened via `veynor follow`. Tracks entry price, exit price, and realized P&L per trade.
- **Position tracking in `veynor follow`** — every executed trade is now recorded. Supports automatic exits via `--take-profit`, `--stop-loss`, and `--max-hold-hours`. Positions persist across restarts.

## What's new in v1.4.6

- Internal: position store and exit logic foundation (shipped as part of v1.4.7).

## What's new in v1.4.5

- **Kalshi-only following** — `veynor follow --venues kalshi` no longer requires Polymarket credentials. Traders are now initialized only for the venues actually requested. Clear error messages guide Kalshi-only users to set `KALSHI_API_KEY_ID` and `KALSHI_PRIVATE_KEY_PATH` instead of showing an irrelevant Polymarket key error.

## What's new in v1.4.4

- **Kalshi hotfix** — corrects API base URL to `external-api.kalshi.com`, fixes RSA auth signing (query params excluded from signature path), fixes `get_balance()` response parsing, and adds `find_ticker_by_slug()` with team-suffix matching for sports markets. v1.4.3 had broken Kalshi support; upgrade to 1.4.4.

## What's new in v1.4.3

- **Whale following** — `veynor follow` daemon mirrors large whale trades to your Polymarket and/or Kalshi account. Persistent dedup, daily spend cap, dry-run mode. Kalshi is auto-detected from env vars.
- **Polymarket minimum contracts** — `market_buy` now enforces the Polymarket minimum of 5 contracts per order, adjusting size up automatically when needed.
- **Multi-venue following** — a single follower instance can watch both Polymarket and Kalshi simultaneously. Use `--venues` to configure explicitly or let it auto-detect from credentials.

## What's new in v1.4.2

- **Market pulse** — `client.pulse()` and `veynor pulse` CLI command. AI-synthesized plain-English briefing covering top markets, whale flow, price movers, volume spikes, and wide spreads. Powered by Claude Haiku on the server. 5 credits.
- **Stale market filtering** — pulse and signals automatically exclude markets past their close time so no expired data surfaces as actionable.
- **Data freshness tracking** — pulse response includes `meta.data_freshness` so you always know how old the underlying scanner data is.

## What's new in v1.4.1

- **Kalshi trading** — `KalshiTrader` with market/limit orders on YES and NO, cancel, positions, balance. RSA key pair auth, non-custodial.
- **Price history endpoint** — `GET /v1/markets/:venue/:id/history` returns rolling ~1h of 60-second price snapshots with computed 5m/15m/1h moves.
- **Market index enriched** — search results now include `end_date`, `spread_cents`, and `liquidity` on every market.
- **Polymarket signed-order relay** — `POST /v1/trade/submit` for agents that sign locally and route through Veynor for builder attribution.
- **Per-user credential storage** — Kalshi keys stored AES-256-GCM encrypted per Veynor API key. Each user trades their own account.

---

## Links

- [Register for an API key](https://veynor.xyz/agents)
- [MCP server](https://github.com/veynor-xyz/veynor-mcp) — connect Claude Desktop, Cursor, or any MCP client to live prediction market data. Listed on the [official MCP registry](https://registry.modelcontextprotocol.io).
- [Web app](https://veynor.xyz) — whale feed, signals, trade interface
