#property strict
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 Lime
#property indicator_color2 Red

extern int fast_MA_period = 20;
extern int slow_MA_period = 30;
extern int long_MA_period = 250;
extern int rsi_period = 14;
extern int tdi_period = 5;
extern int rsi_buy_level = 40;
extern int rsi_sell_level = 60;

double buySignals[];
double sellSignals[];

int OnInit()
{
    SetIndexBuffer(0, buySignals);
    SetIndexStyle(0, DRAW_ARROW);
    SetIndexArrow(0, 233);  // Arrow code for upward arrow
    SetIndexLabel(0, "Buy Signal");
    SetIndexEmptyValue(0, 0);

    SetIndexBuffer(1, sellSignals);
    SetIndexStyle(1, DRAW_ARROW);
    SetIndexArrow(1, 234);  // Arrow code for downward arrow
    SetIndexLabel(1, "Sell Signal");
    SetIndexEmptyValue(1, 0);

    return(INIT_SUCCEEDED);
}

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
    int startIdx = rates_total - prev_calculated;

    for (int i = startIdx; i >= 0; i--)
    {
        double hl2 = (high[i] + low[i]) / 2;
        double hl2_smooth = iMA(NULL, 0, 13, 0, MODE_SMA, PRICE_TYPICAL, i);
        double hl2_double_smooth = iMA(NULL, 0, 13, 0, MODE_SMA, PRICE_TYPICAL, i);
        double r = 2 * hl2_smooth - hl2_double_smooth;

        double nom = (close[i] > r) ? close[i] - r : 0;
        double denom = (close[i] < r) ? r - close[i] : 0;
        double tdi = (denom != 0) ? 100 * iMAOnArray(ArraySetAsSeries(nom), 0, tdi_period, 0, MODE_SMA, i) / iMAOnArray(ArraySetAsSeries(denom), 0, tdi_period, 0, MODE_SMA, i) : 0;

        double ma_20 = iMA(NULL, 0, fast_MA_period, 0, MODE_SMA, PRICE_CLOSE, i);
        double ma_30 = iMA(NULL, 0, slow_MA_period, 0, MODE_SMA, PRICE_CLOSE, i);
        double ma_250 = iMA(NULL, 0, long_MA_period, 0, MODE_SMA, PRICE_CLOSE, i);
        double rsi = iRSI(NULL, 0, rsi_period, PRICE_CLOSE, i);

        buySignals[i] = 0;
        sellSignals[i] = 0;

        if (ma_20 > ma_30 && ma_20 > ma_250 && tdi > rsi_buy_level && rsi > rsi_buy_level)
        {
            buySignals[i] = low[i] - 10 * Point;  // Adjust the arrow position as needed
        }

        if (ma_20 < ma_30 && ma_20 < ma_250 && tdi < rsi_sell_level && rsi < rsi_sell_level)
        {
            sellSignals[i] = high[i] + 10 * Point;  // Adjust the arrow position as needed
        }
    }

    return(rates_total);
}
