Код: Выделить всё
function Initialize()
{
IndicatorName = "VStop";
PriceStudy = true;
AddInput("I", Inputs.Candle);
AddSeries("vstop", DrawAs.Line, Color.Red, false);
AddSeries("Up", DrawAs.Custom, Color.Green);
AddSeries("Dn", DrawAs.Custom, Color.Red);
AddParameter("length", 20); // atr
AddParameter("mult", 2); // atr mult
AddParameter("period", 1); // average sum bars
AddParameter("O", 0); // 0 - off, 1 - on
AddParameter("H", 0); // 0 - off, 1 - on
AddParameter("L", 0); // 0 - off, 1 - on
AddParameter("C", 1); // 0 - off, 1 - on
AddGlobalVariable("is_uptrend", Types.Boolean, false);
AddGlobalVariable("is_uptrend_prev", Types.Boolean, false);
AddGlobalVariable("max_", Types.Double, 0.0);
AddGlobalVariable("min_", Types.Double, 0.0);
AddGlobalVariable("c", Types.Int, 0);
AddGlobalVariable("sum", Types.DoubleList);
}
function Evaluate()
{
// evge 07.03.2018 http://alfadirect4.ru
// ver 1.2
// добавлен период усреднения, кол-во баров
var atr_ = ATR(I, length);
double d = ((O != 0 ? 1 : 0) + (H != 0 ? 1 : 0) + (L != 0 ? 1 : 0) + (C != 0 ? 1 : 0));
double price = ((O != 0 ? I.Open[0] : 0) + (H != 0 ? I.High[0] : 0) + (L != 0 ? I.Low[0] : 0) + (C != 0 ? I.Close[0] : 0)) / (d == 0 ? 1 : d);
sum.Add(price);
if (sum.Count > period) sum.RemoveAt(0);
price = sum.Average(x=>x);
price = price == 0 ? I.Close[0] : price;
double max1 = Math.Max(max_, price);
double min1 = Math.Min(min_, price);
is_uptrend_prev = is_uptrend;
double stop = is_uptrend_prev ? max1 - mult * atr_[0] : min1 + mult * atr_[0];
double vstop_prev = CurrentIndex > length ? vstop[1] : 0.0;
double vstop1 = is_uptrend_prev ? Math.Max(vstop_prev, stop) : Math.Min(vstop_prev, stop);
is_uptrend = (price - vstop1) >= 0;
bool is_trend_changed = is_uptrend != is_uptrend_prev;
max_ = is_trend_changed ? price : max1;
min_ = is_trend_changed ? price : min1;
vstop = is_trend_changed ? is_uptrend ? max_ - mult * atr_ : min_ + mult * atr_ : vstop1;
c += is_uptrend != is_uptrend_prev ? -c : 1;
if (is_uptrend)
{ Up[0] = vstop[0]; if (c > 0) Up.DrawLine(); }
else
{ Dn[0] = vstop[0]; if (c > 0) Dn.DrawLine(); }
}