-1

I am looking to send a POST request using Python to the OANDA API to open an order. They do not have a Python wrapper and use cURL, so I have had to try and convert from cURL to Python. I have done so using https://curl.trillworks.com/ -- but converting this next one does not work.

You can view the OANDA API documentation here, under the first Green POST tab - http://developer.oanda.com/rest-live-v20/order-ep/

Here is what I am working with. This first block specifies the order details. In this case, a market order in the EUR_USD instrument with a quantity of 100 units and a time in force equalling "fill or kill" :

body=$(cat << EOF
{
  "order": {
    "units": "100",
    "instrument": "EUR_USD",
    "timeInForce": "FOK",
    "type": "MARKET",
    "positionFill": "DEFAULT"
  }
}
EOF
)
curl \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer SECRET TOKEN" \
  -d "$body" \
  "https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders"

Converted into Python:

import requests

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer SECRET TOKEN',
}

data = '$body'

response = requests.post('https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders', headers=headers, data=data)

As you can see, I believe there is a formatting error somewhere in the "body=$" portion, but I am not entirely sure. I simply get a 400 error, "invalid values."

  • Are you asking [How to access environment variable values?](https://stackoverflow.com/questions/4906977/how-to-access-environment-variable-values) – Brad Solomon May 27 '19 at 20:34
  • Well, the message I got was: `'{"errorMessage":"Invalid value specified for \'accountID\'"}'` Maybe you just need to put you credentials inside the post. – Victor Hugo Borges May 27 '19 at 20:35
  • `"$body"` is accessing a variable in bash that doesn't exist in your Python code. – jpmc26 May 27 '19 at 21:07
  • they do not have a python wrapper ? There are 2: v20 and oandapyV20 – hootnot Jun 02 '19 at 22:38

1 Answers1

1

If you're sending data in JSON format, you should pass them into json argument instead of data (explanation, method).

import requests

headers = {
    # 'Content-Type': 'application/json', # will be set automatically
    'Authorization': 'Bearer SECRET TOKEN',
}

body = {
  "order": {
    "units": "100",
    "instrument": "EUR_USD",
    "timeInForce": "FOK",
    "type": "MARKET",
    "positionFill": "DEFAULT"
  }
}

response = requests.post('https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders', 
                         headers=headers, json=body)
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
  • @MargeJohns, you're welcome. You can [select](https://stackoverflow.com/help/someone-answers) this answer if it solved your problem. – Olvin Roght May 27 '19 at 20:48