@davoodmehraban89 / VELYQOR / commits / 66dd377
Fork 0

Intelligence, Advanced Charting & Trading Platform

feat(chart-ui): scaffold client-only Lightweight Charts v5 candlestick and reference-line component

davoodmehraban89 committed Oct 12, 2026 at 00:18 UTC 66dd3771016db87c2afa99f7d1dc20fa6643a2e9
1 file changed +180
packages/chart-ui/src/LightweightMarketChart.tsx new
+180
@@ -0,0 +1,180 @@
1 +"use client";
2 +import React,{useEffect,useRef,useState} from "react";
3 +import {
4 + createChart,CandlestickSeries,LineSeries,
5 + type IChartApi,type ISeriesApi,type Time,type UTCTimestamp,
6 +} from "lightweight-charts";
7 +
8 +type Quality="GOOD"|"DEGRADED"|"STALE"|"INVALID";
9 +type Point={date:string;close:number;quality:Quality};
10 +type Candle={openTime:string;sessionDate?:string;open:string|number;high:string|number;low:string|number;close:string|number;quality:Quality};
11 +type History={
12 + ok:boolean;symbol:string;source:string;storage:string;
13 + dataKind:"source_ohlc"|"daily_reference_point_not_ohlc"|"reference_point";
14 + timeframe?:string;series:(Point|Candle)[];quoteCurrency?:string;unit?:string;
15 + attribution?:string;rights?:string;usageNotice?:string;
16 +};
17 +type Frame={type:"market.update";version:1;sequence:number;publishedAt:string;
18 + payload:{symbol:string;dataKind:"reference_point"|"source_ohlc";source:string;unit:string;sourceTimestamp:string;
19 + quality:Quality;timeframe?:string;price?:number|string;openTime?:string;open?:number|string;high?:number|string;low?:number|string;close?:number|string}};
20 +type Props={
21 + symbol:string;from:string;to:string;timeframe:"1h"|"1d";
22 + // Backend owns auth, provider selection, licensing and signed database credentials.
23 + historyEndpoint:string; websocketUrl?:string; className?:string;
24 +};
25 +function safeTime(t:string,day:boolean):Time{
26 + if(day){
27 + const date=t.slice(0,10);
28 + if(!/^\d{4}-\d{2}-\d{2}$/.test(date)||Number.isNaN(Date.parse(date+"T00:00:00Z")))throw Error("Invalid market day");
29 + return date;
30 + }
31 + const value=Date.parse(t);
32 + if(!Number.isFinite(value))throw Error("Invalid UTC market timestamp");
33 + return Math.floor(value/1000) as UTCTimestamp;
34 +}
35 +function pointValue(p:Point):number{
36 + if(!Number.isFinite(p.close)||p.close<=0)throw Error("Invalid reference rate");
37 + return p.close;
38 +}
39 +function candleValue(c:Candle){
40 + const [open,high,low,close]=[c.open,c.high,c.low,c.close].map(Number);
41 + if(![open,high,low,close].every(n=>Number.isFinite(n)&&n>0)||low>open||low>close||high<open||high<close)throw Error("Invalid provider OHLC");
42 + return {open,high,low,close};
43 +}
44 +export function LightweightMarketChart({symbol,from,to,timeframe,historyEndpoint,websocketUrl,className}:Props){
45 + const container=useRef<HTMLDivElement>(null);
46 + const chartRef=useRef<IChartApi|null>(null);
47 + const seriesRef=useRef<ISeriesApi<"Candlestick">|ISeriesApi<"Line">|null>(null);
48 + const lastEvent=useRef(new Map<string,number>());
49 + const [status,setStatus]=useState("در انتظار تاریخچه معتبر");
50 + const [notice,setNotice]=useState("");
51 + useEffect(()=>{
52 + if(!container.current)return;
53 + const chart=createChart(container.current,{
54 + width:Math.max(300,container.current.clientWidth),height:430,
55 + layout:{background:{color:"#0b1423"},textColor:"#d8e8f6",attributionLogo:true},
56 + grid:{vertLines:{color:"#243246"},horzLines:{color:"#243246"}},
57 + timeScale:{timeVisible:timeframe!=="1d"},
58 + });
59 + chartRef.current=chart;
60 + const observer=new ResizeObserver(items=>{
61 + const width=items[0]?.contentRect.width;
62 + if(width&&chartRef.current)chart.applyOptions({width:Math.floor(width)});
63 + });
64 + observer.observe(container.current);
65 + const stop=new AbortController();
66 + let disposed=false,ws:WebSocket|undefined,retry:ReturnType<typeof setTimeout>|undefined,attempt=0;
67 + let kind:History["dataKind"]|null=null;
68 + async function load(){
69 + try{
70 + const url=new URL(historyEndpoint,window.location.href);
71 + // Select only bounded, canonical market symbols; never interpolate SQL.
72 + if(!/^[A-Z0-9_]{3,48}$/.test(symbol))throw Error("نماد نامعتبر");
73 + url.searchParams.set("symbol",symbol);
74 + url.searchParams.set("from",from);url.searchParams.set("to",to);
75 + url.searchParams.set("timeframe",timeframe);
76 + const response=await fetch(url.toString(),{signal:stop.signal,credentials:"same-origin"});
77 + if(!response.ok)throw Error("HTTP "+response.status);
78 + const data=await response.json() as History;
79 + if(!data.ok||data.symbol!==symbol||!Array.isArray(data.series))throw Error("پاسخ تاریخچه نامعتبر است");
80 + if(data.rights&&data.rights!=="approved_public")throw Error("مجوز نمایش داده تأیید نشده");
81 + if(data.dataKind!=="source_ohlc"&&data.dataKind!=="reference_point"&&data.dataKind!=="daily_reference_point_not_ohlc")throw Error("نوع داده پشتیبانی نمی‌شود");
82 + if(data.series.length===0)throw Error("داده تاریخی قابل نمایش نیست");
83 + const isCandle=data.dataKind==="source_ohlc";
84 + if(isCandle&&data.timeframe&&data.timeframe!==timeframe)throw Error("بازه زمانی کندل ناسازگار است");
85 + const mapped=isCandle?data.series.map(p=>{
86 + if(!("openTime" in p))throw Error("Missing source candle");
87 + return {time:safeTime(timeframe==="1d"?(p.sessionDate??p.openTime):p.openTime,timeframe==="1d"),...candleValue(p)};
88 + }):data.series.map(p=>{
89 + if(!("date" in p))throw Error("Missing point timestamp");
90 + return {time:safeTime(p.date,true),value:pointValue(p)};
91 + });
92 + for(let i=1;i<mapped.length;i++){
93 + // Data must already be sorted and deduplicated by the provider adapter.
94 + if(String(mapped[i].time)<=String(mapped[i-1].time))throw Error("داده نامرتب یا تکراری");
95 + }
96 + if(disposed)return;
97 + if(seriesRef.current)chart.removeSeries(seriesRef.current);
98 + if(isCandle){
99 + const s=chart.addSeries(CandlestickSeries,{
100 + upColor:"#1cc38b",downColor:"#f26b6b",wickUpColor:"#1cc38b",wickDownColor:"#f26b6b",
101 + borderVisible:false,
102 + });
103 + s.setData(mapped as {time:Time;open:number;high:number;low:number;close:number}[]);
104 + seriesRef.current=s;
105 + }else{
106 + const s=chart.addSeries(LineSeries,{color:"#43b9e8",lineWidth:2});
107 + s.setData(mapped as {time:Time;value:number}[]);
108 + seriesRef.current=s;
109 + }
110 + kind=data.dataKind;
111 + chart.timeScale().fitContent();
112 + setStatus(data.source+" · "+data.storage+" · "+data.series.length+" مشاهده");
113 + setNotice(isCandle?"کندل‌های منبع · کیفیت و حقوق بازنشر را بررسی کنید":
114 + "نرخ مرجع/نقطه قیمت · نه کندل OHLC؛ حجم و باز/بسته‌شدن روزانه ادعا نمی‌شود.");
115 + }catch(err){
116 + if(!disposed&&!stop.signal.aborted){setStatus("تاریخچه در دسترس نیست");setNotice(String(err instanceof Error?err.message:err));}
117 + }
118 + }
119 + void load();
120 + function connect(){
121 + if(disposed||!websocketUrl)return;
122 + if(!websocketUrl.startsWith("wss://")){setNotice("فقط اتصال رمزنگاری‌شده WebSocket مجاز است");return;}
123 + ws=new WebSocket(websocketUrl);
124 + ws.onopen=()=>{
125 + attempt=0;
126 + ws?.send(JSON.stringify({type:"subscribe",version:1,symbols:[symbol],timeframe}));
127 + };
128 + ws.onmessage=(event)=>{
129 + try{
130 + if(typeof event.data!=="string"||event.data.length>8192)return;
131 + const frame=JSON.parse(event.data) as Frame;
132 + if(frame.type!=="market.update"||frame.version!==1||!Number.isSafeInteger(frame.sequence))return;
133 + const p=frame.payload;
134 + if(!p||p.symbol!==symbol||p.quality==="INVALID"||!seriesRef.current)return;
135 + if((kind==="source_ohlc")!==(p.dataKind==="source_ohlc"))return;
136 + if(p.dataKind==="source_ohlc"&&p.timeframe!==timeframe)return;
137 + const channel=p.symbol+"|"+(p.timeframe??"point")+"|"+p.source;
138 + const previous=lastEvent.current.get(channel)??0;
139 + if(frame.sequence<=previous)return;
140 + lastEvent.current.set(channel,frame.sequence);
141 + if(previous!==0&&frame.sequence!==previous+1){
142 + setNotice("شکاف در جریان داده؛ بازخوانی تاریخچه از REST");
143 + void load();
144 + return;
145 + }
146 + if(p.dataKind==="source_ohlc"){
147 + if(!p.openTime)return;
148 + const value=candleValue(p as Candle);
149 + (seriesRef.current as ISeriesApi<"Candlestick">).update({
150 + time:safeTime(p.openTime,timeframe==="1d"),...value,
151 + });
152 + }else{
153 + if(p.price===undefined)return;
154 + const value=Number(p.price);
155 + if(!Number.isFinite(value)||value<=0)return;
156 + (seriesRef.current as ISeriesApi<"Line">).update({time:safeTime(p.sourceTimestamp,true),value});
157 + }
158 + }catch{setNotice("یک پیام زنده نامعتبر کنار گذاشته شد");}
159 + };
160 + ws.onclose=()=>{
161 + if(disposed)return;
162 + const delay=Math.min(30_000,1000*2**Math.min(attempt++,5));
163 + retry=setTimeout(()=>{void load();connect();},delay);
164 + };
165 + ws.onerror=()=>ws?.close();
166 + }
167 + connect();
168 + return ()=>{
169 + disposed=true;stop.abort();
170 + if(retry)clearTimeout(retry);
171 + ws?.close();observer.disconnect();chart.remove();
172 + chartRef.current=null;seriesRef.current=null;lastEvent.current.clear();
173 + };
174 + },[symbol,from,to,timeframe,historyEndpoint,websocketUrl]);
175 + return <section className={className} aria-label={"نمودار بازار "+symbol}>
176 + <div ref={container} role="img" aria-label={symbol+" · نمودار واقعی با Lightweight Charts"}/>
177 + <p role="status">{status}</p><p>{notice}</p>
178 + <small>Charting library by <a href="https://www.tradingview.com/" target="_blank" rel="noopener noreferrer">TradingView</a> · Lightweight Charts™</small>
179 + </section>;
180 +}