OpenStock is an open-source alternative to expensive market platforms. Track real-time prices, set personalized alerts, and explore detailed company insights — built openly, for everyone, forever free.
fix(stocks): no more stuck charts for blocked exchanges or Hong Kong
ravixalgorithm130a69734d26
diff --git a/MARKET_SUPPORT.md b/MARKET_SUPPORT.mdindex db5fb83..d9a2dfc 100644--- a/MARKET_SUPPORT.md+++ b/MARKET_SUPPORT.md@@ -11,15 +11,16 @@ What OpenStock can show depends on two free data sources. This table was tested| 🇦🇺 Australia (ASX) | Delayed | No || 🇮🇳 India, through BSE (`.BO`; `.NS` symbols are charted on BSE) | End of day | No || 🇩🇪 Germany (Xetra) | End of day | No |-| India NSE, London (LSE), Tokyo (TSE), Hong Kong (HKEX) | Blocked in embeds | No |+| India NSE (charted on BSE instead) | Blocked in embeds | No |+| London, Tokyo, Hong Kong, Korea, Taiwan, Singapore, New Zealand, Thailand, Malaysia, Istanbul, TSX Venture, Mexico, Johannesburg | Candle chart blocked; financials, technicals and profile work | No || Index tickers such as NIFTY, FTSE 100, DAX, Nikkei 225, Hang Seng | Blocked in embeds | No |## What that means in the app- **Dashboard:** pick a market (US, India, Germany, Canada, Australia, Crypto, Forex). US and crypto tiles use our own cached quotes; the others use TradingView quote tiles.- **Stock pages:** symbols Finnhub can price get the full header (live price, day range, market cap). Others get TradingView's quote panel.-- **Alerts:** US stocks and crypto only, because the alert checker needs a quote source it can call every five minutes.-- **Search:** Finnhub search returns listings worldwide; blocked exchanges will show TradingView's "only available on TradingView" message in charts.+- **Alerts:** an OpenStock Cloud feature (or self-hosted in realtime mode). US stocks and crypto only, because the alert checker needs a quote source it can call every five minutes.+- **Search:** Finnhub search returns listings worldwide. On exchanges whose chart is blocked, the stock page links to the chart on TradingView instead (the list is `CHART_BLOCKED_EXCHANGES` in `lib/utils.ts`, each confirmed with two tickers).## Adding a marketdiff --git a/__tests__/utils.test.ts b/__tests__/utils.test.tsindex 49e6b71..86d0c28 100644--- a/__tests__/utils.test.ts+++ b/__tests__/utils.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest';import {formatSymbolForTradingView,+ isChartEmbeddable,formatMarketCapValue,formatChangePercent,getChangeColorClass,@@ -32,7 +33,8 @@ describe('formatSymbolForTradingView', () => {});it('maps Hong Kong (.HK) to HKEX prefix', () => {- expect(formatSymbolForTradingView('0700.HK')).toBe('HKEX:0700');+ // TradingView drops Finnhub's zero padding: HKEX:0700 is an invalid symbol there+ expect(formatSymbolForTradingView('0700.HK')).toBe('HKEX:700');});it('maps Shanghai (.SS) to SSE prefix', () => {@@ -222,3 +224,17 @@ describe('calculateNewsDistribution', () => {expect(calculateNewsDistribution(10).itemsPerSymbol).toBe(1);});});++describe('isChartEmbeddable', () => {+ it('allows exchanges whose candle chart TradingView embeds', () => {+ for (const s of ['AAPL', 'BINANCE:BTCUSDT', 'BSE:RELIANCE', 'XETR:SAP', 'TSX:SHOP', 'PSECZ:CEZ']) expect(isChartEmbeddable(s)).toBe(true);+ });++ it('flags exchanges TradingView refuses in free embeds', () => {+ for (const s of ['TSE:7203', 'HKEX:700', 'LSE:VOD', 'KRX:005930']) expect(isChartEmbeddable(s)).toBe(false);+ });++ it('maps Prague to PSECZ, not the Philippine PSE', () => {+ expect(formatSymbolForTradingView('CEZ.PR')).toBe('PSECZ:CEZ');+ });+});diff --git a/app/(root)/stocks/[symbol]/page.tsx b/app/(root)/stocks/[symbol]/page.tsxindex 3c750cd..616ae45 100644--- a/app/(root)/stocks/[symbol]/page.tsx+++ b/app/(root)/stocks/[symbol]/page.tsx@@ -1,4 +1,5 @@import { Suspense } from "react";+import { CandlestickChart } from "lucide-react";import TradingViewWidget from "@/components/TradingViewWidget";import StockHeader, { StockHeaderSkeleton } from "@/components/stocks/StockHeader";import StockSentimentCard from "@/components/stocks/StockSentimentCard";@@ -10,7 +11,7 @@ import {COMPANY_FINANCIALS_WIDGET_CONFIG,} from "@/lib/constants";import { getStockSentimentInsights } from '@/lib/actions/adanos.actions';-import { formatSymbolForTradingView } from '@/lib/utils';+import { formatSymbolForTradingView, isChartEmbeddable, tradingViewSymbolUrl } from '@/lib/utils';const scriptUrl = `https://s3.tradingview.com/external-embedding/embed-widget-`;@@ -38,14 +39,30 @@ export default async function StockDetails({ params }: StockDetailsPageProps) {<div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(320px,400px)]"><div className="flex min-w-0 flex-col gap-3">- <Panel title="Chart" sub="Live from TradingView · switch interval and style in the chart">- <TradingViewWidget- scriptUrl={`${scriptUrl}advanced-chart.js`}- config={CANDLE_CHART_WIDGET_CONFIG(tvSymbol)}- height={560}- allowExpand- />- </Panel>+ {isChartEmbeddable(tvSymbol) ? (+ <Panel title="Chart" sub="Live from TradingView · switch interval and style in the chart">+ <TradingViewWidget+ scriptUrl={`${scriptUrl}advanced-chart.js`}+ config={CANDLE_CHART_WIDGET_CONFIG(tvSymbol)}+ height={560}+ allowExpand+ />+ </Panel>+ ) : (+ // TradingView refuses this exchange's chart in embeds; say so instead of showing its error+ <Panel title="Chart" sub="Only on TradingView for this exchange">+ <div className="empty-state py-14">+ <span className="empty-icon"><CandlestickChart className="size-5" /></span>+ <h3>Chart not available here</h3>+ <p className="max-w-80 text-[13px]">+ TradingView doesn’t license {tvSymbol.split(':')[0]} charts for other sites. Financials, technicals and the profile below still work.+ </p>+ <a href={tradingViewSymbolUrl(tvSymbol)} target="_blank" rel="noopener noreferrer" className="btn btn-ghost mt-2">+ Open chart on TradingView+ </a>+ </div>+ </Panel>+ )}<Panel title="Financials" sub="Income statement, balance sheet and ratios"><TradingViewWidgetscriptUrl={`${scriptUrl}financials.js`}diff --git a/lib/markets.ts b/lib/markets.tsindex d275817..5ae803c 100644--- a/lib/markets.ts+++ b/lib/markets.ts@@ -1,7 +1,8 @@// Markets OpenStock can show for free. Coverage was tested against the free data sources:// - Finnhub free: US stocks and crypto only (every other exchange returns 403).// - TradingView embeds: US, crypto, forex live; TSX + ASX delayed; BSE + XETRA end-of-day.-// NSE, LSE, Tokyo, Hong Kong and TVC indices (NIFTY, FTSE, DAX, N225, HSI) are blocked in embeds.+// NSE and TVC indices (NIFTY, FTSE, DAX, N225, HSI) are blocked in embeds; LSE, Tokyo, Hong Kong and+// others block only the candle chart (see CHART_BLOCKED_EXCHANGES in lib/utils.ts).// Adding a market = adding an entry here with symbols from an exchange that renders in embeds.import { isInternationalSymbol } from "@/lib/utils";diff --git a/lib/utils.ts b/lib/utils.tsindex 5a89571..9d383fe 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -200,7 +200,7 @@ const FINNHUB_TO_TRADINGVIEW_EXCHANGE: Record<string, string> = {'.SW': 'SIX', // SIX Swiss Exchange'.VI': 'VIE', // Vienna Stock Exchange'.WA': 'GPW', // Warsaw Stock Exchange- '.PR': 'PSE', // Prague Stock Exchange+ '.PR': 'PSECZ', // Prague Stock Exchange (TradingView's PSE is the Philippines)'.AT': 'ATHEX', // Athens Stock Exchange'.IS': 'BIST', // Borsa Istanbul@@ -216,6 +216,15 @@ const FINNHUB_TO_TRADINGVIEW_EXCHANGE: Record<string, string> = {'.JO': 'JSE', // Johannesburg Stock Exchange};+// Exchanges whose candle chart TradingView refuses in free embeds ("This symbol doesn't exist"), each confirmed+// with two tickers. Financials, technicals and profile still work for them.+// ponytail: static list, re-test with a real browser user agent if TradingView changes its licensing.+const CHART_BLOCKED_EXCHANGES = new Set(['TSE', 'HKEX', 'LSE', 'KRX', 'TWSE', 'SGX', 'NZX', 'SET', 'MYX', 'BIST', 'TSXV', 'BMV', 'JSE']);++export const isChartEmbeddable = (tvSymbol: string) => !CHART_BLOCKED_EXCHANGES.has(tvSymbol.split(':')[0]);++export const tradingViewSymbolUrl = (tvSymbol: string) => `https://www.tradingview.com/symbols/${tvSymbol.replace(':', '-')}/`;+// Listed outside the US (has a known exchange suffix like .L, .T, .NS). Class shares such as BRK.B are not.export function isInternationalSymbol(symbol: string): boolean {const upper = symbol.toUpperCase();@@ -233,8 +242,9 @@ export function formatSymbolForTradingView(symbol: string): string {for (const suffix of suffixes) {if (upperSymbol.endsWith(suffix.toUpperCase())) {- const ticker = upperSymbol.slice(0, -suffix.length);const exchange = FINNHUB_TO_TRADINGVIEW_EXCHANGE[suffix];+ // Finnhub pads Hong Kong codes (0700.HK); TradingView doesn't (HKEX:700)+ const ticker = exchange === 'HKEX' ? upperSymbol.slice(0, -suffix.length).replace(/^0+(?=\d)/, '') : upperSymbol.slice(0, -suffix.length);return `${exchange}:${ticker}`;}}