Unrealized PNL (profit and loss) is the gain / loss you would earn by closing your open position now. It is calculated based on the difference in USD value between your average entry price and the current index price.
Realized PNL is the gain / loss that has already been captured from the position after closing or due to funding payments. It is calculated based on the difference in USD value between your average entry price and exit price. Additionally, all funding payments for the position are immediately applied to its realized PNL.
A user is long 100 BTC-USD exposure from an open position with an average entry price of $30,000. The price provided by the relevant index for BTC-USD is $35,000.
Since USDC is the collateral/margin for all perpetuals, all unrealized and realized PNL calculations on dYdX can practically be based on and denominated in USD (accounting for occasional slight market deviations from the 1:1 ratio of USDC:USD).
The unrealized PNL is based on the difference between the average entry price and the oracle price. The index price is used rather than the last trade price or mid-market price.
Unrealized PNL = ($35,000-$30,000) * 100 = $500,000
The realized PNL is based on the difference between the average entry price and the price at which the user sells BTC-USD (not the oracle price). It also includes any funding payments that have been applied to the position.
Now assume that the user decided to sell half their open position to capture profits, and assume that the executed exit price was $36,000. The oracle price is now at $35,500 in this example.
Realized PNL = ($36,000-$30,000) * 50 = $300,000
New Unrealized PNL = ($35,500-$30,000) * 50 = $275,000
The paying and receiving of funding rate payments (based on the funding rate and paid in USDC) also needs to be accounted for in the example above. See here for more detail on the funding rate calculation. The payments occur every hour.
Assuming that the funding rate is 0.25%, it is paid from buyers to sellers (negative means sellers pay buyers). In the example above, the user still has an open position of 50 BTC-USD exposure with the oracle price still at $35,500. At funding rate payment time (every hour), the user (who is long) pays 1/8 of 0.25% since the funding rate is calculated as an 8-hour rate.
Hourly funding rate payment = (0.0025 / 8) * $35,500 * 50 = $554.6875
New Realized PNL = $300,000 - $554.6875 = $299,445.3125