implement keep_drawings

This commit is contained in:
louisnw
2024-05-27 22:24:55 +01:00
parent eaa961a184
commit 16b07546e2
8 changed files with 42 additions and 43 deletions

View File

@ -120,7 +120,7 @@ class Window:
)
''', run_last=True)
return subchart
#TODO test func below with polygon and others
def style(
self,
background_color: str = '#0c0d0f',
@ -175,14 +175,6 @@ class SeriesCommon(Pane):
self.offset = value
break
def _push_to_legend(self):
return
#TODO you dont need this? All series should have a series row?
# self.run_script(f'''
# {self._chart.id}._seriesList.push({self.id})
# {self._chart.id}.legend.lines.push({self._chart.id}.legend.makeSeriesRow({self.id}))
# ''')
@staticmethod
def _format_labels(data, labels, index, exclude_lowercase):
def rename(la, mapper):
@ -319,15 +311,6 @@ class SeriesCommon(Pane):
Creates a horizontal line at the given price.
"""
return HorizontalLine(self, price, color, width, style, text, axis_label_visible, func)
# TODO should these methods be removed
# def remove_horizontal_line(self, price: NUM):
# """
# Removes a horizontal line at the given price.
# """
# self.run_script(f'''
# {self.id}.horizontal_lines.forEach(function (line) {{
# if ({price} === line._point.price) line.detach()
# }})''')
def clear_markers(self):
"""
@ -335,15 +318,6 @@ class SeriesCommon(Pane):
"""
self.markers.clear()
# def clear_horizontal_lines(self):
# """
# Clears the horizontal lines displayed on the data.\n
# """
# self.run_script(f'''
# {self.id}.horizontal_lines.forEach(function (line) {{{self.id}.series.removePriceLine(line.line);}});
# {self.id}.horizontal_lines = [];
# ''')
def price_line(self, label_visible: bool = True, line_visible: bool = True, title: str = ''):
self.run_script(f'''
{self.id}.series.applyOptions({{
@ -517,8 +491,7 @@ class Candlestick(SeriesCommon):
self._last_bar = df.iloc[-1]
self.run_script(f'{self.id}.series.setData({js_data(df)})')
# TODO keep drawings doesnt do anything
self.run_script(f"if ({self._chart.id}.toolBox) {self._chart.id}.toolBox.clearDrawings()")
if 'volume' not in df:
return
volume = df.drop(columns=['open', 'high', 'low', 'close']).rename(columns={'volume': 'value'})
@ -535,6 +508,11 @@ class Candlestick(SeriesCommon):
if (!{self.id}.chart.priceScale("right").options.autoScale)
{self.id}.chart.priceScale("right").applyOptions({{autoScale: true}})
''')
# TODO keep drawings doesn't work consistenly w
if keep_drawings:
self.run_script(f'{self._chart.id}.toolBox?._drawingTool.repositionOnTime()')
else:
self.run_script(f"{self._chart.id}.toolBox?.clearDrawings()")
def update(self, series: pd.Series, _from_tick=False):
"""

View File

@ -114,7 +114,7 @@ class VerticalLine(Drawing):
self.time = time
self.run_script(f'''
{self.id} = new HorizontalLine(
{self.id} = new VerticalLine(
{{time: {time}}},
{{
lineColor: '{color}',

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,7 @@
import {
IChartApi,
ISeriesApi,
Logical,
MouseEventParams,
SeriesType,
} from 'lightweight-charts';
@ -62,6 +63,28 @@ export class DrawingTool {
this._drawings = [];
}
repositionOnTime() {
for (const drawing of this.drawings) {
const newPoints = []
for (const point of drawing.points) {
if (!point) {
newPoints.push(point);
continue;
}
const logical = point.time ? this._chart.timeScale()
.coordinateToLogical(
this._chart.timeScale().timeToCoordinate(point.time) || 0
) : point.logical;
newPoints.push({
time: point.time,
logical: logical as Logical,
price: point.price,
})
}
drawing.updatePoints(...newPoints);
}
}
private _onClick(param: MouseEventParams) {
if (!this._isDrawing) return;
@ -70,7 +93,7 @@ export class DrawingTool {
if (this._activeDrawing == null) {
if (this._drawingType == null) return;
// TODO this line wont work for horizontals ?
this._activeDrawing = new this._drawingType(point, point);
this._series.attachPrimitive(this._activeDrawing);
if (this._drawingType == HorizontalLine) this._onClick(param);

View File

@ -52,7 +52,7 @@ export class Handler {
public _seriesList: ISeriesApi<SeriesType>[] = [];
// TODO make some subcharts in the vite dev window and mess with the CSS to see if you can not need the position param. also see if you can remove resizing each time the window resizes?
// TODO find a better solution rather than the 'position' parameter
constructor(
chartId: string,
innerWidth: number,

View File

@ -128,16 +128,6 @@ export class ToolBox {
this.saveDrawings()
}
// renderDrawings() {
// if (this.mouseDown) return
// this.drawings.forEach((item) => {
// if ('price' in item) return
// let startDate = Math.round(item.from[0]/this.chart.interval)*this.chart.interval
// let endDate = Math.round(item.to[0]/this.chart.interval)*this.chart.interval
// item.calculateAndSet(startDate, item.from[1], endDate, item.to[1])
// })
// }
addNewDrawing(d: Drawing) {
this._drawingTool.addNewDrawing(d);
}

View File

@ -28,6 +28,10 @@ export class HorizontalLine extends Drawing {
this._callbackName = callbackName;
}
public get points() {
return [this._point];
}
public updatePoints(...points: (Point | null)[]) {
for (const p of points) if (p) this._point.price = p.price;
this.requestUpdate();

View File

@ -31,6 +31,10 @@ export class VerticalLine extends Drawing {
this.requestUpdate();
}
get points() {
return [this._point];
}
_moveToState(state: InteractionState) {
switch(state) {
case InteractionState.NONE: