### Installation Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Steps to install the Genesis-Core MCP server, including dependencies and verification. ```APIDOC ## Installation ### Description This section outlines the necessary steps to install the Genesis-Core MCP server and its dependencies. ### Method Command Line (pip) ### Endpoint N/A ### Parameters None ### Request Example ```bash # Install with all dependencies pip install -e ".[mcp]" # Or install individual packages pip install "mcp>=0.9.0" "aiofiles>=23.0.0" "gitpython>=3.1.0" ``` ### Response #### Success Response (200) Installation completes successfully without errors. #### Response Example (No specific output, but successful completion of pip commands) ### Verification #### Description Verify the MCP server installation by attempting to start it. #### Method Command Line #### Endpoint N/A #### Parameters None #### Request Example ```bash python -m mcp_server.server ``` #### Response ##### Success Response (200) Server starts and displays its version, configuration, and readiness message. ##### Response Example ``` ============================================================ Genesis-Core MCP Server v1.0.0 ============================================================ Server Name: genesis-core Log Level: INFO Features Enabled: - File Operations: True - Code Execution: True - Git Integration: True ============================================================ MCP Server started and ready for connections ``` ``` -------------------------------- ### Start MCP Server (Python) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Verifies the MCP server installation by starting it. This command should output server details and confirm that it's ready for connections. It's used for local stdio server setup. ```python python -m mcp_server.server ``` -------------------------------- ### Setup Development Environment (Windows PowerShell) Source: https://github.com/johnccarter/genesis-core/blob/master/AGENTS.md This sequence of commands sets up a Python virtual environment, activates it, upgrades pip, and installs the project dependencies along with development and machine learning extras. This is the standard procedure for preparing the project on a Windows system. ```powershell python -m venv .venv . .\.venv\Scripts\Activate.ps1 python -m pip install --upgrade pip pip install -e .[dev,ml] ``` -------------------------------- ### Example .env File for Genesis-Core Configuration Source: https://context7.com/johnccarter/genesis-core/llms.txt This is an example template for a .env file used to configure genesis-core. It lists common environment variables such as API keys and secrets for Bitfinex, a bearer token for authentication, the symbol mode, and flags for fast window and feature precomputation. This file serves as a starting point for setting up the environment for different trading or testing scenarios. ```dotenv BITFINEX_API_KEY= BITFINEX_API_SECRET= BEARER_TOKEN=change-me-in-production SYMBOL_MODE=synthetic GENESIS_FAST_WINDOW=1 GENESIS_PRECOMPUTE_FEATURES=1 ``` -------------------------------- ### Run MCP Server for AI Assistant Integration (Bash) Source: https://context7.com/johnccarter/genesis-core/llms.txt This bash script demonstrates how to install the necessary dependencies for the MCP (Model Context Protocol) server and then run it. It shows commands for installing MCP dependencies using pip and for starting the server in either standard input/output (stdio) mode, suitable for VS Code or Copilot integration, or in HTTP mode for remote access, specifying a port. ```bash # Install MCP dependencies pip install -e ".[mcp]" # Run stdio server (for VS Code / Copilot) python -m mcp_server.server # Or run HTTP server for remote access GENESIS_MCP_MODE=http python -m mcp_server.remote_server --port 8080 ``` -------------------------------- ### Start Remote HTTP Server for ChatGPT Connectors (Python) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md This command starts the Genesis-Core remote HTTP server, which acts as an entrypoint for ChatGPT connectors. It supports both preferred Streamable HTTP via FastMCP and a fallback JSON-RPC handler for compatibility. The server can be configured using environment variables like PORT, GENESIS_MCP_REMOTE_SAFE, and GENESIS_MCP_REMOTE_ULTRA_SAFE. ```bash python -m mcp_server.remote_server ``` -------------------------------- ### Expand Search Space with More Parameters (YAML) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optuna/OPTUNA_BEST_PRACTICES.md Demonstrates how to expand the search space for optimization by adding more parameters. The example shows a transition from a limited configuration with only two parameters to a richer configuration including multiple thresholds and bar limits. ```yaml # ❌ Only 2 parameters = limited exploration parameters: entry_conf: type: grid values: [0.3, 0.4, 0.5] exit_conf: type: fixed value: 0.4 # ✅ More parameters for richer search parameters: thresholds: entry_conf_overall: type: float low: 0.25 high: 0.45 step: 0.05 exit: exit_conf_threshold: type: float low: 0.35 high: 0.55 step: 0.05 max_hold_bars: type: int low: 15 high: 30 step: 5 ``` -------------------------------- ### Run Full Optimization Workflow (Bash) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optuna/OPTUNA_BEST_PRACTICES.md Outlines the recommended workflow for running a full optimization, starting from designing the search space, validating the configuration, running a smoke test, checking smoke results, and finally proceeding to the full optimization. ```bash 1. **Design Search Space** - Start wide, narrow down later - Aim for 50+ discrete combinations or include continuous params - Include champion parameters in ranges 2. **Validate Configuration** ```bash python scripts/preflight_optuna_check.py config.yaml python scripts/validate_optimizer_config.py config.yaml ``` 3. **Run Smoke Test (2-5 trials)** ```bash python -m core.optimizer.runner config.yaml --run-id smoke_test python scripts/diagnose_optuna_issues.py smoke_test ``` 4. **Check Smoke Results** - At least 1-2 trials should produce >0 trades - No excessive duplicates - Scores not all heavily negative 5. **Full Optimization** ``` -------------------------------- ### Install MCP Server Dependencies (Bash) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Installs the necessary Python packages for the MCP server using pip. It can install all dependencies at once or specific packages individually. Ensure you are in the correct environment. ```bash pip install -e ".[mcp]" ``` ```bash # Note (PowerShell): quote specifiers with ">=" to avoid creating files like "=0.9.0". pip install "mcp>=0.9.0" "aiofiles>=23.0.0" "gitpython>=3.1.0" ``` -------------------------------- ### Project Resources Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Access various project resources including documentation, structure, Git status, and configuration. ```APIDOC ## Resource Access ### Project Documentation **URI Pattern:** `genesis://docs/{path}` Access project documentation files. **Examples:** - `genesis://docs/README.md` - Main README - `genesis://docs/mcp_server_guide.md` - This guide - `genesis://docs/performance/PERFORMANCE_GUIDE.md` - Performance documentation ### Project Structure **URI:** `genesis://structure` Get the project directory structure as a tree (up to 5 levels deep). ### Git Status **URI:** `genesis://git/status` Get the current Git repository status in a readable format. ### Configuration **URI:** `genesis://config` Get project configuration information including: - Available config files - MCP server settings - Feature flags ``` -------------------------------- ### Install MCP Dependencies Source: https://github.com/johnccarter/genesis-core/blob/master/mcp_server/README.md Installs the necessary dependencies for the MCP server using pip. This command ensures that the MCP-specific packages and their requirements are installed in the current Python environment. ```bash # Install MCP dependencies pip install -e ".[mcp]" ``` -------------------------------- ### VSCode Configuration Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Guide to configuring VSCode to use the Genesis-Core MCP server via the `.vscode/mcp.json` file. ```APIDOC ## VSCode Configuration ### Description This section explains how to configure VSCode to connect to the Genesis-Core MCP server using the `.vscode/mcp.json` file. ### Method File Configuration / VSCode Command Palette ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Configuration within `.vscode/mcp.json`: ```json { "servers": { "genesis-core": { "command": ".venv/Scripts/python.exe", "args": ["-m", "mcp_server.server"], "env": {} } } } ``` ### Request Example Ensure the `.vscode/mcp.json` file is present in the project root with the correct configuration. ### Response #### Success Response (200) VSCode successfully connects to the MCP server after activation. #### Response Example (No direct response, but AI assistant functionality becomes available in VSCode.) ### Activation in VSCode #### Description Steps to activate the MCP server connection within VSCode. #### Method VSCode Command Palette #### Endpoint N/A #### Parameters None #### Request Example 1. Open VSCode in the Genesis-Core project directory. 2. Open the Command Palette (Ctrl+Shift+P / Cmd+Shift+P). 3. Search for "MCP: Connect to Server". 4. Select "genesis-core" from the list. #### Response ##### Success Response (200) The MCP server starts automatically and establishes a connection with the AI assistant within VSCode. ``` -------------------------------- ### VSCode MCP Integration Setup Source: https://github.com/johnccarter/genesis-core/blob/master/mcp_server/README.md Instructions for integrating the MCP server with VSCode. This involves ensuring the `.vscode/mcp.json` file exists, opening the project in VSCode, and using the command palette to connect to the 'genesis-core' server. ```text 1. Ensure .vscode/mcp.json exists (already created) 2. Open VSCode in the Genesis-Core directory 3. Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P) 4. Search for "MCP: Connect to Server" 5. Select "genesis-core" ``` -------------------------------- ### Configure MCP Server for VSCode (JSON) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Example JSON configuration for VSCode to connect to the Genesis-Core MCP server. This file, typically named `.vscode/mcp.json`, specifies the command and arguments to launch the server. It ensures the correct Python environment is used. ```json { "servers": { "genesis-core": { "command": ".venv/Scripts/python.exe", "args": ["-m", "mcp_server.server"], "env": {} } } } ``` -------------------------------- ### MCP Server (Local) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Instructions for running the MCP server locally using the stdio server, typically for VS Code and GitHub Copilot integration. ```APIDOC ## MCP Server (Local) ### Description This section describes how to run the MCP server locally using the standard input/output (stdio) server. This is the recommended method for integrating with tools like VS Code and GitHub Copilot. ### Method Command Line ### Endpoint N/A (stdio server) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash python -m mcp_server.server ``` ### Response #### Success Response (200) Upon successful startup, the server will print status information to the console and indicate readiness for connections. #### Response Example ``` ============================================================ Genesis-Core MCP Server v1.0.0 ============================================================ Server Name: genesis-core Log Level: INFO Features Enabled: - File Operations: True - Code Execution: True - Git Integration: True ============================================================ MCP Server started and ready for connections ``` ``` -------------------------------- ### YAML Configuration for Max Concurrent Runs Source: https://github.com/johnccarter/genesis-core/blob/master/docs/analysis/CONCURRENCY_DUPLICATES_ANALYSIS.md Example of a YAML configuration snippet showing how to set the maximum number of concurrent runs. The 'Before' example indicates a high level of parallelism, while the 'After' example demonstrates reducing this number for discrete search spaces to minimize duplicate trials. ```yaml # Before runs: max_concurrent: 8 # High parallelism # After (for discrete space) runs: max_concurrent: 2 # Lower parallelism, fewer duplicates ``` -------------------------------- ### Tool: execute_python Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Executes Python code in a sandboxed environment with a timeout. ```APIDOC ## POST /mcp (with tool: execute_python) ### Description Executes Python code in a safe environment with timeout. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - "tools/call" - **params** (object) - Required - **tool_name** (string) - Required - "execute_python" - **tool_input** (object) - Required - **code** (string) - Required - Python code to execute ### Request Example ```json { "method": "tools/call", "params": { "tool_name": "execute_python", "tool_input": { "code": "print('Hello from MCP!')\nfor i in range(5):\n print(f'Count: {i}')" } } } ``` ### Response #### Success Response (200) - **success** (boolean) - Whether the execution succeeded - **output** (string) - Standard output from execution - **error_output** (string) - Standard error from execution - **return_code** (number) - Process return code - **error** (string) - Error message (if failed) #### Response Example ```json { "success": true, "output": "Hello from MCP!\nCount: 0\nCount: 1\nCount: 2\nCount: 3\nCount: 4", "error_output": "", "return_code": 0, "error": null } ``` ``` -------------------------------- ### Pre-run Configuration Checks for Optuna Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optuna/OPTUNA_FIX_SUMMARY.md Provides command-line scripts for validating Optuna optimization configurations before running. `preflight_optuna_check.py` and `validate_optimizer_config.py` help ensure that the setup is correct and optimal for the intended backtesting. ```bash python scripts/preflight_optuna_check.py config.yaml python scripts/validate_optimizer_config.py config.yaml ``` -------------------------------- ### Load Optimizer Search Configuration (Python) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/ARCHITECTURE_VISUAL.md This function loads the search configuration for the optimizer, taking a configuration path as input. It's a key part of the optimizer CLI's setup. ```Python def load_search_config(config_path): # ... implementation details ... return search_config ``` -------------------------------- ### Start Remote MCP Server (Python) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Entrypoint for starting the remote HTTP server for the MCP server. This is used when a remotely reachable MCP endpoint is needed, such as for ChatGPT integration. It defaults to read-only mode. ```python python -m mcp_server.remote_server ``` -------------------------------- ### Get Git Status API Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Retrieves the current Git status information for the project, including branch, modified files, and repository dirty status. ```APIDOC ## GET /git/status ### Description Get Git status information for the project. ### Method GET ### Endpoint /git/status ### Parameters None ### Response #### Success Response (200) - **success** (boolean) - Whether the operation succeeded - **branch** (string) - Current branch name - **modified_files** (array) - List of modified files - **staged_files** (array) - List of staged files - **untracked_files** (array) - List of untracked files - **remote_url** (string) - Remote repository URL - **is_dirty** (boolean) - Whether the repository has uncommitted changes #### Error Response (400) - **success** (boolean) - False - **error** (string) - Error message (if failed) ### Request Example ```json {} ``` ### Response Example ```json { "success": true, "branch": "main", "modified_files": [ "README.md" ], "staged_files": [], "untracked_files": [ "new_feature.py" ], "remote_url": "git@github.com:johnccarter/genesis-core.git", "is_dirty": true } ``` ``` -------------------------------- ### Write Python Module Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Creates a new Python file with specified content, useful for adding new utility functions or modules to the project. This example demonstrates creating a string helper module. ```json { "tool": "write_file", "arguments": { "file_path": "utils/string_helpers.py", "content": """String utility functions""" def capitalize_words(text: str) -> str: """Capitalize each word in the string.""" return ' '.join(word.capitalize() for word in text.split()) " } } ``` -------------------------------- ### Execute Python Code Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Executes arbitrary Python code within the project environment. This is useful for running scripts, performing calculations, or any task that can be scripted in Python. The example calculates the average of a list of numbers. ```json { "tool": "execute_python", "arguments": { "code": "sizes = [1024, 2048, 4096, 8192]\navg = sum(sizes) / len(sizes)\nprint(f'Average size: {avg} bytes')" } } ``` -------------------------------- ### Basic Optimized Backtest Usage (Bash) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optimization/OPTIMIZATION_SUMMARY.md Demonstrates how to run a backtest with optimizations enabled using command-line flags. Includes options for fast window and precomputing features. ```bash python scripts/run_backtest.py --symbol tBTCUSD --timeframe 1h \ --fast-window --precompute-features ``` -------------------------------- ### Get Git Status Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Retrieves the current Git status of the project, including branch name, modified files, staged files, untracked files, remote URL, and whether the repository is dirty (has uncommitted changes). ```json { "tool": "get_git_status", "arguments": {} } ``` -------------------------------- ### Run Full Optimization Workflow (PowerShell) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optuna/OPTUNA_BEST_PRACTICES.md Provides the PowerShell equivalent for running a full optimization workflow, mirroring the steps outlined in the bash version. This includes designing the search space, validating configuration, running smoke tests, checking results, and initiating the full optimization. ```powershell PowerShell (Windows): ```powershell # Steps are analogous to the bash workflow: # 1. Design Search Space # 2. Validate Configuration (using Python scripts) # 3. Run Smoke Test (using Python scripts) # 4. Check Smoke Results # 5. Full Optimization ``` ``` -------------------------------- ### Setup and Configuration for Optimization Analysis (Python) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/analysis/optimization_analysis.ipynb Initializes the analysis environment by importing necessary libraries, setting the seaborn style, and defining configuration variables such as the run ID and project directories. This script prepares the environment for data loading and processing. ```python import glob import json from pathlib import Path import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # Set style sns.set_theme(style="whitegrid") # Configuration RUN_ID = "run_20251215_092751" PROJECT_ROOT = Path("c:/Users/fa06662/HCP/Skrivbord/Genesis-Core") RESULTS_DIR = PROJECT_ROOT / "results" / "hparam_search" / RUN_ID print(f"Analyzing run: {RUN_ID}") print(f"Directory: {RESULTS_DIR}") ``` -------------------------------- ### Run Optuna Hyperparameter Optimization with Python Source: https://context7.com/johnccarter/genesis-core/llms.txt This Python code snippet illustrates how to execute hyperparameter optimization using the Optuna library within the genesis-core framework. It shows how to set environment variables for execution mode and seed, import the necessary `run_optimization` function, and define the search space, sampler, pruner, and trial configurations in a YAML format. The example also includes programmatic execution using `OptimizerRunner` and printing the best trial's score and parameters. ```python import os # Set canonical execution mode for optimization os.environ["GENESIS_FAST_WINDOW"] = "1" os.environ["GENESIS_PRECOMPUTE_FEATURES"] = "1" os.environ["GENESIS_RANDOM_SEED"] = "42" from core.optimizer.runner import run_optimization # Define search space in YAML format # config/optimizer/tBTCUSD_1h_optuna.yaml: """ study_name: tBTCUSD_1h_hparam_search symbol: tBTCUSD timeframe: 1h start_date: "2024-01-01" end_date: "2024-06-30" sampler: type: TPESampler multivariate: true n_ei_candidates: 256 pruner: type: MedianPruner n_startup_trials: 10 n_warmup_steps: 50 n_trials: 100 n_jobs: 4 search_space: thresholds: entry_conf_overall: type: float low: 0.3 high: 0.8 step: 0.05 min_edge: type: float low: 0.0 high: 0.15 step: 0.01 risk: risk_map: type: categorical choices: - [[0.5, 0.01], [0.6, 0.02], [0.7, 0.03]] - [[0.4, 0.015], [0.55, 0.025], [0.7, 0.035]] gates: hysteresis_steps: type: int low: 1 high: 5 cooldown_bars: type: int low: 0 high: 10 constraints: min_trades: 10 min_profit_factor: 0.8 max_max_dd: 0.25 """ # Run via CLI # python -m core.optimizer.runner config/optimizer/tBTCUSD_1h_optuna.yaml # Or programmatically from core.optimizer.runner import OptimizerRunner runner = OptimizerRunner("config/optimizer/tBTCUSD_1h_optuna.yaml") best_trial = runner.run() print(f"Best Score: {best_trial.value:.4f}") print(f"Best Params: {best_trial.params}") # {'entry_conf_overall': 0.55, 'min_edge': 0.08, 'hysteresis_steps': 2, ...} ``` -------------------------------- ### MCP Server Tool Call Example (JSON) Source: https://context7.com/johnccarter/genesis-core/llms.txt This JSON object represents an example of a tool call made via the MCP protocol. It specifies the method as 'tools/call' and includes parameters for the tool's name ('run_backtest') and its arguments, such as symbol, timeframe, start date, and end date. This format is used for interacting with the MCP server to perform various actions like running backtests or fetching data. ```json { "method": "tools/call", "params": { "name": "run_backtest", "arguments": { "symbol": "tBTCUSD", "timeframe": "1h", "start_date": "2024-01-01", "end_date": "2024-03-31" } } } ``` -------------------------------- ### Benchmark Full Backtest with Optuna Integration (Bash) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optuna/OPTUNA_OPTIMIZATIONS.md This bash command runs a benchmark for the full backtest process, integrating Optuna optimizations. It allows for assessing the overall performance improvement on a specific symbol and timeframe. ```bash # Benchmark full backtest with Optuna integration python scripts/benchmark_backtest.py --symbol tBTCUSD --timeframe 1h ``` -------------------------------- ### Get Project Structure Tool Input (JSON) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md This empty JSON object is the input for the 'get_project_structure' tool. This tool retrieves a tree representation of the project's structure. It returns the structure, project root path, and success status or an error message. ```json {} ``` -------------------------------- ### Scale Startup Trials with Concurrency (Python) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/analysis/CONCURRENCY_DUPLICATES_ANALYSIS.md Dynamically scales the number of initial startup trials based on the concurrency level. This ensures a minimum number of random sampling batches for better initial exploration, providing a stronger seed for subsequent modeling phases like TPE. ```python # Proposed improvement n_startup_trials = max(25, 5 * concurrency) # Examples: # n_jobs=1 → n_startup=25 (5 batches of random) # n_jobs=4 → n_startup=25 (6 batches of random) # n_jobs=8 → n_startup=40 (5 batches of random) # n_jobs=16 → n_startup=80 (5 batches of random) ``` -------------------------------- ### Initialize and Populate Deduplication Guard Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optuna/optuna_performance_improvements.md Demonstrates how to initialize a `NoDupeGuard` for deduplication and pre-populate it with known parameter signatures. This is useful for zero-waste optimization by preventing redundant trials. ```python guard = NoDupeGuard(sqlite_path=".optuna_dedup.db") known_sigs = [param_signature(p) for p in known_params] guard.add_batch(known_sigs) ``` -------------------------------- ### Enable Zero-Copy Window Building Source: https://github.com/johnccarter/genesis-core/blob/master/docs/performance/PERFORMANCE_GUIDE.md Shows how to enable fast window mode for the backtest engine, which utilizes zero-copy slicing to reduce memory allocations and eliminate list conversion overhead. This can be done via a command-line flag or an environment variable. ```bash # Enable fast window mode (recommended) python scripts/run_backtest.py --symbol tBTCUSD --timeframe 1h --fast-window # Or via environment variable export GENESIS_FAST_WINDOW=1 python scripts/run_backtest.py --symbol tBTCUSD --timeframe 1h ``` -------------------------------- ### Python Strategy Example: EMA Cross Source: https://github.com/johnccarter/genesis-core/blob/master/src/genesis_core.egg-info/SOURCES.txt Implements an example trading strategy based on Exponential Moving Average (EMA) crossovers. This strategy likely generates buy or sell signals when shorter-term EMAs cross longer-term EMAs. ```python from genesis_core.strategy.ema_cross import EMACrossStrategy # Initialize the strategy # ema_strategy = EMACrossStrategy(short_ema_period=12, long_ema_period=26) # Example usage within a trading loop: # signals = ema_strategy.generate_signals(historical_data) # for signal in signals: # if signal.type == 'BUY': # # Execute buy order # pass # elif signal.type == 'SELL': # # Execute sell order # pass ``` -------------------------------- ### Run Backtest with BacktestEngine Source: https://context7.com/johnccarter/genesis-core/llms.txt Initializes and runs a backtest using the BacktestEngine. This involves setting up configuration parameters such as symbol, timeframe, dates, capital, commission, slippage, and custom exit strategies. It loads historical data and executes the strategy, providing detailed results including summary statistics and trade details. ```python from core.backtest.engine import BacktestEngine # Initialize engine with configuration engine = BacktestEngine( symbol="tBTCUSD", timeframe="1h", start_date="2024-01-01", end_date="2024-06-30", initial_capital=10000.0, commission_rate=0.001, # 0.1% per trade slippage_rate=0.0005, # 0.05% slippage warmup_bars=120, # Bars for indicator warmup htf_exit_config={ "partial_1_pct": 0.50, "partial_2_pct": 0.30, "fib_threshold_atr": 0.3, "enable_partials": True, "enable_trailing": True, }, ) # Load historical data from Parquet files if not engine.load_data(): raise RuntimeError("Failed to load data") # Run backtest with custom configuration results = engine.run( policy={"symbol": "tBTCUSD", "timeframe": "1h"}, configs={ "thresholds": { "entry_conf_overall": 0.5, "regime_proba": {"bull": 0.6, "bear": 0.4, "balanced": 0.5} }, "risk": { "risk_map": [[0.5, 0.01], [0.6, 0.02], [0.7, 0.03]] }, "exit": { "stop_loss_pct": 0.02, "take_profit_pct": 0.05, "exit_conf_threshold": 0.45 } }, verbose=True ) # Access results print(f"Total Return: {results['summary']['total_return']:.2f}%") print(f"Total Trades: {results['summary']['num_trades']}") print(f"Win Rate: {results['summary']['win_rate']:.1f}%") print(f"Max Drawdown: {results['summary']['max_drawdown']:.2f}%") print(f"Profit Factor: {results['summary']['profit_factor']:.2f}") # Access trade details for trade in results['trades'][:5]: print(f" {trade['side']} {trade['size']:.4f} @ ${trade['entry_price']:.2f} -> " f"${trade['exit_price']:.2f} | PnL: {trade['pnl_pct']:.2f}% | " f"Reason: {trade['exit_reason']}") # Access equity curve equity_curve = results['equity_curve'] # [{"timestamp": "2024-01-02T00:00:00", "total_equity": 10050.0}, ...] ``` -------------------------------- ### Optuna Discrete Search Space Example (YAML) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/analysis/CONCURRENCY_DUPLICATES_ANALYSIS.md Illustrates a discrete search space configuration in Optuna using YAML. This example defines integer and rounded float parameters, which limit the number of unique combinations and increase the probability of duplicate parameter sampling when multiple workers are used. ```yaml parameters: param_a: type: grid values: [1, 2, 3] # Only 3 choices param_b: type: grid values: [0.3, 0.4] # Only 2 choices ``` -------------------------------- ### Tool: get_project_structure Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Retrieves the project structure as a tree representation. ```APIDOC ## POST /mcp (with tool: get_project_structure) ### Description Gets the project structure as a tree representation. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - "tools/call" - **params** (object) - Required - **tool_name** (string) - Required - "get_project_structure" - **tool_input** (object) - Required (empty object) ### Request Example ```json { "method": "tools/call", "params": { "tool_name": "get_project_structure", "tool_input": {} } } ``` ### Response #### Success Response (200) - **success** (boolean) - Whether the operation succeeded - **structure** (string) - Tree representation of project - **root** (string) - Project root path - **error** (string) - Error message (if failed) #### Response Example ```json { "success": true, "structure": "/\n├── src/\n│ ├── core/\n│ │ ├── __init__.py\n│ │ └── config/\n│ │ └── __init__.py\n│ └── main.py\n└── README.md", "root": "/path/to/project", "error": null } ``` ``` -------------------------------- ### Benchmark Backtest Execution (Bash) Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optimization/OPTIMIZATION_SUMMARY.md Provides the command to run the benchmarking tool for backtesting. This script helps in evaluating the performance improvements achieved through the optimizations. ```bash python scripts/benchmark_backtest.py --symbol tBTCUSD --timeframe 1h ``` -------------------------------- ### Use Ask/Tell Optimization with Deduplication Guard Source: https://github.com/johnccarter/genesis-core/blob/master/docs/optuna/optuna_performance_improvements.md Shows how to integrate the `NoDupeGuard` with Optuna's ask/tell optimization interface. This ensures that the optimization process avoids running trials with already known parameter sets. ```python ask_tell_optimize(study, objective, n_trials=1000, guard=guard) ``` -------------------------------- ### Tool: list_directory Source: https://github.com/johnccarter/genesis-core/blob/master/docs/mcp_server_guide.md Lists files and directories within a specified path. ```APIDOC ## POST /mcp (with tool: list_directory) ### Description Lists files and directories in a specified path. ### Method POST ### Endpoint /mcp ### Parameters #### Request Body - **method** (string) - Required - "tools/call" - **params** (object) - Required - **tool_name** (string) - Required - "list_directory" - **tool_input** (object) - Optional - **directory_path** (string) - Optional, default="." - Path to directory ### Request Example ```json { "method": "tools/call", "params": { "tool_name": "list_directory", "tool_input": { "directory_path": "src/core" } } } ``` ### Response #### Success Response (200) - **success** (boolean) - Whether the operation succeeded - **path** (string) - Directory path - **items** (array) - List of files/directories with metadata - **name** (string) - Item name - **path** (string) - Relative path - **type** (string) - "file" or "directory" - **size** (number) - Size in bytes (files only) - **count** (number) - Total number of items - **error** (string) - Error message (if failed) #### Response Example ```json { "success": true, "path": "src/core", "items": [ { "name": "__init__.py", "path": "src/core/__init__.py", "type": "file", "size": 100 }, { "name": "config", "path": "src/core/config", "type": "directory" } ], "count": 2, "error": null } ``` ```