Is there a formula on how to buy the biggest amount possible of a given stock compiled to margin fees?

Let’s say account equity is $100,000, the margin is 4x.

What I need: a quick formula that automatically checks account balance in real-time, then buys the biggest amount possible of a given stock compiled to margin fees.

Thanks in advance!

In php i do a simple estimation and it works for what im doing
it will need a input in each variable, its self explanatory.

FUNCTION MAX_QTY (
//the balance you have in alpaca 	
$CASH_BAL = null,
//a value 0.01 - 0.99 (01%- 99%) i use 80%
$min_investing_Percent = null,
//the price of the stock ($1.00)
$the_price_now = null
){
//this is the max amount im willing to spend on this stock
$max_money_out            = $CASH_BAL        * $min_investing_Percent; 
//this is the max amount of stock i can buy (QTY)
$MAX_STOCK_QTY       = $max_money_out   / $the_price_now;            

$STOCK_QTY_I_CAN_BUY =  round( $MAX_STOCK_QTY, 0, PHP_ROUND_HALF_DOWN );
return $STOCK_QTY_I_CAN_BUY;
}
//try it, it should return 8
echo MAX_QTY(1.00,0.80,0.10);