Adaptive Trend Sabre
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «source code by @fundedmillionairess.mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Индикатор «Adaptive Trend Sabre» для MetaTrader 5 предназначен для анализа и визуализации трендов на основе скользящих средних различных типов и волатильности, рассчитываемой через ATR. Он отображает на графике линию скользящей средней и линию следования тренду (trail), раскрашивает свечи в зависимости от текущего направления движения цены.
Индикатор строит уровни поддержки и сопротивления (Snap Levels) при резких отклонениях цены от скользящей средней и автоматически удаляет уровни при их пробое. При смене направления тренда и при обнаружении повторных тестов уровней или линии следования на графике появляются маркеры-сигналы, а через Alert отправляются уведомления.
В настройках пользователь может выбрать тип и длину скользящей средней, параметры расчёта ATR, количество отображаемых уровней, цвета и виды визуальных элементов. Индикатор работает на графике любого инструмента и таймфрейма, при условии наличия не менее 200 баров.
Настройки программы
| Настройка | Описание |
|---|---|
| InpShowCandles | Переключатель отображения раскрашенных свечей на графике в зависимости от направления текущего тренда. |
| InpShowMALine | Режим отображения линии скользящей средней: всегда видима, скрыта или показывается только при смене тренда. |
| InpShowTrailLine | Режим отображения линии следования тренду (trail): всегда видима, скрыта или показывается только при смене тренда. |
| InpShowSnapLevels | Переключатель отображения уровней поддержки и сопротивления, построенных при резких отклонениях цены от скользящей средней. |
| InpShowSignals | Переключатель отображения маркеров сигналов о смене тренда на графике. |
| InpShowRetests | Переключатель показа маркеров повторных тестов уровней и линии следования тренда. |
| InpMAType | Тип расчитываемой скользящей средней: EMA, SMA, WMA, HMA, DEMA, TEMA, VWMA, ALMA или LSMA. |
| InpMALen | Длина периода расчёта скользящей средней, задаётся целым числом от 1 до 200. |
| InpTrailFactor | Множитель ATR, определяющий расстояние линии следования тренду (trail) от скользящей средней. |
| InpSnapThresh | Пороговое значение в долях ATR, при превышении которого цена считается резко отклонившейся от скользящей средней и фиксируется экстремум для построения уровня. |
| InpLevelBuffer | Буфер в долях ATR, определяющий допустимое отклонение цены от уровня перед признанием его пробитым и удалением с графика. |
| InpMaxLevels | Максимальное количество уровней поддержки и сопротивления, одновременно отображаемых на графике. При превышении лимита старый уровень удаляется. |
| InpRetestCD | Минимальное количество баров между последовательными сигналами повторного теста уровней или линии следования, задаётся целым числом от 2 до 20. |
| InpColorUp | Цвет отображения бычьих свечей, линии следования в восходящем тренде и соответствующих маркеров сигналов. |
| InpColorDown | Цвет отображения медвежьих свечей, линии следования в нисходящем тренде и соответствующих маркеров сигналов. |
| InpATRPeriod | Период расчёта индикатора Average True Range (ATR), используемого для определения волатильности и расчёта расстояния следования, порога снапа и буфера уровней. |
Поиск по коду файла
#property version "2.00"
#property description "We crack MT4 n MT5 Indicators/Robots."
#property description "We convert MT4/MT5 Indicators to Robots."
#property description "."
#property description "CRACKED BY @FundedMillionAiress"
#property description "."
#property description "Instagram = @FundedMillionAiress"
#property description "."
#property description "Telegram = @FundedMillionAiress"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 2
#property indicator_label1 "Trend MA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 C'128,128,128' // Gray
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
#property indicator_label2 "Trail"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrLimeGreen
#property indicator_style2 STYLE_SOLID
#property indicator_width2 2
enum MAType {
MA_EMA, // EMA
MA_SMA, // SMA
MA_WMA, // WMA
MA_HMA, // HMA
MA_DEMA, // DEMA
MA_TEMA, // TEMA
MA_VWMA, // VWMA
MA_ALMA, // ALMA
MA_LSMA // LSMA
};
enum VisibleMode {
VISIBLE_ALWAYS, // Always Visible
VISIBLE_NEVER, // Always Hidden
VISIBLE_CHANGE_ONLY // Show Only on Trend Change
};
struct SnapLevel {
double price;
bool isResistance;
int originBar;
string lineName;
datetime originTime;
SnapLevel() {
price = 0;
isResistance = false;
originBar = 0;
lineName = "";
originTime = 0;
}
};
input bool InpShowCandles = true; // Show Colored Candles
input VisibleMode InpShowMALine = VISIBLE_ALWAYS; // Show MA Line
input VisibleMode InpShowTrailLine = VISIBLE_ALWAYS; // Show Trail Line
input bool InpShowSnapLevels = false; // Show Snap Levels
input bool InpShowSignals = true; // Show Signal Markers
input bool InpShowRetests = true; // Show Retest Markers
input MAType InpMAType = MA_HMA; // MA Type
input int InpMALen = 34; // MA Length (1-200)
input double InpTrailFactor = 3.25; // Trail Distance (ATR)
input double InpSnapThresh = 2.0; // Snap Threshold (ATR)
input double InpLevelBuffer = 0.25; // Level Break Buffer (ATR)
input int InpMaxLevels = 8; // Maximum Levels (2-20)
input int InpRetestCD = 5; // Retest Cooldown (2-20)
input color InpColorUp = clrLimeGreen; // Bullish Color
input color InpColorDown = clrRed; // Bearish Color
input int InpATRPeriod = 14; // ATR Period
double MABuffer[];
double TrailBuffer[];
int trend = 1; // 1 = bullish, -1 = bearish
double trail = 0;
double prevTrail = 0;
int prevTrend = 1;
SnapLevel levels[];
bool wasSnapUp = false;
bool wasSnapDown = false;
double snapHigh = 0;
double snapLow = 0;
int snapHighBar = -1;
int snapLowBar = -1;
datetime snapHighTime = 0;
datetime snapLowTime = 0;
int lastRetestBar = 0;
string levelPrefix = "ATS_LEVEL_";
string signalPrefix = "ATS_SIGNAL_";
string candlePrefix = "ATS_CANDLE_";
int levelCounter = 0;
int signalCounter = 0;
double atrValues[];
double emaValues[];
double hmaRawValues[];
int OnInit() {
// код доступен только после оплаты
}
void UpdateLineVisibility() {
switch(InpShowMALine) {
case VISIBLE_ALWAYS:
PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_LINE);
break;
case VISIBLE_NEVER:
PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_NONE);
break;
case VISIBLE_CHANGE_ONLY:
PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_LINE);
break;
}
switch(InpShowTrailLine) {
case VISIBLE_ALWAYS:
PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_LINE);
break;
case VISIBLE_NEVER:
PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_NONE);
break;
case VISIBLE_CHANGE_ONLY:
PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_LINE);
break;
}
}
void OnDeinit(const int reason) {
ObjectsDeleteAll(0, levelPrefix);
ObjectsDeleteAll(0, signalPrefix);
ObjectsDeleteAll(0, candlePrefix);
}
double CalculateEMA(int index, const double &close[], int period) {
if(index < 0) return close[0];
if(index == 0) {
emaValues[index] = close[0];
return close[0];
}
if(index < period) {
emaValues[index] = close[index];
return close[index];
}
if(index == period) {
double sum = 0;
for(int i = 0; i < period; i++) {
sum += close[index - i];
}
emaValues[index] = sum / period;
return emaValues[index];
}
double alpha = 2.0 / (period + 1.0);
emaValues[index] = close[index] * alpha + emaValues[index-1] * (1 - alpha);
return emaValues[index];
}
double CalculateSMA(int index, const double &close[], int period) {
if(index < period) return close[index];
double sum = 0;
for(int i = 0; i < period; i++) {
sum += close[index - i];
}
return sum / period;
}
double CalculateWMA(int index, const double &close[], int period) {
if(index < period) return close[index];
double sum = 0;
double weightSum = 0;
for(int i = 0; i < period; i++) {
double weight = period - i;
sum += close[index - i] * weight;
weightSum += weight;
}
return sum / weightSum;
}
double CalculateHMA(int index, const double &close[], int period) {
if(index < period * 2) return close[index];
int halfPeriod = (int)MathFloor(period / 2);
if(halfPeriod < 1) halfPeriod = 1;
int sqrtPeriod = (int)MathFloor(MathSqrt(period));
if(sqrtPeriod < 1) sqrtPeriod = 1;
double wmaHalf = CalculateWMA(index, close, halfPeriod);
double wmaFull = CalculateWMA(index, close, period);
double rawHMA = 2 * wmaHalf - wmaFull;
hmaRawValues[index] = rawHMA;
if(index < sqrtPeriod) return rawHMA;
double sum = 0;
double weightSum = 0;
for(int i = 0; i < sqrtPeriod; i++) {
double weight = sqrtPeriod - i;
sum += hmaRawValues[index - i] * weight;
weightSum += weight;
}
return sum / weightSum;
}
double CalculateVWMA(int index, const double &close[], int period) {
if(index < period) return close[index];
double sumPV = 0;
double sumV = 0;
for(int i = 0; i < period; i++) {
long volume = (long)iVolume(_Symbol, _Period, index - i);
sumPV += close[index - i] * volume;
sumV += volume;
}
return (sumV > 0) ? sumPV / sumV : close[index];
}
double CalculateALMA(int index, const double &close[], int period) {
if(index < period) return close[index];
double sigma = 6.0;
double offset = 0.85;
double m = MathFloor(offset * (period - 1));
double s = period / sigma;
double sum = 0;
double weightSum = 0;
for(int i = 0; i < period; i++) {
double weight = MathExp(-MathPow(i - m, 2) / (2 * s * s));
sum += close[index - i] * weight;
weightSum += weight;
}
return (weightSum > 0) ? sum / weightSum : close[Показано первые 50% кода (символов: 18035)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.