- Added async methods to polygon.
- The `requests` library is no longer required, with `urllib` being used instead.
- Added the `get_bar_data` function, which returns a dataframe of aggregate data from polygon.
- Opened up the `subscribe` and `unsubscribe` functions

Enhancements:
- Tables will now scroll when the rows exceed table height.

Bugs:
- Fixed a bug preventing async functions being used with horizontal line event.
- Fixed a bug causing the legend to show duplicate lines if the line was created after the legend.
- Fixed a bug causing the line hide icon to persist within the legend after deletion (#75)
- Fixed a bug causing the search box to be unfocused when the chart is loaded.
This commit is contained in:
louisnw
2023-08-27 00:20:05 +01:00
parent 34ce3f7199
commit f72baf95ba
49 changed files with 43156 additions and 1895 deletions

View File

@ -0,0 +1,329 @@
# `AbstractChart`
`````{py:class} AbstractChart(width, height)
Abstracted chart used to create child classes.
___
```{py:method} set(data: pd.DataFrame, render_drawings: bool = False)
Sets the initial data for the chart.
Columns should be named:
: `time | open | high | low | close | volume`
Time can be given in the index rather than a column, and volume can be omitted if volume is not used. Column names are not case sensitive.
If `render_drawings` is `True`, any drawings made using the `toolbox` will be redrawn with the new data. This is designed to be used when switching to a different timeframe of the same symbol.
`None` can also be given, which will erase all candle and volume data displayed on the chart.
```
___
```{py:method} update(series: pd.Series)
Updates the chart data from a bar.
Series labels should be akin to [`set`](#AbstractChart.set).
```
___
```{py:method} update_from_tick(series: pd.Series, cumulative_volume: bool = False)
Updates the chart from a tick.
Labels should be named:
: `time | price | volume`
As before, the `time` can also be named `date`, and the `volume` can be omitted if volume is not enabled. The `time` column can also be the name of the Series object.
The provided ticks do not need to be rounded to an interval (1 min, 5 min etc.), as the library handles this automatically.
If `cumulative_volume` is used, the volume data given will be added onto the latest bar of volume data.
```
___
```{py:method} create_line(name: str, color: COLOR, style: LINE_STYLE, width: int, price_line: bool, price_label: bool) -> Line
Creates and returns a Line object, representing a `LineSeries` object in Lightweight Charts and can be used to create indicators. As well as the methods described below, the `Line` object also has access to:
[`marker`](#marker), [`horizontal_line`](#AbstractChart.horizontal_line) [`hide_data`](#hide_data), [`show_data`](#show_data) and[`price_line`](#price_line).
Its instance should only be accessed from this method.
```
___
```{py:function} lines() -> List[Line]
Returns a list of all lines for the chart.
```
___
```{py:function} trend_line(start_time: str | datetime, start_value: NUM, end_time: str | datetime, end_value: NUM, color: COLOR, width: int) -> Line
Creates a trend line, drawn from the first point (`start_time`, `start_value`) to the last point (`end_time`, `end_value`).
```
___
```{py:function} ray_line(start_time: str | datetime, value: NUM, color: COLOR, width: int) -> Line
Creates a ray line, drawn from the first point (`start_time`, `value`) and onwards.
```
___
```{py:function} marker(time: datetime, position: MARKER_POSITION, shape: MARKER_SHAPE, color: COLOR, text: str) -> str
Adds a marker to the chart, and returns its id.
If the `time` parameter is not given, the marker will be placed at the latest bar.
When using multiple markers, they should be placed in chronological order or display bugs may be present.
```
___
```{py:function} remove_marker(marker_id: str)
Removes the marker with the given id.
```
___
```{py:function} horizontal_line(price: NUM, color: COLOR, width: int, style: LINE_STYLE, text: str, axis_label_visible: bool, func: callable= None) -> HorizontalLine
Places a horizontal line at the given price, and returns a [`HorizontalLine`] object.
If a `func` is given, the horizontal line can be edited on the chart. Upon its movement a callback will also be emitted to the callable given, containing the HorizontalLine object. The toolbox should be enabled during its usage. It is designed to be used to update an order (limit, stop, etc.) directly on the chart.
```
___
```{py:function} remove_horizontal_line(price: NUM)
Removes a horizontal line at the given price.
```
___
```{py:function} clear_markers()
Clears the markers displayed on the data.
```
___
```{py:function} clear_horizontal_lines
Clears the horizontal lines displayed on the data.
```
___
```{py:function} precision(precision: int)
Sets the precision of the chart based on the given number of decimal places.
```
___
```{py:function} price_scale(mode: PRICE_SCALE_MODE, align_labels: bool, border_visible: bool, border_color: COLOR, text_color: COLOR, entire_text_only: bool, ticks_visible: bool, scale_margin_top: float, scale_margin_bottom: float)
Price scale options for the chart.
```
___
```{py:function} time_scale(right_offset: int, min_bar_spacing: float, visible: bool, time_visible: bool, seconds_visible: bool, border_visible: bool, border_color: COLOR)
Timescale options for the chart.
```
___
```{py:function} layout(background_color: COLOR, text_color: COLOR, font_size: int, font_family: str)
Global layout options for the chart.
```
___
```{py:function} grid(vert_enabled: bool, horz_enabled: bool, color: COLOR, style: LINE_STYLE)
Grid options for the chart.
```
___
```{py:function} candle_style(up_color: COLOR, down_color: COLOR, wick_enabled: bool, border_enabled: bool, border_up_color: COLOR, border_down_color: COLOR, wick_up_color: COLOR, wick_down_color: COLOR)
Candle styling for each of the candle's parts (border, wick).
```
___
```{py:function} volume_config(scale_margin_top: float, scale_margin_bottom: float, up_color: COLOR, down_color: COLOR)
Volume config options.
```{important}
The float values given to scale the margins must be greater than 0 and less than 1.
```
___
```{py:function} crosshair(mode, vert_visible: bool, vert_width: int, vert_color: COLOR, vert_style: LINE_STYLE, vert_label_background_color: COLOR, horz_visible: bool, horz_width: int, horz_color: COLOR, horz_style: LINE_STYLE, horz_label_background_color: COLOR)
Crosshair formatting for its vertical and horizontal axes.
```
___
```{py:function} watermark(text: str, font_size: int, color: COLOR)
Overlays a watermark on top of the chart.
```
___
```{py:function} legend(visible: bool, ohlc: bool, percent: bool, lines: bool, color: COLOR, font_size: int, font_family: str)
Configures the legend of the chart.
```
___
```{py:function} spinner(visible: bool)
Shows a loading spinner on the chart, which can be used to visualise the loading of large datasets, API calls, etc.
```{important}
This method must be used in conjunction with the search event.
```
___
```{py:function} price_line(label_visible: bool, line_visible: bool, title: str)
Configures the visibility of the last value price line and its label.
```
___
```{py:function} fit()
Attempts to fit all data displayed on the chart within the viewport (`fitContent()`).
```
___
```{py:function} show_data()
Shows the hidden candles on the chart.
```
___
```{py:function} hide_data()
Hides the candles on the chart.
```
___
```{py:function} hotkey(modifier: 'ctrl' | 'alt' | 'shift' | 'meta', key: 'str' | 'int' | 'tuple', func: callable)
Adds a global hotkey to the chart window, which will execute the method or function given.
When using a number in `key`, it should be given as an integer. If multiple key commands are needed for the same function, a tuple can be passed to `key`.
```
___
```{py:function} create_table(width: NUM, height: NUM, headings: Tuple[str], widths: Tuple[float], alignments: Tuple[str], position: FLOAT, draggable: bool, func: callable) -> Table
Creates and returns a [`Table`](https://lightweight-charts-python.readthedocs.io/en/latest/tables.html) object.
```
___
````{py:function} create_subchart(position: FLOAT, width: float, height: float, sync: bool | str, scale_candles_only: bool, toolbox: bool) -> AbstractChart
Creates and returns a Chart object, placing it adjacent to the previous Chart. This allows for the use of multiple chart panels within the same window.
`position`
: specifies how the Subchart will float.
`height` | `width`
: Specifies the size of the Subchart, where `1` is the width/height of the window (100%)
`sync`
: If given as `True`, the Subchart's timescale and crosshair will follow that of the declaring Chart. If a `str` is passed, the Chart will follow the panel with the given id. Chart ids can be accessed from the `chart.id` attribute.
```{important}
`width` and `height` should be given as a number between 0 and 1.
```
Charts are arranged horizontally from left to right. When the available space is no longer sufficient, the subsequent Chart will be positioned on a new row, starting from the left side.
````
`````

View File

@ -0,0 +1,155 @@
# Charts
This page contains a reference to all chart objects that can be used within the library.
They inherit from [AbstractChart](#AbstractChart).
___
`````{py:class} Chart(width: int, height: int, x: int, y: int, on_top: bool, maximize: bool, debug: bool, toolbox: bool, inner_width: float, inner_height: float, scale_candles_only: bool)
The main object used for the normal functionality of lightweight-charts-python, built on the pywebview library.
```{important}
The `Chart` object should be defined within an `if __name__ == '__main__'` block.
```
___
```{py:method} show(block: bool)
Shows the chart window, blocking until the chart has loaded. If `block` is enabled, the method will block code execution until the window is closed.
```
___
```{py:method} hide()
Hides the chart window, which can be later shown by calling `chart.show()`.
```
___
```{py:method} exit()
Exits and destroys the chart window.
```
___
```{py:method} show_async(block: bool)
:async:
Show the chart asynchronously.
```
___
````{py:method} screenshot(block: bool) -> bytes
Takes a screenshot of the chart, and returns a bytes object containing the image. For example:
```python
if __name__ == '__main__':
chart = Chart()
df = pd.read_csv('ohlcv.csv')
chart.set(df)
chart.show()
img = chart.screenshot()
with open('screenshot.png', 'wb') as f:
f.write(img)
```
```{important}
This method should be called after the chart window has loaded.
```
````
`````
___
````{py:class} QtChart(widget: QWidget)
The `QtChart` object allows the use of charts within a `QMainWindow` object, and has similar functionality to the `Chart` object for manipulating data, configuring and styling.
Either the `PyQt5` or `PySide6` libraries will work with this chart.
Callbacks can be received through the Qt event loop.
___
```{py:method} get_webview() -> QWebEngineView
Returns the `QWebEngineView` object.
```
````
___
````{py:class} WxChart(parent: WxPanel)
The WxChart object allows the use of charts within a `wx.Frame` object, and has similar functionality to the `Chart` object for manipulating data, configuring and styling.
Callbacks can be received through the Wx event loop.
___
```{py:method} get_webview() -> wx.html2.WebView
Returns a `wx.html2.WebView` object which can be used to for positioning and styling within wxPython.
```
````
___
````{py:class} StreamlitChart
The `StreamlitChart` object allows the use of charts within a Streamlit app, and has similar functionality to the `Chart` object for manipulating data, configuring and styling.
This object only supports the displaying of **static** data, and should not be used with the `update_from_tick` or `update` methods. Every call to the chart object must occur **before** calling `load`.
___
```{py:method} load()
Loads the chart into the Streamlit app. This should be called after setting, styling, and configuring the chart, as no further calls to the `StreamlitChart` will be acknowledged.
```
````
___
````{py:class} JupyterChart
The `JupyterChart` object allows the use of charts within a notebook, and has similar functionality to the `Chart` object for manipulating data, configuring and styling.
This object only supports the displaying of **static** data, and should not be used with the `update_from_tick` or `update` methods. Every call to the chart object must occur **before** calling `load`.
___
```{py:method} load()
Renders the chart. This should be called after setting, styling, and configuring the chart, as no further calls to the `JupyterChart` will be acknowledged.
```
````

View File

@ -0,0 +1,28 @@
# `Events`
````{py:class} AbstractChart.Events
The chart events class, accessed through `chart.events`
Events allow asynchronous and synchronous callbacks to be passed back into python.
Chart events can be subscribed to using: `chart.events.<name> += <callable>`
```{py:method} search -> (chart: Chart, string: str)
Fires upon searching. Searchbox will be automatically created.
```
```{py:method} new_bar -> (chart: Chart)
Fires when a new candlestick is added to the chart.
```
```{py:method} range_change -> (chart: Chart, bars_before: NUM, bars_after: NUM)
Fires when the range (visibleLogicalRange) changes.
```
````
Tutorial: [Topbar & Events](../tutorials/events.md)

View File

@ -0,0 +1,28 @@
# `HorizontalLine`
````{py:class} HorizontalLine(price: NUM, color: COLOR, width: int, style: LINE_STYLE, text: str, axis_label_visible: bool, func: callable= None)
The `HorizontalLine` object represents a `PriceLine` in Lightweight Charts.
Its instance should be accessed from the `horizontal_line` method.
```{py:method} update(price: NUM)
Updates the price of the horizontal line.
```
```{py:method} label(text: str)
Updates the label of the horizontal line.
```
```{py:method} delete()
Irreversibly deletes the horizontal line.
```
````

View File

@ -0,0 +1,23 @@
# Reference
```{toctree}
:hidden:
abstract_chart
line
horizontal_line
charts
events
topbar
toolbox
tables
```
1. [`AbstractChart`](#AbstractChart)
2. [`Line`](#Line)
3. [`HorizontalLine`](#HorizontalLine)
4. [Charts](#charts)
5. [`Events`](./events.md)
6. [`Toolbox`](#ToolBox)
7. [`Table`](#Table)

View File

@ -0,0 +1,44 @@
# `Line`
````{py:class} Line(name: str, color: COLOR, style: LINE_STYLE, width: int, price_line: bool, price_label: bool)
The `Line` object represents a `LineSeries` object in Lightweight Charts and can be used to create indicators. As well as the methods described below, the `Line` object also has access to:
[`marker`](#marker), [`horizontal_line`](#AbstractChart.horizontal_line) [`hide_data`](#hide_data), [`show_data`](#show_data) and [`price_line`](#price_line).
Its instance should only be accessed from [create_line](#AbstractChart.create_line).
___
```{py:function} set(data: pd.DataFrame)
Sets the data for the line.
When a name has not been set upon declaration, the columns should be named: `time | value` (Not case sensitive).
Otherwise, the method will use the column named after the string given in `name`. This name will also be used within the legend of the chart.
```
___
```{py:function} update(series: pd.Series)
Updates the data for the line.
This should be given as a Series object, with labels akin to the `line.set()` function.
```
___
```{py:function} line.delete()
Irreversibly deletes the line.
```
````

View File

@ -0,0 +1,125 @@
# `Table`
`````{py:class} Table(width: NUM, height: NUM, headings: Tuple[str], widths: Tuple[float], alignments: Tuple[str], position: FLOAT, draggable: bool, func: callable)
Tables are panes that can be used to gain further functionality from charts. They are intended to be used for watchlists, order management, or position management. It should be accessed from the `create_table` common method.
The `Table` and `Row` objects act as dictionaries, and can be manipulated as such.
`width`/`height`
: Either given as a percentage (a `float` between 0 and 1) or as an integer representing pixel size.
`widths`
: Given as a `float` between 0 and 1.
`position`
: Used as you would with [`create_subchart`](#AbstractChart.create_subchart), representing how the table will float within the window.
`draggable`
: If `True`, then the window can be dragged to any position within the window.
`func`
: If given, this will be called when a row is clicked, returning the `Row` object in question.
___
````{py:method} new_row(*values, id: int) -> Row
Creates a new row within the table, and returns a `Row` object.
if `id` is passed it should be unique to all other rows. Otherwise, the `id` will be randomly generated.
Rows can be passed a string (header) item or a tuple to set multiple headings:
```python
row['Symbol'] = 'AAPL'
row['Symbol', 'Action'] = 'AAPL', 'BUY'
```
````
___
```{py:method} clear()
Clears and deletes all table rows.
```
___
````{py:method} format(column: str, format_str: str)
Sets the format to be used for the given column. `Table.VALUE` should be used as a placeholder for the cell value. For example:
```python
table.format('Daily %', f'{table.VALUE} %')
table.format('PL', f'$ {table.VALUE}')
```
````
___
```{py:method} visible(visible: bool)
Sets the visibility of the Table.
```
`````
___
````{py:class} Row()
```{py:method} background_color(column: str, color: COLOR)
Sets the background color of the row cell.
```
___
```{py:method} text_color(column: str, color: COLOR)
Sets the foreground color of the row cell.
```
___
```{py:method} delete()
Deletes the row.
```
````
___
````{py:class} Footer
Tables can also have a footer containing a number of text boxes. To initialize this, call the `footer` attribute with the number of textboxes to be used:
```python
table.footer(3) # Footer will be displayed, with 3 text boxes.
```
To edit the textboxes, treat `footer` as a list:
```python
table.footer[0] = 'Text Box 1'
table.footer[1] = 'Text Box 2'
table.footer[2] = 'Text Box 3'
```
````

View File

@ -0,0 +1,62 @@
# `ToolBox`
`````{py:class} ToolBox
The Toolbox allows for trendlines, ray lines and horizontal lines to be drawn and edited directly on the chart.
It can be used within any Chart object, and is enabled by setting the `toolbox` parameter to `True` upon Chart declaration.
The following hotkeys can also be used when the Toolbox is enabled:
| Key Cmd | Action |
|--- |--- |
| `alt T` | Trendline |
| `alt H` | Horizontal Line |
| `alt R` | Ray Line |
| `⌘ Z` or `ctrl Z` | Undo |
Right-clicking on a drawing will open a context menu, allowing for color selection and deletion.
___
````{py:method} save_drawings_under(widget: Widget)
Saves drawings under a specific `topbar` text widget. For example:
```python
chart.toolbox.save_drawings_under(chart.topbar['symbol'])
```
````
___
```{py:method} load_drawings(tag: str)
Loads and displays drawings stored under the tag given.
```
___
```{py:method} import_drawings(file_path: str)
Imports the drawings stored at the JSON file given in `file_path`.
```
___
```{py:method} export_drawings(file_path: str)
Exports all currently saved drawings to the JSON file given in `file_path`.
```
`````

View File

@ -0,0 +1,54 @@
# `TopBar`
````{py:class} TopBar
The `TopBar` class represents the top bar shown on the chart:
![topbar](https://i.imgur.com/Qu2FW9Y.png)
This object is accessed from the `topbar` attribute of the chart object (`chart.topbar.<method>`).
Switchers, text boxes and buttons can be added to the top bar, and their instances can be accessed through the `topbar` dictionary. For example:
```python
chart.topbar.textbox('symbol', 'AAPL') # Declares a textbox displaying 'AAPL'.
print(chart.topbar['symbol'].value) # Prints the value within ('AAPL')
chart.topbar['symbol'].set('MSFT') # Sets the 'symbol' textbox to 'MSFT'
print(chart.topbar['symbol'].value) # Prints the value again ('MSFT')
```
___
```{py:method} switcher(name: str, options: tuple: default: str, func: callable)
* `name`: the name of the switcher which can be used to access it from the `topbar` dictionary.
* `options`: The options for each switcher item.
* `default`: The initial switcher option set.
```
___
```{py:method} textbox(name: str, initial_text: str)
* `name`: the name of the text box which can be used to access it from the `topbar` dictionary.
* `initial_text`: The text to show within the text box.
```
___
```{py:method} button(name: str, button_text: str, separator: bool, func: callable)
* `name`: the name of the text box to access it from the `topbar` dictionary.
* `button_text`: Text to show within the button.
* `separator`: places a separator line to the right of the button.
* `func`: The event handler which will be executed upon a button click.
```
````

View File

@ -0,0 +1,42 @@
:orphan:
# `Typing`
These classes serve as placeholders for type requirements.
```{py:class} NUM(Literal[float, int])
```
```{py:class} FLOAT(Literal['left', 'right', 'top', 'bottom'])
```
```{py:class} TIME(Union[datetime, pd.Timestamp, str])
```
```{py:class} COLOR(str)
Throughout the library, colors should be given as either rgb (`rgb(100, 100, 100)`), rgba(`rgba(100, 100, 100, 0.7)`), hex(`#32a852`) or a html literal(`blue`, `red` etc).
```
```{py:class} LINE_STYLE(Literal['solid', 'dotted', 'dashed', 'large_dashed', 'sparse_dotted'])
```
```{py:class} MARKER_POSITION(Literal['above', 'below', 'inside'])
```
```{py:class} MARKER_SHAPE(Literal['arrow_up', 'arrow_down', 'circle', 'square'])
```
```{py:class} CROSSHAIR_MODE(Literal['normal', 'magnet'])
```
```{py:class} PRICE_SCALE_MODE(Literal['normal', 'logarithmic', 'percentage', 'index100'])
```