Files
lightweight-charts-python/examples/6_callbacks/callbacks.py
louisnw e4459208d2 NEW FEATURE: Trendlines, Rays and the Toolbox
- Added `trend_line` and `ray_line` to the Common Methods.

- Added the `toolbox` parameter to chart declaration. This allows horizontal lines, trend lines and rays to be drawn on the chart using hotkeys and buttons.
    - cmd-Z will delete the last drawing.
    - Drawings can be moved by clicking and dragging.

- Added the `render_drawings` parameter to `set`, which will keep and re-render the drawings displayed on the chart (useful for multiple timeframes!)

Horizontal Lines
- The `horizontal_line` method now returns a HorizontalLine object, containing the methods `update` and `delete`.
- Added the `interactive` parameter to `horizontal_line`, allowing for callbacks to be emitted to the `on_horizontal_line_move` callback method when the line is dragged to a new price (stop losses, limit orders, etc.).

Enhancements:
- added the `precision` method to the Common Methods, allowing for the number of decimal places shown on the price scale to be declared.
- Lines displayed on legends now have toggle switches, allowing for their visibility to be controlled directly within the chart window.
- when using `set`, the column names can now be capitalised, and the `date` column can be the index.

Changes:
- Merged the `title` method into the `price_line` method.
2023-07-16 20:54:32 +01:00

54 lines
1.6 KiB
Python

import asyncio
import pandas as pd
from lightweight_charts import Chart
def get_bar_data(symbol, timeframe):
if symbol not in ('AAPL', 'GOOGL', 'TSLA'):
print(f'No data for "{symbol}"')
return pd.DataFrame()
return pd.read_csv(f'bar_data/{symbol}_{timeframe}.csv')
class API:
def __init__(self):
self.chart: Chart = None # Changes after each callback.
async def on_search(self, searched_string): # Called when the user searches.
new_data = get_bar_data(searched_string, self.chart.topbar['timeframe'].value)
if new_data.empty:
return
self.chart.topbar['symbol'].set(searched_string)
self.chart.set(new_data)
async def on_timeframe_selection(self): # Called when the user changes the timeframe.
new_data = get_bar_data(self.chart.topbar['symbol'].value, self.chart.topbar['timeframe'].value)
if new_data.empty:
return
self.chart.set(new_data, render_drawings=True)
async def on_horizontal_line_move(self, line_id, price):
print(f'Horizontal line moved to: {price}')
async def main():
api = API()
chart = Chart(api=api, topbar=True, searchbox=True, toolbox=True)
chart.legend(True)
chart.topbar.textbox('symbol', 'TSLA')
chart.topbar.switcher('timeframe', api.on_timeframe_selection, '1min', '5min', '30min', default='5min')
df = get_bar_data('TSLA', '5min')
chart.set(df)
chart.horizontal_line(200, interactive=True)
await chart.show_async(block=True)
if __name__ == '__main__':
asyncio.run(main())