Skip to content

Commit

Permalink
Enhancements & Bug Fixes
Browse files Browse the repository at this point in the history
- Updated to Lightweight Charts 4.1
- Topbar menu widgets will now scroll when a large number of items are added to them
- Vertical Spans can now be placed on Line objects

Bugs
- Histograms will now be deleted from the legend
- autoScale is reset to true upon using `set`.
  • Loading branch information
louisnw01 committed Oct 31, 2023
1 parent 5bb3739 commit fecfb65
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 89 deletions.
56 changes: 36 additions & 20 deletions lightweight_charts/abstract.py
Expand Up @@ -227,16 +227,24 @@ def set(self, df: pd.DataFrame = None, format_cols: bool = True):
df = df.rename(columns={self.name: 'value'})
self.data = df.copy()
self._last_bar = df.iloc[-1]
self.run_script(f'{self.id}.series.setData({js_data(df)})')
self.run_script(f'{self.id}.data = {js_data(df)}; {self.id}.series.setData({self.id}.data); ')

def update(self, series: pd.Series):
series = self._series_datetime_format(series, exclude_lowercase=self.name)
if self.name in series.index:
series.rename({self.name: 'value'}, inplace=True)
if series['time'] != self._last_bar['time']:
if self._last_bar and series['time'] != self._last_bar['time']:
self.data.loc[self.data.index[-1]] = self._last_bar
self.data = pd.concat([self.data, series.to_frame().T], ignore_index=True)
self._last_bar = series
bar = js_data(series)
self.run_script(f'''
if (stampToDate(lastBar({self.id}.data).time).getTime() === stampToDate({series['time']}).getTime()) {{
{self.id}.data[{self.id}.data.length-1] = {bar}
}}
else {self.id}.data.push({bar})
{self.id}.series.update({bar})
''')
self.run_script(f'{self.id}.series.update({js_data(series)})')

def marker(self, time: datetime = None, position: MARKER_POSITION = 'below',
Expand Down Expand Up @@ -345,6 +353,15 @@ def _toggle_data(self, arg):
if ('volumeSeries' in {self.id}) {self.id}.volumeSeries.applyOptions({{visible: {jbool(arg)}}})
''')

def vertical_span(self, start_time: Union[TIME, tuple, list], end_time: TIME = None,
color: str = 'rgba(252, 219, 3, 0.2)'):
"""
Creates a vertical line or span across the chart.\n
Start time and end time can be used together, or end_time can be
omitted and a single time or a list of times can be passed to start_time.
"""
return VerticalSpan(self, start_time, end_time, color)


class HorizontalLine(Pane):
def __init__(self, chart, price, color, width, style, text, axis_label_visible, func):
Expand Down Expand Up @@ -388,13 +405,13 @@ def delete(self):


class VerticalSpan(Pane):
def __init__(self, chart: 'AbstractChart', start_time: Union[TIME, tuple, list], end_time: TIME = None,
def __init__(self, series: 'SeriesCommon', start_time: Union[TIME, tuple, list], end_time: TIME = None,
color: str = 'rgba(252, 219, 3, 0.2)'):
super().__init__(chart.win)
self._chart = chart
self._chart = series._chart
super().__init__(self._chart.win)
start_time, end_time = pd.to_datetime(start_time), pd.to_datetime(end_time)
self.run_script(f'''
{self.id} = {chart.id}.chart.addHistogramSeries({{
{self.id} = {self._chart.id}.chart.addHistogramSeries({{
color: '{color}',
priceFormat: {{type: 'volume'}},
priceScaleId: 'vertical_line',
Expand All @@ -414,7 +431,7 @@ def __init__(self, chart: 'AbstractChart', start_time: Union[TIME, tuple, list],
else:
self.run_script(f'''
{self.id}.setData(calculateTrendLine(
{start_time.timestamp()}, 1, {end_time.timestamp()}, 1, {chart.id}))
{start_time.timestamp()}, 1, {end_time.timestamp()}, 1, {series.id}))
''')

def delete(self):
Expand Down Expand Up @@ -510,6 +527,9 @@ def delete(self):
"""
self.run_script(f'''
{self._chart.id}.chart.removeSeries({self.id}.series)
{self._chart.id}.legend.lines.forEach(line => {{
if (line.line === {self.id}) {self._chart.id}.legend.div.removeChild(line.row)
}})
delete {self.id}
''')

Expand Down Expand Up @@ -545,7 +565,7 @@ def set(self, df: pd.DataFrame = None, render_drawings=False):
self.candle_data = df.copy()
self._last_bar = df.iloc[-1]

self.run_script(f'{self.id}.candleData = {js_data(df)}; {self.id}.series.setData({self.id}.candleData)')
self.run_script(f'{self.id}.data = {js_data(df)}; {self.id}.series.setData({self.id}.data)')
toolbox_action = 'clearDrawings' if not render_drawings else 'renderDrawings'
self.run_script(f"if ('toolBox' in {self._chart.id}) {self._chart.id}.toolBox.{toolbox_action}()")
if 'volume' not in df:
Expand All @@ -559,6 +579,11 @@ def set(self, df: pd.DataFrame = None, render_drawings=False):
if line.name not in df.columns:
continue
line.set(df[['time', line.name]], format_cols=False)
# set autoScale to true in case the user has dragged the price scale
self.run_script(f'''
if (!{self.id}.chart.priceScale("right").options.autoScale)
{self.id}.chart.priceScale("right").applyOptions({{autoScale: true}})
''')

def update(self, series: pd.Series, _from_tick=False):
"""
Expand All @@ -574,10 +599,10 @@ def update(self, series: pd.Series, _from_tick=False):
self._last_bar = series
bar = js_data(series)
self.run_script(f'''
if (stampToDate(lastBar({self.id}.candleData).time).getTime() === stampToDate({series['time']}).getTime()) {{
{self.id}.candleData[{self.id}.candleData.length-1] = {bar}
if (stampToDate(lastBar({self.id}.data).time).getTime() === stampToDate({series['time']}).getTime()) {{
{self.id}.data[{self.id}.data.length-1] = {bar}
}}
else {self.id}.candleData.push({bar})
else {self.id}.data.push({bar})
{self.id}.series.update({bar})
''')
if 'volume' not in series:
Expand Down Expand Up @@ -750,15 +775,6 @@ def ray_line(self, start_time: TIME, value: NUM, round: bool = False,
line._set_trend(start_time, value, start_time, value, ray=True, round=round)
return line

def vertical_span(self, start_time: Union[TIME, tuple, list], end_time: TIME = None,
color: str = 'rgba(252, 219, 3, 0.2)'):
"""
Creates a vertical line or span across the chart.\n
Start time and end time can be used together, or end_time can be
omitted and a single time or a list of times can be passed to start_time.
"""
return VerticalSpan(self, start_time, end_time, color)

def set_visible_range(self, start_time: TIME, end_time: TIME):
self.run_script(f'''
{self.id}.chart.timeScale().setVisibleRange({{
Expand Down
3 changes: 3 additions & 0 deletions lightweight_charts/js/callback.js
Expand Up @@ -90,6 +90,9 @@ if (!window.TopBar) {
menu.style.border = '2px solid '+pane.borderColor
menu.style.borderTop = 'none'
menu.style.alignItems = 'flex-start'
menu.style.maxHeight = '80%'
menu.style.overflowY = 'auto'
menu.style.scrollbar

let menuOpen = false
items.forEach(text => {
Expand Down
99 changes: 43 additions & 56 deletions lightweight_charts/js/funcs.js
Expand Up @@ -91,7 +91,7 @@ if (!window.Chart) {
makeCandlestickSeries() {
this.markers = []
this.horizontal_lines = []
this.candleData = []
this.data = []
this.precision = 2
let up = 'rgba(39, 157, 130, 100)'
let down = 'rgba(200, 97, 100, 100)'
Expand Down Expand Up @@ -336,59 +336,46 @@ if (!window.Chart) {
}

function syncCharts(childChart, parentChart) {
syncCrosshairs(childChart.chart, parentChart.chart)
syncRanges(childChart, parentChart)
}
function syncCrosshairs(childChart, parentChart) {
function crosshairHandler (e, thisChart, otherChart, otherHandler) {
thisChart.applyOptions({crosshair: { horzLine: {
visible: true,
labelVisible: true,
}}})
otherChart.applyOptions({crosshair: { horzLine: {
visible: false,
labelVisible: false,
}}})

otherChart.unsubscribeCrosshairMove(otherHandler)
if (e.time !== undefined) {
let xx = otherChart.timeScale().timeToCoordinate(e.time);
otherChart.setCrosshairXY(xx,300,true);
} else if (e.point !== undefined){
otherChart.setCrosshairXY(e.point.x,300,false);

function crosshairHandler(chart, series, point) {
if (!point) {
chart.clearCrosshairPosition()
return
}
otherChart.subscribeCrosshairMove(otherHandler)
}
let parent = 0
let child = 0
let parentCrosshairHandler = (e) => {
parent ++
if (parent < 10) return
child = 0
crosshairHandler(e, parentChart, childChart, childCrosshairHandler)
chart.setCrosshairPosition(point.value || point.close, point.time, series);
}
let childCrosshairHandler = (e) => {
child ++
if (child < 10) return
parent = 0
crosshairHandler(e, childChart, parentChart, parentCrosshairHandler)

function getPoint(series, param) {
if (!param.time) return null;
return param.seriesData.get(series) || null;
}
parentChart.subscribeCrosshairMove(parentCrosshairHandler)
childChart.subscribeCrosshairMove(childCrosshairHandler)
}
function syncRanges(childChart, parentChart) {

let setChildRange = (timeRange) => childChart.chart.timeScale().setVisibleLogicalRange(timeRange)
let setParentRange = (timeRange) => parentChart.chart.timeScale().setVisibleLogicalRange(timeRange)

parentChart.wrapper.addEventListener('mouseover', (event) => {
childChart.chart.timeScale().unsubscribeVisibleLogicalRangeChange(setParentRange)
parentChart.chart.timeScale().subscribeVisibleLogicalRangeChange(setChildRange)
})
childChart.wrapper.addEventListener('mouseover', (event) => {
parentChart.chart.timeScale().unsubscribeVisibleLogicalRangeChange(setChildRange)
childChart.chart.timeScale().subscribeVisibleLogicalRangeChange(setParentRange)
})
let setParentCrosshair = (param) => {
crosshairHandler(parentChart.chart, parentChart.series, getPoint(childChart.series, param))
}
let setChildCrosshair = (param) => {
crosshairHandler(childChart.chart, childChart.series, getPoint(parentChart.series, param))
}

let selected = parentChart
function addMouseOverListener(thisChart, otherChart, thisCrosshair, otherCrosshair, thisRange, otherRange) {
thisChart.wrapper.addEventListener('mouseover', (event) => {
if (selected === thisChart) return
selected = thisChart
otherChart.chart.timeScale().unsubscribeVisibleLogicalRangeChange(thisRange)
otherChart.chart.unsubscribeCrosshairMove(thisCrosshair)
thisChart.chart.timeScale().subscribeVisibleLogicalRangeChange(otherRange)
thisChart.chart.subscribeCrosshairMove(otherCrosshair)
})
}
addMouseOverListener(parentChart, childChart, setParentCrosshair, setChildCrosshair, setParentRange, setChildRange)
addMouseOverListener(childChart, parentChart, setChildCrosshair, setParentCrosshair, setChildRange, setParentRange)

parentChart.chart.timeScale().subscribeVisibleLogicalRangeChange(setChildRange)
parentChart.chart.subscribeCrosshairMove(setChildCrosshair)
}

function stampToDate(stampOrBusiness) {
Expand All @@ -409,26 +396,26 @@ function calculateTrendLine(startDate, startValue, endDate, endValue, chart, ray
[startDate, endDate] = [endDate, startDate];
}
let startIndex
if (stampToDate(startDate).getTime() < stampToDate(chart.candleData[0].time).getTime()) {
if (stampToDate(startDate).getTime() < stampToDate(chart.data[0].time).getTime()) {
startIndex = 0
}
else {
startIndex = chart.candleData.findIndex(item => stampToDate(item.time).getTime() === stampToDate(startDate).getTime())
startIndex = chart.data.findIndex(item => stampToDate(item.time).getTime() === stampToDate(startDate).getTime())
}

if (startIndex === -1) {
return []
}
let endIndex
if (ray) {
endIndex = chart.candleData.length+1000
endIndex = chart.data.length+1000
startValue = endValue
}
else {
endIndex = chart.candleData.findIndex(item => stampToDate(item.time).getTime() === stampToDate(endDate).getTime())
endIndex = chart.data.findIndex(item => stampToDate(item.time).getTime() === stampToDate(endDate).getTime())
if (endIndex === -1) {
let barsBetween = (endDate-lastBar(chart.candleData).time)/chart.interval
endIndex = chart.candleData.length-1+barsBetween
let barsBetween = (endDate-lastBar(chart.data).time)/chart.interval
endIndex = chart.data.length-1+barsBetween
}
}

Expand All @@ -438,12 +425,12 @@ function calculateTrendLine(startDate, startValue, endDate, endValue, chart, ray
let currentDate = null
let iPastData = 0
for (let i = 0; i <= numBars; i++) {
if (chart.candleData[startIndex+i]) {
currentDate = chart.candleData[startIndex+i].time
if (chart.data[startIndex+i]) {
currentDate = chart.data[startIndex+i].time
}
else {
iPastData ++
currentDate = lastBar(chart.candleData).time+(iPastData*chart.interval)
currentDate = lastBar(chart.data).time+(iPastData*chart.interval)
}

const currentValue = reversed ? startValue + rate_of_change * (numBars - i) : startValue + rate_of_change * i;
Expand Down
4 changes: 2 additions & 2 deletions lightweight_charts/js/pkg.js

Large diffs are not rendered by default.

20 changes: 10 additions & 10 deletions lightweight_charts/js/toolbox.js
Expand Up @@ -161,8 +161,8 @@ if (!window.ToolBox) {

currentTime = this.chart.chart.timeScale().coordinateToTime(param.point.x)
if (!currentTime) {
let barsToMove = param.logical - this.chart.candleData.length-1
currentTime = lastBar(this.chart.candleData).time+(barsToMove*this.chart.interval)
let barsToMove = param.logical - this.chart.data.length-1
currentTime = lastBar(this.chart.data).time+(barsToMove*this.chart.interval)
}
let currentPrice = this.chart.series.coordinateToPrice(param.point.y)

Expand All @@ -179,7 +179,7 @@ if (!window.ToolBox) {
this.makingDrawing = true
trendLine = new TrendLine(this.chart, 'rgb(15, 139, 237)', ray)
firstPrice = this.chart.series.coordinateToPrice(param.point.y)
firstTime = !ray ? this.chart.chart.timeScale().coordinateToTime(param.point.x) : lastBar(this.chart.candleData).time
firstTime = !ray ? this.chart.chart.timeScale().coordinateToTime(param.point.x) : lastBar(this.chart.data).time
this.chart.chart.applyOptions({handleScroll: false})
this.chart.chart.subscribeCrosshairMove(crosshairHandlerTrend)
}
Expand Down Expand Up @@ -337,17 +337,17 @@ if (!window.ToolBox) {
let priceDiff = priceAtCursor - originalPrice
let barsToMove = param.logical - originalIndex

let startBarIndex = this.chart.candleData.findIndex(item => item.time === hoveringOver.from[0])
let endBarIndex = this.chart.candleData.findIndex(item => item.time === hoveringOver.to[0])
let startBarIndex = this.chart.data.findIndex(item => item.time === hoveringOver.from[0])
let endBarIndex = this.chart.data.findIndex(item => item.time === hoveringOver.to[0])

let startDate
let endBar
if (hoveringOver.ray) {
endBar = this.chart.candleData[startBarIndex + barsToMove]
endBar = this.chart.data[startBarIndex + barsToMove]
startDate = hoveringOver.to[0]
} else {
startDate = this.chart.candleData[startBarIndex + barsToMove].time
endBar = endBarIndex === -1 ? null : this.chart.candleData[endBarIndex + barsToMove]
startDate = this.chart.data[startBarIndex + barsToMove].time
endBar = endBarIndex === -1 ? null : this.chart.data[endBarIndex + barsToMove]
}

let endDate = endBar ? endBar.time : hoveringOver.to[0] + (barsToMove * this.chart.interval)
Expand Down Expand Up @@ -378,8 +378,8 @@ if (!window.ToolBox) {
}

if (!currentTime) {
let barsToMove = param.logical - this.chart.candleData.length-1
currentTime = lastBar(this.chart.candleData).time + (barsToMove*this.chart.interval)
let barsToMove = param.logical - this.chart.data.length-1
currentTime = lastBar(this.chart.data).time + (barsToMove*this.chart.interval)
}

hoveringOver.calculateAndSet(firstTime, firstPrice, currentTime, currentPrice)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -5,7 +5,7 @@

setup(
name='lightweight_charts',
version='1.0.18.2',
version='1.0.18.3',
packages=find_packages(),
python_requires='>=3.8',
install_requires=[
Expand Down

0 comments on commit fecfb65

Please sign in to comment.