move to iife rather than es, add support for Wx and streamlit

This commit is contained in:
louisnw
2024-05-29 19:01:48 +01:00
parent c518cb335b
commit 8ff980abfc
20 changed files with 808 additions and 97 deletions

View File

@ -113,7 +113,7 @@ class Window:
if not sync_id:
return subchart
self.run_script(f'''
Handler.syncCharts(
Lib.Handler.syncCharts(
{subchart.id},
{sync_id},
{jbool(sync_crosshairs_only)}
@ -132,7 +132,7 @@ class Window:
color: str = '#d8d9db',
active_color: str = '#ececed'
):
self.run_script(f'Handler.setRootStyles({js_json(locals())});')
self.run_script(f'Lib.Handler.setRootStyles({js_json(locals())});')
class SeriesCommon(Pane):
@ -643,7 +643,7 @@ class AbstractChart(Candlestick, Pane):
self.polygon: PolygonAPI = PolygonAPI(self)
self.run_script(
f'{self.id} = new Handler("{self.id}", {width}, {height}, "{position}", {jbool(autosize)})')
f'{self.id} = new Lib.Handler("{self.id}", {width}, {height}, "{position}", {jbool(autosize)})')
Candlestick.__init__(self, self)
@ -666,7 +666,8 @@ class AbstractChart(Candlestick, Pane):
Creates and returns a Line object.
"""
self._lines.append(Line(self, name, color, style, width, price_line, price_label))
self._lines[-1]._push_to_legend()
# TODO check legend still works without this
# self._lines[-1]._push_to_legend()
return self._lines[-1]
def create_histogram(
@ -680,7 +681,7 @@ class AbstractChart(Candlestick, Pane):
histogram = Histogram(
self, name, color, price_line, price_label,
scale_margin_top, scale_margin_bottom)
histogram._push_to_legend()
# histogram._push_to_legend()
return histogram
def lines(self) -> List[Line]:

View File

@ -54,7 +54,7 @@ class TwoPointDrawing(Drawing):
options_string = '\n'.join(f'{key}: {val},' for key, val in options.items())
self.run_script(f'''
{self.id} = new {drawing_type}(
{self.id} = new Lib.{drawing_type}(
{make_js_point(start_time, start_value)},
{make_js_point(end_time, end_value)},
{{
@ -71,7 +71,7 @@ class HorizontalLine(Drawing):
self.price = price
self.run_script(f'''
{self.id} = new HorizontalLine(
{self.id} = new Lib.HorizontalLine(
{{price: {price}}},
{{
lineColor: '{color}',
@ -114,7 +114,7 @@ class VerticalLine(Drawing):
self.time = time
self.run_script(f'''
{self.id} = new VerticalLine(
{self.id} = new Lib.VerticalLine(
{{time: {time}}},
{{
lineColor: '{color}',

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -3,11 +3,7 @@
<head>
<title>lightweight-charts-python</title>
<link rel="stylesheet" href="styles.css">
<script type="importmap">
{
"imports": { "lightweight-charts": "./lightweight-charts.js" }
}
</script>
<script src="./lightweight-charts.js"></script>
<meta name="viewport" content ="width=device-width, initial-scale=1">
<style>
body {
@ -21,7 +17,7 @@
</head>
<body>
<div id="container"></div>
<script type="module" src="./bundle.js"></script>
<script src="./bundle.js"></script>
</body>
</html>

View File

@ -396,7 +396,7 @@ class PolygonChart(Chart):
Tickers, security types and timeframes are to be defined within the chart window.
If using the standard `show` method, the `block` parameter must be set to True.
When using `show_async`, either is acceptable.
`show_async` can also be used.
"""
def __init__(
self, api_key: str, live: bool = False, num_bars: int = 200, end_date: str = 'now', limit: int = 5_000,

View File

@ -97,7 +97,7 @@ class Table(Pane, dict):
self.return_clicked_cells = return_clicked_cells
self.run_script(f'''
{self.id} = new Table(
{self.id} = new Lib.Table(
{width},
{height},
{list(headings)},

View File

@ -139,8 +139,8 @@ class Events:
self.new_bar = Emitter()
self.search = JSEmitter(chart, f'search{chart.id}',
lambda o: chart.run_script(f'''
Handler.makeSpinner({chart.id})
{chart.id}.search = Handler.makeSearchBox({chart.id})
Lib.Handler.makeSpinner({chart.id})
{chart.id}.search = Lib.Handler.makeSearchBox({chart.id})
''')
)
salt = chart.id[chart.id.index('.')+1:]

View File

@ -61,44 +61,20 @@ def emit_callback(window, string):
class WxChart(abstract.AbstractChart):
def __init__(self, parent, inner_width: float = 1.0, inner_height: float = 1.0,
scale_candles_only: bool = False, toolbox: bool = False):
# this isn't available at the moment
raise ModuleNotFoundError('WxChart is not available in lightweight charts 2.0; please downgrade to an earlier version.')
if wx is None:
raise ModuleNotFoundError('wx.html2 was not found, and must be installed to use WxChart.')
self.webview: wx.html2.WebView = wx.html2.WebView.New(parent)
super().__init__(abstract.Window(self.webview.RunScript, 'window.wx_msg.postMessage.bind(window.wx_msg)'),
inner_width, inner_height, scale_candles_only, toolbox)
self.first = True
def on_load(e):
if self.first is True:
self.first = False
print("first")
return
print('second')
# wx.CallLater(2000, self.win.on_js_load)
# wx.CallLater(2000, self.webview.RunScript('alert(Object.keys(window))'))
self.webview.Bind(wx.html2.EVT_WEBVIEW_LOADED, on_load)
self.webview.Bind(wx.html2.EVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, lambda e: emit_callback(self, e.GetString()))
self.webview.Bind(wx.html2.EVT_WEBVIEW_LOADED, lambda e: wx.CallLater(500, self.win.on_js_load))
self.webview.Bind(wx.html2.EVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, lambda e: emit_callback(self.win, e.GetString()))
self.webview.AddScriptMessageHandler('wx_msg')
# with open(abstract.INDEX, 'r') as f:
# html = f.read()
# self.webview.SetPage(html, '/Users/louis/Projects/lightweight-charts-python/lightweight_charts/js/')
self.webview.LoadURL("file://"+abstract.INDEX)
with open('/Users/louis/Projects/lightweight-charts-python/lightweight_charts/js/bundle.js', 'r') as f:
self.webview.AddUserScript(f.read())
# self.webview.AddUserScript(abstract.JS['toolbox']) if toolbox else None
def get_webview(self): return self.webview
def get_webview(self):
return self.webview
class QtChart(abstract.AbstractChart):
@ -141,11 +117,6 @@ class StaticLWC(abstract.AbstractChart):
def __init__(self, width=None, height=None, inner_width=1, inner_height=1,
scale_candles_only: bool = False, toolbox=False, autosize=True):
# this isn't available at the moment
raise ModuleNotFoundError('Streamlit & Jupyter Charts are unavailable in lightweight charts 2.0; please downgrade to an earlier version.')
with open(abstract.INDEX.replace("test.html", 'styles.css'), 'r') as f:
css = f.read()
with open(abstract.INDEX.replace("test.html", 'bundle.js'), 'r') as f:
@ -153,13 +124,12 @@ class StaticLWC(abstract.AbstractChart):
with open(abstract.INDEX.replace("test.html", 'lightweight-charts.js'), 'r') as f:
lwc = f.read()
with open(abstract.INDEX, 'r') as f:
self._html = f.read().replace('</body>\n</html>', f'<script type="module">{lwc}</script><script type="module">{js}')
self._html = self._html.replace("</style>", f"{css}</style>")
self._html = self._html.replace('<script type="module" src="./bundle.js"></script>',
f'')
self._html = f.read() \
.replace('<link rel="stylesheet" href="styles.css">', f"<style>{css}</style>") \
.replace(' src="./lightweight-charts.js">', f'>{lwc}') \
.replace(' src="./bundle.js">', f'>{js}') \
.replace('</body>\n</html>', '<script>')
super().__init__(abstract.Window(run_script=self.run_script), inner_width, inner_height,
scale_candles_only, toolbox, autosize)
@ -197,6 +167,10 @@ class JupyterChart(StaticLWC):
def __init__(self, width: int = 800, height=350, inner_width=1, inner_height=1, scale_candles_only: bool = False, toolbox: bool = False):
super().__init__(width, height, inner_width, inner_height, scale_candles_only, toolbox, False)
# this isn't available at the moment
raise ModuleNotFoundError('JupyterChart is unavailable in lightweight charts 2.0; please downgrade to an earlier version.')
self.run_script(f'''
for (var i = 0; i < document.getElementsByClassName("tv-lightweight-charts").length; i++) {{
var element = document.getElementsByClassName("tv-lightweight-charts")[i];