### Install Dependencies and Initialize Configuration Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/README.md Prepare the environment by installing requirements and copying example configuration files. ```bash pip install -r requirements.txt cp config.example.json config.json cp .env.example .env ``` -------------------------------- ### Start the Main Bot Runtime Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Execute the main bot runtime programmatically using asyncio.run(run()). This initiates all core bot functionalities, including market refresh, position synchronization, price monitoring, and order dispatch. ```python # Run via command line # python -m bot.main # Or programmatically: import asyncio from bot.main import run # This starts the full runtime with: # - Market refresh loop (discovers new markets) # - Position sync loop (tracks open positions) # - Price monitoring loop (evaluates entry opportunities) # - Order dispatch loop (executes pending entries) # - Dashboard server (if PORT is set) # - Redeemer (if configured for live trading) # - Supervisor (restarts crashed tasks) asyncio.run(run()) ``` -------------------------------- ### Get Order Book and Balance Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Retrieves the order book for a given token ID and checks the USDC collateral balance using the Polymarket CLOB API client. ```python # Get order book for a token token_id = "71321045679252212594626385532706912750332728571942532289631379312455583992563" order_book = client.get_order_book(token_id) print(f"Best ask: {min(level.price for level in order_book.asks)}") print(f"Best bid: {max(level.price for level in order_book.bids)}") # Check collateral balance balance = client.get_collateral_balance() print(f"USDC balance: ${balance:.2f}") ``` -------------------------------- ### Set Dashboard Port Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Configure the dashboard port by setting the PORT environment variable before running the bot. This example shows how to set the port to 8080. ```bash # Set dashboard port export PORT=8080 ``` -------------------------------- ### Get Open Orders Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Retrieve a list of all currently open orders for a given token ID. Iterate through the list to display details of each order, such as order ID, side, size, and price. ```python # Get open orders open_orders = client.get_open_orders(token_id) for order in open_orders: print(f"Order {order.order_id}: {order.side} {order.original_size} @ {order.price}") ``` -------------------------------- ### Dashboard WebSocket Message Types Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Examples of messages received by a client connected to the dashboard's WebSocket endpoint. These include portfolio state, session P&L, trade events, and market resolutions. ```javascript // Client connects to ws://localhost:8080/ws and receives: // Portfolio state update { "type": "portfolio", "monitored_markets": 150, "eligible_markets": 45, "in_range_markets": 12, "cash_balance": 4500.50, "target_open_positions": 20, "pending_entry_count": 3, "remaining_position_capacity": 5, "positions": [ { "slug": "will-event-happen", "title": "Will this event happen?", "outcome": "No", "size": 100.5, "avg_price": 0.45, "current_price": 0.42, "pnl_usd": 3.15, "pnl_pct": 7.0, "end_date": "2024-12-31T23:59:59Z" } ] } // Session P&L update { "type": "session_pnl", "starting_balance": 5000.00, "current_balance": 5150.00, "pnl_usd": 150.00, "pnl_pct": 3.0 } // Trade event { "type": "bot_trade", "action": "buy", "market_slug": "will-event-happen", "side": "NO", "amount": 25.00, "reference_price": 0.45 } // Market resolution { "type": "resolution", "market_slug": "will-event-happen", "winner": "No" } ``` -------------------------------- ### Configure and Deploy to Heroku Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/README.md Set environment variables and push the application to Heroku. ```bash heroku config:set BOT_MODE=live DRY_RUN=false LIVE_TRADING_ENABLED=true -a "$HEROKU_APP_NAME" heroku config:set PRIVATE_KEY= FUNDER_ADDRESS= POLYGON_RPC_URL= DATABASE_URL= -a "$HEROKU_APP_NAME" git push heroku :main heroku ps:scale web=1 worker=0 -a "$HEROKU_APP_NAME" ``` -------------------------------- ### Initialize and Bootstrap PolymarketClobExchangeClient Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Initializes the Polymarket CLOB API client and bootstraps live trading by syncing balance and allowance. Requires exchange configuration. ```python from bot.config import load_nothing_happens_config from bot.exchange.polymarket_clob import PolymarketClobExchangeClient from bot.models import MarketOrderIntent, LimitOrderIntent, Side # Initialize client exchange_cfg, _ = load_nothing_happens_config() client = PolymarketClobExchangeClient(exchange_cfg, allow_trading=True) # Bootstrap live trading (syncs balance/allowance) client.bootstrap_live_trading() ``` -------------------------------- ### Initialize and Run Dashboard Server Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Initializes the DashboardServer with state objects and runs it. The exchange parameter is optional and used for live balance updates. ```python import asyncio from bot.dashboard import DashboardServer from bot.portfolio_state import PortfolioState from bot.nothing_happens_control import NothingHappensControlState # Create state objects portfolio_state = PortfolioState() control_state = NothingHappensControlState() # Initialize dashboard (exchange optional for balance polling) dashboard = DashboardServer( host="0.0.0.0", port=8080, exchange=None, # Pass exchange client for live balance updates portfolio_state=portfolio_state, nothing_happens_control=control_state ) # Run dashboard server asyncio.run(dashboard.run()) ``` -------------------------------- ### Run the Bot Locally Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/README.md Execute the bot runtime using the main module. ```bash python -m bot.main ``` -------------------------------- ### Configure and Use RiskController Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Initialize RiskConfig, optionally from environment variables or manually, to set exposure limits and drawdown parameters. Then, instantiate RiskController to manage trading risk, including seeding balance, checking trade allowance, recording trades, and monitoring for drawdowns. ```python import time from bot.risk_controls import RiskConfig, RiskController # Configure from environment or use defaults config = RiskConfig.from_env() # Or configure manually: config = RiskConfig( max_total_open_exposure_usd=1500.0, # Max total portfolio exposure max_market_open_exposure_usd=1000.0, # Max exposure per market max_daily_drawdown_usd=200.0, # Kill switch if balance drops $200 kill_switch_cooldown_sec=900.0, # 15 min cooldown after kill switch drawdown_arm_after_sec=1800.0, # 30 min before drawdown monitoring starts drawdown_min_fresh_observations=3 # Min observations before triggering ) risk = RiskController(config) now_us = int(time.time() * 1_000_000) # Seed the high-water mark at startup startup_balance = 5000.0 risk.seed_balance_hwm(now_us, startup_balance) # Check if a trade is allowed market_slug = "will-trump-win-2024" trade_notional = 50.0 allowed, reason = risk.can_open_trade(now_us, market_slug, trade_notional) if allowed: print("Trade allowed") else: print(f"Trade blocked: {reason}") # Record an opened position risk.on_open_trade(market_slug, trade_notional, now_us) print(f"Total exposure: ${risk.open_exposure_total_usd:.2f}") # Check balance for drawdown (call periodically) current_balance = 4850.0 risk.check_balance_drawdown(now_us, current_balance) if risk.kill_switch_active(now_us): print(f"KILL SWITCH ACTIVE: {risk.kill_switch_reason()}") else: print("Trading enabled") # Record position closure with P&L pnl_usd = 15.0 risk.on_close_trade(market_slug, trade_notional, pnl_usd, now_us) # Get risk state snapshot snapshot = risk.snapshot(now_us) print(f"Daily P&L: ${snapshot['daily_realized_pnl_usd']:.2f}") print(f"Open exposure: ${snapshot['open_exposure_total_usd']:.2f}") ``` -------------------------------- ### Manage Heroku Deployment Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/README.md Use shell helpers to manage the lifecycle of a deployed Heroku instance. ```bash export HEROKU_APP_NAME= ./alive.sh ./logs.sh ./live_enabled.sh ./live_disabled.sh ./kill.sh ``` -------------------------------- ### Initialize and Run Position Redeemer Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Initializes the Redeemer with wallet and chain details, then runs it as an async task. It periodically checks for resolved positions to redeem. ```python import asyncio import aiohttp from bot.redeemer import Redeemer # Initialize redeemer for proxy wallet redeemer = Redeemer( private_key="0x...", proxy_address="0x...", # Gnosis Safe proxy address chain_id=137, # Polygon mainnet rpc_url="https://polygon-rpc.com", check_interval_sec=1800 # Check every 30 minutes ) # Run as async task (integrates with main bot loop) async def main(): async with aiohttp.ClientSession() as session: redeemer._session = session await redeemer.run() # Runs forever, checking periodically asyncio.run(main()) ``` -------------------------------- ### Heroku Deployment and Management Commands Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Standard sequence for configuring environment variables, deploying code, and managing dyno operations on Heroku. ```bash # Set app name export HEROKU_APP_NAME=my-polymarket-bot # Configure environment heroku config:set \ BOT_MODE=live \ DRY_RUN=false \ LIVE_TRADING_ENABLED=true \ PRIVATE_KEY=0x... \ FUNDER_ADDRESS=0x... \ POLYGON_RPC_URL=https://... \ DATABASE_URL=postgresql://... \ -a "$HEROKU_APP_NAME" # Deploy git push heroku main:main # Scale (only web dyno) heroku ps:scale web=1 worker=0 -a "$HEROKU_APP_NAME" # Operational helpers ./alive.sh # Check if bot is running ./logs.sh # Stream logs ./live_enabled.sh # Enable live trading ./live_disabled.sh # Disable live trading ./kill.sh # Stop the dyno ``` -------------------------------- ### Environment Variables for Live Trading Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Lists the required environment variables for enabling live trading and configuring secrets and optional overrides for the bot. ```bash # Required for live trading (all three must be set) BOT_MODE=live DRY_RUN=false LIVE_TRADING_ENABLED=true # Secrets PRIVATE_KEY=0x... # Wallet private key FUNDER_ADDRESS=0x... # Proxy wallet address (for signature_type 1 or 2) DATABASE_URL=postgresql://... # PostgreSQL URL for recovery state POLYGON_RPC_URL=https://... # Polygon RPC for on-chain operations # Optional overrides CONFIG_PATH=config.json # Custom config file path LOG_LEVEL=INFO # Logging level PORT=8080 # Dashboard port PM_NH_MAX_ENTRY_PRICE=0.65 # Override max entry price PM_NH_CASH_PCT_PER_TRADE=0.02 # Override cash percentage ``` -------------------------------- ### Place a Limit Order Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Use LimitOrderIntent to specify order details like token ID, side, price, and size. Then, use the client to place the order. ```python limit_order = LimitOrderIntent( token_id=token_id, side=Side.BUY, price=0.40, size=25.0 # Number of shares ) result = client.place_limit_order(limit_order) ``` -------------------------------- ### Initialize Trade Ledger Database Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Initializes the PostgreSQL database connection for the trade ledger. Ensure the provided URL is correct. ```python from bot.trade_ledger import init_db, record_order # Initialize database connection init_db("postgresql://user:pass@localhost/botdb") ``` -------------------------------- ### Load Bot Configuration Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Loads exchange and strategy configuration from JSON and environment variables. Access configuration values for host, chain ID, live trading status, max entry price, cash percentage, and polling intervals. ```python from bot.config import load_nothing_happens_config # Load exchange and strategy configuration exchange_cfg, strategy_cfg = load_nothing_happens_config() # Access configuration values print(f"Host: {exchange_cfg.host}") print(f"Chain ID: {exchange_cfg.chain_id}") print(f"Live trading enabled: {exchange_cfg.live_send_enabled}") print(f"Max entry price: {strategy_cfg.max_entry_price}") print(f"Cash % per trade: {strategy_cfg.cash_pct_per_trade}") print(f"Price poll interval: {strategy_cfg.price_poll_interval_sec}s") ``` -------------------------------- ### Check Order Readiness Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Use check_order_readiness to determine if an order can be placed, checking for sufficient balance and allowance. The result indicates readiness and provides balance information or the reason for not being ready. ```python # Check order readiness (balance/allowance) readiness = client.check_order_readiness(order) if readiness.ready: print(f"Ready to trade. Balance: ${readiness.balance:.2f}") else: print(f"Not ready: {readiness.reason}") ``` -------------------------------- ### Discover Standalone Candidate Markets Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Fetch candidate markets using aiohttp, filtering for standalone, non-sports, binary yes/no markets within a specified end date. This is the recommended method for discovering eligible markets. ```python import asyncio import aiohttp from bot.standalone_markets import ( fetch_candidate_markets, fetch_all_open_markets, filter_standalone_markets, build_standalone_market ) async def discover_markets(): async with aiohttp.ClientSession() as session: # Fetch filtered standalone markets (recommended) markets = await fetch_candidate_markets( session, max_end_date_months=3 # Only markets ending within 3 months ) print(f"Found {len(markets)} eligible markets") for market in markets[:5]: print(f"\n{market.question}") print(f" Slug: {market.slug}") print(f" NO price: {market.no_price:.2f}") print(f" YES price: {market.yes_price:.2f}") print(f" Volume: ${market.volume:,.0f}") print(f" End date: {market.end_date}") print(f" NO token: {market.no_token_id}") # Alternative: fetch all markets and filter manually all_markets = await fetch_all_open_markets(session) standalone = filter_standalone_markets( all_markets, max_end_date_months=3 ) print(f"\nTotal open markets: {len(all_markets)}") print(f"Standalone eligible: {len(standalone)}") asyncio.run(discover_markets()) ``` -------------------------------- ### Run Database Statistics Script Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Executes a script to query trade events for performance analysis and debugging. Requires the DATABASE_URL environment variable to be set. ```bash # Set database URL export DATABASE_URL=postgresql://user:pass@localhost/botdb # Run stats script python scripts/db_stats.py ``` -------------------------------- ### Config JSON Structure Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Defines the structure of the config.json file, including connection settings and strategy parameters for the Nothing Ever Happens bot. ```json { "connection": { "host": "https://clob.polymarket.com", "chain_id": 137, "signature_type": 2 }, "strategies": { "nothing_happens": { "market_refresh_interval_sec": 600, "price_poll_interval_sec": 60, "position_sync_interval_sec": 60, "order_dispatch_interval_sec": 60, "cash_pct_per_trade": 0.02, "min_trade_amount": 5, "fixed_trade_amount": 0, "max_entry_price": 0.65, "allowed_slippage": 0.30, "request_concurrency": 4, "buy_retry_count": 3, "buy_retry_base_delay_sec": 1, "max_backoff_sec": 900, "max_new_positions": -1, "shutdown_on_max_new_positions": false, "redeemer_interval_sec": 1800 } } } ``` -------------------------------- ### Execute Unit and Regression Tests Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/README.md Run the test suite using pytest. ```bash python -m pytest -q ``` -------------------------------- ### Render portfolio dashboard in JavaScript Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/bot/static/dashboard.html Updates the portfolio dashboard UI, including balance, market status, and individual position rows. ```javascript function renderPortfolio(msg) { latestPortfolio = msg; const positions = sortPositions(msg.positions || []); const cashBalance = Number(msg.cash_balance || 0); const positionsValue = positions.reduce((sum, position) => sum + Number(position.current_value || 0), 0); const portfolioValue = (msg.cash_balance == null ? null : cashBalance + positionsValue); document.getElementById("monitored").textContent = String(msg.monitored_markets ?? "--"); document.getElementById("eligible").textContent = String(msg.eligible_markets ?? "--"); document.getElementById("in-range").textContent = String(msg.in_range_markets ?? "--"); document.getElementById("open-count").textContent = String(positions.length); document.getElementById("cash-balance").textContent = fmtUsd(msg.cash_balance); document.getElementById("portfolio-value").textContent = fmtUsd(portfolioValue); document.getElementById("portfolio-breakdown").textContent = "cash " + fmtUsd(msg.cash_balance) + " | positions " + fmtUsd(positionsValue); document.getElementById("last-error").textContent = msg.last_error ? String(msg.last_error) : "none"; document.getElementById("last-market-refresh").textContent = "market refresh " + fmtAgo(msg.last_market_refresh_ts); document.getElementById("last-position-sync").textContent = "position sync " + fmtAgo(msg.last_position_sync_ts); document.getElementById("last-price-cycle").textContent = "price cycle " + fmtAgo(msg.last_price_cycle_ts); document.getElementById("positions-note").textContent = positions.length ? "sorted by " + (document.querySelector("th[data-sort='" + sortColumn + "']")?.textContent || sortColumn) : "No open positions right now"; updateSortIndicators(); renderTargetControls(msg); positionsBody.innerHTML = ""; if (positions.length === 0) { positionsBody.innerHTML = 'No open positions'; return; } for (const position of positions) { const tr = document.createElement("tr"); const marketCell = document.createElement("td"); const link = document.createElement("a"); link.className = "market-link"; link.href = "https://polymarket.com/event/" + position.slug; link.target = "_blank"; link.rel = "noreferrer"; link.innerHTML = ''; link.querySelector(".market-name").textContent = position.title || position.slug; link.querySelector(".market-slug").textContent = position.slug; marketCell.appendChild(link); const sideCell = document.createElement("td"); sideCell.innerHTML = ''; sideCell.querySelector(".outcome-pill").textContent = position.outcome || "--"; const sizeCell = document.createElement("td"); sizeCell.className = "mono"; sizeCell.textContent = fmtShares(position.size); const avgCell = document.createElement("td"); avgCell.className = "mono"; avgCell.textContent = fmtUsd(position.avg_price, 4); const curCell = document.createElement("td"); curCell.className = "mono"; curCell.textContent = fmtUsd(position.current_price, 4); const valueCell = document.createElement("td"); valueCell.className = "mono"; valueCell.textContent = fmtUsd(position.current_value); const pnlCell = document.createElement("td"); pnlCell.innerHTML = '
'; pnlCell.firstChild.textContent = fmtUsd(position.pnl_usd); pnlCell.lastChild.textContent = fmtPct(position.pnl_pct); pnlCell.firstChild.className = Number(position.pnl_usd || 0) >= 0 ? "positive mono" : "negative mono"; pnlCell.lastChild.className = Number(position.pnl_pct || 0) >= 0 ? "trade-meta positive" : "trade-meta negative"; const potWinCell = document.createElement("td"); const potWin = Number(position.size || 0) - Number(position.initial_value || 0); potWinCell.innerHTML = '
'; potWinCell.firstChild.textContent = fmtUsd(potWin); potWinCell.firstChild.className = potWin >= 0 ? "positive mono" : "negative mono"; const potWinPct = Number(position.initial_value || 0) > 0 ? (potWin / Number(position.initial_value) * 100) : 0; potWinCell.lastChild.textContent = fmtPct(potWinPct); potWinCell.lastChild.className = potWinPct >= 0 ? "trade-meta positive" : "trade-meta negative"; const etaCell = document.createElement("td"); etaCell.innerHTML = '
'; etaCell.firstChild.textContent = fmtEta(position.eta_seconds); etaCell. ``` -------------------------------- ### Place Market Order Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Places a market buy order on Polymarket using the provided token ID, amount, reference price, allowed slippage, and price cap. Returns the order ID, status, and fill price. ```python # Place a market buy order order = MarketOrderIntent( token_id=token_id, side=Side.BUY, amount=10.0, # USDC amount to spend reference_price=0.45, # Expected price allowed_slippage=0.30, # Max slippage tolerance price_cap=0.65 # Maximum acceptable price ) result = client.place_market_order(order) print(f"Order ID: {result.order_id}") print(f"Status: {result.status}") print(f"Fill price: {result.raw.get('_fill_price')}") ``` -------------------------------- ### Manage UI Updates and WebSocket Communication Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/bot/static/dashboard.html Handles incoming WebSocket messages to update the portfolio, trade history, and session PNL. Includes logic for theme toggling and WebSocket reconnection. ```javascript lastChild.textContent = position.end_date || "--"; tr.append(marketCell, sideCell, sizeCell, avgCell, curCell, valueCell, pnlCell, potWinCell, etaCell); positionsBody.appendChild(tr); } } function tradeStatus(msg) { if (msg.error) return msg.error; if (msg.order_status) return msg.order_status; return "--"; } function addTrade(msg) { if (tradesBody.querySelector(".empty")) tradesBody.innerHTML = ""; const div = document.createElement("div"); div.className = "trade-item"; const top = document.createElement("div"); top.className = "trade-top"; const action = document.createElement("div"); const actionText = String(msg.action || "--"); action.className = "trade-action " + ( actionText === "buy" ? "positive" : actionText === "error" ? "negative" : "" ); action.textContent = actionText; const timeEl = document.createElement("div"); timeEl.className = "trade-meta mono"; timeEl.textContent = fmtTime(msg.ts); top.append(action, timeEl); const meta = document.createElement("div"); meta.className = "trade-meta"; meta.textContent = (msg.side || "--") + " | " + (msg.market_slug || "--"); const detail = document.createElement("div"); detail.className = "trade-detail"; detail.innerHTML = "Amount: " + fmtUsd(msg.amount) + " Price: " + fmtUsd(msg.reference_price, 4) + " Status: " + tradeStatus(msg); div.append(top, meta, detail); tradesBody.prepend(div); tradeItems.unshift(div); while (tradeItems.length > 120) { const item = tradeItems.pop(); if (item) item.remove(); } } function renderSessionPnl(msg) { const pnlEl = document.getElementById("session-pnl"); const balEl = document.getElementById("session-balance"); const pnl = Number(msg.pnl_usd || 0); const sign = pnl >= 0 ? "+" : ""; pnlEl.textContent = sign + fmtUsd(pnl).replace("$", "$"); pnlEl.className = "value " + (pnl >= 0 ? "positive" : "negative"); balEl.textContent = "balance " + fmtUsd(msg.current_balance); } function handleMessage(msg) { switch (msg.type) { case "portfolio": renderPortfolio(msg); break; case "bot_trade": addTrade(msg); break; case "session_pnl": renderSessionPnl(msg); break; case "control_ack": if (!msg.ok) { document.getElementById("target-status").textContent = "Update failed: " + (msg.error || "unknown_error"); } break; } } function syncThemeToggle() { const root = document.documentElement; const dark = root.dataset.theme === "dark"; themeToggle.textContent = dark ? "☀️" : "🌙"; themeToggle.title = dark ? "Switch to light theme" : "Switch to dark theme"; themeToggle.setAttribute("aria-label", themeToggle.title); } let ws; let reconnectDelay = 1000; function connect() { const proto = location.protocol === "https:" ? "wss:" : "ws:"; ws = new WebSocket(proto + "//" + location.host + "/ws"); ws.onopen = () => { socketEl.textContent = "socket: connected"; socketEl.className = "socket connected"; reconnectDelay = 1000; }; ws.onclose = () => { socketEl.textContent = "socket: disconnected"; socketEl.className = "socket disconnected"; setTimeout(connect, reconnectDelay); reconnectDelay = Math.min(reconnectDelay * 1.5, 10000); }; ws.onerror = () => ws.close(); ws.onmessage = (event) => { try { handleMessage(JSON.parse(event.data)); } catch (_) { } }; } themeToggle.addEventListener("click", () => { const root = document.documentElement; root.dataset.theme = root.dataset.theme === "dark" ? "light" : "dark"; syncThemeToggle(); }); document.querySelectorAll("th[data-sort]").forEach(th => { th.addEventListener("click", () => { const col = th.dataset.sort; if (sortColumn === col) { sortDirection = sortDirection === "asc" ? "desc" : "asc"; } else { sortDirection = (col === "title" || col === "outcome") ? "asc" : "desc"; } if (latestPortfolio) renderPortfolio(latestPortfolio); }); }); syncThemeToggle(); updateSortIndicators(); connect(); ``` -------------------------------- ### Dashboard JavaScript Logic Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/bot/static/dashboard.html Contains formatting utilities for financial data and sorting logic for portfolio positions. ```javascript "use strict"; const socketEl = document.getElementById("socket"); const tradesBody = document.getElementById("trades-body"); const positionsBody = document.getElementById("positions-body"); const themeToggle = document.getElementById("theme-toggle"); const tradeItems = []; let latestPortfolio = null; let sortColumn = "eta_seconds"; let sortDirection = "asc"; function fmtUsd(value, digits = 2) { if (value == null || Number.isNaN(Number(value))) return "--"; return "$" + Number(value).toLocaleString("en-US", { minimumFractionDigits: digits, maximumFractionDigits: digits, }); } function fmtPct(value) { if (value == null || Number.isNaN(Number(value))) return "--"; const num = Number(value); const sign = num >= 0 ? "+" : ""; return sign + num.toFixed(2) + "%"; } function fmtShares(value) { if (value == null || Number.isNaN(Number(value))) return "--"; return Number(value).toLocaleString("en-US", { maximumFractionDigits: 4 }); } function fmtTime(epochSec) { if (!epochSec) return "--"; const d = new Date(epochSec * 1000); return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }); } function fmtEta(seconds) { const remaining = Math.max(0, Math.floor(Number(seconds || 0))); const days = Math.floor(remaining / 86400); const hours = Math.floor((remaining % 86400) / 3600); const minutes = Math.floor((remaining % 3600) / 60); if (days > 0) return days + "d " + hours + "h"; if (hours > 0) return hours + "h " + minutes + "m"; return minutes + "m"; } function fmtAgo(tsSec) { if (!tsSec) return "--"; const delta = Math.max(0, Math.floor(Date.now() / 1000 - tsSec)); if (delta < 60) return delta + "s ago"; if (delta < 3600) return Math.floor(delta / 60) + "m ago"; return Math.floor(delta / 3600) + "h ago"; } function fmtTarget(value) { return value == null ? "Unlimited" : String(value); } function sortValue(position, col) { if (col === "title") return (position.title || position.slug || "").toLowerCase(); if (col === "outcome") return (position.outcome || "").toLowerCase(); if (col === "pot_win") return Number(position.size || 0) - Number(position.initial_value || 0); return Number(position[col] || 0); } function sortPositions(positions) { return positions.slice().sort((a, b) => { const va = sortValue(a, sortColumn); const vb = sortValue(b, sortColumn); let cmp = 0; if (typeof va === "string") cmp = va.localeCompare(vb); else cmp = va - vb; return sortDirection === "desc" ? -cmp : cmp; }); } function updateSortIndicators() { document.querySelectorAll("th[data-sort]").forEach(th => { th.classList.remove("sort-asc", "sort-desc"); if (th.dataset.sort === sortColumn) { th.classList.add(sortDirection === "asc" ? "sort-asc" : "sort-desc"); } }); } ``` -------------------------------- ### Query Wallet History Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Queries wallet positions and trades using the provided wallet address. ```bash # Query wallet positions and trades python scripts/wallet_history.py --wallet 0x... ``` -------------------------------- ### Render target controls in JavaScript Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/bot/static/dashboard.html Updates the target-meta element with current position counts, pending entries, and capacity metrics. ```javascript function renderTargetControls(msg) { const openCount = (msg.positions || []).length; const pendingCount = Number(msg.pending_entry_count || 0); const remaining = msg.remaining_position_capacity; const target = msg.target_open_positions; const openedThisRun = Number(msg.opened_this_run || 0); document.getElementById("target-meta").textContent = "Open " + openCount + " | Pending " + pendingCount + " | Remaining " + (remaining == null ? "unlimited" : String(remaining)) + " | Target " + fmtTarget(target) + " | Opened " + openedThisRun; } ``` -------------------------------- ### Generate HTML Report Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Redirects the output of the logshtml script to a local report file. ```bash ./logshtml.sh > report.html ``` -------------------------------- ### Export Database Tables Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Exports database tables to timestamped CSV files. Can export from a local DATABASE_URL or a Heroku application. ```bash # Export from DATABASE_URL python scripts/export_db.py # Export from Heroku app python scripts/export_db.py --app my-heroku-app ``` -------------------------------- ### Record Trade Events in Ledger Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Records various trade-related events, including attempts, successful fills, errors, and redemptions, into the trade ledger. Requires the database to be initialized. ```python # Record a buy attempt record_order( action="attempt", market_slug="will-event-happen", side="NO", token_id="71321045679252212594626385532706912750332728571942532289631379312455583992563", amount=25.0, reference_price=0.45, question="Will this event happen?" ) # Record a successful fill record_order( action="buy", market_slug="will-event-happen", side="NO", token_id="71321045679252212594626385532706912750332728571942532289631379312455583992563", amount=24.75, reference_price=0.45, order_id="abc123", order_status="matched", shares=55.0 ) # Record an error record_order( action="error", market_slug="will-event-happen", side="NO", token_id="...", amount=25.0, reference_price=0.45, error="Insufficient balance" ) # Record redemption record_order( action="redeem", market_slug="will-event-happen", side="", token_id="condition_id_here", amount=55.0 ) ``` -------------------------------- ### Parse Heroku Logs Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Converts JSON logs from Heroku to a more readable format using a shell script and a Python parser. ```bash # Convert JSON logs to readable format ./logs.sh | python scripts/parse_logs.py ``` -------------------------------- ### Dashboard CSS Styles Source: https://github.com/sterlingcrispin/nothing-ever-happens/blob/main/bot/static/dashboard.html Defines the layout, typography, and responsive behavior for the dashboard interface. ```css l { display: inline-flex; align-items: center; border-radius: 999px; padding: 4px 8px; font-size: 0.76rem; font-weight: 700; background: var(--accent-soft); color: var(--accent); } .mono { font-family: ui-monospace, monospace; } .positive { color: var(--green); } .negative { color: var(--red); } .trade-list { display: flex; flex-direction: column; gap: 10px; max-height: 72vh; overflow: auto; } .trade-item { border: 1px solid var(--border); background: var(--surface-strong); border-radius: 14px; padding: 12px; } .trade-top { display: flex; justify-content: space-between; gap: 12px; margin-bottom: 8px; } .trade-action { font-weight: 700; } .trade-meta, .trade-detail { color: var(--muted); font-size: 0.82rem; line-height: 1.45; } .trade-detail strong { color: var(--text); } .empty { color: var(--muted); font-style: italic; padding: 18px 4px 6px; } th[data-sort] { cursor: pointer; user-select: none; white-space: nowrap; } th[data-sort]:hover { color: var(--accent); } th[data-sort]::after { content: ""; display: inline-block; margin-left: 4px; width: 0; } th[data-sort].sort-asc::after { content: "\25B2"; } th[data-sort].sort-desc::after { content: "\25BC"; } @media (max-width: 1080px) { .summary-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } .layout { grid-template-columns: 1fr; } } @media (max-width: 700px) { .shell { padding: 16px 12px 24px; } .header { flex-direction: column; } .header-actions { width: 100%; justify-content: space-between; } .summary-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .control-row { flex-direction: column; align-items: stretch; } } ``` -------------------------------- ### Cancel an Order Source: https://context7.com/sterlingcrispin/nothing-ever-happens/llms.txt Cancel an existing order by providing its unique order ID. ```python # Cancel an order client.cancel_order(order_id="abc123") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.