Save/load, news, and watchlist
Overview
This article is part of the Extend to Trading Platform sub-tutorial.
In this step, you save and load chart layouts through a localStorage adapter and fill the widget panel with the news and watchlist widgets. You also build a custom price-crossing alert from chart primitives and add controls to the chart toolbar.
1. Implement save/load with a localStorage adapter
By default Trading Platform can store layouts on your server.
For a browser-only demo, the project implements the save/load adapter contract against localStorage in src/save-load-adapter.js.
1.1. Register the adapter
The save/load adapter, auto-save settings, and broker options are all passed into createTradingPlatformOptions in the bootstrap (see the full initTradingPlatformChart).
Setting save_load_adapter is what tells Trading Platform to persist charts, drawings, and templates through your adapter instead of its server default. load_last_chart: false keeps the demo deterministic, and auto_save_delay: 5 debounces saves to every five seconds.
1.2. Understand what the adapter must implement
LocalStorageSaveLoadAdapter is a class whose methods all return promises (the contract is async). It covers five kinds of state: charts, indicator templates, drawing templates, chart templates, and — because saveload_separate_drawings_storage is enabled — drawings stored separately from the chart.
Each kind is kept in an in-memory bucket and flushed to localStorage on a one-second timer, but only when something changed (_isDirty), which avoids writing on every keystroke:
// Implements TradingView's save/load adapter contract using browser localStorage.
export class LocalStorageSaveLoadAdapter {
constructor() {
var _a, _b, _c, _d, _e;
this._charts = [];
this._studyTemplates = [];
this._drawingTemplates = [];
this._chartTemplates = [];
this._drawings = {};
this._isDirty = false;
this._charts =
(_a = this._getFromLocalStorage(storageKeys.charts)) !== null &&
_a !== void 0
? _a
: [];
this._studyTemplates =
(_b = this._getFromLocalStorage(storageKeys.studyTemplates)) !==
null && _b !== void 0
? _b
: [];
this._drawingTemplates =
(_c = this._getFromLocalStorage(storageKeys.drawingTemplates)) !==
null && _c !== void 0
? _c
: [];
this._chartTemplates =
(_d = this._getFromLocalStorage(storageKeys.chartTemplates)) !==
null && _d !== void 0
? _d
: [];
this._drawings =
(_e = this._getFromLocalStorage(storageKeys.drawings)) !== null &&
_e !== void 0
? _e
: {};
setInterval(() => {
if (this._isDirty) {
this._saveAllToLocalStorage();
this._isDirty = false;
}
}, 1000);
}
}
1.3. Save and load charts
saveChart assigns a stable ID (generating one for a new chart, or removing the previous entry when the ID already exists), stamps a timestamp, and resolves with that ID — Trading Platform stores the ID and uses it for later loads:
// Stores chart JSON and returns the stable id TradingView should use later.
saveChart(chartData) {
if (!chartData.id) {
chartData.id = this._generateUniqueChartId();
} else {
this.removeChart(chartData.id);
}
const savedChartData = Object.assign(Object.assign({}, chartData), {
id: chartData.id,
timestamp: Math.round(Date.now() / 1000),
});
this._charts.push(savedChartData);
this._isDirty = true;
return Promise.resolve(savedChartData.id);
}
The remaining chart methods (getAllCharts, getChartContent, removeChart) and the study/drawing/template methods follow the same in-memory-plus-flush pattern; see the complete file.
1.4. Save drawings separately
With saveload_separate_drawings_storage enabled, TradingView stores drawings apart from the chart and calls saveLineToolsAndGroups / loadLineToolsAndGroups.
The save side iterates the Map of sources TradingView provides (state.sources) and persists them as a plain object keyed by layout and chart ID; the load side rebuilds that object back into the Map TradingView expects. The loader also receives request metadata (_requestType, _requestContext), which this demo ignores:
// Stores drawings separately from the chart when saveload_separate_drawings_storage is enabled.
async saveLineToolsAndGroups(layoutId, chartId, state) {
const drawings = state.sources;
if (!drawings) return;
if (!this._drawings[this._getDrawingKey(layoutId, chartId)]) {
this._drawings[this._getDrawingKey(layoutId, chartId)] = {};
}
for (let [key, state] of drawings) {
if (state === null) {
delete this._drawings[this._getDrawingKey(layoutId, chartId)][key];
} else {
this._drawings[this._getDrawingKey(layoutId, chartId)][key] = state;
}
}
this._isDirty = true;
}
async loadLineToolsAndGroups(
layoutId,
chartId,
_requestType,
_requestContext
) {
if (!layoutId) {
return null;
}
const rawSources =
this._drawings[this._getDrawingKey(layoutId, chartId)];
if (!rawSources) return null;
const sources = new Map();
for (let [key, state] of Object.entries(rawSources)) {
sources.set(key, state);
}
return {
sources,
};
}
1.5. Trigger auto-save
auto_save_delay only debounces; you still tell the widget when to persist.
Subscribe to onAutoSaveNeeded and call saveChartToServer (which routes to your adapter). This lives alongside the other chart-ready subscriptions:
import { LocalStorageSaveLoadAdapter } from './save-load-adapter.js';
const saveLoadAdapter = new LocalStorageSaveLoadAdapter();
// Keep custom chart subscriptions together so future event wiring has one obvious home.
function installChartReadySubscriptions(widget, alertController) {
widget.subscribe('onAutoSaveNeeded', () => {
if (typeof widget.saveChartToServer === 'function') {
widget.saveChartToServer(null, null, {
defaultChartName: 'Default',
});
}
});
alertController.attach(widget);
}
widget.subscribe('onAutoSaveNeeded', () => {
if (typeof widget.saveChartToServer === 'function') {
widget.saveChartToServer(null, null, { defaultChartName: 'Default' });
}
});
2. Custom price alerts
Trading Platform does not include the alerts available on tradingview.com.
This step shows how to build a custom alert from chart primitives instead: a horizontal line you drop at a price, plus crossing detection driven by the datafeed's realtime ticks. It is self-contained in a createAlertController factory.
2.1. Format prices with the chart's formatter
A small helper formats a price using the chart's own price formatter, falling back to two decimals — so alert labels match the chart's precision:
function formatAlertPrice(price, chart) {
const fallback = price.toFixed(2);
try {
const formatter =
chart?.getSeries?.()?.priceFormatter?.() ??
chart?.priceFormatter?.();
const formattedPrice = formatter?.format?.(price);
return formattedPrice || fallback;
} catch {
return fallback;
}
}
2.2. Build the alert controller
The controller returns a contextMenu config and an attach(widget) method, and keeps its state (activeAlerts, previousPrice, lastPlusClickPrice) private. Read it as four cooperating pieces:
contextMenu.items_processor— adds an "Add Alert at<price>" action to the crosshair menu. It useslastPlusClickPrice, draws a horizontal line withchart.createShape, and records{ id, price }inactiveAlerts.onPlusClick— records the price the user clicked, so the menu action knows where to place the alert.onTick— on every realtime price, compares againstpreviousPriceto detect an up- or down-crossing of each alert; on a crossing it callsnotify(...), removes the line, and drops the alert.drawing_event(points_changed) — when the user drags the line, updates the stored alert price to match.
// Keeps the custom alert demo self-contained: context-menu creation, crossing detection, cleanup.
function createAlertController({ getWidget, notify }) {
let activeAlerts = [];
let previousPrice = null;
let lastPlusClickPrice = null;
return {
contextMenu: {
items_processor: async (items, actionsFactory, params) => {
if (params.menuName !== 'CrosshairMenuView') return items;
if (
lastPlusClickPrice === null ||
lastPlusClickPrice === undefined
)
return items;
const price = lastPlusClickPrice;
const chart = getWidget()?.activeChart?.();
const alertAction = actionsFactory.createAction({
actionId: 'create_custom_alert',
label: `Add Alert at ${formatAlertPrice(price, chart)}`,
onExecute: async () => {
const widget = getWidget();
const chart = widget.activeChart();
const lineId = await chart.createShape(
{ price },
{
shape: 'horizontal_line',
overrides: {
linecolor: '#ff9800',
linewidth: 2,
linestyle: 1,
},
}
);
activeAlerts.push({ id: lineId, price });
},
});
items.push(actionsFactory.createSeparator());
items.push(alertAction);
return items;
},
},
attach(widget) {
const chart = widget.activeChart();
widget.subscribe('onPlusClick', params => {
if (params.price !== undefined) {
lastPlusClickPrice = params.price;
}
});
widget.subscribe('onTick', tick => {
const currentPrice = tick.close ?? tick.price ?? tick.last;
if (currentPrice === undefined) return;
if (previousPrice !== null) {
activeAlerts = activeAlerts.filter(alert => {
const crossedUp =
previousPrice < alert.price &&
currentPrice >= alert.price;
const crossedDown =
previousPrice > alert.price &&
currentPrice <= alert.price;
if (!crossedUp && !crossedDown) return true;
const alertPrice = formatAlertPrice(alert.price, chart);
notify(
'Alert Triggered',
`Price crossed your alert at ${alertPrice}`
);
try {
chart.removeEntity(alert.id);
} catch {
// The line may already be gone if the user removed it manually.
}
return false;
});
}
previousPrice = currentPrice;
});
widget.subscribe('drawing_event', (id, type) => {
if (type !== 'points_changed') return;
window.setTimeout(() => {
const alert = activeAlerts.find(alert => alert.id === id);
if (!alert) return;
const shape = chart.getShapeById(id);
const newPrice = shape?.getPoints()[0]?.price;
if (newPrice === undefined) return;
alert.price = newPrice;
shape.setProperties({
text: `Alert: ${formatAlertPrice(newPrice, chart)}`,
});
}, 50);
});
},
};
}
2.3. Notify through the broker host
The controller is created with a notify callback wired to the broker host captured in the broker article, and attached once the chart is ready. Routing through the host makes alerts appear as native trading notifications:
const alertController = createAlertController({
getWidget: () => wdg,
notify: (title, message) => {
brokerHost?.showNotification?.(title, message, 1);
},
});
createAlertController is created before the widget so its contextMenu can be passed into the widget options, and alertController.attach(wdg) runs inside onChartReady (both shown in the bootstrap).
3. News via a same-origin RSS proxy
Trading Platform's news widget reads an rss_news_feed option.
CoinDesk's RSS feed does not send browser CORS headers, so the project proxies it through the local server (server.mjs) and points the widget at the same-origin route.
3.1. Define the feed
src/news.js exports the feed object the widget reads. Both the default and crypto categories point at the local proxy route:
const COINDESK_RSS_PROXY_URL = '/api/news/coindesk-rss';
export const CRYPTO_RSS_NEWS_FEED = {
default: { url: COINDESK_RSS_PROXY_URL, name: 'CoinDesk' },
crypto: { url: COINDESK_RSS_PROXY_URL, name: 'CoinDesk' },
};
export const CRYPTO_RSS_TITLE = 'CoinDesk';
3.2. Proxy and sanitize the feed server-side
server.mjs routes the API request first, then falls through to static files.
It fetches the upstream feed server-side, caches it briefly, strips HTML tags from titles/descriptions, and returns it as application/rss+xml so the browser can consume it from the app's own origin:
// Handles the one dynamic route in the project: same-origin CoinDesk RSS.
async function handleCoinDeskNews(request, response) {
if (request.method !== 'GET' && request.method !== 'HEAD') {
response.writeHead(405, { Allow: 'GET, HEAD' });
response.end('Method Not Allowed');
return;
}
try {
const payload = await fetchCoinDeskRss();
writeNewsHeaders(response, payload);
response.writeHead(200);
if (request.method === 'HEAD') {
response.end();
return;
}
response.end(payload.body);
} catch (error) {
console.error('[news proxy] Error:', error);
response.writeHead(502, {
'Content-Type': 'text/plain; charset=utf-8',
});
response.end('Unable to load CoinDesk RSS feed.');
}
}
// Routes API requests first, then falls through to serve-handler for static files.
async function handleRequest(request, response) {
const url = new URL(
request.url ?? '/',
`http://${request.headers.host ?? `${DEFAULT_HOST}:${DEFAULT_PORT}`}`
);
if (url.pathname === '/api/news/coindesk-rss') {
await handleCoinDeskNews(request, response);
return;
}
if (url.pathname === '/') {
request.url = '/index.html';
} else if (HTML_ROUTE_PATHS.has(url.pathname)) {
request.url = `${HTML_ROUTE_PATHS.get(url.pathname)}${url.search}`;
}
writeStaticHeaders(response);
await handler(request, response, {
public: '.',
cleanUrls: false,
directoryListing: false,
});
}
4. Watchlist
The watchlist is seeded through widgetbar.watchlist_settings.default_symbols. The list is plain text, with '###Binance' acting as a section header above the symbols:
const WATCHLIST_SYMBOLS = [
'###Binance',
'Binance:BTC/USDT',
'Binance:ETH/USDT',
'Binance:BNB/USDT',
'Binance:SOL/USDT',
'Binance:ADA/USDT',
'Binance:ETH/BTC',
'Binance:LTC/USDT',
'Binance:XRP/USDT',
'Binance:XRP/BTC',
];
5. Toolbar
Toolbar controls are installed after widget.headerReady() resolves: a Reset button, a symbol dropdown, a show/hide indicators-and-drawings toggle, a theme switch, and a documentation link:
// Installs trading toolbar controls after the TradingView header has finished mounting.
function installToolbar(widget) {
widget.headerReady().then(() => {
addResetButton(widget);
addSymbolDropdown(widget);
addVisibilityButton(widget);
const themeSwitchCheckbox = addThemeToggle(widget);
const documentationButton = addDocumentationButton(widget);
wireRovingTabindex(themeSwitchCheckbox, documentationButton);
});
}
Result
You now have a complete Trading Platform integration on the same Binance datafeed:
- Broker trading with the account manager, orders, positions, and brackets.
- Live watchlist/details quotes and a live DOM.
- Persistent layouts, drawings, and templates.
- Custom price-crossing alerts and a clean CoinDesk news feed.
Complete code
The complete file for this part lives in the tutorial repository:
What's next?
- Broker API: replace BrokerDemo with a real trading backend.
- Trading Platform overview: explore the full set of trading widgets and options.
- Datafeed Common Issues: review issues you may hit when serving quotes and depth.