### Install Dependencies Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Run this command in the project directory to install all necessary Node.js dependencies. ```bash npm install ``` -------------------------------- ### Run the Assistant Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Start the Polymarket BTC 15m Assistant by running this command in the project's terminal. ```bash npm start ``` -------------------------------- ### Start Binance Trade Stream Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Establishes a WebSocket connection for real-time price updates with automatic reconnection. ```javascript import { startBinanceTradeStream } from "./src/data/binanceWs.js"; // Start the stream with optional callback const stream = startBinanceTradeStream({ symbol: "BTCUSDT", onUpdate: ({ price, ts }) => { console.log(`Price: $${price} at ${new Date(ts).toISOString()}`); } }); // Poll for latest price const { price, ts } = stream.getLast(); // Returns: { price: 43265.75, ts: 1699999200000 } // Clean up when done stream.close(); ``` -------------------------------- ### Set HTTPS Proxy (CMD) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Configure an HTTP(S) proxy for the assistant using Command Prompt. This example sets a local proxy on port 8080. ```cmd set HTTPS_PROXY=http://127.0.0.1:8080 REM or set ALL_PROXY=socks5://127.0.0.1:1080 ``` -------------------------------- ### Start Chainlink WebSocket Stream Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Subscribes to Chainlink AnswerUpdated events via Polygon WebSocket RPC. ```javascript import { startChainlinkPriceStream } from "./src/data/chainlinkWs.js"; const stream = startChainlinkPriceStream({ aggregator: "0xc907E116054Ad103354f2D350FD2514433D57F6f", // BTC/USD decimals: 8, onUpdate: ({ price, updatedAt, source }) => { console.log(`Chainlink: $${price}`); } }); const { price, updatedAt, source } = stream.getLast(); // Returns: { price: 43265.50, updatedAt: 1699999200000, source: "chainlink_ws" } stream.close(); ``` -------------------------------- ### Start Polymarket Chainlink Price Stream Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Connects to Polymarket's live data WebSocket for settlement price updates. ```javascript import { startPolymarketChainlinkPriceStream } from "./src/data/polymarketLiveWs.js"; const stream = startPolymarketChainlinkPriceStream({ wsUrl: "wss://ws-live-data.polymarket.com", symbolIncludes: "btc", onUpdate: ({ price, updatedAt, source }) => { console.log(`Polymarket Chainlink: $${price}`); } }); const { price, updatedAt, source } = stream.getLast(); // Returns: { price: 43265.50, updatedAt: 1699999200000, source: "polymarket_ws" } stream.close(); ``` -------------------------------- ### Start Binance Trade Stream Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Establishes a WebSocket connection to Binance's real-time trade stream for continuous price updates. Features automatic reconnection. ```APIDOC ## WebSocket /stream/binance/trade ### Description Establishes a WebSocket connection to Binance's real-time trade stream for continuous price updates. Features automatic reconnection with exponential backoff. ### Method WebSocket ### Endpoint /stream/binance/trade ### Query Parameters - **symbol** (string) - Optional - The trading pair symbol (e.g., "BTCUSDT"). Defaults to "BTCUSDT". ### Callbacks - **onUpdate** (function) - Callback function executed when a new trade is received. Receives an object with: - **price** (number) - The trade price. - **ts** (integer) - The timestamp of the trade. ### Request Example ```javascript import { startBinanceTradeStream } from "./src/data/binanceWs.js"; const stream = startBinanceTradeStream({ symbol: "BTCUSDT", onUpdate: ({ price, ts }) => { console.log(`Price: $${price} at ${new Date(ts).toISOString()}`); } }); // To get the last received trade data: const { price, ts } = stream.getLast(); // To close the stream: stream.close(); ``` ### Response Example (for getLast) ```json { "price": 43265.75, "ts": 1699999200000 } ``` ``` -------------------------------- ### Start Chainlink WebSocket Stream Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Subscribes to Chainlink AnswerUpdated events via Polygon WebSocket RPC for real-time oracle price updates. ```APIDOC ## WebSocket /stream/chainlink/price ### Description Subscribes to Chainlink AnswerUpdated events via Polygon WebSocket RPC for real-time oracle price updates. Automatically handles reconnection and RPC endpoint rotation. ### Method WebSocket ### Endpoint /stream/chainlink/price ### Query Parameters - **aggregator** (string) - Required - The aggregator contract address for the desired price feed (e.g., "0xc907E116054Ad103354f2D350FD2514433D57F6f" for BTC/USD). - **decimals** (integer) - Required - The number of decimal places for the oracle price. ### Callbacks - **onUpdate** (function) - Callback function executed when a new price update is received. Receives an object with: - **price** (number) - The updated price. - **updatedAt** (integer) - Unix timestamp in milliseconds of the update. - **source** (string) - The source of the price data (e.g., "chainlink_ws"). ### Request Example ```javascript import { startChainlinkPriceStream } from "./src/data/chainlinkWs.js"; const stream = startChainlinkPriceStream({ aggregator: "0xc907E116054Ad103354f2D350FD2514433D57F6f", // BTC/USD decimals: 8, onUpdate: ({ price, updatedAt, source }) => { console.log(`Chainlink: $${price}`); } }); // To get the last received price data: const { price, updatedAt, source } = stream.getLast(); // To close the stream: stream.close(); ``` ### Response Example (for getLast) ```json { "price": 43265.50, "updatedAt": 1699999200000, "source": "chainlink_ws" } ``` ``` -------------------------------- ### Update to Latest Version Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Commands to update the assistant to the latest version from the Git repository, including pulling changes, installing new dependencies, and restarting the assistant. ```bash git pull npm install npm start ``` -------------------------------- ### Start Polymarket Chainlink Price Stream Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Connects to Polymarket's live data WebSocket to receive the Chainlink BTC/USD feed displayed on their UI. ```APIDOC ## WebSocket /stream/polymarket/chainlink-price ### Description Connects to Polymarket's live data WebSocket to receive the same Chainlink BTC/USD feed displayed on their UI. This is the primary price source used for determining market settlement. ### Method WebSocket ### Endpoint /stream/polymarket/chainlink-price ### Query Parameters - **wsUrl** (string) - Required - The WebSocket URL for Polymarket's live data (e.g., "wss://ws-live-data.polymarket.com"). - **symbolIncludes** (string) - Optional - A string to filter market symbols (e.g., "btc"). ### Callbacks - **onUpdate** (function) - Callback function executed when a new price update is received. Receives an object with: - **price** (number) - The updated price. - **updatedAt** (integer) - Unix timestamp in milliseconds of the update. - **source** (string) - The source of the price data (e.g., "polymarket_ws"). ### Request Example ```javascript import { startPolymarketChainlinkPriceStream } from "./src/data/polymarketLiveWs.js"; const stream = startPolymarketChainlinkPriceStream({ wsUrl: "wss://ws-live-data.polymarket.com", symbolIncludes: "btc", onUpdate: ({ price, updatedAt, source }) => { console.log(`Polymarket Chainlink: $${price}`); } }); // To get the last received price data: const { price, updatedAt, source } = stream.getLast(); // To close the stream: stream.close(); ``` ### Response Example (for getLast) ```json { "price": 43265.50, "updatedAt": 1699999200000, "source": "polymarket_ws" } ``` ``` -------------------------------- ### Set HTTPS Proxy (PowerShell) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Configure an HTTP(S) proxy for the assistant using PowerShell. This example sets a local proxy on port 8080. ```powershell $env:HTTPS_PROXY = "http://127.0.0.1:8080" # or $env:ALL_PROXY = "socks5://127.0.0.1:1080" ``` -------------------------------- ### Pick Latest Live Market Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Selects the most relevant market from a list - preferring currently live markets (started but not ended) over upcoming ones, sorted by end time. ```APIDOC ## Pick Latest Live Market ### Description Selects the most relevant market from a list - preferring currently live markets (started but not ended) over upcoming ones, sorted by end time. ### Method N/A (This is a client-side utility function) ### Endpoint N/A ### Parameters #### Request Body (Implicitly, the list of markets) - **markets** (array) - Required - A list of market objects, typically obtained from `fetchLiveEventsBySeriesId` and `flattenEventMarkets`. ### Request Example ```javascript import { pickLatestLiveMarket, flattenEventMarkets, fetchLiveEventsBySeriesId } from "./src/data/polymarket.js"; const events = await fetchLiveEventsBySeriesId({ seriesId: "10192", limit: 25 }); const markets = flattenEventMarkets(events); const currentMarket = pickLatestLiveMarket(markets); ``` ### Response #### Success Response - **market** (object) - The selected market object that is currently live or the next upcoming one. #### Response Example ```json { "slug": "btc-up-down-15m-jan-01-2024-12-00-pm-et", "question": "Will BTC go Up or Down? Price to Beat: $43,250", "outcomes": ["Up", "Down"], "endDate": "2024-01-01T17:15:00Z" } ``` ``` -------------------------------- ### Set Proxy with Username and Password (CMD) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Configure an HTTP(S) proxy with authentication using Command Prompt. Ensure special characters in the password are URL-encoded. ```cmd set HTTPS_PROXY=http://USERNAME:PASSWORD@HOST:PORT npm start ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Set these environment variables to configure market IDs, data sources, and network proxies. ```bash export POLYMARKET_AUTO_SELECT_LATEST=true # Auto-pick latest 15m market export POLYMARKET_SERIES_ID=10192 # BTC Up/Down 15m series ID export POLYMARKET_SERIES_SLUG=btc-up-or-down-15m # Series slug export POLYMARKET_SLUG= # Pin specific market (optional) export POLYMARKET_LIVE_WS_URL=wss://ws-live-data.polymarket.com # Chainlink on Polygon (fallback price source) export CHAINLINK_BTC_USD_AGGREGATOR=0xc907E116054Ad103354f2D350FD2514433D57F6f export POLYGON_RPC_URL=https://polygon-rpc.com export POLYGON_RPC_URLS=https://polygon-rpc.com,https://rpc.ankr.com/polygon export POLYGON_WSS_URLS=wss://polygon-bor-rpc.publicnode.com # Proxy Support (HTTP, HTTPS, SOCKS5) export HTTPS_PROXY=http://127.0.0.1:8080 export ALL_PROXY=socks5://user:pass@127.0.0.1:1080 # Run the assistant npm start ``` -------------------------------- ### Set Polymarket Environment Variables (CMD) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Optional Polymarket settings for automatic latest market selection or pinning a specific market slug, configured via Command Prompt. ```cmd set POLYMARKET_AUTO_SELECT_LATEST=true REM set POLYMARKET_SLUG=btc-updown-15m-... ``` -------------------------------- ### Clone the Repository Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Use this command to clone the project repository from GitHub. Alternatively, download the ZIP file if Git is not available. ```bash git clone https://github.com/FrondEnt/PolymarketBTC15mAssistant.git ``` -------------------------------- ### Configure Proxy Settings Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Use these functions to apply global proxy settings for fetch requests and WebSocket agents. ```javascript import { applyGlobalProxyFromEnv, getProxyUrlFor, wsAgentForUrl } from "./src/net/proxy.js"; // Apply proxy globally for all fetch requests (call once at startup) const applied = applyGlobalProxyFromEnv(); // Returns: true if proxy was configured // Get appropriate proxy URL for a target const proxy = getProxyUrlFor("https://api.binance.com"); // Returns: "http://127.0.0.1:8080" (from HTTPS_PROXY) // Get WebSocket agent for proxied connections import WebSocket from "ws"; const ws = new WebSocket("wss://stream.binance.com/ws", { agent: wsAgentForUrl("wss://stream.binance.com/ws") }); ``` -------------------------------- ### Utilize Timing and Formatting Helpers Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Helper functions for candle window calculations, number formatting, clamping, and CSV logging. ```javascript import { getCandleWindowTiming, formatNumber, formatPct, appendCsvRow, sleep, clamp } from "./src/utils.js"; // Get current 15-minute window timing const timing = getCandleWindowTiming(15); // Returns: { // startMs: 1699999200000, // endMs: 1700000100000, // elapsedMs: 300000, // remainingMs: 600000, // elapsedMinutes: 5.0, // remainingMinutes: 10.0 // } // Format numbers formatNumber(43265.789, 2); // "43,265.79" formatPct(0.0523, 2); // "5.23%" // Clamp values clamp(150, 0, 100); // 100 clamp(-5, 0, 100); // 0 // Async sleep await sleep(1000); // Wait 1 second // Append to CSV log appendCsvRow("./logs/signals.csv", ["timestamp", "signal", "price"], [new Date().toISOString(), "BUY UP", 43265] ); ``` -------------------------------- ### Set Polygon RPC Environment Variables (CMD) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Configure Polygon RPC URLs for fallback on Windows using Command Prompt. These variables apply to the current terminal session. ```cmd set POLYGON_RPC_URL=https://polygon-rpc.com set POLYGON_RPC_URLS=https://polygon-rpc.com,https://rpc.ankr.com/polygon set POLYGON_WSS_URLS=wss://polygon-bor-rpc.publicnode.com ``` -------------------------------- ### Set Polymarket Environment Variables (PowerShell) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Optional Polymarket settings for automatic latest market selection or pinning a specific market slug, configured via PowerShell. ```powershell $env:POLYMARKET_AUTO_SELECT_LATEST = "true" # $env:POLYMARKET_SLUG = "btc-updown-15m-..." # pin a specific market ``` -------------------------------- ### Set Proxy with Username and Password (PowerShell) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Configure an HTTP(S) proxy with authentication using PowerShell. Ensure special characters in the password are URL-encoded. ```powershell $env:HTTPS_PROXY = "http://USERNAME:PASSWORD@HOST:PORT" npm start ``` -------------------------------- ### Fetch Live Events by Series ID Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves active events for a given market series, useful for finding available 15-minute Bitcoin markets. Requires a series ID and an optional limit. ```javascript import { fetchLiveEventsBySeriesId, flattenEventMarkets } from "./src/data/polymarket.js"; const events = await fetchLiveEventsBySeriesId({ seriesId: "10192", // BTC Up or Down 15m series limit: 25 }); // Extract all markets from events const markets = flattenEventMarkets(events); // Returns: [{ slug, question, outcomes, endDate, ... }, ...] ``` -------------------------------- ### Fetch and Summarize Order Book Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves the full order book for a token and summarizes key metrics like best bid/ask, spread, and liquidity. Requires a token ID and the number of top levels to summarize. ```javascript import { fetchOrderBook, summarizeOrderBook } from "./src/data/polymarket.js"; const book = await fetchOrderBook({ tokenId: "12345..." }); const summary = summarizeOrderBook(book, 5); // Top 5 levels // Returns: { // bestBid: 0.51, // bestAsk: 0.53, // spread: 0.02, // bidLiquidity: 2500, // Sum of top 5 bid sizes // askLiquidity: 3200 // Sum of top 5 ask sizes // } ``` -------------------------------- ### Fetch Binance Last Price Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves the current spot price for a trading pair from Binance. ```javascript import { fetchLastPrice } from "./src/data/binance.js"; const spotPrice = await fetchLastPrice(); // Returns: 43265.75 ``` -------------------------------- ### Pick Latest Live Market Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Selects the most relevant market from a list, prioritizing live markets over upcoming ones and sorting by end time. Requires a list of markets. ```javascript import { pickLatestLiveMarket, flattenEventMarkets, fetchLiveEventsBySeriesId } from "./src/data/polymarket.js"; const events = await fetchLiveEventsBySeriesId({ seriesId: "10192", limit: 25 }); const markets = flattenEventMarkets(events); const currentMarket = pickLatestLiveMarket(markets); // Returns the market that is currently live, or the next upcoming one ``` -------------------------------- ### Fetch and Summarize Order Book Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves the full order book for a token and summarizes key metrics including best bid/ask, spread, and liquidity at top levels. ```APIDOC ## Fetch and Summarize Order Book ### Description Retrieves the full order book for a token and summarizes key metrics including best bid/ask, spread, and liquidity at top levels. ### Method GET (assumed, based on fetch operation) ### Endpoint /api/clob/orderbook (assumed, based on fetchOrderBook function) ### Parameters #### Query Parameters - **tokenId** (string) - Required - The unique identifier for the outcome token. ### Request Example ```javascript import { fetchOrderBook, summarizeOrderBook } from "./src/data/polymarket.js"; const book = await fetchOrderBook({ tokenId: "12345..." }); const summary = summarizeOrderBook(book, 5); // Top 5 levels ``` ### Response #### Success Response (200) - **summary** (object) - An object containing summarized order book metrics. - **bestBid** (number) - The highest bid price. - **bestAsk** (number) - The lowest ask price. - **spread** (number) - The difference between best bid and best ask. - **bidLiquidity** (number) - The total liquidity of the top N bids. - **askLiquidity** (number) - The total liquidity of the top N asks. #### Response Example ```json { "bestBid": 0.51, "bestAsk": 0.53, "spread": 0.02, "bidLiquidity": 2500, "askLiquidity": 3200 } ``` ``` -------------------------------- ### Set Polygon RPC Environment Variables (PowerShell) Source: https://github.com/frondent/polymarketbtc15massistant/blob/main/README.md Configure Polygon RPC URLs for fallback on Windows using PowerShell. These variables apply to the current terminal session. ```powershell $env:POLYGON_RPC_URL = "https://polygon-rpc.com" $env:POLYGON_RPC_URLS = "https://polygon-rpc.com,https://rpc.ankr.com/polygon" $env:POLYGON_WSS_URLS = "wss://polygon-bor-rpc.publicnode.com" ``` -------------------------------- ### Fetch Binance Last Price Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Fetches the current spot price for a trading pair from Binance's ticker endpoint. ```APIDOC ## GET /api/binance/last-price ### Description Fetches the current spot price for a trading pair from Binance's ticker endpoint. ### Method GET ### Endpoint /api/binance/last-price ### Query Parameters - **symbol** (string) - Optional - The trading pair symbol (e.g., "BTCUSDT"). Defaults to "BTCUSDT". ### Response #### Success Response (200) - **price** (number) - The current spot price. ### Request Example ```javascript import { fetchLastPrice } from "./src/data/binance.js"; const spotPrice = await fetchLastPrice(); ``` ### Response Example ```json { "price": 43265.75 } ``` ``` -------------------------------- ### Fetch Chainlink BTC/USD Price Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Fetches BTC/USD price from Chainlink oracle on Polygon via JSON-RPC. ```javascript import { fetchChainlinkBtcUsd } from "./src/data/chainlink.js"; const result = await fetchChainlinkBtcUsd(); // Returns: { // price: 43265.50, // updatedAt: 1699999200000, // Unix timestamp in ms // source: "chainlink" // } // On error or missing config: // Returns: { price: null, updatedAt: null, source: "missing_config" } ``` -------------------------------- ### Fetch Market by Slug Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves a specific Polymarket market using its unique slug. Returns the full market object including outcomes, prices, and metadata. ```javascript import { fetchMarketBySlug } from "./src/data/polymarket.js"; const market = await fetchMarketBySlug("btc-up-down-15m-jan-01-2024-12-00-pm-et"); // Returns: { // slug: "btc-up-down-15m-jan-01-2024-12-00-pm-et", // question: "Will BTC go Up or Down? Price to Beat: $43,250", // outcomes: ["Up", "Down"], // outcomePrices: ["0.52", "0.48"], // clobTokenIds: ["123...", "456..."], // endDate: "2024-01-01T17:15:00Z", // liquidity: "5000", // ... // } ``` -------------------------------- ### Fetch Market by Slug Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves a specific Polymarket market by its unique slug identifier. Returns the full market object with outcomes, prices, and metadata. ```APIDOC ## Fetch Market by Slug ### Description Retrieves a specific Polymarket market by its unique slug identifier from the Gamma API. Returns the full market object with outcomes, prices, and metadata. ### Method GET (assumed, based on fetch operation) ### Endpoint /api/markets/{slug} (assumed, based on fetchMarketBySlug function) ### Parameters #### Path Parameters - **slug** (string) - Required - The unique slug identifier for the market. ### Request Example ```javascript import { fetchMarketBySlug } from "./src/data/polymarket.js"; const market = await fetchMarketBySlug("btc-up-down-15m-jan-01-2024-12-00-pm-et"); ``` ### Response #### Success Response (200) - **slug** (string) - The market's slug. - **question** (string) - The market's question. - **outcomes** (array) - An array of possible outcomes. - **outcomePrices** (array) - An array of current prices for each outcome. - **clobTokenIds** (array) - Array of CLOB token IDs for each outcome. - **endDate** (string) - The market's end date and time. - **liquidity** (string) - The total liquidity of the market. #### Response Example ```json { "slug": "btc-up-down-15m-jan-01-2024-12-00-pm-et", "question": "Will BTC go Up or Down? Price to Beat: $43,250", "outcomes": ["Up", "Down"], "outcomePrices": ["0.52", "0.48"], "clobTokenIds": ["123...", "456..."], "endDate": "2024-01-01T17:15:00Z", "liquidity": "5000" } ``` ``` -------------------------------- ### Fetch Live Events by Series ID Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves all active (non-closed) events for a specific market series, used to find available 15-minute Bitcoin markets. ```APIDOC ## Fetch Live Events by Series ID ### Description Retrieves all active (non-closed) events for a specific market series, used to find available 15-minute Bitcoin markets. ### Method GET (assumed, based on fetch operation) ### Endpoint /api/events?seriesId={seriesId}&limit={limit} (assumed, based on fetchLiveEventsBySeriesId function) ### Parameters #### Query Parameters - **seriesId** (string) - Required - The ID of the market series. - **limit** (integer) - Optional - The maximum number of events to retrieve. ### Request Example ```javascript import { fetchLiveEventsBySeriesId, flattenEventMarkets } from "./src/data/polymarket.js"; const events = await fetchLiveEventsBySeriesId({ seriesId: "10192", // BTC Up or Down 15m series limit: 25 }); const markets = flattenEventMarkets(events); ``` ### Response #### Success Response (200) - **events** (array) - An array of live event objects. - Each event object may contain market details like slug, question, outcomes, and endDate. #### Response Example ```json [ { "slug": "btc-up-down-15m-jan-01-2024-12-00-pm-et", "question": "Will BTC go Up or Down? Price to Beat: $43,250", "outcomes": ["Up", "Down"], "endDate": "2024-01-01T17:15:00Z" } // ... more events ] ``` ``` -------------------------------- ### Fetch Chainlink BTC/USD Price Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Fetches the BTC/USD price from Chainlink's price oracle on Polygon via JSON-RPC calls. ```APIDOC ## GET /api/chainlink/btc-usd ### Description Fetches the BTC/USD price from Chainlink's price oracle on Polygon via JSON-RPC calls. Automatically rotates through configured RPC endpoints on failure and caches results. ### Method GET ### Endpoint /api/chainlink/btc-usd ### Response #### Success Response (200) - **result** (object) - Contains the price information: - **price** (number | null) - The BTC/USD price, or null if unavailable. - **updatedAt** (integer | null) - Unix timestamp in milliseconds of the last update, or null. - **source** (string) - The source of the price data (e.g., "chainlink"). ### Request Example ```javascript import { fetchChainlinkBtcUsd } from "./src/data/chainlink.js"; const result = await fetchChainlinkBtcUsd(); ``` ### Response Example ```json { "result": { "price": 43265.50, "updatedAt": 1699999200000, "source": "chainlink" } } ``` ### Error Response Example ```json { "result": { "price": null, "updatedAt": null, "source": "missing_config" } } ``` ``` -------------------------------- ### Detect Market Regime Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Classifies the current market state to inform trading strategy adjustments. ```javascript import { detectRegime } from "./src/engines/regime.js"; const regime = detectRegime({ price: 43280, vwap: 43250, vwapSlope: 1.5, vwapCrossCount: 1, volumeRecent: 1500, volumeAvg: 1200 }); // Returns: { regime: "TREND_UP", reason: "price_above_vwap_slope_up" } // Possible regimes: // "TREND_UP" - Clear upward trend // "TREND_DOWN" - Clear downward trend // "RANGE" - Sideways/ranging market // "CHOP" - Low volume, no clear direction ``` -------------------------------- ### Fetch CLOB Price Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Fetches the current best buy price for a specific outcome token from Polymarket's CLOB. Requires the token ID and the side ('buy'). ```javascript import { fetchClobPrice } from "./src/data/polymarket.js"; // Get buy price for UP outcome const upBuyPrice = await fetchClobPrice({ tokenId: "12345...", // UP token ID from market.clobTokenIds side: "buy" }); // Returns: 0.52 (52 cents) // Get buy price for DOWN outcome const downBuyPrice = await fetchClobPrice({ tokenId: "67890...", // DOWN token ID side: "buy" }); // Returns: 0.48 (48 cents) ``` -------------------------------- ### Fetch Binance Klines Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves historical OHLCV candlestick data from Binance for technical analysis. ```javascript import { fetchKlines } from "./src/data/binance.js"; // Fetch 240 1-minute candles for BTC/USDT const candles1m = await fetchKlines({ interval: "1m", limit: 240 }); // Returns: [{ openTime, open, high, low, close, volume, closeTime }, ...] // Fetch 200 5-minute candles const candles5m = await fetchKlines({ interval: "5m", limit: 200 }); // Example candle object: // { // openTime: 1699999200000, // open: 43250.50, // high: 43280.00, // low: 43240.00, // close: 43265.75, // volume: 125.34, // closeTime: 1699999259999 // } ``` -------------------------------- ### Apply Time Awareness to Probability Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Adjusts raw probability scores based on the remaining time in the market window, causing decay toward 50/50. ```javascript import { applyTimeAwareness } from "./src/engines/probability.js"; const timeAware = applyTimeAwareness( 0.786, // rawUp probability 8, // remaining minutes 15 // total window minutes ); // Returns: { // timeDecay: 0.533, // Time remaining ratio // adjustedUp: 0.652, // Decayed UP probability // adjustedDown: 0.348 // Decayed DOWN probability // } ``` -------------------------------- ### Compute VWAP Indicators Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Calculates session VWAP and rolling series to determine price trends and slopes. ```javascript import { computeSessionVwap, computeVwapSeries } from "./src/indicators/vwap.js"; const candles = [ { high: 43280, low: 43200, close: 43250, volume: 100 }, { high: 43300, low: 43240, close: 43280, volume: 150 }, // ... ]; // Session VWAP const vwap = computeSessionVwap(candles); // Returns: 43265.75 // Rolling VWAP series for slope calculation const vwapSeries = computeVwapSeries(candles); // Returns: [43250, 43258.5, 43265.75, ...] // Calculate VWAP slope const lookback = 5; const vwapSlope = (vwapSeries[vwapSeries.length - 1] - vwapSeries[vwapSeries.length - lookback]) / lookback; // Returns: 2.5 (positive = VWAP trending up) ``` -------------------------------- ### Fetch Binance Klines Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Retrieves historical candlestick (OHLCV) data from Binance for technical analysis. Supports different intervals and lookback periods. ```APIDOC ## GET /api/binance/klines ### Description Retrieves historical candlestick (OHLCV) data from Binance for technical analysis. ### Method GET ### Endpoint /api/binance/klines ### Query Parameters - **interval** (string) - Required - The time interval for the candles (e.g., "1m", "5m", "1h"). - **limit** (integer) - Optional - The number of candles to retrieve. Defaults to 500. ### Response #### Success Response (200) - **candles** (array) - An array of candle objects, each containing: - **openTime** (integer) - Timestamp of the candle open. - **open** (number) - The opening price. - **high** (number) - The highest price during the candle. - **low** (number) - The lowest price during the candle. - **close** (number) - The closing price. - **volume** (number) - The trading volume. - **closeTime** (integer) - Timestamp of the candle close. ### Request Example ```javascript import { fetchKlines } from "./src/data/binance.js"; // Fetch 240 1-minute candles for BTC/USDT const candles1m = await fetchKlines({ interval: "1m", limit: 240 }); ``` ### Response Example ```json { "candles": [ { "openTime": 1699999200000, "open": 43250.50, "high": 43280.00, "low": 43240.00, "close": 43265.75, "volume": 125.34, "closeTime": 1699999259999 } ] } ``` ``` -------------------------------- ### Fetch CLOB Price Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Fetches the current best price for a specific outcome token from Polymarket's CLOB (Central Limit Order Book). ```APIDOC ## Fetch CLOB Price ### Description Fetches the current best price for a specific outcome token from Polymarket's CLOB (Central Limit Order Book). ### Method GET (assumed, based on fetch operation) ### Endpoint /api/clob/price (assumed, based on fetchClobPrice function) ### Parameters #### Query Parameters - **tokenId** (string) - Required - The unique identifier for the outcome token. - **side** (string) - Required - The side of the order book to query ('buy' or 'sell'). ### Request Example ```javascript import { fetchClobPrice } from "./src/data/polymarket.js"; // Get buy price for UP outcome const upBuyPrice = await fetchClobPrice({ tokenId: "12345...", // UP token ID from market.clobTokenIds side: "buy" }); // Get buy price for DOWN outcome const downBuyPrice = await fetchClobPrice({ tokenId: "67890...", // DOWN token ID side: "buy" }); ``` ### Response #### Success Response (200) - **price** (number) - The best available price for the specified token and side. #### Response Example ```json 0.52 ``` ``` -------------------------------- ### Compute Heiken Ashi Candles Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Generates Heiken Ashi candles and counts consecutive same-color candles to assess trend strength. ```javascript import { computeHeikenAshi, countConsecutive } from "./src/indicators/heikenAshi.js"; const candles = [ { open: 43200, high: 43280, low: 43180, close: 43250 }, { open: 43250, high: 43300, low: 43220, close: 43280 }, // ... ]; const ha = computeHeikenAshi(candles); // Returns: [ // { open: 43225, high: 43280, low: 43180, close: 43227.5, isGreen: true, body: 2.5 }, // { open: 43226.25, high: 43300, low: 43220, close: 43262.5, isGreen: true, body: 36.25 }, // ... // ] const { color, count } = countConsecutive(ha); // Returns: { color: "green", count: 5 } // 5 consecutive green HA candles ``` -------------------------------- ### Compute RSI Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Calculates the Relative Strength Index for a series of closing prices. RSI above 55 suggests bullish momentum, below 45 suggests bearish momentum. ```APIDOC ## Compute RSI ### Description Calculates the Relative Strength Index for a series of closing prices. RSI above 55 suggests bullish momentum, below 45 suggests bearish momentum. ### Method N/A (This is a client-side utility function) ### Endpoint N/A ### Parameters #### Function Parameters - **closes** (array) - Required - An array of closing prices. - **period** (integer) - Required - The period for the RSI calculation (e.g., 14). ### Request Example ```javascript import { computeRsi, sma, slopeLast } from "./src/indicators/rsi.js"; const closes = [43200, 43250, 43220, 43280, 43300, ...]; // 15+ prices // Compute 14-period RSI const rsi = computeRsi(closes, 14); // Compute RSI moving average const rsiSeries = closes.map((_, i) => computeRsi(closes.slice(0, i + 1), 14)).filter(Boolean); const rsiMa = sma(rsiSeries, 14); // Compute RSI slope (direction) const rsiSlope = slopeLast(rsiSeries, 3); ``` ### Response #### Success Response - **rsi** (number) - The calculated RSI value (0-100). - **rsiMa** (number) - The calculated moving average of the RSI. - **rsiSlope** (number) - The slope of the RSI over the last N periods. #### Response Example ```json { "rsi": 58.5, "rsiMa": 52.3, "rsiSlope": 0.8 } ``` ``` -------------------------------- ### Compute Edge and Decide Trade Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Evaluates model predictions against market prices to identify trading opportunities and generate decisions. ```javascript import { computeEdge, decide } from "./src/engines/edge.js"; // Compare model vs market const edge = computeEdge({ modelUp: 0.65, // Model's UP probability modelDown: 0.35, // Model's DOWN probability marketYes: 52, // Market UP price (cents) marketNo: 48 // Market DOWN price (cents) }); // Returns: { // marketUp: 0.52, // Normalized market UP probability // marketDown: 0.48, // Normalized market DOWN probability // edgeUp: 0.13, // Model minus market for UP // edgeDown: -0.13 // Model minus market for DOWN // } // Make trading decision const rec = decide({ remainingMinutes: 8, edgeUp: 0.13, edgeDown: -0.13, modelUp: 0.65, modelDown: 0.35 }); // Returns: { // action: "ENTER", // "ENTER" or "NO_TRADE" // side: "UP", // "UP" or "DOWN" // phase: "MID", // "EARLY" (>10m), "MID" (5-10m), "LATE" (<5m) // strength: "GOOD", // "STRONG" (>=0.2), "GOOD" (>=0.1), "OPTIONAL" // edge: 0.13 // } ``` -------------------------------- ### Compute RSI Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Calculates the Relative Strength Index (RSI) for a series of closing prices. RSI values above 55 suggest bullish momentum, while values below 45 suggest bearish momentum. Requires closing prices and a period. ```javascript import { computeRsi, sma, slopeLast } from "./src/indicators/rsi.js"; const closes = [43200, 43250, 43220, 43280, 43300, ...]; // 15+ prices // Compute 14-period RSI const rsi = computeRsi(closes, 14); // Returns: 58.5 (range 0-100) // Compute RSI moving average const rsiSeries = closes.map((_, i) => computeRsi(closes.slice(0, i + 1), 14)).filter(Boolean); const rsiMa = sma(rsiSeries, 14); // Returns: 52.3 // Compute RSI slope (direction) const rsiSlope = slopeLast(rsiSeries, 3); // Returns: 0.8 (positive = RSI increasing) ``` -------------------------------- ### Compute MACD Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Calculates MACD (Moving Average Convergence Divergence) including histogram and histogram delta for momentum analysis. Requires closing prices and fast, slow, and signal periods. Minimum 35 prices are recommended. ```javascript import { computeMacd } from "./src/indicators/macd.js"; const closes = [43200, 43250, ...]; // 35+ prices minimum const macd = computeMacd(closes, 12, 26, 9); // fast, slow, signal // Returns: { // macd: 15.5, // MACD line value // signal: 12.3, // Signal line value // hist: 3.2, // Histogram (macd - signal) // histDelta: 0.5 // Change in histogram (momentum direction) // } // Interpretation: // hist > 0 && histDelta > 0 = "bullish (expanding)" // hist > 0 && histDelta < 0 = "bullish (contracting)" // hist < 0 && histDelta < 0 = "bearish (expanding)" // hist < 0 && histDelta > 0 = "bearish (contracting)" ``` -------------------------------- ### Compute MACD Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Calculates MACD (Moving Average Convergence Divergence) with histogram and histogram delta for momentum analysis. ```APIDOC ## Compute MACD ### Description Calculates MACD (Moving Average Convergence Divergence) with histogram and histogram delta for momentum analysis. ### Method N/A (This is a client-side utility function) ### Endpoint N/A ### Parameters #### Function Parameters - **closes** (array) - Required - An array of closing prices (minimum 35+ prices recommended). - **fastPeriod** (integer) - Required - The period for the fast moving average (e.g., 12). - **slowPeriod** (integer) - Required - The period for the slow moving average (e.g., 26). - **signalPeriod** (integer) - Required - The period for the signal line moving average (e.g., 9). ### Request Example ```javascript import { computeMacd } from "./src/indicators/macd.js"; const closes = [43200, 43250, ...]; // 35+ prices minimum const macd = computeMacd(closes, 12, 26, 9); // fast, slow, signal ``` ### Response #### Success Response - **macd** (number) - The MACD line value. - **signal** (number) - The Signal line value. - **hist** (number) - The Histogram (macd - signal). - **histDelta** (number) - The change in histogram (momentum direction). #### Response Example ```json { "macd": 15.5, "signal": 12.3, "hist": 3.2, "histDelta": 0.5 } ``` ### Interpretation - `hist > 0 && histDelta > 0` = "bullish (expanding)" - `hist > 0 && histDelta < 0` = "bullish (contracting)" - `hist < 0 && histDelta < 0` = "bearish (expanding)" - `hist < 0 && histDelta > 0` = "bearish (contracting)" ``` -------------------------------- ### Score Direction Probability Source: https://context7.com/frondent/polymarketbtc15massistant/llms.txt Analyzes technical indicators to output a raw probability score for market direction. ```javascript import { scoreDirection } from "./src/engines/probability.js"; const scored = scoreDirection({ price: 43280, vwap: 43250, vwapSlope: 1.5, rsi: 58, rsiSlope: 0.3, macd: { hist: 3.2, histDelta: 0.5, macd: 15 }, heikenColor: "green", heikenCount: 3, failedVwapReclaim: false }); // Returns: { // upScore: 11, // Raw weighted score for UP // downScore: 3, // Raw weighted score for DOWN // rawUp: 0.786 // Probability: upScore / (upScore + downScore) // } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.