Context Retrieval Logic
The system utilizes a multi-layered context retrieval strategy to ensure that trading agents make decisions based on both real-time market data and historical knowledge. This is achieved through a combination of Vector RAG (Retrieval-Augmented Generation) and dynamic data connectors.
Knowledge Retrieval (RAG)
The knowledge retrieval system allows agents to access specialized domain expertise stored in the knowledge/ directory. This data is indexed into a vector store to provide agents with relevant snippets during the decision-making process.
Domain-Specific Indexing
Documents are partitioned into four primary domains to ensure agents only retrieve information relevant to their specific role:
- Technical: Patterns, indicator definitions, and chart analysis strategies.
- Sentiment: Market psychology, Fear & Greed index interpretations, and contrarian signals.
- Fundamental: Valuation models, network health metrics, and market cycle phases.
- Risk: Position sizing rules, Kelly Criterion logic, and volatility assessment guidelines.
Usage Example: Indexing Knowledge
The KnowledgeIndexer processes Markdown, Text, and PDF files, splitting them into manageable chunks (default 500 characters) for the vector store.
from agents.rag.indexer import KnowledgeIndexer
# Initialize and index all domain knowledge
indexer = KnowledgeIndexer(knowledge_dir="./knowledge")
stats = indexer.index_all()
print(f"Indexed {stats['technical']} chunks for the Technical Agent.")
Real-Time News Retrieval
The NewsAPIConnector provides a robust pipeline for fetching the latest cryptocurrency news. It is designed with a tiered fallback system to maximize reliability without requiring paid API keys by default.
Retrieval Logic
- Direct RSS Scrapers: Attempts to fetch from high-signal sources like CoinTelegraph or CoinDesk.
- Google News RSS: Fallback to Google News search for "bitcoin cryptocurrency" (no API key required).
- NewsAPI: Final fallback to the official NewsAPI (requires
NEWSAPI_KEY).
Public Interface
The get_bitcoin_news method returns a standardized list of article dictionaries containing titles, descriptions, and source metadata.
from data_connectors.newsapi_connector import NewsAPIConnector
connector = NewsAPIConnector()
news_context = connector.get_bitcoin_news(limit=5)
for article in news_context:
print(f"Source: {article['source']} - {article['title']}")
Historical Trade & Backtest Context
To maintain continuity in trading strategies, the system retrieves historical trade data. This allows the supervisor and risk agents to analyze past performance and current exposure before authorizing new trades.
Trade Log Retrieval
The system parses JSON-based backtest reports and database entries to reconstruct the trade history. This context is injected into the Risk Agent's prompt to determine:
- Current open positions.
- Recent Win/Loss streaks.
- Entry and Exit price benchmarks.
Data Structure
Retrieved trade context follows the TradeResponse schema, ensuring the agent receives structured data including:
- Action: BUY/SELL/HOLD
- Reasoning: The logic used by the agent in the previous step.
- Metrics: P/L percentage and confidence levels.
# Example of retrieved trade context structure
{
"timestamp": "2023-10-27T10:00:00",
"action": "BUY",
"price": 42500.0,
"reasoning": "RSI oversold at 25 on 4H timeframe...",
"confidence": 85
}
Context Injection Workflow
When the TradingOrchestrator initiates an analysis, the following retrieval sequence occurs:
- Market State: Current price and indicators are fetched via tool calls.
- RAG Lookup: The agent queries its domain-specific vector store for relevant strategy documents.
- External News: The News Connector pulls the latest headlines to gauge immediate sentiment.
- Prompt Synthesis: All retrieved context is formatted into a
HumanMessageand passed to the agent's LLM for processing.