
Agent
RugOracl
About this agent
RugOracl
Trading Prediction Agent
A powerful multi-agent trading analysis system with CR-CA (Causal Reasoning - Causal Analysis) style reasoning, live market data integration, and comprehensive risk management.
Table of Contents
- What is Trading Prediction Agent?
- Core Concepts
- Installation
- Quick Start
- Detailed Usage Guide
- Building Your Own Trading System
- API Reference
- Market Data Integration
- Architecture Deep Dive
- Best Practices
- Troubleshooting
What is Trading Prediction Agent?
Trading Prediction Agent is a sophisticated multi-agent AI system for comprehensive market analysis and trading decisions. It combines specialized AI agents with live market data from DexScreener to provide actionable trading insights with causal reasoning.
Why Trading Prediction Agent?
Traditional trading analysis faces several challenges:
| Challenge | Trading Prediction Agent Solution |
|---|---|
| Single-perspective bias | Multi-agent analysis — technical, sentiment, risk, and intelligence perspectives |
| Lack of causal reasoning | CR-CA framework — explicit drivers, mechanisms, and counterfactuals |
| Stale market data | Live DexScreener integration — real-time price, liquidity, and volume data |
| Unclear risk assessment | Dedicated risk agent — conservative sizing, stop placement, black swan scenarios |
| Incomplete analysis | Synthesized recommendations — aggregated insights with clear entry/exit levels |
Use Cases
- Trading Signal Generation — Get multi-perspective entry/exit recommendations
- Portfolio Risk Assessment — Monitor correlations, exposure, and hedge opportunities
- Market Narrative Tracking — Identify and rank dominant trends and rotation opportunities
- Strategy Backtesting — Evaluate trading strategies with causal analysis
- Asset Comparison — Rank multiple opportunities by risk-adjusted returns
- Sentiment Analysis — Quantify market sentiment with catalyst identification
Core Concepts
Multi-Agent Architecture
The system employs four specialized agents working in concert:
PYTHON@dataclass class AgentSystem: technical_agent: Agent # Chart analysis, support/resistance, entries sentiment_agent: Agent # Social sentiment, catalysts, narratives risk_agent: Agent # Position sizing, stops, risk metrics intelligence_agent: Agent # Order flow, liquidity, market context crca_agent: CRCAAGENT # Causal reasoning and counterfactuals
Agent Specializations
Each agent has a unique focus and expertise:
| Agent | Primary Function | Key Outputs |
|---|---|---|
| Technical Analyst | Chart patterns, indicators, price action | Entry zones, targets, stop-loss levels, invalidation points |
| Sentiment Analyst | Social metrics, news, narrative strength | Sentiment scores, catalysts, sentiment flip scenarios |
| Risk Manager | Position sizing, risk metrics, tail events | Risk scores, position size, stop placement, black swans |
| Market Intelligence | Liquidity, order flow, competitive analysis | Liquidity assessment, narrative rotation, relative strength |
| CRCA Analyst | Causal graphs, counterfactuals, interventions | Causal variables, relationships, high-impact scenarios |
CR-CA Causal Reasoning
The system uses Causal Reasoning - Causal Analysis (CR-CA) methodology:
CR-CA Framework:
1. Identify causal variables (drivers)
2. Map causal relationships (mechanisms)
3. Generate counterfactual scenarios (what-if analysis)
4. Highlight high-impact interventions
This provides:
- Drivers — What's causing price movement
- Mechanisms — How drivers create outcomes
- Counterfactuals — What would change the outcome
- Interventions — Actions that could shift the trade setup
DexScreener Integration
Live market data enriches analysis:
PYTHON@dataclass class DexScreenerPairSnapshot: chain_id: str # Blockchain (ethereum, solana, etc.) dex_id: str # Exchange (uniswap, raydium, etc.) pair_address: str # Smart contract address base_symbol: str # Token being traded quote_symbol: str # Quote currency price_usd: str # Current USD price liquidity_usd: float # Total liquidity volume_24h: float # 24-hour volume url: str # DexScreener page URL
Installation
Requirements
- Python 3.9+
- OpenAI API key
- Internet connection (for DexScreener data)
Install Dependencies
BASHpip install -r requirements.txt
Or install manually:
BASHpip install swarms loguru requests python-dotenv
Optional: CRCA Agent
If using the advanced CRCA causal analysis:
BASHpip install crca
Environment Setup
Create a .env file:
ENVOPENAI_API_KEY=your-openai-api-key-here
Or set environment variable:
BASH# Windows set OPENAI_API_KEY=your-api-key-here # Linux/Mac export OPENAI_API_KEY=your-api-key-here
Quick Start
Minimal Example
PYTHONfrom trading_prediction_agent import TradingPredictionAgent # Initialize the system agent = TradingPredictionAgent() # Analyze a trading pair analysis = agent.analyze_market( symbol="BTC/USDT", timeframe="4h", depth="comprehensive" ) # Get the final recommendation print(analysis['final_recommendation'])
Run the Demo
BASHpython trading_prediction_agent.py
This demonstrates:
- BTC/USDT comprehensive analysis
- Multi-asset comparison (5 pairs)
- Portfolio monitoring with alerts
- Market narratives identification
Detailed Usage Guide
1. Initializing the Agent
PYTHONfrom trading_prediction_agent import TradingPredictionAgent agent = TradingPredictionAgent( api_key="your-openai-key", # Optional if in env )
The agent automatically:
- Loads environment variables from
.env - Initializes all specialized agents
- Configures the DexScreener client
- Sets up the CRCA causal analyzer
2. Market Analysis
Comprehensive Analysis
Run a full multi-agent analysis with all perspectives:
PYTHONanalysis = agent.analyze_market( symbol="ETH/USDT", timeframe="1h", # 1m, 5m, 15m, 1h, 4h, 1d, 1w depth="comprehensive", # quick, standard, comprehensive market_data=None, # Optional external data override ) # Result structure { "symbol": "ETH/USDT", "timeframe": "1h", "timestamp": "2026-01-24T12:00:00Z", "depth": "comprehensive", "dexscreener_snapshot": {...}, "causal_analysis": "...", "technical_analysis": "...", "sentiment_analysis": "...", "market_intelligence": "...", "risk_assessment": "...", "final_recommendation": "..." }
Quick Analysis
For faster results with reduced depth:
PYTHONanalysis = agent.analyze_market( symbol="SOL/USDT", timeframe="15m", depth="quick", )
With Custom Market Data
Override live data with your own:
PYTHONcustom_data = { "price": 45.67, "volume_24h": 1250000, "rsi": 58.3, "macd": "bullish", } analysis = agent.analyze_market( symbol="AVAX/USDT", market_data=custom_data, )
3. Asset Comparison
Compare multiple assets and rank opportunities:
PYTHONcomparison = agent.compare_assets( symbols=[ "BTC/USDT", "ETH/USDT", "SOL/USDT", "LINK/USDT", "AVAX/USDT" ], criteria="risk-adjusted-returns" # or "momentum", "technical-quality" ) # Result { "symbols": ["BTC/USDT", ...], "criteria": "risk-adjusted-returns", "timestamp": "2026-01-24T12:00:00Z", "comparison": "Ranked analysis with scores..." }
The comparison provides:
- Technical setup quality (0-100)
- Sentiment score (0-100)
- Risk-reward ratio
- Momentum strength
- Overall opportunity score
- Ranking from best to worst
4. Strategy Backtesting
Backtest trading strategies using LLM-based reasoning:
PYTHONbacktest = agent.backtest_strategy( symbol="BTC/USDT", strategy="Buy when RSI < 30, sell when RSI > 70", period="30d" ) # Result { "symbol": "BTC/USDT", "strategy": "Buy when RSI < 30...", "period": "30d", "timestamp": "2026-01-24T12:00:00Z", "results": "Backtest analysis with win rate, drawdown, optimization..." }
The backtest analyzes:
- Historical performance during the period
- Win rate and average risk-reward
- Maximum drawdown
- Optimal parameters
- Current applicability
- Invalidation scenarios under different regimes
5. Portfolio Monitoring
Monitor portfolio health and identify risks:
PYTHONportfolio_analysis = agent.monitor_portfolio( portfolio={ "BTC/USDT": 40000, # Position size in USD "ETH/USDT": 25000, "SOL/USDT": 15000, "LINK/USDT": 10000, "AVAX/USDT": 10000, }, alerts={ "max_drawdown": 15, # Alert if drawdown > 15% "correlation_threshold": 0.8, # Alert if correlation > 0.8 } ) # Result { "portfolio": {...}, "timestamp": "2026-01-24T12:00:00Z", "analysis": "Portfolio health analysis..." }
The analysis provides:
- Overall portfolio health score
- Correlation and diversification analysis
- Exposure risks (sector, narrative, systemic)
- Rebalancing recommendations
- Hedging opportunities
- Alert status and required actions
6. Market Narratives
Identify dominant trends and rotation opportunities:
PYTHONnarratives = agent.get_market_narratives( focus="crypto" # or "stocks", "forex" ) # Result { "focus": "crypto", "timestamp": "2026-01-24T12:00:00Z", "narratives": "Narrative analysis..." }
The narrative analysis includes:
- Top 5 dominant narratives with momentum
- Emerging trends gaining traction
- Fading narratives losing steam
- Leading projects/assets in each narrative
- Rotation opportunities
- Timeline and sustainability assessments
7. Analysis History
Access recent analysis history:
PYTHON# Get last 5 analyses recent = agent.get_history(limit=5) for analysis in recent: print(f"{analysis['symbol']} - {analysis['timestamp']}") print(f"Recommendation: {analysis['final_recommendation'][:100]}...")
Building Your Own Trading System
Trading Prediction Agent is designed as a template you can extend and customize for your specific trading needs.
Step 1: Customize Agent Prompts
Override the agent creation to add your trading style:
PYTHONclass CustomTradingAgent(TradingPredictionAgent): """Your customized trading system.""" def _create_agents(self) -> None: """Create specialized trading agents with custom prompts.""" self.technical_agent = Agent( agent_name="Technical-Analyst", model=self.model, max_loops=1, autosave=True, verbose=True, system_prompt=( "You are an elite technical analysis expert specializing in " "cryptocurrency markets.\n\n" "TRADING STYLE: Swing trading with 3-7 day holding periods.\n" "PREFERRED INDICATORS: RSI, MACD, Bollinger Bands, Volume Profile.\n" "RISK TOLERANCE: Conservative - prioritize capital preservation.\n\n" "Provide precise entry zones, targets, and stop-loss levels with " "confluence. Use CR-CA style causal reasoning to explain why the " "setup holds or fails. Always include invalidation levels." ), dynamic_temperature_enabled=True, ) # ... customize other agents similarly
Step 2: Add Custom Analysis Methods
Implement domain-specific analysis workflows:
PYTHONclass CustomTradingAgent(TradingPredictionAgent): """Your customized trading system.""" def analyze_breakout_setup( self, symbol: str, resistance_level: float, volume_threshold: float = 1.5, ) -> Dict[str, Any]: """ Specialized analysis for breakout trading setups. Args: symbol: Trading pair resistance_level: Key resistance to break volume_threshold: Volume multiplier for confirmation (default 1.5x) Returns: Breakout-specific analysis """ context = ( f"Analyze {symbol} for a potential breakout setup.\n\n" f"KEY RESISTANCE: ${resistance_level}\n" f"VOLUME THRESHOLD: {volume_threshold}x average\n\n" "Determine:\n" "1. Probability of breakout (0-100%)\n" "2. Ideal entry point (on breakout confirmation)\n" "3. Stop-loss placement (below breakout level)\n" "4. Target zones (measured move + extension)\n" "5. Volume confirmation signals\n" "6. False breakout risks and mitigation\n" "7. Timeframe for setup to play out\n\n" "Use causal reasoning to explain what would confirm or invalidate " "the breakout." ) analysis = self.technical_agent.run(context) return { "symbol": symbol, "setup_type": "breakout", "resistance_level": resistance_level, "volume_threshold": volume_threshold, "analysis": analysis, "timestamp": datetime.now(timezone.utc).isoformat(), } def scan_for_divergences( self, symbols: List[str], timeframe: str = "4h", ) -> Dict[str, Any]: """ Scan multiple symbols for RSI/price divergences. Args: symbols: List of trading pairs to scan timeframe: Chart timeframe Returns: Divergence opportunities ranked by strength """ scan_task = ( f"Scan these symbols for bullish/bearish divergences:\n" f"SYMBOLS: {', '.join(symbols)}\n" f"TIMEFRAME: {timeframe}\n\n" "For each symbol, identify:\n" "1. Type of divergence (regular bullish, hidden bullish, etc.)\n" "2. Divergence strength (weak, moderate, strong)\n" "3. Additional confluence factors\n" "4. Estimated probability of reversal\n" "5. Suggested entry and stop levels\n\n" "Rank all divergences by quality and probability." ) results = self.technical_agent.run(scan_task) return { "symbols": symbols, "timeframe": timeframe, "scan_type": "divergence", "results": results, "timestamp": datetime.now(timezone.utc).isoformat(), }
Step 3: Add Custom Data Sources
Integrate additional market data providers:
PYTHONclass EnhancedTradingAgent(TradingPredictionAgent): """Trading agent with multiple data sources.""" def __init__(self, api_key: Optional[str] = None) -> None: super().__init__(api_key) # Add custom data clients self.binance_client = BinanceClient() # Your implementation self.coingecko_client = CoinGeckoClient() # Your implementation def _fetch_enhanced_data(self, symbol: str) -> Dict[str, Any]: """Fetch data from multiple sources.""" # DexScreener data (already available) dex_data = self._fetch_dex_snapshot(symbol) # Binance order book and trades try: binance_data = self.binance_client.get_order_book(symbol) except Exception as e: logger.warning(f"Binance data unavailable: {e}") binance_data = None # CoinGecko market metrics try: coingecko_data = self.coingecko_client.get_market_data(symbol) except Exception as e: logger.warning(f"CoinGecko data unavailable: {e}") coingecko_data = None return { "dexscreener": dex_data, "binance": binance_data, "coingecko": coingecko_data, } def analyze_market( self, symbol: str, timeframe: str = "4h", depth: str = "comprehensive", market_data: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Enhanced analysis with multiple data sources.""" # Fetch from all sources enhanced_data = self._fetch_enhanced_data(symbol) # Merge with any provided data if market_data: enhanced_data.update(market_data) # Run standard analysis with enhanced data return super().analyze_market( symbol=symbol, timeframe=timeframe, depth=depth, market_data=enhanced_data, )
Step 4: Implement Trading Workflows
Create multi-stage trading workflows:
PYTHONclass WorkflowTradingAgent(TradingPredictionAgent): """Trading agent with structured workflows.""" def execute_trade_workflow( self, symbol: str, position_size_usd: float, ) -> Dict[str, Any]: """ Complete trade workflow: analysis → decision → execution plan. Args: symbol: Trading pair position_size_usd: Intended position size Returns: Complete workflow results """ workflow = {} # Stage 1: Multi-agent analysis logger.info(f"Stage 1: Analyzing {symbol}") workflow['analysis'] = self.analyze_market( symbol=symbol, timeframe="4h", depth="comprehensive", ) # Stage 2: Risk validation logger.info("Stage 2: Risk validation") risk_check = self._validate_position_risk( analysis=workflow['analysis'], position_size=position_size_usd, ) workflow['risk_check'] = risk_check if not risk_check['approved']: workflow['decision'] = "REJECTED" workflow['reason'] = risk_check['reason'] return workflow # Stage 3: Generate execution plan logger.info("Stage 3: Generating execution plan") workflow['execution_plan'] = self._generate_execution_plan( analysis=workflow['analysis'], position_size=position_size_usd, ) workflow['decision'] = "APPROVED" workflow['timestamp'] = datetime.now(timezone.utc).isoformat() return workflow def _validate_position_risk( self, analysis: Dict[str, Any], position_size: float, ) -> Dict[str, Any]: """Validate position against risk parameters.""" risk_task = ( f"Validate this trade for risk approval.\n\n" f"ANALYSIS: {analysis['final_recommendation']}\n" f"POSITION SIZE: ${position_size:,.2f}\n\n" "Determine:\n" "1. Is the risk-reward ratio acceptable? (minimum 1:2)\n" "2. Is position sizing appropriate? (max 5% of portfolio)\n" "3. Are stop-loss levels clearly defined?\n" "4. Are there concerning tail risks?\n\n" "Respond with: APPROVED or REJECTED and detailed reasoning." ) result = self.risk_agent.run(risk_task) return { "approved": "APPROVED" in result, "reason": result, } def _generate_execution_plan( self, analysis: Dict[str, Any], position_size: float, ) -> Dict[str, Any]: """Generate step-by-step execution plan.""" plan_task = ( f"Create a detailed execution plan.\n\n" f"ANALYSIS: {analysis['final_recommendation']}\n" f"POSITION SIZE: ${position_size:,.2f}\n\n" "Provide:\n" "1. Entry strategy (limit order, market order, DCA)\n" "2. Exact entry price(s)\n" "3. Stop-loss order placement\n" "4. Take-profit levels (partial exits)\n" "5. Position monitoring checklist\n" "6. Exit criteria and invalidation signals\n\n" "Format as actionable steps." ) plan = self.technical_agent.run(plan_task) return { "plan": plan, "position_size": position_size, }
Step 5: Build a Complete Custom System
Here's a full example of a customized trading system:
PYTHON""" crypto_swing_trader.py - Customized swing trading system """ from trading_prediction_agent import TradingPredictionAgent from typing import Dict, List, Any, Optional from datetime import datetime, timezone from loguru import logger class CryptoSwingTrader(TradingPredictionAgent): """ Specialized system for cryptocurrency swing trading. Features: - 3-7 day holding periods - Focus on major altcoins - Conservative risk management (2% max risk per trade) - RSI + MACD + Volume confluence """ # Trading parameters MAX_RISK_PER_TRADE = 0.02 # 2% MIN_RISK_REWARD = 2.0 # 1:2 minimum PREFERRED_TIMEFRAME = "4h" def __init__(self, api_key: Optional[str] = None) -> None: super().__init__(api_key) # Track active trades self.active_trades: List[Dict[str, Any]] = [] self.watchlist: List[str] = [] def scan_for_setups( self, watchlist: Optional[List[str]] = None, ) -> Dict[str, Any]: """ Scan watchlist for swing trading setups. Args: watchlist: List of symbols to scan (uses self.watchlist if None) Returns: Ranked list of trading opportunities """ symbols = watchlist or self.watchlist if not symbols: return {"error": "No symbols in watchlist"} logger.info(f"Scanning {len(symbols)} symbols for setups") scan_task = ( f"Scan these cryptocurrency pairs for swing trading setups:\n" f"SYMBOLS: {', '.join(symbols)}\n" f"TIMEFRAME: {self.PREFERRED_TIMEFRAME}\n" f"HOLDING PERIOD: 3-7 days\n\n" "For each symbol, evaluate:\n" "1. Technical setup quality (0-100)\n" "2. RSI positioning (oversold for longs, overbought for shorts)\n" "3. MACD alignment\n" "4. Volume confirmation\n" "5. Key support/resistance levels\n" "6. Estimated risk-reward ratio\n\n" f"Only include setups with risk-reward >= {self.MIN_RISK_REWARD}:1\n" "Rank from best to worst opportunity." ) results = self.technical_agent.run(scan_task) return { "symbols_scanned": symbols, "timeframe": self.PREFERRED_TIMEFRAME, "results": results, "timestamp": datetime.now(timezone.utc).isoformat(), } def evaluate_setup( self, symbol: str, portfolio_size: float, ) -> Dict[str, Any]: """ Comprehensive setup evaluation with position sizing. Args: symbol: Trading pair portfolio_size: Total portfolio value in USD Returns: Setup evaluation with exact position parameters """ # Run full analysis analysis = self.analyze_market( symbol=symbol, timeframe=self.PREFERRED_TIMEFRAME, depth="comprehensive", ) # Calculate position sizing position_params = self._calculate_position_size( analysis=analysis, portfolio_size=portfolio_size, ) return { "symbol": symbol, "analysis": analysis, "position_params": position_params, "timestamp": datetime.now(timezone.utc).isoformat(), } def _calculate_position_size( self, analysis: Dict[str, Any], portfolio_size: float, ) -> Dict[str, Any]: """Calculate position size using 2% risk rule.""" sizing_task = ( f"Calculate position sizing with these parameters:\n\n" f"PORTFOLIO SIZE: ${portfolio_size:,.2f}\n" f"MAX RISK PER TRADE: {self.MAX_RISK_PER_TRADE * 100}%\n" f"ANALYSIS: {analysis['risk_assessment']}\n\n" "Calculate and provide:\n" "1. Maximum risk amount in USD\n" "2. Entry price\n" "3. Stop-loss price\n" "4. Distance from entry to stop (in %)\n" "5. Position size in USD\n" "6. Position size in tokens\n" "7. First take-profit target (50% exit)\n" "8. Final take-profit target (remaining 50%)\n\n" "Formula: Position Size = (Portfolio × Max Risk %) / Stop Distance %" ) sizing = self.risk_agent.run(sizing_task) return { "portfolio_size": portfolio_size, "max_risk_pct": self.MAX_RISK_PER_TRADE, "sizing_details": sizing, } def add_to_watchlist(self, symbols: List[str]) -> None: """Add symbols to watchlist.""" for symbol in symbols: if symbol not in self.watchlist: self.watchlist.append(symbol) logger.info(f"Watchlist updated: {len(self.watchlist)} symbols") def get_watchlist(self) -> List[str]: """Get current watchlist.""" return self.watchlist.copy() # Usage example if __name__ == "__main__": # Initialize trader trader = CryptoSwingTrader() # Add symbols to watchlist trader.add_to_watchlist([ "BTC/USDT", "ETH/USDT", "SOL/USDT", "AVAX/USDT", "LINK/USDT", "MATIC/USDT", "ATOM/USDT", "DOT/USDT", ]) # Scan for setups logger.info("Scanning watchlist for swing trade setups") scan_results = trader.scan_for_setups() print("\n=== SCAN RESULTS ===") print(scan_results['results']) # Evaluate best setup (example: SOL/USDT) logger.info("Evaluating SOL/USDT setup") setup = trader.evaluate_setup( symbol="SOL/USDT", portfolio_size=50000, # $50k portfolio ) print("\n=== SETUP EVALUATION ===") print(f"Symbol: {setup['symbol']}") print(f"\nPosition Parameters:") print(setup['position_params']['sizing_details']) print(f"\nFinal Recommendation:") print(setup['analysis']['final_recommendation'])
API Reference
TradingPredictionAgent
Constructor
PYTHONTradingPredictionAgent(api_key: Optional[str] = None)
Parameters:
api_key(optional): OpenAI API key. If not provided, reads fromOPENAI_API_KEYenvironment variable.
Attributes:
model: LiteLLM instance configured with gpt-4o-minidex_client: DexScreenerClient for live market datacrca_agent: CRCA causal analysis agenttechnical_agent: Technical analysis specialistsentiment_agent: Sentiment analysis specialistrisk_agent: Risk management specialistintelligence_agent: Market intelligence specialistanalysis_history: List of past analyses
Methods
analyze_market()
PYTHONanalyze_market( symbol: str, timeframe: str = "4h", depth: str = "comprehensive", market_data: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]
Perform comprehensive multi-agent market analysis.
Parameters:
symbol: Trading pair (e.g., "BTC/USDT", "ETH/USD")timeframe: Chart timeframe —"1m","5m","15m","1h","4h","1d","1w"depth: Analysis depth —"quick","standard","comprehensive"market_data(optional): External data to override live data
Returns:
PYTHON{ "symbol": str, "timeframe": str, "timestamp": str, # ISO 8601 UTC "depth": str, "dexscreener_snapshot": Dict[str, Any], "causal_analysis": str, "technical_analysis": str, "sentiment_analysis": str, "market_intelligence": str, "risk_assessment": str, "final_recommendation": str, }
compare_assets()
PYTHONcompare_assets( symbols: List[str], criteria: str = "risk-adjusted-returns", ) -> Dict Source: https://github.com/ArcticHonour/RugOracl
Requirements
| Package | Installation |
|---|---|
| requests | pip3 install requests |
| os | pip3 install os |
| dataclasses | pip3 install dataclasses |
| datetime | pip3 install datetime |
| typing | pip3 install typing |
| loguru | pip3 install loguru |
| swarms | pip3 install swarms |
| crca | pip3 install crca |
Environment Variables
OPENAI_API_KEY="..."
Agent Code
The main implementation code for this agent
Chart
Loading chart...
Comments & Discussion
Scroll to load comments...
Share
Loading recommendations...