Investing a percentage of balance

Is there a way to only invest 1% of your Alpaca balance instead having the qty as a whole number?
something like
“qty”: balance * .01 ,
instead of
“qty”: 1,

1 Like

I agree, will be a very usefoul function, I would consider 3 options pct of whole account, pct of buying power, pct of cash

Hey Mike_Oxsmall (condolences BTW :joy:),

You could do something like this:

def calculate_funds_for_trade(_percentage):
    trade_amount = round(float( * _percentage, 2)
    # This will calculate the given percentage of your account cash (0.02 = 2%, 0.1 = 10% etc.)
    # The calculated number is rounded to 2 decimal places.
    # You could use (account.buying_power) instead of cash, if you want.
    print(f'Amount allocated per trade: ${trade_amount}')
    return trade_amount

def get_latest_price(_symbol):
    bar = api.get_latest_bar(_symbol)
    # return the latest Close price
    return bar.c

# Call this to place the order. If the asset can be traded with fractional quantities, just use the calculated trade amount. Otherwise, use integer division to find the largest whole number that your funds will allow.
def buy_order(_symbol):
    asset = api.get_asset(_symbol)
    if asset.tradable: # First, check if the asset is actually tradable.
        if asset.fractionable: # Then check if the asset allows fractional orders.
            order = api.submit_order(
                notional=str(calculate_funds_for_trade(0.01)), # 1%
            order = api.submit_order(
                qty=str(int(calculate_funds_for_trade(0.01) // get_latest_price(_symbol))),
                # The // operator is used in integer division and will return only the whole number (not the remainder).
        print('Order submitted!')
        return order
    print(f'Order not submitted. {_symbol} is not tradable!')
    return None
1 Like

Thanks Mike, very usefoul !

1 Like