I am developing a bot for Isolated Margin where I automatically add a “Stop Loss” position for every position to avoid liquidation.
Calculating the correct liquidation price for Isolated Margin is somewhat complicated due to the tiered system:
Tiered Leverage Function on Isolated Margin | Binance Support
The Query Isolated Margin Account Info in the API returns “liquidatePrice”:
Can I trust the value returned here for my Stop Loss position? I have done some trials, and the value I get is 99.9% equal to my calculations in all cases.
My questions are:
Can I trust the “liquidatePrice” as a basis for calculating the execution price for my Stop Loss positions?
Will Binance compensate an automatic liquidation if my API log shows that the API gave a wrong value, and I acted in good faith? I.e. I placed a Stop Loss position that was too low/high, based on the value I got from the Binance API.
I am aware that I must calculate in the interest on the loans, which will be added to the loans, a tiny fraction every hour.
To calculate the liquidation price, I solved the Margin Level equation in Maple (lazy me) for BTC/USDT Isolated Margin:
I then implemented the solution as a function in Python, to get the liquidation price:
def calculate_liquidation_price(USDT_balance, USDT_loan, BTC_balance, BTC_loan, margin_level):
a = USDT_loan * margin_level - USDT_balance
b = BTC_balance - BTC_loan * margin_level
if b == 0:
return a / b
I tested this with USDT 100 on Isolated Margin BTC/USDT throught the Binance API for different values of Long and Short positions with x4 leverage for both BTC and USDT. The resulting “liquidatePrice” values that I got back from Binance matched very well the results from the Python function with margin_level 1.05, as it should.
In the cases where the formula gave a negative price (which indicates that there is no need for a Stop Loss), Binance returned “liquidatePrice: 0". I find the choice of zero for negative values to be sound, as returning a negativ liquidation price would just create confusion.
Because the returned “liquidatePrice” value from Binance matches the formula so well, it is tempting to simply trust it instead of doing my own math every time I need to place a Stop Loss position.
I did some work in Maple to understand the liquidation formula for a situation where I have loans both for USDT and BTC in an Isolated Margin account. x4 leverage for both.
This gives an interesting result: For small Long positions, there is no need to place a Stop Loss position.
Bottom line is that the values that Binance returned when I tried this with real positions on my BTC/USDT Isolated Margin account matched the theoretical results 100%.