How can I obtain this specific series data to calculate time-to-funding-weighted average of premium index? - time-series

I'm looking to calculate and plot the funding rate of Binance BTCUSDT Perpetual and have come across the following documentation page: https://www.binance.com/en/support/faq/360033525031
It states:
The Funding Rate formula:
"Funding Rate (F) = Average Premium Index (P) + clamp (interest rate - Premium Index (P), 0.05%, -0.05%)"
I'm obtaining the "Premium Index" just fine, just with "p = request.security("BINANCE:BTCUSDT_PREMIUM", "", close)*100"
However I'm currently struggling with how to obtain the:
"Time-to-funding weighted Average of Premium Index " which apparently is calculated with
"Average Premium Index (P) = (1 * Premium_Index_1 + 2 * Premium_Index_2 + 3 * Premium_Index_3 +···+·480 * Premium_index_480)/(1+2+3+···+480)"
(the funding period for Binance is 8 hours hence the average over 480 minutes)
My exact question is, how do I backtrack to the last funding timestamp of 00:00 / 08:00 / 16:00, then obtain an array / series data of the premium index at each of the last 480 minutes, so that I can then iterate over it to use the above formula for the time weighted average?
Thank you very much for any advice in advance. My apologies if the answer is obvious I'm very new to Pine Script.

I believe you can obtain the time weighted average premium like so:
premium = request.security("BINANCE:BTCUSDT_PREMIUM", "1", close)
new_funding_period = ta.change(time("480")) != 0
var int n = na
var float premium_sum = na
var int n_sum = na
if new_funding_period
n := 1
premium_sum := premium
n_sum := 1
else
n += 1
premium_sum += premium * n
n_sum += n
predicted_TWAP = premium_sum / n_sum
current_TWAP = ta.valuewhen(new_funding_period, predicted_TWAP[1], 0)
However, you are limited to performing the calculation on a 1 minute chart to obtain accurate results due to being unable to reliably retrieve the values from a security call from a lower timeframe when the chart is set to a higher timeframe than 1 minute.

Related

Uniswap Liquidity Calculation issue on Arbitrum Chain

According to the "Liqudity Math in uniswap v3", the liqudity of a position should be:
L = amt0 * (sqrt(upper) * sqrt(cprice)) / (sqrt(upper) - sqrt(cprice))
or
L = amt1 / (sqrt(cprice) - sqrt(lower))
I tried to calculate the liquidity of the below position on Arbitrum:
The nft token ID of the position is 69171, so I can get the liqudity by calling the contract(0xC36442b4a4522E871399CD717aBDD847Ab11FE88) on https://arbiscan.io
You can see it shows the liqudity is 50242219347523, and we can do more unit convertion:
Now I try to calcuate this number with the uniswap V3 math:
This is the output:
As we can see, the code output is very similar to the contract output, but if we look carefully, we will find the unit seems to be different. I know the unit of the contract ouput should be 'wei', but I don't know what the unit of the code results is. Can anybody help? Thanks.
I checked that position and pool. Best to query the current price from the pool's contract, for quick look the UI can be found at https://info.uniswap.org/#/arbitrum/pools/0x2f5e87c9312fa29aed5c179e456625d79015299c
The current price is shown as 11.9011 ETH per BTC, and there are 0.3122 BTC and 1.466 ETH in the pool. This gives:
price = 11.9011 * (1e18 / 1e8)
x = 0.3122 * 1e8
y = 1.466 * 1e18
The tick range of the position No. 69171 is 253300 to 259900. Use these values to calculate sp = sqrt(price) and the square roots of the price range boundaries, and from them, the liquidity:
sp = price ** 0.5
sa = 1.0001 ** (253300 // 2)
sb = 1.0001 ** (259900 // 2)
Lx = x * sp * sb / (sb - sp)
Ly = y / (sp - sa)
L = min(Lx, Ly)
The result Lx is 49905251975363.266 and Ly is 51071435112054.96. The Etherscan info shows liquidity L=50242219347523, in between these two values, which have a few % difference. A few % is an acceptable error given the imprecise input values used in this calculation; the UI shows the price and amount values in a rounded format.

Calculate Interest For Mint Token

I saw this code but I didn't understand how he calculated the interest rate . this contract mint tokens as an interest and transfer them to users who deposited to the contract (calculated according to the Hold time) I will be grateful if anyone can help ?
https://github.com/dappuniversity/dbank/blob/master/src/contracts/dBank.sol
//check user's hodl time
uint depositTime = block.timestamp - depositStart[msg.sender];
**//31668017 - interest(10% APY) per second for min. deposit amount (0.01 ETH), cuz:
//1e15(10% of 0.01 ETH) / 31577600 (seconds in 365.25 days)
//(etherBalanceOf[msg.sender] / 1e16) - calc. how much higher interest will be (based on deposit), e.g.:
//for min. deposit (0.01 ETH), (etherBalanceOf[msg.sender] / 1e16) = 1 (the same, 31668017/s)
//for deposit 0.02 ETH, (etherBalanceOf[msg.sender] / 1e16) = 2 (doubled, (2*31668017)/s)
uint interestPerSecond = 31668017 * (etherBalanceOf[msg.sender] / 1e16);
uint interest = interestPerSecond * depositTime;**
//send funds to user
msg.sender.transfer(etherBalanceOf[msg.sender]); //eth back to user
token.mint(msg.sender, interest); //interest to user
depositTime is the number of seconds from the last deposit.
interestPerSecond is calculated from the current ETH balance of the user deposited to the contract
And the interest amount is a simple multiplication between the two above.
Example:
The user has deposited 1 ETH exactly 30 days ago (2,592,000 seconds). This makes the
depositTime == 2592000
interestPerSecond == 31668017 * (etherBalanceOf[msg.sender] / 1e16) == 31668017 * (1000000000000000000 / 1e16) == 31668017 * 100 == 3166801700
interest == interestPerSecond * depositTime == 2592000 * 3166801700 == 8208350006400000
Now, the linked contract imports another contract - Token.sol, that imports the OpenZeppelin ERC20.sol.
The imported ERC20.sol defines 18 decimal places. So you need to account for 18 decimals to get the total amount of tokens that you get as the interest.
8208350006400000 / 1e18 == 0.00820835
So if you deposit 1 ETH 30 days ago, you get 0.00820835 of the token as an interest.

Lua - Take Multiple inputs

I want to write a program that calculate the Average of all input numbers.
First it will asks "How many number you want to input"
If users type 5 then the program will take 5 inputs Then it calculates the Average of it.
I wrote a function that takes passed numbers & returns average of of it But How do we ask the user to input multiple inputs and save it in array
local num = nil;
local sum = 0;
local n = 0;
while num != 0 do
num = io.read()
sum = sum + tonumber(num)
n = n + 1;
end
print(sum / (n-1))
this code will calculate all inputs and will stop asking for input until the user types 0, when he types 0, he will print the average of the values entered

Lua multiple inputs in table

I'm new to lua and I have this assignment and one of the questions I'm really stumped on is asking:
"A program that asks the user repeatedly for students' scores, will stop when the user enters a score of 999 then the program should calculate and display the number of scores entered, highest score, lowest score, and the average score. Make sure to display an error message if a score less than zero or more than 100 is entered by user. "
I've been at this all week long and still can't figure out what to do and its due at 11:59pm est. Any insight and direction would be great.
-How do I input multiple values in a growing table scores = {}? Where the size is given by the number of inputs for variable s after the user enters 999 and ends the repeat loop. This is actually my BIGGEST problem.
My Code:
local scores = {}, avg
repeat
io.write("Enter score(s)")
local s = tonumber(io.read()) --input and convert data type
print(s, type(s)) --s value, check input type
if(s < 0 or s > 100) then
print("Error.")
end
until (s == 999)
for i = 0, #s, 1 do
sum = 0
if s then
sum = sum + s
end
end
-- -----------------------------------------------------------Attemps to find a way to put s values in scores table-----------------------------------------------------------------------------------------
--[[scores[#scores+1] = s ----Attempt 1
print (scores)
for i = 0, #s, 1 do ----Attempt 2
scores{s} = s[i]
print (i, scores) --tried a multitude of different ways and
--kept getting the same number printed once or memory location of last entered number
end
for i, s in ipairs (scores) do --Attempt 3
print (i, s)
end
for i = 0, #s, 1 do
sum = 0
if s then
sum = sum + s
end
end --]]
-- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[function average(myTable)
local sum = 0
for i in scores do
sum = sum + i
end
return (sum / #scores)
end
print ("The number of values in the table"..#scores)
print ("The average of the scores is "..average(s))
print ("The max value in the table is "..math.max(s))
print ("The minimum value in the table is "..math.min(s))
table.maxn(scores), table.minn(scores)
--]]
io.write("Please press enter to continue")
io.read()

Including tax in total sale price

INFORMIX-SQL 7.3 Perform Screen:
Suppose I have a customer who wants to pay a $100 (7% tax included), what logic can I use
so that when the cashier clerk enters $100 in the tax included sale amount, it will
calculate the sale price and tax so that it adds up to $100.
I have the following 3 field tags in my Perform screen:
sprice = transaction.sale_price;
stax = transaction.sale_tax;
stotal = transaction.sale_total;
after editadd of transaction.sale_price
?...what goes here...?
If your problem is the formula then sprice = stotal * 100 / (100 + stax).
For example
$12345 * 100 / (100 + 7) = $11537.38
and adding 7% to $11537.38 gives you $12345.
Note of course that it may be impossible to find an exact amount of pennies that after adding a tax will give you a prescribed total.
To calculate disaggregated cost:
sprice = stotal / (1 + .07)
stax = sprice * .07
Finally round both figures. Depending on the rounding algorithm you may need to apply a penny offset if the resulting rounding operation is off by a cent so that all figures add up.
Basic algebra arithmetic:
93% = 93 per centum which is Latin for 93/100 = 0.93
Total receipt = p
Sale price + Tax = p
Sale price = 0.93p
Tax = 0.07p
4gl form:
sprice = transaction.sale_price,TYPE MONEY(7,2);
stax = transaction.sale_tax,TYPE MONEY(7,2);
stotal = transaction.sale_total,TYPE MONEY(7,2);
.....
INPUT ....
AFTER FIELD stotal
IF transaction.sale_total is NULL THEN
ERROR "Please enter total sale amount"
ELSE
LET transaction.sale_tax = 0.07 * transaction.sale_total
LET transaction.sale_price = 0.93 * transaction.sale_total
ENDIF

Resources