Skill: diagnostikon/polymarket-twitter-weekend-drift-trader (version 0.0.3)

--- name: polymarket-twitter-weekend-drift-trader description: Exploits systematic weekday/weekend posting rate differences in post-count bin markets. Requires SIMMER_API_KEY and simmer-sdk. Use when you want to capture alpha from weekend drift mispricing where markets reflect weekday cadence but the period spans weekends. metadata: author: Diagnostikon owner: Diagnostikon version: "1.0.0" displayName: Twitter Weekend Drift 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 Weekend Drift Trader > **This is a template.** > The default signal uses fixed weekday/weekend rate differentials — remix it with hourly posting distributions, holiday calendars, or timezone-aware activity windows. > The skill handles all the plumbing (market discovery, trade execution, safeguards). Your agent provides the alpha. ## Strategy Overview Public figures post 20-30% less on weekends. But market makers often set prices on Friday, reflecting weekday cadence. A 3-day period spanning Fri-Sun has very different expected post counts than Mon-Wed. This skill counts the actual weekdays vs weekend days in each market's period and adjusts the expected rate accordingly. ## Signal Logic ### Weekend Rate Differentials | Person | Weekday Rate | Weekend Rate | Drop | |--------|-------------|-------------|------| | Elon Musk | 72/day | 50/day | -31% | | Donald Trump | 25/day | 20/day | -20% | | Vitalik Buterin | 9/day | 7/day | -22% | | CZ | 14/day | 10/day | -29% | ### How It Works 1. Parse the date range from the market question 2. Count actual weekdays and weekend days 3. Compute `adjusted_lambda = weekday_rate * weekdays + weekend_rate * weekends` 4. Compare to `naive_lambda = average_rate * total_days` 5. The drift determines which bins are over/underpriced ### Example Elon Musk, March 28 (Fri) to March 30 (Sun) = 3 days: - Naive: 65/day * 3 = 195 posts - Adjusted: 72*1 + 50*2 = 172 posts - **Drift: -12%** — lower bins underpriced, higher bins overpriced ### Remix Ideas - **Holiday calendar**: Major holidays (Christmas, July 4th) suppress posting even more than weekends - **Hourly distribution**: Model posting by hour-of-day for sub-daily market periods - **Timezone awareness**: Elon posts Pacific time, Trump posts Eastern — periods crossing midnight differ - **Rolling rate updates**: Re-estimate weekday/weekend split weekly from actual data ## 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-weekend-drift-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\udcc5",
  "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-weekend-drift-trader
Exploits systematic weekday/weekend posting rate differences in post-count
bin markets.  Weekend posting rates are 20-30% lower for most public figures,
but markets are often set on Friday reflecting weekday cadence.

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 datetime import datetime, timezone, timedelta
from simmer_sdk import SimmerClient

TRADE_SOURCE = "sdk:polymarket-twitter-weekend-drift-trader"
SKILL_SLUG   = "polymarket-twitter-weekend-drift-trader"

KEYWORDS = [
    'Elon Musk', 'elon musk tweet', 'musk tweets',
    'Donald Trump', 'trump post', 'Truth Social',
    'Vitalik', 'vitalik post', 'CZ tweet',
    'tweets', 'posts',
]

PERSONS = {
    'elon musk':        {'key': 'elon',    'weekday_rate': 72, 'weekend_rate': 50},
    'donald trump':     {'key': 'trump',   'weekday_rate': 25, 'weekend_rate': 20},
    'vitalik buterin':  {'key': 'vitalik', 'weekday_rate': 9,  'weekend_rate': 7},
    'cz':               {'key': 'cz',      'weekday_rate': 14, 'weekend_rate': 10},
}

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,
}

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


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}")
    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


def parse_post_market(question: str):
    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, None, None
    rm = BIN_PATTERN.search(question)
    if not rm:
        return None, None, None, None, None, None
    bin_lower, bin_upper = int(rm.group(1)), int(rm.group(2))
    dm = DATE_PATTERN.search(question)
    start_date, end_date = None, None
    period_days = 3
    if dm:
        m1, d1, m2, d2, year = dm.groups()
        try:
            start_date = datetime(int(year), MONTH_MAP.get(m1.lower(), 1), int(d1), tzinfo=timezone.utc)
            end_date   = datetime(int(year), MONTH_MAP.get(m2.lower(), 1), int(d2), tzinfo=timezone.utc)
            period_days = max(1, (end_date - start_date).days + 1)
        except Exception:
            pass
    return person_info, bin_lower, bin_upper, period_days, start_date, end_date


def count_weekend_weekday(start: datetime, days: int) -> tuple[int, int]:
    """Count how many weekend days (Sat=5, Sun=6) vs weekdays in the period."""
    weekend, weekday = 0, 0
    for i in range(days):
        d = start + timedelta(days=i)
        if d.weekday() >= 5:
            weekend += 1
        else:
            weekday += 1
    return weekday, weekend


def weekend_adjusted_lambda(person: dict, start: datetime | None, period_days: int) -> tuple[float, float]:
    """
    Returns (naive_lambda, adjusted_lambda).
    naive = flat daily rate * days (what the market probably assumes).
    adjusted = weekday_rate * weekdays + weekend_rate * weekends.
    """
    avg_rate = (person['weekday_rate'] * 5 + person['weekend_rate'] * 2) / 7
    naive_lam = avg_rate * period_days

    if start:
        weekdays, weekends = count_weekend_weekday(start, period_days)
        adj_lam = person['weekday_rate'] * weekdays + person['weekend_rate'] * weekends
    else:
        adj_lam = naive_lam  # can't compute without dates

    return naive_lam, adj_lam


def compute_signal(market) -> tuple[str | None, float, str]:
    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, start, end = parse_post_market(q)
    if not person:
        return None, 0, "Not a post-count bin market"

    naive_lam, adj_lam = weekend_adjusted_lambda(person, start, period_days)
    bin_mid = (bl + bu) / 2

    # The weekend drift: if adjusted lambda is lower than naive, lower bins are
    # underpriced and higher bins are overpriced (and vice versa)
    drift = adj_lam - naive_lam  # negative = fewer posts expected than market thinks
    drift_pct = drift / max(naive_lam, 1)

    # Determine if this bin benefits from the drift
    if abs(drift_pct) < 0.02:
        return None, 0, f"Minimal drift {drift_pct:+.1%} for {person['key']} ({naive_lam:.0f}->{adj_lam:.0f})"

    # Lower bins benefit from negative drift (fewer posts expected)
    # Higher bins benefit from positive drift (more posts expected)
    bin_aligns_with_drift = (
        (drift < 0 and bin_mid < naive_lam) or  # fewer posts, lower bin
        (drift > 0 and bin_mid > naive_lam)      # more posts, higher bin
    )

    bias = 1.0 + abs(drift_pct) * 3 if bin_aligns_with_drift else max(0.4, 1.0 - abs(drift_pct) * 3)

    if p <= YES_THRESHOLD:
        conviction = min(1.0, (YES_THRESHOLD - p) / YES_THRESHOLD * bias)
        size = max(MIN_TRADE, round(conviction * MAX_POSITION, 2))
        edge = YES_THRESHOLD - p
        return "yes", size, (
            f"YES {p:.0%} edge={edge:.0%} drift={drift_pct:+.0%} "
            f"bias={bias:.1f}x ${size} -- {person['key']} {bl}-{bu}"
        )

    if p >= NO_THRESHOLD:
        conviction = min(1.0, (p - NO_THRESHOLD) / (1 - NO_THRESHOLD) * bias)
        size = max(MIN_TRADE, round(conviction * MAX_POSITION, 2))
        edge = p - NO_THRESHOLD
        return "no", size, (
            f"NO {p:.0%} edge={edge:.0%} drift={drift_pct:+.0%} "
            f"bias={bias:.1f}x ${size} -- {person['key']} {bl}-{bu}"
        )

    return None, 0, f"Neutral {p:.1%} (drift={drift_pct:+.1%}, bias={bias:.1f}x)"


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"


def run(live: bool = False) -> None:
    mode = "LIVE" if live else "PAPER (sim)"
    safe_print(f"[twitter-weekend-drift] mode={mode} max_pos=${MAX_POSITION}")

    client  = get_client(live=live)
    markets = find_markets(client)
    safe_print(f"[twitter-weekend-drift] {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-weekend-drift] 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: clean (LOW)