0

While trying to connect to an API from Alpaca (a broker that accepts automated orders), I found that I was unable to send data with the requests.delete method. Here is some code:

def close_position(symbol, percentage, api_key=api_key, secret_key=secret_key, base_url=base_url):
    data = {"percentage": percentage}
    headers = {
        "APCA-API-KEY-ID": api_key,
        "APCA-API-SECRET-KEY": secret_key
    }
    url = f"{base_url}/v2/positions/{symbol}"
    order = requests.delete(url, json=data, headers=headers)
    return order.json()

This code is supposed to close (i.e., liquidate) a specified percentage of a position. However, it seems that the data sent using the delete method is disregarded; this function always closes my entire position instead of the specified percentage. Here is the documentation for the Alpaca API: https://alpaca.markets/docs/api-references/trading-api/positions/#close-a-position

I have also tried the data and params parameter and json.dumps(data), but to no avail.

Any idea how to send data with the requests.delete method would be appreciated.

  • 1
    The documentation does not say whether the "query parameters" are supposed to be passed as JSON in HTTP data or as part of the URL. If you add `"?percentage={percentage}"` to the URL, does it work? – Tim Roberts Oct 31 '22 at 16:44
  • @TimRoberts, how could I not have thought of that! Thanks a million; this works. – Value_Investor Oct 31 '22 at 17:03

0 Answers0