Skip to content

Instantly share code, notes, and snippets.

@McKlayne
Created August 28, 2021 19:10
Show Gist options
  • Save McKlayne/685d6cf9adca86635104a3a9be3b204b to your computer and use it in GitHub Desktop.
Save McKlayne/685d6cf9adca86635104a3a9be3b204b to your computer and use it in GitHub Desktop.
def fractional_shares_order(symbol, side, notional, amount, api_key, api_secret, endpoint):
"""
A function to programatically purchase fractional shares leveraging the alpaca api
Parameters
----------
symbol : str, required
side: str, 'buy' or "sell"
notional: boolean, if True = notional, if False = fractional of a qty
amount: str, If notional is true, a dollar amount. If notional is false, a fraction of a qty
api_key: str, alpaca_api_key
api_secret: str, alpaca_api_secret
endpoint: str, alpaca_endpoint_url, paper vs. live url
Output
------
order_message: json, what was returned from posting to the alpaca API with our json body, or order request.
"""
#boolean for notional. If true, purchase a notional amount. ie $10,000
if notional == True:
data = {
"symbol":symbol,
"notional":amount,
"side":side,
"type":"market",
"time_in_force":"day"
}
#if false, purchase a qty amount. i.e 1.5 shares of a stock
else:
data = {
"symbol":symbol,
"qty":amount,
"side":side,
"type":"market",
"time_in_force":"day"
}
#auth bearer headers
headers = {'APCA-API-KEY-ID':api_key,'APCA-API-SECRET-KEY':api_secret}
#make the API Raw Request and capture the json body from it
order_message = requests.post(endpoint, json=data, headers=headers).json()
return order_message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment