我在第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,謝謝
ringa_lee2017-06-12 09:29:26
你的程式碼寫的有問題
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) #卖