Re: TradingView Indicators to MT4 Indicators

721
BeatlemaniaSA wrote: Tue Mar 17, 2026 10:01 pm Hi Cagliostro,

I know you don't really do MT4 coding as you are focusing on your mega MT5 suite of indicators, but is there any chance to update this version so that we can adjust the colours, size, and type of the lines? You've hard-coded the lines, so I'm kinda stuck with the defaults.

Always appreciative of the amazing coding you do.

Kind regards,
Beatle 🪲
Sure mate.

Here you go, alerts added too ;)
These users thanked the author Cagliostro for the post (total 2):
BeatlemaniaSA, thomdel
"I conjure from shadows and shape fortunes from the unseen. The treasure lies hidden in plain sight, beneath the sunlight." - Cagliostro

Re: TradingView Indicators to MT4 Indicators

722
Cagliostro wrote: Wed Mar 18, 2026 3:56 am Sure mate.

Here you go, alerts added too ;)
Awesome, thanks mate. :thumbup: :D
Millionaire Maker - “Amateurs chase. Professionals wait. Legends wait with a plan.”

BEATS V5 - "Enjoy The Quiet Between Trades”
Improve Your Trading Psychology - No fear, no doubt
Ultimate Risk Management - Maximize Your Trades
Supply and Demand Course - Learn Supply and Demand
Believe That You Can - Believe That You Can

Re: TradingView Indicators to MT4 Indicators

723
Cagliostro wrote: Wed Mar 18, 2026 3:56 am Sure mate.

Here you go, alerts added too ;)
Hi Cagliostro,

I just discovered a bug in the indicator. If the user sets the width of the trend line to anything greater than 5 or less than 1, the indicator crashes and deletes itself from the chart. There's no safety check, so maybe have a check that if the value is greater than 5 or less than 1, it automatically reverts to the lowest or highest allowed value. Or have the trend width limits from 0 to 10. It never hurts to have a really thick line ;) :D

Regards,
Beatle 🪲
Millionaire Maker - “Amateurs chase. Professionals wait. Legends wait with a plan.”

BEATS V5 - "Enjoy The Quiet Between Trades”
Improve Your Trading Psychology - No fear, no doubt
Ultimate Risk Management - Maximize Your Trades
Supply and Demand Course - Learn Supply and Demand
Believe That You Can - Believe That You Can

Re: TradingView Indicators to MT4 Indicators

724
BeatlemaniaSA wrote: Wed Mar 18, 2026 4:41 am Hi Cagliostro,

I just discovered a bug in the indicator. If the user sets the width of the trend line to anything greater than 5 or less than 1, the indicator crashes and deletes itself from the chart. There's no safety check, so maybe have a check that if the value is greater than 5 or less than 1, it automatically reverts to the lowest or highest allowed value. Or have the trend width limits from 0 to 10. It never hurts to have a really thick line ;) :D

Regards,
Beatle 🪲
Clamped to standard 5 max for lines.
These users thanked the author Cagliostro for the post (total 6):
BeatlemaniaSA, RodrigoRT7, thomdel, Tsar, specialkey, LAMA
"I conjure from shadows and shape fortunes from the unseen. The treasure lies hidden in plain sight, beneath the sunlight." - Cagliostro

Re: TradingView Indicators to MT4 Indicators

725
SonOfTheLivermore wrote: Sat Mar 14, 2026 4:02 am Adaptive Kalman filter - Trend Strength Oscillator (Zeiierman)
https://tradingview.com/script/PDi6enZR ... Zeiierman/ 

ChatGPT's analysis of the indicator using the supplied Pinescript.

Code: Select all

 This is actually a **very sophisticated indicator**, and understanding it properly requires breaking it into several layers:

1. **The Kalman filter engine**
2. **The oscillator extracted from the Kalman model**
3. **Trend strength normalization**
4. **Smoothing and signal logic**
5. **Visual interpretation (signals for traders)**

I will walk through **exactly what the indicator is doing mathematically and logically**, and then explain **how it generates signals in trading terms**.

---

# 1. Core Concept of the Indicator

The **Adaptive Kalman Trend Strength Oscillator** is essentially a **Kalman-filter-based trend detector** that converts the **hidden velocity of price** into a **normalized oscillator representing trend strength**.

In simple terms:

**Price → Kalman Filter → Extract price velocity → Normalize → Smooth → Trend Strength Oscillator**

So instead of measuring trend with:

* moving averages
* RSI
* MACD

…it measures **the internal motion of price estimated by a Kalman filter model**.

---

# 2. The Kalman Filter Model

This indicator uses a **2-state Kalman filter**.

The two states are:

```
State 1 = Estimated Price
State 2 = Estimated Trend Velocity
```

This is implemented here:

```
var X = array.from(0.0, 0.0)
```

Where:

```
X[0] = filtered price estimate
X[1] = trend velocity (oscillator)
```

---

## State Transition Model

The filter predicts the next state using matrix **F**:

```
F =
[1 1]
[0 1]
```

Meaning:

```
New Price = Old Price + Velocity
New Velocity = Old Velocity
```

So the model assumes:

**Price changes according to its velocity**.

This is exactly how many **institutional signal processing models** estimate trend.

---

# 3. Kalman Prediction Step

Each bar:

```
x1 = F00 * price + F01 * velocity
x2 = F11 * velocity
```

Which becomes:

```
x1 = price + velocity
x2 = velocity
```

So the filter predicts where price *should* go based on current velocity.

Then uncertainty is updated:

```
P = F * P * F' + Q
```

Where:

**P** = covariance matrix
**Q** = process noise

---

# 4. Adaptive Noise Models

The indicator offers **three Kalman filter models**:

### 1️⃣ Standard

Uses constant measurement noise.

```
R = measurement_noise
```

This produces **stable smoothing**.

---

### 2️⃣ Volume Adjusted

Measurement noise is scaled by **volume change**.

```
R_adjusted = R * volume[1] / min(volume[1], volume)
```

Meaning:

If **volume rises**, the filter trusts price **more**.

This makes the filter **react faster during high activity**.

---

### 3️⃣ Parkinson Adjusted

Uses **high-low volatility**.

```
range_ratio = current_range / previous_range
parkinson_scaled = 1 + range_ratio
```

Meaning:

When **range expands**, measurement noise increases.

This causes the filter to **adapt to volatility spikes**.

---

# 5. Measurement Update

Kalman correction step:

```
innovation = actual price - predicted price
```

Then the **Kalman gain** determines how much to adjust:

```
K = P * H' * (H * P * H' + R)^-1
```

Then state update:

```
X = X + K * innovation
```

So the filter continuously **balances prediction vs real price**.

---

# 6. What the Oscillator Actually Is

This is the most important line in the code:

```
oscillator = array.get(X, 1)
```

Remember:

```
X[1] = velocity estimate
```

So the oscillator is simply:

**Estimated price velocity.**

Meaning:

```
positive velocity → price trending up
negative velocity → price trending down
```

---

# 7. Converting Velocity Into Trend Strength

Velocity alone isn't useful because it depends on price scale.

So the indicator **normalizes it**.

First it stores velocity values:

```
array.push(osc_buffer, oscillator)
```

Then it finds the **maximum absolute velocity** in the lookback:

```
A = osc_buffer.abs().max()
```

Then normalizes:

```
trend_strength = oscillator / A * 100
```

This creates a **percentage scale**.

```
+100 = strongest uptrend in lookback
-100 = strongest downtrend
```

---

# 8. Trend Strength Smoothing

Two layers of smoothing exist.

### Oscillator smoothing

```
plot(ta.wma(trend_strength,R1))
```

### Strength smoothing

```
trend_strength := ta.wma(...,R2)
```

So the final oscillator is **double smoothed**.

This prevents noisy spikes.

---

# 9. Signal Levels

The indicator defines levels:

```
70  = strong uptrend
0   = neutral
-70 = strong downtrend
```

These are **trend strength zones**.

---

# 10. Color Gradient Logic

The indicator converts trend strength into **visual intensity**.

```
num_segments = 10
segment_width = 10
```

Meaning each segment equals **10% strength**.

The stronger the trend:

```
more segments light up
```

Color rules:

```
positive strength → green gradient
negative strength → red gradient
neutral → blue
```

So visually you see **trend acceleration**.

---

# 11. Secondary Plot (Important)

The script also plots the **Kalman filtered price**:

```
kalmanPlot = plot(filtered_src)
```

This is **not the oscillator**.

It is the **smoothed price estimate from the Kalman filter**.

Think of it like a **super-adaptive moving average**.

---

# 12. What the Indicator Is Measuring (True Meaning)

Most oscillators measure:

* overbought/oversold
* momentum
* mean reversion

This indicator measures something different:

**Trend velocity strength.**

Specifically:

```
Trend Strength =
Normalized Kalman Estimated Velocity
```

---

# 13. Trading Interpretation

### Strong Uptrend

When oscillator > 70

Meaning:

```
price acceleration upward is strong
```

Use case:

```
trend continuation entries
```

---

### Strong Downtrend

When oscillator < -70

Meaning:

```
price acceleration downward is strong
```

Use case:

```
short continuation
```

---

### Zero Line Cross

When oscillator crosses **0**:

```
velocity changes direction
```

Meaning:

```
trend reversal beginning
```

---

### Rising Strength

When oscillator rises from:

```
20 → 50 → 80
```

It means:

```
trend acceleration is increasing
```

This often happens **before large moves**.

---

### Falling Strength

When oscillator drops:

```
90 → 60 → 30
```

It means:

```
trend momentum is weakening
```

Often precedes **trend exhaustion**.

---

# 14. What Makes This Indicator Unique

Compared to standard indicators:

| Indicator | Measures                   |
| --------- | -------------------------- |
| RSI       | mean reversion             |
| MACD      | moving average difference  |
| ADX       | directional trend strength |
| CCI       | deviation from mean        |

This indicator measures:

**Hidden trend velocity estimated via Kalman filtering.**

This makes it:

* smoother
* more adaptive
* less laggy

---

# 15. Potential Weaknesses

Despite its sophistication:

### Lag from smoothing

Two WMAs add delay.

---

### Normalization distortion

Using:

```
max(abs(velocity))
```

means the oscillator **rescales constantly**.

So historical values shift slightly.

---

### Sensitivity to parameters

Changing:

```
process_noise
measurement_noise
```

can radically change behaviour.

---

# 16. Why This Indicator Can Work Well in Forex

Forex trends are often:

```
slow → accelerating → exhaustion
```

This indicator captures exactly that pattern because it measures:

**trend acceleration**.

---

# 17. The Hidden Insight

The oscillator is effectively detecting:

```
d(price) / dt
```

But **Kalman-smoothed**.

Meaning it estimates **true market velocity**, not just candle change.

---

# 18. Summary

The indicator works as follows:

1️⃣ Kalman filter estimates **true price and velocity**

2️⃣ Velocity becomes the **oscillator**

3️⃣ Velocity is normalized into **trend strength %**

4️⃣ Strength is smoothed

5️⃣ Gradient colors visualize trend intensity

---

### In one sentence:

**This indicator measures the strength of price trend by estimating the hidden velocity of price using an adaptive Kalman filter and converting that velocity into a normalized oscillator.**
These users thanked the author BeatlemaniaSA for the post (total 3):
eduarescobar, SonOfTheLivermore, Cagliostro
Millionaire Maker - “Amateurs chase. Professionals wait. Legends wait with a plan.”

BEATS V5 - "Enjoy The Quiet Between Trades”
Improve Your Trading Psychology - No fear, no doubt
Ultimate Risk Management - Maximize Your Trades
Supply and Demand Course - Learn Supply and Demand
Believe That You Can - Believe That You Can

Re: TradingView Indicators to MT4 Indicators

726
I figured I would paste this here, since it's more fitting here than in the "MT4 Indicator requests and ideas" thread.
TransparentTrader wrote: Sat Mar 21, 2026 5:31 am Request: ATR% Multiple From 50-MA [TradingView]

This is an indicator I found while looking for novel approaches to mean reversion.

From the TradingView description:

How can one measure stock price extension?

In my view, decision-making in the trading business should rely on quantifiable data. A method I personally employ for scaling out and taking partial profits involves setting a threshold based on the multiple of Average True Range (ATR%) from the 50-day Simple Moving Average (SMA). For instance, I find it beneficial to start taking profits when positions exceed 7-10 times the ATR% from the 50-SMA. This practice helps prevent second-guessing or becoming emotionally attached to any particular position.

A relevant example illustrating this concept is the case of PLTR, SOFI, TSLA, VRT, NVDA which experienced a stall and subsequent decline after exceeding 10 times the ATR% from its 50-day moving average.

While there is no foolproof profit-taking mechanism that guarantees selling at the absolute market peak, employing this strategy can be a valuable tool for scaling out profits during extended periods to minimize potential losses.


The code is protected, but the formula is provided in the description:

A = ATR% = $ ATR / $ Last Done Price
B = % Gain From 50-MA
B / A = ATR% multiple from 50-MA



I should note one person suggests there would be a better way to do the calculations:

Calculating the ATR% multiple as shown B/A is questionable in the mathematical sense. The ratio B/A exaggerates upside extensions and compresses downside extensions. Please, check:

The proper mathematical way to do the calculation is using distance in dollars, ATR in dollars and then calculating the ratio of both quantities. It is also much simpler to calculate, and more easy to understand.

- First, calculate the distance from the current closing price to the MA of interest (for instance, SMA50).
- Second, calculate the ATR14 (or similar, it may be other length).
- Third, this is key, divide the distance (in dollars) by the ATR14 (in dollars). This is called the "distance of the price to the SMA measured in ATR14 units".


I'm interested in porting this indicator to MT4 for a few reasons.

I want to see how this indicator will behave on timeframes lower than the daily charts. I also want to see how it will behave with other instruments such as forex, futures, and commodities.

Additionally, this indicator is used to show when an asset is heavily over-bought (tops), but I wonder if it can be used in the opposite direction to show when an asset is heavily over-sold (bottoms).

More information can be found in this Substack article written by the author of the indicator, at point #2.

I believe there's an alternate version of this indicator (also a protected script) that plots the extremes in a separate window instead of on the chart, and in an oscillator fashion.

Thanks for all your help in advance!
These users thanked the author TransparentTrader for the post:
ashdays

Re: Help needed (Pine Script)

730
My indicator.. can anyone help make my script into mt4 please? You will really like it!

Code: Select all

//+------------------------------------------------------------------+
//| BBMA OA by Jimbo - GOD MODE FULL                                |
//+------------------------------------------------------------------+
#property indicator_chart_window

// ===== INPUT =====
input int BB_Period = 20;
input double BB_Deviation = 2.0;
input int EMA50_Period = 50;
input int EMA200_Period = 200;

input bool EnableAlert = true;
input bool ShowZone = true;

// ===== FUNCTION =====
double EMA(int tf,int p){ return iMA(NULL,tf,p,0,MODE_EMA,PRICE_CLOSE,0); }
double CLOSE(int tf){ return iClose(NULL,tf,0); }

// ===== INIT =====
int OnInit(){ return(INIT_SUCCEEDED); }

// ===== MAIN =====
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 i=0;

   // ===== CORE =====
   double ema50 = iMA(NULL,0,EMA50_Period,0,MODE_EMA,PRICE_CLOSE,i);
   double ema200= iMA(NULL,0,EMA200_Period,0,MODE_EMA,PRICE_CLOSE,i);

   double ma5H  = iMA(NULL,0,5,0,MODE_LWMA,PRICE_HIGH,i);
   double ma5L  = iMA(NULL,0,5,0,MODE_LWMA,PRICE_LOW,i);
   double ma10H = iMA(NULL,0,10,0,MODE_LWMA,PRICE_HIGH,i);
   double ma10L = iMA(NULL,0,10,0,MODE_LWMA,PRICE_LOW,i);

   double upperBB = iBands(NULL,0,BB_Period,0,BB_Deviation,PRICE_CLOSE,MODE_UPPER,i);
   double lowerBB = iBands(NULL,0,BB_Period,0,BB_Deviation,PRICE_CLOSE,MODE_LOWER,i);
   double midBB   = iBands(NULL,0,BB_Period,0,BB_Deviation,PRICE_CLOSE,MODE_MAIN,i);

   // ===== MTF =====
   double h4 = CLOSE(PERIOD_H4);
   double h1 = CLOSE(PERIOD_H1);
   double m15= CLOSE(PERIOD_M15);

   double h4e = EMA(PERIOD_H4,EMA50_Period);
   double h1e = EMA(PERIOD_H1,EMA50_Period);
   double m15e= EMA(PERIOD_M15,EMA50_Period);

   string H4 = (h4>h4e)?"BULL STR":"BEAR STR";
   string H1 = (h1>h1e)?"BULL":"BEAR";
   string M15= (m15>m15e)?"BULL":"BEAR";

   // ===== BBMA STRUCTURE =====
   bool EXTREME_BUY = (low[i] < lowerBB);
   bool EXTREME_SELL= (high[i] > upperBB);

   bool MHV_BUY = (close[i] > midBB && low[i] <= midBB);
   bool MHV_SELL= (close[i] < midBB && high[i] >= midBB);

   bool CSAK_BUY = (close[i] > midBB);
   bool CSAK_SELL= (close[i] < midBB);

   bool CSM_BUY = (close[i] > upperBB);
   bool CSM_SELL= (close[i] < lowerBB);

   // ===== SCORE (%) =====
   int score=0;
   if(EXTREME_BUY || EXTREME_SELL) score+=20;
   if(MHV_BUY || MHV_SELL) score+=20;
   if(CSAK_BUY || CSAK_SELL) score+=20;
   if(CSM_BUY || CSM_SELL) score+=20;

   // ===== RE-ENTRY =====
   bool buyRe = (close[i] > ema50 && close[i] <= ma10L);
   bool sellRe= (close[i] < ema50 && close[i] >= ma10H);

   if(buyRe || sellRe) score+=20;

   int percent = score;

   // ===== GRADE =====
   string grade="C";
   if(percent>=80) grade="A+";
   else if(percent>=60) grade="A";
   else if(percent>=40) grade="B";

   // ===== WARNING =====
   bool warning=false;
   if(buyRe && m15<m15e) warning=true;
   if(sellRe && m15>m15e) warning=true;

   bool invalid=false;
   if(buyRe && close[i]<midBB) invalid=true;
   if(sellRe && close[i]>midBB) invalid=true;

   // ===== FAKE BREAKOUT =====
   double candleSize = high[0] - low[0];
   double bodySize = MathAbs(close[0] - open[0]);
   bool fakeBreakout = (candleSize > bodySize*3);

   // ===== GOD MODE FILTER =====
   bool godMode=false;

   if(percent>=85 &&
      ((H4=="BULL STR" && H1=="BULL" && M15=="BULL") ||
       (H4=="BEAR STR" && H1=="BEAR" && M15=="BEAR")) &&
      (buyRe || sellRe) &&
      !warning &&
      !invalid &&
      !fakeBreakout)
   {
      godMode=true;
   }

   // ===== ENTRY =====
   string ENTRY="NONE";
   if(godMode)
   {
      if(buyRe) ENTRY="🔥 SNIPER BUY";
      if(sellRe) ENTRY="🔥 SNIPER SELL";
   }

   // ===== PRICE / TP SL =====
   double entryPrice = close[0];
   double SL=0, TP1=0, TP2=0;

   if(buyRe)
   {
      SL = ma10L;
      TP1 = entryPrice + (entryPrice - SL)*2;
      TP2 = entryPrice + (entryPrice - SL)*3;
   }

   if(sellRe)
   {
      SL = ma10H;
      TP1 = entryPrice - (SL - entryPrice)*2;
      TP2 = entryPrice - (SL - entryPrice)*3;
   }

   // ===== DRAW ZONE =====
   if(ShowZone)
   {
      string z="ZONE";
      ObjectDelete(z);

      color c=clrLime;
      if(warning) c=clrOrange;
      if(invalid) c=clrMaroon;

      if(buyRe)
         ObjectCreate(z,OBJ_RECTANGLE,0,Time[10],ma10L,Time[0],ma5L);

      if(sellRe)
         ObjectCreate(z,OBJ_RECTANGLE,0,Time[10],ma5H,Time[0],ma10H);

      ObjectSetInteger(0,z,OBJPROP_COLOR,c);
   }

   // ===== DASHBOARD =====
   Comment(
   "=== BBMA OA GOD MODE ===\n",
   "H4: ",H4,"\n",
   "H1: ",H1,"\n",
   "M15: ",M15,"\n",
   "ENTRY: ",ENTRY,"\n",
   "CONFIDENCE: ",percent,"%\n",
   "PRICE: ",DoubleToString(entryPrice,2),"\n",
   "SL: ",DoubleToString(SL,2),"\n",
   "TP1: ",DoubleToString(TP1,2),"\n",
   "TP2: ",DoubleToString(TP2,2)
   );

   // ===== ALERT =====
   static datetime last;
   if(EnableAlert && Time[0]!=last && godMode)
   {
      Alert(Symbol()," 🔥 SNIPER ",
      "Entry:",DoubleToString(entryPrice,2),
      " SL:",DoubleToString(SL,2),
      " TP1:",DoubleToString(TP1,2),
      " TP2:",DoubleToString(TP2,2),
      " ",percent,"%");
      last=Time[0];
   }

   return(rates_total);
}