python3.x - python連oanda的模擬交易api取得json問題第六問
PHP中文网
PHP中文网 2017-06-12 09:27:26
0
1
933

我在第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)    #卖
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板