Skip to main content
Glama

get_latest_market_data

Retrieve real-time stock data for specified codes and periods using the XTQuantAI MCP server, enabling AI-driven access to trading insights.

Instructions

获取最新行情数据

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codesYes股票代码列表,用逗号分隔,例如 "000001.SZ,600519.SH"
periodNo周期,例如 "1d", "1m", "5m" 等1d

Implementation Reference

  • The core handler function that implements the get_latest_market_data tool logic. It parses input codes, validates them, initializes xtdata if needed, calls xtdata.get_market_data with count=1 for latest data, processes the response (converting numpy arrays to lists), and returns the result or error.
    async def get_latest_market_data(input: GetMarketDataInput) -> Dict[str, Any]:
        """
        获取最新行情数据
        
        Args:
            codes: 股票代码列表,用逗号分隔,例如 "000001.SZ,600519.SH"
            period: 周期,例如 "1d", "1m", "5m" 等
            
        Returns:
            最新行情数据
        """
        try:
            # 确保XTQuant数据中心已初始化
            ensure_xtdc_initialized()
            
            if xtdata is None:
                return {"error": "xtdata模块未正确加载"}
            
            # 解析股票代码列表
            codes = [code.strip() for code in input.codes.split(",") if code.strip()]
            if not codes:
                return {"error": "未提供有效的股票代码"}
            
            # 过滤有效的股票代码
            valid_codes = []
            for code in codes:
                # 检查股票代码格式
                if "." in code and len(code) >= 6:
                    valid_codes.append(code)
            
            if not valid_codes:
                return {"error": "未提供有效的股票代码"}
            
            print(f"获取最新行情数据: 股票={valid_codes}, 周期={input.period}")
            
            try:
                # 获取最新行情数据
                print(f"调用xtdata.get_market_data([], {valid_codes}, {input.period}, count=1)")
                data = xtdata.get_market_data(["open", "high", "low", "close", "volume"], valid_codes, period=input.period, count=1)
                
                # 处理返回值
                if data is None:
                    return {"error": "获取最新行情数据失败"}
                
                # 将数据转换为可序列化的格式
                result = {}
                for code, stock_data in data.items():
                    code_result = {}
                    for field, values in stock_data.items():
                        # 将numpy数组转换为列表
                        if hasattr(values, "tolist"):
                            code_result[field] = values.tolist()
                        else:
                            code_result[field] = list(values)
                    result[code] = code_result
                
                return result
            except Exception as e:
                print(f"获取最新行情数据出错: {str(e)}")
                traceback.print_exc()
                return {"error": f"获取最新行情数据失败: {str(e)}"}
        except Exception as e:
            print(f"处理最新行情数据请求出错: {str(e)}")
            traceback.print_exc()
            return {"error": str(e)}
  • Pydantic input schema (BaseModel) used for validating the tool's input parameters. Note: shared with other market data tools like get_history_market_data.
    class GetMarketDataInput(BaseModel):
        codes: str  # 股票代码列表,用逗号分隔,例如 "000001.SZ,600519.SH"
        period: str = "1d"  # 周期,例如 "1d", "1m", "5m" 等
        start_date: str = ""  # 开始日期,格式为 "YYYYMMDD"
        end_date: str = ""  # 结束日期,格式为 "YYYYMMDD",为空表示当前日期
        fields: str = ""  # 字段列表,用逗号分隔,为空表示所有字段
  • Tool registration in the handle_list_tools() function, defining the tool name, description, and input schema for MCP.
    types.Tool(
        name="get_latest_market_data",
        description="获取最新行情数据",
        inputSchema={
            "type": "object",
            "properties": {
                "codes": {
                    "type": "string",
                    "description": "股票代码列表,用逗号分隔,例如 \"000001.SZ,600519.SH\""
                },
                "period": {
                    "type": "string",
                    "description": "周期,例如 \"1d\", \"1m\", \"5m\" 等",
                    "default": "1d"
                }
            },
            "required": ["codes"]
        }
    ),
  • Dispatch logic in the MCP @server.call_tool() handler that parses arguments, creates the input model, calls the specific get_latest_market_data function, and formats the response as text content.
    elif name == "get_latest_market_data":
        if not arguments or "codes" not in arguments:
            return [types.TextContent(type="text", text="错误: 缺少必要参数 'codes'")]
        
        # 处理字符串格式的codes参数
        codes_str = arguments["codes"]
        codes = [code.strip() for code in codes_str.split(",") if code.strip()]
        
        period = arguments.get("period", "1d")
        
        input_model = GetMarketDataInput(codes=codes_str, period=period)
        result = await get_latest_market_data(input_model)
        return [types.TextContent(type="text", text=json.dumps(result, ensure_ascii=False, indent=2))]
Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/dfkai/xtquantai'

If you have feedback or need assistance with the MCP directory API, please join our Discord server