Giter Site home page Giter Site logo

tysonwu / dash-tradingview Goto Github PK

View Code? Open in Web Editor NEW
115.0 7.0 18.0 6.5 MB

Tradingview Lightweight Charts wrapper for Plotly Dash apps

License: MIT License

R 4.88% Python 57.42% HTML 0.38% Julia 6.55% JavaScript 29.05% CSS 1.72%
charting-library financial-charting-library plotly-dash tradingview tradingview-charting-library tradingview-widget python

dash-tradingview's Introduction

🎛 Dash Tradingview Lightweight Charts Component 📊

Source Code | Documentation | Live Demo

Dash Tradingview Lightweight Charts Components is a Dash component library. This component wraps TradingView's Lightweight Charts, the popular financial charting library written in Javascript, and extends it for use in Python Dash webapp.

Releases

Date Tag
23 Feb 2023 v0.1.1

Installation

This package is available in PyPI:

pip install dash_tvlwc

Demo

Interactive demo

An interactive demo hosted and available here. The source code of this live demo can be found at ./demo/app.py.

The demo hosting on pythonanywhere somehow suffers from very slow callbacks. Fixing this soon.

Chart and series style options

  • 1-to-1 chart and series option capability as in original lightweight chart
  • See ./example/options.py Options

Interactivity with Dash callbacks

  • Modify data or styles on any triggers
  • See ./example/interactivity.py Interactivity

Minimal example

The source code of this minimal example can be found at ./demo/minimal_example.py.

  1. Import dependencies
import dash
from dash import html
import dash_tvlwc
  1. Make some random candlestick data and line plot data
candlestick_data = [
    {'close': 97.56, 'high': 101.29, 'low': 95.07, 'open': 100, 'time': '2021-01-01'},
    {'close': 96.06, 'high': 99.06, 'low': 95.17, 'open': 97.56, 'time': '2021-01-02'},
    {'close': 92.06, 'high': 98.39, 'low': 90.72, 'open': 96.06, 'time': '2021-01-03'},
    {'close': 95.74, 'high': 97.87, 'low': 89.75, 'open': 92.06, 'time': '2021-01-04'},
    {'close': 92.44, 'high': 97.5, 'low': 88.56, 'open': 95.74, 'time': '2021-01-05'},
    {'close': 89.31, 'high': 93.1, 'low': 85.20, 'open': 92.44, 'time': '2021-01-06'},
    {'close': 85.10, 'high': 93.08, 'low': 82.23, 'open': 89.31, 'time': '2021-01-07'},
    {'close': 81.87, 'high': 88.34, 'low': 77.97, 'open': 85.10, 'time': '2021-01-08'},
    {'close': 79.55, 'high': 82.44, 'low': 76.08, 'open': 81.87, 'time': '2021-01-09'},
    {'close': 82.74, 'high': 84.01, 'low': 78, 'open': 79.55, 'time': '2021-01-10'}
]

line_data = [
    {'time': '2021-01-01', 'value': 100.35},
    {'time': '2021-01-02', 'value': 97.09},
    {'time': '2021-01-03', 'value': 95.74},
    {'time': '2021-01-04', 'value': 98.72},
    {'time': '2021-01-05', 'value': 100.3},
    {'time': '2021-01-06', 'value': 95.8},
    {'time': '2021-01-07', 'value': 91.22},
    {'time': '2021-01-08', 'value': 94.26},
    {'time': '2021-01-09', 'value': 94.9},
    {'time': '2021-01-10', 'value': 94.85}
]
  1. Initialize Dash app and add the Tvlwc component
app = dash.Dash(__name__)
app.layout = html.Div(children=[
    dash_tvlwc.Tvlwc(
        seriesData=[candlestick_data, line_data],
        seriesTypes=['candlestick', 'line'],
    ),
])

if __name__ == '__main__':
    app.run_server()
  1. Run the app by python minimal_example.py. The app should be running on localhost:8050/. You should see the plot:

Minimal example

References: Chart properties

The Tradingview Lightweight Chart library is highly customizable in style. For the complete list of chart options and series options available, please refer to the official API documentation.

Configurable props

Property Description
chartOptions a dict of options on chart canvas.
seriesData a list series of list of timepoint dicts on series data.
seriesTypes a list of series types, in the same order as seriesData.
seriesOptions a list of series option dict for each series, in the same order as seriesData.
seriesMarkers a list of list of markers dicts for each series, in the same order as seriesData.
seriesPriceLines a list of list of price line dicts for each series, in the same order as seriesData.
width width of outer container of the chart.
height height of outer container of the chart.

Read-only props

Property Description
id identifiable ID for the chart.
crosshair position of last mouse hover on chart (crosshair coordinates).
click position of last mouse click on chart (click coordinates).
fullChartOptions full dict of applied chart options including default options.
fullPriceScaleOptions full dict of applied series options including default options.
timeRangeVisibleRange from-to dates of visible time range.
timeRangeVisibleLogicalRange from-to numbers of visible time range.
timeScaleWidth width of time scale.
timeScaleHeight height of time scale.
fullTimeScaleOptions full dict of applied time scale options including default options.

Contributing

See CONTRIBUTING.md

Development

  1. Install Dash and its dependencies: https://dash.plotly.com/installation
  2. Run demonstration script with python example/usage.py
  3. Visit the demo Dash app at http://localhost:8050 in your web browser

Install dependencies

If you have selected install_dependencies during the prompt, you can skip this part.

  1. Install npm packages

    $ npm install
    
  2. Create a virtual env and activate.

    $ virtualenv venv
    $ . venv/bin/activate
    

    Note: venv\Scripts\activate for windows

  3. Install python packages required to build components.

    $ pip install -r requirements.txt
    
  4. Install the python packages for testing (optional)

    $ pip install -r tests/requirements.txt
    

dash-tradingview's People

Contributors

tysonwu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

dash-tradingview's Issues

Unable to achieve synchronized pane dragging

Description:
I'm working on a project that involves multiple panes, and I'm facing an issue with achieving synchronized dragging behavior. Currently, when I drag one pane, it doesn't affect the dragging of the other pane. I'm seeking assistance in resolving this problem.

app.layout = html.Div([ html.H1(f'{Ticker}'), html.Div(className='container', children=[ html.Div(className='two', children=Graph_Plate1), html.Div(className='two', children=Graph_Plate2), ]) ])

Expected Behavior:
I want the panes to be synchronized, so that dragging one pane automatically drags the other pane as well. For example, if I drag Graph_Plate1, I expect Graph_Plate2 to move simultaneously.

Any guidance or suggestions to achieve this synchronized pane dragging functionality would be greatly appreciated.

Thank you!

time scale

Hey there! was wondering if it is possible to change the time interval for this library. Seems like for now it only support daily data ? will it support hourly or minute data ?

How do we use hourly and minute timeframes

How do you plot 1 minute data.. it did not accept the time form below:

'time': '2022-04-01 00:00:00'
'time': '2022-04-01 00:01:00'
'time': '2022-04-01 00:02:00'
'time': '2022-04-01 00:03:00'
'time': '2022-04-01 00:04:00'
'time': '2022-04-01 00:05:00'
'time': '2022-04-01 00:06:00'

is there are way i have to format the time or could a any one provide a working example.
Thanks.

The dash-tradingview clientside_callback function calls a quick network response.

app.py

import dash
from dash import html, Output, Input, State, ClientsideFunction, dcc
import dash_tvlwc

candlestick_data = [
    {'close': 97.56, 'high': 101.29, 'low': 95.07, 'open': 100, 'time': '2021-01-01'},
    {'close': 96.06, 'high': 99.06, 'low': 95.17, 'open': 97.56, 'time': '2021-01-02'},
    {'close': 92.06, 'high': 98.39, 'low': 90.72, 'open': 96.06, 'time': '2021-01-03'},
    {'close': 95.74, 'high': 97.87, 'low': 89.75, 'open': 92.06, 'time': '2021-01-04'},
    {'close': 92.44, 'high': 97.5, 'low': 88.56, 'open': 95.74, 'time': '2021-01-05'},
    {'close': 89.31, 'high': 93.1, 'low': 85.20, 'open': 92.44, 'time': '2021-01-06'},
    {'close': 85.10, 'high': 93.08, 'low': 82.23, 'open': 89.31, 'time': '2021-01-07'},
    {'close': 81.87, 'high': 88.34, 'low': 77.97, 'open': 85.10, 'time': '2021-01-08'},
    {'close': 79.55, 'high': 82.44, 'low': 76.08, 'open': 81.87, 'time': '2021-01-09'},
    {'close': 82.74, 'high': 84.01, 'low': 78, 'open': 79.55, 'time': '2021-01-10'}
]

line_data = [
    {'time': '2021-01-01', 'value': 100.35},
    {'time': '2021-01-02', 'value': 97.09},
    {'time': '2021-01-03', 'value': 95.74},
    {'time': '2021-01-04', 'value': 98.72},
    {'time': '2021-01-05', 'value': 100.3},
    {'time': '2021-01-06', 'value': 95.8},
    {'time': '2021-01-07', 'value': 91.22},
    {'time': '2021-01-08', 'value': 94.26},
    {'time': '2021-01-09', 'value': 94.9},
    {'time': '2021-01-10', 'value': 94.85}
]

main_panel = [
    dcc.Store(id='tw_operations_store', data={'data_name': {'0': "A", '1': "B"}}),  # data_name in seriesPrices 0,1 数据名称,和数据顺序对应

    html.Div(style={'position': 'relative', 'width': '100%', 'height': '100%'}, children=[
        html.Div(children=[
            dash_tvlwc.Tvlwc(
                id='tv-chart-1',
                seriesData=[candlestick_data, line_data],
                seriesTypes=['candlestick', 'line'],
                width='100%',
            ),

        ], style={'width': '100%', 'height': '100%', 'left': 0, 'top': 0}),

        html.Div(id='chart-info', children=[
            # https://tradingview.github.io/lightweight-charts/tutorials/how_to/tooltips
            html.Span(id='chart-tooltips',
                      style={'width': '120px', 'height': '100%', 'position': 'absolute', 'padding': '8px', 'fontSize': '12px', 'textAlign': 'left', 'zIndex': 999, 'top': '12px', 'left': '12px',
                             'pointerEvents': 'none',
                             'boxSizing': 'border-box',
                             'boxShadow': 'rgba(117, 134, 150, 0.45) 0px 2px 5px 0px',
                             'background': 'rgba(255, 255, 255, 0.25)',
                             'borderRadius': '4px 4px 0px 0px',
                             'borderTopColor': 'rgb(239, 83, 80)',
                             'borderRightColor': 'rgb(239, 83, 80)',
                             'borderLeftColor': 'rgb(239, 83, 80)',
                             'borderBottom': 'none',
                             'color': '#20262E',
                             'WebkitFontSmoothing': 'antialiased',
                             'fontFamily': '-apple-system, BlinkMacSystemFont, "Trebuchet MS", Roboto, Ubuntu, sans-serif',
                             }
                      ),
        ], style={'left': 0, 'top': 0, 'zIndex': 10})
    ]),

]

app = dash.Dash(__name__, suppress_callback_exceptions=True, )
app.layout = html.Div(className='container', children=[
    html.Div(className='main-container', children=[
        html.Div(children=main_panel),
    ]),
])

app.clientside_callback(
    ClientsideFunction(namespace="lightweight_chart", function_name="lightweight_chart_tooltips"),
    [Output("chart-tooltips", "children")],
    Input("tv-chart-1", "crosshair"),
    Input("chart-tooltips", "id"),
    prevent_initial_call=True
)

if __name__ == '__main__':
    app.run_server()

javascript file

function toStrWithTwoDecimals(num) {
    if (num === undefined) {
        return ""
    } else
        return num.toFixed(2);
}


function iterateDictValueWithKey(obj) {
    let str = "";
    for (const key in obj) {
        const value = obj[key];
        if (typeof value === "object") {
            for (const entry of Object.entries(value)) {
                str += `${entry[0]}:${entry[1]}<br>`;
            }
            str += '<br>'
        } else {
            str += `${toStrWithTwoDecimals(value)}<br>`;
        }
    }
    return str;
}

// Define a relatively long callback function in a stand-alone js script
window.dash_clientside = Object.assign({}, window.dash_clientside, {
    lightweight_chart: {
        lightweight_chart_tooltips: function (param, trigger_id) {


            let toolTip = document.getElementById(trigger_id)

            if (param.point === undefined || !param.time || param.point.x < 0) {
                toolTip.style.display = 'none';
            } else {

                const date_str = param.time.year.toString() + "-" + param.time.month.toString().padStart(2, "0") + "-" + param.time.day.toString().padStart(2, "0");
                const price_str = iterateDictValueWithKey(param.seriesPrices)

                toolTip.style.display = 'block';
                toolTip.innerHTML = `<div style="color: ${'rgba( 239, 83, 80, 1)'}">⬤ ABC Inc.</div>
                    <div style="font-size: 18px;color: ${'black'}">
			        ${date_str}
			        </div>
                    <div style="width:100%;font-size: 12px; margin: 1px; color: ${'black'}">
                         ${price_str}
			        </div>`;

                let left = param.point.x; // relative to timeScale
                left -= 60;
                toolTip.style.left = left + 'px';
                toolTip.style.top = 0 + 'px';
            }
            return window.dash_clientside.no_update;
        }
    }
});
image

Trying to make it work with django-plotly-dash

I've run into an issue where I use dash-tradingview with django-plotly-dash:

GibbsConsulting/django-plotly-dash#477 (comment)

The requested JS file isn't available on unpkg.com, and I found references to that in the dash-tradingview's init.py file:

_js_dist.extend(
    [
        {
            'relative_package_path': 'dash_tvlwc.min.js',
    'external_url': 'https://unpkg.com/{0}@{2}/{1}/{1}.min.js'.format(
                package_name, __name__, __version__),
            'namespace': package_name
        },
        {
            'relative_package_path': 'dash_tvlwc.min.js.map',
    'external_url': 'https://unpkg.com/{0}@{2}/{1}/{1}.min.js.map'.format(
                package_name, __name__, __version__),
            'namespace': package_name,
            'dynamic': True
        }
    ]
)

When I run the app outside the django-plotly-dash wrapper, it does seem to serve the JS file locally instead of getting it from unpkg.com where it's not available.

Any ideas on how to fix that?

Add cloud area or splitted lines

Hi dude, fantastic library I tried to use cloud series but did not work. Can you please add it to current library? Also, how to plot pivot points for seperate days? It does not have the option to split lines unless plot multiple list which is not efficient for live data. Is it possible to make candlestick width adjustable ? So it can overlap each other ?
the repo is here for cloud series
https://github.com/mastermobin/lightweight-charts/blob/cloud-area-chart/docs/cloud-area-series.md

unable to use fullTimeScaleOptions

Do you have an example of showing intraday data with minutes/seconds visible?
I've played around with this for hours, but can't seem to get it. Graph shows up, but only date is visible on the x-axis and on hover.
Here's what I tried last:

        candlestick_data = [{'time': 1685129401, 'open': 175.375, 'close': 175.305, 'low': 175.28, 'high': 175.39, 'volume': 147318},
                            {'time': 1685129501, 'open': 175.375, 'close': 175.305, 'low': 175.28, 'high': 175.39, 'volume': 147318}]
        #candlestick_data = [{'time': '2021-01-01T10:00:01', 'open': 175.375, 'close': 175.305, 'low': 175.28, 'high': 175.39, 'volume': 147318}]
        tv_chart = dash_tvlwc.Tvlwc(
                seriesData=[candlestick_data],
                seriesTypes=['candlestick'],
                fullTimeScaleOptions={ 
                    'rightOffset': 100,
                    'barSpacing': 100,
                    'minBarSpacing': 5,
                    'fixLeftEdge': False,
                    'fixRightEdge': False,
                    'lockVisibleTimeRangeOnResize': False,
                    'rightBarStaysOnScroll': False,
                    'borderVisible': False,
                    'borderColor': "#fff",
                    'visible': True,
		    'timeVisible': True,
                    'secondsVisible': True,
                    'shiftVisibleRangeOnNewBar': True,
                    #'tickMarkFormatter': 'time',
	            }
            )

Is it possible to adjust the visible time-scale range though a callback?

Like the title says, I am looking to modify the visible range of the time-scale (axis) based on data sent through a callback.

For example: I would have a dcc.datepicker as input and then scale a 1D candlestick chart to center on the date selected in the date picker. Ideally, I would like to set a predefined number of days on either side of the selected date. Any idea if this is possible?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.