json - python連oanda的模擬交易api下訂單問題第三問
为情所困
为情所困 2017-05-18 10:54:22
0
2
1044

這次我想以現時市價買進50份USD_CAD合約
程式:
import requests
import json

顯示目前USD_CAD的匯率------------------------------------------ ------------------------------------------------

url = 'https://api-fxpractice.oanda....'
instruments = 'USD_CAD'
account_id = 'cawa11' #使用者名稱
params = {'instruments':instruments ,'accountId':account_id}
access_token = 'a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380'
keners ='urla_vv. ers = headers, params=params )
price = r.json()
print(price)

以現時市價買進50份USD_CAD合約------------------------------------- --------------------------------------------

url = 'https://api-fxpractice.oanda....' #5898545為帳號101-011-5898545-001的一部分

headers = {'Content-Type' : 'application/x- www-form-urlencoded','Authorization':'Bearer ' access_token}
data = {'instrument':'USD_CAD','accountId':'cawa11','units':50,'type':'market ','side':'buy'}
req = requests.post(url,data=data,headers=headers)
print(req.text)
print(req.json())

第二段程式回報錯誤:

{"code" : 4,"message" : "The access token provided does not allow this request to be made","moreInfo":"http://developer.oanda .com/docs/v1/auth/#overview"}
{'message': 'The access token provided does not allow this request to be made', 'moreInfo': 'http://developer.oanda.com /do...', 'code': 4}
但透過第一段程式的正常運作access token是沒有問題的,同時http://developer.oanda.com/do...中錯誤列表錯誤列表

HTTP状态代码 HTTP状态消息 信息                        详细说明
    4           401       擅自 提供不允许该请求的访问令牌进行 确保与请求提供的访问令牌是正确的,是有效的。请参阅认证以获取更多细节。
    

附上一份oanda公司的文件:

import http.client
import urllib
import json
import datetime

該檔案包含一些非常簡單的對OANDA API的呼叫

這表示如果超過閾值,則取得儀器的當前價格並進行交易

def checkAndTrade():

conn = httplib.HTTPSConnection("api-sandbox.oanda.com")
conn.request("GET", "/v1/prices?instruments=USD_CAD")
response = conn.getresponse()
resptext = response.read()
if response.status == 200:
    data = json.loads(resptext)
    if data['prices'][0]['ask'] > 0.994:
        headers = {"Content-Type" : "application/x-www-form-urlencoded"}
        params = urllib.urlencode({"instrument" : "USD_CAD",
                                   "units" : 50,
                                   "type" : 'market',
                                   "side" : "buy"})
        conn.request("POST", "/v1/accounts/8026346/orders", params, headers)
        print(conn.getresponse().read())
else:
    print(resptext)

這樣設定了與上述價格相同的訂單,當價格跨越0.994時將執行交易

def order():

now = datetime.datetime.now()
expire = now + datetime.timedelta(days=1)
expire = expire.isoformat('T') + "Z"    
conn = httplib.HTTPSConnection("api-sandbox.oanda.com")
params = urllib.urlencode({"instrument": "USD_CAD",
                           "units" : 50,
                           "price" : 0.994,
                           "expiry" : expire,
                           "side" : "buy",
                           "type" : "limit"})
headers = {"Content-Type" : "application/x-www-form-urlencoded"}
conn.request("POST", "/v1/accounts/8026346/orders", params, headers)
print(conn.getresponse().read())

order()

checkAndTrade()
此程式可能時間比較久其api位址與現在的api位址不同

为情所困
为情所困

全部回覆(2)
某草草

帳戶有權限讀取數據,不一定有權限下單
你現在的問題都是api裡的東西,應該仔細研究api文檔,不然你後面會遇到無數類似的問題

除非剛好有人對這份api熟悉,不然也給不了你什麼幫助
================ =========
如果你是從網站下單監聽的話你就會發現你的url和data完全和網站的不一樣

import requests

access_token = '81e6f8b8ae23d2c0122cfee68cd26fc2-5681d2e539e0c8d01925bad19ff141f5'
url = 'https://api-fxpractice.oanda.com/v3/accounts/101-011-5898545-001/orders'
headers = {'Content-Type' : 'application/json','Authorization':'Bearer '+access_token}
data = {"order":{"instrument":"EUR_USD","type":"MARKET","units":"1"}}
req = requests.post(url,json=data,headers=headers)
print(req.text)

================================================= ==================

伊谢尔伦

@prolifes:

test.py---------------------------------------------- ------------ ------------ --------

from vnoanda import OandaApi
if name == '__main__':

雷雷

vnoanda.py---------------------------------------------- ----------- ------------ ----------------

編碼:utf-8

導入json
導入請求
from Queue import Queue, Empty
from threading import Thread

API_SETTING = {}
API_SETTING['practice'] = {'rest': 'https://api-fxpractice.oanda.com','stream': 'https://stream-fxpractice.oan...' }
API_SETTING['trade'] = {'rest': 'https://api-fxtrade.oanda.com','stream': 'https://stream-fxtrade.oanda....'}

FUNCTIONCODE_GETINSTRUMENTS = 0
FUNCTIONCODE_GETPRICES = 1
FUNCTIONCODE_GETPRICEHISTORY = 2
FUNCTIONCODE_GETACCOUNTS = 30_FACCTIONDCOUp_F​​DTet_FNP​​3_FACC_FNP_F_F​​ET_FTin_Fonep. DE_SENDORDER = 6
FUNCTION CODE_GETORDERINFO = 7
FUNCTIONCODE_MODIFYORDER = 8
FUNCTIONCODE_CANCELORDER = 9
FUNCTIONCODE_GETTRADES = 10
🎝 FUNCTIONCODE_MODIFYTRADE = 12
FUNCTIONCODE_CLOSETRADE = 13
FUNCTIONCODE_GETPOSITIONS = 14
FUNCTIONCODE_GETPOSITIONINFO= 15FFUNCTIONCODE_F5FUNCDCODE_F54AUNCSNP_F5_FUNC_CODE_FITSITTION TIONCODE_GETTRANSACTIONINFO = 18
FUNCTIONCODE_GETACCOUNTHISTORY = 19
FUNCTIONCODE_GETCALENDAR = 20
FUNCTIONCODE_GETPOSITIONRATIOS = 21
. FUNCTIONCODE_GETORDERBOOK = 24
FUNCTIONCODE_GETAUTOCHARTIST = 25
FUNCTIONCODE_STREAMPRICES = 26
FUNCTIONCODE_STREAMEVENTS = 27

OandaApi 類別(物件):
雷雷

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!