Skill: diagnostikon/polymarket-twitter-cadence-model-trader (version 0.0.3)

--- name: polymarket-twitter-cadence-model-trader description: Trades post-count bin markets using a Poisson statistical model to predict the most likely bins based on historical posting rates. Requires SIMMER_API_KEY and simmer-sdk. Use when you want to price Twitter post-count bins with math instead of gut feeling. metadata: author: Diagnostikon owner: Diagnostikon version: "1.0.0" displayName: Twitter Cadence Model Trader difficulty: advanced homepage: "https://simmer.markets/skills" repository: "https://github.com/SpartanLabsXyz/simmer-sdk" requires_env: "SIMMER_API_KEY" requires_pip: "simmer-sdk" default_mode: "paper" live_flag: "--live" --- # Twitter Cadence Model Trader > **This is a template.** > The default signal is a Poisson model based on historical posting rates — remix it with Twitter/X API v2 real-time post counts, time-of-day distributions, or NLP topic-burst detection. > The skill handles all the plumbing (market discovery, trade execution, safeguards). Your agent provides the alpha. ## Strategy Overview Post-count bin markets (e.g., "Will Elon Musk post 190-214 tweets from March 30 to April 1?") are perfect for statistical modeling because **the number of posts in a time interval follows a Poisson distribution**. Retail traders price these bins by gut feeling. This skill prices them with math. ## Signal Logic ### Poisson Model 1. Parse the person, bin range, and time period from the market question 2. Compute lambda = person's historical daily rate x period days 3. Calculate P(bin) = sum of Poisson PMF from bin_lower to bin_upper 4. Compare model probability to market price 5. Trade when model diverges from market AND price is in threshold band ### Person Baselines | Person | Daily Rate | Platform | |--------|-----------|----------| | Elon Musk | ~65 tweets/day | X/Twitter | | Donald Trump | ~23 posts/day | Truth Social | | Vitalik Buterin | ~8 posts/day | X/Twitter | | CZ | ~12 posts/day | X/Twitter | ### Model Bias The Poisson model acts as a conviction multiplier: - If model says bin is 2x more likely than market → 2x conviction boost - If model says bin is 0.5x less likely → signal vetoed (don't trade against math) ### Remix Ideas - **Twitter API v2**: Replace baseline daily_rate with real-time 7-day rolling average - **Time-of-day model**: Elon posts 60% of tweets between 6PM-2AM Pacific — use hourly Poisson - **Negative binomial**: Better than Poisson for overdispersed counts (bursty posters) - **Topic burst NLP**: Detect thread-mode (3x rate) vs normal mode ## Risk Parameters | Parameter | Default | Notes | |-----------|---------|-------| | Max position size | $40 USDC | Per market | | Min market volume | $1,000 | Standard filter | | Max bid-ask spread | 10% | Default threshold | | Min days to resolution | 0 | Post-count markets are short-lived | | Max open positions | 8 | Diversify across bins | ## Installation & Setup ```bash clawhub install polymarket-twitter-cadence-model-trader ``` Requires: `SIMMER_API_KEY` environment variable. ## Cron Schedule Cron is set to `null` — the skill does not run on a schedule until you configure it in the Simmer UI. ## Safety & Execution Mode **The skill defaults to paper trading (`venue="sim"`). Real trades only execute when `--live` is passed explicitly.** | Scenario | Mode | Financial risk | |----------|------|----------------| | `python trader.py` | Paper (sim) | None | | Cron / automaton | Paper (sim) | None | | `python trader.py --live` | Live (polymarket) | Real USDC | The automaton cron is set to `null` — it does not run on a schedule until you configure it in the Simmer UI. `autostart: false` means it won't start automatically on install. ## Required Credentials | Variable | Required | Notes | |----------|----------|-------| | `SIMMER_API_KEY` | Yes | Trading authority — keep this credential private. Do not place a live-capable key in any environment where automated code could call `--live`. | ## Tunables (Risk Parameters) All risk parameters are declared in `clawhub.json` as `tunables` and adjustable from the Simmer UI without code changes. They use `SIMMER_`-prefixed env vars so `apply_skill_config()` can load them securely. | Variable | Default | Purpose | |----------|---------|---------| | `SIMMER_MAX_POSITION` | `40` | Max USDC per trade (reached at 100% conviction) | | `SIMMER_MIN_VOLUME` | `1000` | Min market volume filter (USD) | | `SIMMER_MAX_SPREAD` | `0.10` | Max bid-ask spread (0.10 = 10%) | | `SIMMER_MIN_DAYS` | `0` | Min days until market resolves | | `SIMMER_MAX_POSITIONS` | `8` | Max concurrent open positions | | `SIMMER_YES_THRESHOLD` | `0.38` | Buy YES if market price ≤ this value | | `SIMMER_NO_THRESHOLD` | `0.62` | Sell NO if market price ≥ this value | | `SIMMER_MIN_TRADE` | `5` | Floor for any trade (min USDC regardless of conviction) | ## Dependency `simmer-sdk` is published on PyPI by Simmer Markets. - PyPI: https://pypi.org/project/simmer-sdk/ - GitHub: https://github.com/SpartanLabsXyz/simmer-sdk - Publisher: [REDACTED_SECRET] Review the source before providing live credentials if you require full auditability.

path: clawhub.json
content: {
  "emoji": "\ud83d\udcca",
  "requires": {
    "env": [
      "SIMMER_API_KEY"
    ],
    "pip": [
      "simmer-sdk"
    ]
  },
  "cron": null,
  "autostart": false,
  "automaton": {
    "managed": true,
    "entrypoint": "trader.py"
  },
  "tunables": [
    {
      "env": "SIMMER_MAX_POSITION",
      "default": 40,
      "range": [
        1,
        200
      ],
      "step": 1,
      "label": "Max position size (USD)",
      "type": "number"
    },
    {
      "env": "SIMMER_MIN_VOLUME",
      "default": 1000,
      "range": [
        0,
        100000
      ],
      "step": 500,
      "label": "Min market volume (USD)",
      "type": "number"
    },
    {
      "env": "SIMMER_MAX_SPREAD",
      "default": 0.1,
      "range": [
        0.01,
        0.5
      ],
      "step": 0.01,
      "label": "Max bid-ask spread",
      "type": "number"
    },
    {
      "env": "SIMMER_MIN_DAYS",
      "default": 0,
      "range": [
        0,
        30
      ],
      "step": 1,
      "label": "Min days until resolution",
      "type": "number"
    },
    {
      "env": "SIMMER_MAX_POSITIONS",
      "default": 8,
      "range": [
        1,
        20
      ],
      "step": 1,
      "label": "Max open positions",
      "type": "number"
    },
    {
      "env": "SIMMER_MIN_TRADE",
      "type": "number",
      "default": 5,
      "range": [
        1,
        100
      ],
      "step": 1,
      "label": "Min trade size (USD)"
    },
    {
      "env": "SIMMER_YES_THRESHOLD",
      "type": "number",
      "default": 0.38,
      "range": [
        0.01,
        0.49
      ],
      "step": 0.01,
      "label": "YES threshold"
    },
    {
      "env": "SIMMER_NO_THRESHOLD",
      "type": "number",
      "default": 0.62,
      "range": [
        0.51,
        0.99
      ],
      "step": 0.01,
      "label": "NO threshold"
    }
  ],
  "version": "0.0.2"
}

path: trader.py
content: """
polymarket-twitter-cadence-model-trader
Trades Twitter/X and Truth Social post-count bin markets using a Poisson
statistical model to predict the most likely bins.

SAFE BY DEFAULT:
- No --live flag = paper trading (venue="sim"), zero financial risk.
- Cron/automaton runs default to paper mode.
- Real trades only with explicit --live flag.
"""
import os
import re
import sys
import argparse
from math import lgamma, exp, log
from datetime import datetime, timezone
from simmer_sdk import SimmerClient

TRADE_SOURCE = "sdk:polymarket-twitter-cadence-model-trader"
SKILL_SLUG   = "polymarket-twitter-cadence-model-trader"

KEYWORDS = [
    'Elon Musk', 'elon musk tweet', 'musk tweets',
    'Donald Trump', 'trump post', 'Truth Social',
    'Vitalik', 'vitalik post', 'CZ tweet',
    'tweets', 'posts',
]

# --- Person baselines (historical daily posting rates) -----------------------
PERSONS = {
    'elon musk':        {'key': 'elon',    'daily_rate': 65, 'weekend_factor': 0.70},
    'donald trump':     {'key': 'trump',   'daily_rate': 23, 'weekend_factor': 0.80},
    'vitalik buterin':  {'key': 'vitalik', 'daily_rate': 8,  'weekend_factor': 0.90},
    'cz':               {'key': 'cz',      'daily_rate': 12, 'weekend_factor': 0.85},
}

MONTH_MAP = {
    'january': 1, 'february': 2, 'march': 3, 'april': 4,
    'may': 5, 'june': 6, 'july': 7, 'august': 8,
    'september': 9, 'october': 10, 'november': 11, 'december': 12,
}

# Risk parameters
MAX_POSITION   = float(os.environ.get("SIMMER_MAX_POSITION",  "40"))
MIN_VOLUME     = float(os.environ.get("SIMMER_MIN_VOLUME",    "1000"))
MAX_SPREAD     = float(os.environ.get("SIMMER_MAX_SPREAD",    "0.10"))
MIN_DAYS       = int(os.environ.get(  "SIMMER_MIN_DAYS",      "0"))
MAX_POSITIONS  = int(os.environ.get(  "SIMMER_MAX_POSITIONS", "8"))
YES_THRESHOLD  = float(os.environ.get("SIMMER_YES_THRESHOLD", "0.38"))
NO_THRESHOLD   = float(os.environ.get("SIMMER_NO_THRESHOLD",  "0.62"))
MIN_TRADE      = float(os.environ.get("SIMMER_MIN_TRADE",     "5"))

_client: SimmerClient | None = None


def safe_print(text: str) -> None:
    try:
        print(text)
    except UnicodeEncodeError:
        print(text.encode("ascii", errors="replace").decode())


def get_client(live: bool = False) -> SimmerClient:
    global _client, MAX_POSITION, MIN_VOLUME, MAX_SPREAD, MIN_DAYS, MAX_POSITIONS
    global YES_THRESHOLD, NO_THRESHOLD, MIN_TRADE
    if _client is None:
        venue = "polymarket" if live else "sim"
        _client = SimmerClient(
            [REDACTED_SECRET]"SIMMER_API_KEY"],
            venue=venue,
        )
        if live:
            _client.live = True
        try:
            _client.apply_skill_config(SKILL_SLUG)
        except AttributeError:
            pass  # apply_skill_config only available in Simmer runtime
        MAX_POSITION   = float(os.environ.get("SIMMER_MAX_POSITION",  str(MAX_POSITION)))
        MIN_VOLUME     = float(os.environ.get("SIMMER_MIN_VOLUME",    str(MIN_VOLUME)))
        MAX_SPREAD     = float(os.environ.get("SIMMER_MAX_SPREAD",    str(MAX_SPREAD)))
        MIN_DAYS       = int(os.environ.get(  "SIMMER_MIN_DAYS",      str(MIN_DAYS)))
        MAX_POSITIONS  = int(os.environ.get(  "SIMMER_MAX_POSITIONS", str(MAX_POSITIONS)))
        YES_THRESHOLD  = float(os.environ.get("SIMMER_YES_THRESHOLD", str(YES_THRESHOLD)))
        NO_THRESHOLD   = float(os.environ.get("SIMMER_NO_THRESHOLD",  str(NO_THRESHOLD)))
        MIN_TRADE      = float(os.environ.get("SIMMER_MIN_TRADE",     str(MIN_TRADE)))
    return _client


# ── Market discovery ─────────────────────────────────────────────────────────

POST_FILTER = re.compile(
    r'(tweet|tweets|post|posts|truth social)', re.IGNORECASE
)
BIN_PATTERN = re.compile(r'(\d+)\s*[-\u2013]\s*(\d+)')
DATE_PATTERN = re.compile(
    r'(\w+)\s+(\d{1,2})\s+to\s+(\w+)\s+(\d{1,2}),?\s*(\d{4})',
    re.IGNORECASE,
)


def find_markets(client: SimmerClient) -> list:
    seen, unique = set(), []
    for kw in KEYWORDS:
        try:
            for m in client.find_markets(query=kw):
                q = getattr(m, 'question', '')
                if m.id not in seen and POST_FILTER.search(q) and BIN_PATTERN.search(q):
                    seen.add(m.id)
                    unique.append(m)
        except Exception as e:
            safe_print(f"[search] {kw!r}: {e}")
    # Fallback: scan all account markets
    try:
        for m in client.get_markets(limit=200):
            q = getattr(m, 'question', '')
            if m.id not in seen and POST_FILTER.search(q) and BIN_PATTERN.search(q):
                seen.add(m.id)
                unique.append(m)
    except Exception as e:
        safe_print(f"[fallback] {e}")
    return unique


# ── Parsing ──────────────────────────────────────────────────────────────────

def parse_post_market(question: str):
    """Returns (person_info, bin_lower, bin_upper, period_days) or Nones."""
    q = question.lower()
    person_info = None
    for name, info in PERSONS.items():
        if name in q:
            person_info = info
            break
    if not person_info:
        return None, None, None, None

    rm = BIN_PATTERN.search(question)
    if not rm:
        return None, None, None, None
    bin_lower, bin_upper = int(rm.group(1)), int(rm.group(2))

    dm = DATE_PATTERN.search(question)
    if dm:
        m1, d1, m2, d2, year = dm.groups()
        m1n = MONTH_MAP.get(m1.lower(), 1)
        m2n = MONTH_MAP.get(m2.lower(), m1n)
        try:
            start = datetime(int(year), m1n, int(d1), tzinfo=timezone.utc)
            end   = datetime(int(year), m2n, int(d2), tzinfo=timezone.utc)
            period_days = max(1, (end - start).days + 1)
        except Exception:
            period_days = 3
    else:
        period_days = 3

    return person_info, bin_lower, bin_upper, period_days


# ── Poisson model ────────────────────────────────────────────────────────────

def poisson_log_pmf(k: int, lam: float) -> float:
    """Log P(X = k) for Poisson(lam)."""
    if lam <= 0:
        return -999.0
    return k * log(lam) - lam - lgamma(k + 1)


def poisson_bin_prob(lower: int, upper: int, lam: float) -> float:
    """P(lower <= X <= upper) using log-space summation for numerical stability."""
    log_probs = [poisson_log_pmf(k, lam) for k in range(lower, upper + 1)]
    if not log_probs:
        return 0.0
    max_lp = max(log_probs)
    return exp(max_lp) * sum(exp(lp - max_lp) for lp in log_probs)


# ── Signal ───────────────────────────────────────────────────────────────────

def compute_signal(market) -> tuple[str | None, float, str]:
    """
    Poisson cadence model: compute P(bin) from person's daily rate x period days,
    compare to market price, trade when model diverges from market.
    """
    p = market.current_probability
    q = market.question

    if market.spread_cents is not None and market.spread_cents / 100 > MAX_SPREAD:
        return None, 0, f"Spread {market.spread_cents/100:.1%} > {MAX_SPREAD:.1%}"

    if market.resolves_at:
        try:
            resolves = datetime.fromisoformat(market.resolves_at.replace("Z", "+00:00"))
            days_left = (resolves - datetime.now(timezone.utc)).days
            if days_left < MIN_DAYS:
                return None, 0, f"Only {days_left} days left"
        except Exception:
            pass

    person, bl, bu, period_days = parse_post_market(q)
    if not person:
        return None, 0, "Not a post-count bin market"

    lam = person['daily_rate'] * period_days
    model_p = poisson_bin_prob(bl, bu, lam)

    # Model bias: how much our model agrees with the threshold signal
    # >1 means model reinforces the signal, <1 means model contradicts it
    if p <= YES_THRESHOLD:
        # We'd buy YES — does our model agree this bin is underpriced?
        if model_p <= p * 0.5:
            return None, 0, f"Model disagrees: model={model_p:.1%} < mkt={p:.1%}, skip YES"
        bias = min(2.0, max(0.5, model_p / max(p, 0.01)))
        conviction = min(1.0, (YES_THRESHOLD - p) / YES_THRESHOLD * bias)
        size = max(MIN_TRADE, round(conviction * MAX_POSITION, 2))
        edge = model_p - p
        return "yes", size, (
            f"YES model={model_p:.0%} mkt={p:.0%} edge={edge:+.0%} "
            f"lam={lam:.0f} bias={bias:.1f}x ${size} -- {q[:55]}"
        )

    if p >= NO_THRESHOLD:
        # We'd sell NO — does our model agree this bin is overpriced?
        if model_p >= p * 1.5:
            return None, 0, f"Model disagrees: model={model_p:.1%} > mkt={p:.1%}, skip NO"
        bias = min(2.0, max(0.5, max(p, 0.01) / max(model_p, 0.01)))
        conviction = min(1.0, (p - NO_THRESHOLD) / (1 - NO_THRESHOLD) * bias)
        size = max(MIN_TRADE, round(conviction * MAX_POSITION, 2))
        edge = p - model_p
        return "no", size, (
            f"NO model={model_p:.0%} mkt={p:.0%} edge={edge:+.0%} "
            f"lam={lam:.0f} bias={bias:.1f}x ${size} -- {q[:55]}"
        )

    return None, 0, f"Neutral {p:.1%} (model={model_p:.1%}, lam={lam:.0f})"


# ── Context check ────────────────────────────────────────────────────────────

def context_ok(client: SimmerClient, market_id: str) -> tuple[bool, str]:
    try:
        ctx = client.get_market_context(market_id)
        if not ctx:
            return True, "no context"
        if ctx.get("discipline", {}).get("is_flip_flop"):
            return False, f"Flip-flop: {ctx['discipline'].get('flip_flop_reason', 'reversal')}"
        slip = ctx.get("slippage", {})
        if isinstance(slip, dict) and slip.get("slippage_pct", 0) > 0.15:
            return False, f"Slippage {slip['slippage_pct']:.1%}"
        for w in ctx.get("warnings", []):
            safe_print(f"  [warn] {w}")
    except Exception as e:
        safe_print(f"  [ctx] {market_id}: {e}")
    return True, "ok"


# ── Main loop ────────────────────────────────────────────────────────────────

def run(live: bool = False) -> None:
    mode = "LIVE" if live else "PAPER (sim)"
    safe_print(f"[twitter-cadence-model] mode={mode} max_pos=${MAX_POSITION}")

    client  = get_client(live=live)
    markets = find_markets(client)
    safe_print(f"[twitter-cadence-model] {len(markets)} post-count bin markets found")

    placed = 0
    for m in markets:
        if placed >= MAX_POSITIONS:
            break
        side, size, reasoning = compute_signal(m)
        if not side:
            safe_print(f"  [skip] {reasoning}")
            continue
        ok, why = context_ok(client, m.id)
        if not ok:
            safe_print(f"  [skip] {why}")
            continue
        try:
            r = client.trade(
                market_id=m.id, side=side, amount=size,
                source=TRADE_SOURCE, skill_slug=SKILL_SLUG, reasoning=reasoning,
            )
            tag = "(sim)" if r.simulated else "(live)"
            status = "OK" if r.success else f"FAIL:{r.error}"
            safe_print(f"  [trade] {side.upper()} ${size} {tag} {status} -- {reasoning[:70]}")
            if r.success:
                placed += 1
        except Exception as e:
            safe_print(f"  [error] {m.id}: {e}")

    safe_print(f"[twitter-cadence-model] done. {placed} orders placed.")


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--live", action="store_true",
                    help="Real trades on Polymarket. Default is paper (sim) mode.")
    run(live=ap.parse_args().live)


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)