Asset compared to asset/market
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © lyubo

//@version=5
indicator("Asset compared to asset/market", overlay=false, precision=7)

// Utility functions - start

// for testing
// plotshape(some_bool_condition, 'Green label', shape.diamond, location.bottom, color.green, -1, size=size.tiny)

// label.new(bar_index, whatToPlot[1], str.tostring(multiplier) + ' - ' + str.tostring(), size = size.normal)

func_print_1_key_and_value_pair(key1, val1) =>
    if barstate.islast
        label.new(bar_index, 1.008*high, str.tostring(key1) + ' - ' + str.tostring(val1), size = size.normal)

func_print_2_key_and_value_pairs(key1, val1, key2, val2) =>
    if barstate.islast
        label.new(bar_index, 1.008*high, str.tostring(key1) + ' - ' + str.tostring(val1) + '\n' + str.tostring(key2) + ' - ' + str.tostring(val2), size = size.normal)

func_print_3_key_and_value_pairs(key1, val1, key2, val2, key3, val3) =>
    if barstate.islast
        label.new(bar_index, 1.008*high, str.tostring(key1) + ' - ' + str.tostring(val1) + '\n' + str.tostring(key2) + ' - ' + str.tostring(val2) + '\n' + str.tostring(key3) + ' - ' + str.tostring(val3), size = size.normal)
// Utility functions - end

// *********************** Global variables declarations - start ***********************
var lastMajorBullCross = false
var lastMajorBearCross = false

var number_to_multiply_by_to_determine_decimal_points = 10000

timeframe = input.timeframe("", title = "Timeframe:")
comparedToSymbol = input.symbol("TOTAL", "Compare to symbol:")
securityOfComparedToSymbol = request.security(comparedToSymbol, timeframe, close)

ema1length = input.int(20, "EMA 1 length:")
ema2length = input.int(45, "EMA 2 length:")
ema3length = input.int(200, "EMA 3/Mean reversion 2 length:")

ema4lengthMeanReversion1 = input.int(100, "EMA 4/Mean reversion 1 length:") 

securitySymbolToCompare = request.security(syminfo.tickerid, timeframe, close)

compareAnotherSymbolThanCurrent = input.bool(false, "Compare another symbol other than the current one:")
otherSymbolToCompare = input.symbol("BTCUSD", "Symbol to compare:")
securityOfOtherSymbolToCompare=request.security(otherSymbolToCompare, timeframe, close)

whatToPlot = ((securitySymbolToCompare)/(securityOfComparedToSymbol)) * 100

x = if compareAnotherSymbolThanCurrent
    whatToPlot:=(securityOfOtherSymbolToCompare/securityOfComparedToSymbol)*100

// logic to prevent calculation mistakes with too discrepant numbers
number_of_multiplied_times = 0
while whatToPlot < 1 and (whatToPlot * number_to_multiply_by_to_determine_decimal_points < 1)    
    whatToPlot := whatToPlot * 10
    number_of_multiplied_times += 1

// fix for cases which go from ...9 to ...1 and vice versa
prev_value_first_num = ''
curr_value_first_num = '' 

num_prev = whatToPlot[1]
while num_prev < 1
    num_prev := num_prev * 10

num_curr = whatToPlot
while num_curr < 1
    num_curr := num_curr * 10

prev_value_first_num := str.substring(str.tostring(num_prev), 0, 1)
curr_value_first_num := str.substring(str.tostring(num_curr), 0, 1)

var multiplier = 1.0

if number_of_multiplied_times > number_of_multiplied_times[1]
    multiplier := multiplier / 10
else if number_of_multiplied_times < number_of_multiplied_times[1]
    multiplier := multiplier * 10

whatToPlot := whatToPlot * multiplier

ema1 = ta.ema(whatToPlot, ema1length)
ema2 = ta.ema(whatToPlot, ema2length)
ema3 = ta.ema(whatToPlot, ema3length)

emaPrice20 = ta.ema(close, ema1length)
emaPrice45 = ta.ema(close, ema2length)
emaPrice200 = ta.ema(close, ema3length)
emaPrice100 = ta.ema(close, ema4lengthMeanReversion1)

includeBullBackground = input.bool(true, "Include Bull background")
includeBearBackground = input.bool(true, "Include Bear background")

strongBullAlignment= whatToPlot > ema1 and ema1 > ema2 and ema2 > ema3
strongBearAlignment= whatToPlot < ema1 and ema1 < ema2 and ema2 < ema3

strongBullInPrice = close > emaPrice20 and emaPrice20 > emaPrice45 and emaPrice45 > emaPrice200
strongBearInPrice = close < emaPrice20 and emaPrice20 < emaPrice45 and emaPrice45 < emaPrice200

// *********************** Global variables declarations - end ***********************

bgcolor(includeBullBackground and strongBullAlignment ? color.new(color.green, 70) : na, title="Bull")
bgcolor(includeBearBackground and strongBearAlignment ? color.new(color.red,70) : na, title="Bear")

bgcolor(includeBullBackground and strongBullInPrice ? color.new(color.green, 70) : na, title="Bull")
bgcolor(includeBearBackground and strongBearInPrice ? color.new(color.red,70) : na, title="Bear")

plot(whatToPlot, "Asset compared to asset index", color=color.black, linewidth=2)
plot(ema1, "EMA 1", color=color.new(#2196f3,0))
plot(ema2, "EMA 2", color=color.new(#f803c1,0))
plot(ema3, "EMA 3", color=color.new(#ff1100, 0), linewidth=2)

// Alarms

bearPriceCross = ta.crossunder(close, emaPrice200)
bullPriceCross = ta.crossover(close, emaPrice200)
bearPriceCondition = close < emaPrice200
bullPriceCondition = close > emaPrice200

bearIndexCross = ta.crossunder(whatToPlot,ema3)
bullIndexCross = ta.crossover(whatToPlot,ema3)
bearIndexCondition = whatToPlot<ema3
bullIndexCondition = whatToPlot>ema3

MajorBearAlert= (bearPriceCross and bearIndexCondition) or (bearIndexCross and bearPriceCondition)
MajorBullAlert= (bullPriceCross and bullIndexCondition) or (bullIndexCross and bullPriceCondition)

if MajorBullAlert
    lastMajorBullCross = true
    lastMajorBearCross = false

if MajorBearAlert
    lastMajorBullCross = false
    lastMajorBearCross = true

PriceBearAlert = bearPriceCross //and strongBearInPrice
PriceBullAlert = bullPriceCross //and strongBullInPrice

IndexBearAlert = bearIndexCross //and strongBearAlignment
IndexBullAlert = bullIndexCross //and strongBullAlignment

// *********************** Alerts - start ***********************

// Any of major, price or index alerts
if MajorBearAlert or PriceBearAlert or IndexBearAlert // maybe to add the condition saying that before that there was a bear cross of both PA and index with ema200 or something like that
    alert("Any bear alert", alert.freq_once_per_bar_close)

if MajorBullAlert or PriceBullAlert or IndexBullAlert
    alert("Any bull alert", alert.freq_once_per_bar_close)

// Mean reversion alerts - Price
// 100 EMA mean reversion 1
if lastMajorBullCross and ta.crossunder(close, emaPrice100)
    alert('Mean reversion 1 - Bull', alert.freq_once_per_bar_close)

if lastMajorBearCross and ta.crossover(close, emaPrice100)
    alert('Mean reversion 1 - Bear', alert.freq_once_per_bar_close)

// 200 EMA mean reversion 2
if lastMajorBullCross and ta.crossunder(close, emaPrice200)
    alert('Mean reversion 1 - Bull', alert.freq_once_per_bar_close)

if lastMajorBearCross and ta.crossover(close, emaPrice200)
    alert('Mean reversion 1 - Bear', alert.freq_once_per_bar_close)
    
// *********************** Alerts - end ***********************

alertcondition(MajorBearAlert, title='Major Bear alert', message='Major Bear - 200 EMA crossed on both price and Asset vs asset indicator')
alertcondition(MajorBullAlert, title='Major Bull alert', message='Major Bull - 200 EMA crossed on both price and Asset vs asset indicator')

alertcondition(PriceBearAlert, title='Price Bear alert', message='Price Bear - 200 EMA crossed on price')
alertcondition(PriceBullAlert, title='Price Bull alert', message='Price Bull - 200 EMA crossed on price')

alertcondition(IndexBearAlert, title='Index Bear alert', message='Index Bear - 200 EMA crossed on price')
alertcondition(IndexBullAlert, title='Index Bull alert', message='Index Bull - 200 EMA crossed on price')
