Auto-calculate amount of Futures contracts I can buy with my balance?


New member
Hi All,

I'm trying to come up with an automatic way to tell me how much futures I can buy with my current balance/margin balance.
Futures act differently than regular stocks, so the market price isn't really the price it will cost to buy a margin, but rather the margin requirement needs to be calculated. any suggestions on which variables to use inside thinkscript? I can't find one that will give me what I need.



I just have $2000 in my account per MES contract. That way if the price goes in the opposite direction I can go negative for a bit without getting margin called.


Active member
The GetTotalCash() function will get your cash balance. I only trade stocks so I'm not familiar with whatever might be different for futures. I hacked up parts of one of my scripts to give you the pieces I think you need. You may need to adjust for your buying power.

input accountBalanceFallback = 0; # used in OnDemand or if premarket data not on
input accountBalanceOverride = 0; # if you want to force a lower value

# reminder = GetTotalCash only works with premarket data on
def cash = GetTotalCash();
# reminder = GetTotalCash only works with premarket data on
def accountBalance =
  if accountBalanceOverride > 0 then accountBalanceOverride
  else if !IsNaN(cash) then cash
  else accountBalanceFallback

def buyingPower = accountBalance * 4;
def buyPowerMaxShares = RoundDown(buyingPower / close, 0);

AddLabel(yes, "Contracts: " + buyPowerMaxShares);

If the cash balance isn't relevant GetNetLiq() will get the total value of your account which you can then multiply by your margin to get total buying power. For buying power already used you can get the sizes of your open positions using GetQuantity( Symbol symbol) and try to calculate how much margin is used by those and then subtract from your total buying power.
Last edited:

Similar threads