Blockchain Fundamentals: Electricity Cost of BTC [CR]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © theheirophant

//@version=5
indicator("Blockchain Fundamentals: Electricity Cost of BTC [CR]")

//historical windows for halvings
start1  = timestamp('1 Jan 2000 00:00 +0000')
finish1 = timestamp('27 Nov 2012 23:59 +0000')
window1() =>
    time >= start1 and time <= finish1 ? true : false

start2  = timestamp('28 Nov 2012 00:00 +0000')
finish2 = timestamp('8 Jul 2016 23:59 +0000')
window2() =>
    time >= start2 and time <= finish2 ? true : false

start3  = timestamp('9 Jul 2016 00:00 +0000')
finish3 = timestamp('10 May 2020 23:59 +0000')
window3() =>
    time >= start3 and time <= finish3 ? true : false

start4  = timestamp('11 May 2020 00:00 +0000')
finish4 = timestamp('1 Jun 2024 23:59 +0000')
window4() =>
    time >= start4 and time <= finish4 ? true : false

//bitcoin block emission rate based on halvings
emissionrate  = 6.25
emissionrate := window1() == true ? 50   : emissionrate
emissionrate := window2() == true ? 25   : emissionrate
emissionrate := window3() == true ? 12.5 : emissionrate
emissionrate := window4() == true ? 6.25 : emissionrate

//inputs
terahashes  = input.int(110, minval=0, title='Total Mining TH/s?', tooltip="Total TH/s of all Miners")
power       = input.float(3.1, minval=0, title='Total kWh Used?', tooltip="1000 watts = 1 kWh | 3500 watts = 3.5 kWh etc ")
elecprice   = input.float(5, minval=0.1, title='Electricity Cost: Cents per kWh?')
tru         = input.bool(true, title='Also Plot Total Cost?')
elecpercent = input.float(80, minval=0.1, maxval=100, title='Total Cost: Electricity accounts for X% of all costs?', tooltip="Studies report 80% is an average value for efficient miners") / 100

//calculation
diff             = request.security('quandl:bchain/diff',  'D', close)
secstomine1block = math.pow(2, 32) * diff / (math.pow(10, 12) * terahashes)
daystomine1block = secstomine1block / (24 * 3600)
daystomine1btc   = daystomine1block / emissionrate

//division by 100 to convert cents to dollars
costtomine1day = power * elecprice * 24 / 100
costtomine1btc = costtomine1day * daystomine1btc

//plots
plot(costtomine1btc, 'Cost to mine 1 BTC - Electric Only', color=color.new(color.blue, 0))
plot(costtomine1btc * ((1 - elecpercent) + 1), 'Cost to mine 1 BTC - All Costs', color=tru ? color.new(color.yellow, 0) : color.new(color.yellow, 100))