```
chore(gitignore): add development log file patterns - Add patterns for .log, .out, and .err files - Add wget-log and download.log patterns - Organize under new "Development Logs" section ```
This commit is contained in:
149
apps/agents/compliance/src/compliance_agent.py
Normal file
149
apps/agents/compliance/src/compliance_agent.py
Normal file
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AITBC Compliance Agent
|
||||
Automated compliance and regulatory monitoring agent
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from typing import Dict, Any, List
|
||||
from datetime import datetime
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add parent directory to path
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
|
||||
|
||||
from apps.agent_services.agent_bridge.src.integration_layer import AgentServiceBridge
|
||||
|
||||
class ComplianceAgent:
|
||||
"""Automated compliance agent"""
|
||||
|
||||
def __init__(self, agent_id: str, config: Dict[str, Any]):
|
||||
self.agent_id = agent_id
|
||||
self.config = config
|
||||
self.bridge = AgentServiceBridge()
|
||||
self.is_running = False
|
||||
self.check_interval = config.get("check_interval", 300) # 5 minutes
|
||||
self.monitored_entities = config.get("monitored_entities", [])
|
||||
|
||||
async def start(self) -> bool:
|
||||
"""Start compliance agent"""
|
||||
try:
|
||||
success = await self.bridge.start_agent(self.agent_id, {
|
||||
"type": "compliance",
|
||||
"capabilities": ["kyc_check", "aml_screening", "regulatory_reporting"],
|
||||
"endpoint": f"http://localhost:8006"
|
||||
})
|
||||
|
||||
if success:
|
||||
self.is_running = True
|
||||
print(f"Compliance agent {self.agent_id} started successfully")
|
||||
return True
|
||||
else:
|
||||
print(f"Failed to start compliance agent {self.agent_id}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Error starting compliance agent: {e}")
|
||||
return False
|
||||
|
||||
async def stop(self) -> bool:
|
||||
"""Stop compliance agent"""
|
||||
self.is_running = False
|
||||
success = await self.bridge.stop_agent(self.agent_id)
|
||||
if success:
|
||||
print(f"Compliance agent {self.agent_id} stopped successfully")
|
||||
return success
|
||||
|
||||
async def run_compliance_loop(self):
|
||||
"""Main compliance monitoring loop"""
|
||||
while self.is_running:
|
||||
try:
|
||||
for entity in self.monitored_entities:
|
||||
await self._perform_compliance_check(entity)
|
||||
|
||||
await asyncio.sleep(self.check_interval)
|
||||
except Exception as e:
|
||||
print(f"Error in compliance loop: {e}")
|
||||
await asyncio.sleep(30) # Wait before retrying
|
||||
|
||||
async def _perform_compliance_check(self, entity_id: str) -> None:
|
||||
"""Perform compliance check for entity"""
|
||||
try:
|
||||
compliance_task = {
|
||||
"type": "compliance_check",
|
||||
"user_id": entity_id,
|
||||
"check_type": "full",
|
||||
"monitored_activities": ["trading", "transfers", "wallet_creation"]
|
||||
}
|
||||
|
||||
result = await self.bridge.execute_agent_task(self.agent_id, compliance_task)
|
||||
|
||||
if result.get("status") == "success":
|
||||
compliance_result = result["result"]
|
||||
await self._handle_compliance_result(entity_id, compliance_result)
|
||||
else:
|
||||
print(f"Compliance check failed for {entity_id}: {result}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error performing compliance check for {entity_id}: {e}")
|
||||
|
||||
async def _handle_compliance_result(self, entity_id: str, result: Dict[str, Any]) -> None:
|
||||
"""Handle compliance check result"""
|
||||
status = result.get("status", "unknown")
|
||||
|
||||
if status == "passed":
|
||||
print(f"✅ Compliance check passed for {entity_id}")
|
||||
elif status == "failed":
|
||||
print(f"❌ Compliance check failed for {entity_id}")
|
||||
# Trigger alert or further investigation
|
||||
await self._trigger_compliance_alert(entity_id, result)
|
||||
else:
|
||||
print(f"⚠️ Compliance check inconclusive for {entity_id}")
|
||||
|
||||
async def _trigger_compliance_alert(self, entity_id: str, result: Dict[str, Any]) -> None:
|
||||
"""Trigger compliance alert"""
|
||||
alert_data = {
|
||||
"entity_id": entity_id,
|
||||
"alert_type": "compliance_failure",
|
||||
"severity": "high",
|
||||
"details": result,
|
||||
"timestamp": datetime.utcnow().isoformat()
|
||||
}
|
||||
|
||||
# In a real implementation, this would send to alert system
|
||||
print(f"🚨 COMPLIANCE ALERT: {json.dumps(alert_data, indent=2)}")
|
||||
|
||||
async def get_status(self) -> Dict[str, Any]:
|
||||
"""Get agent status"""
|
||||
status = await self.bridge.get_agent_status(self.agent_id)
|
||||
status["monitored_entities"] = len(self.monitored_entities)
|
||||
status["check_interval"] = self.check_interval
|
||||
return status
|
||||
|
||||
# Main execution
|
||||
async def main():
|
||||
"""Main compliance agent execution"""
|
||||
agent_id = "compliance-agent-001"
|
||||
config = {
|
||||
"check_interval": 60, # 1 minute for testing
|
||||
"monitored_entities": ["user001", "user002", "user003"]
|
||||
}
|
||||
|
||||
agent = ComplianceAgent(agent_id, config)
|
||||
|
||||
# Start agent
|
||||
if await agent.start():
|
||||
try:
|
||||
# Run compliance loop
|
||||
await agent.run_compliance_loop()
|
||||
except KeyboardInterrupt:
|
||||
print("Shutting down compliance agent...")
|
||||
finally:
|
||||
await agent.stop()
|
||||
else:
|
||||
print("Failed to start compliance agent")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
166
apps/agents/trading/src/trading_agent.py
Normal file
166
apps/agents/trading/src/trading_agent.py
Normal file
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AITBC Trading Agent
|
||||
Automated trading agent for AITBC marketplace
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from typing import Dict, Any, List
|
||||
from datetime import datetime
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add parent directory to path
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
|
||||
|
||||
from apps.agent_services.agent_bridge.src.integration_layer import AgentServiceBridge
|
||||
|
||||
class TradingAgent:
|
||||
"""Automated trading agent"""
|
||||
|
||||
def __init__(self, agent_id: str, config: Dict[str, Any]):
|
||||
self.agent_id = agent_id
|
||||
self.config = config
|
||||
self.bridge = AgentServiceBridge()
|
||||
self.is_running = False
|
||||
self.trading_strategy = config.get("strategy", "basic")
|
||||
self.symbols = config.get("symbols", ["AITBC/BTC"])
|
||||
self.trade_interval = config.get("trade_interval", 60) # seconds
|
||||
|
||||
async def start(self) -> bool:
|
||||
"""Start trading agent"""
|
||||
try:
|
||||
# Register with service bridge
|
||||
success = await self.bridge.start_agent(self.agent_id, {
|
||||
"type": "trading",
|
||||
"capabilities": ["market_analysis", "trading", "risk_management"],
|
||||
"endpoint": f"http://localhost:8005"
|
||||
})
|
||||
|
||||
if success:
|
||||
self.is_running = True
|
||||
print(f"Trading agent {self.agent_id} started successfully")
|
||||
return True
|
||||
else:
|
||||
print(f"Failed to start trading agent {self.agent_id}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Error starting trading agent: {e}")
|
||||
return False
|
||||
|
||||
async def stop(self) -> bool:
|
||||
"""Stop trading agent"""
|
||||
self.is_running = False
|
||||
success = await self.bridge.stop_agent(self.agent_id)
|
||||
if success:
|
||||
print(f"Trading agent {self.agent_id} stopped successfully")
|
||||
return success
|
||||
|
||||
async def run_trading_loop(self):
|
||||
"""Main trading loop"""
|
||||
while self.is_running:
|
||||
try:
|
||||
for symbol in self.symbols:
|
||||
await self._analyze_and_trade(symbol)
|
||||
|
||||
await asyncio.sleep(self.trade_interval)
|
||||
except Exception as e:
|
||||
print(f"Error in trading loop: {e}")
|
||||
await asyncio.sleep(10) # Wait before retrying
|
||||
|
||||
async def _analyze_and_trade(self, symbol: str) -> None:
|
||||
"""Analyze market and execute trades"""
|
||||
try:
|
||||
# Perform market analysis
|
||||
analysis_task = {
|
||||
"type": "market_analysis",
|
||||
"symbol": symbol,
|
||||
"strategy": self.trading_strategy
|
||||
}
|
||||
|
||||
analysis_result = await self.bridge.execute_agent_task(self.agent_id, analysis_task)
|
||||
|
||||
if analysis_result.get("status") == "success":
|
||||
analysis = analysis_result["result"]["analysis"]
|
||||
|
||||
# Make trading decision
|
||||
if self._should_trade(analysis):
|
||||
await self._execute_trade(symbol, analysis)
|
||||
else:
|
||||
print(f"Market analysis failed for {symbol}: {analysis_result}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in analyze_and_trade for {symbol}: {e}")
|
||||
|
||||
def _should_trade(self, analysis: Dict[str, Any]) -> bool:
|
||||
"""Determine if should execute trade"""
|
||||
recommendation = analysis.get("recommendation", "hold")
|
||||
return recommendation in ["buy", "sell"]
|
||||
|
||||
async def _execute_trade(self, symbol: str, analysis: Dict[str, Any]) -> None:
|
||||
"""Execute trade based on analysis"""
|
||||
try:
|
||||
recommendation = analysis.get("recommendation", "hold")
|
||||
|
||||
if recommendation == "buy":
|
||||
trade_task = {
|
||||
"type": "trading",
|
||||
"symbol": symbol,
|
||||
"side": "buy",
|
||||
"amount": self.config.get("trade_amount", 0.1),
|
||||
"strategy": self.trading_strategy
|
||||
}
|
||||
elif recommendation == "sell":
|
||||
trade_task = {
|
||||
"type": "trading",
|
||||
"symbol": symbol,
|
||||
"side": "sell",
|
||||
"amount": self.config.get("trade_amount", 0.1),
|
||||
"strategy": self.trading_strategy
|
||||
}
|
||||
else:
|
||||
return
|
||||
|
||||
trade_result = await self.bridge.execute_agent_task(self.agent_id, trade_task)
|
||||
|
||||
if trade_result.get("status") == "success":
|
||||
print(f"Trade executed successfully: {trade_result}")
|
||||
else:
|
||||
print(f"Trade execution failed: {trade_result}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error executing trade: {e}")
|
||||
|
||||
async def get_status(self) -> Dict[str, Any]:
|
||||
"""Get agent status"""
|
||||
return await self.bridge.get_agent_status(self.agent_id)
|
||||
|
||||
# Main execution
|
||||
async def main():
|
||||
"""Main trading agent execution"""
|
||||
agent_id = "trading-agent-001"
|
||||
config = {
|
||||
"strategy": "basic",
|
||||
"symbols": ["AITBC/BTC"],
|
||||
"trade_interval": 30,
|
||||
"trade_amount": 0.1
|
||||
}
|
||||
|
||||
agent = TradingAgent(agent_id, config)
|
||||
|
||||
# Start agent
|
||||
if await agent.start():
|
||||
try:
|
||||
# Run trading loop
|
||||
await agent.run_trading_loop()
|
||||
except KeyboardInterrupt:
|
||||
print("Shutting down trading agent...")
|
||||
finally:
|
||||
await agent.stop()
|
||||
else:
|
||||
print("Failed to start trading agent")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user