Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions IntelliTrader.Rules/Services/RulesService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,11 @@ public IModuleRules GetRules(string module)

public bool CheckConditions(IEnumerable<IRuleCondition> conditions, Dictionary<string, ISignal> 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;
Expand All @@ -47,10 +50,10 @@ public bool CheckConditions(IEnumerable<IRuleCondition> conditions, Dictionary<s
signal = s;
}

if (condition.MinPrice != null && (tradingService.GetPrice(pair) < condition.MinPrice) ||
condition.MaxPrice != null && (tradingService.GetPrice(pair) > 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<ArbitrageMarket> { condition.ArbitrageMarket.Value } : null, condition.ArbitrageType).Percentage < condition.MinArbitrage ||
condition.MaxArbitrage != null && tradingService.Exchange.GetArbitrage(pair, tradingService.Config.Market,
Expand Down
51 changes: 51 additions & 0 deletions IntelliTrader.Rules/test_audit.py
Original file line number Diff line number Diff line change
@@ -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)
27 changes: 27 additions & 0 deletions IntelliTrader.Trading/Models/TrailingSafetyOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;

namespace IntelliTrader.Trading
{
/// <summary>
/// Options for spread-aware trailing safety checks.
/// </summary>
public class TrailingSafetyOptions
{
/// <summary>
/// Gets or sets the maximum allowed spread percentage to continue trailing.
/// If the spread exceeds this value, trailing may be paused or stopped.
/// </summary>
public decimal MaxTrailingSpread { get; set; }

/// <summary>
/// Gets or sets a value indicating whether to pause trailing when spread is high.
/// </summary>
public bool PauseOnHighSpread { get; set; }

/// <summary>
/// Gets or sets the minimum price change percentage required to update trailing stop
/// even if spread is high.
/// </summary>
public decimal MinPriceChangeWithHighSpread { get; set; }
}
}
134 changes: 133 additions & 1 deletion magda_agent_system/agent_tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
},
{
"id": "trading-strategy-audit",
"status": "todo",
"status": "done",
"area": "trading",
"risk": "medium",
"title": "Audit existing trading strategies for potential improvements",
Expand Down Expand Up @@ -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"
]
}
]
}
3 changes: 3 additions & 0 deletions magda_agent_system/backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added magda_agent_system/memory_db/chroma.sqlite3
Binary file not shown.
Binary file added magda_agent_system/metrics_db.sqlite3
Binary file not shown.