TSSuperTrendSTS
Download scriptThis script is a technical analysis tool designed to identify and visualize market trends on a trading chart. Its primary goal is to help traders distinguish between upward (bullish) and downward (bearish) price movements by calculating a dynamic "trend line" that adapts to market volatility.
Core Logic Overview
The logic operates by combining three main components: Price Smoothing, Volatility Calculation, and Trend Detection.
1. Price Smoothing (The Foundation) Instead of looking at raw, jagged price movements which can contain "noise," the script first smooths the price data. It offers several different methods for this calculation (such as Simple Moving Averages or more advanced filters). This ensures that the resulting trend line is fluid and doesn't react erratically to every minor price fluctuation.
2. Volatility Offsets (The Buffer) To determine how far the "trend line" should sit away from the current price, the script uses a volatility measurement. It provides two distinct modes for this:
- ATR Mode: Uses a standard volatility indicator to create a buffer zone around the price.
- Dual Thrust Mode: A specialized calculation that looks at the range between recent highs and lows to determine the buffer size.
By multiplying this volatility by a user-defined factor, the script creates a "safety zone." This prevents the trend from flipping back and forth too quickly during choppy markets.
3. Trend Switching Mechanics The script constantly monitors the relationship between the current market price and its calculated trend line:
- Bullish Flip: If the price closes above the previous downward trend line, the script identifies a shift to an "UpTrend." It then draws a line below the price.
- Bearish Flip: If the price closes below the previous upward trend line, the script identifies a shift to a "DownTrend." It then draws a line above the price.
4. Visual and Audible Feedback To make the data actionable for the user, the script provides several visual cues:
- Dynamic Lines: It plots colored lines that follow the price movement based on the current trend.
- Directional Arrows: When a trend flip occurs (from up to down or vice versa), the script places arrows on the chart to signal the exact point of the reversal.
- Color Coding: The script can change the color of the actual trading candles to match the current trend (e.g., turning them blue for up-trends and red for down-trends).
- Audio Alerts: It can trigger sound notifications at the moment a trend shift is detected, allowing traders to react in real-time without constantly staring at the screen.
Summary of Operation
In short, the script filters out market noise using moving averages, measures how "wild" the market is moving to create a buffer zone, and then watches for the price to break through that buffer. When it does, the script signals a trend change through visual lines, arrows, candle colors, and sound alerts.
//+------------------------------------------------------------------+
//| TSSuperTrend.mq4 |
//+------------------------------------------------------------------+
#property link "http://www.backtothefuturetrading.com/"
#include <stderror.mqh>
#include <stdlib.mqh>
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 Lime
#property indicator_color2 Red
#property indicator_color3 Lime
#property indicator_color4 Red
#property indicator_width1 1
#property indicator_width2 1
#property indicator_width3 2
#property indicator_width4 2
extern string Modes = "Key: 1-ATR, 2-Dual Thrust";
extern int SuperTrendMode = 1;
extern int SuperTrendPeriod = 3;
extern double Multiplier = 2.314;
extern string SmoothingTypes ="Key: 1-EMA, 2-SMA, 3-NLMA, 4-WMA, 5-ESF, 6-SMMA";
extern int SmoothingMAtype = 3;
extern int SmoothingPeriod = 3;
extern string msg1="- - - - Alerts - - - - -";
extern string BuySound = "alert2.wav";
extern string SellSound = "alert2.wav";
extern string msg2="- - - - Visual - - - - -";
extern bool ShowArrows = true;
extern bool ColorBars = false;
extern color UpTrendColor = Blue;
extern color DownTrendColor = Red;
extern int CandleWidth = 4;
extern int WickWidth = 1;
//==============================================
int FLAT = 0;
int UPTREND = 1;
int DOWNTREND = -1;
int CurrentBar = -1;
double TrendUpPlot[], TrendDownPlot[],ArrowsUp[], ArrowsDn[];
double smoothingMA[], trend[];
double offset = 0;
datetime currentbartime = 0;
color BarColor = White;
color prevColor = White;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
DeleteObject("ErrorLabel");
if(!ObjectCreate("ErrorLabel", OBJ_LABEL, 0, 0, 0)) Alert("Error creating error label");
ObjectSetText("ErrorLabel", " ", 10, "Arial", Red);
ObjectSet("ErrorLabel", OBJPROP_XDISTANCE, 10);
ObjectSet("ErrorLabel", OBJPROP_YDISTANCE, 30);
CheckError(74,Bars-1);
IndicatorBuffers(6);
SetIndexBuffer(0, TrendUpPlot);
SetIndexStyle(0, DRAW_LINE);
SetIndexLabel(0, "Trend Up");
SetIndexBuffer(1, TrendDownPlot);
SetIndexStyle(1, DRAW_LINE);
SetIndexLabel(1, "Trend Down");
SetIndexBuffer(2, ArrowsUp);
SetIndexStyle(2, DRAW_ARROW);
SetIndexArrow(2, 233);
SetIndexLabel(2, "ArrowsUp");
SetIndexBuffer(3, ArrowsDn);
SetIndexStyle(3, DRAW_ARROW);
SetIndexArrow(3, 234);
SetIndexLabel(3, "ArrowsDn");
SetIndexBuffer(4, smoothingMA);
SetIndexBuffer(5, trend);
prevColor = UpTrendColor;
BarColor = UpTrendColor;
CheckError(94,Bars-1);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
int p = ObjectsTotal();
while(p>=0) {
string name = ObjectName(p);
if(StringFind(name, "tssbar", 0)==0) ObjectDelete(name);
p--;
}
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start() {
int limit;
int counted_bars = IndicatorCounted();
//---- check for possible errors
if(counted_bars < 0) return(-1);
limit=Bars-counted_bars-1;
if(counted_bars!=0) limit++;
//----
for (int i = limit; i >= 0; i--) {
CurrentBar++;
if(CurrentBar<MathMax(SmoothingPeriod,SuperTrendPeriod)*2) {
trend[i] = UPTREND;
TrendUpPlot[i] = Close[i];
TrendDownPlot[i] = Close[i];
}
CheckError(221,i);
if(Time[i]!=currentbartime) { //this is the first tick of this new bar
currentbartime = Time[i];
}
CheckError(225,i);
if(SmoothingMAtype==1) smoothingMA[i] = iMA(NULL,0,SmoothingPeriod, 0, MODE_EMA, PRICE_CLOSE, i);
else if(SmoothingMAtype==2) smoothingMA[i] = iMA(NULL,0,SmoothingPeriod, 0, MODE_SMA, PRICE_CLOSE, i);
else if(SmoothingMAtype==3) smoothingMA[i] = iCustom(NULL,0,"NonLagMA_v7.1",0,SmoothingPeriod,0,0.0,0,1,0.0,0,0,0,i);
else if(SmoothingMAtype==4) smoothingMA[i] = iMA(NULL,0,SmoothingPeriod, 0, MODE_LWMA, PRICE_CLOSE, i);
else if(SmoothingMAtype==5) smoothingMA[i] = iCustom(NULL,0,"Ehlers Two Pole Super Smoother Filter",SmoothingPeriod,0,i);
else if(SmoothingMAtype==6) smoothingMA[i] = iMA(NULL,0,SmoothingPeriod, 0, MODE_SMMA, PRICE_CLOSE, i);
CheckError(234,i);
if(SuperTrendMode == 1) offset = iATR(NULL,0,SuperTrendPeriod,i)*Multiplier;
else if(SuperTrendMode == 2) offset = DTT(SuperTrendPeriod,Multiplier,i);
CheckError(239,i);
if(i==0 || (counted_bars==0 && i!=limit)) {
if (TrendDownPlot[i+1] != EMPTY_VALUE && Close[i]>TrendDownPlot[i+1]) {
trend[i]=UPTREND;
}
else if (TrendUpPlot[i+1] != EMPTY_VALUE && Close[i]<TrendUpPlot[i+1]) {
trend[i]=DOWNTREND;
}
else trend[i]=trend[i+1];
}
CheckError(249,i);
if (trend[i]>FLAT && trend[i+1]<FLAT) {
TrendDownPlot[i] = EMPTY_VALUE;
TrendUpPlot[i] = smoothingMA[i]-offset;
BarColor = UpTrendColor;
if(ShowArrows) ArrowsUp[i] = TrendUpPlot[i]-Point;
if(i==0) PlaySound(BuySound);
}
else if (trend[i]<FLAT && trend[i+1]>FLAT) {
TrendDownPlot[i] = smoothingMA[i]+offset;
TrendUpPlot[i] = EMPTY_VALUE;
BarColor = DownTrendColor;
if(ShowArrows) ArrowsDn[i] = TrendDownPlot[i]+Point;
if(i==0) PlaySound(SellSound);
} else {
if (trend[i]>FLAT) {
if(smoothingMA[i] - offset > TrendUpPlot[i+1]) TrendUpPlot[i] = smoothingMA[i] - offset; else TrendUpPlot[i] = TrendUpPlot[i+1];
} else {
if(smoothingMA[i] + offset < TrendDownPlot[i+1]) TrendDownPlot[i] = smoothingMA[i] + offset; else TrendDownPlot[i] = TrendDownPlot[i+1];
}
BarColor = prevColor;
}
CheckError(273,i);
if(ColorBars && i<200) {
string linename = "tssbarw"+TimeStr(Time[i]);
if(ObjectFind(linename)>=0) ObjectDelete(linename);
if(High[i]!=Low[i]) {
ObjectCreate(linename,OBJ_TREND,0,Time[i], High[i], Time[i], Low[i]);
ObjectSet(linename, OBJPROP_COLOR, BarColor);
ObjectSet(linename, OBJPROP_WIDTH, WickWidth);
ObjectSet(linename, OBJPROP_RAY, false);
}
linename = "tssbarb"+TimeStr(Time[i]);
if(ObjectFind(linename)>=0) ObjectDelete(linename);
if(Open[i]!=Close[i]) {
ObjectCreate(linename,OBJ_TREND,0,Time[i], Open[i], Time[i], Close[i]);
ObjectSet(linename, OBJPROP_COLOR, BarColor);
ObjectSet(linename, OBJPROP_WIDTH, CandleWidth);
ObjectSet(linename, OBJPROP_RAY, false);
}
prevColor = BarColor;
}
}
//----
return(0);
}
//=================================================================================
double DTT(int nDay, double mult, int shift)
{
double HH = MAX(PRICE_HIGH, nDay, shift);
double HC = MAX(PRICE_CLOSE,nDay, shift);
double LL = MIN(PRICE_LOW, nDay, shift);
double LC = MIN(PRICE_CLOSE, nDay, shift);
return (mult * MathMax((HH - LC),(HC - LL)));
}
//=================================================================================
double MAX(int type, int period, int shift) {
double p = -1000.0;
for(int j = 0; j<period; j++){
switch(type) {
case PRICE_HIGH: p = MathMax(High[j+shift],p); break;
case PRICE_LOW: p = MathMax(Low[j+shift],p); break;
case PRICE_CLOSE: p = MathMax(Close[j+shift],p); break;
case PRICE_OPEN: p = MathMax(Open[j+shift],p); break;
}
}
return (p);
}
//=================================================================================
double MIN(int type, int period, int shift) {
double p = Close[shift]*10;
for(int j = 0; j<period; j++){
switch(type) {
case PRICE_HIGH: p = MathMin(High[j+shift],p); break;
case PRICE_LOW: p = MathMin(Low[j+shift],p); break;
case PRICE_CLOSE: p = MathMin(Close[j+shift],p); break;
case PRICE_OPEN: p = MathMin(Open[j+shift],p); break;
}
}
return (p);
}
//=================================================================================
string TimeStr(datetime t) {
string result = DoubleToStr(TimeYear(t),0);
string temp = DoubleToStr(TimeMonth(t),0); if(StringLen(temp)==1) temp = "_"+temp;
result = result + temp;
temp = DoubleToStr(TimeDay(t),0); if(StringLen(temp)==1) temp = "_"+temp;
result = result + temp;
temp = DoubleToStr(TimeHour(t),0); if(StringLen(temp)==1) temp = "_"+temp;
result = result + temp;
temp = DoubleToStr(TimeMinute(t),0); if(StringLen(temp)==1) temp = "_"+temp;
result = result + temp;
temp = DoubleToStr(TimeSeconds(t),0);
result = result + temp;
return(result);
}
//=================================================================================
void CheckError(int line, int RelBar)
{
int err = GetLastError();
if(err > ERR_NO_RESULT) {
string msg="";
if(msg=="") msg = "RBT_Intel: "+TimeToStr(Time[0], TIME_MINUTES)+", "+ErrorDescription(err)+" (#"+err+" ";
Alert(msg);
if(RelBar>=0) {
}
}
}
//=================================================================================
void DeleteObject(string name) {
if(ObjectFind(name)!=-1) ObjectDelete(name);
}
//=================================================================================
Comments