Prevent to buy more (using margin) from the equity with IBcontroller


I use automatic trading with margin account type. unfortunately the purchases often exceed my capital and in my opinion this is dangerous and should be prevented.

  1. Some of the options that I have done are asking my broker (IBKR) to turn off the margin feature but still using a margin account (not a cash account), but that doesn't seem possible (please let me know if this is possible).

  2. By preventing purchases from the algo If equity = 0, then don't buy again. Maybe by asking for info by using ibc.GetAccountValue, The problem is that things like this have to be done in realtime with money and events that are a bit difficult, So I want to ask input from this forum.

How to insert If equity = 0, then don't buy again with ibc.GetAccountValue

if(LastValue(Buy) AND Position==0 AND transmit==1){         
  Price           = LastValue(C);        
  Position        = Max(round(Posisi_1/Harga_Terupdate),1);               
  orderid         = Panggil_IBController.PlaceOrder( Name(), "BUY", Posisi_1 , "MKT", 0, 0, "GTC", Transmit );         
  StaticVarSet(Symbol + "Shares", Shares, True);         
  Posisi_Open1    = 1;         
  StaticVarSet(Symbol + "Posisi_Open1", 1, True);         
  Trade           = Trade+1;         
  StaticVarSet(Symbol + "Trade",Trade, True);         
  price           = LastValue(C);         
  StaticVarSet(Symbol + "buyprice",buyprice, True);         

Thank you for your attention

Hi @ibenxs ,
tthere's no easy soluton with IBController for general instruments (you need to fetch margins). Hopefully it's easier for shares as margin can be computed by user (I also guess you haven't opted for IBKR portfolio margin).
Use some piece of code like:

// shares == number of shares to buy
sharesValue = shares * LastValue(C); // or LastValue(Foreign(ticker, "Close")) in general
maxLeverage = Param("Max Leverage", 4, 1, 5, 0.5); // 5 is max in most cases, 1 means no leverage
requiredCash = sharesValue/maxLeverage; // <= stocks margin
availableFunds = ibc.GetAccountValue("AvailableFunds"); // or "CashBalance" or "TotalCashBalance"
// Additional condition for buying: (requiredCash <= availableFunds)

Caveat: account values are not updated in real-time, only every few minutes (3 ?), so your order may be rejected if you send several buy orders quickly. If you want to be sure, keep track of all your positions size (see code in IBController doc), compute their market value, and deduce it from initial cash balance (as above). I guess it's overkill here though.


PS: you're over-leveraged, it's a recipe for disaster (a friendly warning)
PPS: IBKR notes about margins may help you Understanding IB Margin Webinar Notes | Interactive Brokers LLC

1 Like