### Python Environment Setup Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Instructions for installing Python 3.12, necessary development libraries, and setting up a virtual environment for the bot project. ```bash sudo apt install -y python3.12 python3.12-venv python3.12-dev python3-pip sudo apt install -y libssl-dev libffi-dev libbz2-dev libreadline-dev libsqlite3-dev libncurses5-dev libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev mkdir -p /root/market_bot && cd /root/market_bot python3.12 -m venv venv source venv/bin/activate pip install --upgrade pip setuptools wheel pip install python-telegram-bot requests pandas numpy psutil ``` -------------------------------- ### Bot Management and Troubleshooting Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Common commands for managing the systemd service, viewing logs, and inspecting system resources. ```bash sudo systemctl status market-bot sudo journalctl -u market-bot -f htop ss -tulpn ``` -------------------------------- ### Configure System Monitoring and Logging Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Commands to install monitoring tools like htop and netdata, and to configure systemd journald limits to prevent disk space exhaustion. ```bash sudo apt install -y htop iotop nethogs bash <(curl -Ss https://my-netdata.io/kickstart.sh) ``` ```ini SystemMaxUse=500M SystemKeepFree=1G SystemMaxFileSize=100M MaxRetentionSec=7day ``` -------------------------------- ### System Initialization and Maintenance Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Commands for updating the Ubuntu system, installing essential utilities, configuring time zones, and managing swap memory to ensure a stable server environment. ```bash sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y sudo apt install -y curl wget git build-essential software-properties-common apt-transport-https ca-certificates gnupg lsb-release htop nano ufw fail2ban logrotate sudo timedatectl set-timezone UTC sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab ``` -------------------------------- ### System Performance Optimization Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Configuration snippets for increasing file descriptor limits, tuning network stack parameters via sysctl, and setting up log rotation to prevent disk space issues. ```bash # Set limits in /etc/security/limits.d/market-bot.conf root soft nofile 65536 root hard nofile 65536 root soft nproc 32768 root hard nproc 32768 # Sysctl settings in /etc/sysctl.d/99-market-bot.conf net.core.somaxconn = 1024 net.ipv4.tcp_max_syn_backlog = 2048 vm.swappiness = 10 # Logrotate configuration /root/market_bot/*.log { daily rotate 7 compress } ``` -------------------------------- ### Automate Project Backups Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md A script to archive the project directory while excluding temporary files and virtual environments, with automatic cleanup of old backups. ```bash #!/bin/bash BACKUP_DIR="/root/backups" DATE=$(date +%Y%m%d_%H%M%S) PROJECT_DIR="/root/market_bot" mkdir -p $BACKUP_DIR tar -czf $BACKUP_DIR/market_bot_$DATE.tar.gz \ -C /root market_bot \ --exclude='venv' \ --exclude='__pycache__' \ --exclude='*.pyc' find $BACKUP_DIR -name "market_bot_*.tar.gz" -mtime +7 -delete ``` -------------------------------- ### Verify Network and API Connectivity Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Tools to test connectivity to external services like Bybit and Telegram, and to verify DNS resolution. Helps troubleshoot network-related bot failures. ```bash curl -I https://api.bybit.com curl -I https://api.telegram.org nslookup api.bybit.com ``` -------------------------------- ### Harden Server Security Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Configures UFW firewall, Fail2Ban for SSH protection, and disables root login to secure the server environment. ```bash sudo ufw allow 22/tcp sudo ufw enable ``` ```ini [DEFAULT] bantime = 3600 findtime = 600 maxretry = 5 [sshd] enabled = true port = 22 logpath = /var/log/auth.log ``` -------------------------------- ### Replay Engine Usage Examples Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/REPLAY_ENGINE_ARCHITECTURE.md Practical examples for running the Replay Engine on single snapshots, recent history, or specific lists, including report generation and export. ```python from core.replay_engine import ReplayEngine from core.signal_snapshot_store import SignalSnapshotStore from core.replay_report import ReplayReporter store = SignalSnapshotStore() engine = ReplayEngine(store) reporter = ReplayReporter() # Single snapshot replay result = engine.replay_snapshot(snapshot_id=123) # Batch replay and report generation results = engine.replay_recent_snapshots(symbol="BTCUSDT", limit=50) report = reporter.generate_report(results) print(reporter.format_report(report)) # Export to JSON import json with open("replay_report.json", "w") as f: json.dump(reporter.export_to_dict(report), f, indent=2) ``` -------------------------------- ### Usage Examples for Snapshot Store Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/SIGNAL_SNAPSHOT_STORE_ARCHITECTURE.md Demonstrates how to instantiate the store, save a snapshot with market data, and retrieve snapshots from the database. ```python store = SignalSnapshotStore() snapshot_id = store.save_snapshot( timestamp=datetime.now(UTC), symbol="BTCUSDT", states={"15m": "D", "30m": "A"}, confidence=0.75, entropy=0.25, score=85.0, risk_level="LOW" ) # Retrieval snapshot = store.get_snapshot_by_id(snapshot_id) recent = store.get_recent_snapshots(limit=50) ``` -------------------------------- ### Reinstall Python Dependencies Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Updates and forces a clean reinstallation of all project dependencies from requirements.txt within the virtual environment. This is useful for resolving corrupted package issues. ```bash cd /root/market_bot source venv/bin/activate pip install --upgrade --force-reinstall -r requirements.txt ``` -------------------------------- ### Systemd Service Configuration Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Configuration for running the bot as a background service, ensuring it restarts automatically on failure and logs output to the system journal. ```ini [Unit] Description=Market Trading Bot After=network.target [Service] Type=simple User=root WorkingDirectory=/root/market_bot Environment="PATH=/root/market_bot/venv/bin:/usr/local/bin:/usr/bin:/bin" ExecStart=/root/market_bot/venv/bin/python /root/market_bot/runner.py Restart=always RestartSec=10 StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target ``` -------------------------------- ### Example: Retrieving Recent Decisions Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/DECISION_TRACE_ARCHITECTURE.md Shows how to use the get_recent_decisions method to fetch trading decisions, with examples for retrieving a limited number, filtering by symbol, and filtering for blocked trades. ```python # Получить последние 50 решений recent = trace.get_recent_decisions(limit=50) # Получить решения по символу btc_decisions = trace.get_recent_decisions(limit=100, symbol="BTCUSDT") # Получить только заблокированные решения blocked = trace.get_recent_decisions(limit=100, allow_trading=False) ``` -------------------------------- ### Automate Bot Health Checks with Cron Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Creates a bash script to check if the bot service is active and restarts it if necessary, scheduled via crontab. ```bash #!/bin/bash if ! systemctl is-active --quiet market-bot; then echo "Bot is not running! Restarting..." systemctl restart market-bot echo "Bot restarted at $(date)" >> /root/market_bot/bot_restarts.log fi ``` ```bash */5 * * * * /root/market_bot/check_bot.sh ``` -------------------------------- ### Module Registry Registration Example Source: https://github.com/samurai-deus/python-bot/blob/main/SYSTEM_ARCHITECTURE_CANONICAL.md Shows how to register a module with the ModuleRegistry, specifying its name, criticality, instance retrieval function, timeout, and description. This is crucial for centralized module management. ```python module_registry.register_module( name="DecisionCore", criticality=ModuleCriticality.CRITICAL, get_instance=get_decision_core, timeout_seconds=5.0, description="Единая точка принятия торговых решений" ) ``` -------------------------------- ### Position Sizer Calculation Example (Python) Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/POSITION_SIZER_ARCHITECTURE.md Demonstrates how to use the PositionSizer class to calculate a position size. It shows the instantiation of the sizer, portfolio state, and the call to the calculate method with sample inputs. ```python from core.position_sizer import PositionSizer, PortfolioStateAdapter from core.portfolio_brain import PortfolioState # Создаём PositionSizer sizer = PositionSizer() # Создаём PortfolioState portfolio_state = PortfolioState( total_exposure=5000.0, long_exposure=3000.0, short_exposure=2000.0, net_exposure=1000.0, risk_budget=10000.0, used_risk=5000.0 ) # Адаптер для PortfolioState adapter = PortfolioStateAdapter(portfolio_state) # Рассчитываем размер позиции result = sizer.calculate( confidence=0.8, entropy=0.3, portfolio_state=adapter, symbol="BTCUSDT", balance=10000.0 ) # Результат: # position_allowed = True # final_risk = 2.0 * 0.8 * 0.7 * 0.5 = 0.56% # position_size_usd = 10000.0 * 0.56 / 100 = 56.0 USDT ``` -------------------------------- ### SystemGuardian Usage Example Source: https://github.com/samurai-deus/python-bot/blob/main/SYSTEM_ARCHITECTURE_CANONICAL.md Demonstrates how to use the SystemGuardian to check trading permissions before initiating a trading cycle. It involves obtaining an instance of SystemGuardian and calling its `can_trade` method. ```python # В runner.py - перед каждым торговым циклом system_guardian = get_system_guardian() permission = await system_guardian.can_trade() if not permission.allowed: return # Early exit ``` -------------------------------- ### Monitor System Memory Usage Source: https://github.com/samurai-deus/python-bot/blob/main/operations/SERVER_SETUP.md Commands to inspect current RAM availability and identify memory-intensive processes. Useful for diagnosing crashes related to out-of-memory errors. ```bash free -h ps aux --sort=-%mem | head ``` -------------------------------- ### Example: Logging a Trading Decision Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/DECISION_TRACE_ARCHITECTURE.md Demonstrates how to instantiate the DecisionTrace and log a specific trading decision, including details like symbol, source, trading allowance, block level, reason, and a context snapshot. ```python from core.decision_trace import DecisionTrace, BlockLevel trace = DecisionTrace() # Логирование решения от MetaDecisionBrain trace.log_decision( symbol="SYSTEM", decision_source="MetaDecisionBrain", allow_trading=False, block_level=BlockLevel.HARD, reason="High entropy (0.75) combined with low confidence (0.30)", context_snapshot={ "entropy_score": 0.75, "confidence_score": 0.30, "portfolio_exposure": 0.5 } ) ``` -------------------------------- ### Data Validator Usage Example Source: https://github.com/samurai-deus/python-bot/blob/main/SYSTEM_ARCHITECTURE_CANONICAL.md Provides an example of using the DataValidator to validate a confidence score. It shows how to obtain a validator instance and call its validation method, handling potential invalid results. ```python validator = get_data_validator() result = validator.validate_confidence_score(confidence) if not result.valid: # Обработка ошибки ... ``` -------------------------------- ### Example: Low Confidence Calculation Python Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/COGNITIVE_ENGINE_ARCHITECTURE.md Presents a Python code example for a scenario resulting in low confidence and high entropy. The SignalSnapshot features inconsistent market states, a low score, a decision to skip, high risk, and extreme volatility, leading to the expected metric values. ```python # Assuming MarketState, SignalDecision, RiskLevel, VolatilityLevel enums are defined # Assuming SignalSnapshot class is defined snapshot = SignalSnapshot( states={"15m": MarketState.D, "30m": MarketState.A, "1h": MarketState.B}, score=40, score_max=125, decision=SignalDecision.SKIP, risk_level=RiskLevel.HIGH, volatility_level=VolatilityLevel.EXTREME, ... ) # Expected result (approximate): # confidence ≈ 0.25 # Low confidence # entropy ≈ 0.80 # High uncertainty ``` -------------------------------- ### Decision Trace Logging Example Source: https://github.com/samurai-deus/python-bot/blob/main/SYSTEM_ARCHITECTURE_CANONICAL.md Shows how to log a trading decision using the DecisionTrace utility. This includes details like the symbol, decision source, trading allowance, block level, reason, and a context snapshot for explainability. ```python decision_trace.log_decision( symbol="BTCUSDT", decision_source="DecisionCore", allow_trading=True, block_level=BlockLevel.NONE, reason="All checks passed", context_snapshot={...} ) ``` -------------------------------- ### Example: High Confidence Calculation Python Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/COGNITIVE_ENGINE_ARCHITECTURE.md Provides a Python code example illustrating a scenario that results in high confidence and low entropy. The SignalSnapshot is configured with consistent market states, high score, low risk, and normal volatility, leading to expected metric values. ```python # Assuming MarketState, SignalDecision, RiskLevel, VolatilityLevel enums are defined # Assuming SignalSnapshot class is defined snapshot = SignalSnapshot( states={"15m": MarketState.D, "30m": MarketState.D, "1h": MarketState.D}, score=100, score_max=125, decision=SignalDecision.ENTER, risk_level=RiskLevel.LOW, volatility_level=VolatilityLevel.NORMAL, ... ) # Expected result (approximate): # confidence ≈ 0.85 # High confidence # entropy ≈ 0.15 # Low uncertainty ``` -------------------------------- ### Example: Conflict Scenario Calculation Python Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/COGNITIVE_ENGINE_ARCHITECTURE.md Illustrates a Python code example demonstrating a conflict scenario that leads to low confidence and high entropy. The SignalSnapshot shows a high score but a decision to block, coupled with high risk and high volatility, resulting in penalized confidence and increased entropy. ```python # Assuming MarketState, SignalDecision, RiskLevel, VolatilityLevel enums are defined # Assuming SignalSnapshot class is defined snapshot = SignalSnapshot( states={"15m": MarketState.D, "30m": MarketState.D}, score=90, # High score score_max=125, decision=SignalDecision.BLOCK, # But blocked risk_level=RiskLevel.HIGH, # And high risk ... ) # Expected result (approximate): # confidence ≈ 0.30 # Low confidence due to conflicts # entropy ≈ 0.75 # High uncertainty due to conflict ``` -------------------------------- ### Python Example: Invalid Data Type for State Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/MARKET_STATE_INVARIANTS.md Shows a Python example where an integer is used instead of a MarketState enum. The code explains that this is detected by the validate_state function, logged as an ERROR, and the state is subsequently replaced with None. ```python states = {"15m": 123} # Число вместо enum # → Ловится в validate_state() # → Логируется ERROR # → Заменяется на None ``` -------------------------------- ### Python Logging Example: String Instead of Enum Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/MARKET_STATE_INVARIANTS.md Provides a sample Python log output for an error where a string was used instead of an enum for a market state. It includes an ERROR message indicating the invalid type and context, followed by a WARNING about auto-normalization. ```python ERROR: Invalid market state type detected: D (type: str) in context: normalize_states_dict[15m] WARNING: Auto-normalized string 'D' to MarketState enum (should be normalized earlier) ``` -------------------------------- ### Integrate Replay Engine with Drift Detector Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/REPLAY_ENGINE_ARCHITECTURE.md Example usage of the ReplayEngine to detect system drift. It processes snapshots, generates a report, and triggers an alert if the change rate exceeds a defined threshold. ```python results = engine.replay_recent_snapshots(limit=100) report = reporter.generate_report(results) if report.change_rate > 0.2: print("Drift detected: {:.1f}% decisions changed".format(report.change_rate * 100)) ``` -------------------------------- ### Python Logging Example: Invalid String After Normalization Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/MARKET_STATE_INVARIANTS.md Presents a Python log output for an invalid string state after normalization attempts. It shows an initial ERROR for an invalid type, a WARNING about failing to normalize, and a subsequent 'INVARIANT VIOLATION' error when the state becomes None. ```python ERROR: Invalid market state type detected: X (type: str) in context: normalize_states_dict[15m] WARNING: Could not normalize state 'X', using None as fallback ERROR: INVARIANT VIOLATION in calculate_score: state[15m] = None (type: NoneType), expected MarketState or None. This is an architectural error. ``` -------------------------------- ### Python Example: String Instead of Enum State Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/MARKET_STATE_INVARIANTS.md Illustrates a scenario in Python where a string value is provided instead of the expected MarketState enum. The code demonstrates how this is caught during state normalization and validation, logged as an ERROR, and then normalized or replaced with None. ```python states = {"15m": "D"} # Строка вместо MarketState.D # → Ловится в normalize_states_dict() и validate_state() # → Логируется ERROR # → Нормализуется или заменяется на None ``` -------------------------------- ### Initialize and Run Trading Bot Source: https://github.com/samurai-deus/python-bot/blob/main/CLAUDE.md Commands to navigate to the project directory, activate the virtual environment, and execute the main bot runner script. ```bash cd C:/Users/Дмитрий/Documents/market_bot source venv/bin/activate # или venv\Scripts\activate на Windows python runner.py ``` -------------------------------- ### Position Sizer Calculation Example - Position Not Allowed (Python) Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/POSITION_SIZER_ARCHITECTURE.md An example demonstrating a scenario where the calculated position is not allowed due to the final risk being below the minimum threshold. This highlights the 'reason' field in the result. ```python result = sizer.calculate( confidence=0.3, # Низкая уверенность entropy=0.8, # Высокая неопределённость portfolio_state=adapter, symbol="BTCUSDT", balance=10000.0 ) # Результат: # position_allowed = False # final_risk = 2.0 * 0.3 * 0.2 * 0.5 = 0.06% < 0.5% (min_threshold) # reason = "Risk too small after scaling (0.06% < 0.50%)" ``` -------------------------------- ### Position Sizer Calculation Example - High Confidence (Python) Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/POSITION_SIZER_ARCHITECTURE.md An example showcasing a scenario with high confidence and low entropy, resulting in a permitted position. It illustrates how these factors positively influence the final risk calculation. ```python result = sizer.calculate( confidence=0.9, # Высокая уверенность entropy=0.2, # Низкая неопределённость portfolio_state=adapter, symbol="BTCUSDT", balance=10000.0 ) # Результат: # position_allowed = True # final_risk = 2.0 * 0.9 * 0.8 * 0.5 = 0.72% # position_size_usd = 10000.0 * 0.72 / 100 = 72.0 USDT ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/samurai-deus/python-bot/blob/main/CLAUDE.md Required configuration parameters for the trading bot, including API credentials for Bybit, Telegram bot tokens, and operational flags for trading modes. ```env TELEGRAM_BOT_TOKEN=... BYBIT_API_KEY=... BYBIT_API_SECRET=... BYBIT_TESTNET=true BOT_INTERVAL=300 DRY_RUN=true PAPER_TRADING=false LIVE_TRADING=false MAX_CONSECUTIVE_ERRORS=5 ERROR_PAUSE=600 LOG_FILE=monitor.log ``` -------------------------------- ### Python Logging Example: Invalid Type for State Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/MARKET_STATE_INVARIANTS.md This Python log example demonstrates an 'INVARIANT VIOLATION' error. It shows a case where an integer (123) was found for a state, and the expected type was MarketState or None, indicating an architectural error. ```python ERROR: INVARIANT VIOLATION in risk_level: state[15m] = 123 (type: int), expected MarketState or None. This is an architectural error. ``` -------------------------------- ### Create SignalSnapshot Instance Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/SIGNAL_SNAPSHOT_ARCHITECTURE.md Demonstrates the instantiation of a SignalSnapshot object with required market data, including timestamp, symbol, market states, and risk parameters. ```python snapshot = SignalSnapshot( timestamp=datetime.now(UTC), symbol="BTCUSDT", timeframe_anchor="15m", states={"15m": MarketState.D, "30m": MarketState.A, "1h": MarketState.B}, market_regime=market_regime, volatility_level=VolatilityLevel.NORMAL, correlation_level=0.75, score=85, score_max=125, risk_level=RiskLevel.LOW, recommended_leverage=3.0, entry=50000.0, tp=51000.0, sl=49500.0, decision=SignalDecision.ENTER, decision_reason="Score: 85/125, Mode: TRADE, Risk: LOW", directions={"30m": "UP", "1h": "UP"}, score_details={"total_score": 85, "volatility_score": 10}, reasons=["Чёткий отказ на 15m", "1H и 30m согласованы"] ) ``` -------------------------------- ### Replay historical signal snapshots using ReplayEngine Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/SIGNAL_SNAPSHOT_STORE_ARCHITECTURE.md Demonstrates how to use the ReplayEngine to retrieve and process historical snapshots within a specific time range. It iterates through snapshots to regenerate signals for backtesting or analysis purposes. ```python from core.signal_snapshot_store import ReplayEngine from datetime import timedelta replay = ReplayEngine(store) # Воспроизвести snapshot'ы за последний час end_time = datetime.now(UTC) start_time = end_time - timedelta(hours=1) snapshots = replay.replay_snapshots(start_time, end_time, symbol="BTCUSDT") for snapshot in snapshots: result = replay.replay_signal_generation(snapshot) print(f"Replay: {result['symbol']} at {result['timestamp']}") ``` -------------------------------- ### SystemGuardian Integration in Market Analysis Loop (Python) Source: https://github.com/samurai-deus/python-bot/blob/main/FAIL_SAFE_ARCHITECTURE.md This snippet shows how SystemGuardian is integrated into the market analysis loop in `runner.py`. It demonstrates the sequence of checks performed before each trading cycle, including invariant checks, module health, and TradingGate verification. ```python # В runner.py - перед каждым торговым циклом async def market_analysis_loop(): # 1. SystemGuardian проверяет все инварианты violations = await system_guardian.check_all_invariants() if violations: await system_guardian.handle_violations(violations) return # Early exit # 2. Проверка здоровья модулей health_status = await system_guardian.check_module_health() if health_status.has_critical_failures: system_state → SAFE_HALT return # 3. TradingGate проверка permission = await trading_gate.can_trade() if not permission.allowed: return # Early exit # 4. Нормальная работа # ... ``` -------------------------------- ### Integrate PositionSizer with SignalSnapshot Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/POSITION_SIZER_ARCHITECTURE.md Demonstrates how to initialize the PositionSizer and calculate position sizing based on a signal snapshot. It handles the validation of whether a position is allowed based on the calculated risk threshold. ```python from core.position_sizer import PositionSizer, PortfolioStateAdapter sizer = PositionSizer() portfolio_adapter = PortfolioStateAdapter(portfolio_state) sizing_result = sizer.calculate( confidence=snapshot.confidence, entropy=snapshot.entropy, portfolio_state=portfolio_adapter, symbol=snapshot.symbol ) if sizing_result.position_allowed: position_size = sizing_result.position_size_usd else: print(f"Position sizing blocked: {sizing_result.reason}") ``` -------------------------------- ### Evaluate Signal Snapshot Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/SIGNAL_SNAPSHOT_ARCHITECTURE.md Example of using the SignalSnapshot object to perform risk assessment and determine whether to enter or skip a trade. ```python def evaluate_signal(snapshot: SignalSnapshot) -> str: """Оценка сигнала на основе snapshot""" if snapshot.risk_level == RiskLevel.HIGH: return "BLOCK" if snapshot.score_pct < 50: return "SKIP" return "ENTER" ``` -------------------------------- ### Integration with PortfolioBrain (Python) Source: https://github.com/samurai-deus/python-bot/blob/main/contracts/POSITION_SIZER_ARCHITECTURE.md Shows how to integrate the PositionSizer with the PortfolioBrain. It outlines the steps to first calculate the portfolio state and then use it with the PositionSizer via an adapter. ```python from core.position_sizer import PositionSizer, PortfolioStateAdapter from core.portfolio_brain import PortfolioState # После портфельного анализа portfolio_state = calculate_portfolio_state(...) adapter = PortfolioStateAdapter(portfolio_state) ``` -------------------------------- ### Module Registry Criticality Check Example Source: https://github.com/samurai-deus/python-bot/blob/main/SYSTEM_ARCHITECTURE_CANONICAL.md Illustrates how to check if a registered module is considered critical using the ModuleRegistry. This check is often used to implement fail-safe behaviors. ```python if module_registry.is_critical("DecisionCore"): # Fail-safe поведение ... ```