### Generate Getting Started Documentation Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmb/workflows/module/steps-c/step-06-docs.md This markdown file provides a 'Getting Started' guide for the module, covering its purpose, installation, initial steps, common use cases, and where to find further help. ```markdown # Getting Started with {module_display_name} Welcome to {module_code}! This guide will help you get up and running. - -- ## What This Module Does {module_purpose_from_brief} - -- ## Installation If you haven't installed the module yet: ```bash bmad install {module_code} ```bash Follow the prompts to configure the module for your needs. - -- ## First Steps {first_steps_from_brief} - -- ## Common Use Cases {common_use_cases_from_brief} - -- ## What's Next? - Check out the [Agents Reference](agents.md) to meet your team - Browse the [Workflows Reference](workflows.md) to see what you can do - See [Examples](examples.md) for real-world usage - -- ## Need Help? If you run into issues: 1. Check the troubleshooting section in examples.md 2. Review your module configuration 3. Consult the broader BMAD documentation ```bash ``` -------------------------------- ### PyPI First-Time Setup Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/developer-guide/release.md Install necessary build tools and configure authentication for PyPI publishing. ```bash # Install build tools pip install build twine # Create API token at # Store in ~/.pypirc: [pypi] username = __token__ password = pypi-...your-token-here... ``` -------------------------------- ### Copy Example .env File Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/advanced/live-trading/ccxt-env-config.md Copy the example .env file to your project directory to start configuring your API keys. ```bash cp .env.example .env ``` -------------------------------- ### Example: Main function for Live Trading Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代112-基于BTBinance优化.md Demonstrates the setup and execution of a live trading session using LiveTradingEngine, including adding a strategy and starting the engine. ```python async def main(): cerebro = LiveTradingEngine( exchange_api=BinanceAPI(), symbol='BTCUSDT', timeframe='1m' ) cerebro.addstrategy(MyStrategy, param1=10, param2=20) await cerebro.start() ``` -------------------------------- ### Example: Live Data Source Setup Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代112-基于BTBinance优化.md Shows how to create and configure a LiveDataSource for real-time market data, including history backfilling. ```python from backtrader.live import LiveDataSource # 创建实时数据源 data = LiveDataSource( symbol='BTCUSDT', timeframe='1m', history_bars=100, backfill=True ) # 添加到 Cerebro cerebro = bt.Cerebro() cerebro.adddata(data) # 添加策略 cerebro.addstrategy(MyStrategy) # 运行 cerebro.run() ``` -------------------------------- ### Practical Phase Example Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/advanced/architecture/phase-system.md A complete example demonstrating the prenext, nextstart, and next phases in a Backtrader strategy, including data feed setup. ```python import backtrader as bt from datetime import datetime class PhaseExample(bt.Strategy): params = (('period', 20),) def __init__(self): self.sma = bt.indicators.SMA(period=self.params.period) self.prenext_count = 0 def prenext(self): self.prenext_count += 1 # Logging not recommended during backtest # Use observer instead def nextstart(self): # This is the first bar with valid SMA value print(f"First valid bar: {len(self)}") def next(self): # Normal execution if len(self) == self.params.period + 1: print(f"Second valid bar: SMA = {self.sma[0]:.2f}") cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime(2020, 1, 1), todate=datetime(2020, 12, 31)) cerebro.adddata(data) cerebro.addstrategy(PhaseExample) cerebro.run() ``` -------------------------------- ### CTPStore Quick Reference Example Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/brokers/ctp-store-broker.md A quick reference guide demonstrating the steps to create a CTPStore, get a data feed, set the broker, and add it to a Backtrader Cerebro instance. ```APIDOC ## CTPStore Quick Reference ### Description This example demonstrates the basic workflow for setting up a CTP broker and data feed within Backtrader. ### Steps 1. **Create store**: Initialize `bt.stores.CTPStore` with connection parameters. 2. **Create data feed**: Use `store.getdata()` to obtain a data feed for a specific instrument. 3. **Create broker**: Obtain a broker instance from the store using `store.getbroker()` and configure commissions. 4. **Add to cerebro**: Add the data feed and strategy to the Backtrader `cerebro` engine. ### Code Example ```python import backtrader as bt # 1. Create store store = bt.stores.CTPStore( td_front='tcp://182.254.243.31:30001', md_front='tcp://182.254.243.31:30011', broker_id='9999', user_id='your_id', password='your_password', app_id='simnow_client_test', auth_code='0000000000000000', ) # 2. Create data feed data = store.getdata( dataname='rb2501.SHFE', timeframe=bt.TimeFrame.Minutes, compression=1, num_init_backfill=100, ) # 3. Create broker cerebro.setbroker(store.getbroker( use_positions=True, commission=1.0, )) # 4. Add to cerebro cerebro.adddata(data) cerebro.addstrategy(YourStrategy) ``` ``` -------------------------------- ### First Time Setup for Backtrader Development Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/developer-guide/contributing.md Follow these steps to set up your local development environment for Backtrader. This includes forking, cloning, installing dependencies, and compiling Cython extensions. ```bash # 1. Fork the repository on GitHub # Click "Fork" button at # 2. Clone your fork git clone cd backtrader # 3. Add upstream remote git remote add upstream # 4. Install dependencies pip install -r requirements.txt # 5. Install in development mode pip install -e . # 6. Compile Cython extensions (recommended for performance) cd backtrader && python -W ignore compile_cython_numba_files.py && cd .. ``` -------------------------------- ### Example Command to Start Development Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmm/workflows/bmad-quick-flow/quick-spec/steps/step-04-review.md This code block provides the exact command to initiate the development process using the finalized tech-spec file, emphasizing the use of a clean context. ```bash quick-dev {finalFile} ``` -------------------------------- ### Example Usage of FutuStore Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代95-基于bt-futu-store优化.md Demonstrates the basic setup for using FutuStore within a backtrader strategy. Requires importing necessary backtrader and futu modules. ```python """ 使用富途 Store 的完整示例 """ import backtrader as bt from backtrader.stores.futustore import FutuStore from backtrader.stores.base import MarketType import futu as ft ``` -------------------------------- ### Example: Live Trading Engine Initialization and Execution Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代112-基于BTBinance优化.md Demonstrates setting up and running a live trading engine with Binance API credentials, adding a strategy, and managing the trading session duration. ```python from backtrader.live import LiveTradingEngine import asyncio async def main(): # 创建实时交易引擎 engine = LiveTradingEngine( exchange_api=BinanceAPI( api_key='your_api_key', api_secret='your_api_secret' ), symbol='BTCUSDT', timeframe='1m' ) # 添加策略 engine.addstrategy(MyStrategy, param1=10) # 启动 await engine.start() # 运行 1 小时 await asyncio.sleep(3600) # 停止 await engine.stop() asyncio.run(main()) ``` -------------------------------- ### Generate README.md Structure Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmb/workflows/module/steps-c/step-06-docs.md This markdown structure defines the content for the module's README.md file, providing an overview, installation instructions, quick start guide, component details, configuration, module structure, documentation links, development status, author, and license. ```markdown # {module_display_name} {brief_header} {subheader} - -- ## Overview {module_overview_from_brief} - -- ## Installation ```bash bmad install {module_code} ```bash - -- ## Quick Start {quick_start_from_brief} - *For detailed documentation, see [docs/](docs/).** - -- ## Components ### Agents {agent_list_from_brief} ### Workflows {workflow_list_from_brief} - -- ## Configuration The module supports these configuration options (set during installation): {config_variables_from_module_yaml} - -- ## Module Structure ```bash {module_code}/ ├── module.yaml ├── README.md ├── TODO.md ├── docs/ │ ├── getting-started.md │ ├── agents.md │ ├── workflows.md │ └── examples.md ├── agents/ └── workflows/ ```bash - -- ## Documentation For detailed user guides and documentation, see the **[docs/](docs/)** folder: - [Getting Started](docs/getting-started.md) - [Agents Reference](docs/agents.md) - [Workflows Reference](docs/workflows.md) - [Examples](docs/examples.md) - -- ## Development Status This module is currently in development. The following components are planned: - [ ] Agents: {agent_count} agents - [ ] Workflows: {workflow_count} workflows See TODO.md for detailed status. - -- ## Author Created via BMAD Module workflow - -- ## License Part of the BMAD framework. ```bash ``` -------------------------------- ### Install Playwright CLI and Register Skills Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/tea/testarch/knowledge/playwright-cli.md Install the Playwright CLI globally and then register it as an agent skill within your project. This is a one-time setup for global installation. ```bash npm install -g @playwright/cli@latest # Install globally (Node.js 18+) playwright-cli install --skills # Register as an agent skill ``` -------------------------------- ### Build Scenario Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/gds/gametest/knowledge/unreal-testing.md Executes all queued setup actions. If no actions are queued, the completion callback is invoked immediately. ```cpp void UScenarioBuilder::Build(TFunction OnComplete) { if (SetupActions.Num() == 0) { OnComplete(); return; } ExecuteNextAction(0, OnComplete); } ``` -------------------------------- ### Setup Commands Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmm/workflows/document-project/templates/index-template.md Commands to set up the project locally. Ensure all prerequisites are met before execution. ```bash cd {{root_path}} {{setup_command}} {{run_command}} ``` -------------------------------- ### Setup Commands Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/gds/workflows/document-project/templates/index-template.md Commands to set up the project locally. Ensure you are in the project's root directory before executing. ```bash cd /cloudquant/backtrader ./scripts/setup.sh ./scripts/install-deps.sh ``` -------------------------------- ### Setup Git Hooks for Backtrader Development Source: https://github.com/cloudquant/backtrader/blob/development/CLAUDE.md Installs git hooks to enforce development standards and practices. Requires 'make' to be installed. ```bash make git-setup ``` -------------------------------- ### Repeating Timer Strategy Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/stores/signal-timer-store.md Execute a timer repeatedly at a specified interval. This example sets a timer to repeat every 30 minutes, starting at the session start. ```python class RepeatingTimerStrategy(bt.Strategy): """Execute every N minutes.""" def __init__(self): self.execution_count = 0 # Timer that repeats every 30 minutes self.add_timer( when=bt.Timer.SESSION_START, repeat=timedelta(minutes=30), ) def notify_timer(self, timer, when, *args, **kwargs): self.execution_count += 1 print(f'Repeating timer #{self.execution_count} at {when}') ``` -------------------------------- ### Project Setup Commands Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmm/workflows/document-project/templates/index-template.md General commands for setting up the project. These are typically executed in the root directory. ```bash {{setup_commands}} ``` -------------------------------- ### plotrange Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/core/backtrader.linebuffer.md Gets a slice of data from the array within a specified start and end index. ```APIDOC ## plotrange(start, end) ### Description Get a slice of data from the array. ### Parameters - **start** – Start index of the slice. - **end** – End index of the slice. ### Returns Slice of data from start to end. ### Return type list or [array](#backtrader.linebuffer.PseudoArray.array) ``` -------------------------------- ### Run All Examples Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代138/验收标准.md Execute all provided examples to ensure they run without errors and produce reasonable output. This covers basic and advanced usage scenarios. ```bash # Run all examples cd examples/tick_level python 01_basic_tick_backtest.py python 02_mixed_mode_backtest.py python 03_live_trading_simulation.py # ... # Acceptance conditions # - All examples run without errors # - Output results are reasonable ``` -------------------------------- ### Configure API Keys and Run Strategy Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/tutorials/examples/strategies/DOGS_STRATEGY_QUICK_REF.md Set up your API keys in the .env file, then run the provided Python scripts to check configuration, test data loading, and execute the strategy. ```bash # 1. 配置 API 密钥(在 .env 文件中) OKX_API_KEY=your_key OKX_SECRET=your_secret OKX_PASSWORD=your_password # 2. 检查配置 python check_okx_config_simple.py # 3. 测试数据加载 python test_dogs_data.py # 4. 运行策略 python examples/backtrader_ccxt_okx_dogs_bollinger.py ``` -------------------------------- ### Execute Next Setup Action Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/gds/gametest/knowledge/unreal-testing.md Internal function to recursively execute setup actions. Invokes the final callback when all actions are completed. ```cpp void UScenarioBuilder::ExecuteNextAction( int32 Index, TFunction FinalCallback) { if (Index >= SetupActions.Num()) { SetupActions.Empty(); FinalCallback(); return; } SetupActions[Index]([this, Index, FinalCallback]() { ExecuteNextAction(Index + 1, FinalCallback); }); } ``` -------------------------------- ### Bar Chart Example Source: https://github.com/cloudquant/backtrader/blob/development/examples/output/plotly_chart.html Illustrates how to create a bar chart. Make sure Plotly is installed and imported. ```python import plotly.graph_objects as go x = ['A', 'B', 'C', 'D'] y = [15, 12, 18, 10] fig = go.Figure(data=go.Bar(x=x, y=y)) fig.show() ``` -------------------------------- ### Get Specific Slice of Buffer Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/user-guide/linebuffer.md Retrieves a slice of the buffer defined by start and end indices (exclusive of end). ```python subset = buf.plotrange(100, 200) # Indices 100-199 ``` -------------------------------- ### Get Values from Specific Physical Index Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/user-guide/linebuffer.md Retrieves 10 values starting from a specific physical index in the buffer. ```python middle_vals = buf.getzero(idx=50, size=10) ``` -------------------------------- ### Get First 10 Values from Physical Start Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/user-guide/linebuffer.md Retrieves the first 10 values from the beginning of the physical buffer. ```python first_10 = buf.getzero(idx=0, size=10) ``` -------------------------------- ### View Documentation Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/developer-guide/setup.md Serve and view the generated project documentation locally. ```bash # View documentation make docs-view ``` -------------------------------- ### Create a Line Chart with Plotly Source: https://github.com/cloudquant/backtrader/blob/development/examples/output/plotly_chart.html This example shows how to generate a line chart. Ensure Plotly is installed and imported. ```python import plotly.graph_objects as go x = [1, 2, 3, 4, 5] y = [2, 3, 5, 8, 12] fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines')) fig.show() ``` -------------------------------- ### Agent Variable Access Example Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmb/workflows/module/data/module-yaml-conventions.md Illustrates how module variables are accessed within agent frontmatter or context after installation. ```yaml # In agent.agent.yaml or workflow execution {variable_name} # Expands to the user's configured value ``` -------------------------------- ### Install and Configure Pre-commit Hooks Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/developer-guide/style.md Install the pre-commit framework and then install the project's hooks into the local repository. This ensures checks run automatically. ```bash # Install pre-commit framework pip install pre-commit # Install hooks in your repository pre-commit install ``` -------------------------------- ### Build Local Documentation with Make Source: https://github.com/cloudquant/backtrader/blob/development/README.md Follow these steps to build the documentation locally. Ensure you have the required dependencies installed. ```bash cd docs pip install -r requirements.txt make html make serve ``` -------------------------------- ### Monolithic Test Example (Bad Practice) Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/tea/testarch/knowledge/test-quality.md Avoid monolithic tests exceeding 300 lines. This example demonstrates a long, unmanageable test that combines setup, user creation, permissions, and cleanup, making it difficult to understand and debug. ```typescript // ❌ BAD: 400-line monolithic test (truncated for example) test('complete user journey - TOO LONG', async ({ page, request }) => { // 50 lines of setup const admin = createUser({ role: 'admin' }); await request.post('/api/users', { data: admin }); await page.goto('/login'); await page.fill('[data-testid="email"]', admin.email); await page.fill('[data-testid="password"]', 'password123'); await page.click('[data-testid="login"]'); await expect(page).toHaveURL('/dashboard'); // 100 lines of user creation await page.goto('/admin/users'); const newUser = createUser(); await page.fill('[data-testid="email"]', newUser.email); // ... 95 more lines of form filling, validation, etc. // 100 lines of permissions assignment await page.click('[data-testid="assign-permissions"]'); // ... 95 more lines // 100 lines of notification preferences await page.click('[data-testid="notification-settings"]'); // ... 95 more lines // 50 lines of cleanup await request.delete(`/api/users/${newUser.id}`); // ... 45 more lines // TOTAL: 400 lines - impossible to understand or debug }); ``` -------------------------------- ### Complete Backtrader Example with Multiple Analyzers Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/user-guide/analyzers/analyzers.md A comprehensive example demonstrating the setup of Cerebro, adding a strategy, data feed, multiple analyzers (Returns, SharpeRatio, DrawDown, TradeAnalyzer, AnnualReturn), broker settings, and running the backtest to print results. ```python import backtrader as bt import datetime class TestStrategy(bt.Strategy): pass # Create cerebro cerebro = bt.Cerebro() # Add strategy cerebro.addstrategy(TestStrategy) # Add data data = bt.feeds.YahooFinanceData( dataname='AAPL', fromdate=datetime.datetime(2023, 1, 1), todate=datetime.datetime(2023, 12, 31) ) cerebro.adddata(data) # Add analyzers cerebro.addanalyzer(bt.analyzers.Returns, _name='returns') cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe') cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown') cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trades') cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='annual_return') # Set broker cerebro.broker.setcash(10000) cerebro.broker.setcommission(0.001) # Run strats = cerebro.run() strat = strats[0] # Print results print('-' *50) print('ANALYSIS RESULTS') print('-'*50) # Returns returns = strat.analyzers.returns.get_analysis() print(f'Total return: {returns["rtot"]:.2%}') print(f'average return: {returns["ravg"]:.2%}') # Sharpe Ratio sharpe = strat.analyzers.sharpe.get_analysis() print(f'Sharpe Ratio: {sharpe["sharperatio"]:.3f}') # Drawdown drawdown = strat.analyzers.drawdown.get_analysis() print(f'Max Drawdown: {drawdown["max"]["drawdown"]:.2%}') print(f'Max Drawdown Duration: {drawdown["max"]["len"]} days') # Trades trades = strat.analyzers.trades.get_analysis() print(f'Total trades: {trades["total"]["total"]}') if trades["total"]["total"] > 0: print(f'Win rate: {trades["won"]["total"] / trades["total"]["total"]:.2%}') ``` -------------------------------- ### Get Starter Template CLI Commands Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmm/workflows/3-solutioning/create-architecture/steps/step-03-starter.md Retrieve the exact CLI commands for creating a new project with a selected starter template. ```bash Search the web: "{{starter_name}} CLI command options flags latest" Search the web: "{{starter_name}} create new project command examples" ``` -------------------------------- ### Create a Histogram with Plotly Source: https://github.com/cloudquant/backtrader/blob/development/examples/output/plotly_chart.html Example of generating a histogram using Plotly Express to visualize the distribution of a dataset. Requires Plotly installation. ```python import plotly.express as px import numpy as np data = np.random.randn(100) fig = px.histogram(data) fig.show() ``` -------------------------------- ### Install CloudQuant Backtrader from Source Source: https://github.com/cloudquant/backtrader/blob/development/README.md Instructions for installing the CloudQuant Backtrader project from GitHub or Gitee, including dependency installation and verification. ```bash # 注意:本项目未发布到 PyPI,请从源码安装 # 从 GitHub 克隆 git clone https://github.com/cloudQuant/backtrader.git cd backtrader pip install -r requirements.txt pip install -U . # 或从 Gitee 克隆(国内用户推荐) git clone https://gitee.com/yunjinqi/backtrader.git cd backtrader pip install -r requirements.txt pip install -U . # 验证安装 python -c "import backtrader as bt; print(bt.__version__)" ``` -------------------------------- ### Add a session start timer Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/stores/signal-timer-store.md Schedules a timer to trigger at the beginning of each trading session. This example targets weekdays from Monday to Friday. ```python self.add_timer( when=bt.Timer.SESSION_START, weekdays=[0, 1, 2, 3, 4], # Monday to Friday ) ``` -------------------------------- ### Setup for Cython Extensions Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代133-使用cython重构方案.md Configures the build process for Cython extensions using setuptools and Cython. Includes necessary include directories for NumPy. ```python from setuptools import setup, Extension from Cython.Build import cythonize import numpy as np extensions = [ Extension( "backtrader._linebuffer", ["backtrader/_linebuffer.pyx"], include_dirs=[np.get_include()], ), Extension( "backtrader.indicators._mathops", ["backtrader/indicators/_mathops.pyx"], include_dirs=[np.get_include()], ), Extension( "backtrader._operations", ["backtrader/_operations.pyx"], include_dirs=[np.get_include()], ), ] setup( name="backtrader", ext_modules=cythonize( extensions, compiler_directives={ 'language_level': '3', 'boundscheck': False, 'wraparound': False, 'cdivision': True, } ), ) ``` -------------------------------- ### Tick Data Processing Example Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代75-基于forwardtrader优化.md This example demonstrates the setup for processing tick data using TickData and TickAggregator. It shows how to create a tick data feed with aggregation and how to access multi-level quote information within a strategy's next method. ```python from backtrader.tick import TickData, TickAggregator # 创建 Tick 数据源 tick_feed = TickData( aggregator=TickAggregator(period=60), aggregate_period=60 ) cerebro = bt.Cerebro() cerebro.adddata(tick_feed) # 策略中访问多档行情 class MyStrategy(bt.Strategy): def next(self): ``` -------------------------------- ### Implementation Summary Example Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmm/workflows/bmad-quick-flow/quick-dev/steps/step-04-self-check.md Provides a template for summarizing implementation details before proceeding to the next review stage. This includes a high-level status, a brief description of changes, modified files, test outcomes, and acceptance criteria status. ```bash - *Implementation Complete!** - *Summary:** {what was implemented} - *Files Modified:** {list of files} - *Tests:** {test summary - passed/added/etc} - *AC Status:** {all satisfied / issues noted} Proceeding to adversarial code review... ``` -------------------------------- ### PercentSizer Examples Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/sizers/sizer.md Demonstrates creating PercentSizer instances with different percentage and return type configurations. ```python # Use 30% of available cash sizer = bt.sizers.PercentSizer(percents=30) # Use 10% of cash, return integer sizer = bt.sizers.PercentSizer(percents=10, retint=True) ``` -------------------------------- ### Complete CTP Live Trading Example Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/brokers/ctp-store-broker.md A full example demonstrating live trading with the CTP Store Broker. It includes strategy implementation, order notification handling, and Cerebro setup. Ensure you replace placeholder credentials with your actual SimNow details. ```python # !/usr/bin/env python """CTP Live Trading Example with API Reference""" import backtrader as bt import logging logging.basicConfig(level=logging.INFO) class TestStrategy(bt.Strategy): """Test strategy demonstrating CTP API usage.""" def __init__(self): self.order = None self.log('Strategy initialized') def log(self, txt, dt=None): dt = dt or self.data.datetime[0] print(f'{dt} {txt}') def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: return if order.status == order.Completed: if order.isbuy(): self.log(f'BUY EXECUTED: Price={order.executed.price:.2f}, ' f'Size={order.executed.size}, Comm={order.executed.comm:.2f}') else: self.log(f'SELL EXECUTED: Price={order.executed.price:.2f}, ' f'Size={order.executed.size}, Comm={order.executed.comm:.2f}') elif order.status == order.Canceled: self.log('Order Canceled') elif order.status == order.Rejected: self.log('Order Rejected') self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log(f'TRADE CLOSED: P&L={trade.pnl:.2f}, Comm={trade.commission:.2f}') def next(self): # Check cash cash = self.broker.getcash() value = self.broker.getvalue() # Check position pos = self.getposition() size = pos.size price = pos.price # Place order if no pending order and no position if not self.order and size == 0: self.order = self.buy(size=1, exectype=bt.Order.Market) self.log(f'BUY ORDER PLACED: Cash={cash:.2f}, Value={value:.2f}') def main(): # Create cerebro cerebro = bt.Cerebro() # CTP connection settings ctp_setting = { 'td_front': 'tcp://182.254.243.31:30001', 'md_front': 'tcp://182.254.243.31:30011', 'broker_id': '9999', 'user_id': 'your_id', 'password': 'your_password', 'app_id': 'simnow_client_test', 'auth_code': '0000000000000000', } # Create store store = bt.stores.CTPStore(**ctp_setting) # Check connection if not store.is_connected: print("Failed to connect to CTP") return print(f"Connected to CTP: Cash={store.get_cash():.2f}, Value={store.get_value():.2f}") # Add data feed data = store.getdata( dataname='rb2505.SHFE', timeframe=bt.TimeFrame.Minutes, compression=1, num_init_backfill=100, ) cerebro.adddata(data) # Set broker cerebro.setbroker(store.getbroker( use_positions=True, commission=1.0, )) # Add strategy cerebro.addstrategy(TestStrategy) # Run try: cerebro.run() except KeyboardInterrupt: print("\nStopped by user") if __name__ == '__main__': main() ``` -------------------------------- ### Full Training Example with BTGym and Stable Baselines3 Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代63-基于btgym优化.md This snippet shows the complete workflow for setting up a Backtrader environment with BTGym, creating a vectorized environment, initializing an RL model (PPO), training the model, saving it, and then testing its performance. Ensure you have 'btc.csv' data available and necessary libraries installed. ```python import backtrader as bt from backtrader.env import BTGymEnv from backtrader.strategy.rl_base import RLStrategy from stable_baselines3 import PPO, A2C from stable_baselines3.common.vec_env import DummyVecEnv import pandas as pd # 1. 准备数据 df = pd.read_csv('btc.csv') df['datetime'] = pd.to_datetime(df['timestamp']) df.set_index('datetime', inplace=True) data = bt.feeds.PandasData(dataname=df) # 2. 创建环境 def make_env(): return BTGymEnv( strategy_class=RLStrategy, data=data, initial_cash=10000, commission=0.001, time_embedding=30, reward_type='pnl', reward_shaping=True, gamma=0.99, ) # 3. 向量化环境(可选) env = DummyVecEnv([make_env]) # 4. 创建 RL 模型 model = PPO( 'MlpPolicy', env, learning_rate=3e-4, n_steps=2048, batch_size=64, gamma=0.99, verbose=1 ) # 5. 训练 model.learn(total_timesteps=100000) # 6. 保存 model.save('ppo_trading_bot') # 7. 测试 env = make_env() obs = env.reset() rewards = [] for i in range(1000): action, _ = model.predict(obs) obs, reward, done, info = env.step(action) rewards.append(reward) if done: break print(f"Total reward: {sum(rewards)}") ``` -------------------------------- ### Line Chart with Plotly Express Source: https://github.com/cloudquant/backtrader/blob/development/examples/output/plotly_chart.html Example of creating a line chart to visualize trends over time or continuous data. Requires Plotly installation. ```python import plotly.express as px data = { 'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04'], 'value': [5, 7, 6, 8] } fig = px.line(data, x='date', y='value', title='Trend Over Time') fig.show() ``` -------------------------------- ### Basic Cerebro Setup and Run Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/user-guide/cerebro.md Initialize Cerebro, add data, a strategy, an analyzer, run the backtest, and plot the results. Ensure MyStrategy is defined elsewhere. ```python import backtrader as bt # Create cerebro instance cerebro = bt.Cerebro() # Add components cerebro.adddata(data) cerebro.addstrategy(MyStrategy, param1=value1) cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe') # Run backtest results = cerebro.run() # Plot results cerebro.plot() ``` -------------------------------- ### Full Example: Cerebro with PercentSizer Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/sizers/sizer_zh.md A complete Backtrader example demonstrating the setup of Cerebro, adding data, setting initial cash, configuring a `PercentSizer` to use 30% of funds, adding a strategy, and running the backtest. This illustrates a typical workflow for integrating sizers. ```python import backtrader as bt class TestStrategy(bt.Strategy): def __init__(self): self.sma = bt.indicators.SMA(self.data.close, period=20) def next(self): if not self.position: if self.data.close[0] > self.sma[0]: # 不指定 size,使用 Sizer 自动计算 self.buy() else: if self.data.close[0] < self.sma[0]: self.sell() # 创建 Cerebro cerebro = bt.Cerebro() # 添加数据 data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate='2020-01-01') cerebro.adddata(data) # 设置初始资金 cerebro.broker.setcash(10000) # 添加 Sizer - 使用 30% 资金 cerebro.addsizer(bt.sizers.PercentSizer, percents=30) # 添加策略 cerebro.addstrategy(TestStrategy) # 运行 result = cerebro.run() ``` -------------------------------- ### Example Strategy Implementation Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/gds/workflows/document-project/templates/source-tree-template.md Demonstrates a basic 'buy and hold' strategy implementation. ```python import backtrader as bt class BuyAndHold(bt.Strategy): def next(self): if len(self) > 1 and not self.position: size = int(self.broker.getcash() / self.data.close[0]) self.buy(size=size) ``` -------------------------------- ### Adding Interactivity to Plotly Charts Source: https://github.com/cloudquant/backtrader/blob/development/examples/output/plotly_chart.html This example demonstrates how to add interactive features like tooltips to your Plotly charts. Make sure Plotly is installed. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[4, 1, 2], mode='markers+lines', text=['A', 'B', 'C'], marker=dict(size=10), line=dict(width=2))) fig.update_layout(title='Interactive Scatter Plot') fig.show() ``` -------------------------------- ### Customize Plotly Chart Appearance Source: https://github.com/cloudquant/backtrader/blob/development/examples/output/plotly_chart.html This example demonstrates how to customize the layout and appearance of a Plotly chart, such as adding titles and labels. Ensure Plotly is installed. ```python import plotly.express as px data = { 'x': [1, 2, 3, 4, 5], 'y': [10, 11, 12, 13, 14] } fig = px.scatter(data, x='x', y='y') fig.update_layout( title='Custom Scatter Plot', xaxis_title='X Axis Label', yaxis_title='Y Axis Label' ) fig.show() ``` -------------------------------- ### Store Initial Cash in `start` Method Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/user-guide/strategy.md The `start` method is called before backtesting begins. Use it to store initial cash for later comparison. ```python def start(self): self.initial_cash = self.broker.getcash() ``` -------------------------------- ### Investigate Starter Template Details Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmm/workflows/3-solutioning/create-architecture/steps/step-03-starter.md Investigate specific details of promising starter templates, including their technologies, structure, and deployment capabilities. ```bash Search the web: "{{starter_name}} default setup technologies included latest" Search the web: "{{starter_name}} project structure file organization" Search the web: "{{starter_name}} production deployment capabilities" Search the web: "{{starter_name}} recent updates maintenance status" ``` -------------------------------- ### Intent-Based Workflow Example Source: https://github.com/cloudquant/backtrader/blob/development/_bmad/bmb/workflows/workflow/data/intent-vs-prescriptive-spectrum.md Use this for creative, exploratory, or collaborative workflows. It guides the LLM towards a goal, allowing it to determine the best conversational path. ```bash "Guide the user through discovering their ideal nutrition plan. Use multi-turn conversation. Ask 1-2 questions at a time. Think about their responses before asking follow-ups. Probe to understand preferences, restrictions, goals." ``` -------------------------------- ### Full Example: PercentSizer Strategy Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/api/sizers/sizer.md Demonstrates adding a PercentSizer to allocate 10% of available cash for trades. This example includes setting up data, a strategy, and the sizer. ```python import backtrader as bt import datetime class TestStrategy(bt.Strategy): params = (('period', 20),) def __init__(self): super().__init__() self.sma = bt.indicators.SMA(self.data.close, period=self.p.period) self.crossover = bt.Indicators.CrossOver(self.data.close, self.sma) def next(self): if self.crossover > 0: self.buy() # Size determined by sizer elif self.crossover < 0: self.sell() # Size determined by sizer # Create cerebro cerebro = bt.Cerebro() # Add data data = bt.feeds.YahooFinanceData( dataname='AAPL', fromdate=datetime.datetime(2020, 1, 1), todate=datetime.datetime(2021, 12, 31) ) cerebro.adddata(data) # Add strategy cerebro.addstrategy(TestStrategy) # Add sizer - use 10% of available cash cerebro.addsizer(bt.sizers.PercentSizer, percents=10) # Set initial cash cerebro.broker.setcash(10000) # Run results = cerebro.run() ``` -------------------------------- ### ParallelEnv Initialization and Worker Setup Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代63-基于btgym优化.md Initializes the ParallelEnv wrapper, sets up multiprocessing context, pipes for communication, and starts worker processes for each environment instance. ```APIDOC ## Class: ParallelEnv ### Description Supports multi-process parallel execution of multiple environment instances, accelerating reinforcement learning training. ### `__init__` #### Parameters - **env_fn** (callable) - Environment creation function. - **n_envs** (int) - Number of environments to run in parallel. Defaults to 4. - **sampling** (str) - Sampling method for environments ('random' or 'sequential'). Defaults to 'random'. ``` -------------------------------- ### CryptoTradingBot Multi-Instance Management Source: https://github.com/cloudquant/backtrader/blob/development/docs/source/reference/optimization-docs/requirements/迭代85-基于CryptoTradingBot优化.md Demonstrates the command-line process for setting up and starting a new instance of CryptoTradingBot using configuration files. ```bash cp etc/K.sh.dist X.sh && chmod +x X.sh K=X.sh make start ``` -------------------------------- ### Initialize and Upload Program Configurations Source: https://github.com/cloudquant/backtrader/blob/development/examples/output/plotly_chart.html Initializes and uploads program configurations. This is typically done once during the setup phase. ```javascript this.programConfigurations.upload(A),this.uploaded=!0} ```