Sign In

@spfunctions/cli

Package Overview
Dependencies
Maintainers
1
Versions
138
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@spfunctions/cli

Prediction market infrastructure — CLI for Kalshi + Polymarket. Cross-venue pairs, live orderbook, indicators (IY/CRI/EE/LAS), regime detection, contagion, salience-ranked world snapshot for AI agents, causal-thesis edge detection. Interactive agent mode

latest
Source
npmnpm
Version
3.0.47
Version published
Weekly downloads
218
26.74%
Maintainers
1
Weekly downloads
 
Created
Source

SimpleFunctions CLI (sf)

A terminal-native prediction-market CLI. Query live Kalshi + Polymarket state, inspect markets, export structured JSON for agents, and gate execution from the shell. The installed binary is the source of truth; inspect the current command surface with sf describe --all --json.

$ sf world
# World State — 2026-04-09T13:00 UTC
SF Index v2: Disagree 57/100 | GeoRisk 35/100 | Breadth +0.33 | Activity 86/100

Markets: SPY $655.94 (+0.12%) | GLD $429.08 (-1.79%) | USO $138.18 (+11.99%)

## Geopolitical
- Will the U.S. invade Iran before 2027?: 54c (-7c)
- Russia x Ukraine ceasefire by end of 2026?: 30c

## Economy
- US recession by end of 2026?: 28c
- How many Fed rate cuts in 2026?: 0 (0 bps): 36c

Install

npm install -g @spfunctions/cli
sf login                # browser auth (recommended)
sf status               # verify everything works

What it does

World model — Real-time prediction index distilled from the active market universe. One command gives any LLM situational awareness.

sf world                    # ~800 token world state snapshot
sf world --delta            # what changed since last check (~30 tokens)
sf world --focus energy,geo # deep coverage on specific topics
sf ideas                    # S&T-style trade ideas with catalyst + risk

Thesis engine — Structured causal models with Bayesian node trees, continuous evaluation against live market data, and automatic edge detection.

sf thesis create 'Oil will exceed $120 by Q3 due to Hormuz disruption'
sf thesis list              # all theses with confidence + status
sf thesis context <id>      # causal tree + top edges + positions
sf thesis evaluate <id>     # trigger deep re-evaluation
sf thesis signal <id> "OPEC cuts"  # inject a signal for next eval cycle

Edge detection — Cross-venue scanner compares your model's probabilities against Kalshi and Polymarket prices.

sf edges                    # top mispricings across all theses
sf scan "recession"         # search live markets by keyword
sf book KXRECSSNBER-26      # orderbook depth
sf watch oil orderbook      # live terminal orderbook stream
sf watch "fed" all --smart  # LLM-filtered alerts + news divergence detection

Intent system — Declarative execution: describe what you want, the runtime handles when and how.

sf intent buy KXRECSSNBER-26 10 --price 30 --trigger below:28 --auto
sf intent list              # active intents + fill status
sf runtime start            # daemon evaluates triggers, executes orders

Interactive agent — Natural language interface over the installed sf command surface. Maintains a persistent workspace, shares context across sessions, and can schedule its own future actions.

sf agent <id>               # TUI agent with tool calling
sf agent <id> --once "summarize my portfolio risk"  # single-shot
sf agent <id> --plain       # readline mode, no TUI
sf telegram --daemon        # Telegram bot (text + voice)

Agent harness — Deterministic replay, budget + permission capsules.

sf agent <id> --record-trace /tmp/t.ndjson   # record session
sf agent <id> --replay-trace /tmp/t.ndjson   # replay offline
sf agent --budget-usd 5 --deny order         # constrained agent

Event subscription — Reactive agents. NDJSON stream or webhook push.

sf subscribe list
sf subscribe cancel <id>

Runtime controls — Local runtime commands keep side effects explicit. Cloud/remote runtime surfaces are not the canonical public workflow; use the local CLI and HTTP/Data API unless your account has a separately documented remote runtime enabled.

X / Twitter intelligence — Social signal layer.

sf x "tariff impact"        # discussion summary + top posts
sf x-volume "iran oil"      # volume and velocity trend
sf x-news "fed rate"        # Grok-aggregated news stories
sf x-account @elikinosian   # recent posts from an account

Setup

Quick (browser login)

sf login

Power user

sf setup                    # interactive wizard: API key, Kalshi, Polymarket, trading
sf setup --check            # show config status
sf setup --polymarket       # configure Polymarket wallet
sf setup --enable-trading   # unlock buy/sell/intent commands

Config is saved to ~/.sf/config.json. Environment variables override config values:

export SF_API_KEY=sf_live_xxx
export KALSHI_API_KEY_ID=xxx
export KALSHI_PRIVATE_KEY_PATH=~/.kalshi/private.pem

Verify

$ sf status
  API            ok  simplefunctions.dev 252ms
  Auth           ok  sf_live_8838...
  Kalshi         ok  $156.42 balance
  Polymarket     ok  0xd53b9354...
  Theses         ok  4 active, 4 total
  Trading        ok  enabled
  Runtime        --  not running (sf runtime start)
  Telegram       ok  PID 84372

Command Reference

World Model (no auth required)

CommandDescription
sf worldPrediction index: markets + geopolitics + economy + crypto + elections
sf world --deltaChanges since last check (~30 tokens, ideal for agent polling)
sf world --focus <topics>Deep coverage on specific topics
sf ideasTrade ideas with conviction, catalyst, direction, risk
sf query "question"LLM-enhanced market knowledge search
sf marketsTraditional markets: SPY, VIX, bonds, gold, oil

Thesis

CommandDescription
sf thesis listAll theses with status, confidence, last update
sf thesis get <id>Full details: causal tree, edges, evaluation history
sf thesis context <id>Thesis context snapshot
sf thesis create "thesis"Create a new thesis
sf thesis signal <id> "text"Inject signal for next evaluation
sf evaluate <id>Trigger deep re-evaluation
sf augment <id>Evolve causal tree with new nodes
sf heartbeat <id>View/configure autonomous evaluation schedule + costs
sf publish / sf unpublish <id>Manage public visibility

Markets

CommandDescription
sf scan "keywords"Search Kalshi + Polymarket by keyword
sf scan --series TICKERBrowse all markets in a Kalshi series
sf edges [--json]Top mispricings across all theses
sf watch [query] [mode]Live market watch (modes: orderbook, flow, cross-venue, all)
sf watch "q" --smartLLM-filtered alerts + news divergence via monitor-the-situation
sf watch "q" --smart --executeAuto-create trading intents from detected signals
sf book <ticker> [...]Orderbook depth for specific markets
sf whatif <id>What-if scenario analysis on causal tree
sf liquidity [topic]Orderbook liquidity scanner
sf forecast <event>Market distribution (P50/P75/P90)
sf explore [slug]Browse public theses

Portfolio

CommandDescription
sf positionsKalshi + Polymarket positions with P&L
sf balanceAccount balance
sf ordersResting (open) orders
sf fillsRecent trade fills
sf settlementsSettled contracts with final P&L
sf performanceP&L over time with event annotations
sf dashboardInteractive TUI portfolio overview

Intents & Runtime

Intents are declarative execution orders. You define the trade and trigger condition; the runtime daemon evaluates and executes.

CommandDescription
sf intent buy <ticker> <qty>Create buy intent (--trigger below:28, --trigger time:<ISO>, --soft "condition", --auto)
sf intent sell <ticker> <qty>Create sell intent
sf intent listActive intents (--all for history)
sf intent status <id>Detailed status + fills
sf intent cancel <id>Cancel an intent
sf runtime startStart execution daemon (Kalshi + Polymarket)
sf runtime stopStop daemon
sf runtime statusActive intents + runtime state
sf backtest <ticker>Strategy backtest (--entry-below 35 --stop 20 --tp 60 --days 30)
sf heartbeat <id>View/configure heartbeat + closed-loop (--closed-loop-entry, --closed-loop-exit)

Trading (requires --enable-trading)

CommandDescription
sf buy <ticker> <qty>Buy contracts (--price 31, --market, --side yes|no)
sf sell <ticker> <qty>Sell contracts
sf cancel [orderId]Cancel order(s)
sf rfq <ticker> <qty>Request for quote on large orders

Agent

CommandDescription
sf agent [id]Interactive agent (TUI with panels)
sf agent [id] --plainReadline mode, pipe-friendly
sf agent [id] --once "prompt"Single-shot: run, answer, exit
sf prompt [id]Print dynamic system prompt for any LLM
sf telegram [--daemon]Telegram bot (text + voice messages)

The agent uses the installed command manifest, including market scanning, trading, workspace read/write, X search, self-wake scheduling, and a math calculator. Check the exact surface with sf describe --all --json. Slash commands inside the agent include /voice /tree /edges /pos /eval /balance /intents /wakes /alerts /switch /model /help /exit.

X / Twitter

CommandDescription
sf x "query"Discussion summary + top posts
sf x-volume "query"Discussion volume and velocity trend
sf x-news "query"Grok-aggregated news stories
sf x-account @usernameRecent posts from a specific account

Info

CommandDescription
sf feedEvaluation history stream
sf delta <id>Changes since last check
sf milestonesUpcoming Kalshi events
sf scheduleExchange status
sf announcementsExchange announcements
sf history <ticker>Historical market data
sf statusFull system health check

Sharing

Any command with --share generates a short URL:

sf scan "gold" --share
sf query "fed rate" --share
sf context --share

JSON Output

Most commands support --json for machine-readable output:

sf thesis list --json
sf context f582bf76 --json
sf edges --json
sf world --json
sf ideas --json
sf discover --quality --json
sf brief --agent --json
sf intent list --json

For AI Agents

If you are an AI agent (Claude, GPT, Cursor, etc.), these are the commands that matter:

Setup

npm install -g @spfunctions/cli
sf login                          # or: export SF_API_KEY=sf_live_xxx
sf thesis list                           # verify: should print theses
sf doctor --agent --deep --json          # verify CLI JSON/manifest/auth surfaces

Primary commands

# World state in ~800 tokens — give your agent situational awareness
sf world --json

# Compact authenticated loop context: health, portfolio, workflow, world, gaps
sf brief --agent --json

# Quality-ranked opportunity queue across ideas/world/cross-venue/new/contagion
sf discover --quality --json

# What changed since last poll — ~30 tokens, efficient for loops
sf world --delta --json

# Thesis context: causal tree + edges + positions + evaluation
sf context <thesisId> --json

# Top mispricings across all theses
sf edges --json

# Single-shot agent: ask a question, get an answer, exit
sf agent <thesisId> --once "what is the biggest risk to my portfolio?"

Key JSON fields

sf context <id> --json returns:

{
  "confidence": 0.31,
  "causalTree": {
    "nodes": [{ "id": "n1", "label": "...", "probability": 0.95 }]
  },
  "edges": [{
    "marketId": "KXWTIMAX-26DEC31-T140",
    "venue": "kalshi",
    "marketPrice": 62,
    "thesisPrice": 95,
    "edge": 33
  }]
}
  • confidence — overall thesis probability (0 to 1)
  • edges[].edge — mispricing in cents (positive = market underpriced vs model)
  • edges[].marketPrice — current market price (0-100 cents)

Patterns

# Monitor: poll world state, react to deltas
sf world --delta --json

# React to news: inject signal, re-evaluate, read updated state
sf signal <id> "Breaking: OPEC cuts production" --type news
sf evaluate <id>
sf context <id> --json

# Trade: create intent with trigger, let runtime execute
sf intent buy KXRECSSNBER-26 5 --price 30 --trigger below:28 --auto
sf runtime start

Error codes

ErrorFix
"API key required"sf login or set SF_API_KEY
"Thesis not found"sf thesis list to get valid IDs (8-char prefix works)
"Kalshi not configured"sf setup to add Kalshi credentials
"Trading disabled"sf setup --enable-trading

Architecture

You ──→ sf agent ──→ LLM (Claude/GPT) ──→ sf command manifest
              │                                  │
              │         ┌────────────────────────┘
              ▼         ▼
         ┌─────────────────────┐
         │   SF API Server     │
         │  thesis · edges ·   │
         │  intents · eval ·   │
         │  proxy (LLM/TTS)    │
         └────────┬────────────┘
                  │
         ┌────────┴────────┐
         │                 │
    ┌────▼────┐     ┌──────▼──────┐
    │ Kalshi  │     │ Polymarket  │
    │  API    │     │    API      │
    └─────────┘     └─────────────┘

Local only (never leaves your machine):
  ~/.sf/config.json     — API keys, Kalshi private key path
  ~/.sf/workspace/      — agent scratchpad (notes, context logs)
  ~/.sf/wake/           — scheduled agent wake conditions
  ~/.sf/bus/            — daemon ↔ agent message bus
  ~/.sf/trade-journal.jsonl — local trade log

Kalshi credentials never leave your machine. Orders are signed locally with your RSA private key and sent directly to the Kalshi API. The SF server never sees your trading keys.

Local Development

cd cli
npm install
npm run dev -- list          # run without building
npm run build                # compile to dist/
npm run test                 # run tests
npm link                     # install as global 'sf' command

License

MIT

Keywords

prediction-market

FAQs

Package last updated on 27 May 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts