### Install bn-lightweight-charts Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/README.md Install the library using pip. This command fetches and installs the latest version from PyPI. ```bash pip install bn-lightweight-charts ``` -------------------------------- ### Initialize Chart via JavaScript Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/_templates/landing.html Example of initializing the chart component within a browser environment using JavaScript. ```javascript window.addEventListener('DOMContentLoaded', () => { let chart = new Chart(document.getElementById('wrapper'), 1, 1, 'left', true) chart.makeCandlestickSeries() let toolbox = new ToolBox(chart) chart.chart.applyOptions({ grid: { vertLines: { visible: false, }, horzLines: { visible: false, }, } }) fetch("_static/ohlcv.json") .then(response => response.json()) .then(data => { chart.candleData = data.candleData chart.volumeSeries.setData(data.volume) chart.series.setData(chart.candleData) chart.reSize() }) document.querySelector('.theme-toggle').addEventListener('click', () => { let theme = localStorage.getItem('theme') let color = theme === 'dark' ? '#000' : theme === 'light' ? '#fff' : '#000' chart.chart.applyOptions({ layout: { textColor: color === '#000' ? '#fff' : '#000', background: { color: color, type: LightweightCharts.ColorType.Solid, }, } }) }) }) ``` -------------------------------- ### Install Lightweight Charts Python Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/_templates/landing.html Command to install the library via pip. ```bash pip install lightweight-charts ``` -------------------------------- ### Save Chart as PNG Screenshot Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/screenshot.md This example demonstrates how to create a chart, load data, display it, take a screenshot, and save it to a file. The screenshot command requires the chart window to be open, so ensure `block` is `False`, use a callback, or `async_show`. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart() df = pd.read_csv('ohlcv.csv') chart.set(df) chart.show() img = chart.screenshot() with open('screenshot.png', 'wb') as f: f.write(img) ``` -------------------------------- ### Initialize and Display a Chart Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/_templates/landing.html Basic setup to load OHLCV data from a CSV file and display a candlestick chart. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart(toolbox=True) df = pd.read_csv('ohlcv.csv') chart.set(df) chart.show(block=True) ``` -------------------------------- ### Create a Synced Line Chart Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/subchart.md This example demonstrates creating a main chart and a synchronized subchart. The subchart is configured to have its time scale synced with the main chart, making it useful for displaying related data like volume or indicators. The `sync=True` parameter is key for this functionality. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart(inner_width=1, inner_height=0.8) chart.time_scale(visible=False) chart2 = chart.create_subchart(width=1, height=0.2, sync=True) line = chart2.create_line() df = pd.read_csv('ohlcv.csv') df2 = pd.read_csv('rsi.csv') chart.set(df) line.set(df2) chart.show(block=True) ``` -------------------------------- ### Customize Chart Styling Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/README.md Provides an example of how to style the chart, including background and text colors, candle styles, volume configuration, watermark, and crosshair appearance. Uses pandas for data loading. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart() df = pd.read_csv('ohlcv.csv') chart.layout(background_color='#090008', text_color='#FFFFFF', font_size=16, font_family='Helvetica') chart.candle_style(up_color='#00ff55', down_color='#ed4807', border_up_color='#FFFFFF', border_down_color='#FFFFFF', wick_up_color='#FFFFFF', wick_down_color='#FFFFFF') chart.volume_config(up_color='#00ff55', down_color='#ed4807') chart.watermark('1D', color='rgba(180, 180, 240, 0.7)') chart.crosshair(mode='normal', vert_color='#FFFFFF', vert_style='dotted', horz_color='#FFFFFF', horz_style='dotted') chart.legend(visible=True, font_size=14) chart.set(df) chart.show(block=True) ``` -------------------------------- ### Grid of 4 with Maximize Buttons Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/subchart.md This advanced example creates a grid of four subcharts and adds a maximize button to each. Clicking the button toggles between displaying all four charts at half size and displaying only the clicked chart at full size, while hiding the others. This requires defining a callback function `on_max` to handle the resizing logic. ```python import pandas as pd from bn_lightweight_charts import Chart # ascii symbols FULLSCREEN = '■' CLOSE = '×' def on_max(target_chart): button = target_chart.topbar['max'] if button.value == CLOSE: [c.resize(0.5, 0.5) for c in charts] button.set(FULLSCREEN) else: for chart in charts: width, height = (1, 1) if chart == target_chart else (0, 0) chart.resize(width, height) button.set(CLOSE) if __name__ == '__main__': main_chart = Chart(inner_width=0.5, inner_height=0.5) charts = [ main_chart, main_chart.create_subchart(position='top', width=0.5, height=0.5), main_chart.create_subchart(position='left', width=0.5, height=0.5), main_chart.create_subchart(position='right', width=0.5, height=0.5), ] df = pd.read_csv('examples/1_setting_data/ohlcv.csv') for i, c in enumerate(charts): chart_number = str(i+1) c.watermark(chart_number) c.topbar.textbox('number', chart_number) c.topbar.button('max', FULLSCREEN, False, align='right', func=on_max) c.set(df) charts[0].show(block=True) ``` -------------------------------- ### Initialize Chart with Default Settings Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Create a basic chart window with default settings. Ensure the script is run directly using `if __name__ == '__main__':`. ```python from bn_lightweight_charts import Chart if __name__ == '__main__': # Basic chart with default settings chart = Chart() chart.show(block=True) ``` -------------------------------- ### GET polygon.get_bar_data Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/polygon.md Retrieves historical aggregate bar data for a specified ticker and timeframe. ```APIDOC ## GET polygon.get_bar_data ### Description Returns a formatted pandas DataFrame of the requested aggregate data. ### Parameters #### Query Parameters - **ticker** (str) - Required - The ticker symbol, prefixed for the security type (e.g., I:NDX). - **timeframe** (str) - Required - The timeframe for the data. - **start_date** (str) - Required - The start date for the data range. - **end_date** (str) - Required - The end date for the data range. - **limit** (int) - Optional - The maximum number of bars to return (default: 5000). ### Response - **pd.DataFrame** - A formatted DataFrame containing the aggregate data. ``` -------------------------------- ### Initialize and show chart Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/tutorials/getting_started.md Create a chart instance, load data from a CSV, and display it. Must be wrapped in an if __name__ == '__main__' block due to multiprocessing. ```python if __name__ == '__main__': chart = Chart() df = pd.read_csv('ohlcv.csv') chart.set(df) chart.show(block=True) ``` -------------------------------- ### Initialize Chart and Fetch Stock Data with PolygonAPI Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/polygon.md Demonstrates setting the API key and fetching historical stock data using the PolygonAPI. Ensure to set block=True when using the show method with live data. ```python from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart() chart.polygon.api_key('') chart.polygon.stock( symbol='AAPL', timeframe='5min', start_date='2023-06-09' ) chart.show(block=True) ``` -------------------------------- ### Initialize Chart with Custom Settings Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Create a chart window with custom dimensions, position, and features like title, on-top display, and toolbox. The `screen` parameter specifies the monitor index. ```python from bn_lightweight_charts import Chart if __name__ == '__main__': # Chart with custom dimensions and features chart = Chart( width=1200, height=800, x=100, # Window x position y=100, # Window y position title='AAPL Stock Chart', screen=0, # Monitor index (0 = primary) on_top=False, # Keep window on top maximize=False, # Start maximized debug=False, # Enable debug mode toolbox=True, # Enable drawing tools inner_width=1.0, # Chart width ratio (0-1) inner_height=1.0 # Chart height ratio (0-1) ) chart.show(block=True) ``` -------------------------------- ### Initialize PolygonChart for Live Data Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/polygon.md Shows how to instantiate the PolygonChart class for real-time data display. This class requires the 'websockets' library for live data functionality. ```python from bn_lightweight_charts import PolygonChart if __name__ == '__main__': chart = PolygonChart( api_key='', num_bars=200, limit=5000, live=True ) chart.show(block=True) ``` -------------------------------- ### Initialize Empty Drawings JSON Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/toolbox.md Create an empty JSON file to store drawings. This serves as the initial state before any drawings are saved. ```default {} ``` -------------------------------- ### Configure Hotkey Events in Python Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/events.md Set up custom hotkeys to trigger specific functions. Define key combinations and associated callback functions for interactive chart control. ```python from bn_lightweight_charts import Chart def place_buy_order(key): print(f'Buy {key} shares.') def place_sell_order(key): print(f'Sell all shares, because I pressed {key}.') if __name__ == '__main__': chart = Chart() chart.hotkey('shift', (1, 2, 3), place_buy_order) chart.hotkey('shift', 'X', place_sell_order) chart.show(block=True) ``` -------------------------------- ### Create Multi-pane Charts Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/README.md Demonstrates how to create multi-pane charts with different types of series (lines and histograms) and calculate SMAs for each pane. Requires pandas for data manipulation. ```python import pandas as pd import webbrowser from bn_lightweight_charts import HTMLChart def calculate_sma(df, period: int = 50, name = None): name = name or f'SMA {period}' return pd.DataFrame({ 'time': df['date'], name: df['close'].rolling(window=period).mean() }) #.dropna() def demo(): chart = HTMLChart(width=1200, height=800, inner_height=-500, filename='charts.html') chart.legend(visible=True) df = pd.read_csv('./PDATA/4ohlcv.csv') chart.set(df) # Pane 0 line7 = chart.create_line('SMA 7', color='red', price_line=False, price_label=False) sma7_data = calculate_sma(df, period=7) line7.set(sma7_data) line14 = chart.create_line('SMA 14', color='blue', price_line=False, price_label=False) sma14_data = calculate_sma(df, period=14) line14.set(sma14_data) # Pane 1 sma20_data = calculate_sma(df, period=20, name='Hist SMA(20)') line20 = chart.create_histogram('Hist SMA(20)', price_line=False, price_label=False, pane_index=1) line20.set(sma20_data) # Pane 2 sma50_data = calculate_sma(df, period=50) line50 = chart.create_line('SMA 50', color='green', price_line=False, price_label=False, pane_index=2) line50.set(sma50_data) chart.load() webbrowser.open(chart.filename) if __name__ == '__main__': demo() ``` -------------------------------- ### Implement Chart Callbacks Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/README.md Shows how to implement callbacks for user interactions such as searching, changing timeframes, and moving horizontal lines. Includes functions for fetching bar data and event handlers. ```python import pandas as pd from bn_lightweight_charts import Chart def get_bar_data(symbol, timeframe): if symbol not in ('AAPL', 'GOOGL', 'TSLA'): print(f'No data for "{symbol}"') return pd.DataFrame() return pd.read_csv(f'bar_data/{symbol}_{timeframe}.csv') def on_search(chart, searched_string): # Called when the user searches. new_data = get_bar_data(searched_string, chart.topbar['timeframe'].value) if new_data.empty: return chart.topbar['symbol'].set(searched_string) chart.set(new_data) def on_timeframe_selection(chart): # Called when the user changes the timeframe. new_data = get_bar_data(chart.topbar['symbol'].value, chart.topbar['timeframe'].value) if new_data.empty: return chart.set(new_data, True) def on_horizontal_line_move(chart, line): print(f'Horizontal line moved to: {line.price}') if __name__ == '__main__': chart = Chart(toolbox=True) chart.legend(True) chart.events.search += on_search chart.topbar.textbox('symbol', 'TSLA') chart.topbar.switcher('timeframe', ('1min', '5min', '30min'), default='5min', func=on_timeframe_selection) df = get_bar_data('TSLA', '5min') chart.set(df) chart.horizontal_line(200, func=on_horizontal_line_move) chart.show(block=True) ``` -------------------------------- ### Configuring Table Footer Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/reference/tables.md Initialize and populate a table footer with text boxes or interactive buttons. ```python table.footer(3) # Footer will be displayed, with 3 text boxes. ``` ```python table.footer[0] = 'Text Box 1' table.footer[1] = 'Text Box 2' table.footer[2] = 'Text Box 3' ``` ```python def on_footer_click(table, box_index): print(f'Box number {box_index+1} was pressed.') table.footer(3, func=on_footer_click) ``` -------------------------------- ### Create and Display Interactive Chart with Table Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/table.md This snippet demonstrates the core functionality of bn_lightweight-charts-python. It sets up a main chart and a subchart, loads data from a CSV, creates a table with custom formatting and a row click handler, and displays the interactive output. Ensure 'ohlcv.csv' is available in the same directory. ```python import pandas as pd from bn_lightweight_charts import Chart def on_row_click(row): row['PL'] = round(row['PL']+1, 2) row.background_color('PL', 'green' if row['PL'] > 0 else 'red') table.footer[1] = row['Ticker'] if __name__ == '__main__': chart = Chart(width=1000, inner_width=0.7, inner_height=1) subchart = chart.create_subchart(width=0.3, height=0.5) df = pd.read_csv('ohlcv.csv') chart.set(df) subchart.set(df) table = chart.create_table(width=0.3, height=0.2, headings=('Ticker', 'Quantity', 'Status', '%', 'PL'), widths=(0.2, 0.1, 0.2, 0.2, 0.3), alignments=('center', 'center', 'right', 'right', 'right'), position='left', func=on_row_click) table.format('PL', f'£ {table.VALUE}') table.format('%', f'{table.VALUE} %') table.new_row('SPY', 3, 'Submitted', 0, 0) table.new_row('AMD', 1, 'Filled', 25.5, 105.24) table.new_row('NVDA', 2, 'Filled', -0.5, -8.24) table.footer(2) table.footer[0] = 'Selected:' chart.show(block=True) ``` -------------------------------- ### Live data processing with asyncio in Python Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/tutorials/events.md Integrates live data updates from a CSV file with chart events and topbar controls using asyncio. ```python import asyncio import pandas as pd from bn_lightweight_charts import Chart async def data_loop(chart): ticks = pd.read_csv('ticks.csv') for i, tick in ticks.iterrows(): if not chart.is_alive: return chart.update_from_tick(ticks.iloc[i]) await asyncio.sleep(0.03) def on_new_bar(chart): print('New bar event!') def on_timeframe_selection(chart): print(f'Selected timeframe of {chart.topbar["timeframe"].value}') async def main(): chart = Chart() chart.events.new_bar += on_new_bar chart.topbar.switcher('timeframe', ('1min', '5min'), func=on_timeframe_selection) df = pd.read_csv('ohlc.csv') chart.set(df) await asyncio.gather(chart.show_async(), data_loop(chart)) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Subscribe to search event in Python Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/tutorials/events.md Demonstrates subscribing a function to the search event. Ensure block=True is set when using chart.show(). ```python from bn_lightweight_charts import Chart def on_search(chart, string): print(f'Search Text: "{string}" | Chart/SubChart ID: "{chart.id}"') if __name__ == '__main__': chart = Chart() # Subscribe the function above to search event chart.events.search += on_search chart.show(block=True) ``` -------------------------------- ### Capture a chart screenshot Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/reference/charts.md Demonstrates taking a screenshot of a chart and saving it to a file. Must be called after the chart window has loaded. ```python if __name__ == '__main__': chart = Chart() df = pd.read_csv('ohlcv.csv') chart.set(df) chart.show() img = chart.screenshot() with open('screenshot.png', 'wb') as f: f.write(img) ``` -------------------------------- ### Create Line Indicators (SMA) Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/README.md Demonstrates how to create and display line indicators, such as a Simple Moving Average (SMA), on the chart. Requires pandas for data processing and calculation. ```python import pandas as pd from bn_lightweight_charts import Chart def calculate_sma(df, period: int = 50): return pd.DataFrame({ 'time': df['date'], f'SMA {period}': df['close'].rolling(window=period).mean() }).dropna() if __name__ == '__main__': chart = Chart() chart.legend(visible=True) df = pd.read_csv('ohlcv.csv') chart.set(df) line = chart.create_line('SMA 50') sma_data = calculate_sma(df, period=50) line.set(sma_data) chart.show(block=True) ``` -------------------------------- ### Display YFinance Data in Lightweight Charts Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/yfinance.md Fetches historical market data from Yahoo Finance and updates the chart dynamically based on user input. Requires the yfinance and bn_lightweight_charts libraries. ```python import datetime as dt import yfinance as yf from bn_lightweight_charts import Chart def get_bar_data(symbol, timeframe): if timeframe in ('1m', '5m', '30m'): days = 7 if timeframe == '1m' else 60 start_date = dt.datetime.now()-dt.timedelta(days=days) else: start_date = None chart.spinner(True) data = yf.download(symbol, start_date, interval=timeframe) chart.spinner(False) if data.empty: return False chart.set(data) return True def on_search(chart, searched_string): if get_bar_data(searched_string, chart.topbar['timeframe'].value): chart.topbar['symbol'].set(searched_string) def on_timeframe_selection(chart): get_bar_data(chart.topbar['symbol'].value, chart.topbar['timeframe'].value) if __name__ == '__main__': chart = Chart(toolbox=True, debug=True) chart.legend(True) chart.events.search += on_search chart.topbar.textbox('symbol', 'n/a') chart.topbar.switcher( 'timeframe', ('1m', '5m', '30m', '1d', '1wk'), default='5m', func=on_timeframe_selection ) chart.show(block=True) ``` -------------------------------- ### Configure Price and Time Scales Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Customizes the appearance and behavior of price and time axes, including margins and visible ranges. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart() df = pd.read_csv('ohlcv.csv') chart.set(df) # Configure price scale chart.price_scale( auto_scale=True, mode='normal', # 'normal', 'logarithmic', 'percentage', 'index100' invert_scale=False, align_labels=True, scale_margin_top=0.1, # 10% margin at top scale_margin_bottom=0.1, # 10% margin at bottom border_visible=True, border_color='#555', text_color='#DDD', visible=True ) # Configure time scale chart.time_scale( right_offset=5, # Bars of space on right min_bar_spacing=0.5, visible=True, time_visible=True, seconds_visible=False, border_visible=True ) # Set visible range chart.set_visible_range( start_time='2024-01-01', end_time='2024-03-01' ) # Fit all data in view chart.fit() chart.show(block=True) ``` -------------------------------- ### Async clock update in Python Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/tutorials/events.md Uses asyncio to update a topbar textbox with the current time while the chart remains responsive. ```python import asyncio from datetime import datetime from bn_lightweight_charts import Chart async def update_clock(chart): while chart.is_alive: await asyncio.sleep(1-(datetime.now().microsecond/1_000_000)) chart.topbar['clock'].set(datetime.now().strftime('%H:%M:%S')) async def main(): chart = Chart() chart.topbar.textbox('clock') await asyncio.gather(chart.show_async(), update_clock(chart)) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Topbar button interaction in Python Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/tutorials/events.md Shows how to add a button to the topbar and handle its press event using a callback function. ```python from bn_lightweight_charts import Chart def on_button_press(chart): new_button_value = 'On' if chart.topbar['my_button'].value == 'Off' else 'Off' chart.topbar['my_button'].set(new_button_value) print(f'Turned something {new_button_value.lower()}.') if __name__ == '__main__': chart = Chart() chart.topbar.button('my_button', 'Off', func=on_button_press) chart.show(block=True) ``` -------------------------------- ### Create Interactive Tables Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Creates interactive tables for displaying data like watchlists or order information. Tables can be customized with headings, column widths, alignments, and styling. Rows can be added, updated, styled individually, and deleted. A callback function can be defined for row clicks. ```python import pandas as pd from bn_lightweight_charts import Chart def on_row_click(row): """Called when a table row is clicked""" print(f'Selected: {row["Symbol"]} at ${row["Price"]}') if __name__ == '__main__': chart = Chart() df = pd.read_csv('ohlcv.csv') chart.set(df) # Create table table = chart.create_table( width=300, height=200, headings=('Symbol', 'Price', 'Change', 'Volume'), widths=(0.25, 0.25, 0.25, 0.25), alignments=('left', 'right', 'right', 'right'), position='left', draggable=True, background_color='#1e222d', border_color='#3d4f5f', border_width=1, func=on_row_click ) # Add rows row1 = table.new_row('AAPL', '150.25', '+1.5%', '1.2M') row2 = table.new_row('GOOGL', '140.00', '-0.8%', '800K') row3 = table.new_row('MSFT', '380.50', '+2.1%', '950K') # Update cell value row1['Price'] = '151.00' # Style individual cells row1.background_color('Change', '#26a69a') # Green background row2.background_color('Change', '#ef5350') # Red background row3.text_color('Symbol', '#ffd700') # Gold text # Delete a row # row3.delete() # Clear all rows # table.clear() chart.show(block=True) ``` -------------------------------- ### Manage Sidebar and Theme UI Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/bn_lightweight_charts/js/index_bn.html Handles sidebar visibility toggling and theme switching between light and dark modes using localStorage. ```javascript // Sidebar toggle const sidebar = document.getElementById('sidebar'); const sidebarBackdrop = document.getElementById('sidebar-backdrop'); const menuBtn = document.getElementById('menu-btn'); function openSidebar() { sidebar.classList.add('open'); sidebarBackdrop.classList.add('open'); menuBtn.setAttribute('aria-expanded', 'true'); } function closeSidebar() { sidebar.classList.remove('open'); sidebarBackdrop.classList.remove('open'); menuBtn.setAttribute('aria-expanded', 'false'); } menuBtn.addEventListener('click', openSidebar); document.getElementById('sidebar-close').addEventListener('click', closeSidebar); sidebarBackdrop.addEventListener('click', closeSidebar); document.addEventListener('keydown', e => { if (e.key === 'Escape' && sidebar.classList.contains('open')) closeSidebar(); }); // Theme toggle const _sunIcon = ` Light`; const _moonIcon = ` Dark`; const _themeBtn = document.getElementById('theme-btn'); function _applyTheme(theme) { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem('theme', theme); _themeBtn.innerHTML = theme === 'dark' ? _sunIcon : _moonIcon; _themeBtn.title = theme === 'dark' ? 'Switch to Light theme' : 'Switch to Dark theme'; } _themeBtn.addEventListener('click', () => { _applyTheme(document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark'); }); _applyTheme(localStorage.getItem('theme') || 'dark'); ``` -------------------------------- ### PolygonAPI Methods Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/polygon.md Methods for fetching market data from Polygon.io and configuring the API connection. ```APIDOC ## PolygonAPI Methods ### Description Methods to set the API key and request market data for various asset classes. ### Methods - **api_key(key: str)**: Sets the API key for the chart. - **stock(symbol, timeframe, start_date, end_date, limit, live)**: Requests stock data. - **option(symbol, timeframe, expiration, right, strike, end_date, limit, live)**: Requests option data. - **index(symbol, timeframe, start_date, end_date, limit, live)**: Requests index data. - **forex(fiat_pair, timeframe, start_date, end_date, limit, live)**: Requests forex data. - **crypto(crypto_pair, timeframe, start_date, end_date, limit, live)**: Requests crypto data. ### Parameters - **timeframe** (str) - Optional - The timeframe to be used (e.g., '1min', '5min', 'H'). - **start_date** (str) - Optional - Start date in YYYY-MM-DD format. - **end_date** (str) - Optional - End date in YYYY-MM-DD format (default: 'now'). - **limit** (int) - Optional - Maximum number of base aggregates. - **live** (bool) - Optional - If True, uses websocket for real-time updates. ### Response - **bool** - Returns True if the request was successful. ``` -------------------------------- ### Use PolygonChart Prebuilt Widget Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt The PolygonChart class provides a ready-to-use trading terminal interface with built-in search and timeframe switching capabilities. ```python from bn_lightweight_charts import PolygonChart if __name__ == '__main__': # Complete trading terminal with Polygon.io integration chart = PolygonChart( api_key='your_polygon_api_key', live=True, # Enable real-time updates num_bars=200, # Number of bars to display timeframe_options=('1min', '5min', '15min', '1H', 'D'), security_options=('Stock', 'Option', 'Index', 'Forex', 'Crypto'), toolbox=True, width=1200, height=800 ) # Chart starts with search box focused # User can search symbols and switch timeframes chart.show(block=True) ``` -------------------------------- ### Create a Grid of 4 Subcharts Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/examples/subchart.md This snippet shows how to create a main chart and then add three subcharts to form a 2x2 grid. Each subchart is configured with specific dimensions and populated with data. The `inner_width` and `inner_height` of the main chart control the overall space available for subcharts. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart(inner_width=0.5, inner_height=0.5) chart2 = chart.create_subchart(position='right', width=0.5, height=0.5) chart3 = chart.create_subchart(position='left', width=0.5, height=0.5) chart4 = chart.create_subchart(position='right', width=0.5, height=0.5) chart.watermark('1') chart2.watermark('2') chart3.watermark('3') chart4.watermark('4') df = pd.read_csv('ohlcv.csv') chart.set(df) chart2.set(df) chart3.set(df) chart4.set(df) chart.show(block=True) ``` -------------------------------- ### Update Bars in Real-time Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/README.md Demonstrates updating chart bars with new data in real-time. Requires pandas for data manipulation and time.sleep for controlling update frequency. ```python import pandas as pd from time import sleep from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart() df1 = pd.read_csv('ohlcv.csv') df2 = pd.read_csv('next_ohlcv.csv') chart.set(df1) chart.show() last_close = df1.iloc[-1]['close'] for i, series in df2.iterrows(): chart.update(series) if series['close'] > 20 and last_close < 20: chart.marker(text='The price crossed $20!') last_close = series['close'] sleep(0.1) ``` -------------------------------- ### Export Chart to HTML File Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Generates a standalone HTML file containing the chart and opens it in the default browser. ```python from bn_lightweight_charts import HTMLChart import webbrowser chart = HTMLChart(width=1200, height=600, filename='my_chart.html') df = pd.read_csv('ohlcv.csv') chart.set(df) chart.load() webbrowser.open('my_chart.html') ``` -------------------------------- ### Configure Multi-Pane Charts Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Use HTMLChart to render charts with multiple panes by assigning unique pane_index values to series. Requires browser viewing via HTML output. ```python import pandas as pd import webbrowser from bn_lightweight_charts import HTMLChart def calculate_sma(df, period, name=None): name = name or f'SMA {period}' return pd.DataFrame({ 'time': df['time'], name: df['close'].rolling(window=period).mean() }) if __name__ == '__main__': # HTMLChart outputs to file for browser viewing chart = HTMLChart(width=1200, height=800, filename='multi_pane.html') chart.legend(visible=True) df = pd.read_csv('ohlcv.csv') chart.set(df) # Pane 0 (main chart) - Add moving averages sma_fast = chart.create_line('SMA 7', color='red', pane_index=0) sma_fast.set(calculate_sma(df, 7)) sma_slow = chart.create_line('SMA 21', color='blue', pane_index=0) sma_slow.set(calculate_sma(df, 21)) # Pane 1 - Histogram indicator histogram = chart.create_histogram( 'Momentum', price_line=False, pane_index=1 # New pane below main chart ) momentum_data = calculate_sma(df, 10, name='Momentum') histogram.set(momentum_data) # Pane 2 - Another line indicator rsi_line = chart.create_line('RSI', color='purple', pane_index=2) rsi_data = calculate_sma(df, 14, name='RSI') # Simplified example rsi_line.set(rsi_data) chart.load() webbrowser.open(chart.filename) ``` -------------------------------- ### Manage TopBar Textbox Widgets Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/reference/topbar.md Demonstrates how to declare, access, and update a textbox widget within the chart's top bar. ```python chart.topbar.textbox('symbol', 'AAPL') # Declares a textbox displaying 'AAPL'. print(chart.topbar['symbol'].value) # Prints the value within 'symbol' -> 'AAPL' chart.topbar['symbol'].set('MSFT') # Sets the 'symbol' textbox to 'MSFT' print(chart.topbar['symbol'].value) # Prints the value again -> 'MSFT' ``` -------------------------------- ### QtChart Object Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/reference/charts.md Enables the use of charts within a QMainWindow object using PyQt or PySide. ```APIDOC ## class QtChart ### Description The `QtChart` object allows the use of charts within a `QMainWindow` object, and has similar functionality to the `Chart` object for manipulating data, configuring and styling. Either the `PyQt5`, `PyQt6` or `PySide6` libraries will work with this chart. Callbacks can be received through the Qt event loop. ### Constructor `QtChart(widget: QWidget)` ### Methods #### get_webview() -> QWebEngineView Returns the `QWebEngineView` object. ``` -------------------------------- ### Topbar switcher implementation in Python Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/tutorials/events.md Configures a switcher widget in the topbar for selecting options like timeframes. ```python from bn_lightweight_charts import Chart def on_timeframe_selection(chart): print(f'Getting data with a {chart.topbar["my_switcher"].value} timeframe.') if __name__ == '__main__': chart = Chart() chart.topbar.switcher( name='my_switcher', options=('1min', '5min', '30min'), default='5min', func=on_timeframe_selection) chart.show(block=True) ``` -------------------------------- ### Capture Chart Screenshot Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Programmatically captures the current chart view as an image file. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart() df = pd.read_csv('ohlcv.csv') chart.set(df) chart.legend(visible=True, text='AAPL Daily') chart.watermark('AAPL', font_size=50) chart.show() # Must show chart first # Take screenshot after chart is visible img_bytes = chart.screenshot() with open('chart_screenshot.png', 'wb') as f: f.write(img_bytes) print('Screenshot saved!') ``` -------------------------------- ### Create Line Indicators with SMA Calculation Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/index.md Demonstrates creating a line indicator for Simple Moving Average (SMA). The `calculate_sma` function computes the SMA, and the chart is configured to display it. Requires 'ohlcv.csv'. ```python import pandas as pd from bn_lightweight_charts import Chart def calculate_sma(df, period: int = 50): return pd.DataFrame({ 'time': df['date'], f'SMA {period}': df['close'].rolling(window=period).mean() }).dropna() if __name__ == '__main__': chart = Chart() chart.legend(visible=True) df = pd.read_csv('ohlcv.csv') chart.set(df) line = chart.create_line('SMA 50') sma_data = calculate_sma(df, period=50) line.set(sma_data) chart.show(block=True) ``` -------------------------------- ### Type Definitions and Literals Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/docs/source/reference/typing.md Overview of the classes used for type hinting and validation within the library. ```APIDOC ## Type Definitions ### NUM - **Type**: Literal[float, int] - **Description**: Placeholder for numeric values. ### FLOAT - **Type**: Literal['left', 'right', 'top', 'bottom'] - **Description**: Defines positioning constraints. ### TIME - **Type**: Union[datetime, pd.Timestamp, str] - **Description**: Accepted formats for time-series data. ### COLOR - **Type**: str - **Description**: Supports rgb(), rgba(), hex codes, or HTML color literals. ### LINE_STYLE - **Type**: Literal['solid', 'dotted', 'dashed', 'large_dashed', 'sparse_dotted'] - **Description**: Available styles for chart lines. ### MARKER_POSITION - **Type**: Literal['above', 'below', 'inside'] - **Description**: Positioning for chart markers. ### MARKER_SHAPE - **Type**: Literal['arrow_up', 'arrow_down', 'circle', 'square'] - **Description**: Available shapes for chart markers. ### CROSSHAIR_MODE - **Type**: Literal['normal', 'magnet'] - **Description**: Behavior modes for the chart crosshair. ### PRICE_SCALE_MODE - **Type**: Literal['normal', 'logarithmic', 'percentage', 'index100'] - **Description**: Scaling modes for the price axis. ### ALIGN - **Type**: Literal['left', 'right'] - **Description**: Alignment options for text or elements. ``` -------------------------------- ### Initial Call to Refresh Numeric Decorations in JavaScript Source: https://github.com/smalinin/bn_lightweight-charts-python/blob/main/bn_lightweight_charts/js/index_bn.html Ensures that numeric decorations are applied to the tables immediately upon script execution, before any mutations occur. This is a one-time call to set the initial state. ```javascript refreshNumericDecorations(); ``` -------------------------------- ### Create Synchronized Subcharts Source: https://context7.com/smalinin/bn_lightweight-charts-python/llms.txt Use create_subchart to display multiple symbols side-by-side. Call sync_charts after all subcharts are initialized to link scrolling and crosshairs. ```python import pandas as pd from bn_lightweight_charts import Chart if __name__ == '__main__': chart = Chart(width=1200, height=800) chart.legend(visible=True, text='AAPL') # Main chart data aapl = pd.read_csv('AAPL.csv') chart.set(aapl) # Create subchart (synchronized by default) subchart = chart.create_subchart( position='right', # 'left', 'right', 'top', 'bottom' width=0.5, # 50% of window width height=1.0, # 100% of window height sync=True, # Sync scrolling and crosshair sync_crosshairs_only=False, # If True, only sync crosshair toolbox=False ) subchart.legend(visible=True, text='GOOGL') # Subchart data googl = pd.read_csv('GOOGL.csv') subchart.set(googl) # Sync all charts (call after creating all subcharts) chart.sync_charts(sync_crosshairs_only=False) chart.show(block=True) ```