This commit is contained in:
mhmmdjafarg 2025-12-26 00:20:14 +07:00
parent f76f12b60d
commit 1fceaad2fc
10 changed files with 166 additions and 35 deletions

View File

@ -4,3 +4,4 @@ TELEGRAM_API_ID=telegram_api_placeholder
TELEGRAM_API_HASH=telegram_api_hash_placeholder
TELEGRAM_SESSION_NAME=telegram_session_name_placeholder
BINANCE_API_KEY=binance_api_key_placeholder
TAAPI_API_KEY=taapi_api_key_placeholder

View File

@ -1,48 +1,35 @@
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.dataflows.config import get_config
from tradingagents.agents.utils.agent_utils import get_crypto_data, get_indicators
def create_market_analyst(llm):
def market_analyst_node(state):
current_date = state["trade_date"]
ticker = state["company_of_interest"]
company_name = state["company_of_interest"]
symbol = state["ticker_of_interest"] # for crypto, e.g BTC/USDT
tools = [
get_stock_data,
get_crypto_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:
"""You are a crypto trading assistant tasked with analyzing cryptocurrency markets. Your role is to select the **most relevant indicators** for a given crypto market condition or trading strategy from the following list. The goal is to choose the **most effective indicators** that provide complementary insights without redundancy. Available 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.
- 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.
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.
- macd: MACD (Moving Average Convergence Divergence): 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.
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.
- rsi: RSI (Relative Strength Index): 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 crypto trends, RSI can remain extreme for extended periods; always confirm 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.
- 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.
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."""
- 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."""
+ """ 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."""
)
@ -57,7 +44,7 @@ Volume-Based Indicators:
" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
" You have access to the following tools: {tool_names}.\n{system_message}"
"For your reference, the current date is {current_date}. The company we want to look at is {ticker}",
"For your reference, the current date is {current_date}. The cryptocurrency symbol we want to analyze is {symbol}",
),
MessagesPlaceholder(variable_name="messages"),
]
@ -66,7 +53,7 @@ Volume-Based Indicators:
prompt = prompt.partial(system_message=system_message)
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
prompt = prompt.partial(current_date=current_date)
prompt = prompt.partial(ticker=ticker)
prompt = prompt.partial(ticker=symbol)
chain = prompt | llm.bind_tools(tools)

View File

@ -8,8 +8,8 @@ from tradingagents.dataflows.config import get_config
def create_social_media_analyst(llm):
def social_media_analyst_node(state):
current_date = state["trade_date"]
ticker = state["coin_of_interest"]
coin_name = state["coin_of_interest"]
ticker = state["ticker_of_interest"]
coin_name = state["ticker_of_interest"]
tools = [
get_news,

View File

@ -49,7 +49,7 @@ class RiskDebateState(TypedDict):
class AgentState(MessagesState):
company_of_interest: Annotated[str, "Company that we are interested in trading"]
coin_of_interest: Annotated[str, "Coin that we are interested in trading"]
ticker_of_interest: Annotated[str, "Ticker that we are interested in trading"] # e.g BTC/USDT
trade_date: Annotated[str, "What date we are trading at"]
sender: Annotated[str, "Agent that sent this message"]

View File

@ -4,7 +4,7 @@ from tradingagents.dataflows.interface import route_to_vendor
@tool
def get_crypto_data(
symbol: Annotated[str, "trading symbol, e.g., BTCUSDT"],
symbol: Annotated[str, "trading symbol, e.g., BTC/USDT"],
start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
end_date: Annotated[str, "End date in yyyy-mm-dd format"],
) -> str:

View File

@ -20,13 +20,16 @@ def get_market_data(symbol: str, start_date: str, end_date: str):
"""Fetch market data for a given symbol from Binance. Get OHLCV data. interval is 1 day.
Args:
symbol: Trading symbol (e.g., 'BTCUSDT')
symbol: Trading symbol (e.g., 'BTC/USDT')
start_date: Start date in YYYY-MM-DD format
end_date: End date in YYYY-MM-DD format
Returns:
CSV formatted string with OHLCV data
"""
# remove / from symbol for binance format
symbol = symbol.replace("/", "")
# Convert dates to epoch time (milliseconds)
start_epoch = int(datetime.strptime(start_date, "%Y-%m-%d").timestamp() * 1000)
end_epoch = int(datetime.strptime(end_date, "%Y-%m-%d").timestamp() * 1000)

View File

@ -18,6 +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
# Configuration and routing logic
from .config import get_config
@ -84,9 +85,10 @@ VENDOR_METHODS = {
},
# technical_indicators
"get_indicators": {
"alpha_vantage": get_alpha_vantage_indicator,
"yfinance": get_stock_stats_indicators_window,
"local": get_stock_stats_indicators_window
"taapi": get_crypto_stats_indicators_window,
# "alpha_vantage": get_alpha_vantage_indicator,
# "yfinance": get_stock_stats_indicators_window,
# "local": get_stock_stats_indicators_window
},
# fundamental_data
"get_fundamentals": {

View File

@ -0,0 +1,134 @@
import requests
from typing import Annotated
import os
from tradingagents.dataflows.config import get_config
def get_api_key() -> str:
"""Retrieve the API key for TAAPI from environment variables."""
api_key = os.getenv("TAAPI_API_KEY")
if not api_key:
raise ValueError("TAAPI_API_KEY environment variable is not set.")
return api_key
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"],
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 technical indicator data from TAAPI.io for a given symbol.
Args:
symbol: Ticker symbol of the coin/asset (e.g., 'BTC/USDT')
indicator: Technical indicator to get the analysis and report of (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 the technical indicators for the specified ticker symbol and indicator.
"""
# quick fix add n seconds cooldown to avoid rate limit issues
import time
time.sleep(2)
# Supported indicators mapping
supported_indicators = {
"sma": "Simple Moving Average",
"macd": "MACD (Moving Average Convergence Divergence)",
"rsi": "Relative Strength Index",
"bbands": "Bollinger Bands",
"atr": "Average True Range"
}
# 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.",
"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."
}
# Validate indicator
if indicator.lower() not in supported_indicators:
return f"Error: Indicator '{indicator}' is 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()
# Set backtrack as requested
backtrack = look_back_days
# Construct the API URL
url = f"{base_url}/{indicator.lower()}"
# Set up parameters for the API call
params = {
"secret": api_key,
"exchange": "binance", # Default to binance exchange for crypto
"symbol": symbol,
"interval": "1d", # Daily interval
"backtrack": backtrack
}
try:
# Make the API request
response = requests.get(url, params=params)
response.raise_for_status() # Raise an exception for bad status codes
# Get the JSON response
data = response.json()
# Format the response based on indicator type
if isinstance(data, list):
# Handle historical data (multiple periods)
result_str = f"## {supported_indicators[indicator.lower()]} ({indicator.upper()}) for {symbol}:\n\n"
for i, period_data in enumerate(data):
if isinstance(period_data, dict):
result_str += f"Period {i + 1}:\n"
for key, value in period_data.items():
clean_key = key.replace("value", "").replace("Value", "")
if isinstance(value, (int, float)):
result_str += f" {clean_key}: {value:.4f}\n"
else:
result_str += f" {clean_key}: {value}\n"
result_str += "\n"
elif isinstance(data, dict):
# Handle single period data
result_str = f"## {supported_indicators[indicator.lower()]} ({indicator.upper()}) for {symbol}:\n\n"
result_str += f"Current Date: {curr_date}\n"
result_str += f"Lookback Days: {look_back_days}\n\n"
# Generic formatting for all indicators
for key, value in data.items():
clean_key = key.replace("value", "").replace("Value", "")
if isinstance(value, (int, float)):
result_str += f"{clean_key}: {value:.4f}\n"
else:
result_str += f"{clean_key}: {value}\n"
else:
result_str = f"## {supported_indicators[indicator.lower()]} for {symbol}:\n{str(data)}"
# Add the indicator description
result_str += f"\n\n{indicator_descriptions.get(indicator.lower(), 'No description available.')}"
return result_str
except requests.exceptions.RequestException as e:
return f"Error fetching data from TAAPI.io: {str(e)}"
except ValueError as e:
return f"Error parsing response from TAAPI.io: {str(e)}"
except KeyError as e:
return f"Error: Missing expected field in API response: {str(e)}"
except Exception as e:
return f"Unexpected error: {str(e)}"

View File

@ -22,7 +22,7 @@ DEFAULT_CONFIG = {
"data_vendors": {
"core_crypto_apis": "binance", # Options: binance
"core_stock_apis": "yfinance", # Options: yfinance, alpha_vantage, local
"technical_indicators": "yfinance", # Options: yfinance, alpha_vantage, local
"technical_indicators": "taapi", # Options: taapi
"fundamental_data": "alpha_vantage", # Options: openai, alpha_vantage, local
"news_data": "alpha_vantage", # Options: openai, alpha_vantage, google, local
},
@ -31,4 +31,8 @@ DEFAULT_CONFIG = {
# Example: "get_stock_data": "alpha_vantage", # Override category default
# Example: "get_news": "openai", # Override category default
},
# Tool provider settings
"tool_providers": {
"TAAPI_BASE_URL": "https://api.taapi.io",
}
}

View File

@ -22,7 +22,7 @@ class Propagator:
return {
"messages": [("human", ticker)],
"company_of_interest": ticker,
"coin_of_interest": ticker,
"ticker_of_interest": ticker,
"trade_date": str(trade_date),
"investment_debate_state": InvestDebateState(
{"history": "", "current_response": "", "count": 0}