Mike C.
Mike C.

Reputation: 1921

Trying to place an order on Oanda using Python Requests. Getting JSON error

I am trying to place an Fx order using Python and the Oanda api.

from requests import post

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer <auth code>"
}
data = {
    "order": {
        "units": "100",
        "instrument": "EUR_USD",
        "timeInForce": "FOK",
        "type": "MARKET",
        "positionFill": "DEFAULT"
    }
}

#Practice Account
r = post(
    "https://api-fxpractice.oanda.com/v3/accounts/<acct #>/orders",
    headers=headers,
    data=data
)
print(r.text)

I get the following error:

Invalid JSON, ParseErrorCode: 3, Message: Invalid value.

Does anyone know what the error means?

Here is the example CURL code from their website:

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 <AUTHENTICATION TOKEN>" \
  -d "$body" \
  "https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"

Upvotes: 4

Views: 645

Answers (1)

Mike C.
Mike C.

Reputation: 1921

You must encode the dictionary with json.dumps. I also removed the quotes from the value.

Here's the code:

from requests import post
import json

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer <auth code>"
}
data = {
    "order": {
        "units": 10,
        "instrument": "EUR_USD",        
        "timeInForce": "FOK",
        "type": "MARKET",
        "positionFill": "DEFAULT"
    }
}
data = json.dumps(data)
#Practice Account
r = post(
    "https://api-fxpractice.oanda.com/v3/accounts/<acct #>/orders",
    headers=headers,
    data=data
)
print(r.text)

Upvotes: 4

Related Questions