DEFI FINANCIAL MATHEMATICS AND MODELING

Building a Robust DeFi Financial Model for Borrowing and Liquidation

5 min read
#DeFi Modeling #Smart Contracts #Yield Farming #Borrowing #Liquidation
Building a Robust DeFi Financial Model for Borrowing and Liquidation

You’ve probably felt that whirlwind feeling that hits when you first read about borrowing against crypto—there’s a new protocol, a slick website, interest rates quoted in percentages that look oddly like a new form of mortgages, and the promise that you can finally put idle holdings to work. Behind that promise sits a delicate ballet of mechanics: the way interest accrues, how collateral value fluctuates, and the precise moment a lender decides something is “at risk” and seizes assets. Building a model that captures all those moments without turning into a spreadsheet nightmare is what we’ll walk through together.


The Anatomy of DeFi Borrowing

At a high level, borrowing in DeFi is a three‑step dance:

  1. Lock collateral – You deposit an asset into a smart contract, often an ERC‑20 token like USDC or a volatile coin like ETH.
  2. Draw a loan – The protocol lends you a different asset or the same asset, with a collateral ratio that protects the lender.
  3. Repay (plus interest) – You put the borrowed asset back, plus interest, and the smart contract releases your collateral.

What makes it special:

  • Interest is often variable and determined by on‑chain supply/demand. It changes continuously, not every 30 days like a traditional mortgage.
  • Collateral values are highly volatile. Even a 10% drop in price can bring you to the liquidation horizon.
  • Liquidation is instant. A smart contract can seize your collateral automatically when the ratio falls below a hard threshold.

Let’s unpack each piece.


Why Interest Rates Matter

Interest rates in DeFi are usually expressed in the form of an average daily rate R_daily. Every block, the protocol recalculates R_daily based on the total supply (S) and total borrowings (B). A simple linear model looks like:

R_daily = (α * B) / S
  • α is an amplification factor representing protocol risk appetite.
  • B and S are on‑chain variables that a model can pull directly.

In practice, protocols add caps or curves so that as borrowing loads increase, the rate accelerates. These curves help sustain the ecosystem when demand spikes.

Key point: Because rates shift every block, a model must capture a time series of rates, not just a single snapshot. If you hand someone a static spreadsheet showing one rate and tell them that’s enough to decide, you’re about to mislead.


Collateral Ratios: The Safety Net

Protocols set two important ratios:

  • Health Factor (HF): A continuous measure of how much your collateral covers your borrowings, often expressed in a form like HF = (CV * CR) / B, where CV is collateral value, CR is the collateral factor (often 0.75–0.85), and B is borrowed amount.
  • Liquidation Threshold (LT): The minimum ratio before liquidation triggers automatically, typically 0.8 or 0.85.

In the model, you’ll track:

  1. Collateral Value (CV) – The USD value of what you locked. This comes from oracles. Oracle uncertainty should be modeled by adding a volatility factor or a confidence interval.
  2. Borrowed Amount (B) – Current balance after interest accruals. Borrowed assets can also be volatile; their USD value will influence the loss in case of liquidation.
  3. Health Factor Projection – Predict how HF will evolve as price moves and rates change.

Emotion behind this: The HF is essentially the protocol’s way of saying, “If you keep this health factor, we’re comfortable; if it dips below this, we’ll protect our liquidity.” For you, it feels like watching the tide rise or fall, feeling your breath catch when the barometer approaches the warning line.


Liquidation Penalty and Bonus Mechanism

When HF < LT, the protocol initiates liquidation. Two key numbers:

  • Liquidation Penalty (Ppen) – A fee the lender takes to compensate for the risk of liquidation. Usually a percentage of the collateral value liquidated.
  • Liquidation Bonus (Pbon) – A discount given to the liquidator to incentivize them to step in. The bonus is typically a multiple of the penalty, like 20% extra.

In an economic sense, the net cost to the protocol per liquidation is:

Net Cost = Pbon - Ppen

If Net Cost < 0, the protocol actually gains from liquidation (unlikely but possible in some experiments).

Why is this important for modeling? Because the penalty feeds back into the borrower’s effective borrowing cost. If penalties are too high, borrowers will stay in the safe zone; if too low, the pool’s liquidity dries up.


Putting It All Together: Building the Model

1. Define the State Variables

Symbol Variable What it is Source
S Total supply Outstanding lendable tokens Chain data
B Total borrowings Outstanding borrowed tokens Chain data
R_daily Daily interest rate Protocol‑determined Protocol code
CV Collateral Value USD value of deposited collateral Oracle
CR Collateral factor Protocol‑set safety buffer Protocol rule
LT Liquidation threshold Minimum safe ratio Protocol rule
Ppen Penalty Penalty for liquidations Protocol rule
Pbon Bonus Bonus offered to liquidators Protocol rule
V Volatility Historical or implied volatility of asset Statistical analysis

2. Create the Dynamical Equations

  1. Interest Accrual – For each borrowing:
    dB/dt = B * R_daily
    
  2. Health Factor Evolution – Incorporate price dynamics dP:
    dHF/dt = (-B/V + CV * dP/(P * CR)) / B
    
    Here P is the asset price; V the volatility; the first term reflects growing debt, second term the rising collateral value if price goes up.
  3. Liquidation Trigger – An instant event when HF <= LT. The instantaneous penalty and bonus flows are:
    Penalty = CV * Ppen
    Bonus = CV * Pbon
    

3. Simulate with Monte Carlo

Because volatility is uncertain, run thousands of price paths (P_t) in a Monte Carlo framework:

  • At each step, sample a price move from a log‑normal distribution.
  • Compute CV_t, HF_t, B_t.
  • Record the fraction of paths that hit liquidation before a horizon T.

The output is a liquidation probability and a expected cost of borrowing when considering penalties.

4. Sensitivity Analysis

Key parameters to test:

  • Change in LT: Raising the threshold (say from 0.85 to 0.90) reduces liquidations but may reduce lending rewards.
  • Adjusting CR: A higher collateral factor (e.g., 0.8 vs 0.7) gives borrowers more breathing room.
  • Modifying Ppen: If penalty increases, borrowers may choose lower loans or diversify collateral.

Each scenario gives a realistic decision matrix.


A Practical Example: Borrowing Against ETH

Let’s walk through a concrete example. Suppose you lock 10 ETH (worth ~15,000 USD at the time) into a platform that:

  • CR = 0.75 (you can borrow up to 75 % of collateral value)
  • LT = 0.80
  • Ppen = 10 % (of liquidated collateral)
  • Pbon = 12 % (of liquidated collateral)

You borrow 10,000 USD worth of USDC (roughly 0.666 ETH at 15,000 USD). Your initial health factor:

HF_initial = (15,000 * 0.75) / 10,000 = 1.125

A 20 % drop in ETH price leads to CV = 12,000, so:

HF_dropped = (12,000 * 0.75) / 10,000 = 0.9

Still above LT. A 30 % drop pushes it to 10,500 CV:

HF_d1 = (10,500 * 0.75) / 10,000 = 0.7875

Now HF_d1 < LT, so liquidation triggers automatically. The protocol seizes 10,000 USD worth of collateral (about 0.666 ETH at the time) and charges a 10 % penalty ≈ 1,000 USD. However, the liquidator receives a 12 % bonus ≈ 1,200 USD, effectively giving the liquidator a 200 USD edge over the penalty. The net protocol cost is negative, which is why liquidation is profitable as a deterrent.

Your final loss, excluding penalty and bonus, is the difference between what you were owed (10,000 USD) and what you repaid (the 10,000 USD borrowed plus the accrued interest). The penalty and bonus adjust the borrower’s net cost but do not change the principal amount.


Why “Less About Timing, More About Time”

In a world where price shocks hit in seconds, you might think the magic is to time markets. But in DeFi borrowing, time is the governing factor. The longer you hold a loan, the more cumulative interest you pay, and the greater the chance of a price shock. Instead of chasing “the right moment to borrow or pay”, the model forces you to consider the duration of your exposure.

Your model should answer:

  • If I lock collateral for one month, what is the probability of liquidation?
  • If I aim to maintain an HF above 1.2, how much buffer do I need in collateral volatility?

You can compute these using the Monte Carlo framework or analytical approximations for log‑normal distribution tails.


Emotional Lens: The Psychology of Liquidation Risk

When you see a bar on your dashboard hover near the red line, fear can spike. That’s a normal response. But the numbers behind that bar are not just risk—they’re information telling you how much of a safety cushion you have. A robust model gives you a clearer picture, so the fear becomes a reason to adjust rather than a reflex to withdraw immediately.

Think of it like this: each asset you lock is a seed. The more water (collateral) and light (stable price), the better it grows. A sudden temperature drop (price crash) is a shock. How fast it will hit you depends on your watering schedule (collateral ratio) and the soil’s capacity to hold water (collateral factor). A good model tells you whether the soil will crack before you can plant more seeds.


Building the Spreadsheet (or Code)

Spreadsheet Quick‑Start

Row Description Formula
1 Total Supply S =QUERY(...)
2 Total Borrow B =QUERY(...)
3 Daily Rate R_daily =(α * B) / S
4 Collateral Value CV =B * current price
5 Health Factor =(CV * CR) / B
6 Liquidation? =IF(HealthFactor < LT, "YES", "NO")
7 Expected Penalty =CV * Ppen
8 Expected Bonus =CV * Pbon

Copy these across dates and let the spreadsheet roll forward. For volatility, use a simple rolling standard deviation of daily returns.

A Few Lines of Python

import numpy as np

# Parameters
CR   = 0.75
LT   = 0.80
Ppen = 0.10
Pbon = 0.12
alpha = 0.0005

# Simulate price path
T = 30  # days
price = 15000
prices = [price]
for _ in range(T):
    price *= np.exp(np.random.normal(-0.0002, 0.02))  # drift, vol
    prices.append(price)

# Calculate HF over time
S = 1e6   # supply
B = 1e4   # borrowed
CV = np.array(prices) * 10  # 10 ETH

hf = (CV * CR) / B
liquidation_flag = hf < LT

Run this and count the proportion of days where liquidation_flag is true for numerous iterations. That proportion is your liquidation probability over the horizon.


Tips for Practical Use

  1. Keep an eye on oracle reliability. If the price feed is delayed or manipulated, your CV can suddenly shrink, sparking a false liquidation.
  2. Diversify collateral if possible. Lending against a single volatile token magnifies risk. Some platforms allow multi‑collateral borrowing.
  3. Set alerts for when HF moves below 1.1 or 1.05. Early warnings give you time to add collateral or repay before hitting the LT.
  4. Use a “reserve” buffer: Borrow only 70-80 % of your available collateral value. That extra cushion can survive moderate swings.
  5. Understand the penalty and bonus. A high bonus may tempt you to liquidate on purpose to claim the reward—rare, but it matters for risk modeling.

Final Thought: Empathy in Numbers

Numbers in DeFi borrowing aren’t just abstract figures. They influence real lives: an emergency fund, a retirement plan, kids’ education savings. A robust model is a safety net that lets you ask, “What if the market takes a hit? How much will I lose? Which decisions can mitigate that?” That’s the why behind the math.

When building or reading a DeFi financial model, remember: the goal isn’t to predict the market’s next move perfectly; it’s to understand how much risk you’re taking on, how fragile that risk is, and whether the mechanics of the protocol help you stay on your path to freedom.

Let’s zoom out and view the whole picture. The interest rate, the collateral ratio, the liquidation penalty—they’re all pieces of a puzzle. A well‑compiled model fits them together so you can spot missing pieces before a crisis hits. And in the long run, that clarity is what moves you beyond the get‑rich‑quick headlines toward genuine, disciplined financial independence.

Lucas Tanaka
Written by

Lucas Tanaka

Lucas is a data-driven DeFi analyst focused on algorithmic trading and smart contract automation. His background in quantitative finance helps him bridge complex crypto mechanics with practical insights for builders, investors, and enthusiasts alike.

Contents