python3.x - python连oanda的模拟交易api获取json问题第六问
问题描述
我在第3问中通过大家的帮助解决了下单的问题,但是在今天进行对历史数据测试时,发现了一个奇怪的事情。我要对6种货币对进行操作(GBP_USD、EUR_USD、USD_CAD和USD_CHF、USD_JPY、AUD_USD),想让GBP_USD、EUR_USD、USD_CAD在下买单时买,让USD_CHF、USD_JPY、AUD_USD在下买单时卖,开始几次交易没有问题,但在尝试过一次在下买单时卖后,GBP_USD、EUR_USD、USD_CAD也变成了在下买单时卖,程序如下:
import requestsdef trade(action,pairs,unit='1'): account_id = ’101-011-5898545-001’ access_token = ’33c7d4049fe8720c37918482bc830c12-06467701c963e60220d7e18436f3225d’ url = ’https://api-fxpractice.oanda.com/v3/accounts/’+account_id+’/orders’ headers = {’Content-Type’ : ’application/json’,’Authorization’:’Bearer ’+access_token}if pairs == 'GBP_USD' or 'EUR_USD' or 'AUD_USD' :if action == 'buy' : data = {'order':{'instrument':pairs,'type':'MARKET','units':unit}}if action == 'sell' : data = {'order':{'instrument':pairs,'type':'MARKET','units':'-'+unit}}if pairs == 'USD_CHF' or 'USD_JPY' or 'USD_CAD' :if action == 'buy' : data = {'order':{'instrument':pairs,'type':'MARKET','units':'-'+unit}}if action == 'sell' : data = {'order':{'instrument':pairs,'type':'MARKET','units':unit}}req = requests.post(url,json=data,headers=headers) #print(req.text)if __name__==’__main__’ : trade('buy','GBP_USD','3')
交易情况请在https://trade.oanda.com/查看,用户名:cawa11,密码:1122334455,谢谢
问题解答
回答1:你的代码写的有问题
if pairs == 'GBP_USD' or 'EUR_USD' or 'AUD_USD'应该改成if pairs == 'GBP_USD' or pairs == 'EUR_USD' or pairs == 'AUD_USD'但我更推荐你这样写if pairs in ['GBP_USD', 'EUR_USD', 'AUD_USD']
你的代码完全可以精简成这样,买单、卖单用unit为正还是为负来判定:
# coding: utf-8import requestsdef trade(pairs, unit=1): account_id = ’101-011-5898545-001’ access_token = ’33c7d4049fe8720c37918482bc830c12-06467701c963e60220d7e18436f3225d’ url = ’https://api-fxpractice.oanda.com/v3/accounts/’+account_id+’/orders’ headers = {’Content-Type’ : ’application/json’,’Authorization’:’Bearer ’+access_token}#你逻辑里只提到当货币为['USD_CHF', 'USD_JPY', 'USD_CAD']时,只要是买单就要变成卖单 if pairs in ['USD_CHF', 'USD_JPY', 'USD_CAD'] and unit > 0:unit *= -1 data = {'order':{'instrument':pairs,'type':'MARKET','units':unit}} req = requests.post(url,json=data,headers=headers) #print(req.text)if __name__==’__main__’ : trade('GBP_USD', 1) #买 trade('GBP_USD', -1) #卖
相关文章:
1. linux - 【已解决】fabric部署的Python项目Apache启动之后提示403Forbidden该如何解决?2. python - (初学者)代码运行不起来,求指导,谢谢!3. mysql里的大表用mycat做水平拆分,是不是要先手动分好,再配置mycat4. window下mysql中文乱码怎么解决??5. python - flask sqlalchemy signals 无法触发6. nginx - pip install python库报错7. python - 获取到的数据生成新的mysql表8. python的文件读写问题?9. javascript - js 对中文进行MD5加密和python结果不一样。10. 为什么python中实例检查推荐使用isinstance而不是type?
