- the thought of recording fee is 'trade space for time'
- record the outside fee sum to save time further, that is, calculate tick's left/right fee sum and the global fee sum, that is useful for calculating the fee sum while a swap cross many tick
eg. calculate the fee sum when the price range is [tick_-1000,tick_1000]
just do subtraction for 2 time
globalSum - tick_-1000.oustsideSum - tick_1000.outsideSum
,
instead of add every tick interval fee
[-1000,-999).fee + [-999,-998).fee + ... + [999,1000).fee
- left sum & right sum & global sum
a tick splits the whole tick space into two part, (-∞,Price_t) (Price_t,+∞)
for every tick, every swap's price belong to either the left or the right space, so there is a left sum and a right sum of historical fee correspond to that two part
left sum = global sum - right sum
right sum = global sum - left sum
when calculate [-1000,1000], we need -1000.leftSum and also 1000.rightSum.
- what is outside sum
we use only one variable to record that sum because we only use one of them for a particular interval(aka position). In fact, outsideSum is the leftSum or the rightSum depending on which one will not change in the future (after this cross, before the next time we cross it). And it is easy to calculate another(see 3).
Don't worry if you get confused about "cross", you'll understand what happened the moment you crossed the tick at part 5
- When to change the outside value of a tick
when the price cross a tick from left to right, this tick.leftSum is
definite, but rightSum still changing when the price is belong to the right space of that tick and new swaps occur, so we will renew tick.outsideSum == tick.leftSum. What's the value of tick.outsideSum now? it is the tick.rightSum because last time we crossed that tick from right to left (or never crossed it before thus it's zero, still holds)
do the crossing renew see 4
tick.outsideSum = left sum
on the other hand, renew the outsideSum to the latest rightSum when cross a tick from right to left.
- an example
a swap makes the price's tick change from -998 to -1000, what's the fee sum on the interval [-1000,-998]?
ic : -998
fb : tick_-1000.leftSum
tick_-1000.outsideSum is leftSum
see formula 6.18.i
fa : tick_-998.rightSum
tick_-998.outsideSum is leftSum because last time we crossed -998 from left to right
calculate the rightSum easily
see formula 6.17.i
answer = global - fa - fb
🐭