Skip to content

spfunctions/langchain-prediction-markets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

langchain-prediction-markets

npm License: MIT

LangChain tools for real-time prediction market data. Drop-in tools that give any LangChain agent (createReactAgent, createOpenAIToolsAgent, custom chains) world awareness from the active Kalshi and Polymarket market universe — no auth required.

import { ChatOpenAI } from '@langchain/openai'
import { createReactAgent } from '@langchain/langgraph/prebuilt'
import { predictionMarketTools } from 'langchain-prediction-markets'

const agent = createReactAgent({
  llm: new ChatOpenAI({ model: 'gpt-4o' }),
  tools: predictionMarketTools(),
})

const result = await agent.invoke({
  messages: [{ role: 'user', content: "What's the highest-conviction trade idea right now?" }],
})

Install

npm install langchain-prediction-markets @langchain/core

Peer dep: @langchain/core >= 0.2.0. Works with all LangChain JS chat models (@langchain/openai, @langchain/anthropic, @langchain/google-genai, etc.).

Tools

All six tools hit the public SimpleFunctions API. No API key, no rate limit, no auth. Every endpoint below is verified live.

Tool Endpoint When to use
get_context /api/public/context Start here. Single bundle: edges, movers, highlights, traditional-market context.
get_world_state /api/agent/world ~800-token compressed snapshot of all markets, ideal for system-prompt injection.
get_world_changes /api/agent/world/delta ~30-50 token incremental delta — cheap polling loops.
get_market_edges /api/edges Raw mispricings (thesis price vs market price) with reasoning.
get_uncertainty_index /api/public/index Single numeric pulse: uncertainty, geopolitical risk, momentum, activity.
get_ideas /api/public/ideas LLM-generated trade ideas with conviction, catalyst, time horizon.

Quick start: ReAct agent

import { ChatAnthropic } from '@langchain/anthropic'
import { createReactAgent } from '@langchain/langgraph/prebuilt'
import { predictionMarketTools } from 'langchain-prediction-markets'

const agent = createReactAgent({
  llm: new ChatAnthropic({ model: 'claude-sonnet-4-5' }),
  tools: predictionMarketTools(),
  stateModifier:
    'You are a market intelligence assistant. Use the tools to ground every claim in real-time prediction-market data. Cite tickers explicitly.',
})

const result = await agent.invoke({
  messages: [{ role: 'user', content: 'What changed in markets in the last 6 hours?' }],
})
console.log(result.messages.at(-1)?.content)

Use individual tools in a custom chain

import { getContext, getMarketEdges } from 'langchain-prediction-markets'
import { ChatOpenAI } from '@langchain/openai'

const llm = new ChatOpenAI({ model: 'gpt-4o' }).bindTools([getContext, getMarketEdges])

const out = await llm.invoke('Show me the open edges right now.')
for (const call of out.tool_calls ?? []) {
  if (call.name === 'get_market_edges') {
    const edges = await getMarketEdges.invoke(call.args)
    console.log(edges)
  }
}

Direct invocation (no LangChain agent)

Every tool is a standard LangChain tool — you can call .invoke() directly:

import { getUncertaintyIndex, getIdeas } from 'langchain-prediction-markets'

const index = JSON.parse(await getUncertaintyIndex.invoke({}))
console.log(`Uncertainty: ${index.uncertainty}/100`)

const { ideas } = JSON.parse(await getIdeas.invoke({}))
console.log(`Top idea: ${ideas[0].headline}`)

Response shapes

Tools return JSON-stringified payloads (LangChain expects string outputs). get_world_state and get_world_changes return raw markdown strings.

get_context

{
  edges: Edge[]
  movers: Mover[]
  highlights: Highlight[]
  traditionalMarkets: { [topic: string]: TraditionalMarket[] }
}

get_uncertainty_index

{
  uncertainty: number    // 0-100
  geopolitical: number   // 0-100
  momentum: number       // -1 to +1
  activity: number       // 0-100
  components: { medianSpread: number; avgSpread: number; ... }
  timestamp: string
}

get_market_edges

{
  edges: {
    ticker: string
    venue: 'kalshi' | 'polymarket'
    title: string
    marketPrice: number
    thesisPrice: number
    executableEdge: number
    confidence: number
    liquidityScore: 'high' | 'medium' | 'low'
    direction: 'yes' | 'no'
    reasoning: string
  }[]
}

get_ideas

{
  generatedAt: string
  cached: boolean
  ideas: {
    headline: string
    pitch: string
    conviction: 'high' | 'medium' | 'low'
    direction: 'buy_yes' | 'buy_no'
    markets: { url: string; ticker: string; currentPrice: number; venue: string }[]
    catalyst: string
    timeHorizon: string
    risk: string
  }[]
}

Errors

All tools throw Error("SimpleFunctions API error <status> for <path>") on non-2xx responses. LangChain agents will see the error string in the tool message and can retry or recover.

Sister packages

If you're not on LangChain, use the wrapper for your stack:

Stack Package
Vercel AI SDK vercel-ai-prediction-markets
OpenAI Agents SDK / function calling openai-agents-prediction-markets
CrewAI (Python) crewai-prediction-markets
MCP / Claude / Cursor simplefunctions-cli
Bare Python SDK simplefunctions-python

Testing

npm test

12 tests, all fetch-mocked — no network required.

License

MIT — built by SimpleFunctions.

About

LangChain adapter for SimpleFunctions prediction-market context: world state, uncertainty, edges, and market reads.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors