### Perform Initial Chart Setup Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Executes the initial setup for the chart, including rendering the chart and attaching it to the DOM. ```typescript this.Jm(),t.appendChild(this.yp),this.Qm() ``` -------------------------------- ### Install backtrader-next Source: https://github.com/smalinin/backtrader_next/blob/master/README.md Command to install the package via pip. ```bash pip install backtrader-next ``` -------------------------------- ### Handle Touch Start Logic Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Contains the core logic for handling touch start events. Captures initial touch points, sets up timers, and prepares for subsequent touch events. ```javascript mf(t){if(null!==this.Id)return;const i=t.changedTouches[0];this.Id=i.identifier,this.Bd=ps(t);const s=this.Zd.ownerDocument.documentElement;this.bd=!1,this.gd=!1,this.Ed=!1,this.wd=fs(i),this.kd&&(this.kd(),this.kd=null);{const i=this.nf.bind(this),n=this.cf.bind(this);this.kd=()=>{s.removeEventListener("touchmove",i),s.removeEventListener("touchend",n)},s.addEventListener("touchmove",i,{passive:!1}),s.addEventListener("touchend",n,{passive:!1}),this.Jd(),this.pd=setTimeout(this.wf.bind(this,t),240)}const n=this.Wd(t,i);this.Ud(n,this.jd.gf),this.dd||(this.ud=0,this.dd=setTimeout(this.qd.bind(this),500),this.fd=fs(i))} ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/smalinin/backtrader_next/blob/master/examples/3_perf_compare/README.md Use uv for fast and efficient dependency management. Ensure Python 3.13 is installed. ```bash pip install uv ``` -------------------------------- ### Install IbPy using pip with Git Source: https://github.com/smalinin/backtrader_next/blob/master/README.md Use this command to install the IbPy library if you have Git installed on your system. ```bash pip install git+https://github.com/blampe/IbPy.git ``` -------------------------------- ### Strategy Output Log Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/README.md Example output log displaying performance metrics for a specific strategy run. ```text Strategy SmaCross MA1 35 MA2 65 Start 2010-01-04 00:00:00 End 2024-12-31 00:00:00 Duration 5475 days 00:00:00 Equity Start [$] 1000000.0 Equity Final [$] 7218593.659401 Equity Peak [$] 8087290.121056 Commissions [$] 0.0 Cum Return [%] 621.8594 Return (Ann.) [%] 14.1133 Volatility (Ann.) [%] 18.548 CAGR [%] 9.52 Sharpe Ratio 0.8049 Skew -0.1963 Kurtosis 15.8372 Smart Sharpe Ratio 0.4396 Sortino Ratio 1.1743 VWR Ratio 4.8679 Calmar Ratio 0.4326 Recovery factor [%] 6.8521 Max. Drawdown [%] -32.6211 Avg. Drawdown [%] -2.8806 Max. Drawdown Duration 1098 days 00:00:00 Avg. Drawdown Duration 35 days 00:00:00 Drawdown Peak 2023-01-05 00:00:00 # Trades 26 Win Rate [%] 61.5385 Best Trade [%] 113.7157 Worst Trade [%] -15.1364 Avg. Trade [%] 8.8499 Max. Trade Duration 846 days 00:00:00 Avg. Trade Duration 145 days 00:00:00 Profit Factor 1.1934 Expectancy [%] 0.0592 SQN 2.2167 Kelly Criterion [%] 49.468 dtype: object ``` -------------------------------- ### Install IbPy using pip without Git Source: https://github.com/smalinin/backtrader_next/blob/master/README.md Use this command to install the IbPy library if Git is not available on your system. It downloads the master zip archive. ```bash pip install https://github.com/blampe/IbPy/archive/master.zip ``` -------------------------------- ### Component Initialization and Lifecycle Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Handles the creation of DOM elements, canvas setup, and lifecycle management for chart components. ```javascript ("td"),this.Mm.style.padding="0",this.qf=document.createElement("td"),this.qf.style.height="25px",this.qf.style.padding="0",this.bm=document.createElement("div"),this.bm.style.width="100%",this.bm.style.height="100%",this.bm.style.position="relative",this.bm.style.overflow="hidden",this.qf.appendChild(this.bm),this.Zp=xs(this.bm,Qi({width:16,height:16})),this.Zp.subscribeSuggestedBitmapSizeChanged(this.Up);const s=this.Zp.canvasElement;s.style.position="absolute",s.style.zIndex="1",s.style.left="0",s.style.top="0",this.Gp=xs(this.bm,Qi({width:16,height:16})),this.Gp.subscribeSuggestedBitmapSizeChanged(this.jp);const n=this.Gp.canvasElement;n.style.position="absolute",n.style.zIndex="2",n.style.left="0",n.style.top="0",this.yp.appendChild(this.gm),this.yp.appendChild(this.qf),this.yp.appendChild(this.Mm),this.xm(),this.Dp.Qt().Eo().i(this.xm.bind(this),this),this.Lf=new us(this.Gp.canvasElement,this,{hf:()=>!0,af:()=>!this.Dp.N().handleScroll.horzTouchDrag}) ``` ```javascript m(){this.Lf.m(),null!==this.fm&&this.fm.m(),null!==this.pm&&this.pm.m(),this.Gp.unsubscribeSuggestedBitmapSizeChanged(this.jp),Ss(this.Gp.canvasElement),this.Gp.dispose(),this.Zp.unsubscribeSuggestedBitmapSizeChanged(this.Up),Ss(this.Zp.canvasElement),this.Zp.dispose()} ``` -------------------------------- ### Handle Touch Start for Multi-touch Detection Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Detects the start of a multi-touch gesture. Sets up listeners for touchmove and touchend events to handle pinch-to-zoom. ```javascript if(2===t.touches.length&&null!==this.Td&&void 0!==this.jd.yf){const i=cs(t.touches[0],t.touches[1])/this.Rd;this.jd.yf(this.Td,i),ds(t)}} ``` -------------------------------- ### Implement Simple Moving Average Crossover Strategy Source: https://github.com/smalinin/backtrader_next/blob/master/README.md A complete example demonstrating a strategy with a custom sizer, SMA indicators, and performance reporting. ```python import pandas as pd import backtrader_next as bt from backtrader_next.feeds import PandasData class SimpleSizer(bt.Sizer): params = ( ('percents', 99), ) def _getsizing(self, comminfo, cash, data, isbuy): value = self.broker.getvalue() price = data.close[0]+comminfo.p.commission size = value / price * (self.p.percents / 100) return int(size) class SmaCross(bt.Strategy): params = ( ('MA1', 20), ('MA2', 50), ) def __init__(self): self.Order = None self.ma1 = bt.nind.SMA(self.data.close, period=self.p.MA1) self.ma2 = bt.nind.SMA(self.data.close, period=self.p.MA2) def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: # Order is submitted/accepted return # Do nothing until the order is completed elif order.status in [order.Canceled]: print('Order was Canceled', self.data.datetime.datetime(0)) elif order.status in [order.Margin]: print('Order was Margin ', self.data.datetime.datetime(0)) elif order.status in [order.Rejected]: print('Order was Rejected', self.data.datetime.datetime(0)) self.Order = None # Reset order def next(self): # Use ONLY Long Positions if self.crossover(self.ma1, self.ma2): pos = self.getposition() if pos: self.close(size=pos.size) self.Order = self.buy() elif self.crossover(self.ma2, self.ma1): pos = self.getposition() if pos: self.close(size=pos.size) # self.Order = self.sell() def crossover(self, ma1, ma2): try: return ma1[-1] <= ma2[-1] and ma1[0] > ma2[0] except IndexError: return False if __name__ == '__main__': cerebro = bt.Cerebro() cerebro.broker.setcash(1_000_000.0) cerebro.broker.set_shortcash(False) cerebro.broker.setcommission(commission=0, margin=False) cerebro.addsizer(SimpleSizer, percents=90) df = pd.read_csv(f"AAPL_1d.csv.zip", sep=";") df['Datetime'] = pd.to_datetime(df['Date'].astype(str) , format='%Y-%m-%d') df.set_index('Datetime', inplace=True) data = PandasData(dataframe=df, timeframe=bt.TimeFrame.Days, compression=1) cerebro.adddata(data, name='AAPL') cerebro.addstrategy(SmaCross, ) print(f'Starting Portfolio Value: {cerebro.broker.getvalue():.2f}\n') results = cerebro.run() print(f'\nFinal Portfolio Value: {cerebro.broker.getvalue():.2f}\n') rc = cerebro.statistics print(rc) # old plot required matplotlib # cerebro.old_plot(style='candle') cerebro.plot(filename="smacross.html") cerebro.show_report(filename="smacross_stats.html") print("end") ``` -------------------------------- ### Handle Mousedown for Zoom Start Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initiates zoom behavior on mousedown. Sets initial zoom state and prepares for mousemove events. ```javascript if(0!==t.button)return;const i=this.Wd(t);this.Pd&&this.Pd();const s=this.tf.bind(this);if(this.Pd=()=>{this.Zd.removeEventListener("mousemove",i)},this.Zd.addEventListener("mousemove",i),this.Nd(t))return;const s=this.Wd(t);this.Yd(s,this.jd.if),this.Ad=!0}} ``` -------------------------------- ### Handle Touch Start Event Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Manages the initiation of touch interactions, including single and multi-touch gestures. Sets up listeners for subsequent touch events. ```javascript this.Zd.addEventListener("touchstart", this.mf.bind(this),{passive:!0}) ``` -------------------------------- ### Handle Mousedown for Panning Start Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initiates panning behavior on mousedown. Sets initial pan position and prepares for mousemove events. ```javascript if(0!==t.button)return;const i=this.Wd(t);this.Pd&&this.Pd();const s=this.tf.bind(this);if(this.Pd=()=>{this.Zd.removeEventListener("mousemove",i)},this.Zd.addEventListener("mousemove",i),this.Nd(t))return;const s=this.Wd(t);this.Yd(s,this.jd.if),this.Ad=!0} ``` -------------------------------- ### Handle Mousedown for Drag Start Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initiates drag behavior on mousedown. Sets initial drag position and prepares for mousemove events. ```javascript if(0!==t.button)return;const i=this.Zd.ownerDocument.documentElement;as()&&i.addEventListener("mouseleave",this.zd),this.Md=!1,this.md=fs(t),this.yd&&(this.yd(),this.yd=null);{const t=this._f.bind(this),s=this.Od.bind(this);this.yd=()=>{i.removeEventListener("mousemove",t),i.removeEventListener("mouseup",s)},i.addEventListener("mousemove",t),i.addEventListener("mouseup",s)}if(this.Vd=!0,this.Nd(t))return;const s=this.Wd(t);this.Yd(s,this.jd.bf),this.od||(this.ld=0,this.od=setTimeout(this.Xd.bind(this),500),this._d=fs(t))} ``` -------------------------------- ### Setup Global Event Listeners Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Adds global event listeners for mouse and touch interactions. This includes listeners for document-level events like mouseleave. ```javascript {const t=this.Zd.ownerDocument,i=t=>{this.jd.xf&&(t.composed&&this.Zd.contains(t.composedPath()[0])||t.target&&this.Zd.contains(t.target)||this.jd.xf())};this.Sd=()=>{t.removeEventListener("touchstart",i)},this.xd=()=>{t.removeEventListener("mousedown",i)},t.addEventListener("mousedown",i),t.addEventListener("touchstart",i,{passive:!0})} ``` -------------------------------- ### Get the version of Lightweight Charts Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Retrieve the currently installed version of the Lightweight Charts library using the `version` function. ```javascript const version = LightweightCharts.version(); ``` -------------------------------- ### Execute smacross sample Source: https://github.com/smalinin/backtrader_next/blob/master/examples/1_smacross/README.md Run the main script using the UV package manager. ```bash uv run main.py ``` -------------------------------- ### Initialize Charting Library Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initializes the global charting environment and configuration settings. ```javascript var Lib=function(t,e){"use strict";const i={backgroundColor:"rgb(18,24,38)",hoverBackgroundColor:"#3c434c",clickBackgroundColor:"#50565E",activeBackgroundColor:"rgba(0, 122, 255, 0.7)",mutedBackgroundColor:"rgba(0, 122, 255, 0.3)",borderColor:"#3C434C",color:"#d8d9db",activeColor:"#ececed"};function s(){window.pane={...i},window.containerDiv=document.getElementById("container")||document.createElement("div"),window.setCursor=t=>{t&&(window.cursor=t),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1} ``` -------------------------------- ### Handle Touchstart for Gestures Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initializes touch gesture handling. Sets up touchmove and touchend listeners and captures initial touch points. ```javascript this.Id=i.identifier,this.Bd=ps(t);const s=this.Zd.ownerDocument.documentElement;this.bd=!1,this.gd=!1,this.Ed=!1,this.wd=fs(i),this.kd&&(this.kd(),this.kd=null);{const i=this.nf.bind(this),n=this.cf.bind(this);this.kd=()=>{s.removeEventListener("touchmove",i),s.removeEventListener("touchend",n)},s.addEventListener("touchmove",i,{passive:!1}),s.addEventListener("touchend",n,{passive:!1}),this.Jd(),this.pd=setTimeout(this.wf.bind(this,t),240)}const n=this.Wd(t,i);this.Ud(n,this.jd.gf),this.dd||(this.ud=0,this.dd=setTimeout(this.qd.bind(this),500),this.fd=fs(i))} ``` -------------------------------- ### Update of bidask sample Source: https://github.com/smalinin/backtrader_next/blob/master/changelog.txt An updated sample demonstrating the use of bidask data. ```python Update of bidask sample ``` -------------------------------- ### Get Chart Instance Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns the currently active chart instance. ```javascript Wt(){return this.qi} ``` -------------------------------- ### Price Scale Initialization and Configuration Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initialization logic for price scales and managing multiple scale instances. ```javascript class mi{constructor(t,i){this.dl=[],this.wo=new Map,this.sl=0,this.Mo=0,this.bo=1,this.pl=null,this.xo=!1,this.So=new o,this.yh=[],this.uh=t,this.ts=i,this.Co=new Jt(this);const s=i.N();this.Po=this.yo("left",s.leftPriceScale),this.ko=this.yo("right",s.rightPriceScale),this.Po.Al().i(this.To.bind(this,this.Po),this),this.ko.Al().i(this.To.bind(this,this.ko),this),this.Ro(s)}Ro(t){if(t.leftPriceScale&&this.Po.hr(t.leftPriceScale),t.rightPriceScale&&this.ko.hr(t.rightPriceScale),t.localization&&(this.Po.ga(),this.ko.ga()),t.overlayPriceScales){const i=Array.from(this.wo.values());for(const s of i){const i=a(s[0].Wt());i.hr(t.overlayPriceScales),t.localization&&i.ga()}}} ``` -------------------------------- ### Get Component Options Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns the options object associated with this component. ```typescript N(){return this.Ps} ``` -------------------------------- ### Get Specific Table Cell Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Retrieves a cell element from a specific row and heading. ```javascript _getCell(t,e){return this.rows[t].cells[this.headings.indexOf(e)]} ``` -------------------------------- ### Add sample for LinesCoupler Source: https://github.com/smalinin/backtrader_next/blob/master/changelog.txt Includes a sample demonstrating the usage of the LinesCoupler object. ```python Add sample for LinesCoupler ``` -------------------------------- ### Get Current Bar Count Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Returns the current number of bars processed by the ticker. ```javascript Qi(){ return this.Mo } ``` -------------------------------- ### Integrating Live Trading Adapters Source: https://context7.com/smalinin/backtrader_next/llms.txt Configure live trading using Interactive Brokers or Oanda store adapters. ```python import backtrader_next as bt from backtrader_next.stores import IBStore # Interactive Brokers live trading ibstore = IBStore( host='127.0.0.1', port=7497, clientId=1, ) cerebro = bt.Cerebro() # Use IB as broker cerebro.setbroker(ibstore.getbroker()) # Add live data feed data = ibstore.getdata( dataname='AAPL-STK-SMART-USD', timeframe=bt.TimeFrame.Minutes, compression=1, ) cerebro.adddata(data) # Add strategy cerebro.addstrategy(MyStrategy) # Run live cerebro.run() # Oanda forex trading from backtrader_next.stores import OandaStore oandastore = OandaStore( token='your-api-token', account='your-account-id', practice=True, # Use practice account ) cerebro = bt.Cerebro() cerebro.setbroker(oandastore.getbroker()) data = oandastore.getdata( dataname='EUR_USD', timeframe=bt.TimeFrame.Minutes, compression=5, ) cerebro.adddata(data) cerebro.addstrategy(ForexStrategy) cerebro.run() ``` -------------------------------- ### Get Chart Instance Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns the chart instance, which is the primary object for interacting with the chart. ```typescript this.ts=new Ii(this.Zu.bind(this),this.Ps,s) ``` -------------------------------- ### Create a new chart instance Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Use `createChart` to initialize a new chart. Pass the DOM element or its ID and an options object for initial configuration. ```javascript createChart(document.getElementById('chart'), { width: 600, height: 300, layout: { backgroundColor: '#222', textColor: 'white', }, }); ``` -------------------------------- ### Handle Touchstart for Multi-touch Zoom Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initializes multi-touch gestures, specifically for zoom. Captures initial touch points and calculates the distance for scaling. ```javascript const i=vs(t.changedTouches,a(this.Id));if(null===i)return;if(this.Bd=ps(t),null!==this.Td)return;if(this.Ed)return;this.Dd=!0;const s=this.Hd(fs(i),a(this.wd)),{ef:n,rf:e,Fd:r}=s;if(this.gd||!(r<5)){if(!this.gd){const t=.5*n,i=e>=t&&!this.Ps.hf(),s=t>e&&!this.Ps.af();i||s||(this.Ed=!0),this.gd=!0,this.bd=!0,this.Jd(),this.qd()}if(!this.Ed){const s=this.Wd(t,i);this.Ud(s,this.jd.lf),ds(t)}}} ``` -------------------------------- ### Get Chart Title Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns the title of the chart as configured in the component's options. ```typescript Ie(){return this.Ps.title} ``` -------------------------------- ### Sample for bidask data to OHLC Source: https://github.com/smalinin/backtrader_next/blob/master/changelog.txt Provides a sample demonstrating the conversion of bidask data to OHLC format, closing issue #78. ```python Sample for bidask data to OHLC. Closes #78 ``` -------------------------------- ### Default horizontal scale behavior Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Get the default behavior configuration for the horizontal scale of the chart. ```javascript const defaultBehavior = defaultHorzScaleBehavior(); ``` -------------------------------- ### Get Right Offset Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Returns the current right offset, which influences the positioning of the last bar. ```javascript wu(){ return this.U_ } ``` -------------------------------- ### Get Bar Spacing Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Returns the current bar spacing, which determines the horizontal distance between bars. ```javascript vu(){ return this.j_ } ``` -------------------------------- ### Get Chart Height for Scaling Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Retrieves the total height of the chart, used for scaling calculations. ```javascript Ua(){return this.qi.P()} ``` -------------------------------- ### Comprehensive IB testing sample Source: https://github.com/smalinin/backtrader_next/blob/master/changelog.txt A sample demonstrating comprehensive testing with the Interactive Brokers (IB) platform. ```python Comprehensive ib testing sample ``` -------------------------------- ### Get Time Scale Annotations Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns an array of all time scale annotations currently present on the chart. ```typescript Wh(){return this.bh} ``` -------------------------------- ### Handle Touchstart for Single Touch Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initializes single-touch interactions. Captures touch identifier and sets up listeners for touchmove and touchend. ```javascript if(null!==this.Id)return;const i=t.changedTouches[0];this.Id=i.identifier,this.Bd=ps(t);const s=this.Zd.ownerDocument.documentElement;this.bd=!1,this.gd=!1,this.Ed=!1,this.wd=fs(i),this.kd&&(this.kd(),this.kd=null);{const i=this.nf.bind(this),n=this.cf.bind(this);this.kd=()=>{s.removeEventListener("touchmove",i),s.removeEventListener("touchend",n)},s.addEventListener("touchmove",i,{passive:!1}),s.addEventListener("touchend",n,{passive:!1}),this.Jd(),this.pd=setTimeout(this.wf.bind(this,t),240)}const n=this.Wd(t,i);this.Ud(n,this.jd.gf),this.dd||(this.ud=0,this.dd=setTimeout(this.qd.bind(this),500),this.fd=fs(i))} ``` -------------------------------- ### Get Maximum Y-Axis Value Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Calculates and returns the maximum y-axis value across all series currently being tracked. ```javascript function hn.Xw(){if(0===this.Ow.size)return null; let t=0; return this.Ow.forEach((i=>{0!==i.length&&(t=Math.max(t,i[i.length-1].Re))})), t} ``` -------------------------------- ### Adapt docs and test to new interfaces Source: https://github.com/smalinin/backtrader_next/blob/master/changelog.txt Updates documentation and tests to reflect the removal of old DataReplayer/DataResampler and the adoption of newer interfaces. ```python Adapt docs and test to remove DataReplayer/DataResampler and document the newer interfaces ``` -------------------------------- ### Get Calculated Grid Lines Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Returns the list of calculated grid lines, including their coordinates and scaling factors. ```javascript Ea(){return this.La} ``` -------------------------------- ### Initialize Event Listeners Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Sets up all necessary event listeners for mouse and touch interactions on the target element. Includes listeners for enter, leave, mousedown, mouseup, touchstart, touchmove, touchend, and touchcancel. ```javascript this.Zd.addEventListener("mouseenter", this.Qd.bind(this)),this.Zd.addEventListener("touchcancel", this.Jd.bind(this));{const t=this.Zd.ownerDocument,i=t=>{this.jd.xf&&(t.composed&&this.Zd.contains(t.composedPath()[0])||t.target&&this.Zd.contains(t.target)||this.jd.xf())};this.Sd=()=>{t.removeEventListener("touchstart",i)},this.xd=()=>{t.removeEventListener("mousedown",i)},t.addEventListener("mousedown",i),t.addEventListener("touchstart",i,{passive:!0})}ls()&&(this.Cd=()=>{this.Zd.removeEventListener("dblclick",this.Ld)},this.Zd.addEventListener("dblclick",this.Ld)),this.Zd.addEventListener("mouseleave", this.Sf.bind(this)),this.Zd.addEventListener("touchstart", this.mf.bind(this),{passive:!0}),_s(this.Zd),this.Zd.addEventListener("mousedown", this.Mf.bind(this)),this.Cf(),this.Zd.addEventListener("touchmove",(()=>{}),{passive:!1}),_s(this.Zd)} ``` -------------------------------- ### Execute Backtrader Strategy with Arguments Source: https://github.com/smalinin/backtrader_next/blob/master/samples_old/pyfolio2/backtrader-pyfolio.ipynb Example of how to call a Backtrader strategy with a list of string arguments, simulating command-line input. This is useful for testing or programmatic execution. ```python runstrat('--data0 015ES --timeframe days --compression 1 --pyfolio --printout --cash 200000 --short'.split()) ``` -------------------------------- ### Get Data Series Manager Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns the data series manager instance, which handles all data-related operations for the component. ```typescript Xs(){return this.qt} ``` -------------------------------- ### Navigate Chart Time Range Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Adjusts the visible logical range of a chart based on provided start and end timestamps. ```javascript function scrollToTime(chart, stm0, stm1) { const tm0 = (new Date((stm0+":00").replace(' ','T')+'Z')).getTime()/1000 const tm1 = stm1 ? (new Date((stm1+":00").replace(' ','T')+'Z')).getTime()/1000 : null const scale = chart.timeScale() const tc0 = scale.timeToCoordinate(tm0) if (tc0) { const idx0 = scale.coordinateToLogical(tc0) if (tm1) { const tc1 = scale.timeToCoordinate(tm1) if (tc1) { const idx1 = scale.coordinateToLogical(tc1) scale.setVisibleLogicalRange({ from: idx0 - 5, to: idx1 + 5 }); document.querySelector("#nav-home-tab").click(); } } else { scale.setVisibleLogicalRange({ from: idx0 - 5, to: idx0 + 200 + 5 }); document.querySelector("#nav-home-tab").click(); } } } ``` -------------------------------- ### WeekDaysFiller sample for #76 Source: https://github.com/smalinin/backtrader_next/blob/master/changelog.txt Includes a sample demonstrating the WeekDaysFiller functionality, related to issue #76. ```python WeekDaysFiller sample for #76 ``` -------------------------------- ### Get Last Point Weight Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Iterates through a collection of points to find and return the 'Pw' (weight) of the last point encountered. ```javascript function rn(t){let i;return t.forEach((t=>{void 0===i&&(i=t.Pw)})),h(i)} ``` -------------------------------- ### Initialize and Manage ResizeObserver Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Initializes a ResizeObserver to monitor changes in the chart's container size. If ResizeObserver is not supported, it returns false. ```javascript Zm(){return"ResizeObserver"in window&&(this.Hm=new ResizeObserver((t=>{const i=t[t.length-1];i&&this.Gm(i.contentRect.width,i.contentRect.height)})),this.Hm.observe(this.Rp,{box:"border-box"}),!0)} ``` ```javascript sw(){null!==this.Hm&&this.Hm.disconnect(),this.Hm=null}} ``` -------------------------------- ### Get Middle Pane Views Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Retrieves views for the middle pane of the chart. This can be used for various types of chart elements. ```typescript ia(t){return this.Qh(Ft,t)} ``` -------------------------------- ### Initialize Chart Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Initializes the chart with provided data and options. This includes setting up panes, scales, and default behaviors. The constructor handles initial setup, and methods like `hr` can be used for subsequent updates. ```typescript constructor(t,i,s){this.$u=[],this.ju=[],this.Mo=0,this.qu=null,this.Yu=new o,this.Ku=new o,this.Xu=null,this.Zu=t,this.Ps=i,this.o_=s,this.Sl=new S(this.Ps.layout.colorParsers),this.Gu=new M(this),this.uh=new Ti(this,i.timeScale,this.Ps.localization,s),this.Ct=new j(this,i.crosshair),this.Ju=new qt(i.crosshair),i.addDefaultPane&&(this.Qu(0),this.$u[0].Bo(2)),this.tc=this.sc(0),this.nc=this.sc(1)} hr(t){_(this.Ps,t),this.$u.forEach((i=>i.Ro(t))),void 0!==t.timeScale&&this.uh.hr(t.timeScale),void 0!==t.localization&&this.uh.K_(t.localization),(t.leftPriceScale||t.rightPriceScale)&&this.Yu.p(),this.tc=this.sc(0),this.nc=this.sc(1),this.Bh()} ``` -------------------------------- ### Get Chart Data Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Retrieves the chart's data, likely containing price, time, and other relevant information for rendering. ```typescript const s={Ec:this.Dp.Qt().Ec()} ``` -------------------------------- ### Run strategy optimization Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/README.md Executes the optimization script using the UV package manager. ```bash uv run run_optimize.py ``` -------------------------------- ### Get Chart Instance Reference Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Provides access to the internal chart instance, which can be used for further manipulation or querying of chart properties. ```typescript Qt(){return this.ts} ``` -------------------------------- ### Run Backtesting.py Performance Test Source: https://github.com/smalinin/backtrader_next/blob/master/examples/3_perf_compare/README.md Execute the Backtesting.py framework for performance testing. This framework is known for its fastest execution. ```bash uv run main_backtesting.py ``` -------------------------------- ### Get Chart Canvas Width Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns the current width of the chart's canvas element. Useful for layout calculations. ```javascript hv(){return a(this.Op).width} ``` -------------------------------- ### Get Tickmark Renderer Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Retrieves or creates a renderer for tickmarks based on their weight. This is used for drawing tickmarks on the price scale. ```typescript Mu(t){let i=this.V_.get(t.weight);return void 0===i&&(i=new xi((t=>this.Uu(t)),this.o_),this.V_.set(t.weight,i)),i._(t)} ``` -------------------------------- ### Image Configuration Helper Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Utility function We to structure image configuration with source and dimensions. ```javascript function We(t,i,s,n){return{...t,jM:i,YM:s,qM:n}} ``` -------------------------------- ### Prepare for Bitmap Rendering Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Applies suggested bitmap size to the main drawing canvas. This is a preparatory step before drawing chart content. ```javascript lv(){if(null===this.Op||null===this.qi)return;let t=this.Op.height/2;const i=[],s=this.qi.Dt().slice(),n=this.Pt.hp(),e=this.iv();this.qi===n.$n()&&this.Pt.hp().Dt().forEach((t=>{n.Un(t)&&s.push(t)}));const r=this.qi.ba()[0],h=this.qi;s.forEach((s=>{const e=s.Fs(n,h);e.forEach((t=>{t.Fi(null),t.Hi()&&i.push(t)})),r===s&&e.length>0&&(t=e[0].Bi())})),i.forEach((t=>t.Fi(t.Bi())));this.qi.N().alignLabels&&this.vv(i,e,t)} ``` -------------------------------- ### Run Backtrader-next Performance Test Source: https://github.com/smalinin/backtrader_next/blob/master/examples/3_perf_compare/README.md Execute the Backtrader-next framework for performance testing. This is a modern, optimized fork of Backtrader. ```bash uv run main_backtrader_next.py ``` -------------------------------- ### Initialize Library and DOM Elements Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Initializes the library's global variables and DOM elements. Sets up default cursor and focus state. This function should be called once at the beginning of the application. ```javascript var Lib=function(t,e){"use strict";const i={backgroundColor:"rgb(18,24,38)",hoverBackgroundColor:"#3c434c",clickBackgroundColor:"#50565E",activeBackgroundColor:"rgba(0, 122, 255, 0.7)",mutedBackgroundColor:"rgba(0, 122, 255, 0.3)",borderColor:"#3C434C",color:"#d8d9db",activeColor:"#ececed"}; function s(){window.pane={...i},window.containerDiv=document.getElementById("container")||document.createElement("div"),window.setCursor=t=>{t&&(window.cursor=t),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1} function n(t){let e=document.createElement("template");t=t.trim(),e.innerHTML=t;const i=e.content.firstChild;if(!i)throw new Error("Invalid HTML passed to htmlToElement");return i} class o{ handler; div; seriesContainer; ohlcEnabled=!1; percentEnabled=!1; linesEnabled=!1; colorBasedOnCandle=!1; text; candle; _lines=[] _lines_grp={}; constructor(t){ this.legendHandler=this.legendHandler.bind(this); this.handler=t; this.ohlcEnabled=!1, this.percentEnabled=!1, this.linesEnabled=!1, this.colorBasedOnCandle=!1, this.div=document.createElement("div"), this.div.classList.add("legend"), this.div.style.maxWidth=100*t.scale.width-8+"vw", this.div.style.display="none"; const e=document.createElement("div"); e.style.display="flex", e.style.flexDirection="row"; this.seriesContainer=document.createElement("div"), this.seriesContainer.classList.add("series-container"), this.text=document.createElement("span"), this.text.style.lineHeight="1.8", this.candle=document.createElement("div"), e.appendChild(this.seriesContainer), this.div.appendChild(this.text), this.div.appendChild(this.candle), this.div.appendChild(e), t.div.appendChild(this.div), t.chart.subscribeCrosshairMove(this.legendHandler) } toJSON(){ const{_lines:t,handler:e,...i}=this; return i } makeSeriesRow(t,e,i){ const s="#FFF"; let o=`\n \n \ ` let r=`\n \n` const a=document.createElement("div"); a.style.display="flex", a.style.alignItems="center"; let l=document.createElement("div"), h=document.createElement("div"); h.classList.add("legend-toggle-switch"); let d=document.createElementNS("http://www.w3.org/2000/svg","svg"); d.setAttribute("width","22"), d.setAttribute("height","16"); let c=document.createElementNS("http://www.w3.org/2000/svg","g"); c.innerHTML=o; let p=!0; h.addEventListener("click",(()=>{ p?(p=!1,c.innerHTML=r,e.applyOptions({visible:!1})): (p=!0,e.applyOptions({visible:!0}),c.innerHTML=o) })), d.appendChild(c), h.appendChild(d), a.appendChild(l), a.appendChild(h), this.seriesContainer.appendChild(a); const u=e.options().baseLineColor; this._lines.push({name:t,paneIndex:i,div:l,row:a,toggle:h,series:e,solid:u.startsWith("rgba")?u.replace(/[^,]+(?=\))/,"1"):u}), this._lines.sort(((t,e)=>t.paneIndex-e.paneIndex)), this._lines_grp=this._lines.reduce(((t,e)=>((t[e.paneIndex]||(t[e.paneIndex]=[])),t[e.paneIndex].push(e),t)),{}), this.seriesContainer.innerHTML=""; for(const t in this._lines_grp){ for(const e of this._lines_grp[t]) this.seriesContainer.appendChild(e.row); this.seriesContainer.appendChild(n("
")) } } legendItemFormat(t,e){ return t.toFixed(e).toString().padStart(8," ") } shorthandFormat(t){ const e=Math.abs(t); return e>=1e6?(t/1e6).toFixed(1)+"M":e>=1e3?(t/1e3).toFixed(1)+"K":t.toString().padSt ``` -------------------------------- ### Get Price Scale Factor Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Calculates and returns the factor used for scaling prices, typically based on the chart's height. ```javascript Fa(){return Math.c} ``` -------------------------------- ### Create a chart with custom options Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Use `createOptionsChart` for creating charts with predefined options, often used for specific chart types or configurations. ```javascript const optionsChart = createOptionsChart(document.body, { width: 800, height: 400, }); ``` -------------------------------- ### Get Chart Width and Height Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Calculates the total width and height occupied by chart elements, including panes and price scales. ```typescript aw(t){let i=0,s=0;const n=this.Am[0],e=(i,s)=>{let n=0;for(let e=0;e{a("left"===i?this.Xm.Sm():this.Xm.Cm()).Jf(a(t),s,n)};if(this.Ps.timeScale.visible)} ``` -------------------------------- ### Get Chart Time Scale Instance Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns the time scale instance associated with the chart, allowing for manipulation of the time axis. ```typescript uc(){return this.Ku} ``` -------------------------------- ### Execute Strategy Source: https://github.com/smalinin/backtrader_next/blob/master/samples_old/pyfoliotest/backtrader-pyfolio.ipynb Runs the strategy with the provided arguments. ```python runstrat([]) ``` -------------------------------- ### Initialize Marker Configuration Source: https://github.com/smalinin/backtrader_next/blob/master/examples/2_optimize/smacross.html Creates a default configuration object for chart markers. ```javascript function er(t){return{...$e,...t}} ``` -------------------------------- ### Get Chart Layout Information Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Returns layout information for the chart, potentially including dimensions and positioning of various chart elements. ```typescript const t=this.Dp.Qt(),i=t.N() ``` -------------------------------- ### Showcase of Backtrader Next Indicators Source: https://context7.com/smalinin/backtrader_next/llms.txt Illustrates the initialization of various built-in indicators, including moving averages, momentum, volatility, trend indicators, and Numba-accelerated versions for faster execution. Example usage within the next method is also shown. ```python import backtrader_next as bt class IndicatorShowcase(bt.Strategy): def __init__(self): # Moving Averages self.sma = bt.indicators.SMA(self.data.close, period=20) self.ema = bt.indicators.EMA(self.data.close, period=12) self.wma = bt.indicators.WMA(self.data.close, period=10) # Numba-accelerated indicators (faster execution) self.sma_fast = bt.nind.SMA(self.data.close, period=20) self.ema_fast = bt.nind.EMA(self.data.close, period=12) self.macd_fast = bt.nind.MACD(self.data.close) # Momentum indicators self.rsi = bt.indicators.RSI(self.data.close, period=14) self.macd = bt.indicators.MACD(self.data.close) self.stoch = bt.indicators.Stochastic(self.data, period=14) self.momentum = bt.indicators.Momentum(self.data.close, period=12) # Volatility indicators self.atr = bt.indicators.ATR(self.data, period=14) self.bollinger = bt.indicators.BollingerBands(self.data.close, period=20) # Trend indicators self.adx = bt.indicators.ADX(self.data, period=14) self.aroon = bt.indicators.AroonUpDown(self.data, period=25) self.psar = bt.indicators.ParabolicSAR(self.data) # Crossover signals self.crossover = bt.indicators.CrossOver(self.sma, self.ema) # Advanced indicators self.ichimoku = bt.indicators.Ichimoku(self.data) self.pivot = bt.indicators.PivotPoint(self.data) self.cci = bt.indicators.CCI(self.data, period=20) def next(self): # Access indicator values if self.rsi[0] < 30 and self.macd.macd[0] > self.macd.signal[0]: if self.data.close[0] > self.bollinger.lines.mid[0]: self.buy() # Check Bollinger Band breakout if self.data.close[0] > self.bollinger.lines.top[0]: print(f"Upper band breakout at {self.data.datetime.date()}") ``` -------------------------------- ### Get Custom Cursor Style Source: https://github.com/smalinin/backtrader_next/blob/master/docs/2_optimize/smacross.html Retrieves the currently set custom CSS cursor style for the chart's main container. ```typescript dw(){return this.Um} ```