Markov Candle Prediction

whoDAT

Member
Plus
Caution - This study is resource intensive, doing over 1000 calculations per candle.
-- Oh, that got your attention didn't it.
-- You should really be here because the title says Markov Candle Prediction.

Markov uses chains of previous events to predict future events. This is how Google knows I'm about to mistype the word 'mistype' and offers me corrections. How does it do that? I predicted you'd ask, and here is that link you want... https://en.wikipedia.org/wiki/Markov_model

So how do we implement this in Thinkscript. This implementation uses chains of prior candles (close, hl2, whatever) and asks is it up strongly compared to the prior candle, weakly up, down weakly, or down strongly. You will need to change the input "strongThreshold" to tell the study where you want those cutoffs to be. I'm trading FOREX so my threshold is supersmall to a stock.

Alright those are the 4 states. Now we're going to classify the prior 3 candles' states into a chunk such as 2,2,-1 (strong up, strong up, weak down). I evaluated the quantity of states and lengths of chunks, but settled on 4 and 3. That means there are 4 to the power of 3 or 64 possible combinations of these chunks.

Next we look back at the last x candles to determine the when we see one of these 64 states (of 3 candle results) and see what happened in the next candle. Was it strongly, weakly, up or down. I settled looking back at the last 1000 candles to get some probability of what usually happens. So you'll need a time frame with more candles than the lookback. The result is to calculate a net directional score for that edge pattern of 3-candle states. An average of the edge can be added to the net score.

Some stats are displayed. The pattern. How many matches of that pattern occurred in the previous 1000 candles. And what is the net edge score (negative 5% means it is 5% more likely to drop the next candle than rise). And viola its done.

Enjoy.

Code:
# by whoDAT
# 1/2026

declare lower;

input src = close;
# Threshold for 'Strong' move (e.g., 4 pips)
input strongThreshold = 0.0004;
input lookback = 1000;
input averageType = averagetype.simple;
input avgLength = 3;

# --- 1. Four-State Definition ---
# 2: Strong Up, 1: Weak Up, -1: Weak Down, -2: Strong Down
def change = src - src[1];
def state = if change >= strongThreshold then 2
            else if change > 0 then 1
            else if change <= -strongThreshold then -2
            else -1;

# --- 2. Current Pattern ID (Base-4) ---
# Mapping: -2->0, -1->1, 1->2, 2->3
def s1 = if state[3] == -2 then 0 else if state[3] == -1 then 1 else if state[3] == 1 then 2 else 3;
def s2 = if state[2] == -2 then 0 else if state[2] == -1 then 1 else if state[2] == 1 then 2 else 3;
def s3 = if state[1] == -2 then 0 else if state[1] == -1 then 1 else if state[1] == 1 then 2 else 3;

def currentPID = (s1 * 16) + (s2 * 4) + s3;

# --- 3. The Match Loop Logic ---

# LOOP 1: Total Matches
def totalMatches = fold i = 1 to lookback with count = 0 do (
    if ((if GetValue(state, i + 3) == -2 then 0 else if GetValue(state, i + 3) == -1 then 1 else if GetValue(state, i + 3) == 1 then 2 else 3) * 16) +
       ((if GetValue(state, i + 2) == -2 then 0 else if GetValue(state, i + 2) == -1 then 1 else if GetValue(state, i + 2) == 1 then 2 else 3) * 4) +
       (if GetValue(state, i + 1) == -2 then 0 else if GetValue(state, i + 1) == -1 then 1 else if GetValue(state, i + 1) == 1 then 2 else 3)
       == currentPID
    then count + 1
    else count
);

# LOOP 2: Net Directional Score
def netScore = fold j = 1 to lookback with score = 0 do (
    if ((if GetValue(state, j + 3) == -2 then 0 else if GetValue(state, j + 3) == -1 then 1 else if GetValue(state, j + 3) == 1 then 2 else 3) * 16) +
       ((if GetValue(state, j + 2) == -2 then 0 else if GetValue(state, j + 2) == -1 then 1 else if GetValue(state, j + 2) == 1 then 2 else 3) * 4) +
       (if GetValue(state, j + 1) == -2 then 0 else if GetValue(state, j + 1) == -1 then 1 else if GetValue(state, j + 1) == 1 then 2 else 3)
       == currentPID
    then score + (if GetValue(state, j) > 0 then 1 else -1)
    else score
);

# --- 4. Edge Calculation ---
plot NetEdge = if totalMatches > 0 then (netScore / totalMatches) * 100 else 0;

# --- 5. Visuals ---
NetEdge.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
NetEdge.SetLineWeight(4);
NetEdge.AssignValueColor(if NetEdge > 0 then Color.UPTICK else Color.DOWNTICK);

plot NetEdgeAvg = MovingAverage(averageType, NetEdge, avgLength);
NetEdgeAvg.SetPaintingStrategy(PaintingStrategy.LINE);
NetEdgeAvg.SetLineWeight(4);
NetEdgeAvg.AssignValueColor(if NetEdge > 0 then Color.UPTICK else Color.DOWNTICK);


plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.GRAY);

# --- 6. Dashboard ---
AddLabel(yes, "Pattern: " + state[3] + " | " + state[2] + " | " + state[1], Color.WHITE);
AddLabel(yes, "TRUE MATCHES: " + totalMatches, Color.CYAN);
AddLabel(yes, "UP Bias: " + AsPercent(if totalMatches > 0 then netScore / totalMatches else 0), if NetEdge > 0 then Color.GREEN else Color.RED);

markov.jpg
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
754 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top