Skip to content

pywry

Main PyWry application class and top-level functions.


PyWry Class

pywry.app.PyWry

PyWry(mode: WindowMode = NEW_WINDOW, theme: ThemeMode = DARK, title: str = 'PyWry', width: int = 800, height: int = 600, settings: PyWrySettings | None = None, hot_reload: bool = False)

Bases: GridStateMixin, PlotlyStateMixin, TVChartStateMixin, ToolbarStateMixin

Main PyWry application for displaying content in native windows.

Supports three window modes: - NEW_WINDOW: Creates a new window for each show() call - SINGLE_WINDOW: Reuses one window, replaces content - MULTI_WINDOW: Multiple independent windows

Examples:

>>> pywry = PyWry(mode=WindowMode.SINGLE_WINDOW)
>>> pywry.show("<h1>Hello World</h1>")

Initialize PyWry.

Parameters:

Name Type Description Default
mode WindowMode

Window mode to use.

NEW_WINDOW
theme ThemeMode

Default theme mode.

DARK
title str

Default window title.

'PyWry'
width int

Default window width.

800
height int

Default window height.

600
settings PyWrySettings or None

Configuration settings. If None, loads from env/files.

None
hot_reload bool

Enable hot reload for CSS/JS files.

False

Attributes

settings property

settings: PyWrySettings

Get the current settings.

theme property writable

theme: ThemeMode

Get the current theme mode.

is_authenticated property

is_authenticated: bool

Check if the app has a successful authentication result.

default_config property

default_config: WindowConfig

Return the mutable default WindowConfig.

Callers may set builder-level fields directly::

app.default_config.resizable = False
app.default_config.transparent = True

Functions

login

login(provider: Any | None = None, on_login: Callable[[Any], None] | None = None, on_logout: Callable[[], None] | None = None, show_page: bool = False, page_title: str = 'Sign In', auto_alert: bool = True, **kwargs: Any) -> Any

Authenticate via OAuth2.

The library owns the full auth lifecycle. Developers provide on_login and on_logout middleware to plug in their business logic (database writes, session setup, etc.).

In native mode, opens a browser window pointing at the provider's authorize URL. Blocks until authentication completes.

Parameters:

Name Type Description Default
provider OAuthProvider

Override the default provider from settings.

None
on_login callable

Called after successful authentication with the AuthFlowResult. Use this to write to your user table, set up sessions, and call app.show() with the authenticated UI.

None
on_logout callable

Called when the user triggers logout (via auth:do-logout event). Use this to invalidate DB sessions and clean up app-specific state. Token cleanup is handled automatically by the library. If omitted, only token cleanup is performed.

None
show_page bool

If True, shows a built-in themed login page with a "Sign in with {provider}" button before starting OAuth. After logout, the login page is re-shown automatically.

False
page_title str

Title for the built-in login page (used when show_page=True).

'Sign In'
auto_alert bool

If True, shows toast notifications for auth status changes (signing in, welcome, error, signed out).

True
**kwargs Any

Additional keyword arguments passed to AuthFlowManager.run_native().

{}

Returns:

Type Description
AuthFlowResult

The result of the authentication flow.

Raises:

Type Description
AuthenticationError

If authentication fails.

Examples:

>>> app = PyWry(mode=WindowMode.SINGLE_WINDOW)
>>> provider = GoogleProvider(client_id=..., client_secret=...)
>>>
>>> def on_login(result):
...     app.show(build_home(result.user_info), toolbars=toolbars)
>>> def on_logout():
...     db.invalidate_session()
>>> app.login(
...     provider=provider, on_login=on_login, on_logout=on_logout, show_page=True
... )
>>> app.block()

logout

logout(auto_alert: bool = True) -> None

Log out and clear authentication state.

Clears stored tokens and cancels any background refresh.

Parameters:

Name Type Description Default
auto_alert bool

If True, shows a "Signed out." toast notification.

True

set_initialization_script

set_initialization_script(js: str) -> None

Set the default initialization_script for new windows.

This JavaScript is injected by WebviewWindowBuilder before the page loads and persists across navigations. Individual show() calls can override this via the initialization_script keyword argument.

Parameters:

Name Type Description Default
js str

JavaScript source code to inject.

required

create_menu

create_menu(menu_id: str, items: list[Any] | None = None) -> Any

Create a native menu.

Parameters:

Name Type Description Default
menu_id str

Unique menu identifier.

required
items list of MenuItemKindConfig

Menu items.

None

Returns:

Type Description
MenuProxy

Proxy for the created menu.

create_tray

create_tray(tray_id: str, tooltip: str | None = None, title: str | None = None, icon: bytes | None = None, icon_width: int = 32, icon_height: int = 32, menu: Any = None, menu_on_left_click: bool = True) -> Any

Create a system tray icon.

Parameters:

Name Type Description Default
tray_id str

Unique tray icon identifier.

required
tooltip str or None

Hover tooltip text.

None
title str or None

Tray title (macOS menu bar text).

None
icon bytes or None

RGBA icon bytes.

None
icon_width int

Icon width.

32
icon_height int

Icon height.

32
menu MenuConfig or None

Menu to attach.

None
menu_on_left_click bool

Whether left click opens the menu.

True

Returns:

Type Description
TrayProxy

Proxy for the created tray icon.

remove_tray

remove_tray(tray_id: str) -> None

Remove a system tray icon.

Works for trays created via :meth:create_tray and those created directly via TrayProxy.from_config() or TrayProxy.create().

Parameters:

Name Type Description Default
tray_id str

The tray icon identifier.

required

show

show(content: str | HtmlContent, title: str | None = None, width: int | str | None = None, height: int | None = None, callbacks: dict[str, CallbackFunc] | None = None, include_plotly: bool = False, include_aggrid: bool = False, include_tvchart: bool = False, aggrid_theme: Literal['quartz', 'alpine', 'balham', 'material'] = 'alpine', label: str | None = None, watch: bool | None = None, toolbars: list[dict[str, Any] | Toolbar] | None = None, modals: list[dict[str, Any] | Modal] | None = None, initialization_script: str | None = None, menu: MenuConfig | None = None) -> NativeWindowHandle | BaseWidget

Show content in a window.

In a notebook environment (Jupyter, IPython, Colab, etc.), this will automatically render content inline via IFrame instead of opening a native window.

Parameters:

Name Type Description Default
content str or HtmlContent

HTML content or HtmlContent object.

required
title str or None

Window title (overrides default).

None
width int or str or None

Window width - int for pixels, str for CSS value (e.g., "60%", "500px").

None
height int or None

Window height (overrides default).

None
callbacks dict[str, CallbackFunc] or None

Event callbacks (event_type -> handler).

None
include_plotly bool

Include Plotly.js library.

False
include_aggrid bool

Include AG Grid library.

False
aggrid_theme ('quartz', 'alpine', 'balham', 'material')

AG Grid theme name (default: 'alpine').

'quartz'
label str or None

Window label (for MULTI_WINDOW mode updates).

None
watch bool or None

Enable hot reload for CSS/JS files (overrides HtmlContent.watch).

None
toolbars list[dict]

List of toolbar configs. Each toolbar has 'position' and 'items' keys.

None
modals list[dict]

List of modal configs. Each modal has 'title' and 'items' keys.

None
initialization_script str or None

JavaScript to inject via WebviewWindowBuilder before the page loads. Persists across navigations (unlike per-content HtmlContent.init_script). Overrides the default set via set_initialization_script() for this call only.

None
menu MenuConfig or None

Native menu bar configuration. Item handlers are automatically registered before the window is created so menus work from the moment the window appears. Pass a :class:MenuConfig with handler-bearing items (e.g. MenuItemConfig(id="save", text="Save", handler=on_save)).

None

Returns:

Type Description
NativeWindowHandle or PyWryWidget or InlineWidget

A NativeWindowHandle (native window) or widget (notebook). All implement the BaseWidget protocol.

show_plotly

show_plotly(figure: Any, title: str | None = None, width: int | None = None, height: int | None = None, callbacks: dict[str, CallbackFunc] | None = None, label: str | None = None, inline_css: str | None = None, on_click: Any = None, on_hover: Any = None, on_select: Any = None, toolbars: list[dict[str, Any] | Toolbar] | None = None, modals: list[dict[str, Any] | Modal] | None = None, config: Any = None) -> NativeWindowHandle | BaseWidget

Show a Plotly figure.

In a notebook environment, this will automatically render the figure inline via IFrame with full interactivity.

Parameters:

Name Type Description Default
figure Any

Plotly figure object (must have to_html method) or dictionary spec.

required
title str or None

Window title.

None
width int or None

Window/IFrame width (overrides default).

None
height int or None

Window/IFrame height (overrides default).

None
callbacks dict[str, CallbackFunc] or None

Event callbacks.

None
label str or None

Window label (for MULTI_WINDOW mode).

None
inline_css str or None

Custom CSS to inject (e.g., override window background).

None
on_click Callable or None

Click callback for notebook mode.

None
on_hover Callable or None

Hover callback for notebook mode.

None
on_select Callable or None

Selection callback for notebook mode.

None
toolbars list[dict]

List of toolbar configs. Each toolbar has 'position' and 'items' keys.

None
modals list[dict]

List of modal configs. Each modal has 'title' and 'items' keys.

None
config PlotlyConfig or dict

Plotly.js configuration (modebar, responsive, etc.).

None

Returns:

Type Description
NativeWindowHandle or BaseWidget

A NativeWindowHandle (native window) or widget (notebook). All implement the BaseWidget protocol.

show_dataframe

show_dataframe(data: Any, title: str | None = None, width: int | None = None, height: int | None = None, callbacks: dict[str, CallbackFunc] | None = None, label: str | None = None, column_defs: list[dict[str, Any]] | None = None, aggrid_theme: Literal['quartz', 'alpine', 'balham', 'material'] = 'alpine', grid_options: dict[str, Any] | None = None, toolbars: list[dict[str, Any] | Toolbar] | None = None, modals: list[dict[str, Any] | Modal] | None = None, inline_css: str | None = None, on_cell_click: Any = None, on_row_selected: Any = None, server_side: bool = False, row_selection: Any = False, pagination: bool | None = None, pagination_page_size: int = 100, enable_cell_span: bool | None = None) -> NativeWindowHandle | BaseWidget

Show a DataFrame in an AG Grid table.

In a notebook environment, this will automatically render the table inline via IFrame with full interactivity.

Parameters:

Name Type Description Default
data Any

DataFrame or list of dicts to display.

required
title str or None

Window title.

None
width int or None

Window/IFrame width (overrides default).

None
height int or None

Window/IFrame height (overrides default).

None
callbacks dict[str, CallbackFunc] or None

Event callbacks.

None
label str or None

Window label (for MULTI_WINDOW mode).

None
column_defs list[dict[str, Any]] or None

AG Grid column definitions.

None
aggrid_theme ('quartz', 'alpine', 'balham', 'material')

AG Grid theme.

'quartz'
grid_options dict[str, Any] or None

Custom AG Grid options to merge with defaults.

None
toolbars list[dict]

List of toolbar configs. Each toolbar has 'position' and 'items' keys.

None
inline_css str or None

Custom CSS to inject (e.g., override window background).

None
on_cell_click Callable or None

Cell click callback for notebook mode.

None
on_row_selected Callable or None

Row selection callback for notebook mode.

None
server_side bool

Enable server-side mode where data stays in Python memory. Useful for very large datasets (>100K rows) where you want to filter/sort the full data. Data is fetched via IPC on demand. Default is False.

False

Returns:

Type Description
NativeWindowHandle or BaseWidget

A NativeWindowHandle (native window) or widget (notebook). All implement the BaseWidget protocol.

show_tvchart

show_tvchart(data: Any = None, title: str | None = None, width: int | None = None, height: int | None = None, callbacks: dict[str, CallbackFunc] | None = None, label: str | None = None, chart_options: dict[str, Any] | None = None, series_options: dict[str, Any] | None = None, symbol_col: str | None = None, max_bars: int = 10000, toolbars: list[dict[str, Any] | Toolbar] | None = None, modals: list[dict[str, Any] | Modal] | None = None, inline_css: str | None = None, on_click: Any = None, on_crosshair: Any = None, storage: dict[str, Any] | None = None, use_datafeed: bool = False, symbol: str | None = None, resolution: str = '1D', provider: Any = None) -> NativeWindowHandle | BaseWidget

Show a TradingView Lightweight Chart.

Parameters:

Name Type Description Default
data Any

OHLCV data as a DataFrame, list of dicts, or dict of lists.

None
title str or None

Window title.

None
width int or None

Window width.

None
height int or None

Window height.

None
callbacks dict or None

Event callbacks.

None
label str or None

Window label.

None
chart_options dict or None

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

None
series_options dict or None

Series-specific options.

None
symbol_col str or None

Column name for multi-series grouping.

None
max_bars int

Maximum bars per series.

10000
toolbars list or None

Toolbar configurations.

None
modals list or None

Modal configurations.

None
inline_css str or None

Custom CSS to inject.

None
on_click Callable or None

Click callback.

None
on_crosshair Callable or None

Crosshair move callback.

None
storage dict or None

Optional persistence backend config for TVChart layouts/templates. If omitted, defaults to settings.tvchart.storage_* in non-deploy mode, and localStorage in deploy mode.

None
provider DatafeedProvider or None

A :class:~pywry.tvchart.datafeed.DatafeedProvider instance. When supplied, use_datafeed is set to True automatically and all datafeed IPC events are wired to the provider.

None

Returns:

Type Description
NativeWindowHandle or BaseWidget

emit

emit(event_type: str, data: dict[str, Any], label: str | None = None) -> None

Emit an event to the JavaScript side.

Parameters:

Name Type Description Default
event_type str

Event name.

required
data dict

Event data.

required
label str

Window label. If None, targets all active windows.

None
Notes

pywry:update-theme is broadcast to all windows/widgets by default so theme toggles stay in sync across multi-window sessions. To scope a theme update to a single label, pass {"scope": "local"} in data.

alert

alert(message: str, alert_type: Literal['info', 'success', 'warning', 'error', 'confirm'] = 'info', title: str | None = None, duration: int | None = None, callback_event: str | None = None, position: Literal['top-right', 'bottom-right', 'bottom-left', 'top-left'] = 'top-right', label: str | None = None) -> None

Show a toast notification.

Parameters:

Name Type Description Default
message str

The message to display.

required
alert_type str

Alert type: 'info', 'success', 'warning', 'error', or 'confirm'.

'info'
title str

Optional title for the toast.

None
duration int

Auto-dismiss duration in ms. Defaults based on type.

None
callback_event str

Event name to emit when confirm dialog is answered.

None
position str

Toast position: 'top-right', 'top-left', 'bottom-right', 'bottom-left'.

'top-right'
label str

Window label. If None, targets all active windows.

None

on

on(event_type: str, handler: CallbackFunc | None = None, label: str | None = None, widget_id: str | None = None) -> bool | Callable[[CallbackFunc], CallbackFunc]

Register an event handler.

Can be used as a direct call or as a decorator::

# Direct call
app.on("view:change", my_handler)


# Decorator
@app.on("view:change")
def my_handler(data): ...

Parameters:

Name Type Description Default
event_type str

Event type (namespace:event-name or * for wildcard).

required
handler CallbackFunc

Callback function. If omitted, returns a decorator.

None
label str

Window label. If None, registers on all active windows.

None
widget_id str

Widget ID to target specific component events.

None

Returns:

Type Description
bool or decorator

True if registered successfully (direct call), or a decorator function (when handler is omitted).

command

command(name: str | None = None) -> Any

Register a custom IPC command callable from JavaScript.

The decorated function becomes available to the front-end via window.__TAURI__.pytauri.pyInvoke('name', body).

Must be called before show() / start() so the command is registered in the subprocess before the Tauri app builder runs.

Parameters:

Name Type Description Default
name str or None

Command name exposed to JS. Defaults to the function's __name__.

None

Returns:

Type Description
callable

Decorator that registers the handler.

Raises:

Type Description
TypeError

If the handler is not callable.

RuntimeError

If the app is in a non-native mode (BROWSER, NOTEBOOK) where pyInvoke is not available, or if the subprocess has already started.

Examples:

>>> app = PyWry()
>>>
>>> @app.command()
... def get_user(data: dict) -> dict:
...     return {"name": "Alice", "id": 42}
>>>
>>> @app.command("fetch_data")
... async def _fetch(data: dict) -> dict:
...     rows = await load_from_db(data["query"])
...     return {"rows": rows}

on_grid

on_grid(event_type: str, handler: CallbackFunc | None = None, label: str | None = None, grid_id: str = '*') -> bool | Callable[[CallbackFunc], CallbackFunc]

Register an event handler for grid events.

Can be used as a direct call or as a decorator::

@app.on_grid("grid:cell-click")
def handle_click(data): ...

Parameters:

Name Type Description Default
event_type str

Event type (e.g., "grid:cell-click", "cell_click").

required
handler CallbackFunc

Callback function. If omitted, returns a decorator.

None
label str

Window label. If None, registers on all active windows.

None
grid_id str

Grid ID to target specific grid instance (default "*" for all).

'*'

Returns:

Type Description
bool or decorator

True if registered (direct call), or decorator (when handler omitted).

on_chart

on_chart(event_type: str, handler: CallbackFunc | None = None, label: str | None = None, chart_id: str = '*') -> bool | Callable[[CallbackFunc], CallbackFunc]

Register an event handler for chart (Plotly) events.

Can be used as a direct call or as a decorator::

@app.on_chart("plotly:click")
def handle_click(data): ...

Parameters:

Name Type Description Default
event_type str

Event type (e.g., "plotly:click", "plotly:hover").

required
handler CallbackFunc

Callback function. If omitted, returns a decorator.

None
label str

Window label. If None, registers on all active windows.

None
chart_id str

Chart ID to target specific chart instance (default "*" for all).

'*'

Returns:

Type Description
bool or decorator

True if registered (direct call), or decorator (when handler omitted).

on_toolbar

on_toolbar(event_type: str, handler: CallbackFunc | None = None, label: str | None = None, toolbar_id: str = '*') -> bool | Callable[[CallbackFunc], CallbackFunc]

Register an event handler for toolbar events.

Can be used as a direct call or as a decorator::

@app.on_toolbar("view:change")
def handle_change(data): ...

Parameters:

Name Type Description Default
event_type str

Event type (e.g., "toolbar:change", custom button events).

required
handler CallbackFunc

Callback function. If omitted, returns a decorator.

None
label str

Window label. If None, registers on all active windows.

None
toolbar_id str

Toolbar ID to target specific toolbar (default "*" for all).

'*'

Returns:

Type Description
bool or decorator

True if registered (direct call), or decorator (when handler omitted).

on_html

on_html(event_type: str, handler: CallbackFunc | None = None, label: str | None = None, element_id: str = '*') -> bool | Callable[[CallbackFunc], CallbackFunc]

Register an event handler for HTML element events.

Can be used as a direct call or as a decorator::

@app.on_html("app:custom-event")
def handle_event(data): ...

Parameters:

Name Type Description Default
event_type str

Event type (e.g., custom events from HTML elements).

required
handler CallbackFunc

Callback function. If omitted, returns a decorator.

None
label str

Window label. If None, registers on all active windows.

None
element_id str

HTML element ID to target specific element (default "*" for all).

'*'

Returns:

Type Description
bool or decorator

True if registered (direct call), or decorator (when handler omitted).

on_window

on_window(event_type: str, handler: CallbackFunc | None = None, label: str | None = None) -> bool | Callable[[CallbackFunc], CallbackFunc]

Register an event handler for window-level events.

Can be used as a direct call or as a decorator::

@app.on_window("window:close")
def handle_close(data): ...

Parameters:

Name Type Description Default
event_type str

Event type (e.g., "window:close", "window:resize").

required
handler CallbackFunc

Callback function. If omitted, returns a decorator.

None
label str

Window label. If None, registers on all active windows.

None

Returns:

Type Description
bool or decorator

True if registered (direct call), or decorator (when handler omitted).

send_event

send_event(event_type: str, data: Any, label: str | None = None) -> bool

Send an event to window(s).

Parameters:

Name Type Description Default
event_type str

Event type (namespace:event-name).

required
data Any

Event data.

required
label str or None

Specific window label (None = all windows).

None

Returns:

Type Description
bool

True if event was sent to at least one window.

update_content

update_content(html: str, label: str | None = None) -> bool

Update window content.

Parameters:

Name Type Description Default
html str

New HTML content.

required
label str or None

Window label (required for NEW_WINDOW/MULTI_WINDOW).

None

Returns:

Type Description
bool

True if updated successfully.

eval_js

eval_js(script: str, label: str | None = None) -> bool

Evaluate JavaScript in a window without replacing content.

This is useful for DOM queries and dynamic updates that should not replace the window content.

Parameters:

Name Type Description Default
script str

JavaScript code to execute.

required
label str or None

Window label (None = main window in SINGLE_WINDOW mode).

None

Returns:

Type Description
bool

True if command was sent.

show_window

show_window(label: str) -> bool

Show a hidden window.

Parameters:

Name Type Description Default
label str

Window label to show.

required

Returns:

Type Description
bool

True if window was shown.

hide_window

hide_window(label: str) -> bool

Hide a window (keeps it alive, just not visible).

Parameters:

Name Type Description Default
label str

Window label to hide.

required

Returns:

Type Description
bool

True if window was hidden.

close

close(label: str | None = None) -> bool

Close window(s).

Parameters:

Name Type Description Default
label str or None

Window label to close (None = close all).

None

Returns:

Type Description
bool

True if any window was closed.

get_labels

get_labels() -> list[str]

Get all active window labels.

Returns:

Type Description
list of str

List of window labels.

is_open

is_open(label: str | None = None) -> bool

Check if window(s) are open.

Parameters:

Name Type Description Default
label str or None

Specific window to check (None = any window).

None

Returns:

Type Description
bool

True if window(s) are open.

refresh

refresh(label: str | None = None) -> bool

Refresh window content.

Triggers a full page refresh while preserving scroll position.

Parameters:

Name Type Description Default
label str or None

Specific window to refresh (None = all windows).

None

Returns:

Type Description
bool

True if at least one window was refreshed.

refresh_css

refresh_css(label: str | None = None) -> bool

Hot-reload CSS files for window(s).

Re-injects CSS files without page refresh.

Parameters:

Name Type Description Default
label str or None

Specific window to refresh CSS (None = all windows).

None

Returns:

Type Description
bool

True if at least one window's CSS was refreshed.

enable_hot_reload

enable_hot_reload() -> None

Enable hot reload if not already enabled.

disable_hot_reload

disable_hot_reload() -> None

Disable hot reload and stop file watching.

get_icon

get_icon() -> bytes

Get the OpenBB icon.

Returns:

Type Description
bytes

Icon bytes.

get_lifecycle

get_lifecycle() -> WindowLifecycle

Get the window lifecycle manager.

Returns:

Type Description
WindowLifecycle

WindowLifecycle instance.

destroy

destroy() -> None

Destroy all resources and close all windows.

block

block(label: str | None = None) -> None

Block until window(s) are closed or KeyboardInterrupt.

This is the recommended way to keep your script running while windows are open. Works for all modes:

  • Native modes (NEW_WINDOW, SINGLE_WINDOW, MULTI_WINDOW): Waits for windows to close via the Tauri event loop.
  • BROWSER mode: Delegates to pywry.inline.block() to wait for browser tabs to disconnect.

Parameters:

Name Type Description Default
label str or None

Specific window label to wait for. If None, waits for all windows.

None

Examples:

>>> app = PyWry()
>>> label = app.show("<h1>Hello</h1>")
>>> app.block()  # Wait until all windows are closed
>>> # Or wait for a specific window
>>> app.block(label)  # Wait until this specific window is closed

request_toolbar_state

request_toolbar_state(toolbar_id: str | None = None) -> None

Request values of all toolbar inputs.

set_toolbar_value

set_toolbar_value(component_id: str, value: Any = _UNSET, toolbar_id: str | None = None, **attrs: Any) -> None

Set a toolbar component's value and/or attributes.

Parameters:

Name Type Description Default
component_id str

The component_id of the toolbar item to update.

required
value Any

The new value for the component.

_UNSET
toolbar_id str

The toolbar ID (if applicable).

None
**attrs Any

Additional attributes to set on the component: - label/text: Update text content - disabled: Enable/disable the component - variant: Button variant (primary, secondary, danger, etc.) - tooltip/description: Update tooltip text - options: Update dropdown/select options - style: Inline styles (str or dict) - className/class: Add/remove CSS classes - placeholder, min, max, step: Input constraints

{}

set_toolbar_values

set_toolbar_values(values: dict[str, Any], toolbar_id: str | None = None) -> None

Set multiple toolbar input values at once.

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

update_figure

update_figure(figure: Any, chart_id: str | None = None, animate: bool = False, config: dict[str, Any] | None = None) -> None

Update the entire chart figure (data and layout).

update_layout

update_layout(layout: dict[str, Any], chart_id: str | None = None) -> None

Update specific layout properties (Plotly.relayout).

update_traces

update_traces(patch: dict[str, Any], indices: list[int] | None = None, chart_id: str | None = None) -> None

Update specific trace properties (Plotly.restyle).

request_plotly_state

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

Request current chart state (viewport, zoom, selections).

reset_zoom

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

Reset the chart zoom/pan to default.

set_zoom

set_zoom(xaxis_range: tuple[Any, Any] | None = None, yaxis_range: tuple[Any, Any] | None = None, chart_id: str | None = None) -> None

Set specific zoom ranges for axes.

set_trace_visibility

set_trace_visibility(visible: bool | str | list[bool | str], indices: list[int] | None = None, chart_id: str | None = None) -> None

Set visibility for specific traces.

request_grid_state

request_grid_state(context: dict[str, Any] | None = None, grid_id: str | None = None) -> None

Request the current state of the grid (sort, filter, columns, etc.).

The frontend will respond with a 'grid:state-response' event.

Parameters:

Name Type Description Default
context dict

Context data to include in the response. This is echoed back unchanged in the state_response event, useful for tracking which request triggered the response (e.g., view switching).

None
grid_id str

The ID of the grid to query.

None

restore_state

restore_state(state: dict[str, Any], grid_id: str | None = None) -> None

Restore the grid state from a previous state object.

reset_state

reset_state(grid_id: str | None = None, hard: bool = False) -> None

Reset the grid state to default values.

Parameters:

Name Type Description Default
grid_id str | None

The ID of the grid to reset.

None
hard bool

If True, completely destroys and recreates the grid instance. If False (default), only resets state columns/filters/sort.

False

update_cell

update_cell(row_id: str | int, col_id: str, value: Any, grid_id: str | None = None) -> None

Update a single cell value.

update_data

update_data(data: list[dict[str, Any]], grid_id: str | None = None, strategy: str = 'set') -> None

Update grid data rows.

Parameters:

Name Type Description Default
data list[dict[str, Any]]

List of row data dictionaries.

required
grid_id str | None

The ID of the grid.

None
strategy str

Update strategy ('set', 'append', 'update'). 'set' replaces all data.

'set'

update_columns

update_columns(column_defs: list[dict[str, Any]], grid_id: str | None = None) -> None

Update column definitions.

update_grid

update_grid(data: list[dict[str, Any]] | Any | None = None, columns: list[dict[str, Any]] | None = None, restore_state: dict[str, Any] | None = None, grid_id: str | None = None) -> None

Update the grid with new data, columns, and/or restore saved state.

This is the primary method for switching views or making bulk updates. It combines data, column, and state updates into a single operation to minimize UI flicker.

Parameters:

Name Type Description Default
data list[dict] | DataFrame

New row data. If a DataFrame, it will be converted to records.

None
columns list[dict]

New column definitions.

None
restore_state dict

Previously saved grid state to restore (from grid:state-response). Contains columnState, filterModel, sortModel.

None
grid_id str

The ID of the grid to update.

None

Inline Rendering Functions

These functions provide quick one-liner display for Plotly figures and DataFrames.

pywry.inline.show_plotly

show_plotly(figure: Figure, callbacks: dict[str, Callable[..., Any]] | None = None, title: str = 'PyWry', width: str = '100%', height: int = 500, theme: ThemeLiteral | None = None, port: int | None = None, config: dict[str, Any] | PlotlyConfig | None = None, toolbars: list[dict[str, Any] | Toolbar] | None = None, modals: list[dict[str, Any] | Modal] | None = None, open_browser: bool = False) -> BaseWidget

Show a Plotly figure inline in a notebook with automatic event handling.

This function automatically wires up Plotly events (click, hover, selected) and uses the best available widget backend (anywidget or InlineWidget).

Parameters:

Name Type Description Default
figure Figure

Plotly figure to display.

required
callbacks dict[str, Callable]

Event callbacks. Keys are event names (e.g., 'plotly_click', 'plotly_hover', 'plotly_selected'), values are handler functions receiving (data, event_type, label). The function signature should be: callback(data: dict, event_type: str, label: str).

None
title str

Page title.

'PyWry'
width str

Widget width (CSS format).

'100%'
height int

Widget height in pixels.

500
theme 'dark' or 'light'

Color theme.

None
port int

Server port (only used if InlineWidget fallback is needed).

None
config dict

Plotly config dictionary (e.g., {'modeBarButtonsToAdd': [...]}).

None
toolbars list[dict]

List of toolbar configurations, each with: - position: "top", "bottom", "left", "right", "inside" - items: list of item configs

None
modals list[dict]

List of modal configurations.

None
open_browser bool

If True, open in system browser instead of displaying IFrame in notebook. Used by BROWSER mode. Default: False.

False

Returns:

Type Description
BaseWidget

Widget implementing BaseWidget protocol (PyWryPlotlyWidget or InlineWidget).

Examples:

>>> import plotly.graph_objects as go
>>> fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[4, 5, 6]))
>>> widget = show_plotly(
...     fig,
...     callbacks={
...         "plotly_click": lambda d, t, l: print(f"Clicked: {d['points']}"),
...         "plotly_hover": lambda d, t, l: print(f"Hover: {d['points']}"),
...     },
... )

pywry.inline.show_dataframe

show_dataframe(df: Any, callbacks: dict[str, Callable[..., Any]] | None = None, title: str = 'PyWry', width: str = '100%', height: int = 500, theme: ThemeLiteral | None = None, aggrid_theme: Literal['quartz', 'alpine', 'balham', 'material'] = 'alpine', header_html: str = '', grid_options: dict[str, Any] | None = None, toolbars: list[Any] | None = None, modals: list[Any] | None = None, port: int | None = None, widget_id: str | None = None, column_defs: list[Any] | None = None, row_selection: Any | bool = False, enable_cell_span: bool | None = None, pagination: bool | None = None, pagination_page_size: int = 100, open_browser: bool = False) -> BaseWidget

Show a DataFrame (or dict/list) inline in a notebook with automatic event handling.

This function automatically wires up AG Grid events (grid:cell-click, grid:row-selected) and uses the best available widget backend (anywidget or InlineWidget).

Parameters:

Name Type Description Default
df DataFrame | list[dict] | dict[str, list]

Data to display. Can be pandas DataFrame, list of row dicts, or dict of columns.

required
callbacks dict[str, Callable]

Event callbacks.

None
title str

Page title.

'PyWry'
width str

Widget width (CSS format).

'100%'
height int

Widget height in pixels.

500
theme 'dark' or 'light'

Color theme.

None
aggrid_theme str

AG Grid theme.

'alpine'
header_html str

Custom HTML to display above the grid (e.g., buttons).

''
grid_options dict

Custom AG Grid options.

None
toolbars list[Toolbar | dict]

List of toolbars. Each can be a Toolbar model or dict with: - position: "top", "bottom", "left", "right", "inside" - items: list of item configs (Button, Select, etc.)

None
modals list[dict]

List of modal configurations.

None
port int

Server port (only used if InlineWidget fallback is needed).

None
widget_id str

Unique ID for the widget. If None, a random UUID is generated.

None
column_defs list

Custom column definitions. Can be dicts or ColDef objects.

None
row_selection RowSelection | dict | bool

Row selection config. True = multiRow with checkboxes.

False
enable_cell_span bool | None

Enable row spanning for index columns. None = auto-detect from MultiIndex.

None
pagination bool | None

Enable pagination. None = auto-enable for datasets > 10 rows.

None
pagination_page_size int

Rows per page when pagination is enabled.

100
open_browser bool

If True, open in system browser instead of displaying IFrame in notebook. Used by BROWSER mode. Default: False.

False

Returns:

Type Description
BaseWidget

Widget implementing BaseWidget protocol.

pywry.inline.block

block() -> None

Block until all widgets disconnect or KeyboardInterrupt.

Use this in scripts using BROWSER mode to keep the server alive until all browser tabs are closed.

Examples:

>>> widget = pywry.inline.show("<h1>Hello</h1>")
>>> widget.open_in_browser()
>>> pywry.inline.block()  # Wait until browser tab is closed

App-level convenience methods for native menus and tray icons. See the Native Menus and System Tray guides.

The following methods are on the PyWry class (documented above via autodoc):

  • create_menu(menu_id, items)MenuProxy
  • create_tray(tray_id, ...)TrayProxy
  • remove_tray(tray_id) — remove a tracked tray icon
  • set_initialization_script(js) — set default init script for new windows
  • default_config property — mutable WindowConfig with builder defaults

Window Lifecycle

pywry.window_manager.get_lifecycle

get_lifecycle() -> WindowLifecycle

Get the global window lifecycle manager.

Returns:

Type Description
WindowLifecycle

The window lifecycle singleton.