Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

topbar -> button & ButtonWidget || Added disabled feature & font size & right-click action & toggle select #458

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
84e2d6f
topbar -> button & ButtonWidget || Added disabled feature
JimChr-R4GN4R Sep 27, 2024
8ba9f30
topbar -> button & ButtonWidget || Added text font size
JimChr-R4GN4R Sep 27, 2024
604cbd8
Update topbar.py
JimChr-R4GN4R Sep 27, 2024
cdfdc8b
Added button right click action
JimChr-R4GN4R Sep 27, 2024
7f7e8ea
topbar -> button & ButtonWidget || right-click improvements
JimChr-R4GN4R Sep 27, 2024
33bcdf2
util -> Added hex_to_rgb function
JimChr-R4GN4R Sep 28, 2024
4809f23
topbar -> button & ButtonWidget || Added toggle select feature.
JimChr-R4GN4R Sep 28, 2024
a3d84d9
Fixed toggle select feature
JimChr-R4GN4R Sep 28, 2024
f2f341a
Merge pull request #1 from louisnw01/main
JimChr-R4GN4R Sep 29, 2024
04fb233
abstract -> SeriesCommon | Added toggle_data
JimChr-R4GN4R Sep 29, 2024
143e822
All imports from r4gn4r's library fix
JimChr-R4GN4R Sep 30, 2024
5049743
abstract -> SeriesCommon || Added remove_markers
JimChr-R4GN4R Sep 30, 2024
c2b2a15
abstract -> SeriesCommon || fixed toggle_data feature
JimChr-R4GN4R Sep 30, 2024
9368966
chart -> Added better debugging
JimChr-R4GN4R Sep 30, 2024
1f3ebc5
fix | use my library instead of original
JimChr-R4GN4R Oct 1, 2024
461051a
drawings -> Drawing || Added show/hide logic
JimChr-R4GN4R Oct 5, 2024
d6a2ce3
drawings -> Drawing || fixed delete()
JimChr-R4GN4R Oct 5, 2024
2ec1de0
topbar -> MenuWidget || execute option's function directly through Me…
JimChr-R4GN4R Oct 6, 2024
c0d681a
abstract -> SeriesCommon || Added marker show/hide feature
JimChr-R4GN4R Oct 9, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ pyrightconfig.json

working/
.zed/
.vscode/settings.json
2 changes: 1 addition & 1 deletion examples/1_setting_data/setting_data.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pandas as pd
from lightweight_charts import Chart
from lightweight_charts_r4gn4r.lightweight_charts import Chart

if __name__ == '__main__':
chart = Chart()
Expand Down
2 changes: 1 addition & 1 deletion examples/2_live_data/live_data.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pandas as pd
from time import sleep
from lightweight_charts import Chart
from lightweight_charts_r4gn4r.lightweight_charts import Chart

if __name__ == '__main__':

Expand Down
2 changes: 1 addition & 1 deletion examples/3_tick_data/tick_data.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pandas as pd
from time import sleep
from lightweight_charts import Chart
from lightweight_charts_r4gn4r.lightweight_charts import Chart

if __name__ == '__main__':

Expand Down
2 changes: 1 addition & 1 deletion examples/4_line_indicators/line_indicators.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pandas as pd
from lightweight_charts import Chart
from lightweight_charts_r4gn4r.lightweight_charts import Chart


def calculate_sma(df, period: int = 50):
Expand Down
2 changes: 1 addition & 1 deletion examples/5_styling/styling.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pandas as pd
from lightweight_charts import Chart
from lightweight_charts_r4gn4r.lightweight_charts import Chart


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion examples/6_callbacks/callbacks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pandas as pd
from lightweight_charts import Chart
from lightweight_charts_r4gn4r.lightweight_charts import Chart


def get_bar_data(symbol, timeframe):
Expand Down
67 changes: 66 additions & 1 deletion lightweight_charts/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ def __init__(self, chart: 'AbstractChart', name: str = ''):
self.offset = 0
self.data = pd.DataFrame()
self.markers = {}
self._visible = True

def _set_interval(self, df: pd.DataFrame):
if not pd.api.types.is_datetime64_any_dtype(df['time']):
Expand Down Expand Up @@ -265,6 +266,7 @@ def marker_list(self, markers: list):
"time": self._single_datetime_format(marker['time']),
"position": marker_position(marker['position']),
"color": marker['color'],
"original_color": marker['color'], # Store the original color
"shape": marker_shape(marker['shape']),
"text": marker['text'],
}
Expand Down Expand Up @@ -294,6 +296,7 @@ def marker(self, time: Optional[datetime] = None, position: MARKER_POSITION = 'b
"time": formatted_time,
"position": marker_position(position),
"color": color,
"original_color": color,
"shape": marker_shape(shape),
"text": text,
}
Expand All @@ -307,6 +310,60 @@ def remove_marker(self, marker_id: str):
self.markers.pop(marker_id)
self._update_markers()

def remove_markers(self, marker_ids: list):
"""
Removes multiple markers with the given ids.

:param marker_ids: A list of marker ids to be removed.
"""
for marker_id in marker_ids:
self.markers.pop(marker_id, None) # Use pop with default to avoid KeyError
self._update_markers()

def hide_marker(self, marker_id: str):
"""
Hides the marker with the given id by setting its color to 'transparent'.
:param marker_id: The id of the marker to hide.
"""
if marker_id in self.markers:
self.markers[marker_id]['color'] = 'transparent' # Set marker color to transparent
self._update_markers()

def show_marker(self, marker_id: str):
"""
Shows the marker with the given id by restoring its color.
:param marker_id: The id of the marker to show.
:param color: The color to restore to the marker.
"""
if marker_id in self.markers:
self.markers[marker_id]['color'] = self.markers[marker_id]['original_color'] # Restore original or specified color
self._update_markers()

def toggle_marker(self, marker_id: str):
"""
Toggles the visibility of the marker with the given id.
If the marker is currently visible, it will be hidden.
If the marker is currently hidden, it will be shown.
:param marker_id: The id of the marker to toggle.
"""
if marker_id in self.markers:
# Get the current color and original color of the marker
current_color = self.markers[marker_id]['color']
original_color = self.markers[marker_id]['original_color']

# Determine if the marker is currently visible or hidden
if current_color == 'transparent':
# If the marker is hidden, restore the original color
self.markers[marker_id]['color'] = original_color
else:
# If the marker is visible, hide it
self.markers[marker_id]['color'] = 'transparent'

# Update the markers in the chart
self._update_markers()



def horizontal_line(self, price: NUM, color: str = 'rgb(122, 146, 202)', width: int = 2,
style: LINE_STYLE = 'solid', text: str = '', axis_label_visible: bool = True,
func: Optional[Callable] = None
Expand Down Expand Up @@ -399,6 +456,14 @@ def hide_data(self):
def show_data(self):
self._toggle_data(True)

def toggle_data(self):
"""
Toggles the visibility of the data and its volume if applicable.
if the data is visible, it will be hidden, and vice versa.
"""
self._toggle_data(not self._visible)
self._visible = not self._visible

def _toggle_data(self, arg):
self.run_script(f'''
{self.id}.series.applyOptions({{visible: {jbool(arg)}}})
Expand Down Expand Up @@ -701,7 +766,7 @@ def __init__(self, window: Window, width: float = 1.0, height: float = 1.0,
self._height = height
self.events: Events = Events(self)

from lightweight_charts.polygon import PolygonAPI
from lightweight_charts_r4gn4r.lightweight_charts.polygon import PolygonAPI
self.polygon: PolygonAPI = PolygonAPI(self)

self.run_script(
Expand Down
20 changes: 15 additions & 5 deletions lightweight_charts/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import webview
from webview.errors import JavascriptException

from lightweight_charts import abstract
from lightweight_charts_r4gn4r.lightweight_charts import abstract
from .util import parse_event_message, FLOAT

import os
Expand Down Expand Up @@ -61,7 +61,6 @@ def create_window(

self.windows[-1].events.loaded += lambda: self.loaded_event.set()


def loop(self):
# self.loaded_event.set()
while self.is_alive:
Expand All @@ -88,10 +87,21 @@ def loop(self):
else:
window.evaluate_js(arg)
except KeyError as e:
# Handle KeyError if it occurs in the evaluation
print(f"KeyError encountered: {e}")
return
except JavascriptException as e:
msg = eval(str(e))
raise JavascriptException(f"\n\nscript -> '{arg}',\nerror -> {msg['name']}[{msg['line']}:{msg['column']}]\n{msg['message']}")
# Enhanced error handling
msg = eval(str(e)) # Ensure msg is a dictionary
line_info = msg.get('line', 'unknown line') # Use 'unknown line' as default
column_info = msg.get('column', 'unknown column') # Use 'unknown column' as default

# Raise a new JavascriptException with detailed info
raise JavascriptException(
f"\n\nscript -> '{arg}',\n"
f"error -> {msg.get('name', 'unknown error name')}[{line_info}:{column_info}]\n"
f"{msg.get('message', 'No message available')}"
)


class WebviewHandler():
Expand Down Expand Up @@ -204,7 +214,7 @@ def show(self, block: bool = False):
async def show_async(self):
self.show(block=False)
try:
from lightweight_charts import polygon
from lightweight_charts_r4gn4r.lightweight_charts import polygon
[asyncio.create_task(self.polygon.async_set(*args)) for args in polygon._set_on_load]
while 1:
while Chart.WV.emit_queue.empty() and self.is_alive:
Expand Down
40 changes: 39 additions & 1 deletion lightweight_charts/drawings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class Drawing(Pane):
def __init__(self, chart, func=None):
super().__init__(chart.win)
self.chart = chart
self._visible = True

def update(self, *points):
formatted_points = []
Expand All @@ -36,7 +37,7 @@ def delete(self):
"""
Irreversibly deletes the drawing.
"""
self.run_script(f'{self.id}.detach()')
self.run_script(f'{self.chart.id}.series.detachPrimitive({self.id})')

def options(self, color='#1E80F0', style='solid', width=4):
self.run_script(f'''{self.id}.applyOptions({{
Expand All @@ -45,6 +46,43 @@ def options(self, color='#1E80F0', style='solid', width=4):
width: {width},
}})''')

def show_data(self):
"""
Shows the drawing.
"""
if not self._visible:
self.run_script(f'{self.chart.id}.series.attachPrimitive({self.id})')
self._visible = True

def hide_data(self):
"""
Hides the drawing.
"""
if self._visible:
self.run_script(f'{self.id}.detach()')
self._visible = False


def _toggle_data(self, visible: bool):
"""
Toggles the visibility of the drawing. If visible is True, attach the drawing to the chart.
If False, detach the drawing (effectively hiding it).
"""
if visible:
# Re-attach the drawing to make it visible again
self.run_script(f'{self.chart.id}.series.attachPrimitive({self.id})')
else:
# Detach the drawing to hide it
self.run_script(f'{self.id}.detach()')
self._visible = visible

def toggle_data(self):
"""
Toggles the visibility of the drawing.
"""
self._toggle_data(not self._visible)


class TwoPointDrawing(Drawing):
def __init__(
self,
Expand Down
Loading