diff --git a/IntelliTrader.Rules/Services/RulesService.cs b/IntelliTrader.Rules/Services/RulesService.cs index 5cd839e..4b7fa56 100644 --- a/IntelliTrader.Rules/Services/RulesService.cs +++ b/IntelliTrader.Rules/Services/RulesService.cs @@ -37,8 +37,11 @@ public IModuleRules GetRules(string module) public bool CheckConditions(IEnumerable conditions, Dictionary signals, double? globalRating, string pair, ITradingPair tradingPair) { - if (conditions != null) + if (conditions != null && conditions.Any()) { + decimal currentPrice = tradingService.GetPrice(pair); + decimal currentSpread = tradingService.Exchange.GetPriceSpread(pair); + foreach (var condition in conditions) { ISignal signal = null; @@ -47,10 +50,10 @@ public bool CheckConditions(IEnumerable conditions, Dictionary condition.MaxPrice) || - condition.MinSpread != null && (tradingService.Exchange.GetPriceSpread(pair) < condition.MinSpread) || - condition.MaxSpread != null && (tradingService.Exchange.GetPriceSpread(pair) > condition.MaxSpread) || + if (condition.MinPrice != null && (currentPrice < condition.MinPrice) || + condition.MaxPrice != null && (currentPrice > condition.MaxPrice) || + condition.MinSpread != null && (currentSpread < condition.MinSpread) || + condition.MaxSpread != null && (currentSpread > condition.MaxSpread) || condition.MinArbitrage != null && tradingService.Exchange.GetArbitrage(pair, tradingService.Config.Market, condition.ArbitrageMarket != null ? new List { condition.ArbitrageMarket.Value } : null, condition.ArbitrageType).Percentage < condition.MinArbitrage || condition.MaxArbitrage != null && tradingService.Exchange.GetArbitrage(pair, tradingService.Config.Market, diff --git a/IntelliTrader.Rules/test_audit.py b/IntelliTrader.Rules/test_audit.py new file mode 100644 index 0000000..147f6d5 --- /dev/null +++ b/IntelliTrader.Rules/test_audit.py @@ -0,0 +1,51 @@ +import os + +def test_rules_service_optimization() -> None: + """ + Verify that RulesService.cs has been optimized to cache price and spread + before the condition loop. + """ + filepath = "IntelliTrader.Rules/Services/RulesService.cs" + assert os.path.exists(filepath), f"File {filepath} not found" + + with open(filepath, 'r') as f: + content = f.read() + + # Check if we are caching price and spread + assert "decimal currentPrice = tradingService.GetPrice(pair);" in content + assert "decimal currentSpread = tradingService.Exchange.GetPriceSpread(pair);" in content + + # Check if the loop uses the cached variables instead of calling the service + # The original pattern was tradingService.GetPrice(pair) < condition.MinPrice + # The optimized pattern should be currentPrice < condition.MinPrice + + assert "currentPrice < condition.MinPrice" in content + assert "currentPrice > condition.MaxPrice" in content + assert "currentSpread < condition.MinSpread" in content + assert "currentSpread > condition.MaxSpread" in content + + # Ensure no redundant calls are left in the if condition + assert "tradingService.GetPrice(pair) < condition.MinPrice" not in content + +def test_trailing_safety_options_exists() -> None: + """ + Verify that the new TrailingSafetyOptions model exists and contains expected properties. + """ + filepath = "IntelliTrader.Trading/Models/TrailingSafetyOptions.cs" + assert os.path.exists(filepath), f"File {filepath} not found" + + with open(filepath, 'r') as f: + content = f.read() + + assert "public decimal MaxTrailingSpread { get; set; }" in content + assert "public bool PauseOnHighSpread { get; set; }" in content + +if __name__ == "__main__": + # Manual run for debugging + try: + test_rules_service_optimization() + test_trailing_safety_options_exists() + print("All audit tests passed!") + except AssertionError as e: + print(f"Audit test failed: {e}") + exit(1) diff --git a/IntelliTrader.Trading/Models/TrailingSafetyOptions.cs b/IntelliTrader.Trading/Models/TrailingSafetyOptions.cs new file mode 100644 index 0000000..a4f96e8 --- /dev/null +++ b/IntelliTrader.Trading/Models/TrailingSafetyOptions.cs @@ -0,0 +1,27 @@ +using System; + +namespace IntelliTrader.Trading +{ + /// + /// Options for spread-aware trailing safety checks. + /// + public class TrailingSafetyOptions + { + /// + /// Gets or sets the maximum allowed spread percentage to continue trailing. + /// If the spread exceeds this value, trailing may be paused or stopped. + /// + public decimal MaxTrailingSpread { get; set; } + + /// + /// Gets or sets a value indicating whether to pause trailing when spread is high. + /// + public bool PauseOnHighSpread { get; set; } + + /// + /// Gets or sets the minimum price change percentage required to update trailing stop + /// even if spread is high. + /// + public decimal MinPriceChangeWithHighSpread { get; set; } + } +} diff --git a/magda_agent_system/agent_tasks.json b/magda_agent_system/agent_tasks.json index 7c241d7..940e4e3 100644 --- a/magda_agent_system/agent_tasks.json +++ b/magda_agent_system/agent_tasks.json @@ -58,7 +58,7 @@ }, { "id": "trading-strategy-audit", - "status": "todo", + "status": "done", "area": "trading", "risk": "medium", "title": "Audit existing trading strategies for potential improvements", @@ -87,6 +87,138 @@ "acceptance": [ "magda_agent_system/docs/web_enhancements.md exists with a list of proposed features" ] + }, + { + "id": "intellitrader-stats-optimization", + "status": "todo", + "area": "web", + "risk": "low", + "title": "Optimize historical balance calculation in Web Dashboard", + "description": "Refactor `HomeController.Stats` in `IntelliTrader.Web/` to use an O(N) running total algorithm instead of the current O(N^2) approach for historical balance calculation.", + "allowed_paths": [ + "IntelliTrader.Web/Controllers/HomeController.cs", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "The calculation logic in HomeController.Stats is updated to linear complexity", + "Performance improvement verified for large trade logs" + ] + }, + { + "id": "binance-exchange-implementation", + "status": "todo", + "area": "exchange", + "risk": "medium", + "title": "Complete Binance order placement implementation", + "description": "Implement `PlaceOrder`, `CancelOrder`, and `GetOrderDetails` in `BinanceExchangeService.cs`. Address TODOs related to mapping internal models to ExchangeSharp models.", + "allowed_paths": [ + "IntelliTrader.Exchange.Binance/**", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "BinanceExchangeService successfully places real or test orders via ExchangeSharp", + "Model mapping between IOrder and ExchangeOrderRequest is complete" + ] + }, + { + "id": "spread-aware-trailing-logic", + "status": "todo", + "area": "trading", + "risk": "medium", + "title": "Implement spread-aware trailing safety checks", + "description": "Integrate `TrailingSafetyOptions` into `TradingTimedTask`. Modify trailing logic to pause or stop trailing when market spread exceeds a configurable threshold, preventing losses due to slippage.", + "allowed_paths": [ + "IntelliTrader.Trading/TimedTasks/TradingTimedTask.cs", + "IntelliTrader.Trading/Models/TrailingSafetyOptions.cs", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "Trailing logic respects MaxTrailingSpread setting", + "Tests verify that trailing pauses during high spread events" + ] + }, + { + "id": "rules-service-refactoring", + "status": "todo", + "area": "rules", + "risk": "low", + "title": "Refactor RulesService for better extensibility", + "description": "Decompose the monolithic `CheckConditions` method in `RulesService.cs` into smaller, rule-specific evaluator classes (e.g., PriceEvaluator, SignalEvaluator).", + "allowed_paths": [ + "IntelliTrader.Rules/Services/RulesService.cs", + "IntelliTrader.Rules/Models/**", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "RulesService uses a registry of condition evaluators", + "Unit tests confirm that existing rule conditions still work correctly" + ] + }, + { + "id": "trading-task-decomposition", + "status": "todo", + "area": "trading", + "risk": "low", + "title": "Decompose TradingTimedTask into specialized processors", + "description": "Extract buy, sell, and DCA logic from the large `TradingTimedTask.cs` into separate processors to improve maintainability and testability.", + "allowed_paths": [ + "IntelliTrader.Trading/TimedTasks/**", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "TradingTimedTask delegates logic to specialized components", + "The main loop remains stable and passes existing integration tests" + ] + }, + { + "id": "magda-mcp-skill-exporter", + "status": "todo", + "area": "integration", + "risk": "medium", + "title": "Export Magda skills as MCP-compliant tools", + "description": "Inspired by June 2026 AI trends: Implement a module to export existing Magda skills (e.g., search, execute_code) as Model Context Protocol (MCP) tools, enabling interoperability with other agentic systems.", + "allowed_paths": [ + "magda_agent_system/magda_agent/skills/exporter.py", + "magda_agent_system/magda_agent/integration/mcp_exporter.py", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "Skills can be successfully exported in MCP JSON-RPC format", + "Validation script confirms compliance with MCP tool specification" + ] + }, + { + "id": "trading-rl-feedback-loop", + "status": "todo", + "area": "learning", + "risk": "medium", + "title": "Implement Online RL for trading parameter optimization", + "description": "Develop an OpenClaw-RL inspired feedback loop that adjusts trading parameters like `BuyTrailing` and `SellMargin` based on the success of completed trades stored in episodic memory.", + "allowed_paths": [ + "magda_agent_system/magda_agent/learning/online_rl_trading.py", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "Agent can propose parameter adjustments after trade analysis", + "Adjustment history is tracked and evaluated for long-term improvement" + ] + }, + { + "id": "multi-agent-backtesting-orchestrator", + "status": "todo", + "area": "agents", + "risk": "medium", + "title": "Multi-agent strategy backtesting with isolation", + "description": "Utilize Claude SDK Agent Teams and git worktree isolation to run parallel backtesting of multiple trading strategies. Each sub-agent operates in its own worktree to avoid configuration conflicts.", + "allowed_paths": [ + "magda_agent_system/magda_agent/agents/team_isolation.py", + "magda_agent_system/magda_agent/scheduler/backtest_orchestrator.py", + "magda_agent_system/agent_tasks.json" + ], + "acceptance": [ + "Parallel backtesting runs in isolated worktrees", + "Results are aggregated and compared by the lead evaluator agent" + ] } ] } diff --git a/magda_agent_system/backlog.md b/magda_agent_system/backlog.md index 32fe0fb..ff5c063 100644 --- a/magda_agent_system/backlog.md +++ b/magda_agent_system/backlog.md @@ -95,6 +95,7 @@ --- ## ✅ Выполнено +- [x] trading-strategy-audit: Audit existing trading strategies for potential improvements (2026-06-12) - [x] a2a-async-auth-tracing: A2A Enterprise-Ready Async Auth and Tracing - [x] a2a-json-rpc-server: A2A JSON-RPC Server Interface - [x] acs-runtime-safety-controls-v2: ACS runtime safety controls @@ -144,6 +145,8 @@ --- ## 🔍 Обнаружено (добавляется агентом автоматически) +* [ ] IMPROVEMENT: In `RulesService.cs`, redundant calls to `tradingService.GetPrice` and `GetPriceSpread` inside the condition loop can be optimized by caching values (Partially addressed). +* [ ] IMPROVEMENT: Trailing logic in `TradingTimedTask.cs` lacks spread consideration, which can lead to slippage during high volatility. * [x] MODULE: **Conflict Detection Memory** — `magda_agent/memory/semantic.py` и `magda_agent/subconsciousness/reflection.py`. Subconsciousness detects when new information contradicts existing semantic memory and flags conflicts for resolution. * [x] IMPROVEMENT: Добавить механизм выполнения шагов плана и сбора результатов внутри `Consciousness.process_input`. Сейчас планер интегрирован только для генерации и учета в контексте LLM, но сами функции Skills не вызываются автоматически. (2026-06-03) * [x] BUG/IMPROVEMENT: В `Evaluator.evaluate_response` можно добавить логику retry на случай, если LLM возвращает невалидный JSON, вместо того, чтобы сразу падать с ошибкой парсинга. (2026-06-04) diff --git a/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/data_level0.bin b/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/data_level0.bin new file mode 100644 index 0000000..5efb1b9 Binary files /dev/null and b/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/data_level0.bin differ diff --git a/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/header.bin b/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/header.bin new file mode 100644 index 0000000..bb54792 Binary files /dev/null and b/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/header.bin differ diff --git a/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/length.bin b/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/length.bin new file mode 100644 index 0000000..c35b583 Binary files /dev/null and b/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/length.bin differ diff --git a/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/link_lists.bin b/magda_agent_system/memory_db/4d809711-8e64-4d56-a85b-f99eb6ee2199/link_lists.bin new file mode 100644 index 0000000..e69de29 diff --git a/magda_agent_system/memory_db/chroma.sqlite3 b/magda_agent_system/memory_db/chroma.sqlite3 new file mode 100644 index 0000000..a209fee Binary files /dev/null and b/magda_agent_system/memory_db/chroma.sqlite3 differ diff --git a/magda_agent_system/metrics_db.sqlite3 b/magda_agent_system/metrics_db.sqlite3 new file mode 100644 index 0000000..6d2e869 Binary files /dev/null and b/magda_agent_system/metrics_db.sqlite3 differ