fix tools and bulk taapi

This commit is contained in:
mhmmdjafarg 2025-12-26 01:41:25 +07:00
parent ea0874e078
commit 06a002fbcc
7 changed files with 188 additions and 18 deletions

View File

@ -1 +1 @@
3.10
3.12.7

View File

@ -1,5 +1,5 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from tradingagents.agents.utils.agent_utils import get_crypto_data, get_indicators
from tradingagents.agents.utils.agent_utils import get_crypto_data, get_indicators_bulk
def create_market_analyst(llm):
@ -10,7 +10,7 @@ def create_market_analyst(llm):
tools = [
get_crypto_data,
get_indicators,
get_indicators_bulk,
]
system_message = (
@ -29,7 +29,7 @@ Volatility Indicators:
- bbands: Bollinger Bands: Volatility indicator consisting of upper, middle (SMA), and lower bands based on standard deviations. Usage: Identify overbought/oversold conditions, volatility expansion/contraction, and potential breakout zones. Tips: Price touching bands doesn't guarantee reversal; use band squeeze for volatility breakout trades.
- atr: ATR (Average True Range): Measures market volatility by calculating the average of true ranges over a period. Usage: Set stop-loss levels, position sizing, and identify high/low volatility periods for strategy adjustment. Tips: Higher ATR indicates more volatile conditions; use for risk management rather than directional signals.
- Select indicators that provide diverse and complementary information. Avoid redundancy and focus on the most effective combination for crypto market analysis. Also briefly explain why they are suitable for the given crypto 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_crypto_data first to retrieve the cryptocurrency price data. 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 crypto traders make decisions."""
- Select indicators that provide diverse and complementary information. Avoid redundancy and focus on the most effective combination for crypto market analysis. Also briefly explain why they are suitable for the given crypto 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_crypto_data first to retrieve the cryptocurrency price data. Then use get_indicators_bulk with a list of the specific indicator names (e.g., ["sma", "rsi", "macd"]). 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 crypto 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."""
)

View File

@ -5,10 +5,11 @@ from tradingagents.agents.utils.core_crypto_tools import (
get_crypto_data
)
from tradingagents.agents.utils.core_stock_tools import (
get_stock_data
get_stock_data,
)
from tradingagents.agents.utils.technical_indicators_tools import (
get_indicators
get_indicators,
get_indicators_bulk
)
from tradingagents.agents.utils.fundamental_data_tools import (
get_fundamentals,

View File

@ -1,5 +1,5 @@
from langchain_core.tools import tool
from typing import Annotated
from typing import Annotated, List
from tradingagents.dataflows.interface import route_to_vendor
@tool
@ -20,4 +20,24 @@ def get_indicators(
Returns:
str: A formatted dataframe containing the technical indicators for the specified ticker symbol and indicator.
"""
return route_to_vendor("get_indicators", symbol, indicator, curr_date, look_back_days)
return route_to_vendor("get_indicators", symbol, indicator, curr_date, look_back_days)
@tool
def get_indicators_bulk(
symbol: Annotated[str, "ticker symbol of the company"],
indicators: Annotated[List[str], "list of technical indicators to get the analysis and report of"],
curr_date: Annotated[str, "The current trading date you are trading on, YYYY-mm-dd"],
look_back_days: Annotated[int, "how many days to look back"] = 30,
) -> str:
"""
Retrieve multiple technical indicators for a given ticker symbol.
Uses the configured technical_indicators vendor.
Args:
symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
indicators (List[str]): List of technical indicators to get the analysis and report of
curr_date (str): The current trading date you are trading on, YYYY-mm-dd
look_back_days (int): How many days to look back, default is 30
Returns:
str: A formatted report containing the technical indicators for the specified ticker symbol and indicators.
"""
return route_to_vendor("get_indicators_bulk", symbol, indicators, curr_date, look_back_days)

View File

@ -18,7 +18,7 @@ from .alpha_vantage import (
from .alpha_vantage_common import AlphaVantageRateLimitError
from .telegram import get_crypto_news_telegram
from .binance import get_market_data as get_binance_crypto_data
from .taapi import get_crypto_stats_indicators_window
from .taapi import get_crypto_stats_indicators_window, get_crypto_stats_indicators
# Configuration and routing logic
from .config import get_config
@ -40,7 +40,8 @@ TOOLS_CATEGORIES = {
"technical_indicators": {
"description": "Technical analysis indicators",
"tools": [
"get_indicators"
"get_indicators",
"get_indicators_bulk"
]
},
"fundamental_data": {
@ -65,24 +66,25 @@ TOOLS_CATEGORIES = {
}
VENDOR_LIST = [
"binance"
"local",
"yfinance",
"openai",
"google"
"google",
"taapi"
]
# Mapping of methods to their vendor-specific implementations
VENDOR_METHODS = {
# core_crypto_apis
"get_crypto_data": {
"binance": get_binance_crypto_data,
},
# core_stock_apis
"get_stock_data": {
"alpha_vantage": get_alpha_vantage_stock,
"yfinance": get_YFin_data_online,
"local": get_YFin_data,
},
# core_crypto_apis
"get_crypto_data": {
"binance": get_binance_crypto_data,
},
# technical_indicators
"get_indicators": {
"taapi": get_crypto_stats_indicators_window,
@ -90,6 +92,9 @@ VENDOR_METHODS = {
# "yfinance": get_stock_stats_indicators_window,
# "local": get_stock_stats_indicators_window
},
"get_indicators_bulk": {
"taapi": get_crypto_stats_indicators,
},
# fundamental_data
"get_fundamentals": {
"alpha_vantage": get_alpha_vantage_fundamentals,

View File

@ -1,5 +1,5 @@
import requests
from typing import Annotated
from typing import Annotated, List, Dict
import os
from tradingagents.dataflows.config import get_config
@ -11,7 +11,7 @@ def get_api_key() -> str:
raise ValueError("TAAPI_API_KEY environment variable is not set.")
return api_key
# This is for single indicator, unused for now but kept for reference
def get_crypto_stats_indicators_window(
symbol: Annotated[str, "ticker symbol of the coin/asset"],
indicator: Annotated[str, "technical indicator to get the analysis and report of"],
@ -129,3 +129,142 @@ def get_crypto_stats_indicators_window(
return f"Error: Missing expected field in API response: {str(e)}"
except Exception as e:
return f"Unexpected error: {str(e)}"
def get_crypto_stats_indicators(
symbol: Annotated[str, "ticker symbol of the coin/asset"],
indicators: Annotated[List[str], "list of technical indicators to get analysis for"],
curr_date: Annotated[
str, "The current trading date you are trading on, YYYY-mm-dd"
],
look_back_days: Annotated[int, "how many days to look back"],
) -> str:
"""Fetch multiple technical indicator data from TAAPI.io for a given symbol using bulk API.
Args:
symbol: Ticker symbol of the coin/asset (e.g., 'BTC/USDT')
indicators: List of technical indicators to get analysis for (e.g., ['rsi', 'macd', 'sma', 'bbands', 'atr'])
curr_date: The current trading date you are trading on, in YYYY-MM-DD format
look_back_days: How many days to look back
Returns:
str: A formatted report containing all requested technical indicators for the specified ticker symbol.
"""
# Supported indicators mapping
supported_indicators = {
"sma": "Simple Moving Average",
"ema": "Exponential Moving Average",
"macd": "MACD (Moving Average Convergence Divergence)",
"rsi": "Relative Strength Index",
"bbands": "Bollinger Bands",
"atr": "Average True Range",
"kdj": "KDJ (Stochastic KDJ)"
}
# Detailed indicator descriptions and usage
indicator_descriptions = {
"sma": "SMA (Simple Moving Average): A basic trend-following indicator that smooths out price data. Usage: Identify trend direction and serve as dynamic support/resistance levels. Tips: Use multiple SMAs for crossover signals; combines well with volume analysis for confirmation.",
"ema": "EMA (Exponential Moving Average): A trend-following indicator that gives more weight to recent prices. Usage: More responsive than SMA for trend changes and crossover signals. Tips: Better for short-term trading; reacts faster to price changes than SMA.",
"macd": "MACD: Measures momentum via differences between fast and slow EMAs. Usage: Look for signal line crossovers, centerline crossovers, and divergence patterns for trend changes. Tips: Most effective in trending markets; combine with RSI to avoid false signals in sideways markets.",
"rsi": "RSI: Oscillator measuring momentum to identify overbought (>70) and oversold (<30) conditions. Usage: Look for reversal signals at extreme levels and divergence with price action. Tips: In strong trends, RSI can remain extreme for extended periods; always confirm with trend analysis.",
"bbands": "Bollinger Bands: Volatility indicator consisting of upper, middle (SMA), and lower bands based on standard deviations. Usage: Identify overbought/oversold conditions, volatility expansion/contraction, and potential breakout zones. Tips: Price touching bands doesn't guarantee reversal; use band squeeze for volatility breakout trades.",
"atr": "ATR: Measures market volatility by calculating the average of true ranges over a period. Usage: Set stop-loss levels, position sizing, and identify high/low volatility periods for strategy adjustment. Tips: Higher ATR indicates more volatile conditions; use for risk management rather than directional signals.",
"kdj": "KDJ: Advanced stochastic oscillator with three lines (K, D, J). Usage: Identify overbought/oversold conditions and momentum changes. Tips: J line is most sensitive; use crossovers between K, D, and J lines for entry/exit signals."
}
# Validate indicators
invalid_indicators = [ind for ind in indicators if ind.lower() not in supported_indicators]
if invalid_indicators:
return f"Error: Indicators {invalid_indicators} are not supported. Please choose from: {list(supported_indicators.keys())}"
config = get_config()
base_url = config["tool_providers"].get("TAAPI_BASE_URL", "https://api.taapi.io")
api_key = get_api_key()
# Construct the bulk API URL
url = f"{base_url}/bulk"
# Prepare indicators list for the bulk request
indicator_list = []
for indicator in indicators:
indicator_list.append({
"indicator": indicator.lower(),
"backtrack": look_back_days
})
# Set up the JSON payload for the bulk request
payload = {
"secret": api_key,
"construct": {
"exchange": "binance",
"symbol": symbol,
"interval": "1d",
"indicators": indicator_list
}
}
try:
# Make the POST request to bulk API
response = requests.post(url, json=payload)
response.raise_for_status()
# Get the JSON response
data = response.json()
# Format the bulk response
result_str = f"# Technical Indicators Report for {symbol}\n\n"
result_str += f"**Current Date:** {curr_date}\n"
result_str += f"**Lookback Days:** {look_back_days}\n\n"
if "data" in data and isinstance(data["data"], list):
for item in data["data"]:
if "errors" in item and item["errors"]:
# Handle errors for individual indicators
result_str += f"## ❌ Error for {item.get('indicator', 'Unknown').upper()}:\n"
result_str += f"- {'; '.join(item['errors'])}\n\n"
continue
indicator_name = item.get("indicator", "unknown")
indicator_display = supported_indicators.get(indicator_name, indicator_name.upper())
result_str += f"## {indicator_display} ({indicator_name.upper()})\n\n"
# Handle the result data
if "result" in item and isinstance(item["result"], dict):
result_data = item["result"]
# Format the values
for key, value in result_data.items():
clean_key = key.replace("value", "").replace("Value", "")
if clean_key == "":
clean_key = "Value"
if isinstance(value, (int, float)):
result_str += f"**{clean_key}:** {value:.4f}\n"
else:
result_str += f"**{clean_key}:** {value}\n"
# Add description
if indicator_name in indicator_descriptions:
result_str += f"\n*{indicator_descriptions[indicator_name]}*\n"
result_str += "\n---\n\n"
else:
result_str += f"Unexpected response format: {str(data)}"
return result_str
except requests.exceptions.RequestException as e:
return f"Error fetching bulk data from TAAPI.io: {str(e)}"
except ValueError as e:
return f"Error parsing bulk response from TAAPI.io: {str(e)}"
except KeyError as e:
return f"Error: Missing expected field in bulk API response: {str(e)}"
except Exception as e:
return f"Unexpected error in bulk request: {str(e)}"

View File

@ -24,8 +24,10 @@ from tradingagents.dataflows.config import set_config
# Import the new abstract tool methods from agent_utils
from tradingagents.agents.utils.agent_utils import (
get_crypto_data,
get_stock_data,
get_indicators,
get_indicators_bulk,
get_fundamentals,
get_balance_sheet,
get_cashflow,
@ -125,10 +127,13 @@ class TradingAgentsGraph:
return {
"market": ToolNode(
[
# Crypto data tools
get_crypto_data,
# Core stock data tools
get_stock_data,
# Technical indicators
get_indicators,
get_indicators_bulk,
]
),
"social": ToolNode(