Skip to content

Instantly share code, notes, and snippets.

@banteg

banteg/twap.py Secret

Created Sep 15, 2021
Embed
What would you like to do?
from brownie import *
def decode_uq112x112(num):
upper = num >> 112
lower = num & (2 ** 112 - 1)
return upper + lower / 2 ** 112
def main():
sushi_factory = Contract('0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac')
ldo = '0x5a98fcbea516cf06857215779fd812ca3bef1b32'
weth = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'
pair = Contract(sushi_factory.getPair(ldo, weth))
height = chain.height
sample = 10_000
block_time = (chain[height].timestamp - chain[height - sample].timestamp) / sample
height_old = height - int(30 * 86400 / block_time)
prices = [
decode_uq112x112(pair.price0CumulativeLast(block_identifier=x))
for x in [height_old, height]
]
timestamps = [chain[x].timestamp for x in [height_old, height]]
twap = (prices[1] - prices[0]) / (timestamps[1] - timestamps[0])
discount = 0.3
ldo_sell = 462_962.9629629634
eth_buy = twap * ldo_sell * (1 - discount)
print(f'twap = {twap} eth')
print(f'discount = {discount:.1%}')
print(f'sell = {ldo_sell} ldo')
print(f'buy = {eth_buy} eth')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment