You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写算法交易Python代码时遭遇Oandapy API AttributeError错误

解决oandapy模块的AttributeError: 'module' has no attribute 'API'问题

你碰到的这个报错,核心原因是你用的oandapy包已经过时,和OANDA当前主推的API版本完全不兼容。下面给你一步步拆解解决方法和背后的原因:

问题根源

原来的oandapy是针对OANDA旧版v1 API开发的库,现在已经停止维护了,它的类结构和你代码里调用的API类根本对不上。现在OANDA官方推荐使用V20版本的API,对应的Python专属库是oandapyV20——这才是你应该用的工具。

解决步骤

  1. 卸载旧的oandapy包
    打开终端执行:

    pip uninstall oandapy
    
  2. 安装正确的oandapyV20库
    运行安装命令:

    pip install oandapyV20
    
  3. 修改代码适配V20版本
    调整后的可用代码示例:

    import configparser
    from oandapyV20 import API
    from oandapyV20.exceptions import V20Error
    
    # 读取配置文件
    config = configparser.ConfigParser()
    config.read("oanda.cfg")
    
    # 初始化V20 API客户端
    oanda = API(access_token=config["oanda"]["access_token"], environment="practice")
    

    要是你的oanda.cfg里存了账户ID,后续调用接口(比如查账户、下单)会用到,这里给你加个获取账户详情的示例参考:

    import oandapyV20.endpoints.accounts as accounts
    
    # 构造账户详情请求
    account_id = config["oanda"]["account_id"]
    r = accounts.AccountDetails(accountID=account_id)
    
    # 发送请求并处理响应
    try:
        response = oanda.request(r)
        print("账户详情:", response)
    except V20Error as err:
        print("请求出错:", err)
    
  4. 确认你的oanda.cfg格式正确
    配置文件得是标准INI格式,示例如下:

    [oanda]
    access_token = 你的实际访问令牌
    account_id = 你的实际账户ID
    environment = practice
    

额外提示

如果你非要用旧版oandapy(非常不推荐,旧API随时可能被停用),得确保装的是正确的旧版本,而且调用方式要改成oandapy.oandapy.API()——但真心建议你直接升级到V20版本,省得后续再踩更多兼容性的坑。

内容的提问来源于stack exchange,提问作者Moet Mills

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:13:29