Skip to content

pywry.tvchart (Mixin & Helpers)

The TVChartStateMixin is the main Python ↔ JS bridge for TradingView charts. It provides methods for updating data, managing series, controlling the UI, and implementing the full datafeed protocol.


TVChartStateMixin

pywry.tvchart.mixin.TVChartStateMixin

Bases: EmittingWidget

Mixin for TradingView Lightweight Charts state management.

Attributes

_TV_INDEX_KEY class-attribute instance-attribute

_TV_INDEX_KEY = '__pywry_tvchart_layout_index_v1'

_TV_DATA_PREFIX class-attribute instance-attribute

_TV_DATA_PREFIX = '__pywry_tvchart_layout_data_v1_'

_TV_SETTINGS_DEFAULT_KEY class-attribute instance-attribute

_TV_SETTINGS_DEFAULT_KEY = '__pywry_tvchart_settings_default_template_v1'

_TV_SETTINGS_CUSTOM_KEY class-attribute instance-attribute

_TV_SETTINGS_CUSTOM_KEY = '__pywry_tvchart_settings_custom_template_v1'

Functions

update_series

update_series(data: Any, chart_id: str | None = None, series_id: str | None = None, fit_content: bool = True) -> None

Replace all bar data for a series.

Parameters:

Name Type Description Default
data list[dict] | DataFrame

OHLCV bar data. If a DataFrame, it will be normalized via normalize_ohlcv().

required
chart_id str

Target chart instance ID.

None
series_id str

Series to update (defaults to 'main').

None
fit_content bool

Whether to auto-fit the time scale after update.

True

update_bar

update_bar(bar: dict[str, Any], chart_id: str | None = None, series_id: str | None = None) -> None

Stream a single bar update (real-time tick).

Parameters:

Name Type Description Default
bar dict

Single bar with time, open, high, low, close keys.

required
chart_id str

Target chart instance ID.

None
series_id str

Series to update (defaults to 'main').

None

add_indicator

add_indicator(indicator_data: list[dict[str, Any]], series_id: str = 'indicator', series_type: str = 'Line', series_options: dict[str, Any] | None = None, chart_id: str | None = None) -> None

Add an indicator overlay series to the chart.

Parameters:

Name Type Description Default
indicator_data list[dict]

List of {time, value} dicts for the indicator line.

required
series_id str

Unique identifier for this indicator series.

'indicator'
series_type str

Series type: 'Line', 'Histogram', 'Area', etc.

'Line'
series_options dict

Options for the series (color, lineWidth, etc.).

None
chart_id str

Target chart instance ID.

None

remove_indicator

remove_indicator(series_id: str, chart_id: str | None = None) -> None

Remove an indicator series from the chart.

Parameters:

Name Type Description Default
series_id str

The series to remove.

required
chart_id str

Target chart instance ID.

None

add_marker

add_marker(markers: list[dict[str, Any]], series_id: str | None = None, chart_id: str | None = None) -> None

Add markers (buy/sell signals) to a series.

Parameters:

Name Type Description Default
markers list[dict]

List of marker dicts with time, position ('aboveBar'/'belowBar'), color, shape ('arrowUp'/'arrowDown'/'circle'), and text keys.

required
series_id str

Target series (defaults to 'main').

None
chart_id str

Target chart instance ID.

None

add_price_line

add_price_line(price: float, color: str = '#2196F3', line_width: int = 1, title: str = '', series_id: str | None = None, chart_id: str | None = None) -> None

Add a horizontal price line to a series.

Parameters:

Name Type Description Default
price float

Price level for the line.

required
color str

Line color.

'#2196F3'
line_width int

Line width in pixels.

1
title str

Label text for the price line.

''
series_id str

Target series (defaults to 'main').

None
chart_id str

Target chart instance ID.

None

set_visible_range

set_visible_range(from_time: int, to_time: int, chart_id: str | None = None) -> None

Set the visible time range on the chart.

Parameters:

Name Type Description Default
from_time int

Start time as Unix epoch seconds.

required
to_time int

End time as Unix epoch seconds.

required
chart_id str

Target chart instance ID.

None

fit_content

fit_content(chart_id: str | None = None) -> None

Auto-fit the chart to show all data.

Parameters:

Name Type Description Default
chart_id str

Target chart instance ID.

None

apply_chart_options

apply_chart_options(chart_options: dict[str, Any] | None = None, series_options: dict[str, Any] | None = None, series_id: str | None = None, chart_id: str | None = None) -> None

Apply options to the chart or a specific series.

Parameters:

Name Type Description Default
chart_options dict

Chart-level options (layout, grid, crosshair, etc.).

None
series_options dict

Series-level options (colors, line width, etc.).

None
series_id str

Target series for series_options.

None
chart_id str

Target chart instance ID.

None

request_tvchart_state

request_tvchart_state(chart_id: str | None = None, context: dict[str, Any] | None = None) -> None

Request the current chart state (viewport, series info).

The frontend responds with a 'tvchart:state-response' event.

Parameters:

Name Type Description Default
chart_id str

Target chart instance ID.

None
context dict

Context data to echo back in the response. Useful for correlating state requests during reloads or view/context switches managed by the application shell.

None

respond_tvchart_datafeed_config

respond_tvchart_datafeed_config(request_id: str, config: dict[str, Any] | None = None, chart_id: str | None = None, error: str | None = None) -> None

Respond with datafeed configuration (onReady).

Parameters:

Name Type Description Default
request_id str

Correlation ID from the incoming tvchart:datafeed-config-request.

required
config dict

Datafeed configuration dict (supported_resolutions, exchanges, etc.).

None
chart_id str

Target chart instance ID.

None
error str

Error message; the frontend will reject the onReady promise.

None
request_tvchart_symbol_search(query: str, request_id: str, chart_id: str | None = None, exchange: str = '', symbol_type: str = '', limit: int = 20) -> None

Request dynamic symbol search results from the host.

Parameters:

Name Type Description Default
query str

User-typed search string.

required
request_id str

Correlation ID for the response.

required
chart_id str

Target chart instance ID.

None
exchange str

Exchange filter (empty string for all).

''
symbol_type str

Symbol type filter (empty string for all).

''
limit int

Maximum number of results to return.

20
respond_tvchart_symbol_search(request_id: str, items: list[dict[str, Any]], chart_id: str | None = None, query: str | None = None, error: str | None = None) -> None

Respond with symbol search results for a datafeed request.

Parameters:

Name Type Description Default
request_id str

Correlation ID from the incoming search request.

required
items list of dict

Search result items, each with symbol, full_name, description, exchange, type keys.

required
chart_id str

Target chart instance ID.

None
query str

Echo the original query for client-side dedup.

None
error str

Error message; rejects the search promise.

None

request_tvchart_symbol_resolve

request_tvchart_symbol_resolve(symbol: str, request_id: str, chart_id: str | None = None) -> None

Request full metadata for a specific symbol from the host.

Parameters:

Name Type Description Default
symbol str

Symbol name to resolve (e.g. "AAPL").

required
request_id str

Correlation ID for the response.

required
chart_id str

Target chart instance ID.

None

respond_tvchart_symbol_resolve

respond_tvchart_symbol_resolve(request_id: str, symbol_info: dict[str, Any] | None, chart_id: str | None = None, error: str | None = None) -> None

Respond with resolved symbol metadata for a datafeed request.

Parameters:

Name Type Description Default
request_id str

Correlation ID from the incoming resolve request.

required
symbol_info dict or None

Full symbol metadata matching TVChartSymbolInfo shape.

required
chart_id str

Target chart instance ID.

None
error str

Error message; rejects the resolve promise.

None

request_tvchart_history

request_tvchart_history(symbol: str, resolution: str, from_time: int, to_time: int, request_id: str, chart_id: str | None = None, count_back: int | None = None, first_data_request: bool = False) -> None

Request historical bars using the datafeed contract.

Parameters:

Name Type Description Default
symbol str

Symbol name (e.g. "AAPL").

required
resolution str

Bar resolution string ("1", "60", "1D", etc.).

required
from_time int

Start of the requested range (UNIX seconds).

required
to_time int

End of the requested range (UNIX seconds).

required
request_id str

Correlation ID for the response.

required
chart_id str

Target chart instance ID.

None
count_back int

Preferred number of bars counting back from to_time.

None
first_data_request bool

True on the very first load for a symbol.

False

respond_tvchart_history

respond_tvchart_history(request_id: str, bars: list[dict[str, Any]], chart_id: str | None = None, status: str = 'ok', no_data: bool | None = None, next_time: int | None = None, error: str | None = None) -> None

Respond with historical bars for a datafeed history request.

Parameters:

Name Type Description Default
request_id str

Correlation ID from the incoming history request.

required
bars list of dict

OHLCV bar dicts with time, open, high, low, close keys (volume optional).

required
chart_id str

Target chart instance ID.

None
status str

"ok" on success, "error" on failure.

'ok'
no_data bool

True when no more historical data is available.

None
next_time int

Earliest timestamp with data, used for scrollback hinting.

None
error str

Error message; rejects the history promise.

None

respond_tvchart_bar_update

respond_tvchart_bar_update(listener_guid: str, bar: dict[str, Any], chart_id: str | None = None) -> None

Push a real-time bar update to a subscribed listener.

Parameters:

Name Type Description Default
listener_guid str

Subscription GUID from the tvchart:datafeed-subscribe event.

required
bar dict

OHLCV bar dict with time, open, high, low, close keys (volume optional).

required
chart_id str

Target chart instance ID.

None

respond_tvchart_reset_cache

respond_tvchart_reset_cache(listener_guid: str, chart_id: str | None = None) -> None

Signal that cached bar data for a listener should be reset.

Parameters:

Name Type Description Default
listener_guid str

Subscription GUID from the tvchart:datafeed-subscribe event.

required
chart_id str

Target chart instance ID.

None

respond_tvchart_marks

respond_tvchart_marks(request_id: str, marks: list[dict[str, Any]], chart_id: str | None = None, error: str | None = None) -> None

Respond with chart marks for a getMarks request.

Parameters:

Name Type Description Default
request_id str

Correlation ID from the incoming marks request.

required
marks list of dict

Mark objects with id, time, color, text, etc.

required
chart_id str

Target chart instance ID.

None
error str

Error message; rejects the marks promise.

None

respond_tvchart_timescale_marks

respond_tvchart_timescale_marks(request_id: str, marks: list[dict[str, Any]], chart_id: str | None = None, error: str | None = None) -> None

Respond with timescale marks for a getTimescaleMarks request.

Parameters:

Name Type Description Default
request_id str

Correlation ID from the incoming timescale marks request.

required
marks list of dict

Timescale mark objects with id, time, color, label, tooltip keys.

required
chart_id str

Target chart instance ID.

None
error str

Error message; rejects the timescale marks promise.

None

respond_tvchart_server_time

respond_tvchart_server_time(request_id: str, time: int, chart_id: str | None = None, error: str | None = None) -> None

Respond with server time (unix seconds, no milliseconds).

Parameters:

Name Type Description Default
request_id str

Correlation ID from the incoming server-time request.

required
time int

Current server time as UNIX seconds.

required
chart_id str

Target chart instance ID.

None
error str

Error message; rejects the server-time promise.

None

_wire_datafeed_provider

_wire_datafeed_provider(provider: DatafeedProvider, label: str | None = None) -> None

Register all datafeed event handlers for provider.

This eliminates the boilerplate each adapter would otherwise need to duplicate. Call once after the provider is ready (e.g. after its config has been fetched).

The host class must implement on(event, callback) (which PyWry, InlineWidget, and PyWryWidget all do).

Parameters:

Name Type Description Default
provider DatafeedProvider

The datafeed provider instance.

required
label str or None

Window label to register handlers on. If None, registers on all active windows (default on() behavior).

None

_wire_data_request_handler

_wire_data_request_handler(provider: DatafeedProvider, label: str | None = None) -> None

Wire the tvchart:data-request handler for interval changes.

When the user changes the interval, the JS toolbar emits tvchart:data-request. We call provider.get_bars() to fetch data from the upstream source (e.g. UDF server) and respond with tvchart:data-response containing the bars. The JS then destroys and recreates the chart with the new data.

_wire_core_handlers

_wire_core_handlers(provider: DatafeedProvider, label: str | None = None) -> None

Wire config, search, resolve, and history handlers.

_wire_subscription_handlers

_wire_subscription_handlers(provider: DatafeedProvider, label: str | None = None) -> None

Wire subscribe/unsubscribe bar-update handlers.

_wire_optional_handlers

_wire_optional_handlers(provider: DatafeedProvider, label: str | None = None) -> None

Wire marks, timescale marks, and server time handlers.

_wire_chart_storage

_wire_chart_storage(user_id: str = 'default') -> None

Register event handlers for the server storage backend.

The JS server adapter emits tvchart:storage-set and tvchart:storage-remove on every write/delete. This method translates those events into ChartStore calls so data is persisted on the Python side.

Parameters:

Name Type Description Default
user_id str

Owner identity for the chart store.

'default'

_normalize_tvchart_data staticmethod

_normalize_tvchart_data(data: Any) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]

Convert data into bars and volume lists.

Parameters:

Name Type Description Default
data list[dict] | DataFrame

OHLCV data.

required

Returns:

Type Description
tuple[list[dict], list[dict]]

(bars, volume) ready for the JS frontend.


Data Normalization

pywry.tvchart.normalize.normalize_ohlcv

normalize_ohlcv(data: Any, *, symbol_col: str | None = None, max_bars: int = 10000) -> TVChartData

Convert Python data formats to normalized TVChartData.

Parameters:

Name Type Description Default
data Any

DataFrame, list of dicts, or dict of lists.

required
symbol_col str or None

Column name for multi-series grouping.

None
max_bars int

Maximum bars per series.

10000

Returns:

Type Description
TVChartData

Raises:

Type Description
ValueError

If required columns cannot be resolved.


Toolbar Builder

pywry.tvchart.toolbars.build_tvchart_toolbars

build_tvchart_toolbars(intervals: list[str] | None = None, selected_interval: str | None = None, *, theme: str | None = None) -> list[Any]

Build the default toolbar set for a TradingView chart.

Parameters:

Name Type Description Default
intervals list[str] | None

Data-frequency intervals the user can switch between. Only intervals that can actually be resolved from the underlying data (or that the developer explicitly wants) should be listed. Pass None (default) to omit the interval selector entirely. Examples: ["1d", "1w", "1M"], ["1m", "5m", "1h", "1d"].

None
selected_interval str | None

Which interval is initially active. Falls back to the first entry in intervals.

None
theme str | None

Active theme ("dark" or "light"). Controls the initial state of the dark-mode toggle. Defaults to "dark" when None.

None

Returns:

Type Description
list

Four :class:Toolbar objects: header (top), drawing tools (left), time-range presets (bottom), and OHLC legend overlay (inside).