This commit is contained in:
BrunoNatalicio 2026-03-22 17:52:29 -04:00 committed by GitHub
commit d6f259804e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 407 additions and 44 deletions

4
.gitignore vendored
View File

@ -217,3 +217,7 @@ __marimo__/
# Cache
**/data_cache/
# Git Worktrees
.worktrees/
worktrees/

View File

@ -2,49 +2,57 @@ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
import time
import json
from tradingagents.agents.utils.agent_utils import get_stock_data, get_indicators
from tradingagents.agents.utils.dex_tools import get_token_ohlcv, get_token_info
from tradingagents.dataflows.config import get_config
# DEX-specific system prompt for crypto analysis
DEX_MARKET_ANALYST_PROMPT = """You are an On-Chain Market Analyst specializing in cryptocurrency and DeFi tokens.
Your role is to analyze cryptocurrency market data to help traders make informed decisions.
When analyzing crypto assets, consider:
1. Price momentum and trend direction from OHLCV data
2. Volume analysis and market liquidity
3. Market cap and trading volume ratios
4. Support and resistance levels
5. Comparison to similar tokens in the ecosystem
Provide insights in a structured format that helps traders make informed decisions.
Make sure to call get_token_ohlcv to retrieve price data and get_token_info for market metadata.
Write a very detailed and nuanced report of the trends you observe. Do not simply state the trends are mixed, provide detailed and fine-grained analysis and insights.
Append a Markdown table at the end of the report to organize key points, organized and easy to read."""
def create_market_analyst(llm):
def market_analyst_node(state):
# Check trading mode from config
config = get_config()
trading_mode = config.get("trading_mode", "stock")
current_date = state["trade_date"]
ticker = state["company_of_interest"]
company_name = state["company_of_interest"]
tools = [
get_stock_data,
get_indicators,
]
system_message = (
"""You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy. Categories and each category's indicators are:
Moving Averages:
- close_50_sma: 50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals.
- close_200_sma: 200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries.
- close_10_ema: 10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals.
MACD Related:
- macd: MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets.
- macds: MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives.
- macdh: MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets.
Momentum Indicators:
- rsi: RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis.
Volatility Indicators:
- boll: Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals.
- boll_ub: Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends.
- boll_lb: Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals.
- atr: ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy.
Volume-Based Indicators:
- vwma: VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses.
- Select indicators that provide diverse and complementary information. Avoid redundancy (e.g., do not select both rsi and stochrsi). Also briefly explain why they are suitable for the given market context. When you tool call, please use the exact name of the indicators provided above as they are defined parameters, otherwise your call will fail. Please make sure to call get_stock_data first to retrieve the CSV that is needed to generate indicators. Then use get_indicators with the specific indicator names. Write a very detailed and nuanced report of the trends you observe. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions."""
+ """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."""
)
# Use different tools based on trading mode
if trading_mode == "dex":
tools = [
get_token_ohlcv,
get_token_info,
]
system_message = DEX_MARKET_ANALYST_PROMPT
# For DEX, use coin ID format (lowercase for CoinGecko)
ticker = ticker.lower()
else:
tools = [
get_stock_data,
get_indicators,
]
system_message = ( # Original stock prompt
"""You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy. Categories and each category's indicators are: Moving Averages: close_50_sma: 50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals. close_200_sma: 200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries. close_10_ema: 10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals. MACD Related: macd: MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets. macds: MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives. macdh: MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets. Momentum Indicators: rsi: RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis. Volatility Indicators: boll: Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals. boll_ub: Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends. boll_lb: Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals. atr: ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy. Volume-Based Indicators: vwma: VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses. Select indicators that provide diverse and complementary information. Avoid redundancy (e.g., do not select both rsi and stochrsi). Also briefly explain why they are suitable for the given market context. When you tool call, please use the exact name of the indicators provided above as they are defined parameters, otherwise your call will fail. Please make sure to call get_stock_data first to retrieve the CSV that is needed to generate indicators. Then use get_indicators with the specific indicator names. Write a very detailed and nuanced report of the trends you observe. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.""" +
""" Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""")
prompt = ChatPromptTemplate.from_messages(
[
@ -82,4 +90,4 @@ Volume-Based Indicators:
"market_report": report,
}
return market_analyst_node
return market_analyst_node

View File

@ -0,0 +1,69 @@
"""DEX tool wrappers for TradingAgents."""
from typing import Annotated
from langchain_core.tools import tool
from tradingagents.dataflows.dex.coingecko_provider import get_coin_ohlcv as _get_coin_ohlcv
from tradingagents.dataflows.dex.coingecko_provider import get_coin_info as _get_coin_info
@tool
def get_token_ohlcv(
coin_id: Annotated[str, "CoinGecko ID (e.g., solana, bitcoin, ethereum)"],
vs_currency: Annotated[str, "Target currency (default: usd)"] = "usd",
days: Annotated[int, "Number of days (1-365, default: 7)"] = 7
) -> str:
"""Get OHLCV (Open-High-Low-Close-Volume) price data for a cryptocurrency token.
Use this to analyze price movements, trends, and volatility.
CoinGecko ID examples:
- solana, bitcoin, ethereum, cardano, polygon, avalanche-2, chainlink
Returns formatted OHLC data with price summary.
"""
import asyncio
return asyncio.run(_get_coin_ohlcv(coin_id, vs_currency, days))
@tool
def get_token_info(
coin_id: Annotated[str, "CoinGecko ID (e.g., solana, bitcoin, ethereum)"]
) -> str:
"""Get comprehensive token metadata and market data.
Includes: current price, market cap, volume, supply, ATH/ATL.
Use this for fundamental analysis of cryptocurrency tokens.
CoinGecko ID examples:
- solana, bitcoin, ethereum, cardano, polygon, avalanche-2, chainlink
"""
import asyncio
return asyncio.run(_get_coin_info(coin_id))
@tool
def get_pool_data(
pool_address: Annotated[str, "DEX pool contract address"],
chain: Annotated[str, "Blockchain (solana, ethereum, bsc)"] = "solana"
) -> str:
"""Get DEX pool metrics: TVL, volume 24h, fees.
Note: This requires DeFiLlama provider (Phase 2).
Currently returns placeholder.
"""
return "Pool data requires DeFiLlama provider (Phase 2). Use get_token_ohlcv for now."
@tool
def get_whale_transactions(
token_address: Annotated[str, "Token contract address"],
chain: Annotated[str, "Blockchain network"] = "solana",
min_usd: Annotated[float, "Minimum USD value (default: 10000)"] = 10000
) -> str:
"""Track large holder (whale) movements.
Note: This requires Birdeye provider (Phase 3).
Currently returns placeholder.
"""
return "Whale tracking requires Birdeye provider (Phase 3). Use get_token_ohlcv for now."

View File

@ -0,0 +1,8 @@
"""DEX Data Providers for TradingAgents."""
try:
from .coingecko_provider import CoinGeckoProvider, get_coin_ohlcv, get_coin_info
__all__ = ["CoinGeckoProvider", "get_coin_ohlcv", "get_coin_info"]
except ImportError:
# Coingecko provider will be added in Task 2
__all__ = []

View File

@ -0,0 +1,220 @@
"""CoinGecko data provider for DEX data.
This module provides access to CoinGecko's free API for OHLCV data and token metadata.
The output is formatted as readable text for LLM consumption.
"""
import aiohttp
from datetime import datetime
from typing import Optional
COINGECKO_BASE_URL = "https://api.coingecko.com/api/v3"
class CoinGeckoProvider:
"""Async provider for CoinGecko API."""
def __init__(self):
self.base_url = COINGECKO_BASE_URL
self._session: Optional[aiohttp.ClientSession] = None
async def _get_session(self) -> aiohttp.ClientSession:
"""Get or create an aiohttp session."""
if self._session is None or self._session.closed:
self._session = aiohttp.ClientSession()
return self._session
async def close(self):
"""Close the HTTP session."""
if self._session and not self._session.closed:
await self._session.close()
async def get_ohlc(
self, coin_id: str, vs_currency: str = "usd", days: int = 7
) -> list:
"""
Get OHLC data for a coin.
Args:
coin_id: CoinGecko coin ID (e.g., 'solana', 'bitcoin')
vs_currency: Currency to compare against (e.g., 'usd', 'eur')
days: Number of days of data (1, 7, 14, 30, 90, 365, max)
Returns:
List of OHLC data points: [timestamp, open, high, low, close]
"""
url = f"{self.base_url}/coins/{coin_id}/ohlc"
params = {"vs_currency": vs_currency, "days": days}
session = await self._get_session()
async with session.get(url, params=params) as response:
response.raise_for_status()
return await response.json()
async def get_coin_data(self, coin_id: str) -> dict:
"""
Get detailed metadata for a coin.
Args:
coin_id: CoinGecko coin ID (e.g., 'solana', 'bitcoin')
Returns:
Dictionary containing coin metadata
"""
url = f"{self.base_url}/coins/{coin_id}"
params = {
"localization": "false",
"tickers": "false",
"market_data": "true",
"community_data": "false",
"developer_data": "false",
"sparkline": "false",
}
session = await self._get_session()
async with session.get(url, params=params) as response:
response.raise_for_status()
return await response.json()
async def __aenter__(self):
"""Async context manager entry."""
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit."""
await self.close()
def _format_ohlc_data(ohlc_data: list) -> str:
"""Format OHLC data as readable text for LLM consumption."""
if not ohlc_data:
return "No OHLC data available."
lines = ["OHLC Data (Open, High, Low, Close):"]
lines.append("-" * 60)
for point in ohlc_data:
timestamp, open_price, high, low, close = point
date = datetime.fromtimestamp(timestamp / 1000).strftime("%Y-%m-%d %H:%M")
lines.append(
f"Timestamp: {date} | Open: ${open_price:,.2f} | High: ${high:,.2f} | "
f"Low: ${low:,.2f} | Close: ${close:,.2f}"
)
return "\n".join(lines)
def _format_coin_info(coin_data: dict) -> str:
"""Format coin metadata as readable text for LLM consumption."""
if not coin_data or "market_data" not in coin_data:
return "No coin data available."
md = coin_data.get("market_data", {})
info = coin_data.get("info", {})
name = coin_data.get("name", "Unknown")
symbol = coin_data.get("symbol", "").upper()
lines = [f"Token Information: {name} ({symbol})"]
lines.append("=" * 60)
# Market data
lines.append("\n--- Market Data ---")
current_price = md.get("current_price", {}).get("usd", 0)
lines.append(f"Current Price (USD): ${current_price:,.2f}")
market_cap = md.get("market_cap", {}).get("usd", 0)
lines.append(f"Market Cap (USD): ${market_cap:,.0f}")
total_volume = md.get("total_volume", {}).get("usd", 0)
lines.append(f"24h Trading Volume (USD): ${total_volume:,.0f}")
# Price changes
lines.append("\n--- Price Changes ---")
for period in ["1h", "24h", "7d", "30d"]:
change = md.get(f"price_change_percentage_{period}s")
if change is not None:
sign = "+" if change >= 0 else ""
lines.append(f"{period} Change: {sign}{change:.2f}%")
# Supply data
lines.append("\n--- Supply Data ---")
circulating = md.get("circulating_supply", 0)
if circulating:
lines.append(f"Circulating Supply: {circulating:,.0f} {symbol}")
total_supply = md.get("total_supply")
if total_supply:
lines.append(f"Total Supply: {total_supply:,.0f} {symbol}")
max_supply = md.get("max_supply")
if max_supply:
lines.append(f"Max Supply: {max_supply:,.0f} {symbol}")
# ATH/ATL
lines.append("\n--- All-Time High/Low ---")
ath = md.get("ath", {}).get("usd", 0)
ath_date = md.get("ath_date", {}).get("usd", "")
if ath:
lines.append(f"All-Time High: ${ath:,.2f} ({ath_date[:10] if ath_date else 'N/A'})")
atl = md.get("atl", {}).get("usd", 0)
atl_date = md.get("atl_date", {}).get("usd", "")
if atl:
lines.append(f"All-Time Low: ${atl:,.2f} ({atl_date[:10] if atl_date else 'N/A'})")
return "\n".join(lines)
async def get_coin_ohlcv(coin_id: str, vs_currency: str = "usd", days: int = 7) -> str:
"""
Get OHLCV data for a cryptocurrency.
Args:
coin_id: CoinGecko coin ID (e.g., 'solana', 'bitcoin', 'ethereum')
vs_currency: Currency to compare against (default: 'usd')
days: Number of days of data (default: 7, max: 365)
Returns:
Formatted string containing OHLC data for LLM consumption
"""
async with CoinGeckoProvider() as provider:
try:
ohlc_data = await provider.get_ohlc(coin_id, vs_currency, days)
return _format_ohlc_data(ohlc_data)
except aiohttp.ClientError as e:
return f"Error fetching OHLC data: {str(e)}"
except Exception as e:
return f"Unexpected error: {str(e)}"
async def get_coin_info(coin_id: str) -> str:
"""
Get detailed token metadata from CoinGecko.
Args:
coin_id: CoinGecko coin ID (e.g., 'solana', 'bitcoin', 'ethereum')
Returns:
Formatted string containing token metadata for LLM consumption
"""
async with CoinGeckoProvider() as provider:
try:
coin_data = await provider.get_coin_data(coin_id)
return _format_coin_info(coin_data)
except aiohttp.ClientError as e:
return f"Error fetching coin info: {str(e)}"
except Exception as e:
return f"Unexpected error: {str(e)}"
# Module-level provider instance for reuse
_provider: Optional[CoinGeckoProvider] = None
async def _get_provider() -> CoinGeckoProvider:
"""Get or create a module-level provider instance."""
global _provider
if _provider is None:
_provider = CoinGeckoProvider()
return _provider

View File

@ -0,0 +1,18 @@
import pytest
from tradingagents.dataflows.dex.coingecko_provider import get_coin_ohlcv, get_coin_info
@pytest.mark.asyncio
async def test_get_coin_ohlcv_returns_data():
"""Test that get_coin_ohlcv returns OHLCV data for SOL."""
result = await get_coin_ohlcv("solana", "usd", 7)
assert " timestamp " in result.lower() or "open" in result.lower()
assert len(result) > 100
@pytest.mark.asyncio
async def test_get_coin_info_returns_metadata():
"""Test that get_coin_info returns token metadata."""
result = await get_coin_info("solana")
assert "solana" in result.lower()
assert "market_cap" in result.lower() or "$" in result

View File

@ -65,6 +65,33 @@ VENDOR_LIST = [
"alpha_vantage",
]
# DEX vendors for crypto/decentralized exchange data
DEX_VENDOR_LIST = ["coingecko", "defillama", "birdeye"]
# Tool categories for DEX
DEX_TOOLS_CATEGORIES = {
"core_token_apis": {
"tools": ["get_token_ohlcv"],
"default": "coingecko"
},
"token_info": {
"tools": ["get_token_info"],
"default": "coingecko"
},
"technical_indicators": {
"tools": ["get_token_indicators"],
"default": "coingecko"
},
"defi_fundamentals": {
"tools": ["get_pool_data", "get_token_info"],
"default": "defillama"
},
"whale_tracking": {
"tools": ["get_whale_transactions"],
"default": "birdeye"
},
}
# Mapping of methods to their vendor-specific implementations
VENDOR_METHODS = {
# core_stock_apis

View File

@ -13,22 +13,31 @@ DEFAULT_CONFIG = {
"quick_think_llm": "gpt-5-mini",
"backend_url": "https://api.openai.com/v1",
# Provider-specific thinking configuration
"google_thinking_level": None, # "high", "minimal", etc.
"openai_reasoning_effort": None, # "medium", "high", "low"
"google_thinking_level": None, # "high", "minimal", etc.
"openai_reasoning_effort": None, # "medium", "high", "low"
# Debate and discussion settings
"max_debate_rounds": 1,
"max_risk_discuss_rounds": 1,
"max_recur_limit": 100,
# Data vendor configuration
# Category-level configuration (default for all tools in category)
# Data vendor configuration (Stock/TradFi)
"data_vendors": {
"core_stock_apis": "yfinance", # Options: alpha_vantage, yfinance
"technical_indicators": "yfinance", # Options: alpha_vantage, yfinance
"fundamental_data": "yfinance", # Options: alpha_vantage, yfinance
"news_data": "yfinance", # Options: alpha_vantage, yfinance
"core_stock_apis": "yfinance", # Options: alpha_vantage, yfinance
"technical_indicators": "yfinance", # Options: alpha_vantage, yfinance
"fundamental_data": "yfinance", # Options: alpha_vantage, yfinance
"news_data": "yfinance", # Options: alpha_vantage, yfinance
# DEX/Crypto data vendors (Phase 1-3)
"core_token_apis": "coingecko",
"token_info": "coingecko",
"technical_indicators_dex": "coingecko",
"defi_fundamentals": "defillama", # Phase 2
"whale_tracking": "birdeye", # Phase 3
},
# Tool-level configuration (takes precedence over category-level)
"tool_vendors": {
# Example: "get_stock_data": "alpha_vantage", # Override category default
# Example: "get_stock_data": "alpha_vantage", # Override category default
},
}
# Trading mode: "stock" (TradFi) or "dex" (DeFi/Crypto)
"trading_mode": "stock",
# Default blockchain for DEX operations
"default_chain": "solana", # Options: solana, ethereum, bsc, arbitrum, etc.
}