### Custom Indicator Creation Example (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Demonstrates how to create a custom technical indicator using the KLineCharts indicator template. It defines the indicator's name, figures, styles, and calculation logic, and then registers it with the klinecharts library. ```typescript // composables/kline/indicators/BigPeriodHL.ts - Custom indicator example import type { IndicatorTemplate } from "klinecharts"; import { LineType } from "klinecharts"; const customIndicator: IndicatorTemplate = { name: "CustomMA", figures: [ { key: "ma5", title: "MA5: ", type: "line" }, { key: "ma10", title: "MA10: ", type: "line" } ], styles: { lines: [ { style: LineType.Solid, size: 1, color: "#FF6B6B" }, { style: LineType.Solid, size: 1, color: "#4ECDC4" } ] }, calc: (dataList, { calcParams }) => { const result = []; const period1 = calcParams[0] || 5; const period2 = calcParams[1] || 10; for (let i = 0; i < dataList.length; i++) { const item = { ma5: NaN, ma10: NaN }; if (i >= period1 - 1) { let sum = 0; for (let j = 0; j < period1; j++) { sum += dataList[i - j].close; } item.ma5 = sum / period1; } if (i >= period2 - 1) { let sum = 0; for (let j = 0; j < period2; j++) { sum += dataList[i - j].close; } item.ma10 = sum / period2; } result.push(item); } return result; } }; // Register the indicator import * as kc from "klinecharts"; kc.registerIndicator(customIndicator); ``` -------------------------------- ### Make General API Requests Source: https://context7.com/banbox/ban-ui/llms.txt Provides examples of using the general API client for public endpoints that do not require bot authentication. This client is used for fetching market data like K-line history, available symbols, and cloud indicators. ```typescript import { getApi, postApi } from "~/utils/netio"; // Fetch K-line data const klineData = await getApi("/kline/hist", { symbol: "BTC/USDT.P", timeframe: "1h", exchange: "binance", from: 1699200000000, to: 1699234567000 }); // Response: { data: [[timestamp, open, high, low, close, volume], ...] } // Fetch available symbols const symbols = await getApi("/kline/symbols"); // Response: { data: [{ symbol: "BTC/USDT.P", exchange: "binance", market: "spot" }, ...] } // Fetch cloud indicators const indicators = await getApi("/kline/all_inds"); // Response: { data: [{ name: "CustomMA", title: "Custom Moving Average", is_main: true }, ...] } ``` -------------------------------- ### Interact with Banbot API Client Source: https://context7.com/banbox/ban-ui/llms.txt Shows how to use the ban-ui API client for authenticated GET and POST requests to the trading bot backend. It supports automatic token refresh on 401 errors and can be used with a specific bot instance or the currently selected bot. ```typescript import { useApi, useCurApi } from "~/composables/dash/api"; import { type TradeBot } from "~/composables/dash/types"; // Use with specific bot const bot: TradeBot = { url: "http://localhost:9000", /* ... */ }; const { getApi, postApi } = useApi(bot); // Or use current selected bot const { getApi, postApi } = useCurApi(); // Fetch bot information const botInfo = await getApi("/bot_info"); // Response: { cpu_pct: 15.2, ram_pct: 45.1, last_process: 1699234567000, ... } // Fetch trading statistics const stats = await getApi("/statistics"); // Response: { win_rate: 0.65, profit_factor: 1.8, expectancy: 0.023, ... } // Fetch account balance const balance = await getApi("/balance"); // Response: { total: 10543.25, items: [{ symbol: "USDT", free: 5000, used: 5543.25 }] } // Delay entry orders const delayResult = await postApi("/delay_entry", { secs: 3600 }); // Response: { code: 200, allow_trade_at: 1699238167000 } ``` -------------------------------- ### Bot API Client Endpoints Source: https://context7.com/banbox/ban-ui/llms.txt Provides authenticated GET and POST requests to the trading bot backend. It automatically handles JWT token refresh on 401 errors. ```APIDOC ## Bot API Client Endpoints ### Description Provides authenticated GET and POST requests to the trading bot backend. It automatically handles JWT token refresh on 401 errors. ### Method GET, POST ### Endpoint `/api/*` (Base URL determined by `getBizUrl()` from Bot Authentication) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Varies per endpoint, see examples) ### Request Example ```typescript // composables/dash/api.ts - API client usage import { useApi, useCurApi } from "~/composables/dash/api"; import { type TradeBot } from "~/composables/dash/types"; // Use with specific bot const bot: TradeBot = { url: "http://localhost:9000", /* ... */ }; const { getApi, postApi } = useApi(bot); // Or use current selected bot // const { getApi, postApi } = useCurApi(); // Fetch bot information const botInfo = await getApi("/bot_info"); // Fetch trading statistics const stats = await getApi("/statistics"); // Fetch account balance const balance = await getApi("/balance"); // Delay entry orders const delayResult = await postApi("/delay_entry", { secs: 3600 }); ``` ### Specific Endpoints & Responses #### GET /bot_info ##### Description Fetches general information about the trading bot. ##### Response Example ```json { "cpu_pct": 15.2, "ram_pct": 45.1, "last_process": 1699234567000, "// ... other fields" } ``` #### GET /statistics ##### Description Fetches trading performance statistics. ##### Response Example ```json { "win_rate": 0.65, "profit_factor": 1.8, "expectancy": 0.023, "// ... other fields" } ``` #### GET /balance ##### Description Fetches the current account balance information. ##### Response Example ```json { "total": 10543.25, "items": [ { "symbol": "USDT", "free": 5000, "used": 5543.25 }, { "symbol": "BTC", "free": 0.5, "used": 0.1 } ] } ``` #### POST /delay_entry ##### Description Delays the execution of entry orders for a specified duration. ##### Request Body Example ```json { "secs": 3600 } ``` ##### Response Example ```json { "code": 200, "allow_trade_at": 1699238167000 } ``` ``` -------------------------------- ### Manage Dashboard State with Pinia Store (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Manages the state for a dashboard, including bot connections and UI elements, with localStorage persistence. It allows accessing connected bots, switching between them, adding new bots, and controlling UI states like menu selection and modal visibility. ```typescript import { useDashLocal } from "~/stores/dashLocal"; import { useDashStore } from "~/stores/dash"; const local = useDashLocal(); const store = useDashStore(); // Access all connected bots console.log("Connected bots:", local.all_bots); // Get current selected bot console.log("Current bot:", local.bot); // Switch to different bot local.cur_id = 1; // Add new bot after login local.all_bots.push({ url: "http://bot2.example.com:9000", user_name: "trader", password: "pass123", auto_refresh: true, name: "Bot-2", token: "jwt_token_here", account: "account1", role: "admin" }); // Dashboard UI state store.menu_id = "2"; // Active menu item store.showContact = true; // Show contact modal ``` -------------------------------- ### Manage K-line Chart State with Pinia Store (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Manages the state of K-line charts, including symbols, indicators, and UI preferences, using Pinia with localStorage persistence. It allows setting symbols, timeframes, managing indicators, and customizing chart styles. It also provides access to all available symbols and allows filtering them. ```typescript import { useKlineStore } from "~/stores/kline"; import { useKlineLocal } from "~/stores/klineLocal"; import { makePeriod } from "~/composables/kline/coms"; const store = useKlineStore(); const local = useKlineLocal(); // Set current symbol local.setSymbolTicker("ETH/USDT.P", "binance"); // Set timeframe local.setTimeframe("4h"); // Or with full period object local.setPeriod(makePeriod("1d")); // Access chart state console.log("Current symbol:", local.symbol.ticker); console.log("Current period:", local.period.timeframe); console.log("Theme:", local.theme); // "light" or "dark" console.log("Timezone:", local.timezone); // Manage saved indicators local.save_inds.push({ name: "MACD", pane_id: "pane_MACD" }); local.removeInd("pane_MACD", "MACD"); // Set chart styles local.setStyleItem("candle.priceMark.last.show", true); local.resetStyle(); // Reset to defaults // Access all available symbols console.log("All symbols:", store.all_symbols); console.log("Current symbols (filtered):", store.symbols); // Set trading pairs filter store.setCurSymbols(["BTC/USDT.P", "ETH/USDT.P"]); ``` -------------------------------- ### General API Client Endpoints Source: https://context7.com/banbox/ban-ui/llms.txt Used for public endpoints that do not require bot authentication. This client is suitable for fetching market data and configuration. ```APIDOC ## General API Client Endpoints ### Description Used for public endpoints that do not require bot authentication. This client is suitable for fetching market data and configuration. ### Method GET, POST ### Endpoint (Base URL is typically defined in `utils/netio.ts` or environment configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Varies per endpoint, see examples) ### Request Example ```typescript // utils/netio.ts - General API requests import { getApi, postApi } from "~/utils/netio"; // Fetch K-line data const klineData = await getApi("/kline/hist", { symbol: "BTC/USDT.P", timeframe: "1h", exchange: "binance", from: 1699200000000, to: 1699234567000 }); // Fetch available symbols const symbols = await getApi("/kline/symbols"); // Fetch cloud indicators const indicators = await getApi("/kline/all_inds"); ``` ### Specific Endpoints & Responses #### GET /kline/hist ##### Description Fetches historical K-line (candlestick) data for a given symbol and timeframe. ##### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., "BTC/USDT.P"). - **timeframe** (string) - Required - The time interval for the candles (e.g., "1h", "1d"). - **exchange** (string) - Required - The cryptocurrency exchange (e.g., "binance"). - **from** (integer) - Required - Start timestamp in milliseconds. - **to** (integer) - Required - End timestamp in milliseconds. ##### Response Example ```json { "data": [ [1699200000000, 50000.0, 51000.0, 49500.0, 50500.0, 100.5], [1699203600000, 50500.0, 51500.0, 50000.0, 51200.0, 120.2] // ... more data points [timestamp, open, high, low, close, volume] ] } ``` #### GET /kline/symbols ##### Description Fetches a list of available trading symbols and their associated exchanges and markets. ##### Response Example ```json { "data": [ { "symbol": "BTC/USDT.P", "exchange": "binance", "market": "spot" }, { "symbol": "ETH/USDT.P", "exchange": "binance", "market": "spot" }, { "symbol": "BTC/USD", "exchange": "okx", "market": "future" } // ... more symbols ] } ``` #### GET /kline/all_inds ##### Description Fetches a list of all available technical indicators, including custom ones. ##### Response Example ```json { "data": [ { "name": "MA", "title": "Moving Average", "is_main": true }, { "name": "EMA", "title": "Exponential Moving Average", "is_main": true }, { "name": "CustomMA", "title": "Custom Moving Average", "is_main": false } // ... more indicators ] } ``` ``` -------------------------------- ### Fetch and Subscribe to K-line Datafeed (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Implements a datafeed class to fetch historical K-line data and subscribe to real-time WebSocket updates for live chart rendering. It requires symbol and period information as input and returns bar data or symbol lists. Unsubscription is also supported. ```typescript import { MyDatafeed } from "~/composables/kline/datafeeds"; import { type SymbolInfo, type Period } from "~/components/kline/types"; const datafeed = new MyDatafeed(); // Define symbol and period const symbol: SymbolInfo = { ticker: "BTC/USDT.P", exchange: "binance", market: "spot", priceCurrency: "USDT" }; const period: Period = { multiplier: 1, timespan: "hour", text: "1H", timeframe: "1h", secs: 3600 }; // Fetch historical K-line data const kdata = await datafeed.getHistoryKLineData({ symbol, period, from: 1699200000000, to: 1699234567000 }); // Response: { data: [{ timestamp, open, high, low, close, volume }, ...], lays: [...] } // Fetch available symbols const symbols = await datafeed.getSymbols(); // Response: [{ ticker: "BTC/USDT.P", name: "BTC/USDT.P", exchange: "binance", ... }, ...] // Subscribe to real-time updates datafeed.subscribe(symbol, (result) => { console.log("New bar data:", result.bars); // result.bars: [[timestamp, open, high, low, close, volume], ...] }); // Unsubscribe when done datafeed.unsubscribe(symbol); ``` -------------------------------- ### Authenticate Banbot Trading Bot Source: https://context7.com/banbox/ban-ui/llms.txt Demonstrates how to authenticate with a banbot trading robot instance using Basic Auth for initial login and JWT tokens for subsequent requests. It utilizes the `useBotAuth` composable and requires `TradeBot` type definition. ```typescript import { useBotAuth } from "~/composables/dash/auth"; import { type TradeBot } from "~/composables/dash/types"; // Define bot connection const bot: TradeBot = { url: "http://localhost:9000", user_name: "admin", password: "secret123", auto_refresh: true }; // Authenticate with the bot const { login, getBizUrl } = useBotAuth(bot); const result = await login(); if (result.code === 200) { console.log("Login successful, token:", bot.token); console.log("API base URL:", getBizUrl()); // Returns: http://localhost:9000/api } else { console.error("Login failed:", result.msg); } ``` -------------------------------- ### Bot Authentication API Source: https://context7.com/banbox/ban-ui/llms.txt Handles the authentication process for connecting to the trading bot backend. It uses Basic Auth for initial login and JWT tokens for subsequent requests, supporting multiple trading accounts. ```APIDOC ## Bot Authentication API ### Description Handles the authentication process for connecting to the trading bot backend. It uses Basic Auth for initial login and JWT tokens for subsequent requests, supporting multiple trading accounts. ### Method POST (Implicit via composable) ### Endpoint (Not directly exposed, handled by composable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Authentication details are passed via the `TradeBot` object configuration) ### Request Example ```typescript // composables/dash/auth.ts - Bot authentication import { useBotAuth } from "~/composables/dash/auth"; import { type TradeBot } from "~/composables/dash/types"; // Define bot connection const bot: TradeBot = { url: "http://localhost:9000", user_name: "admin", password: "secret123", auto_refresh: true }; // Authenticate with the bot const { login, getBizUrl } = useBotAuth(bot); const result = await login(); if (result.code === 200) { console.log("Login successful, token:", bot.token); console.log("API base URL:", getBizUrl()); // Returns: http://localhost:9000/api } else { console.error("Login failed:", result.msg); } ``` ### Response #### Success Response (200) - **token** (string) - JWT token for subsequent authenticated requests. - **msg** (string) - Success message. #### Response Example ```json { "code": 200, "msg": "Login successful", "token": "your_jwt_token_here" } ``` #### Error Response - **code** (integer) - Error code. - **msg** (string) - Error message. #### Error Response Example ```json { "code": 401, "msg": "Invalid credentials" } ``` ``` -------------------------------- ### Chart Period and Utility Functions (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Provides helper functions for creating and managing chart time periods, accessing predefined periods, retrieving theme-specific styles, aggregating OHLCV data, and loading symbol information. It relies on imports from `~/composables/kline/coms`. ```typescript // composables/kline/coms.ts - Period and chart utilities import { makePeriod, AllPeriods, getThemeStyles, build_ohlcvs, useSymbols } from "~/composables/kline/coms"; // Create period object from timeframe string const period1h = makePeriod("1h"); // Result: { multiplier: 1, timespan: "hour", text: "1H", timeframe: "1h", secs: 3600 } const period4h = makePeriod("4h"); const period1d = makePeriod("1d"); const period1w = makePeriod("1w"); // Access all predefined periods console.log(AllPeriods); // [1m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, 1d, 3d, 1w] // Get theme-specific chart styles const darkStyles = getThemeStyles("dark"); const lightStyles = getThemeStyles("light"); // Aggregate bars from smaller timeframe to larger const detailBars = [[1699200000000, 100, 102, 99, 101, 1000], /* ... */]; const aggregated = build_ohlcvs(detailBars, 60000, 3600000); // 1m to 1h // Load symbols utility const { loadSymbols } = useSymbols(); await loadSymbols(); // Populates store.all_symbols ``` -------------------------------- ### Date and Time Utility Functions (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Provides a suite of date and time utility functions for common tasks such as converting date strings to UTC timestamps, formatting timestamps into human-readable strings, converting between timeframes and seconds, adjusting date ranges for data fetching, setting the global timezone, and formatting durations. ```typescript import { toUTCStamp, getDateStr, tf_to_secs, secs_to_tf, adjustFromTo, setTimezone, fmtDuration } from "~/composables/dateutil"; import { makePeriod } from "~/composables/kline/coms"; // Convert date string to UTC timestamp const ts1 = toUTCStamp("20231115"); // 1700006400000 const ts2 = toUTCStamp("202311151430"); // 1700059800000 const ts3 = toUTCStamp("2023-11-15 14:30:00"); // 1700059800000 // Format timestamp to string const dateStr = getDateStr(1700059800000, "YYYY-MM-DD HH:mm:ss"); // Result: "2023-11-15 14:30:00" // Timeframe conversions const secs1h = tf_to_secs("1h"); // 3600 const secs1d = tf_to_secs("1d"); // 86400 const tf = secs_to_tf(86400); // "1d" // Calculate from/to timestamps for data loading const period = makePeriod("4h"); const [from, to] = adjustFromTo(period, Date.now(), 500); // Returns [startTimestamp, endTimestamp] for 500 bars // Set global timezone await setTimezone("Asia/Shanghai"); // Format duration const duration = fmtDuration(3665); // "01:01:05" ``` -------------------------------- ### TypeScript Interfaces for Trading System (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Defines core TypeScript interfaces for the trading system, including structures for trade bots, bot information, balance items, symbol information, chart periods, and data feed configurations. These types facilitate data management and communication within the application. ```typescript // composables/dash/types.ts - Trading types interface TradeBot { url: string; user_name: string; password: string; auto_refresh: boolean; name?: string; avaiable?: boolean; token?: string; account?: string; role?: string; } interface BotInfo { cpu_pct: number; ram_pct: number; last_process: number; allow_trade_at: number; win_rate: number; profit_factor: number; expectancy: number; max_drawdown_pct: number; balance_total: number; balance_items: BalanceItem[]; exchange: string; market: string; pairs: string[]; } interface BalanceItem { symbol: string; total: number; free: number; used: number; upol: number; total_fiat: number; } // components/kline/types.ts - Chart types interface SymbolInfo { ticker: string; name?: string; shortName?: string; exchange?: string; market?: string; pricePrecision?: number; volumePrecision?: number; priceCurrency?: string; } interface Period { multiplier: number; timespan: string; text: string; timeframe: string; secs: number; } interface Datafeed { getSymbols(): Promise; getHistoryKLineData(args: GetKlineArgs): Promise; subscribe(symbol: SymbolInfo, callback: DatafeedWatchCallback): void; unsubscribe(symbol: SymbolInfo): void; } ``` -------------------------------- ### Technical Indicator Configuration (TypeScript) Source: https://context7.com/banbox/ban-ui/llms.txt Defines configurations for built-in technical indicators, including parameter definitions and default values. It utilizes functions from `~/components/kline/inds` to retrieve indicator fields and defaults. ```typescript // components/kline/inds.ts - Indicator configuration import { GetIndFields, GetIndDefaults } from "~/components/kline/inds"; // Get indicator parameter definitions const indFields = GetIndFields(); // MACD parameters console.log(indFields.MACD); // [{ paramNameKey: 'params_1', default: 12 }, { paramNameKey: 'params_2', default: 26 }, ...] // BOLL parameters console.log(indFields.BOLL); // [{ paramNameKey: 'period', default: 20 }, { paramNameKey: 'standard_deviation', default: 2 }] // RSI parameters with style keys console.log(indFields.RSI); // [{ paramNameKey: 'RSI1', styleKey: 'lines[0].color' }, ...] // Get default calculation parameters const maDefaults = GetIndDefaults("MA"); // [5, 10, 30] const emaDefaults = GetIndDefaults("EMA"); // [5, 10, 30] const macdDefaults = GetIndDefaults("MACD"); // undefined (use indicator defaults) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.