# Trying to understand pricing of defi swap pools (x*y=k)

I am trying to understand how a swap impacts the price on liquidity pools in defi like uniswap. I am new to crypto, and don't have a financial background so I apologize in advance if I am saying nonsense.

I created this script https://jsfiddle.net/9fz0ac6n/ to see a live example of the calculations. The script assumes a pool with reserves of 2000000 Token A / 1000 Token B, the result from a swap of 10000 Token A to Token B is this:

``````---------------------------------------------

[Prices before swap]

reserveA: 2000000
reserveB: 1000
1 TokenA: 0.0005 TokenB
1 TokenB: 2000 TokenA

---------------------------------------------

[Swap prices]

newReserveA: 2010000
newReserveB: 995.0248756218906
1 TokenA: 0.0004975124378109399 TokenB
1 TokenB: 2010.0000000000216 TokenA

---------------------------------------------

[Prices after swap]

newReserveA: 2010000
newReserveB: 995.0248756218906
1 TokenA: 0.0004950372515531794 TokenB
1 TokenB: 2020.05 TokenA

---------------------------------------------
``````

The `[Prices before swap]` part makes sense to me, without taking price impact into account, you would have to pay 0.0005 Token B to get 1 Token A and 2000 Token A to get 1 Token B.

`[Swap prices]` also makes sense. In order to keep the invariant constant, the bigger the trade the more you have to pay, since the swap will cause the reserves to change.

But why is `[Prices after swap]` different than `[Swap prices]`? I was expecting the price impact of the swap to dictate the new price after the swap.

Is there an error in my code/calculations? What is it that I am not understanding?

• Sorry for the lazy comment - but did try reading the Uniswap v2 whitepaper. That's where all of this should be explained. Oct 29, 2021 at 21:36
• @PaulRazvanBerg Yes and I don't fully understand it, that's why I am asking for help understanding a practical example. Oct 29, 2021 at 22:12
• What about the Uniswap v2 docs? Oct 30, 2021 at 13:43

The price impact is not the ratio between the old and new mid price (mid price being the ratio of the reserves). Rather, it is the difference between the mid price and the market price: `price_impact = 1 - (mid_price / market_price)`.

``````amountInWithFee = amount_traded * (1 - fee);
constant_product = reserve_a_initial * reserve_b_initial;
reserve_b_after_execution = constant_product / (reserve_a_initial + amountInWithFee);
amountOut = reserve_b_initial - reserve_b_after_execution;
market_price = amountInWithFee / amountOut;
mid_price = reserve_a_initial / reserve_b_initial;
price_impact = 1 - (mid_price / market_price);
// this simplifies to
price_impact = amountInWithFee / (reserve_a_initial + amountInWithFee);
``````

For more detailed explanation on calculating the price impact, have a look at this answer.

this is correct, but swap price is just for the swapper point of view, obviously there is new ratio in the pool once the swap is done.