Intelligence, Advanced Charting & Trading Platform

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