-- More information about this indicator can be found at:
-- http://fxcodebase.com/code/viewtopic.php?f=31&t=71577

--+------------------------------------------------------------------------+
--|                                    Copyright © 2021, Gehtsoft USA LLC  |
--|                                                 http://fxcodebase.com  |
--+------------------------------------------------------------------------+
--|                                      Support our efforts by donating   |
--|                                         Paypal: https://goo.gl/9Rj74e  |
--+------------------------------------------------------------------------+
--|                                           Developed by : Mario Jemic   |
--|                                               mario.jemic@gmail.com    |
--|                                https://AppliedMachineLearning.systems  |
--|                                     Patreon :  https://goo.gl/GdXWeN   |
--+------------------------------------------------------------------------+
--|BitCoin Address            : 15VCJTLaz12Amr7adHSBtL9v8XomURo9RF         |
--|Ethereum Address           : 0x8C110cD61538fb6d7A2B47858F0c0AaBd663068D |
--|Dogecoin Address           : DNDTFfmVa2Gjts5YvSKEYaiih6cums2L6C         |
--|Binance(ERC20 & BSC only)  : 0xe84751063de8ade7c5fbff5e73f6502f02af4e2c |
--|Binance Address (BEP2 only): bnb136ns6lfw4zs5hg4n85vdthaad7hq5m4gtkgf23 |
--|Binance MEMO (BEP2 only)   : 107152697                                  |
--|LiteCoin Address           : LLU8PSY2vsq7B9kRELLZQcKf5nJQrdeqwD         |
--+------------------------------------------------------------------------+

function AddAverages(id, name, default)
    indicator.parameters:addString(id, name, "", default);
    indicator.parameters:addStringAlternative(id, "MVA", "", "MVA");
    indicator.parameters:addStringAlternative(id, "EMA", "", "EMA");
    indicator.parameters:addStringAlternative(id, "Wilder", "", "Wilder");
    indicator.parameters:addStringAlternative(id, "LWMA", "", "LWMA");
    indicator.parameters:addStringAlternative(id, "SineWMA", "", "SineWMA");
    indicator.parameters:addStringAlternative(id, "TriMA", "", "TriMA");
    indicator.parameters:addStringAlternative(id, "LSMA", "", "LSMA");
    indicator.parameters:addStringAlternative(id, "SMMA", "", "SMMA");
    indicator.parameters:addStringAlternative(id, "HMA", "", "HMA");
    indicator.parameters:addStringAlternative(id, "ZeroLagEMA", "", "ZeroLagEMA");
    indicator.parameters:addStringAlternative(id, "DEMA", "", "DEMA");
    indicator.parameters:addStringAlternative(id, "T3", "", "T3");
    indicator.parameters:addStringAlternative(id, "ITrend", "", "ITrend");
    indicator.parameters:addStringAlternative(id, "Median", "", "Median");
    indicator.parameters:addStringAlternative(id, "GeoMean", "", "GeoMean");
    indicator.parameters:addStringAlternative(id, "REMA", "", "REMA");
    indicator.parameters:addStringAlternative(id, "ILRS", "", "ILRS");
    indicator.parameters:addStringAlternative(id, "IE/2", "", "IE/2");
    indicator.parameters:addStringAlternative(id, "TriMAgen", "", "TriMAgen");
    indicator.parameters:addStringAlternative(id, "JSmooth", "", "JSmooth");
    indicator.parameters:addStringAlternative(id, "KAMA", "", "KAMA");
    indicator.parameters:addStringAlternative(id, "ARSI", "", "ARSI");
    indicator.parameters:addStringAlternative(id, "VIDYA", "", "VIDYA");
    indicator.parameters:addStringAlternative(id, "HPF", "", "HPF");
    indicator.parameters:addStringAlternative(id, "VAMA", "", "VAMA");
    indicator.parameters:addStringAlternative(id, "Regression", "", "REGRESSION");
end
function CreateAverages(period, method, source)
    if method == "MVA" or method == "EMA" or method == "ARSI"
       or method == "KAMA" or method == "LWMA" or method == "SMMA"
        or method == "VIDYA" or method == "REGRESSION"
    then
        --assert(core.indicators:findIndicator(method) ~= nil, method .. " indicator must be installed");
        return core.indicators:create(method, source, period);
    end
    assert(core.indicators:findIndicator("AVERAGES") ~= nil, "Please, download and install AVERAGES indicator");
    return core.indicators:create("AVERAGES", source, method, period);
end

local source, rsi, rsi_indi, up_color, down_color, b, marsioma
local MABuffer1, RSIBuffer1, marsioma1, rsi_os, rsi_ob, rsi_use_obos, ma
local indi_alerts = {}
indi_alerts.Version = "2.2"
indi_alerts.inverted_arrows = false
local alerts = {
    {
        Stage = 102,
        UpCondition = function(period)
            if period < 2 or not RSIBuffer1.DATA:hasData(period - 1) then
                return false
            end
            if rsi_use_obos and (RSIBuffer1.DATA[period] > rsi_ob or RSIBuffer1.DATA[period] < rsi_os) then
                return false
            end
            return core.crossesOver(RSIBuffer1.DATA, rsi_os, period) 
                and RSIBuffer1.DATA[period] > marsioma[period]
                and source.close[period] > ma.DATA[period]
        end,
        DownCondition = function(period)
            if period < 2 or not RSIBuffer1.DATA:hasData(period - 1) then
                return false
            end
            if rsi_use_obos and (RSIBuffer1.DATA[period] > rsi_ob or RSIBuffer1.DATA[period] < rsi_os) then
                return false
            end
            return core.crossesUnder(RSIBuffer1.DATA, rsi_ob, period) 
                and RSIBuffer1.DATA[period] < marsioma[period]
                and source.close[period] < ma.DATA[period]
        end,
        FormatMessage = function(source, period, level, label, isUp, metadata)
            return string.format(
                "Label: %s\013\010" ..
                    "Instrument: %s\013\010" .. "Time Frame: %s\013\010" .. "Price: %s\013\010" .. "Date: %s",
                isUp and (label .. " Bull pattern") or (label .. " Bear pattern"),
                source:instrument(),
                source:barSize(),
                win32.formatNumber(source.close[NOW], false, source:getPrecision()),
                core.formatDate(core.now())
            )
        end,
        FilterConsecutive = false,
        OnChange = true,
        Name = "Alert Name"
    }
}

function Init()
    indicator:name("X-RSIOMA")
    indicator:description("")
    indicator:requiredSource(core.Bar)
    indicator:type(core.Oscillator)
    indicator.parameters:addInteger("RSIOMA", "RSIOMA", "", 10)
    indicator.parameters:addInteger("Ma_RSIOMA", "Ma_RSIOMA", "", 14)
    indicator.parameters:addBoolean("rsi_use_obos", "Use RSI OB/OS", "", true)
    indicator.parameters:addInteger("rsi_os", "RSI Oversold", "", 10)
    indicator.parameters:addInteger("rsi_ob", "RSI Overbought", "", 90)
    indicator.parameters:addInteger("ma_period", "MA Period", "", 14);
    AddAverages("ma_method", "MA Method", "LWMA");
    indicator.parameters:addColor("rsi_color", "RSI Color", "Color", core.colors().DodgerBlue)
    indicator.parameters:addInteger("rsi_width", "RSI Width", "Width", 1, 1, 5)
    indicator.parameters:addInteger("rsi_style", "RSI Style", "Style", core.LINE_SOLID)
    indicator.parameters:setFlag("rsi_style", core.FLAG_LINE_STYLE)
    indicator.parameters:addColor("up_color", "Up Color", "", core.rgb(16, 195, 5))
    indicator.parameters:addColor("down_color", "Down Color", "", core.rgb(155, 5, 16))
    indicator.parameters:addColor("marsioma_up_color", "Marsioma Up Color", "Color", core.colors().Green)
    indicator.parameters:addColor("marsioma_dn_color", "Marsioma Down Color", "Color", core.colors().Red)
    indicator.parameters:addInteger("marsioma_width", "Marsioma Width", "Width", 1, 1, 5)
    indicator.parameters:addInteger("marsioma_style", "Marsioma Style", "Style", core.LINE_SOLID)
    indicator.parameters:setFlag("marsioma_style", core.FLAG_LINE_STYLE)
    indi_alerts:AddParameters(indicator.parameters)
    for i, alert in ipairs(alerts) do
        indi_alerts:AddAlert(alert.Name)
    end

    indicator.parameters:addGroup("Levels")
    indicator.parameters:addDouble("Level1", "1. Level", "", 90)
    indicator.parameters:addDouble("Level2", "2. Level", "", 50)
    indicator.parameters:addDouble("Level3", "3. Level", "", 10)
    indicator.parameters:addColor("level_overboughtsold_color", "Line Color", "", core.COLOR_LABEL)
    indicator.parameters:addInteger("level_overboughtsold_width", "Line width", "", 1, 1, 5)
    indicator.parameters:addInteger("level_overboughtsold_style", "Line Style", "", core.LINE_SOLID)
    indicator.parameters:setFlag("level_overboughtsold_style", core.FLAG_LEVEL_STYLE)
end
local marsioma_up_color, marsioma_dn_color;
function Prepare(nameOnly)
    source = instance.source
    marsioma_up_color = instance.parameters.marsioma_up_color;
    marsioma_dn_color = instance.parameters.marsioma_dn_color;
    local name = string.format("%s(%s)", profile:id(), source:name())
    instance:name(name)
    if nameOnly then
        return
    end
    ma = CreateAverages(instance.parameters.ma_period, instance.parameters.ma_method, source);
    RSIOMA = instance.parameters.RSIOMA
    Ma_RSIOMA = instance.parameters.Ma_RSIOMA
    rsi_os = instance.parameters.rsi_os
    rsi_ob = instance.parameters.rsi_ob
    rsi_use_obos = instance.parameters.rsi_use_obos
    MABuffer1 = core.indicators:create("LWMA", source, RSIOMA)
    RSIBuffer1 = core.indicators:create("RSI", MABuffer1.DATA, RSIOMA)
    marsioma1 = core.indicators:create("MVA", RSIBuffer1.DATA, Ma_RSIOMA)
    up_color = instance.parameters.up_color
    down_color = instance.parameters.down_color
    rsi = instance:addStream("RSI", core.Line, "RSI", "RSI", instance.parameters.rsi_color, 0, 0)
    rsi:setWidth(instance.parameters.rsi_width)
    rsi:setStyle(instance.parameters.rsi_style)
    b = instance:addStream("b", core.Bar, "B", "B", up_color, 0, 0)
    marsioma = instance:addStream("marsioma", core.Line, "marsioma", "marsioma", instance.parameters.marsioma_up_color, 0, 0)
    marsioma:setWidth(instance.parameters.marsioma_width)
    marsioma:setStyle(instance.parameters.marsioma_style)
    marsioma:addLevel(rsi_os)
    marsioma:addLevel(rsi_ob)
    indi_alerts:Prepare()
    indi_alerts.source = instance.source
    instance:drawOnMainChart(true)
    instance:ownerDrawn(true)

    marsioma:addLevel(
        instance.parameters.Level1,
        instance.parameters.level_overboughtsold_style,
        instance.parameters.level_overboughtsold_width,
        instance.parameters.level_overboughtsold_color
    )
    marsioma:addLevel(
        instance.parameters.Level2,
        instance.parameters.level_overboughtsold_style,
        instance.parameters.level_overboughtsold_width,
        instance.parameters.level_overboughtsold_color
    )
    marsioma:addLevel(
        instance.parameters.Level3,
        instance.parameters.level_overboughtsold_style,
        instance.parameters.level_overboughtsold_width,
        instance.parameters.level_overboughtsold_color
    )
end

local init = false
local FONT = 1
function Draw(stage, context)
    indi_alerts:Draw(stage, context, source)
    if stage ~= 2 then
        return
    end
    if not init then
        init = true
        context:createFont(FONT, "Arial", 0, context:pointsToPixels(36), context.LEFT)
    end
    if rsi[NOW] <= marsioma[NOW] and rsi[NOW] < 50 then
        local w, h = context:measureText(FONT, "SELLS ONLY", context.LEFT)
        context:drawText(
            FONT,
            "SELLS ONLY",
            core.colors().Red,
            0,
            context:left(),
            context:top(),
            context:left() + w,
            context:top() + h,
            context.LEFT
        )
    elseif rsi[NOW] >= marsioma[NOW] and rsi[NOW] > 50 then
        local w, h = context:measureText(FONT, "BUYS ONLY", context.LEFT)
        context:drawText(
            FONT,
            "BUYS ONLY",
            core.colors().Blue,
            0,
            context:left(),
            context:top(),
            context:left() + w,
            context:top() + h,
            context.LEFT
        )
    end
end

function Update(period, mode)
    ma:update(mode)
    MABuffer1:update(mode)
    RSIBuffer1:update(mode)
    marsioma1:update(mode)
    if RSIBuffer1.DATA[period] <= 50 then
        b[period] = -12
        b:setColor(period, down_color)
    else
        b[period] = 12
        b:setColor(period, up_color)
    end
    rsi[period] = RSIBuffer1.DATA[period]
    marsioma[period] = marsioma1.DATA[period]
    if period > 0 and marsioma[period - 1] < marsioma[period] then
        marsioma:setColor(period, marsioma_up_color);
    else
        marsioma:setColor(period, marsioma_dn_color);
    end
    for _, alert in ipairs(indi_alerts.Alerts) do
        Activate(alert, period, period ~= source:size() - 1)
    end
end

function Activate(alert, period, historical_period)
    if indi_alerts.Live ~= "Live" then
        period = period - 1
    end
    alert.Alert[period] = 0
    if not alert.ON then
        return
    end
    local isUp, upMetadata = alert.UpCondition(period)
    if isUp then
        if alert.OnChange then
            local isUpPrev, _ = alert.UpCondition(period - 1)
            if isUpPrev then
                return
            end
        end
        alert:UpAlert(source, period, source.high[period], historical_period, upMetadata)
        return
    end
    local isDown, downMetadata = alert.DownCondition(period)
    if isDown then
        if alert.OnChange then
            local isDownPrev, _ = alert.DownCondition(period - 1)
            if isDownPrev then
                return
            end
        end
        alert:DownAlert(source, period, source.low[period], historical_period, downMetadata)
    end
end

function AsyncOperationFinished(cookie, success, message, message1, message2)
    indi_alerts:AsyncOperationFinished(cookie, success, message, message1, message2)
end

indi_alerts.last_id = 0
indi_alerts._alerts = {}
indi_alerts._advanced_alert_timer = nil
function indi_alerts:AddParameters(parameters)
    indicator.parameters:addGroup("Alert Mode")
    indicator.parameters:addString("Live", "End of Turn / Live", "", "Live")
    indicator.parameters:addStringAlternative("Live", "End of Turn", "", "End of Turn")
    indicator.parameters:addStringAlternative("Live", "Live", "", "Live")
    indicator.parameters:addBoolean("strategy_output", "Output for strategies", "Used by the strategies", false)

    indicator.parameters:addInteger("ToTime", "Convert the date to", "", 6)
    indicator.parameters:addIntegerAlternative("ToTime", "EST", "", 1)
    indicator.parameters:addIntegerAlternative("ToTime", "UTC", "", 2)
    indicator.parameters:addIntegerAlternative("ToTime", "Local", "", 3)
    indicator.parameters:addIntegerAlternative("ToTime", "Server", "", 4)
    indicator.parameters:addIntegerAlternative("ToTime", "Financial", "", 5)
    indicator.parameters:addIntegerAlternative("ToTime", "Display", "", 6)

    indicator.parameters:addGroup("Alert Style")
    indicator.parameters:addInteger("Size", "Label Size", "", 10, 1, 100)

    indicator.parameters:addGroup("Alerts")
    indicator.parameters:addBoolean("Show", "Show Dialog box Alert", "", false)
    indicator.parameters:addBoolean("ShowAlert", "Show Alert", "", false)

    indicator.parameters:addGroup("Alerts Sound")
    indicator.parameters:addBoolean("PlaySound", "Play Sound", "", false)
    indicator.parameters:addBoolean("RecurrentSound", "Recurrent Sound", "", false)

    indicator.parameters:addGroup("Alerts Email")
    indicator.parameters:addBoolean("SendEmail", "Send Email", "", false)
    indicator.parameters:addString("Email", "Email", "", "")
    indicator.parameters:setFlag("Email", core.FLAG_EMAIL)

    indicator.parameters:addGroup("External Alerts")
    indicator.parameters:addBoolean(
        "use_advanced_alert",
        "Send Advanced Alert",
        "Telegram/Discord/other platform (like MT4)",
        false
    )
    indicator.parameters:addString(
        "advanced_alert_key",
        "Advanced Alert Key",
        "You can get a key via @profit_robots_bot Telegram Bot. Visit ProfitRobots.com for Discord/other platform keys",
        ""
    )
end

function indi_alerts:AsyncOperationFinished(cookie, success, message, message1, message2)
    if cookie == self._advanced_alert_timer and #self._alerts > 0 then
        if self._advanced_alert_key == nil then
            return
        end
        local data = self:ArrayToJSON(self._alerts)
        self._alerts = {}
        local req = http_lua.createRequest()
        local query =
            string.format(
            '{"Key":"%s","StrategyName":"%s","Platform":"FXTS2","Notifications":%s}',
            self._advanced_alert_key,
            string.gsub(self.StrategyName or "", '"', '\\"'),
            data
        )
        req:setRequestHeader("Content-Type", "application/json")
        req:setRequestHeader("Content-Length", tostring(string.len(query)))
        req:start("http://profitrobots.com/api/v1/notification", "POST", query)
    end
end
function indi_alerts:ToJSON(item)
    local json = {}
    function json:AddStr(name, value)
        local separator = ""
        if self.str ~= nil then
            separator = ","
        else
            self.str = ""
        end
        self.str = self.str .. string.format('%s"%s":"%s"', separator, tostring(name), tostring(value))
    end
    function json:AddNumber(name, value)
        local separator = ""
        if self.str ~= nil then
            separator = ","
        else
            self.str = ""
        end
        self.str = self.str .. string.format('%s"%s":%f', separator, tostring(name), value or 0)
    end
    function json:AddBool(name, value)
        local separator = ""
        if self.str ~= nil then
            separator = ","
        else
            self.str = ""
        end
        self.str = self.str .. string.format('%s"%s":%s', separator, tostring(name), value and "true" or "false")
    end
    function json:ToString()
        return "{" .. (self.str or "") .. "}"
    end
    local first = true
    for idx, t in pairs(item) do
        local stype = type(t)
        if stype == "number" then
            json:AddNumber(idx, t)
        elseif stype == "string" then
            json:AddStr(idx, t)
        elseif stype == "boolean" then
            json:AddBool(idx, t)
        elseif stype == "function" or stype == "table" then
        else
            core.host:trace(tostring(idx) .. " " .. tostring(stype))
        end
    end
    return json:ToString()
end
function indi_alerts:ArrayToJSON(arr)
    local str = "["
    for i, t in ipairs(self._alerts) do
        local json = self:ToJSON(t)
        if str == "[" then
            str = str .. json
        else
            str = str .. "," .. json
        end
    end
    return str .. "]"
end
function indi_alerts:AddAlert(label)
    self.last_id = self.last_id + 1
    indicator.parameters:addGroup(label .. " Alert")

    indicator.parameters:addBoolean("ON" .. self.last_id, "Show " .. label .. " Alert", "", true)

    indicator.parameters:addString("drawing_mode" .. self.last_id, "Drawing mode", "", "arrows")
    indicator.parameters:addStringAlternative("drawing_mode" .. self.last_id, "Arrows", "", "arrows")
    indicator.parameters:addStringAlternative("drawing_mode" .. self.last_id, "Vertical lines", "", "vlines")

    indicator.parameters:addFile("Up" .. self.last_id, label .. " Cross Over Sound", "", "")
    indicator.parameters:setFlag("Up" .. self.last_id, core.FLAG_SOUND)
    indicator.parameters:addInteger("UpSymbol" .. self.last_id, "Up Symbol", "", 217)
    indicator.parameters:addColor("UpColor" .. self.last_id, "Up Color", "", core.rgb(0, 255, 0))

    indicator.parameters:addFile("Down" .. self.last_id, label .. " Cross Under Sound", "", "")
    indicator.parameters:setFlag("Down" .. self.last_id, core.FLAG_SOUND)
    indicator.parameters:addInteger("DownSymbol" .. self.last_id, "Down Symbol", "", 218)
    indicator.parameters:addColor("DownColor" .. self.last_id, "Down Color", "", core.rgb(255, 0, 0))

    indicator.parameters:addString("Label" .. self.last_id, "Label", "", label)
end

function indi_alerts:AddSingleAlert(Label)
    self.last_id = self.last_id + 1
    indicator.parameters:addGroup(Label .. " Alert")

    indicator.parameters:addBoolean("ON" .. self.last_id, "Show " .. Label .. " Alert", "", true)

    indicator.parameters:addFile("Up" .. self.last_id, Label .. " Sound", "", "")
    indicator.parameters:setFlag("Up" .. self.last_id, core.FLAG_SOUND)
    indicator.parameters:addInteger("UpSymbol" .. self.last_id, "Symbol", "", 217)
    indicator.parameters:addColor("UpColor" .. self.last_id, "Color", "", core.rgb(0, 255, 0))

    indicator.parameters:addString("Label" .. self.last_id, "Label", "", Label)
end

function indi_alerts:DrawAlert(context, alert, period)
    if not alert.Alert:hasData(period) then
        return
    end

    if alert.Alert[period] == 1 then
        local x = context:positionOfBar(period)
        if alert.DrawingMode == "arrows" then
            visible, y = context:pointOfPrice(alert.AlertLevel[period])
            width, height = context:measureText(self._stages[alert.Stage].FONT_ID, alert.UpSymbol, 0)
            local x1 = x - width / 2
            local x2 = x + width / 2
            local y1, y2
            if self.inverted_arrows then
                y1 = y
                y2 = y + height
            else
                y1 = y - height
                y2 = y
            end
            context:drawText(self._stages[alert.Stage].FONT_ID, alert.UpSymbol, alert.UpColor, -1, x1, y1, x2, y2, 0)
        else
            context:drawLine(alert.UpLinePen, x, context:top(), x, context:bottom())
        end
    elseif alert.Alert[period] == -1 then
        local x = context:positionOfBar(period)
        if alert.DrawingMode == "arrows" then
            visible, y = context:pointOfPrice(alert.AlertLevel[period])
            width, height = context:measureText(self._stages[alert.Stage].FONT_ID, alert.DownSymbol, 0)
            local x1 = x - width / 2
            local x2 = x + width / 2
            local y1, y2
            if self.inverted_arrows then
                y1 = y - height
                y2 = y
            else
                y1 = y
                y2 = y + height
            end
            context:drawText(
                self._stages[alert.Stage].FONT_ID,
                alert.DownSymbol,
                alert.DownColor,
                -1,
                x1,
                y1,
                x2,
                y2,
                0
            )
        else
            context:drawLine(alert.DownLinePen, x, context:top(), x, context:bottom())
        end
    end
end
indi_alerts.NextId = 1
indi_alerts._stages = {}
function indi_alerts:Draw(stage, context)
    if self._stages[stage] == nil then
        self._stages[stage] = {}
        self._stages[stage].createFont = false
        for _, level in ipairs(self.Alerts) do
            if level.Stage == stage then
                if level.DrawingMode == "vlines" then
                    level.UpLinePen = self.NextId
                    self.NextId = self.NextId + 1
                    level.DownLinePen = self.NextId
                    self.NextId = self.NextId + 1
                    context:createPen(level.UpLinePen, context.SOLID, 1, level.UpColor)
                    context:createPen(level.DownLinePen, context.SOLID, 1, level.DownColor)
                else
                    self._stages[stage].createFont = true
                end
            end
        end
        if self._stages[stage].createFont and self._stages[stage].FONT_ID == nil then
            self._stages[stage].FONT_ID = self.NextId
            self.NextId = self.NextId + 1
            context:createFont(
                self._stages[stage].FONT_ID,
                "Wingdings",
                context:pointsToPixels(self.Size),
                context:pointsToPixels(self.Size),
                0
            )
        end
    end
    for period = math.max(context:firstBar(), self.source:first()), math.min(context:lastBar(), self.source:size() - 1), 1 do
        for _, level in ipairs(self.Alerts) do
            if level.Stage == stage then
                self:DrawAlert(context, level, period)
            end
        end
    end
end
indi_alerts.Alerts = {}
function indi_alerts:GetTimezone()
    local tz = instance.parameters.ToTime
    if tz == 1 then
        return core.TZ_EST
    elseif tz == 2 then
        return core.TZ_UTC
    elseif tz == 3 then
        return core.TZ_LOCAL
    elseif tz == 4 then
        return core.TZ_SERVER
    elseif tz == 5 then
        return core.TZ_FINANCIAL
    elseif tz == 6 then
        return core.TZ_TS
    end
end
function indi_alerts:Prepare()
    self.Show = instance.parameters.Show
    self.Live = instance.parameters.Live
    self.ShowAlert = instance.parameters.ShowAlert
    self.ToTime = self:GetTimezone()

    self.Size = instance.parameters.Size
    self.SendEmail = instance.parameters.SendEmail

    self.PlaySound = instance.parameters.PlaySound
    for i = 1, 100 do
        local on = instance.parameters:getBoolean("ON" .. i)
        if on == nil then
            break
        end
        local alert = {}
        alert.id = i
        alert.UpCondition = alerts[i].UpCondition
        alert.FormatMessage = alerts[i].FormatMessage
        alert.DownCondition = alerts[i].DownCondition
        alert.OnChange = alerts[i].OnChange
        alert.Stage = alerts[i].Stage
        alert.FilterConsecutive = alerts[i].FilterConsecutive
        alert.Label = instance.parameters:getString("Label" .. i)
        alert.ON = on
        alert.DrawingMode = instance.parameters:getString("drawing_mode" .. i)
        alert.UpSymbol = string.char(instance.parameters:getInteger("UpSymbol" .. i))
        local down_symbol = instance.parameters:getInteger("DownSymbol" .. i)
        if down_symbol ~= nil then
            alert.DownSymbol = string.char(down_symbol)
        end
        alert.UpColor = instance.parameters:getColor("UpColor" .. i)
        alert.DownColor = instance.parameters:getColor("DownColor" .. i)
        alert.Up = self.PlaySound and instance.parameters:getString("Up" .. i) or nil
        alert.Down = self.PlaySound and instance.parameters:getString("Down" .. i) or nil
        if alert.DownSymbol == nil then
            alert.DownSymbol = alert.UpSymbol
            alert.DownColor = alert.UpColor
            alert.Down = alert.Up
        end
        assert(
            not (self.PlaySound) or (self.PlaySound and alert.Up ~= "") or (self.PlaySound and alert.Up ~= ""),
            "Sound file must be chosen"
        )
        assert(
            not (self.PlaySound) or (self.PlaySound and alert.Down ~= "") or (self.PlaySound and alert.Down ~= ""),
            "Sound file must be chosen"
        )
        alert.U = nil
        alert.D = nil
        if instance.parameters.strategy_output then
            alert.Alert =
                instance:addStream(
                "strat_signal_" .. i,
                core.Dot,
                "strat_signal_" .. i,
                "Strategy signal #" .. i,
                core.rgb(0, 0, 0),
                0,
                0
            )
        else
            alert.Alert = instance:addInternalStream(0, 0)
        end
        alert.AlertLevel = instance:addInternalStream(0, 0)
        function alert:Clear(period)
            local bookmark = self.Alert:getBookmark(i)
            if bookmark ~= period then
                return
            end
            local i = 1
            while (bookmark ~= -1) do
                bookmark = self.Alert:getBookmark(i + 1)
                self.Alert:setBookmark(i, bookmark)
                i = i + 1
            end
        end
        function alert:AddBookmark(period)
            local i = 1
            local bookmark = self.Alert:getBookmark(i)
            if bookmark == period then
                return
            end
            self.Alert:setBookmark(1, period)
            while (bookmark ~= -1) do
                local last_bookmark = self.Alert:getBookmark(i + 1)
                self.Alert:setBookmark(i + 1, bookmark)
                bookmark = last_bookmark
                i = i + 1
            end
        end
        function alert:DownAlert(source, period, level, historical_period, metadata)
            if self.FilterConsecutive then
                local last_signal = self:GetLast(period - 1)
                if last_signal == -1 then
                    return
                end
            end
            local text = self.FormatMessage(source, period, level, self.Label, false, metadata)
            shift = indi_alerts.Live ~= "Live" and 1 or 0
            self.Alert[period] = -1
            self:AddBookmark(period)
            self.AlertLevel[period] = level
            self.U = nil
            if self.D ~= source:date(period) and period == source:size() - 1 - shift then
                self.D = source:date(period)
                if not historical_period then
                    indi_alerts:SoundAlert(self.Down)
                    indi_alerts:EmailAlert(self.Label, text, period)
                    indi_alerts:SendAlert(self.Label, text, period)
                    if indi_alerts.Show then
                        indi_alerts:Pop(self.Label, text)
                    end
                end
            end
        end
        function alert:UpAlert(source, period, level, historical_period, metadata)
            if self.FilterConsecutive then
                local last_signal = self:GetLast(period - 1)
                if last_signal == 1 then
                    return
                end
            end
            local text = self.FormatMessage(source, period, level, self.Label, true, metadata)
            shift = indi_alerts.Live ~= "Live" and 1 or 0
            self.Alert[period] = 1
            self:AddBookmark(period)
            self.AlertLevel[period] = level
            self.D = nil
            if self.U ~= source:date(period) and period == source:size() - 1 - shift then
                self.U = source:date(period)
                if not historical_period then
                    indi_alerts:SoundAlert(self.Up)
                    indi_alerts:EmailAlert(self.Label, text, period)
                    indi_alerts:SendAlert(self.Label, text, period)
                    if indi_alerts.Show then
                        indi_alerts:Pop(self.Label, text)
                    end
                end
            end
        end
        function alert:GetLast(period)
            local index = self.Alert:getBookmark(1)
            if index == -1 then
                return nil
            end
            return self.Alert[index], index, self.AlertLevel[index]
        end
        self.Alerts[#self.Alerts + 1] = alert
    end

    self.Email = self.SendEmail and instance.parameters.Email or nil
    assert(not (self.SendEmail) or (self.SendEmail and self.Email ~= ""), "E-mail address must be specified")
    self.RecurrentSound = instance.parameters.RecurrentSound

    if instance.parameters.advanced_alert_key ~= "" and instance.parameters.use_advanced_alert then
        self._advanced_alert_key = instance.parameters.advanced_alert_key
        require("http_lua")
        self._advanced_alert_timer = 1234
        core.host:execute("setTimer", self._advanced_alert_timer, 1)
    end
end

function indi_alerts:Pop(label, note)
    core.host:execute("prompt", 1, label, self.source:instrument() .. " " .. label .. " : " .. note)
end

function indi_alerts:SoundAlert(Sound)
    if not self.PlaySound then
        return
    end
    terminal:alertSound(Sound, self.RecurrentSound)
end

function indi_alerts:EmailAlert(label, Subject, period)
    if not self.SendEmail then
        return
    end

    local now = self.source:date(period)
    now = core.host:execute("convertTime", core.TZ_EST, self.ToTime, now)
    local DATA = core.dateToTable(now)
    local delim = "\013\010"
    local Note = profile:id() .. delim .. " Label : " .. label .. delim .. " Alert : " .. Subject
    local Symbol = "Instrument : " .. self.source:instrument()
    local Time =
        " Date : " ..
        DATA.month .. " / " .. DATA.day .. " Time:  " .. DATA.hour .. " / " .. DATA.min .. " / " .. DATA.sec
    local TF = "Time Frame : " .. source:barSize()
    local text = Note .. delim .. Symbol .. delim .. TF .. delim .. Time
    terminal:alertEmail(self.Email, profile:id(), text)
end

function indi_alerts:SendAlert(label, Subject, period)
    if not self.ShowAlert then
        return
    end

    local now = self.source:date(period)
    now = core.host:execute("convertTime", core.TZ_EST, self.ToTime, now)
    local DATA = core.dateToTable(now)
    local delim = "\013\010"
    local Note = profile:id() .. delim .. " Label : " .. label .. delim .. " Alert : " .. Subject
    local Symbol = "Instrument : " .. self.source:instrument()
    local Time =
        " Date : " ..
        DATA.month .. " / " .. DATA.day .. " Time:  " .. DATA.hour .. " / " .. DATA.min .. " / " .. DATA.sec
    local TF = "Time Frame : " .. source:barSize()
    local text = Note .. delim .. Symbol .. delim .. TF .. delim .. Time
    terminal:alertMessage(self.source:instrument(), self.source[NOW], text, self.source:date(NOW))
end

function indi_alerts:AlertTelegram(message, instrument, timeframe)
    local alert = {}
    alert.Text = message or ""
    alert.Instrument = instrument or ""
    alert.TimeFrame = timeframe or ""
    self._alerts[#self._alerts + 1] = alert
end
