如何解决OANDA交易平台POST请求的"Invalid JSON body"错误?
OANDA POST请求报"Invalid JSON body"问题解决
问题根源分析
你的代码存在几个明确错误导致JSON格式无效:
requests.post的json参数使用错误
你用了json=json.dumps(formatted_order),但requests库的json参数直接接受Python字典对象,requests会自动将其序列化为标准JSON字符串并适配请求头。手动转成字符串后传给json参数,会导致请求体变成字符串嵌套的字符串,API解析时必然报错。时间格式不符合OANDA API要求
OANDA V20 API要求gtdTime必须是RFC3339格式(如"2024-09-27T21:00:00Z"),你使用的空格分隔格式"2024-09-27 21:00:00"会触发API格式验证失败,也可能被判定为无效JSON内容。代码中的全角空格
定义formatted_order时使用了全角空格(如"order":{中的空格),这会导致Python解析字典时出现语法错误,或生成的JSON包含非法字符,进而触发API的JSON解析错误。
修正后的代码
import requests def submit_order(): headers = { "Content-Type": "application/json", "Authorization": "Bearer " + "[你的访问令牌]" # 替换为实际令牌 } submit_order_path = "https://api-fxpractice.oanda.com/v3/accounts/[你的账户号]/orders" # 替换为实际账户号 formatted_order = { "order": { "type": "STOP", "instrument": "GBP_USD", "units": "10000", "price": "1.33606", "priceBound": "1.33606", "timeInForce": "GTD", "gtdTime": "2024-09-27T21:00:00Z", # 修正为RFC3339格式 "positionFill": "DEFAULT", "triggerCondition": "DEFAULT", "clientExtensions": { "id": "V-ALPHA", "tag": "V-ALPHA", "comment": "V-ALPHA" }, "takeProfitOnFill": { "price": "1.34374", "timeInForce": "GTD", "gtdTime": "2024-09-27T21:00:00Z" # 同上修正格式 }, "stopLossOnFill": { "price": "1.33016", "timeInForce": "GTD", "gtdTime": "2024-09-27T21:00:00Z" # 同上修正格式 }, "tradeClientExtensions": { "id": "V-ALPHA", "tag": "V-ALPHA", "comment": "V-ALPHA" } } } # 直接传字典给json参数,requests自动处理序列化 response = requests.post(url=submit_order_path, headers=headers, json=formatted_order) return response
额外验证步骤
- 可以先打印生成的JSON确认格式:
import json; print(json.dumps(formatted_order, indent=2)),检查是否有语法错误。 - 测试时可先简化订单结构,去掉
priceBound、clientExtensions等非必填字段,先确保基础订单提交成功,再逐步添加额外参数。
内容的提问来源于stack exchange,提问作者user16243249
相关产品推荐
相关产品推荐

