Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.61 KB | None | 0 0
  1. //@version=3
  2. study("Bitmex Funding Bias", shorttitle="Skrrrt", 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. whenLong = input(title= "Short", type=float, defval= 0.11, step= 0.01)
  47. whenShort = input(title= "Long", type=float, defval= -0.12, step= 0.01)
  48. whichFunding = input("Daily Funding", title="Type of Funding", options=[ "8h Funding", "Daily Funding" ] )
  49. contract = input("XBTUSD", title="Contract", options=[ "XBTUSD", "ETHUSD" ])
  50. capFunding = true
  51. useAlternateColorsWhenAccuracyReduced = true
  52.  
  53. CONTRACT_XBTUSD = "XBTUSD"
  54. CONTRACT_ETHUSD = "ETHUSD"
  55.  
  56.  
  57. //----- HELPERS
  58.  
  59. clamp (lowest, highest, subject) => max(lowest, min(highest, subject))
  60.  
  61. minutesToBars (minutes) =>
  62. dailyMinutes = 1440
  63. weeklyMinutes = 10080
  64. monthlyMinutes = weeklyMinutes * 30
  65. resolutionBaseMinutes = ismonthly ? monthlyMinutes :
  66. isweekly ? weeklyMinutes :
  67. isdaily ? dailyMinutes :
  68. 1
  69. barMinutes = interval * resolutionBaseMinutes
  70. minutes / barMinutes
  71.  
  72. total (src, length) =>
  73. result = 0.0
  74. for i = 0 to length - 1
  75. if (i < 0)
  76. result := na
  77. break
  78. result := result + src[i]
  79. result
  80.  
  81. simpleMovingAverage (src, length) => total(src, length) / length
  82.  
  83. // this seems to be faster than the built-in `barssince ` function, which was contributing to an error for being too slow
  84. barsSince (condition) =>
  85. bars = 0
  86. bars := condition ? 0 : bars[1] + 1
  87.  
  88. twap (resetWhen, src) =>
  89. bars = barsSince(resetWhen) + 1
  90. simpleMovingAverage(src, bars)
  91.  
  92. // Funding occurs every 8 hours at 04:00 UTC, 12:00 UTC and 20:00 UTC.
  93. isBitmexFundingBar = ((hour == 4 or hour == 12 or hour == 20) and (minute == 0)) or isdwm
  94.  
  95. fundingTwap (src) => twap(isBitmexFundingBar, src)
  96.  
  97. bitmexInterestRateTwap (asset) =>
  98. //----- Interest Rate Component
  99.  
  100. // Every contract traded on BitMEX consists of two instruments: a Base currency and a Quote currency.
  101. // For example, on XBTUSD, the Base currency is XBT while the quote currency is USD.
  102. // The Interest Rate is a function of interest rates between these two currencies:
  103.  
  104. interestBaseIndex = security("BITMEX:" + asset + "BON", period, close) // The Interest Rate for borrowing the Base currency
  105. interestQuoteIndex = security("BITMEX:USDBON", period, close) // The Interest Rate for borrowing the Quote currency
  106. fundingInterval = 3 // (Since funding occurs every 8 hours)
  107. interestRate = nz((interestQuoteIndex - interestBaseIndex) / fundingInterval, 0.0001)
  108. fundingTwap(interestRate)
  109.  
  110. bitmexPremiumIndexTwap (asset) =>
  111. //----- Premium / Discount Component
  112.  
  113. // The perpetual contract may trade at a significant premium or discount to the Mark Price.
  114. // 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.
  115. // Each contract’s Premium Index is available on the specific instrument’s Contract Specifications page and is calculated as follows:
  116. // 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
  117.  
  118. premiumIndexTwap_fallback = security("BITMEX:" + asset + "USDPI", period, fundingTwap(ohlc4))
  119. premiumIndexTwap = security("BITMEX:" + asset + "USDPI", "1", fundingTwap(ohlc4))
  120. [ premiumIndexTwap, premiumIndexTwap_fallback ]
  121.  
  122. bitmexPredictedFundingRate (asset, capFunding, fundingCapAmount, dampenerAmount, interestRateTwap, premiumIndexTwap) =>
  123. predictedBaseFundingRateRatio = premiumIndexTwap + clamp(-dampenerAmount, dampenerAmount, interestRateTwap - premiumIndexTwap)
  124. predictedFundingRateRatio = capFunding ? clamp(-fundingCapAmount, fundingCapAmount, predictedBaseFundingRateRatio) : predictedBaseFundingRateRatio
  125. predictedFundingRateRatio * 100
  126.  
  127. bitmexNextFundingRate (predictedFundingRate) =>
  128. nextFundingRate = 0.01
  129. nextFundingRate := isBitmexFundingBar ? predictedFundingRate[1] : nextFundingRate[1]
  130.  
  131. bitmexFundingBarValue (assetTicker, predictedFundingRate) =>
  132. fundingPeriodMinutes = 480
  133. fundingPeriodBars = max(1, floor(minutesToBars(fundingPeriodMinutes)))
  134. fundingOffset = fundingPeriodBars + 1
  135.  
  136. dwmIntervalModifier = isdaily ? 3 :
  137. isweekly ? 3 * 7 :
  138. ismonthly ? 3 * 30 :
  139. na
  140. dwmModifier = interval * dwmIntervalModifier
  141.  
  142. intradayFundingBarValue = predictedFundingRate[fundingOffset]
  143. // 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`
  144. nonIntradayFundingBarValue = security(assetTicker, "240", intradayFundingBarValue) * dwmModifier
  145. (not isBitmexFundingBar) ? na : (isintraday ? intradayFundingBarValue : nonIntradayFundingBarValue)
  146.  
  147.  
  148. //----- VALUES
  149.  
  150. asset = contract == CONTRACT_XBTUSD ? "XBT" :
  151. contract == CONTRACT_ETHUSD ? "ETH" :
  152. "XBT"
  153.  
  154. assetTicker = asset + "USD"
  155.  
  156. [ premiumIndexTwap_ideal, premiumIndexTwap_fallback ] = bitmexPremiumIndexTwap(asset)
  157. premiumIndexTwap = na(premiumIndexTwap_ideal) ? premiumIndexTwap_fallback : premiumIndexTwap_ideal
  158. interestRateTwap = bitmexInterestRateTwap(asset)
  159.  
  160. predictedFundingRate = bitmexPredictedFundingRate(asset, capFunding, 0.00375, 0.0005, interestRateTwap, premiumIndexTwap)
  161. nextFundingRate = bitmexNextFundingRate(predictedFundingRate)
  162. fundingBarValue = bitmexFundingBarValue(assetTicker, predictedFundingRate)
  163. accuracyReduced = na(premiumIndexTwap_ideal)
  164.  
  165. theActualUsedFunding = whichFunding == "8h Funding" ? nextFundingRate : predictedFundingRate
  166.  
  167. //----- RENDER
  168.  
  169. longsColor = #53B987
  170. shortsColor = #EB4D5C
  171. longsAlternateColor = #247BA0
  172. shortsAlternateColor = orange
  173. useAlternateColors = useAlternateColorsWhenAccuracyReduced and accuracyReduced
  174.  
  175. FundingColor (rate) => rate < 0 ? (useAlternateColors ? shortsAlternateColor : shortsColor) : (useAlternateColors ? longsAlternateColor : longsColor)
  176.  
  177. nextFundingColor = FundingColor(nextFundingRate)
  178. fundingBarColor = FundingColor(fundingBarValue)
  179.  
  180. longsPay= theActualUsedFunding > whenLong
  181. shortsPay= theActualUsedFunding < whenShort
  182.  
  183.  
  184. bgcolor(color=(longsPay ? #8b3030 : (shortsPay ? #0F1626 : na)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement