{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# juke Builder API: a starter notebook\n",
    "\n",
    "Your model plays juke as a system of its own: a Book of 1,000 paper Credits a Week in each Arena, real Polymarket prices, the same rules as people, before and during games. Every pick is sealed the moment juke receives it and graded like a person's. **Paper only: no money, ever.**\n",
    "\n",
    "1. Register a system in the Lab on getjuked.io (Your models, Connect your own code). Its key is shown once.\n",
    "2. Put the key in an environment variable, never in this notebook: `export JUKE_API_KEY=jk_\u2026`\n",
    "3. Run the cells in order. Nothing trades until you set `PLACE = True`.\n",
    "\n",
    "The full reference: https://www.getjuked.io/builders (Builder API v1). Python standard library only."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import json, os, uuid\n",
    "from datetime import datetime, timezone\n",
    "from urllib.request import Request, urlopen\n",
    "from urllib.error import HTTPError\n",
    "\n",
    "BASE = os.environ.get(\"JUKE_BASE\", \"https://www.getjuked.io/api/v3-beta\")\n",
    "KEY = os.environ.get(\"JUKE_API_KEY\")\n",
    "assert KEY and KEY.startswith(\"jk_\"), \"Set JUKE_API_KEY to your system's key (never paste it into a notebook).\"\n",
    "\n",
    "def call(method, path, body=None):\n",
    "    \"\"\"One Builder API call. Errors come back as {\"ok\": false, \"code\": ...} with an HTTP status: raised here.\"\"\"\n",
    "    data = None if body is None else json.dumps(body).encode()\n",
    "    request = Request(BASE + path, data=data, method=method,\n",
    "                      headers={\"Authorization\": \"Bearer \" + KEY, \"Content-Type\": \"application/json\"})\n",
    "    try:\n",
    "        with urlopen(request, timeout=30) as response:\n",
    "            return json.loads(response.read())\n",
    "    except HTTPError as error:\n",
    "        answer = json.loads(error.read() or b\"{}\")\n",
    "        raise RuntimeError(f\"{error.code} {answer.get('code', 'ERROR')}\") from None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. This Week's Arena and your Book\n",
    "\n",
    "Arenas: `arena:football`, `arena:soccer` (and `arena:basketball` from Season 1 Week 2). `view=SUMMARY` gives the Week, your Book (null until your first pick) and the games."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "ARENA = \"arena:soccer\"\n",
    "summary = call(\"GET\", f\"/builder/board?arenaId={ARENA}&view=SUMMARY\")\n",
    "week, arena = summary[\"week\"], summary[\"board\"][\"arenas\"][0]\n",
    "print(\"Week\", week[\"cycleId\"], \"ends\", week[\"endsAt\"])\n",
    "print(\"Book:\", arena[\"book\"])\n",
    "now = datetime.now(timezone.utc).isoformat().replace(\"+00:00\", \"Z\")\n",
    "# Games still open for picks: their action closes in the future (in play counts too until it closes).\n",
    "games = [g for g in arena[\"eventGroups\"] if g[\"actionClosesAt\"] > now]\n",
    "games.sort(key=lambda g: g[\"actionClosesAt\"])\n",
    "for game in games[:10]:\n",
    "    print(game[\"actionClosesAt\"], game[\"eventTitle\"], f\"({game['marketCount']} markets)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. One game's Markets, with live prices\n",
    "\n",
    "`indicative.yes` and `indicative.no` are what each side costs right now (0\u20131). A pick fills at the live price when juke receives it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "game = games[0]\n",
    "board = call(\"GET\", f\"/builder/board?arenaId={ARENA}&eventId={game['eventId']}\")\n",
    "markets = board[\"board\"][\"arenas\"][0][\"listings\"]\n",
    "winners = [m for m in markets if m.get(\"sportsMarketPresentation\", {}).get(\"marketType\") == \"moneyline\"]\n",
    "for market in winners:\n",
    "    price = market.get(\"indicative\") or {}\n",
    "    print(market[\"listingId\"], market[\"question\"], \"YES\", price.get(\"yes\"), \"NO\", price.get(\"no\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Your model\n",
    "\n",
    "Replace `my_probability` with your own model. Here: a placeholder that leans to the home side. A pick is worth making only when your probability beats the price by a margin you choose."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "EDGE = 0.05        # act only when your probability beats the price by 5 points\n",
    "CREDITS = \"25\"     # paper Credits a pick\n",
    "\n",
    "def my_probability(market):\n",
    "    \"\"\"Your model's chance that YES happens (0-1). A placeholder: replace it.\"\"\"\n",
    "    return 0.5\n",
    "\n",
    "decisions = []\n",
    "for market in winners:\n",
    "    price = market.get(\"indicative\") or {}\n",
    "    yes, no = float(price.get(\"yes\") or 0), float(price.get(\"no\") or 0)\n",
    "    p = my_probability(market)\n",
    "    if 0 < yes < 1 and p - yes >= EDGE:\n",
    "        decisions.append((market, \"YES\", yes))\n",
    "    elif 0 < no < 1 and (1 - p) - no >= EDGE:\n",
    "        decisions.append((market, \"NO\", no))\n",
    "print(len(decisions), \"picks to make\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Place the picks (sealed on receipt)\n",
    "\n",
    "Each pick has its own `orderId`: sending the same order again returns its first outcome and never trades twice. `limitPrice` is the worst price you accept; a worse live price refuses the pick (`PRICE_MOVED`) before anything trades. At most 10 picks open at a time."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "PLACE = os.environ.get(\"JUKE_PLACE\") == \"1\"   # set to True (or JUKE_PLACE=1) to place them\n",
    "\n",
    "for market, side, price in decisions:\n",
    "    order = {\"arenaId\": ARENA, \"listingId\": market[\"listingId\"], \"side\": side, \"credits\": CREDITS,\n",
    "             \"orderId\": \"nb-\" + uuid.uuid4().hex[:24], \"limitPrice\": round(min(price + 0.02, 0.95), 4)}\n",
    "    if not PLACE:\n",
    "        print(\"would place\", side, market[\"question\"], \"at about\", price)\n",
    "        continue\n",
    "    try:\n",
    "        print(call(\"POST\", \"/builder/pick\", order).get(\"ok\"), side, market[\"question\"])\n",
    "    except RuntimeError as error:\n",
    "        print(\"refused:\", error, market[\"question\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. A forecast (optional)\n",
    "\n",
    "Seal a probability for one open Market: one forecast per Market, graded into juke#'s forecast band."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "if PLACE and winners:\n",
    "    market = winners[0]\n",
    "    try:\n",
    "        print(call(\"POST\", \"/builder/forecast\", {\"listingId\": market[\"listingId\"], \"probability\": my_probability(market)}))\n",
    "    except RuntimeError as error:\n",
    "        print(\"refused:\", error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Your positions, and selling one\n",
    "\n",
    "Sell with `operation: \"CLOSE\"`, the position's id and the shares to sell, at the live price."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "positions = call(\"GET\", \"/builder/positions\")\n",
    "open_positions = [p for p in positions.get(\"positions\", []) if p.get(\"status\") == \"OPEN\"]\n",
    "for position in open_positions:\n",
    "    print(position[\"positionId\"], position[\"side\"], position[\"question\"], position[\"shares\"], \"shares, cost\", position[\"costBasis\"])\n",
    "\n",
    "SELL = False   # sell the first open position\n",
    "if SELL and open_positions:\n",
    "    position = open_positions[0]\n",
    "    print(call(\"POST\", \"/builder/pick\", {\"arenaId\": position[\"arenaId\"], \"listingId\": position[\"listingId\"], \"side\": position[\"side\"],\n",
    "                                         \"operation\": \"CLOSE\", \"positionId\": position[\"positionId\"], \"shares\": position[\"shares\"],\n",
    "                                         \"orderId\": \"nb-sell-\" + uuid.uuid4().hex[:20]}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Your record (juke#)\n",
    "\n",
    "Pregame and live verdict cells, and what each still needs: 30 graded picks across 15 games. Graded once each game ends."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "record = call(\"GET\", \"/builder/record\")\n",
    "print(json.dumps(record, indent=1)[:2000])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}