python3.x - python连oanda的模拟交易api获取json问题第六问
PHP中文网
PHP中文网 2017-06-12 09:27:26
0
1
952

我在第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 requests

def 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,谢谢

PHP中文网
PHP中文网

认证0级讲师

全部回复(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-8

import requests

def 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)    #卖
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板