MJ F.
MJ F.

Reputation: 53

Julia API Call to Alpaca trading receives HTTP/1.1 401 Unauthorized

First time asking a question here. Hoping I do this right!

I've recently heard of Alpaca for algorithmic trading, and thought it would be a cool opportunity to learn Julia and try to get an algo working! Super excited, but running into some trouble getting the initial API call to work.

I'm hung up on the initial API HTTP request for authorization. My account is set up and approved. I've been able to get it to work with the Python library: alpaca-trade-api, but have not had luck with a simple Julia HTTP GET request. Same keys, same domain, but Julia gives an "unauthorized" error.

Link to API documentation: https://docs.alpaca.markets/web-api/

Here's the code I'm using:

using HTTP
using JSON

key = Dict("APCA-API-KEY-ID" => "my_key")
secret_key = Dict("APCA-API-SECRET-KEY" => "my_secret_key")
params = merge(key,secret_key)

base_url = "https://paper-api.alpaca.markets"
endpoint = "/v1/account"
url = base_url * endpoint

api = HTTP.request(
    "GET",
    url,
    ["Content-Type" => "application/json"],
    JSON.json(params)
    )

And I get the error: "code":40110000,"message":"access key verification failed : access key not found (Code = 40110000)

Unsure if it has to do with the format in which I'm submitting my keys, but I've tried just using the dictionary as the argument, or defining "headers=params" and that didn't work either. Same error.

Curious if anyone else has experience with getting Alpaca working with Julia, or has insight into why this wouldn't be working.

Upvotes: 1

Views: 1748

Answers (2)

Alex338207
Alex338207

Reputation: 1905

From the linked documentation, you see the corresponding curl command:

curl -X GET \
   -H "APCA-API-KEY-ID: {YOUR_API_KEY_ID}" \
   -H "APCA-API-SECRET-KEY: {YOUR_API_SECRET_KEY}"\
   https://{apiserver_domain}/v1/account

The option -H, means header. So the keys must go in the header, i.e. the 3rd parameter of HTTP.request (https://juliaweb.github.io/HTTP.jl/stable/index.html#Requests-1):

api = HTTP.request(
   "GET",
   url,
   ["Content-Type" => "application/json",
    "APCA-API-KEY-ID => "YOUR_API_KEY_ID", 
    "APCA-API-SECRET-KEY => "YOUR_API_SECRET_KEY" ]
)

You should replace YOUR_API_KEY_ID and YOUR_API_SECRET_KEY by your credientials.

Upvotes: 2

user10678933
user10678933

Reputation: 46

I just resolved a similar issue using PyLiveTrader, although that uses a config.yaml for the API keys. I was able to solve it by using the proper syntax for yaml (four spaces after colon), as well as making sure that I was using the paper key when using the paper base_url (originally I had the regular base_url). Best of luck! (I'm very new to this, so sorry if this isn't helpful).

Upvotes: 3

Related Questions