{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c723d607",
   "metadata": {},
   "source": [
    "# 03 — Libro de Ordenes en Tiempo Real (Binance)\n",
    "\n",
    "Dos enfoques para mantener un order book local:\n",
    "\n",
    "### Enfoque A: Partial Book Depth (simple)\n",
    "Stream `<symbol>@depth<levels>@100ms` con levels = 5, 10, 20.\n",
    "Envia snapshot completo del top N en cada update. Sin logica de sync.\n",
    "\n",
    "### Enfoque B: Diff Depth + REST Snapshot (completo)\n",
    "1. Abrir stream `<symbol>@depth@100ms` (diffs incrementales)\n",
    "2. Buffear eventos iniciales\n",
    "3. Pedir snapshot REST: `GET /api/v3/depth?symbol=X&limit=1000`\n",
    "4. Descartar eventos con `u <= lastUpdateId` del snapshot\n",
    "5. Primer evento procesado debe tener `U <= lastUpdateId+1` AND `u >= lastUpdateId+1`\n",
    "6. Aplicar: qty > 0 = update nivel, qty = 0 = eliminar nivel\n",
    "7. Validar continuidad: cada evento `U` == anterior `u + 1`, si no, re-sync\n",
    "\n",
    "### Campos del depth update\n",
    "```json\n",
    "{\n",
    "  \"U\": 157,  \"u\": 160,\n",
    "  \"b\": [[\"price\", \"qty\"], ...],  \n",
    "  \"a\": [[\"price\", \"qty\"], ...]   \n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23b19294",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import json\n",
    "import requests\n",
    "import websockets\n",
    "from decimal import Decimal\n",
    "from collections import deque\n",
    "import pandas as pd\n",
    "\n",
    "BASE = \"https://api.binance.com\"\n",
    "WS_BASE = \"wss://stream.binance.com:9443/ws\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cff459c9",
   "metadata": {},
   "source": [
    "## Enfoque A: Partial Book Depth (simple, sin sync)\n",
    "\n",
    "Stream `<symbol>@depth<levels>@100ms` — recibe snapshot completo del top N cada 100ms.\n",
    "\n",
    "Ideal para monitoreo rapido sin necesidad de mantener estado."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf70712b",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def stream_top_book(symbol: str, levels: int = 10, snapshots: int = 50) -> list[dict]:\n",
    "    \"\"\"Captura N snapshots del top del order book.\"\"\"\n",
    "    url = f\"{WS_BASE}/{symbol.lower()}@depth{levels}@100ms\"\n",
    "    results = []\n",
    "\n",
    "    async with websockets.connect(url) as ws:\n",
    "        while len(results) < snapshots:\n",
    "            data = json.loads(await ws.recv())\n",
    "            best_bid = (float(data[\"bids\"][0][0]), float(data[\"bids\"][0][1]))\n",
    "            best_ask = (float(data[\"asks\"][0][0]), float(data[\"asks\"][0][1]))\n",
    "            spread = best_ask[0] - best_bid[0]\n",
    "            mid = (best_bid[0] + best_ask[0]) / 2\n",
    "            results.append({\n",
    "                \"time\": pd.Timestamp.now(tz=\"UTC\"),\n",
    "                \"best_bid\": best_bid[0], \"bid_qty\": best_bid[1],\n",
    "                \"best_ask\": best_ask[0], \"ask_qty\": best_ask[1],\n",
    "                \"spread\": spread, \"spread_bps\": (spread / mid) * 10000,\n",
    "                \"bids\": [(float(p), float(q)) for p, q in data[\"bids\"]],\n",
    "                \"asks\": [(float(p), float(q)) for p, q in data[\"asks\"]],\n",
    "            })\n",
    "\n",
    "    return results"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
