Skip to content

Charts

Candlestick charts with plotly.

Warning

With the default auto_save=True, KbarChartClient writes kbar_<symbol>_<timestamp>.html to the current directory and rewrites it on every update.

cjtrade.pkgs.chart.kbar_client

KbarChartType

Bases: str, Enum

Available chart backends (only plotly).

KbarChartClient(chart_type=KbarChartType.PLOTLY, auto_save=True, **config)

Front end that creates a chart backend and forwards calls to it.

Parameters:

Name Type Description Default
chart_type KbarChartType

Backend to use.

KbarChartType.PLOTLY
auto_save bool

Passed to the backend; for plotly, rewrite the HTML file on every update.

True
**config

Extra backend arguments (plotly: width, height).

{}

Raises:

Type Description
ValueError

If chart_type is not supported.

Warnings

With auto_save=True (the default) the plotly backend writes kbar_<symbol>_<timestamp>.html in the current directory on updates.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
39
40
41
42
43
44
def __init__(self, chart_type: KbarChartType = KbarChartType.PLOTLY, auto_save: bool = True, **config):
    self.chart_type = chart_type
    self.auto_save = auto_save
    self.config = config
    self.chart: Optional[KbarChartBase] = None
    self._create_chart()

set_kbar_data(data, product)

Replace the chart's bars with data for product.

Parameters:

Name Type Description Default
data list of KbarData

Bars in time order.

required
product Product

The product the bars belong to.

required
Warnings

With auto-save on, writes the chart's HTML file.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def set_kbar_data(self, data: List[KbarData], product: Product) -> None:
    """Replace the chart's bars with `data` for `product`.

    Parameters
    ----------
    data : list of KbarData
        Bars in time order.
    product : Product
        The product the bars belong to.

    Warnings
    --------
    With auto-save on, writes the chart's HTML file.
    """
    if self.chart:
        self.chart.set_kbar_data(data, product)

set_product(product)

Set product without data, useful for live data streams.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
70
71
72
73
def set_product(self, product: Product) -> None:
    """Set product without data, useful for live data streams."""
    if self.chart:
        self.chart.set_product(product)

append_kbar(kbar)

Append one bar to the chart.

Parameters:

Name Type Description Default
kbar KbarData

The new bar.

required
Warnings

With auto-save on and a product set, rewrites the chart's HTML file.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def append_kbar(self, kbar: KbarData) -> None:
    """Append one bar to the chart.

    Parameters
    ----------
    kbar : KbarData
        The new bar.

    Warnings
    --------
    With auto-save on and a product set, rewrites the chart's HTML file.
    """
    if self.chart:
        self.chart.append_kbar(kbar)

render_chart()

Return the backend's figure, or None if there is no chart.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
90
91
92
93
94
def render_chart(self) -> Any:
    """Return the backend's figure, or None if there is no chart."""
    if self.chart:
        return self.chart.render_chart()
    return None

show_chart()

Display the chart through the backend.

Warnings

Plotly writes the HTML file, or opens a browser if no product is set.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
 96
 97
 98
 99
100
101
102
103
104
def show_chart(self) -> None:
    """Display the chart through the backend.

    Warnings
    --------
    Plotly writes the HTML file, or opens a browser if no product is set.
    """
    if self.chart:
        self.chart.show_chart()

save_chart(filename)

Save the chart to filename.

Parameters:

Name Type Description Default
filename str

Output path.

required
Warnings

Writes a file.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def save_chart(self, filename: str) -> None:
    """Save the chart to `filename`.

    Parameters
    ----------
    filename : str
        Output path.

    Warnings
    --------
    Writes a file.
    """
    if self.chart:
        self.chart.save_chart(filename)

set_theme(theme)

Set the colour theme if the backend supports themes.

Parameters:

Name Type Description Default
theme str

Theme name (plotly: nordic, gruvbox, light, dark).

required
Source code in src/cjtrade/pkgs/chart/kbar_client.py
121
122
123
124
125
126
127
128
129
130
def set_theme(self, theme: str) -> None:
    """Set the colour theme if the backend supports themes.

    Parameters
    ----------
    theme : str
        Theme name (plotly: ``nordic``, ``gruvbox``, ``light``, ``dark``).
    """
    if self.chart and hasattr(self.chart, 'set_theme'):
        self.chart.set_theme(theme)

switch_chart_type(chart_type, **new_config)

Replace the backend, carrying over existing bars and product.

Parameters:

Name Type Description Default
chart_type KbarChartType

New backend.

required
**new_config

Backend arguments; they replace the previous config.

{}
Warnings

Rarely useful: plotly is the only backend.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def switch_chart_type(self, chart_type: KbarChartType, **new_config) -> None:
    """Replace the backend, carrying over existing bars and product.

    Parameters
    ----------
    chart_type : KbarChartType
        New backend.
    **new_config
        Backend arguments; they replace the previous config.

    Warnings
    --------
    Rarely useful: plotly is the only backend.
    """
    old_data = self.chart.kbar_data if self.chart else []
    old_product = self.chart.product if self.chart else None

    self.chart_type = chart_type
    self.config = new_config
    self._create_chart()

    if old_data and old_product:
        self.set_kbar_data(old_data, old_product)

add_indicator(name, values, color='orange', mode='lines', row=1)

Add an overlay indicator to the current chart.

values should align with current kbar_data length (or will be aligned).

Parameters:

Name Type Description Default
name str

Display name.

required
values list of float

Numeric values, or NaN for missing.

required
color str

Line color.

'orange'
mode str

Plotly mode (e.g., 'lines').

'lines'
row int

Subplot row to attach (1=price, 2=volume).

1
Warnings

Redraws the whole chart; with auto-save on, rewrites the HTML file.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def add_indicator(self, name: str, values: List[float], color: str = 'orange', mode: str = 'lines', row: int = 1) -> None:
    """Add an overlay indicator to the current chart.

    `values` should align with current kbar_data length (or will be aligned).

    Parameters
    ----------
    name : str
        Display name.
    values : list of float
        Numeric values, or NaN for missing.
    color : str, default 'orange'
        Line color.
    mode : str, default 'lines'
        Plotly mode (e.g., 'lines').
    row : int, default 1
        Subplot row to attach (1=price, 2=volume).

    Warnings
    --------
    Redraws the whole chart; with auto-save on, rewrites the HTML file.
    """
    if self.chart and hasattr(self.chart, 'indicators'):
        self.chart.indicators.append({'name': name, 'values': values, 'color': color, 'mode': mode, 'row': row})
        # Recreate chart to ensure new trace added
        # TODO: optimize to just add trace without full redraw
        self.chart._create_chart()

remove_indicator(name)

Remove every indicator called name and redraw the chart.

Parameters:

Name Type Description Default
name str

Indicator display name.

required
Warnings

With auto-save on, rewrites the HTML file.

Source code in src/cjtrade/pkgs/chart/kbar_client.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def remove_indicator(self, name: str) -> None:
    """Remove every indicator called `name` and redraw the chart.

    Parameters
    ----------
    name : str
        Indicator display name.

    Warnings
    --------
    With auto-save on, rewrites the HTML file.
    """
    if self.chart and hasattr(self.chart, 'indicators'):
        self.chart.indicators = [i for i in self.chart.indicators if i.get('name') != name]
        # TODO: optimize to just add trace without full redraw
        self.chart._create_chart()

get_output_filename()

Return the chart's HTML filename, or "No file generated".

Source code in src/cjtrade/pkgs/chart/kbar_client.py
202
203
204
205
206
def get_output_filename(self) -> str:
    """Return the chart's HTML filename, or ``"No file generated"``."""
    if hasattr(self.chart, 'output_filename') and self.chart.output_filename:
        return self.chart.output_filename
    return "No file generated"

cjtrade.pkgs.chart.PlotlyKbarChart(width=1200, height=600, auto_save=True)

Bases: KbarChartBase

K-bar chart drawn with plotly: candlesticks over a volume subplot.

Parameters:

Name Type Description Default
width int

Figure width in pixels.

1200
height int

Figure height in pixels.

600
auto_save bool

Rewrite the HTML file whenever the chart changes; the page then polls itself for live updates.

True
Warnings

With auto_save=True the chart writes kbar_<symbol>_<timestamp>.html in the current directory once a product is set.

Source code in src/cjtrade/pkgs/chart/_plotly.py
107
108
109
110
111
112
113
114
115
116
def __init__(self, width: int = 1200, height: int = 600, auto_save: bool = True):
    super().__init__()
    self.width = width
    self.height = height
    self.auto_save = auto_save
    self.fig = None
    self.output_filename = None
    self.theme = "nordic"
    # indicators: list of dicts {name, values, color, mode, row, trace_index}
    self.indicators = []

set_theme(theme)

Set the colour theme and redraw if a chart exists.

Parameters:

Name Type Description Default
theme str

One of nordic, gruvbox, light, dark.

required

Raises:

Type Description
ValueError

If theme is not a known theme.

Warnings

The redraw rewrites the HTML file when auto-save is on.

Source code in src/cjtrade/pkgs/chart/_plotly.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def set_theme(self, theme: str) -> None:
    """Set the colour theme and redraw if a chart exists.

    Parameters
    ----------
    theme : str
        One of ``nordic``, ``gruvbox``, ``light``, ``dark``.

    Raises
    ------
    ValueError
        If `theme` is not a known theme.

    Warnings
    --------
    The redraw rewrites the HTML file when auto-save is on.
    """
    valid_themes = list(CHART_THEMES.keys())
    if theme not in valid_themes:
        raise ValueError(f"Invalid theme '{theme}'. Valid themes: {valid_themes}")
    self.theme = theme

    if self.fig and hasattr(self, 'kbar_data') and self.kbar_data:
        self._create_chart()

set_kbar_data(data, product)

Replace the bars, set the product and output filename, and redraw.

Parameters:

Name Type Description Default
data list of KbarData

Bars in time order.

required
product Product

The product; its symbol names the output file.

required
Warnings

Writes the HTML file when auto-save is on.

Source code in src/cjtrade/pkgs/chart/_plotly.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def set_kbar_data(self, data: List[KbarData], product: Product) -> None:
    """Replace the bars, set the product and output filename, and redraw.

    Parameters
    ----------
    data : list of KbarData
        Bars in time order.
    product : Product
        The product; its symbol names the output file.

    Warnings
    --------
    Writes the HTML file when auto-save is on.
    """
    self.kbar_data = data
    self.product = product
    self._generate_filename()
    self._create_chart()

set_product(product)

Set product and generate filename without needing data.

Source code in src/cjtrade/pkgs/chart/_plotly.py
165
166
167
168
def set_product(self, product: Product) -> None:
    """Set product and generate filename without needing data."""
    self.product = product
    self._generate_filename()

append_kbar(kbar)

Append one bar, log it at DEBUG, and update the figure.

Parameters:

Name Type Description Default
kbar KbarData

The new bar.

required
Warnings

Rewrites the HTML file when auto-save is on and a filename is set.

Source code in src/cjtrade/pkgs/chart/_plotly.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def append_kbar(self, kbar: KbarData) -> None:
    """Append one bar, log it at DEBUG, and update the figure.

    Parameters
    ----------
    kbar : KbarData
        The new bar.

    Warnings
    --------
    Rewrites the HTML file when auto-save is on and a filename is set.
    """
    # Initialize data list if empty
    if not hasattr(self, 'kbar_data') or self.kbar_data is None:
        self.kbar_data = []

    self.kbar_data.append(kbar)
    log.debug("@%s o=%s h=%s l=%s c=%s v=%s", kbar.timestamp, kbar.open, kbar.high,
              kbar.low, kbar.close, kbar.volume)

    # Create chart if this is the first data
    if len(self.kbar_data) == 1:
        self._create_chart()
    else:
        self._update_chart_data()

    if self.auto_save and self.output_filename:
        self._auto_save()

render_chart()

Return the plotly figure, building it first if needed.

Returns:

Type Description
Figure or None

None if there are no bars or no product.

Source code in src/cjtrade/pkgs/chart/_plotly.py
509
510
511
512
513
514
515
516
517
518
519
def render_chart(self) -> go.Figure:
    """Return the plotly figure, building it first if needed.

    Returns
    -------
    plotly.graph_objects.Figure or None
        None if there are no bars or no product.
    """
    if not self.fig:
        self._create_chart()
    return self.fig

show_chart()

Write the chart's HTML file, or call fig.show() if no filename is set.

Warnings

Writes a file; without a filename plotly's show() may open a browser.

Source code in src/cjtrade/pkgs/chart/_plotly.py
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
def show_chart(self) -> None:
    """Write the chart's HTML file, or call ``fig.show()`` if no filename is set.

    Warnings
    --------
    Writes a file; without a filename plotly's ``show()`` may open a browser.
    """
    if not self.fig:
        self._create_chart()

    if self.output_filename:
        self._save_html_with_template(self.output_filename)
    else:
        # Fallback to old behavior if no filename set
        theme_config = self._get_theme_config()
        self.fig.show(config=theme_config['config'])

save_chart(filename)

Save the chart to filename.

.png and .pdf are written as images; anything else is written as HTML, adding .html if missing.

Parameters:

Name Type Description Default
filename str

Output path.

required
Warnings

Writes a file.

Source code in src/cjtrade/pkgs/chart/_plotly.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
def save_chart(self, filename: str) -> None:
    """Save the chart to `filename`.

    ``.png`` and ``.pdf`` are written as images; anything else is
    written as HTML, adding ``.html`` if missing.

    Parameters
    ----------
    filename : str
        Output path.

    Warnings
    --------
    Writes a file.
    """
    if not self.fig:
        self._create_chart()

    if filename.endswith('.png'):
        self.fig.write_image(filename)
    elif filename.endswith('.pdf'):
        self.fig.write_image(filename)
    else:
        if not filename.endswith('.html'):
            filename = f"{filename}.html"
        self._save_html_with_template(filename)