如何设置TradingView图表库实现图表自动更新?
How to Set Up Automatic Updates for TradingView Charts
Hey Marco, let's get that auto-refresh working for your TradingView chart so you don't have to manually reload the page. Here's a tailored solution using the chart library's built-in tools:
Key Fix: Combine Subscription & Periodic Refresh Logic
TradingView's widget has native methods to handle automatic data updates. We'll add this functionality directly to your existing initOnReady function.
Updated Code with Auto-Refresh
function initOnReady() { var widget = window.tvWidget = new TradingView.widget({ fullscreen: true, symbol: 'AAPL', interval: '1D', container_id: "tv_chart_container", datafeed: new Datafeeds.UDFCompatibleDatafeed("<data feed url>"), library_path: "charting_library/", locale: getParameterByName('lang') || "en", disabled_features: ["use_localstorage_for_settings"], enabled_features: ["study_templates"], charts_storage_url: 'http://{$smarty.server.HTTP_HOST}', charts_storage_api_version: "1.1", client_id: 'tradingview.com', user_id: 'public_user_id', // Run logic once the chart is fully initialized onChartReady: function() { // Map chart intervals to appropriate refresh rates (in milliseconds) const intervalRefreshMap = { '1': 60000, // 1-minute interval → refresh every 60 seconds '5': 300000, // 5-minute → every 5 minutes '15': 900000, // 15-minute → every 15 minutes '30': 1800000, // 30-minute → every 30 minutes '60': 3600000, // 1-hour → every hour '1D': 86400000 // Daily → once per day }; // Get current chart configuration const currentSymbol = widget.activeChart().symbol(); const currentInterval = widget.activeChart().interval(); // Use matching refresh rate, default to 1 minute if interval isn't mapped const refreshInterval = intervalRefreshMap[currentInterval] || 60000; // 1. Preferred method: Subscribe to real-time data pushes widget.subscribeBars( currentSymbol, currentInterval, (newBars) => { // Chart auto-updates when new data is received from your feed console.log("New data loaded:", newBars); }, (error) => { console.error("Failed to subscribe to data feed:", error); } ); // 2. Fallback: Periodically refresh the chart manually setInterval(() => { widget.activeChart().refresh(); console.log("Chart refreshed manually"); }, refreshInterval); } }); };
What This Does
onChartReadyCallback: Ensures we only run update logic after the chart is fully loaded and ready to accept data.- Interval-Specific Refresh Rates: The
intervalRefreshMapsets logical refresh times for each chart interval (no need to refresh a daily chart every minute!). subscribeBars: TradingView's official method for real-time data pushes. When your UDF feed sends new bars, the chart updates automatically without manual intervention.setInterval+refresh(): A reliable fallback if your data feed doesn't support push updates. It triggers a manual refresh at your chosen interval.
Important Notes
- Verify your UDF data feed either supports real-time push updates (for
subscribeBarsto work) or returns the latest data when itshistoryendpoint is called (for the manual refresh fallback). - If users change the chart's symbol or interval after initialization, you can add a listener to re-subscribe to the new symbol/interval for continuous updates.
内容的提问来源于stack exchange,提问作者Marco




