### Install borsa-api Source: https://context7.com/ibidi/borsa-api/llms.txt Install the library globally for CLI access or locally for use within a project. ```bash # Global install — enables the `borsa` CLI command npm install -g borsa-api # Local install — use as a library in your project npm install borsa-api ``` -------------------------------- ### Install Borsa API Globally Source: https://github.com/ibidi/borsa-api/blob/main/README.md Install the borsa-api package globally for CLI usage. ```bash npm install -g borsa-api ``` -------------------------------- ### Install Borsa API Locally Source: https://github.com/ibidi/borsa-api/blob/main/README.md Install the borsa-api package locally for programmatic use within your project. ```bash npm install borsa-api ``` -------------------------------- ### CLI Example: Fetch Index Data Source: https://github.com/ibidi/borsa-api/blob/main/README.md Example of using the Borsa API CLI to fetch and display data for a specific index, such as XU100. ```bash $ borsa endeks XU100 📊 BIST 100 (XU100) ────────────────────────────────────────────────── Değer: 9234.56 Değişim: ▲ 123.45 (1.35%) Yüksek: 9250.00 Düşük: 9100.00 Hacim: 12,345,678 ────────────────────────────────────────────────── ``` -------------------------------- ### Borsa API CLI Commands Source: https://context7.com/ibidi/borsa-api/llms.txt Examples of using the Borsa API command-line interface for various market data queries. Commands cover index data, single stock quotes, popular stocks, market screeners, watchlist management, comparisons, and historical data retrieval. ```bash # BIST index data (default: XU100) borsa endeks borsa endeks XU030 borsa endeks XBANK # Single stock quote borsa hisse THYAO borsa hisse GARAN # Popular stocks table borsa populer # All tracked indexes borsa endeksler # Full-text search (Turkish characters supported) borsa ara garanti borsa ara koç # same as 'koc' # Market screeners borsa yukselenler # top gainers (default 10) borsa yukselenler 5 # top 5 gainers borsa dusenler 5 # top 5 losers borsa hacim 5 # top 5 by volume # Watchlist management borsa watchlist --add THYAO borsa watchlist --add GARAN borsa watchlist borsa watchlist --remove THYAO borsa watchlist --clear # Side-by-side comparison borsa karsilastir THYAO GARAN borsa compare AKBNK ISCTR # Historical price data borsa gecmis THYAO # last 1 month (daily) borsa gecmis THYAO 5d # last 5 days borsa gecmis THYAO 1y # last 1 year borsa historical AKBNK 3mo # last 3 months # Extended fundamentals (market cap, P/E, sector, etc.) borsa detay THYAO borsa details GARAN ``` -------------------------------- ### Get Detailed Stock Information (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieve detailed information about a stock, including market cap, P/E ratio, and sector. ```bash borsa detay THYAO borsa details GARAN ``` -------------------------------- ### Get All Indexes Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves a list of all available BIST indexes. ```APIDOC ## getAllIndexes() ### Description Get all BIST indexes / Tüm BIST endekslerini al ### Method `getAllIndexes` ### Returns Promise ``` -------------------------------- ### Search Stocks by Query with BorsaAPI Source: https://github.com/ibidi/borsa-api/blob/main/README.md Allows searching for stocks using a query string. For example, searching for 'garanti'. ```javascript // Hisse arama async function search() { const results = await api.searchStock('garanti'); console.log(results); } ``` -------------------------------- ### Get Popular Stocks Source: https://github.com/ibidi/borsa-api/blob/main/README.md Fetches a list of currently popular stocks. ```APIDOC ## getPopularStocks() ### Description Get popular stocks / Popüler hisseleri al ### Method `getPopularStocks` ### Returns Promise ``` -------------------------------- ### Get Historical Stock Data (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieve historical price data for a stock. Specify the time frame (e.g., 5d, 1y, 3mo). ```bash # Last 1 month (default) borsa gecmis THYAO # Last 5 days borsa gecmis THYAO 5d # Last 1 year borsa gecmis THYAO 1y # Last 3 months borsa historical AKBNK 3mo ``` -------------------------------- ### Get Top Losers Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves a list of the top N stocks with the largest losses. ```APIDOC ## getTopLosers(count) ### Description En çok düşenler ### Method `getTopLosers` ### Parameters #### Path Parameters - **count** (number) - Required - The number of top losers to retrieve. ### Returns Promise ``` -------------------------------- ### Get Top Volume Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves a list of the top N stocks by trading volume. ```APIDOC ## getTopVolume(count) ### Description En yüksek hacimli hisseler ### Method `getTopVolume` ### Parameters #### Path Parameters - **count** (number) - Required - The number of top volume stocks to retrieve. ### Returns Promise ``` -------------------------------- ### Get Top Gainers Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves a list of the top N stocks with the highest gains. ```APIDOC ## getTopGainers(count) ### Description En çok yükselenler ### Method `getTopGainers` ### Parameters #### Path Parameters - **count** (number) - Required - The number of top gainers to retrieve. ### Returns Promise ``` -------------------------------- ### Get Index Data Source: https://github.com/ibidi/borsa-api/blob/main/README.md Fetches data for a specific stock market index. Supports various index symbols like XU100, XU030, etc. ```APIDOC ## getIndex(symbol) ### Description Get index data / Endeks verisi al ### Method `getIndex` ### Parameters #### Path Parameters - **symbol** (string) - Required - Index symbol (XU100, XU030, etc.) ### Returns Promise ``` -------------------------------- ### Get Stock Data Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves detailed data for a specific stock symbol. Supports symbols like THYAO, GARAN, etc. ```APIDOC ## getStock(symbol) ### Description Get stock data / Hisse senedi verisi al ### Method `getStock` ### Parameters #### Path Parameters - **symbol** (string) - Required - Stock symbol (THYAO, GARAN, etc.) ### Returns Promise ``` -------------------------------- ### Get Stock Details Source: https://context7.com/ibidi/borsa-api/llms.txt Retrieves extended fundamental data for a stock symbol, including price, market cap, P/E ratio, and sector information. Requires the stock symbol as input. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const details = await api.getStockDetails('THYAO'); console.log(details); // { // symbol: 'THYAO', // name: 'TURK HAVA YOLLARI', // price: 234.50, // change: 5.25, // changePercent: 2.29, // high: 236.00, low: 230.00, open: 231.00, close: 229.25, // volume: 1234567, // timestamp: '2024-11-23T14:30:00.000Z', // marketCap: 123456789000, // peRatio: 15.23, // eps: 12.34, // dividendYield: 0.025, // fiftyTwoWeekHigh: 346.25, // fiftyTwoWeekLow: 249.20, // averageVolume: 25000000, // beta: 1.15, // sector: 'Industrials', // industry: 'Airlines', // description: 'Türk Hava Yolları Anonim Ortaklığı...' // } } main().catch(console.error); ``` -------------------------------- ### Initialize BorsaAPI and Fetch Index Data Source: https://github.com/ibidi/borsa-api/blob/main/README.md Demonstrates how to initialize the BorsaAPI client and fetch data for a specific index like XU100. Includes error handling. ```javascript const BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); // Endeks verisi al async function getIndex() { try { const xu100 = await api.getIndex('XU100'); console.log(xu100); // { // symbol: 'XU100', // name: 'BIST 100', // value: 9234.56, // change: 123.45, // changePercent: 1.35, // high: 9250.00, // low: 9100.00, // volume: 12345678, // timestamp: '2024-11-16T...' // } } catch (error) { console.error(error.message); } } ``` -------------------------------- ### View All BIST Indexes (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md List all available BIST indexes using the CLI. ```bash borsa endeksler ``` -------------------------------- ### CLI Reference Source: https://context7.com/ibidi/borsa-api/llms.txt Command-line interface commands for interacting with the Borsa API. ```APIDOC ## CLI Reference ### Market Data - `borsa endeks [INDEX_NAME]` - Retrieves BIST index data. Defaults to XU100. Examples: `borsa endeks XU030`, `borsa endeks XBANK`. - `borsa hisse [SYMBOL]` - Retrieves a single stock quote. Example: `borsa hisse THYAO`. - `borsa populer` - Displays a table of popular stocks. - `borsa endeksler` - Lists all tracked indexes. ### Search - `borsa ara [QUERY]` - Performs a full-text search. Turkish characters are supported. Example: `borsa ara garanti`. ### Market Screeners - `borsa yukselenler [COUNT]` - Shows top gainers. Defaults to 10. Example: `borsa yukselenler 5`. - `borsa dusenler [COUNT]` - Shows top losers. Example: `borsa dusenler 5`. - `borsa hacim [COUNT]` - Shows top stocks by volume. Example: `borsa hacim 5`. ### Watchlist Management - `borsa watchlist --add [SYMBOL]` - Adds a stock symbol to the watchlist. Example: `borsa watchlist --add THYAO`. - `borsa watchlist` - Displays the current watchlist. - `borsa watchlist --remove [SYMBOL]` - Removes a stock symbol from the watchlist. Example: `borsa watchlist --remove THYAO`. - `borsa watchlist --clear` - Clears the entire watchlist. ### Comparison - `borsa karsilastir [SYMBOL1] [SYMBOL2]` - Compares two stocks side-by-side. Example: `borsa karsilastir THYAO GARAN`. - `borsa compare [SYMBOL1] [SYMBOL2]` - Alias for `karsilastir`. ### Historical Data - `borsa gecmis [SYMBOL] [PERIOD]` - Retrieves historical price data. Default period is '1mo' (daily). Examples: `borsa gecmis THYAO 5d`, `borsa gecmis THYAO 1y`. - `borsa historical [SYMBOL] [PERIOD]` - Alias for `gecmis`. ``` -------------------------------- ### Constructor - new BorsaAPI(options?) Source: https://context7.com/ibidi/borsa-api/llms.txt Instantiates the API client. Accepts an optional BorsaAPIOptions object. By default, useRealData is true, pulling live delayed data from Yahoo Finance via the .IS exchange suffix. Set useMockData: true for deterministic offline testing. ```APIDOC ## Constructor - `new BorsaAPI(options?)` ### Description Instantiates the API client. Accepts an optional `BorsaAPIOptions` object. By default, `useRealData` is `true`, pulling live delayed data from Yahoo Finance via the `.IS` exchange suffix. Set `useMockData: true` for deterministic offline testing. ### Usage ```typescript import BorsaAPI = require('borsa-api'); // Default — fetches real delayed data const api = new BorsaAPI(); // With explicit options const devApi = new BorsaAPI({ timeout: 15000, // request timeout in ms (default: 10000) useMockData: true, // use built-in mock dataset (offline/testing) useRealData: false // skip Yahoo Finance (use mock or legacy REST fallback) }); ``` ``` -------------------------------- ### View Popular Stocks (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Display a list of popular stocks using the CLI command. ```bash borsa populer ``` -------------------------------- ### Instantiate BorsaAPI Client Source: https://context7.com/ibidi/borsa-api/llms.txt Instantiate the API client with optional configuration. By default, it fetches real delayed data. Set `useMockData: true` for offline testing. ```typescript import BorsaAPI = require('borsa-api'); // Default — fetches real delayed data const api = new BorsaAPI(); // With explicit options const devApi = new BorsaAPI({ timeout: 15000, // request timeout in ms (default: 10000) useMockData: true, // use built-in mock dataset (offline/testing) useRealData: false // skip Yahoo Finance (use mock or legacy REST fallback) }); ``` -------------------------------- ### Compare Stocks (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Compare two stocks side-by-side using their ticker symbols via the CLI. ```bash borsa karsilastir THYAO GARAN borsa compare AKBNK ISCTR ``` -------------------------------- ### Manage Watchlist with BorsaAPI Source: https://github.com/ibidi/borsa-api/blob/main/README.md Demonstrates adding stocks to a watchlist and retrieving the current watchlist. Stocks are added with their symbol and name. ```javascript // Watchlist işlemleri api.watchlist.addToWatchlist('THYAO', 'Türk Hava Yolları'); api.watchlist.addToWatchlist('GARAN', 'Garanti Bankası'); const watchlist = api.watchlist.getWatchlist(); console.log(watchlist); ``` -------------------------------- ### Fetch All BIST Indexes with BorsaAPI Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves a list of all available BIST indexes. This function requires no parameters. ```javascript // Tüm endeksler async function getAllIndexes() { const indexes = await api.getAllIndexes(); console.log(indexes); } ``` -------------------------------- ### Manage Watchlist (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Add, view, remove, or clear stocks from your watchlist using the CLI. ```bash # Add to watchlist borsa watchlist --add THYAO borsa watchlist --add GARAN # Show watchlist borsa watchlist # Remove from watchlist borsa watchlist --remove THYAO # Clear watchlist borsa watchlist --clear ``` -------------------------------- ### Get Historical OHLCV Data Source: https://context7.com/ibidi/borsa-api/llms.txt Fetches historical Open, High, Low, Close, and Volume data for a given stock symbol. Supports period shorthands or custom date ranges and different intervals (daily, weekly, monthly). ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { // Last 3 months of daily data for Turkish Airlines const history = await api.getHistoricalData('THYAO', { period: '3mo', interval: '1d' }); console.log(history.meta.longName); // 'Türk Hava Yollari Anonim Ortakligi' console.log(history.meta.currency); // 'TRY' console.log(history.meta.fiftyTwoWeekHigh); // 346.25 console.log(history.meta.fiftyTwoWeekLow); // 249.20 console.log(`${history.quotes.length} trading days`); // e.g. "63 trading days" // First quote const q = history.quotes[0]; console.log(q); // { // date: Date('2024-08-23'), // open: 273.00, // high: 274.75, // low: 271.50, // close: 273.00, // adjClose: 266.68, // volume: 19991989 // } // Custom date range const custom = await api.getHistoricalData('GARAN', { period1: '2024-01-01', period2: '2024-06-30', interval: '1wk' }); console.log(`Weekly bars: ${custom.quotes.length}`); } main().catch(console.error); ``` -------------------------------- ### View Top Gainers/Losers/Volume Leaders (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Display lists of top-performing stocks (gainers/losers) and highest volume stocks. Optionally specify the number of stocks to display. ```bash # Top gainers (default 10) borsa yukselenler borsa yukselenler 5 # Top losers borsa dusenler borsa dusenler 5 # Volume leaders borsa hacim borsa hacim 5 ``` -------------------------------- ### View BIST Index Data (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Use the CLI to view specific BIST index data. Defaults to XU100 if no index is specified. ```bash # XU100 index (default) borsa endeks # Specific index borsa endeks XU030 borsa endeks XBANK ``` -------------------------------- ### Search for Stocks (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Search for stocks by name using the CLI. Supports Turkish characters. ```bash borsa ara garanti borsa ara turkcell ``` -------------------------------- ### getAllIndexes() - Fetch all BIST indexes Source: https://context7.com/ibidi/borsa-api/llms.txt Returns a Promise containing data for all seven tracked BIST indexes in a single parallel call. ```APIDOC ## `getAllIndexes()` — Fetch all BIST indexes ### Description Returns a `Promise` containing data for all seven tracked BIST indexes in a single parallel call. ### Method `getAllIndexes(): Promise` ### Response #### Success Response (200) - **IndexData[]** - An array of objects, each containing index data. - **symbol** (string) - The index symbol. - **name** (string) - The full name of the index. - **value** (number) - The current value of the index. - **change** (number) - The daily change in value. - **changePercent** (number) - The daily change as a percentage. - **high** (number) - The daily high value. - **low** (number) - The daily low value. - **volume** (number) - The daily trading volume. - **timestamp** (string) - The timestamp of the data. ### Request Example ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function printAllIndexes() { const indexes = await api.getAllIndexes(); indexes.forEach(idx => { const sign = idx.changePercent >= 0 ? '▲' : '▼'; console.log(`${idx.symbol.padEnd(8)} ${idx.value.toFixed(2).padStart(10)} ${sign} ${Math.abs(idx.changePercent).toFixed(2)}%`); }); } printAllIndexes().catch(console.error); ``` ### Response Example ```json [ { "symbol": "XU100", "name": "BIST 100", "value": 9234.56, "change": 123.45, "changePercent": 1.35, "high": 9250.00, "low": 9100.00, "volume": 12345678, "timestamp": "2024-11-23T14:30:00.000Z" }, { "symbol": "XU030", "name": "BIST 30", "value": 10456.78, "change": 91.23, "changePercent": 0.89, "high": 10500.00, "low": 10300.00, "volume": 8765432, "timestamp": "2024-11-23T14:30:00.000Z" } ] ``` ``` -------------------------------- ### Fetch Stock Data with BorsaAPI Source: https://github.com/ibidi/borsa-api/blob/main/README.md Shows how to retrieve detailed information for a specific stock symbol, such as THYAO. Includes error handling. ```javascript // Hisse senedi verisi al async function getStock() { try { const thyao = await api.getStock('THYAO'); console.log(thyao); // { // symbol: 'THYAO', // name: 'TURK HAVA YOLLARI', // price: 234.50, // change: 5.25, // changePercent: 2.29, // high: 236.00, // low: 230.00, // open: 231.00, // close: 229.25, // volume: 1234567, // timestamp: '2024-11-16T...' // } } catch (error) { console.error(error.message); } } ``` -------------------------------- ### View Stock Data (CLI) Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieve data for a specific stock using its ticker symbol via the CLI. ```bash borsa hisse THYAO borsa hisse GARAN borsa hisse EREGL ``` -------------------------------- ### Export Data using BorsaAPI Utils Source: https://github.com/ibidi/borsa-api/blob/main/README.md Shows how to export fetched stock data to JSON and CSV formats using utility functions provided by the API. ```javascript // Verileri export et const { exportToJSON, exportToCSV } = api.utils; const stocks = await api.getPopularStocks(); exportToJSON(stocks, 'stocks.json'); exportToCSV(stocks, 'stocks.csv'); ``` -------------------------------- ### Watchlist Methods Source: https://github.com/ibidi/borsa-api/blob/main/README.md Methods for managing the user's watchlist. ```APIDOC ## Watchlist Methods ### `api.watchlist.addToWatchlist(symbol, name)` Add a stock to the watchlist. ### `api.watchlist.removeFromWatchlist(symbol)` Remove a stock from the watchlist. ### `api.watchlist.getWatchlist()` Get the current watchlist. ### `api.watchlist.clearWatchlist()` Clear all stocks from the watchlist. ``` -------------------------------- ### Retrieve Popular Stocks with BorsaAPI Source: https://github.com/ibidi/borsa-api/blob/main/README.md Fetches a list of currently popular stocks. This function requires no parameters. ```javascript // Popüler hisseler async function getPopular() { const stocks = await api.getPopularStocks(); console.log(stocks); } ``` -------------------------------- ### Fetch All BIST Indexes Source: https://context7.com/ibidi/borsa-api/llms.txt Retrieves data for all seven tracked BIST indexes simultaneously. Formats and displays the symbol, value, and percentage change for each index. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function printAllIndexes() { const indexes = await api.getAllIndexes(); indexes.forEach(idx => { const sign = idx.changePercent >= 0 ? '▲' : '▼'; console.log(`${idx.symbol.padEnd(8)} ${idx.value.toFixed(2).padStart(10)} ${sign} ${Math.abs(idx.changePercent).toFixed(2)}%`); }); // XU100 9234.56 ▲ 1.35% // XU030 10456.78 ▲ 0.89% // XBANK 7890.12 ▼ 0.42% // ... } printAllIndexes().catch(console.error); ``` -------------------------------- ### Fetch a BIST Index Source: https://context7.com/ibidi/borsa-api/llms.txt Fetches data for a named BIST index. Defaults to 'XU100'. Supported symbols include 'XU100', 'XU030', 'XBANK', 'XUSIN', 'XGIDA', 'XHOLD', 'XUTEK'. Handles potential errors during fetch. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { try { const xu100 = await api.getIndex('XU100'); console.log(xu100); // { // symbol: 'XU100', // name: 'BIST 100', // value: 9234.56, // change: 123.45, // changePercent: 1.35, // high: 9250.00, // low: 9100.00, // volume: 12345678, // timestamp: '2024-11-23T14:30:00.000Z' // } const xbank = await api.getIndex('XBANK'); console.log(`Banking sector: ${xbank.value} (${xbank.changePercent > 0 ? '+' : ''}${xbank.changePercent.toFixed(2)}%)`); } catch (err) { console.error('Failed to fetch index:', err.message); } } main(); ``` -------------------------------- ### Fetch Top Losers Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves a list of the worst performing stocks based on percentage loss over a specified number. ```javascript // En çok düşenler async function topLosers() { const losers = await api.getTopLosers(5); console.log(losers); } ``` -------------------------------- ### Fetch Top 10 Popular BIST Stocks Source: https://context7.com/ibidi/borsa-api/llms.txt Retrieves data for the ten most-watched BIST equities. Individual failures during concurrent fetching are silently dropped. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function displayPopular() { const stocks = await api.getPopularStocks(); console.table( stocks.map(s => ({ Symbol: s.symbol, Price: s.price.toFixed(2), 'Change%': s.changePercent.toFixed(2) + '%', Volume: s.volume.toLocaleString() })) ); } displayPopular().catch(console.error); ``` -------------------------------- ### Utility Methods Source: https://github.com/ibidi/borsa-api/blob/main/README.md Utility functions for data export and filtering. ```APIDOC ## Utility Methods ### `api.utils.exportToJSON(data, filename)` Export provided data to a JSON file. ### `api.utils.exportToCSV(data, filename)` Export provided data to a CSV file. ### `api.utils.getTopGainers(stocks, limit)` Filter a list of stocks to get the top gainers. ### `api.utils.getTopLosers(stocks, limit)` Filter a list of stocks to get the top losers. ### `api.utils.getTopVolume(stocks, limit)` Filter a list of stocks by trading volume. ``` -------------------------------- ### getPopularStocks() Source: https://context7.com/ibidi/borsa-api/llms.txt Fetches the top 10 most-watched BIST stocks. Individual failures during concurrent fetching are silently dropped. ```APIDOC ## `getPopularStocks()` — Fetch top 10 popular BIST stocks Returns a `Promise` for the ten most-watched BIST equities: `THYAO`, `GARAN`, `EREGL`, `AKBNK`, `TUPRS`, `SAHOL`, `ISCTR`, `KCHOL`, `ASELS`, `BIMAS`. All quotes are fetched concurrently with `Promise.all`; individual failures are silently dropped. ### Method `getPopularStocks()` ### Returns `Promise` - An array of StockData objects for the top 10 popular stocks. ### Example ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function displayPopular() { const stocks = await api.getPopularStocks(); console.table( stocks.map(s => ({ Symbol: s.symbol, Price: s.price.toFixed(2), 'Change%': s.changePercent.toFixed(2) + '%', Volume: s.volume.toLocaleString() })) ); } displayPopular().catch(console.error); ``` ``` -------------------------------- ### Fetch Watchlist Data Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves the current data for all stocks present in the user's watchlist. ```javascript // Watchlist verilerini getir async function getWatchlistData() { const stocks = await api.getWatchlistData(); console.log(stocks); } ``` -------------------------------- ### getTopGainers(limit?) Source: https://context7.com/ibidi/borsa-api/llms.txt Retrieves a list of top gaining stocks, sorted by the highest positive change percentage. ```APIDOC ## `getTopGainers(limit?)` — Top gaining stocks Returns a `Promise` of the stocks with the highest positive `changePercent`, limited to `limit` results (default `10`). Only stocks with `changePercent > 0` are included. ### Method `getTopGainers(limit?: number)` ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of top gainers to return. Defaults to 10. ### Returns `Promise` - An array of StockData objects representing the top gaining stocks. ### Example ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const gainers = await api.getTopGainers(5); gainers.forEach((s, i) => { console.log(`#${i + 1} ${s.symbol}: +${s.changePercent.toFixed(2)}% @ ${s.price.toFixed(2)} TRY`); }); // #1 BIMAS: +3.87% @ 460.37 TRY // #2 THYAO: +2.29% @ 234.50 TRY // ... } main().catch(console.error); ``` ``` -------------------------------- ### Utility Functions for Stock Data Manipulation Source: https://context7.com/ibidi/borsa-api/llms.txt Demonstrates the use of utility functions from `api.utils` to process `StockData[]` arrays. These functions include filtering, sorting, creating ASCII charts, and exporting data to JSON or CSV. They operate on local data and do not require network calls. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const stocks = await api.getPopularStocks(); // Filter and sort helpers (same logic used internally by getTopGainers/getTopLosers/getTopVolume) const gainers = api.utils.getTopGainers(stocks, 3); const losers = api.utils.getTopLosers(stocks, 3); const byVolume = api.utils.getTopVolume(stocks, 3); // Sort any array by changePercent const sorted = api.utils.sortByChange(stocks, 'desc'); // ASCII bar chart from a series of close prices const closes = stocks.map(s => s.close); const chart = api.utils.createASCIIChart(closes, 8); console.log(chart); // Export to disk api.utils.exportToJSON(stocks, 'bist-snapshot.json'); // Writes: [{"symbol":"THYAO","price":234.50,...}, ...] api.utils.exportToCSV(stocks, 'bist-snapshot.csv'); // Writes CSV with auto-detected headers + quoted values containing commas } main().catch(console.error); ``` -------------------------------- ### Retrieve Top Gaining Stocks Source: https://context7.com/ibidi/borsa-api/llms.txt Returns a list of stocks with positive change percentages, sorted by the highest gains. An optional limit can be specified for the number of results. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const gainers = await api.getTopGainers(5); gainers.forEach((s, i) => { console.log(`#${i + 1} ${s.symbol}: +${s.changePercent.toFixed(2)}% @ ${s.price.toFixed(2)} TRY`); }); // #1 BIMAS: +3.87% @ 460.37 TRY // #2 THYAO: +2.29% @ 234.50 TRY // ... } main().catch(console.error); ``` -------------------------------- ### Compare Two Stocks Side by Side Source: https://context7.com/ibidi/borsa-api/llms.txt Fetches two specified stocks concurrently and provides a detailed comparison including price, change percentage, and volume differences. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const result = await api.compareStocks('THYAO', 'GARAN'); console.log(result); // { // stock1: { symbol: 'THYAO', price: 234.50, changePercent: 2.29, volume: 1234567, ... }, // stock2: { symbol: 'GARAN', price: 89.75, changePercent: 0.84, volume: 8456789, ... }, // comparison: { // priceDiff: 144.75, // stock1.price - stock2.price // changeDiff: 1.45, // stock1.changePercent - stock2.changePercent // volumeDiff: -7222222 // stock1.volume - stock2.volume // } // } } main().catch(console.error); ``` -------------------------------- ### getTopLosers(limit?) Source: https://context7.com/ibidi/borsa-api/llms.txt Retrieves a list of top losing stocks, sorted by the steepest negative change percentage. ```APIDOC ## `getTopLosers(limit?)` — Top losing stocks Returns a `Promise` of the stocks with the steepest negative `changePercent`, sorted ascending. Only stocks with `changePercent < 0` are included. ### Method `getTopLosers(limit?: number)` ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of top losers to return. Defaults to 10. ### Returns `Promise` - An array of StockData objects representing the top losing stocks. ### Example ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const losers = await api.getTopLosers(5); losers.forEach((s, i) => { console.log(`#${i + 1} ${s.symbol}: ${s.changePercent.toFixed(2)}% @ ${s.price.toFixed(2)} TRY`); }); // #1 ISCTR: -1.92% @ 12.21 TRY // #2 EREGL: -0.95% @ 44.77 TRY // ... } main().catch(console.error); ``` ``` -------------------------------- ### getIndex(symbol?) - Fetch a BIST index Source: https://context7.com/ibidi/borsa-api/llms.txt Returns a Promise with value, daily change, high/low, and volume for a named BIST index. Default symbol is 'XU100'. Supported symbols: XU100, XU030, XBANK, XUSIN, XGIDA, XHOLD, XUTEK. ```APIDOC ## `getIndex(symbol?)` — Fetch a BIST index ### Description Returns a `Promise` with value, daily change, high/low, and volume for a named BIST index. Default symbol is `'XU100'`. Supported symbols: `XU100`, `XU030`, `XBANK`, `XUSIN`, `XGIDA`, `XHOLD`, `XUTEK`. ### Method `getIndex(symbol?: string): Promise` ### Parameters #### Query Parameters - **symbol** (string) - Optional - The symbol of the BIST index to fetch. Defaults to 'XU100'. ### Response #### Success Response (200) - **IndexData** - An object containing index data. - **symbol** (string) - The index symbol. - **name** (string) - The full name of the index. - **value** (number) - The current value of the index. - **change** (number) - The daily change in value. - **changePercent** (number) - The daily change as a percentage. - **high** (number) - The daily high value. - **low** (number) - The daily low value. - **volume** (number) - The daily trading volume. - **timestamp** (string) - The timestamp of the data. ### Request Example ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { try { const xu100 = await api.getIndex('XU100'); console.log(xu100); } catch (err) { console.error('Failed to fetch index:', err.message); } } main(); ``` ### Response Example ```json { "symbol": "XU100", "name": "BIST 100", "value": 9234.56, "change": 123.45, "changePercent": 1.35, "high": 9250.00, "low": 9100.00, "volume": 12345678, "timestamp": "2024-11-23T14:30:00.000Z" } ``` ``` -------------------------------- ### Fetch Detailed Stock Information Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves comprehensive details for a specific stock, including market cap, P/E ratio, and sector information. ```javascript // Detaylı hisse bilgisi async function getDetails() { const details = await api.getStockDetails('THYAO'); console.log(details); // { // ...StockData, // marketCap: 123456789000, // peRatio: 15.23, // eps: 12.34, // dividendYield: 0.025, // fiftyTwoWeekHigh: 346.25, // fiftyTwoWeekLow: 249.20, // averageVolume: 25000000, // beta: 1.15, // sector: 'Industrials', // industry: 'Airlines', // description: 'Company description...' // } ``` -------------------------------- ### Retrieve Top Losing Stocks Source: https://context7.com/ibidi/borsa-api/llms.txt Returns a list of stocks with negative change percentages, sorted by the steepest losses. An optional limit can be specified for the number of results. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const losers = await api.getTopLosers(5); losers.forEach((s, i) => { console.log(`#${i + 1} ${s.symbol}: ${s.changePercent.toFixed(2)}% @ ${s.price.toFixed(2)} TRY`); }); // #1 ISCTR: -1.92% @ 12.21 TRY // #2 EREGL: -0.95% @ 44.77 TRY // ... } main().catch(console.error); ``` -------------------------------- ### Fetch Top Gainers Source: https://github.com/ibidi/borsa-api/blob/main/README.md Retrieves a list of the top performing stocks based on percentage gain over a specified number. ```javascript // En çok yükselenler async function topGainers() { const gainers = await api.getTopGainers(5); console.log(gainers); } ``` -------------------------------- ### getTopVolume(limit?) Source: https://context7.com/ibidi/borsa-api/llms.txt Retrieves a list of stocks with the highest trading volume. ```APIDOC ## `getTopVolume(limit?)` — Highest volume stocks Returns a `Promise` sorted by descending `volume`, limited to `limit` items (default `10`). ### Method `getTopVolume(limit?: number)` ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of highest volume stocks to return. Defaults to 10. ### Returns `Promise` - An array of StockData objects sorted by volume. ### Example ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { const leaders = await api.getTopVolume(3); leaders.forEach(s => { console.log(`${s.symbol}: ${s.volume.toLocaleString()} lots traded`); }); // GARAN: 8,456,789 lots traded // AKBNK: 6,123,001 lots traded // THYAO: 1,234,567 lots traded } main().catch(console.error); ``` ``` -------------------------------- ### Utility Functions Source: https://context7.com/ibidi/borsa-api/llms.txt Standalone helper functions exported from `src/utils.ts` that operate on `StockData[]` arrays and do not require network calls. ```APIDOC ## Utility Functions — `api.utils` These functions operate on `StockData[]` arrays and do not require a network call. ### `getTopGainers(stocks: StockData[], count: number): StockData[]` Filters an array of stocks to return the top gainers. ### `getTopLosers(stocks: StockData[], count: number): StockData[]` Filters an array of stocks to return the top losers. ### `getTopVolume(stocks: StockData[], count: number): StockData[]` Filters an array of stocks to return the top by volume. ### `sortByChange(stocks: StockData[], direction: 'asc' | 'desc'): StockData[]` Sorts an array of stocks by their change percentage. ### `createASCIIChart(closes: number[], width: number): string` Creates an ASCII bar chart from a series of closing prices. ### `exportToJSON(data: any[], filename: string): void` Exports data to a JSON file. ### `exportToCSV(data: any[], filename: string): void` Exports data to a CSV file with auto-detected headers. ``` -------------------------------- ### Borsa API TypeScript Type Definitions Source: https://context7.com/ibidi/borsa-api/llms.txt Reference for TypeScript types provided by the Borsa API library. Includes definitions for API options, time periods, time intervals, and historical data query options. ```typescript import { StockData, IndexData, HistoricalData, StockDetails, HistoricalOptions, TimePeriod, TimeInterval, WatchlistItem, WatchlistResult, BorsaAPIOptions } from 'borsa-api'; // BorsaAPIOptions interface BorsaAPIOptions { baseURL?: string; // default: 'https://api.genelpara.com' timeout?: number; // ms, default: 10000 useMockData?: boolean; useRealData?: boolean; // default: true } // TimePeriod union type TimePeriod = '1d' | '5d' | '1mo' | '3mo' | '6mo' | '1y' | '2y' | '5y' | '10y' | 'ytd' | 'max'; // TimeInterval union type TimeInterval = '1d' | '1wk' | '1mo'; // HistoricalOptions interface HistoricalOptions { period?: TimePeriod; // shorthand period interval?: TimeInterval; // bar size period1?: string | Date; // explicit start date (ISO string or Date) period2?: string | Date; // explicit end date } ``` -------------------------------- ### Search Stocks by Name or Symbol Source: https://context7.com/ibidi/borsa-api/llms.txt Searches for stocks using a query string, normalizing Turkish characters for broader matching. Both accented and non-accented queries yield the same results. ```typescript import BorsaAPI = require('borsa-api'); const api = new BorsaAPI(); async function main() { // Both queries match "GARANTI BANKASI" const result1 = await api.searchStock('garanti'); const result2 = await api.searchStock('garan'); console.log(result1.map(s => s.symbol)); // ['GARAN'] console.log(result2.map(s => s.symbol)); // ['GARAN'] // Turkish characters work too const result3 = await api.searchStock('koç'); // matches 'KOC HOLDING' const result4 = await api.searchStock('koc'); // same result console.log(result3[0]?.name); // 'KOC HOLDING' } main().catch(console.error); ``` -------------------------------- ### Compare Stocks Source: https://github.com/ibidi/borsa-api/blob/main/README.md Compares the data of two specified stocks. ```APIDOC ## compareStocks(symbol1, symbol2) ### Description Compare two stocks / İki hisseyi karşılaştır ### Method `compareStocks` ### Parameters #### Path Parameters - **symbol1** (string) - Required - First stock symbol - **symbol2** (string) - Required - Second stock symbol ### Returns Promise ``` -------------------------------- ### Compare Two Stocks Source: https://github.com/ibidi/borsa-api/blob/main/README.md Compares the performance and data of two specified stock symbols. ```javascript // İki hisseyi karşılaştır async function compare() { const comparison = await api.compareStocks('THYAO', 'GARAN'); console.log(comparison); } ```