Skill: diagnostikon/polymarket-emerging-tech-trader (version 0.0.3)

--- name: polymarket-emerging-tech-trader description: Trades Polymarket prediction markets on Web3/DeFi milestones, NFT market recovery, metaverse adoption, humanoid robotics deployments, quantum computing breakthroughs, and synthetic biology commercialization. Use when you want to capture alpha on niche emerging technology markets where most retail traders lack domain expertise. metadata: author: Diagnostikon version: '1.0' displayName: Emerging Tech Trader difficulty: advanced --- # Emerging Tech Trader > **This is a template.** > The default signal is keyword discovery + on-chain data signals — remix it with DeFiLlama TVL feeds, GitHub commit velocity for quantum computing projects, robotics deployment trackers, or synthetic biology investment databases. > The skill handles all the plumbing (market discovery, trade execution, safeguards). Your agent provides the alpha. ## Strategy Overview Emerging tech markets are among the highest-edge opportunities on Polymarket because most retail participants lack domain expertise. A trader with genuine technical knowledge in robotics, quantum computing, or DeFi holds massive informational advantage. This skill covers 5 sub-categories: ### 1. Web3 & DeFi - Prediction market TVL milestones, cross-chain liquidity thresholds - NFT market recovery volume markers - Tokenized prediction position collateral milestones ### 2. Metaverse & VR/AR - Meta Horizon DAU milestones, VR headset sales - Virtual real estate transaction volumes ### 3. Robotics & Automation - Humanoid robot factory deployments (Figure, Tesla Optimus, 1X) - Autonomous delivery robot counts - Warehouse automation penetration rates ### 4. Quantum Computing - IBM qubit count milestones - Commercial quantum revenue thresholds - Quantum advantage demonstrations ### 5. Synthetic Biology - Lab-grown meat regulatory approvals - Precision fermentation market size - Engineered bacteria commercial deployments ## Signal Logic ### Default Signal: Conviction-Based Sizing with Hype-Cycle Bias 1. Discover markets matching emerging tech keywords 2. Compute base conviction from distance to threshold (0% at boundary → 100% at p=0/p=1) 3. Apply `domain_bias()` multiplier — boost underappreciated domains, dampen hype-prone ones 4. Size = `max(MIN_TRADE, conviction × bias × MAX_POSITION)` — capped at MAX_POSITION 5. Skip markets with spread > MAX_SPREAD or fewer than MIN_DAYS to resolution ### Domain Bias (built-in, no API required) Different emerging tech categories have systematic mispricing patterns. `domain_bias()` adjusts conviction based on known retail behavior in each domain: | Domain | Bias | Why | |---|---|---| | Metaverse / NFT | **0.70x** | Media hype cycles inflate YES; most milestones miss | | Humanoid robots | **0.75x** | YouTube demos precede real deployments by 6–18 months | | Quantum computing | **1.30x** | arXiv progress is systematic; markets lag by weeks | | Synthetic biology | **1.25x** | Regulatory filings are public; market underweights precedent | | DeFi / TVL | **1.20x** | On-chain data is real-time; market repricing lags 2–6h | | Other | **1.00x** | No systematic bias detected | Example: quantum market at 25% → conviction 34% × 1.3x = 44% → $11 position. Metaverse market at same price → 34% × 0.7x = 24% → $6 (conservative). ### Remix Ideas - **DeFiLlama API**: Replace `market.current_probability` with TVL-implied probability — trade the divergence between on-chain data and market price - **GitHub API**: Measure commit velocity on IBM Qiskit / Google Cirq repos as quantum progress signal - **CoinGlass / OpenSea**: NFT floor and volume data as leading indicator for NFT milestone markets - **The Good Food Institute**: Lab-grown meat regulatory tracker for synthetic biology markets - **arXiv API**: Monitor quantum/ML paper releases as leading signal before market repricing ## Market Categories Tracked ```python KEYWORDS = [ 'Web3', 'DeFi', 'NFT', 'blockchain', 'metaverse', 'VR', 'AR', 'robot', 'humanoid', 'autonomous delivery', 'Boston Dynamics', 'Tesla Optimus', 'Figure robot', 'warehouse automation', 'quantum', 'qubit', 'IBM quantum', 'Google quantum', 'synthetic biology', 'lab-grown meat', 'cultivated meat', 'precision fermentation', 'Solana', 'Ethereum', 'TVL', ] ``` ## Risk Parameters | Parameter | Default | Notes | |-----------|---------|-------| | Max position size | $25 USDC | Emerging tech markets are volatile | | Min market volume | $2,000 | Some niche markets start illiquid | | Max bid-ask spread | 15% | Accept wider spreads for edge markets | | Min days to resolution | 14 | Technical milestones need longer lead time | | Max open positions | 8 | Diversify across sub-categories | ## Sub-Category Edge Analysis | Category | Edge Source | Typical Market Bias | |----------|-------------|---------------------| | Quantum Computing | Academic paper lag (arXiv 6–24h before news) | Retail underestimates IBM progress | | Humanoid Robots | YouTube demo videos precede deployments | Fan hype overprices Tesla Optimus | | DeFi/TVL | On-chain data is real-time | Markets lag DeFiLlama by 2–6h | | Lab-Grown Meat | Regulatory filings public before decisions | Market underweights FDA precedent | | NFT Markets | OpenSea/Blur volume APIs | Volume data available before price consensus | ## Key Data Sources - **DeFiLlama**: https://defillama.com/ - **GitHub API**: https://api.github.com/ - **IBM Quantum Network**: https://quantum.ibm.com/ - **The Good Food Institute**: https://gfi.org/ - **CoinGlass NFT**: https://www.coinglass.com/nft ## Installation & Setup ```bash clawhub install polymarket-emerging-tech-trader ``` Requires: `SIMMER_API_KEY` environment variable. ## Cron Schedule Runs every 15 minutes (`*/15 * * * *`). Emerging tech events are infrequent but high-impact when they occur. ## 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` | `25` | Max USDC per trade (reached at 100% conviction) | | `SIMMER_MIN_VOLUME` | `2000` | Min market volume filter (USD) | | `SIMMER_MAX_SPREAD` | `0.15` | Max bid-ask spread (0.15 = 15%) | | `SIMMER_MIN_DAYS` | `14` | 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": "\u269b\ufe0f",
  "requires": {
    "env": [
      "SIMMER_API_KEY"
    ],
    "pip": [
      "simmer-sdk"
    ]
  },
  "cron": null,
  "autostart": false,
  "automaton": {
    "managed": true,
    "entrypoint": "trader.py"
  },
  "tunables": [
    {
      "env": "SIMMER_MAX_POSITION",
      "default": 25,
      "range": [
        1,
        200
      ],
      "step": 1,
      "label": "Max position size (USD)",
      "type": "number"
    },
    {
      "env": "SIMMER_MIN_VOLUME",
      "default": 2000,
      "range": [
        0,
        100000
      ],
      "step": 500,
      "label": "Min market volume (USD)",
      "type": "number"
    },
    {
      "env": "SIMMER_MAX_SPREAD",
      "default": 0.15,
      "range": [
        0.01,
        0.5
      ],
      "step": 0.01,
      "label": "Max bid-ask spread",
      "type": "number"
    },
    {
      "env": "SIMMER_MIN_DAYS",
      "default": 14,
      "range": [
        1,
        90
      ],
      "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"
    }
  ],
  "version": "0.0.2"
}

path: trader.py
content: """
polymarket-emerging-tech-trader
Trades Web3/DeFi, metaverse, robotics, quantum computing, and synthetic biology markets on Polymarket.

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 argparse
from datetime import datetime, timezone
from simmer_sdk import SimmerClient

TRADE_SOURCE = "sdk:polymarket-emerging-tech-trader"
SKILL_SLUG   = "polymarket-emerging-tech-trader"

KEYWORDS = [
    'Web3', 'DeFi', 'NFT', 'blockchain', 'metaverse', 'VR', 'AR',
    'robot', 'humanoid', 'autonomous delivery', 'Boston Dynamics',
    'Tesla Optimus', 'Figure robot', 'warehouse automation',
    'quantum', 'qubit', 'IBM quantum', 'Google quantum',
    'synthetic biology', 'lab-grown meat', 'cultivated meat',
    'precision fermentation', 'Solana', 'Ethereum', 'TVL',
]

# Risk parameters — declared as tunables in clawhub.json, tunable from Simmer UI.
# Named SIMMER_* so apply_skill_config() can load automaton-managed overrides.
MAX_POSITION   = float(os.environ.get("SIMMER_MAX_POSITION",  "25"))
MIN_VOLUME     = float(os.environ.get("SIMMER_MIN_VOLUME",    "2000"))
MAX_SPREAD     = float(os.environ.get("SIMMER_MAX_SPREAD",    "0.15"))
MIN_DAYS       = int(os.environ.get(  "SIMMER_MIN_DAYS",      "14"))
MAX_POSITIONS  = int(os.environ.get(  "SIMMER_MAX_POSITIONS", "8"))
# Signal thresholds — buy YES below YES_THRESHOLD, sell NO above NO_THRESHOLD.
# Position size scales with conviction, further adjusted by domain-specific hype bias.
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 get_client(live: bool = False) -> SimmerClient:
    """
    live=False → venue="sim"  (paper trades — safe default).
    live=True  → venue="polymarket" (real trades, only with --live flag).
    """
    global _client, MAX_POSITION, MIN_VOLUME, MAX_SPREAD, MIN_DAYS, MAX_POSITIONS, 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,
        )
        # Load tunable overrides set via the Simmer UI (SIMMER_* vars only).
        if live:
            _client.live = True
        try:
            _client.apply_skill_config(SKILL_SLUG)
        except AttributeError:
            pass  # apply_skill_config only available in Simmer runtime
        # Re-read params in case apply_skill_config updated os.environ.
        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


def find_markets(client: SimmerClient) -> list:
    """Find active markets matching strategy keywords, deduplicated."""
    seen, unique = set(), []
    for kw in KEYWORDS:
        try:
            for m in client.find_markets(query=kw):
                if m.id not in seen:
                    seen.add(m.id)
                    unique.append(m)
        except Exception as e:
            print(f"[search] {kw!r}: {e}")
    return unique


def domain_bias(question: str) -> float:
    """
    Returns a conviction multiplier (0.7–1.3) based on systematic mispricing
    patterns by emerging tech domain.

    Hype-prone categories attract overconfident retail traders who inflate YES
    prices — we trade smaller to avoid crowded, overpriced positions.

    Underappreciated categories are systematically underpriced because retail
    lacks domain depth — we trade larger when we have edge.

    Pattern                        Reason
    ─────────────────────────────  ──────────────────────────────────────────
    Metaverse / NFT → 0.70x        Media hype cycles inflate YES; most milestones miss
    Humanoid robots → 0.75x        YouTube demos precede deployments by 6–18 months
    Quantum computing → 1.30x      arXiv progress systematic; markets lag by weeks
    Synthetic biology → 1.25x      Regulatory filings public; market underweights precedent
    DeFi / TVL → 1.20x             On-chain data real-time; market repricing lags 2–6h
    """
    q = question.lower()

    # Hype-prone: retail overestimates likelihood — trade cautiously
    if any(w in q for w in ("metaverse", "virtual reality", "vr headset", "nft", "meta horizon")):
        return 0.7
    if any(w in q for w in ("humanoid", "optimus", "tesla robot", "figure robot", "1x robot")):
        return 0.75

    # Underappreciated: retail underestimates steady technical progress — lean in
    if any(w in q for w in ("quantum", "qubit", "quantum advantage", "quantum volume", "quantum error")):
        return 1.3
    if any(w in q for w in ("lab-grown", "cultivated meat", "precision fermentation", "synthetic biology", "bioreactor")):
        return 1.25
    if any(w in q for w in ("defi", "tvl", "total value locked", "defillama", "protocol revenue")):
        return 1.2

    return 1.0  # no systematic bias detected — neutral


def compute_signal(market) -> tuple[str | None, float, str]:
    """
    Returns (side, size, reasoning) or (None, 0, skip_reason).

    Conviction-based sizing with domain hype/discount adjustment:
    - Base conviction scales linearly with distance from threshold
    - domain_bias() multiplies conviction up or down based on tech category
    - Result capped at 1.0 so size never exceeds MAX_POSITION
    - MIN_TRADE floor prevents trivially small orders near the boundary

    Remix: replace market.current_probability with DeFiLlama TVL-implied
    probability or GitHub commit velocity score to trade the divergence
    between observable data and market price.
    """
    p = market.current_probability
    q = market.question

    # Spread gate
    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%}"

    # Days-to-resolution gate
    if market.resolves_at:
        try:
            resolves = datetime.fromisoformat(market.resolves_at.replace("Z", "+00:00"))
            days = (resolves - datetime.now(timezone.utc)).days
            if days < MIN_DAYS:
                return None, 0, f"Only {days} days to resolve"
        except Exception:
            pass

    bias = domain_bias(q)

    if p <= YES_THRESHOLD:
        # conviction=0 at threshold boundary, conviction=1 at p=0 — scaled by domain bias
        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%} bias={bias:.2f}x size=${size} — {q[:65]}"

    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 YES={p:.0%} edge={edge:.0%} bias={bias:.2f}x size=${size} — {q[:65]}"

    return None, 0, f"Neutral at {p:.1%} (outside {YES_THRESHOLD:.0%}/{NO_THRESHOLD:.0%} bands)"


def context_ok(client: SimmerClient, market_id: str) -> tuple[bool, str]:
    """Check flip-flop and slippage safeguards."""
    try:
        ctx = client.get_market_context(market_id)
        if not ctx:
            return True, "no context"
        if ctx.get("discipline", {}).get("is_flip_flop"):
            reason = ctx["discipline"].get("flip_flop_reason", "recent reversal")
            return False, f"Flip-flop: {reason}"
        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", []):
            print(f"  [warn] {w}")
    except Exception as e:
        print(f"  [ctx] {market_id}: {e}")
    return True, "ok"


def run(live: bool = False) -> None:
    mode = "LIVE" if live else "PAPER (sim)"
    print(f"[polymarket-emerging-tech-trader] mode={mode} max_pos=${MAX_POSITION} min_vol=${MIN_VOLUME} max_spread={MAX_SPREAD:.0%} min_days={MIN_DAYS}")

    client  = get_client(live=live)
    markets = find_markets(client)
    print(f"[polymarket-emerging-tech-trader] {len(markets)} candidate markets")

    placed = 0
    for m in markets:
        if placed >= MAX_POSITIONS:
            break

        side, size, reasoning = compute_signal(m)
        if not side:
            print(f"  [skip] {reasoning}")
            continue

        ok, why = context_ok(client, m.id)
        if not ok:
            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}"
            print(f"  [trade] {side.upper()} ${size} {tag} {status} — {reasoning[:70]}")
            if r.success:
                placed += 1
        except Exception as e:
            print(f"  [error] {m.id}: {e}")

    print(f"[polymarket-emerging-tech-trader] done. {placed} orders placed.")


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="Trades Web3/DeFi, metaverse, robotics, quantum computing, and synthetic biology markets on Polymarket.")
    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)