SHARE
TWEET

Untitled

a guest Jun 24th, 2019 96 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //@version=3
  2. study("BitMEX Funding [m59]", shorttitle="BitMEX Funding", precision=4, max_bars_back=481, overlay=true)
  3.  
  4.  
  5. //----- DESCRIPTION
  6.  
  7. // This indicator emulates BitMEX funding rates with reasonably accurate results.
  8.  
  9. // BitMEX funding occurs every 8 hours at 4:00 UTC, 12:00 UTC and 20:00 UTC.
  10. // You pay the funding rate if you are in a position at funding time.
  11. // The funding rate is predicted from the minute funding occurs over 480 minutes (8 hours).
  12. // After 8 hours, which is another funding time, the predicted rate is set as the next funding rate, which will be paid 8 hours later at the next funding time.
  13. // For example:
  14. //   It is 4:00 UTC and funding is paid, and there is currently a predicted rate of 0.01.
  15. //   The predicted rate, 0.01, will be set as the next funding rate which will be paid in 8 hours at the next funding time.
  16. //   The predicted rate resets and will become a more accurate prediction each minute.
  17.  
  18. // Funding Rate Bar: On the bar on which funding is paid (see funding times), a column is rendered with the value of the paid funding rate.
  19. // Next Funding Rate: The rendered circles show the next funding rate, which will be the value of the Funding Rate Bar
  20. // Predicted Funding Rate: The rendered line is the predicted funding rate that resets when funding is paid.
  21.  
  22. // Daily, Weekly, and Monthly views show the total of fundings within the bar.
  23. // i.e. a daily bar contains 3 funding periods, so if funding were 0.1 each of those times, the daily funding is 0.3.
  24. // There are 21 funding periods in a week, so a week during which the funding was 0.1 on average will have a Weekly bar with a funding value of 2.1
  25.  
  26. // * A note on emulation accuracy
  27. // Funding rate emulation uses lower time frame data from TradingView which has limited history.
  28. // On my chart at the time of writing this, I am able to access 20 weeks of that data.
  29. // Beyond that point, the funding rate emulation becomes less accurate,
  30. // though it is still reasonably similar for the purpose of trend/sentiment analysis.
  31.  
  32.  
  33. //----- PRINTED VALUES
  34.  
  35. // Predicted Funding Rate | Next Funding Rate | Funding Rate Bar
  36.  
  37.  
  38. //----- OPTIONS
  39.  
  40. // - Contract: Choose the BitMEX perpetual swap contract for which to emulate funding. XBTUSD or ETHUSD
  41. // - Cap Funding: BitMEX funding has a cap. Disable this if you want to see what the value would be without the funding cap.
  42. // - Use Alternate Colors When Accuracy Reduced: Use distinct colors when accuracy is reduced. See note about accuracy in the indicator description.
  43.  
  44.  
  45. //----- INPUTS
  46.  
  47. contract = input("XBTUSD", title="Contract", options=[ "XBTUSD", "ETHUSD" ])
  48. capFunding = input(true, "Cap Funding")
  49. useAlternateColorsWhenAccuracyReduced = input(true, title="Use Alternate Colors When Accuracy Reduced")
  50.  
  51. CONTRACT_XBTUSD = "XBTUSD"
  52. CONTRACT_ETHUSD = "ETHUSD"
  53.  
  54.  
  55. //----- HELPERS
  56.  
  57. clamp (lowest, highest, subject) => max(lowest, min(highest, subject))
  58.  
  59. minutesToBars (minutes) =>
  60.     dailyMinutes = 1440
  61.     weeklyMinutes = 10080
  62.     monthlyMinutes = weeklyMinutes * 30
  63.     resolutionBaseMinutes = ismonthly ? monthlyMinutes :
  64.        isweekly ? weeklyMinutes :
  65.        isdaily ? dailyMinutes :
  66.        1
  67.     barMinutes = interval * resolutionBaseMinutes
  68.     minutes / barMinutes
  69.  
  70. total (src, length) =>
  71.     result = 0.0
  72.     for i = 0 to length - 1
  73.         if (i < 0)
  74.             result := na
  75.             break
  76.         result := result + src[i]
  77.     result
  78.  
  79. simpleMovingAverage (src, length) => total(src, length) / length
  80.  
  81. // this seems to be faster than the built-in `barssince ` function, which was contributing to an error for being too slow
  82. barsSince (condition) =>
  83.     bars = 0
  84.     bars := condition ? 0 : bars[1] + 1
  85.  
  86. twap (resetWhen, src) =>
  87.     bars = barsSince(resetWhen) + 1
  88.     simpleMovingAverage(src, bars)
  89.  
  90. // Funding occurs every 8 hours at 04:00 UTC, 12:00 UTC and 20:00 UTC.
  91. isBitmexFundingBar = ((hour == 4 or hour == 12 or hour == 20) and (minute == 0)) or isdwm
  92.  
  93. fundingTwap (src) => twap(isBitmexFundingBar, src)
  94.  
  95. bitmexInterestRateTwap (asset) =>
  96.     //----- Interest Rate Component
  97.  
  98.     // Every contract traded on BitMEX consists of two instruments: a Base currency and a Quote currency.
  99.     // For example, on XBTUSD, the Base currency is XBT while the quote currency is USD.
  100.     // The Interest Rate is a function of interest rates between these two currencies:
  101.  
  102.     interestBaseIndex = security("BITMEX:" + asset + "BON", period, close) // The Interest Rate for borrowing the Base currency
  103.     interestQuoteIndex = security("BITMEX:USDBON", period, close) // The Interest Rate for borrowing the Quote currency
  104.     fundingInterval = 3 // (Since funding occurs every 8 hours)
  105.     interestRate = nz((interestQuoteIndex - interestBaseIndex) / fundingInterval, 0.0001)
  106.     fundingTwap(interestRate)
  107.  
  108. bitmexPremiumIndexTwap (asset) =>
  109.     //----- Premium / Discount Component
  110.  
  111.     // The perpetual contract may trade at a significant premium or discount to the Mark Price.
  112.     // In those situations, a Premium Index will be used to raise or lower the next Funding Rate to levels consistent with where the contract is trading.
  113.     // Each contract’s Premium Index is available on the specific instrument’s Contract Specifications page and is calculated as follows:
  114.     // Premium Index (P) = (Max(0, Impact Bid Price - Mark Price) - Max(0, Mark Price - Impact Ask Price)) / Spot Price + Fair Basis used in Mark Price
  115.  
  116.     premiumIndexTwap_fallback = security("BITMEX:" + asset + "USDPI", period, fundingTwap(ohlc4))
  117.     premiumIndexTwap = security("BITMEX:" + asset + "USDPI", "1", fundingTwap(ohlc4))
  118.     [ premiumIndexTwap, premiumIndexTwap_fallback ]
  119.    
  120. bitmexPredictedFundingRate (asset, capFunding, fundingCapAmount, dampenerAmount, interestRateTwap, premiumIndexTwap) =>
  121.     predictedBaseFundingRateRatio = premiumIndexTwap + clamp(-dampenerAmount, dampenerAmount, interestRateTwap - premiumIndexTwap)
  122.     predictedFundingRateRatio = capFunding ? clamp(-fundingCapAmount, fundingCapAmount, predictedBaseFundingRateRatio) : predictedBaseFundingRateRatio
  123.     predictedFundingRateRatio * 100
  124.    
  125. bitmexNextFundingRate (predictedFundingRate) =>
  126.     nextFundingRate = 0.01
  127.     nextFundingRate := isBitmexFundingBar ? predictedFundingRate[1] : nextFundingRate[1]
  128.  
  129. bitmexFundingBarValue (assetTicker, predictedFundingRate) =>
  130.     fundingPeriodMinutes = 480
  131.     fundingPeriodBars = max(1, floor(minutesToBars(fundingPeriodMinutes)))
  132.     fundingOffset = fundingPeriodBars + 1
  133.    
  134.     dwmIntervalModifier = isdaily ? 3 :
  135.        isweekly ? 3 * 7 :
  136.        ismonthly ? 3 * 30 :
  137.        na
  138.     dwmModifier = interval * dwmIntervalModifier
  139.    
  140.     intradayFundingBarValue = predictedFundingRate[fundingOffset]
  141.     // any ticker will work fine here, but simply using `ticker` (the current chart) doesn't work on special charts like spread charts that can't access `ticker`
  142.     nonIntradayFundingBarValue = security(assetTicker, "240", intradayFundingBarValue) * dwmModifier
  143.     (not isBitmexFundingBar) ? na : (isintraday ? intradayFundingBarValue : nonIntradayFundingBarValue)
  144.  
  145.  
  146. //----- VALUES
  147.  
  148. asset = contract == CONTRACT_XBTUSD ? "XBT" :
  149.    contract == CONTRACT_ETHUSD ? "ETH" :
  150.    "XBT"
  151.    
  152. assetTicker = asset + "USD"
  153.  
  154. [ premiumIndexTwap_ideal, premiumIndexTwap_fallback ] = bitmexPremiumIndexTwap(asset)
  155. premiumIndexTwap = na(premiumIndexTwap_ideal) ? premiumIndexTwap_fallback : premiumIndexTwap_ideal
  156. interestRateTwap = bitmexInterestRateTwap(asset)
  157.  
  158. predictedFundingRate = bitmexPredictedFundingRate(asset, capFunding,  0.00375, 0.0005, interestRateTwap, premiumIndexTwap)
  159. nextFundingRate = bitmexNextFundingRate(predictedFundingRate)
  160. fundingBarValue = bitmexFundingBarValue(assetTicker, predictedFundingRate)
  161. accuracyReduced = na(premiumIndexTwap_ideal)
  162.  
  163.  
  164. //----- RENDER
  165.  
  166. longsColor = #53B987
  167. shortsColor = #EB4D5C
  168. longsAlternateColor = #247BA0
  169. shortsAlternateColor = orange
  170. useAlternateColors = useAlternateColorsWhenAccuracyReduced and accuracyReduced
  171.  
  172. FundingColor (rate) => rate < 0 ? (useAlternateColors ? shortsAlternateColor : shortsColor) : (useAlternateColors ? longsAlternateColor : longsColor)
  173.  
  174. nextFundingColor = FundingColor(nextFundingRate)
  175. fundingBarColor = FundingColor(fundingBarValue)
  176.  
  177. longsPay= nextFundingRate> 0.01
  178. shortsPay= nextFundingRate< 0.01
  179.  
  180. bgcolor(color=red, when= longsPay )
  181. bgcolor(color=green, when= shortsPay )
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top