# Formula For Calculating Optimal Input for Arbitrage Transaction

I have the following code which calculates the maximum order quantity permissible given a price impact of i, which I wrote based on this explanation of price impact:

https://dailydefi.org/articles/price-impact-and-how-to-calculate/

Understand price impact and liquidity in pancakeswap

Now I would like to modify this to instead determine the order size necessary to bring the spread between the two pools to 1.0 (same price on both).

``````def calculate_swap(self, qty=0, max_impact=0.01, token=0):
"""
Calculate amount received and execution price for a swap
with price impact.

Pool info
USDC = 2,000,000
ETH = 1,000
Constant Product = 2,000,000,000
Market Price = 2,000
First example, 10,000 USDC for ETH
After swap
USDC = 2,010,000 (because we added 10,000 to the pool)
Constant Product = 2,000,000,000 (stays the same)
ETH = 995.024 (constant product / new usdc amount)
ETH recieved = 4.976 (old eth amount - new eth amount)
Price paid per ETH = 2009.64 USDC
ETH recieved = 4.976 (old eth amount - new eth amount)
Price impact = 0.48%

:param qty: of sell token
:param token: index of sell token
:return: amount received, price paid, price impact, qty
"""

fee = 0.003
r0, r1 = self.reserves()
r0 = (r0 / (10 ** self.pair.base_decimals))
r1 = (r1 / (10 ** self.pair.quote_decimals))
constant_product = r0 * r1

token0_price = r1 / r0
token1_price = r0 / r1
if qty == 0 and token == 0:
qty = r0 * max_impact / ((1 - max_impact) * (1 - fee))
if qty == 0 and token == 1:
qty = r1 * max_impact / ((1 - max_impact) * (1 - fee))
if token == 0:
old_price = token1_price
new_r0 = r0 + (qty * (1 - fee))
new_constant_product = constant_product + (1 - (qty * (1 - fee)))
new_r1 = new_constant_product / new_r0
new_price = new_r0 / new_r1
price_impact = ((new_price / old_price) - 1) * 100
else:
old_price = token0_price
new_r1 = r1 + (qty * (1 - fee))
new_constant_product = constant_product + (1 - (qty * (1 - fee)))
new_r0 = new_constant_product / new_r1
new_price = new_r1 / new_r0
price_impact = ((new_price / old_price) - 1) * 100
``````

Currently, what I am doing is first determining the quantity based on the supplied `max_price_impact` parameter, and then feeding that quantity into my smart contract's quote function. But surely this is not ideal. Math was never my best subject and I don't know how to modify this formula to determine the quantity needed to converge the price on both exchanges.

Here is some example output from running my program:

``````[+] Calculating. Spread: 1.0007158869188668 ..