### Environment Variables Configuration Example Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Demonstrates how to configure environment variables using a .env file for sensitive information like API keys and custom settings. It includes examples for LLM configuration, exchange API keys, and custom trading parameters. ```bash # LLM Configuration (for AI strategies) OLLAMA_API_KEY=your_api_key_here OLLAMA_BASE_URL=http://localhost:11434 # Exchange API Keys (for live trading) BINANCE_API_KEY=your_binance_key BINANCE_API_SECRET=your_binance_secret # Custom Configuration (optional) CC_PERCENT_SLIPPAGE=0.1 CC_PERCENT_FEE=0.1 ``` -------------------------------- ### Environment Variables Setup and Usage Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md This section demonstrates how to configure environment variables for the backtest-kit project, particularly for API credentials and framework settings. It shows an example `.env` file and the command-line usage with `dotenv-cli` to load these variables before running the application. ```bash # Exchange API credentials BINANCE_API_KEY=your_api_key BINANCE_API_SECRET=your_api_secret # Ollama configuration (for optimization mode) OLLAMA_HOST=http://localhost:11434 OLLAMA_MODEL=deepseek-v3.1 # Framework configuration LOG_LEVEL=debug ``` ```bash npm install --save-dev dotenv-cli dotenv -e .env -- node ./src/index.mjs ``` -------------------------------- ### Install backtest-kit using NPM Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Installs the backtest-kit package from the npm registry. This is the primary command for adding the library to your project. ```bash npm install backtest-kit ``` -------------------------------- ### Install Base Backtest-Kit Package (Bash) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Installs the core backtest-kit package and its essential dependencies using npm. This is the first step in setting up the framework for a new project. ```bash mkdir my-trading-bot cd my-trading-bot npm init -y npm install backtest-kit ``` -------------------------------- ### Complete Backtest Setup and Execution in TypeScript Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/04_Quick_Start_Guide.md This snippet demonstrates the full lifecycle of setting up and running a backtest using the backtest-kit library in TypeScript. It includes registering a mock exchange, configuring a backtest frame, defining a simple trading strategy, listening for backtest events (signals and completion), and finally executing the backtest. Dependencies include the 'backtest-kit' library. ```typescript import { addExchange, addFrame, addStrategy, Backtest, listenSignalBacktest, listenDoneBacktest, ICandleData, ISignalDto } from 'backtest-kit'; // 1. Register exchange addExchange({ exchangeName: "binance", async getCandles(symbol, interval, since, limit): Promise { const candles: ICandleData[] = []; const intervalMs = 60000; for (let i = 0; i < limit; i++) { const timestamp = since.getTime() + i * intervalMs; candles.push({ timestamp, open: 50000 + Math.random() * 1000, high: 50500 + Math.random() * 1000, low: 49500 + Math.random() * 1000, close: 50000 + Math.random() * 1000, volume: 100 }); } return candles; }, async formatPrice(symbol, price) { return price.toFixed(2); }, async formatQuantity(symbol, quantity) { return quantity.toFixed(8); } }); // 2. Configure backtest period addFrame({ frameName: "1d-test", interval: "1m", startDate: new Date("2024-01-01T00:00:00Z"), endDate: new Date("2024-01-02T00:00:00Z") }); // 3. Define strategy let signalGenerated = false; addStrategy({ strategyName: "simple-long", interval: "5m", async getSignal(symbol, when): Promise { if (signalGenerated) return null; signalGenerated = true; return { position: "long", note: "Test signal", priceTakeProfit: 51000, priceStopLoss: 49000, minuteEstimatedTime: 60 }; } }); // 4. Listen to events listenSignalBacktest((result) => { console.log(`[${result.action}] ${result.symbol}`); if (result.action === "closed") { console.log(` PNL: ${result.pnl.pnlPercentage.toFixed(2)}%`); } }); listenDoneBacktest(async (event) => { console.log("Backtest completed!"); // 5. Get results const stats = await Backtest.getData("BTCUSDT"); console.log(`Win Rate: ${stats.winRate}%`); console.log(`Sharpe Ratio: ${stats.sharpeRatio}`); // Export report await Backtest.dump("BTCUSDT", "./backtest-report.md"); }); // 6. Execute Backtest.background("BTCUSDT", { strategyName: "simple-long", exchangeName: "binance", frameName: "1d-test" }); ``` -------------------------------- ### Complete Production Setup Example with Backtest Kit Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/04-live-trading.md This comprehensive example illustrates a full production setup for live trading using backtest-kit. It includes environment variable loading, logger configuration, global settings, exchange and strategy registration, error handling, signal monitoring, and graceful shutdown procedures. ```typescript import { config } from "dotenv"; import ccxt from "ccxt"; import { setLogger, setConfig, addExchange, addStrategy, Live, listenSignalLive, listenDoneLive, listenError, } from "backtest-kit"; // Load environment variables config(); // Setup logger setLogger({ log: (topic, ...args) => console.log(`[LOG] ${topic}:`, ...args), debug: (topic, ...args) => { if (process.env.LOG_LEVEL === "debug") { console.debug(`[DEBUG] ${topic}:`, ...args); } }, info: (topic, ...args) => console.info(`[INFO] ${topic}:`, ...args), warn: (topic, ...args) => console.warn(`[WARN] ${topic}:`, ...args), }); // Global configuration setConfig({ CC_PERCENT_SLIPPAGE: 0.1, CC_PERCENT_FEE: 0.1, CC_SCHEDULE_AWAIT_MINUTES: 120, CC_MAX_SIGNAL_LIFETIME_MINUTES: 480, // 8 hours }); // Register exchange addExchange({ exchangeName: "binance-live", getCandles: async (symbol, interval, since, limit) => { const exchange = new ccxt.binance({ apiKey: process.env.BINANCE_API_KEY, secret: process.env.BINANCE_API_SECRET, enableRateLimit: true, }); const ohlcv = await exchange.fetchOHLCV( symbol, interval, since.getTime(), limit ); return ohlcv.map(([timestamp, open, high, low, close, volume]) => ({ timestamp, open, high, low, close, volume })); }, formatPrice: async (symbol, price) => { const exchange = new ccxt.binance(); await exchange.loadMarkets(); return exchange.priceToPrecision(symbol, price); }, formatQuantity: async (symbol, quantity) => { const exchange = new ccxt.binance(); await exchange.loadMarkets(); return exchange.amountToPrecision(symbol, quantity); }, }); // Register strategy addStrategy({ strategyName: "production-strategy", interval: "15m", getSignal: async (symbol) => { // Fetch candles for analysis const candles = await getCandles(symbol, "15m", 50); const currentPrice = candles[candles.length - 1].close; // Your trading logic here // Example: check if conditions met // return signal or null return null; // Or return signal }, callbacks: { onOpen: async (symbol, signal, price, backtest) => { console.log(`✓ POSITION OPENED: ${signal.position} @ ${price}`); await sendTelegramNotification(`Opened ${signal.position} position at ${price}`); }, onClose: async (symbol, signal, price, backtest) => { console.log(`✓ POSITION CLOSED @ ${price}`); // Log to database await logToDatabase({ symbol, signal, price }); }, }, }); // Handle errors listenError((error) => { console.error("❌ ERROR:", error); // Send alert sendErrorAlert(error); }); // Monitor signals listenSignalLive((event) => { if (event.action === "active") { console.log(`→ Monitoring: ${event.symbol} @ ${event.currentPrice}`); console.log(` TP progress: ${event.percentTp.toFixed(1)}%`); console.log(` SL distance: ${event.percentSl.toFixed(1)}%`); } }); // Completion listener listenDoneLive(async (event) => { console.log("Live trading completed"); await Live.dump(event.symbol, event.strategyName); }); // Start live trading console.log("Starting production live trading..."); const cancel = Live.background("BTCUSDT", { strategyName: "production-strategy", exchangeName: "binance-live", }); // Graceful shutdown process.on("SIGINT", () => { console.log("\nStopping..."); cancel(); setTimeout(() => process.exit(0), 10000); // 10 seconds to complete }); process.on("SIGTERM", () => { console.log("\nReceived SIGTERM..."); cancel(); setTimeout(() => process.exit(0), 10000); }); console.log("Live trading active. Press Ctrl+C to stop."); ``` -------------------------------- ### Install Ollama Client for AI/LLM Integration Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Installs the Ollama client library for local LLM inference. This is an optional dependency used for AI-powered strategy generation and signal generation with LLMs. ```bash npm install ollama ``` -------------------------------- ### Verify backtest-kit Installation Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Create a minimal test file to verify that the backtest-kit library has been imported successfully. This involves importing several key functions and logging a success message. Run the test file using Node.js. ```javascript import { setLogger, setConfig, addExchange, addStrategy, addFrame } from 'backtest-kit'; console.log('backtest-kit imported successfully'); ``` -------------------------------- ### Install Dependencies and Run Optimizer (Bash) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/demo/optimization/README.md Commands to navigate to the project directory, install necessary npm packages, set environment variables for Ollama API key, and start the optimizer. ```bash cd demo/optimization npm install export OLLAMA_API_KEY=your_ollama_api_key npm start ``` -------------------------------- ### Install Dependencies and Run Live Trading (Bash) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/demo/live/README.md Commands to navigate to the project directory, install npm dependencies, set environment variables for Ollama API key, and start the live trading process. ```bash cd demo/live npm install export OLLAMA_API_KEY=your_ollama_api_key npm start ``` -------------------------------- ### Verify Backtest Kit Installation Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md This TypeScript code snippet verifies the installation of the backtest-kit library. It sets up a basic logger, retrieves default configuration parameters, and imports core modules to ensure they are accessible. This is a crucial step for confirming a successful installation. ```typescript import { getDefaultConfig, setLogger } from 'backtest-kit'; // Test 1: Logger configuration setLogger({ log: (topic, ...args) => console.log(topic, args), debug: () => {}, info: () => {}, warn: () => {}, }); // Test 2: Configuration access const config = getDefaultConfig(); console.log('Loaded default configuration:', Object.keys(config).length, 'parameters'); // Test 3: Module imports import { addStrategy, addExchange, addFrame, Backtest, Live, Walker, } from 'backtest-kit'; console.log('All core modules successfully imported'); ``` -------------------------------- ### Install CCXT for Exchange Integration Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Installs the CCXT library, which provides unified API access to numerous cryptocurrency exchanges. This is an optional dependency often needed for fetching historical OHLCV data. ```bash npm install ccxt ``` -------------------------------- ### Install Optional LLM Dependencies (Bash) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Installs additional packages, 'ollama' and 'uuid', which are necessary for enabling LLM-based strategy generation features within the framework. ```bash npm install ollama uuid ``` -------------------------------- ### Install and Run Backtest (Bash) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/demo/backtest/README.md Commands to navigate to the project directory, install dependencies, set environment variables, and start the backtest process. Requires Node.js and npm. ```bash cd demo/backtest npm install export OLLAMA_API_KEY=your_ollama_api_key npm start ``` -------------------------------- ### Direct Programmatic Loading of Environment Variables Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Illustrates the direct programmatic method for loading environment variables using the 'dotenv/config' import. This approach is useful for simpler setups or when explicit control over loading is required. ```javascript import 'dotenv/config'; import { setConfig } from 'backtest-kit'; ``` -------------------------------- ### Minimal Project Structure for Backtest-Kit Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Illustrates the basic file and directory layout for a project using backtest-kit. It includes key files like package.json, .env, and the src directory for main logic, along with a dump directory for reports and persistence. ```tree my-trading-bot/ ├── package.json # Project metadata and dependencies ├── .env # Environment variables (API keys, config) ├── src/ │ ├── index.mjs # Main entry point │ └── utils/ │ ├── json.mjs # LLM helper (optional) │ └── messages.mjs # Market data formatter (optional) └── dump/ # Auto-generated reports and persistence ├── data/ # Crash recovery state (live mode only) │ ├── signal/ # PersistSignalAdapter storage │ ├── risk/ # PersistRiskAdapter storage │ ├── schedule/ # PersistScheduleAdapter storage │ └── partial/ # PersistPartialAdapter storage └── report/ # Markdown reports ├── backtest/ # BacktestMarkdownService output ├── live/ # LiveMarkdownService output └── walker/ # WalkerMarkdownService output ``` -------------------------------- ### Basic UI Server Launch (Default) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/packages/front/README.md A simplified example of launching the @backtest-kit/ui server with default settings. This is a concise way to get the full dashboard running quickly, demonstrating the ease of use. ```typescript // ✅ With @backtest-kit/ui import { serve } from '@backtest-kit/ui'; serve(); // Full dashboard ready! ``` -------------------------------- ### Configure Backtest-Kit Global Settings (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Shows an example of how to set global configuration parameters for backtest-kit using the setConfig function. This allows customization of parameters like slippage, fees, and timeouts. ```typescript import { setConfig } from 'backtest-kit'; setConfig({ // Increase slippage for low-liquidity markets CC_PERCENT_SLIPPAGE: 0.2, // Reduce fee for VIP tier CC_PERCENT_FEE: 0.05, // Extend pending signal timeout to 2 hours CC_SCHEDULE_AWAIT_MINUTES: 120, // Show signal notes in markdown reports CC_REPORT_SHOW_SIGNAL_NOTE: true, }); ``` -------------------------------- ### Create Trading Bot with Sidekick CLI (Bash) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/README.md This command uses npx to create a new trading bot project with the Backtest Kit Sidekick CLI. It then navigates into the project directory and starts the application. This is the recommended and fastest way to get started. ```bash # Create project with npx (recommended) npx -y @backtest-kit/sidekick my-trading-bot cd my-trading-bot npm start ``` -------------------------------- ### Import backtest-kit using ES Modules Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Demonstrates how to import functions and classes from the backtest-kit library using the ES Modules format (`import`). This is the recommended approach for modern JavaScript projects. ```javascript import { addStrategy, Backtest } from 'backtest-kit'; ``` -------------------------------- ### Configuring the Logger in Backtest-Kit Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Demonstrates how to set up the logging mechanism for backtest-kit using the `setLogger` function. This allows customization of log output by providing custom implementations for console logging methods. ```javascript import { setLogger } from 'backtest-kit'; setLogger({ log: console.log, debug: console.debug, info: console.info, warn: console.warn, }); ``` -------------------------------- ### Typical Public API Import Statement Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Demonstrates a typical import statement for the backtest-kit library, showcasing how to import various components for configuration, registration, execution, event monitoring, and utilities. ```javascript import { // Configuration setLogger, setConfig, // Component Registration addExchange, addStrategy, addFrame, addRisk, // Execution Backtest, Live, // Event Monitoring listenSignalBacktest, listenDoneBacktest, listenError, // Utilities getCandles, dumpSignal } from 'backtest-kit'; ``` -------------------------------- ### Import backtest-kit using CommonJS Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Demonstrates how to import functions and classes from the backtest-kit library using the CommonJS module format (`require`). This is typically used in Node.js environments that do not support ES Modules natively. ```javascript const { addStrategy, Backtest } = require('backtest-kit'); ``` -------------------------------- ### Live Trading Initialization and Recovery Example (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/06_Execution_Modes.md Demonstrates how to start live trading with the backtest-kit library and how the system automatically recovers state after a process restart. This ensures that active signals, scheduled orders, and risk limits are maintained accurately. ```typescript import { Live } from "backtest-kit"; // Start live trading - state saved to disk after each tick const cancel = Live.background("BTCUSDT", { strategyName: "production-v1", exchangeName: "binance" }); // Process crashes (power loss, SIGKILL, OOM) // ... time passes ... // Restart process - state automatically recovered Live.background("BTCUSDT", { strategyName: "production-v1", exchangeName: "binance" }); // Active signals continue monitoring TP/SL exactly where they left off // Scheduled signals wait for price activation // Risk limits reflect actual portfolio state ``` -------------------------------- ### Listen for Partial Profit Events with Dynamic Scaling in TypeScript Source: https://github.com/tripolskypetr/backtest-kit/blob/master/LLMs.md This example shows how to use `listenPartialProfitAvailable` from `backtest-kit` to dynamically scale out of positions based on profit levels. It defines custom percentages to close for different TP levels and executes partial closes using `executePartialClose`. Ensure `backtest-kit` is installed. ```typescript import { Constant, listenPartialProfitAvailable } from "backtest-kit"; // Advanced: Dynamic scaling based on level listenPartialProfitAvailable(({ symbol, signal, price, level, backtest }) => { const percentToClose = level === Constant.TP_LEVEL3 ? 0.25 : // 25% at first level level === Constant.TP_LEVEL2 ? 0.35 : // 35% at second level level === Constant.TP_LEVEL1 ? 0.40 : // 40% at third level 0; if (percentToClose > 0) { executePartialClose(symbol, signal.id, percentToClose); } }); ``` -------------------------------- ### Minimal tsconfig.json for Backtest-Kit Development Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Provides a recommended minimal TypeScript configuration file (tsconfig.json) for projects using backtest-kit. It focuses on essential settings for type checking, IDE intellisense, and compilation, ensuring compatibility with modern JavaScript features like async/await. ```json { "compilerOptions": { "target": "ES2020", "module": "ES2020", "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": true, "strict": true, "resolveJsonModule": true, "types": ["node"] }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } ``` -------------------------------- ### Install Optional Environment Variable Manager (Bash) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Installs 'dotenv-cli' as a development dependency, used for managing environment variables in the project, which can be helpful for configuration. ```bash npm install --save-dev dotenv-cli ``` -------------------------------- ### Backtest-Kit Core Dependencies (JSON) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Lists the primary dependencies automatically installed with the backtest-kit package. These packages provide essential functionalities for the framework. ```json { "di-kit": "^1.0.18", "di-scoped": "^1.0.20", "functools-kit": "^1.0.94", "get-moment-stamp": "^1.1.1", "ollama": "^0.6.3" } ``` -------------------------------- ### Get Backtest Statistics and Reports with Backtest.getData(), Backtest.getReport(), Backtest.dump() (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/04_Quick_Start_Guide.md Retrieve structured statistics, generate a markdown report, or export the backtest results to a file after execution. These methods require the 'backtest-kit' library and operate on a completed backtest identified by its symbol. ```typescript import { Backtest } from 'backtest-kit'; // Get structured data const stats = await Backtest.getData("BTCUSDT"); console.log(`Total Signals: ${stats.totalSignals}`); console.log(`Win Rate: ${stats.winRate}%`); console.log(`Sharpe Ratio: ${stats.sharpeRatio}`); console.log(`Average PNL: ${stats.avgPnl}%`); console.log(`Total PNL: ${stats.totalPnl}%`); // Generate markdown report const markdown = await Backtest.getReport("BTCUSDT"); console.log(markdown); // Export to file await Backtest.dump("BTCUSDT", "./results/backtest-report.md"); ``` -------------------------------- ### Run Live Trading with npm start Source: https://github.com/tripolskypetr/backtest-kit/blob/master/demo/live/README.md Executes the live trading functionality of the backtest-kit. This command initiates the trading process and generates various report files upon completion or during trading sessions. It outputs real-time trading actions and final report paths. ```bash npm start ``` -------------------------------- ### Backtest Kit Entry Point Template Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md This TypeScript code serves as a template for the main entry point of a backtest-kit application. It initializes the logger, sets custom configuration parameters, and demonstrates how to initiate a backtest using the Backtest module. It also includes necessary imports for configuration setup. ```typescript // src/index.ts import { setLogger, setConfig } from 'backtest-kit'; import './config/exchanges'; import './config/strategies'; import './config/frames'; import './config/risk'; // Initialize framework setLogger({ log: console.log, debug: console.debug, info: console.info, warn: console.warn, }); setConfig({ CC_PERCENT_SLIPPAGE: 0.1, CC_PERCENT_FEE: 0.1, }); // Execute run (example) import { Backtest } from 'backtest-kit'; await Backtest.background('BTCUSDT', { strategyName: 'macd-crossover', exchangeName: 'binance', frameName: '30d-backtest', }); ``` -------------------------------- ### Install dotenv-cli for Environment Variables Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Installs the dotenv-cli package for loading environment variables from .env files. This is useful for managing API keys and configuration parameters. ```bash npm install dotenv-cli ``` -------------------------------- ### Install TypeScript Peer Dependency Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Installs TypeScript version 5.0.0 or higher, which is a required peer dependency for backtest-kit to ensure type safety. This command enforces the version constraint. ```bash npm install typescript@^5.0.0 ``` -------------------------------- ### Install UUID for Signal Identifiers Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Installs the UUID library for generating unique identifiers. This is an optional dependency recommended for ensuring stronger uniqueness guarantees for signal IDs in production systems. ```bash npm install uuid ``` -------------------------------- ### Strategy Client Creation Example Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/08_Component_Registration.md This example illustrates the process of creating and retrieving a strategy client instance when the `Backtest.run` function is executed. It shows how the `StrategyConnectionService` computes a memoization key, retrieves the strategy schema, instantiates a `ClientStrategy`, and caches it for future use. ```typescript // Example execution flow: // 1. Backtest.run("BTCUSDT", { strategyName: "test_strategy", ... }) // 2. BacktestCommandService calls StrategyConnectionService.getClient("BTCUSDT", "test_strategy", true) // 3. Connection service computes memoization key: "BTCUSDT:test_strategy:backtest" // 4. If not cached, connection service: // - Calls StrategySchemaService.get("test_strategy") → returns IStrategySchema // - Creates new ClientStrategy(schema, symbol, backtest=true) // - Caches client under memoization key // 5. Returns cached/created ClientStrategy instance // 6. Command service calls clientStrategy.backtest(timeframes) to execute strategy ``` -------------------------------- ### Initialize Backtest-Kit Project with npx Source: https://github.com/tripolskypetr/backtest-kit/blob/master/README.md This command initializes a new trading bot project using Backtest-Kit. It automatically sets up the project structure, including strategy, risk management, and LLM integration. The process requires Node.js and npm to be installed. ```bash npx -y @backtest-kit/sidekick my-trading-bot cd my-trading-bot npm start ``` -------------------------------- ### Position Sizing Calculator with backtest-kit (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/LLMs.md Demonstrates how to use the `backtest-kit` library to add and calculate position sizes using different risk management methods like fixed percentage, Kelly Criterion, and ATR-based sizing. It requires the `backtest-kit` library and provides examples for calculating quantities based on account balance, entry price, stop loss, win rate, win/loss ratio, and ATR. ```typescript import { addSizing, PositionSize } from "backtest-kit"; // Fixed Percentage Risk - risk fixed % of account per trade addSizing({ sizingName: "conservative", note: "Conservative 2% risk per trade", method: "fixed-percentage", riskPercentage: 2, // Risk 2% of account per trade maxPositionPercentage: 10, // Max 10% of account in single position (optional) minPositionSize: 0.001, // Min 0.001 BTC position (optional) maxPositionSize: 1.0, // Max 1.0 BTC position (optional) }); // Kelly Criterion - optimal bet sizing based on edge addSizing({ sizingName: "kelly-quarter", note: "Kelly Criterion with 25% multiplier for safety", method: "kelly-criterion", kellyMultiplier: 0.25, // Use 25% of full Kelly (recommended for safety) maxPositionPercentage: 15, // Cap position at 15% of account (optional) minPositionSize: 0.001, // Min 0.001 BTC position (optional) maxPositionSize: 2.0, // Max 2.0 BTC position (optional) }); // ATR-based - volatility-adjusted position sizing addSizing({ sizingName: "atr-dynamic", note: "ATR-based sizing with 2x multiplier", method: "atr-based", riskPercentage: 2, // Risk 2% of account atrMultiplier: 2, // Use 2x ATR as stop distance maxPositionPercentage: 12, // Max 12% of account (optional) minPositionSize: 0.001, // Min 0.001 BTC position (optional) maxPositionSize: 1.5, // Max 1.5 BTC position (optional) }); // Calculate position sizes const quantity1 = await PositionSize.fixedPercentage( "BTCUSDT", 10000, // Account balance: $10,000 50000, // Entry price: $50,000 49000, // Stop loss: $49,000 { sizingName: "conservative" } ); console.log(`Position size: ${quantity1} BTC`); const quantity2 = await PositionSize.kellyCriterion( "BTCUSDT", 10000, // Account balance: $10,000 50000, // Entry price: $50,000 0.55, // Win rate: 55% 1.5, // Win/loss ratio: 1.5 { sizingName: "kelly-quarter" } ); console.log(`Position size: ${quantity2} BTC`); const quantity3 = await PositionSize.atrBased( "BTCUSDT", 10000, // Account balance: $10,000 50000, // Entry price: $50,000 500, // ATR: $500 { sizingName: "atr-dynamic" } ); console.log(`Position size: ${quantity3} BTC`); ``` -------------------------------- ### Package.json for ES Module Support (JSON) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Configures the project's package.json to support ES Modules, including setting the 'type' to 'module' and defining a start script for running the application. ```json { "name": "my-trading-bot", "version": "1.0.0", "type": "module", "scripts": { "start": "node ./src/index.mjs" } } ``` -------------------------------- ### Define Trading Strategy with TypeScript Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/04_Quick_Start_Guide.md Implements a trading strategy by providing a unique name, signal generation interval, and the `getSignal` function. The `getSignal` function contains the core trading logic, returning either a trading signal object (long/short position, take profit, stop loss) or null if no signal is generated. This example demonstrates a simple 'always long' strategy. ```typescript import { addStrategy, ISignalDto, SignalInterval } from 'backtest-kit'; addStrategy({ strategyName: "simple-long", interval: "5m" as SignalInterval, // Check for signals every 5 minutes async getSignal(symbol: string, when: Date): Promise { // Your strategy logic here // Return null when no signal, or return a signal object // Example: Always long when price is available return { position: "long", note: "Simple long strategy", // priceOpen: undefined means open immediately at current price priceTakeProfit: 51000, // Exit at +2% profit priceStopLoss: 49000, // Exit at -2% loss minuteEstimatedTime: 60 // Close after 60 minutes if not hit }; } }); ``` -------------------------------- ### Create New Backtest Kit Project Source: https://github.com/tripolskypetr/backtest-kit/blob/master/README.md Initializes a new Backtest Kit trading bot project using the Sidekick package, similar to how create-react-app is used for React projects. ```bash npx @backtest-kit/sidekick create-my-bot ``` -------------------------------- ### Initialize Backtest Kit Configuration (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/LLMs.md Sets up the backtest-kit framework by configuring essential parameters like signal wait time and average price candle count before initiating backtest or live strategies. This ensures all configurations are applied prior to strategy execution. ```typescript import { setConfig, Backtest, Live } from "backtest-kit"; // 1. Configure framework first await setConfig({ CC_SCHEDULE_AWAIT_MINUTES: 90, CC_AVG_PRICE_CANDLES_COUNT: 7, }); // 2. Then run strategies Backtest.background("BTCUSDT", { strategyName: "my-strategy", exchangeName: "binance", frameName: "1d-backtest" }); Live.background("ETHUSDT", { strategyName: "my-strategy", exchangeName: "binance" }); ``` -------------------------------- ### Configure and Run Basic Live Trading (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/58_Live_Trading.md Demonstrates how to configure a strategy and an exchange, then initiate live trading for a given symbol. It shows how to subscribe to position open and close events. ```typescript import { Live, addStrategy, addExchange } from "backtest-kit"; // Configure components addStrategy({ strategyName: "my-live-strategy", interval: "5m", getSignal: async (payload) => { // Strategy logic } }); addExchange({ exchangeName: "binance", getCandles: async (symbol, interval, startTime, limit) => { // Fetch real-time data from Binance API } }); // Run live trading for await (const result of Live.run("BTCUSDT", { strategyName: "my-live-strategy", exchangeName: "binance" })) { if (result.action === "opened") { console.log("Position opened:", result.signal.id); } if (result.action === "closed") { console.log("Position closed:", result.pnl.pnlPercentage); } } ``` -------------------------------- ### TypeScript Configuration (JSON) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Defines the minimal TypeScript configuration required for the project, specifying compiler options like target, module resolution, and strictness. ```json { "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "node", "esModuleInterop": true, "strict": true, "skipLibCheck": true } } ``` -------------------------------- ### Live Trading with Backtest-Kit and Crash Recovery Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/33_ClientStrategy.md Illustrates how to implement live trading using the 'Live' module from 'backtest-kit'. It includes setting up listeners for signal events and running the live trading loop, which automatically restores state in case of a crash. ```typescript import { Live, listenSignalLive } from "backtest-kit"; // Listen for signal events listenSignalLive((result) => { if (result.action === "opened") { console.log("Position opened:", result.signal.id); } else if (result.action === "closed") { console.log("Position closed:", result.pnl.pnlPercentage); } }); // Start live trading (will restore state if crashed) for await (const result of Live.run("BTCUSDT", { strategyName: "momentum-scalper", exchangeName: "binance", })) { console.log(`Action: ${result.action}`); } ``` -------------------------------- ### Configure Backtest Timeframe with TypeScript Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/04_Quick_Start_Guide.md Sets up the backtest period and iteration interval using the `addFrame` function. This configuration defines the start and end dates for the backtest and the frequency at which the strategy's `tick()` method will be called. Available intervals range from 1 minute to 1 day. ```typescript import { addFrame, FrameInterval } from 'backtest-kit'; addFrame({ frameName: "1d-test", interval: "1m", // Tick every 1 minute startDate: new Date("2024-01-01T00:00:00Z"), endDate: new Date("2024-01-02T00:00:00Z") // 1 day backtest }); ``` -------------------------------- ### Registering a Custom Frame Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/35_ClientFrame.md Example of how to register a new frame configuration with the backtest kit. This involves providing a unique frame name, the desired interval, start and end dates, and callback functions to handle the generated timeframe. The example shows registration for a 1-minute interval over a 24-hour period. ```typescript import { addFrame } from "backtest-kit"; addFrame({ frameName: "1d-backtest", interval: "1m", // 1-minute tick resolution startDate: new Date("2024-01-01T00:00:00Z"), endDate: new Date("2024-01-02T00:00:00Z"), callbacks: { onTimeframe: (timeframe, startDate, endDate, interval) => { console.log(`Generated ${timeframe.length} timestamps`); console.log(`Period: ${startDate} to ${endDate}`); console.log(`Interval: ${interval}`); } } }); ``` -------------------------------- ### Basic Performance Tracking Example (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/73_Performance_Metrics.md Demonstrates how to use the `listenPerformance` function to subscribe to performance events and log them to the console. It also shows how to run a backtest and then unsubscribe from the events. ```typescript import { listenPerformance, Backtest } from "backtest-kit"; // Subscribe to performance events const unsubscribe = listenPerformance((event) => { console.log(`${event.metricType}: ${event.duration.toFixed(2)}ms`); }); // Run backtest (emits performance events automatically) await Backtest.run("BTCUSDT", { strategyName: "my-strategy", exchangeName: "binance", frameName: "1d-backtest" }); // Stop listening unsubscribe(); ``` -------------------------------- ### Configure Backtest-Kit Logger (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/01-getting-started.md Demonstrates how to configure the backtest-kit logger by providing a custom implementation using console methods. This enables the framework to output logs. ```typescript import { setLogger } from 'backtest-kit'; setLogger({ log: (topic, ...args) => console.log(`[LOG] ${topic}:`, ...args), debug: (topic, ...args) => console.debug(`[DEBUG] ${topic}:`, ...args), info: (topic, ...args) => console.info(`[INFO] ${topic}:`, ...args), warn: (topic, ...args) => console.warn(`[WARN] ${topic}:`, ...args), }); ``` -------------------------------- ### Launch UI Server with @backtest-kit/ui Source: https://github.com/tripolskypetr/backtest-kit/blob/master/packages/front/README.md Starts the UI server for the @backtest-kit/ui dashboard. It takes the host and port as arguments. The dashboard will then be accessible via a web browser at the specified address. ```typescript import { serve } from '@backtest-kit/ui'; // Start the UI server serve('0.0.0.0', 60050); // Dashboard available at http://localhost:60050 ``` -------------------------------- ### Verify TypeScript Types Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Validate that TypeScript types are correctly resolved by the TypeScript compiler. This command checks the type definitions (`types.d.ts`) without performing any compilation, ensuring type safety. ```bash npx tsc --noEmit ``` -------------------------------- ### Sidekick CLI Options for Project Creation Source: https://github.com/tripolskypetr/backtest-kit/blob/master/packages/sidekick/README.md Demonstrates different ways to use the @backtest-kit/sidekick CLI for creating trading bot projects. It shows how to specify a custom project name or create a project in the current directory if it's empty. ```bash # Create project with custom name npx -y @backtest-kit/sidekick my-bot # Create in current directory (must be empty) npx -y @backtest-kit/sidekick . ``` -------------------------------- ### Configure Exchange for Live Trading (TypeScript) Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/example/04-live-trading.md Sets up a cryptocurrency exchange for live trading by configuring API keys, enabling rate limiting, and ensuring price/quantity precision. This is crucial for interacting with exchanges like Binance in real-time. ```typescript import ccxt from "ccxt"; import { addExchange } from "backtest-kit"; addExchange({ exchangeName: "binance-live", getCandles: async (symbol, interval, since, limit) => { const exchange = new ccxt.binance({ apiKey: process.env.BINANCE_API_KEY, secret: process.env.BINANCE_API_SECRET, enableRateLimit: true, // Important for live trading! }); const ohlcv = await exchange.fetchOHLCV( symbol, interval, since.getTime(), limit ); return ohlcv.map(([timestamp, open, high, low, close, volume]) => ({ timestamp, open, high, low, close, volume })); }, formatPrice: async (symbol, price) => { const exchange = new ccxt.binance(); const market = await exchange.loadMarkets(); return exchange.priceToPrecision(symbol, price); }, formatQuantity: async (symbol, quantity) => { const exchange = new ccxt.binance(); const market = await exchange.loadMarkets(); return exchange.amountToPrecision(symbol, quantity); }, }); ``` -------------------------------- ### Loading Environment Variables with dotenv-cli Source: https://github.com/tripolskypetr/backtest-kit/blob/master/docs/design/03_Installation_and_Setup.md Shows how to integrate dotenv-cli into the package.json scripts for automatically loading environment variables from a .env file before running the application. This is the recommended approach for managing environment configurations. ```json { "scripts": { "start": "dotenv -e .env -- node ./src/index.mjs" } } ```