Kokan: Polymarket Algorithmic Trading & Forensics
Real-time quantitative forensics dashboard tracking algorithmic trade bots, copy execution, and volume anomalies on Polymarket CLOB.










KoKan was engineered to address a high-stakes operational gap: real-time security forensics and telemetry on Polymarket. When running sophisticated algorithmic strategies and automated execution bots across hundreds of decentralized predictive markets, transparency is everything. Without instant feedback loops on order-book depth, execution latency, and address forensics, it is virtually impossible to safeguard capital against wash-trading algorithms, frontrunners, or sudden liquidity drainage.
This dashboard is the command center. It bridges the gap between low-latency Rust/Python execution daemons and a highly responsive React console. By connecting directly to our telemetry gateways—Karin (the elimination funnel), Kakashi (the copy-trading streams), and Byakugan (the real-time market scanner)—KoKan visualizes high-conviction transaction data, tracks order execution latencies, and provides security audits in sub-millisecond intervals.
📈 Polymarket CLOB & Liquidity Mechanics (The 101)
To build a high-fidelity forensic engine, one must first master the intricate market mechanics of Polymarket. Unlike traditional automated market makers (AMMs) like Uniswap, Polymarket relies on a centralized off-chain order matcher with on-chain settlement, known as the Central Limit Order Book (CLOB).
Understanding this system requires looking past simple buy/sell buttons and examining three core pillars:
1. The Central Limit Order Book (CLOB) API
Polymarket's matching engine acts as a hybrid. Limit orders are placed and matched off-chain at sub-millisecond speeds, while execution settlement is dispatched to Polygon. This off-chain matching is exposed via the CLOB API, which operates through high-frequency WebSockets and REST interfaces:
- Order Book Depth (
GET /book): Ingests live snapshots of bid and ask arrays containing precise{ price, size }structures. Because order increments are restricted to minimum tick sizes (typically$0.001or$0.01depending on volatility), automated bots monitor micro-price spreads to detect frontrunning bands. - Historical Pricing (
GET /prices-history): Feeds historical candle grids representing real-time probability shifts. In prediction markets, price equals probability; a YES share at$0.72implies a72%probability of occurrence. - The Taker vs. Maker Paradigm: To sustain liquidity, Polymarket's CLOB is fee-less, meaning market makers submit limit orders without paying gas or transaction fees, while takers cross the spread to trigger instant on-chain settlements.
2. Gnosis Conditional Token Framework (ERC1155)
Prediction shares on Polymarket are minted and redeemed using the Gnosis Conditional Token Framework. This standard defines complex conditional outcomes as unique on-chain assets:
- Collateral and Splitting: The platform utilizes USDC.e (Bridged USDC on Polygon) as collateral. Interacting with the conditional contract,
$1.00 USDC.eis split into exactly oneYEStoken and oneNOtoken. - Condition IDs & Keccak256: A market's address space is governed by a
Condition ID, which is generated viakeccak256hashing of the oracle address (e.g., UMA Optimistic Oracle), a uniqueQuestion ID, and the number of outcome slots. - Settlement Mechanics: When UMA resolves the outcome slot, the winning share becomes redeemable for
$1.00 USDC.edirectly from the conditional reserve pool, while the losing share instantly depreciates to$0.00.
3. Proxy Wallets & The Gas Station Network (GSN)
Every user trading on Polymarket interacts via a 1 of 1 smart contract proxy wallet (typically a Gnosis Safe or specialized Poly Proxy) deployed to Polygon.
- Owner Authorization: The smart contract wallet is owned by the user's primary Externally Owned Account (EOA), such as a MetaMask or Magic Link address.
- Atomic Multi-Step Executions: By routing trades through proxy contracts, the interface bundles multi-step sequences—such as approving USDC.e, splitting collateral, and submitting matching order limits—into a single atomic transaction hash.
- Meta-Transactions: Relayers on the Gas Station Network (GSN) pick up these transactions and pay the local gas fees on Polygon, utilizing signatures formatted under
GNOSIS_SAFEorPOLY_PROXYstandards.
🏛️ System Architecture & Telemetry Loop
The frontend console connects to a high-frequency FastAPI backend through secure WebSockets. This backend orchestrates real-time streams from Polymarket’s CLOB API and custom RPC nodes, normalizing trade events, order cancellations, and order-book updates through a Redis pub/sub queue.
By separating high-frequency data ingestion from state management, the system maintains smooth UI updates without thread blocking or UI layout lag—rendering live ticks at 60 FPS.
🌪️ Karin: The Forensic Elimination Funnel
One of the most complex modules inside the forensic suite is the Karin Elimination Funnel. In prediction markets, volume can be heavily distorted by circular wash-trading (addresses executing trades against themselves to harvest platform rewards or manufacture false sentiment).
To uncover genuine market interest, Karin runs trade streams through a strict, multi-stage elimination pipeline that isolates synthetic activity. The funnel is divided into four mathematical filter stages, decreasing noise step-by-step.
The Karin daemon implements this pipeline using a sliding-window algorithm in Python, utilizing asynchronous Redis transaction streams. Here is a high-level representation of Karin's transaction telemetry stream filter logic:
# karin/telemetry/filter.py
from typing import Dict, List
from datetime import datetime, timedelta
class TransactionEliminationFunnel:
def __init__(self, time_window_seconds: int = 300, risk_threshold: float = 0.85):
self.time_window = timedelta(seconds=time_window_seconds)
self.risk_threshold = risk_threshold
self.active_address_loops: Dict[str, List[Dict]] = {}
async def analyze_execution_loop(self, tx_log: Dict) -> bool:
"""
Executes multi-stage checks on Polygon RPC trade telemetry to flag wash trading.
Returns True if transaction is genuine, False if loop detected (eliminated).
"""
sender = tx_log.get("from_address")
recipient = tx_log.get("to_address")
value = float(tx_log.get("value", 0))
timestamp = datetime.fromisoformat(tx_log.get("timestamp"))
if sender == recipient:
return False # Self-wash trading detected
# Check if recipient has routed value back to sender via intermediate proxies
is_loop, loop_depth = self._scan_fund_flows(recipient, sender, value, max_depth=3)
if is_loop and (1.0 / loop_depth) >= self.risk_threshold:
return False # Wash trading loop isolated
self.active_address_loops.setdefault(sender, []).append({
"to": recipient, "value": value, "time": timestamp
})
return True👤 Kakashi: Low-Latency Copy Trading Engine
Once Karin filters out the market noise and Byakugan approves the volatility indicators, the high-conviction order signals are forwarded to Kakashi, the copy-trading and order replication engine.
Kakashi matches target wallet transactions directly against our client execution bots, bypassing high-overhead abstraction layers to lock in executions with minimal slip.
🔒 Source Code & Telemetry Privacy
Because Kokan runs active, profitable prediction market execution strategies, the code repository and live execution telemetry are private. Keeping these models open-source would dilute the execution edge and saturate the market liquidity spreads.
If you are an engineer or quantitative developer interested in prediction market mechanics, circular wash-trade filters, or high-frequency order book telemetry, I am always open to walking through the architecture, algorithms, and design choices. Feel free to connect with me at aditya@adixcode.com to talk shop!