Two markets, one story
Suppose gold pushes above the high it made twenty minutes ago, and silver, which normally moves in step with it, refuses to follow. Both charts cover the same stretch of time, yet they disagree about whether that high was a genuine breakout. When two closely linked markets tell different stories, one of them is usually wrong, and the stronger suspicion falls on the market that made the exciting new extreme.
That disagreement is only half of a trading idea, though. It says nothing about when to act, where the entry sits, or where the trade is wrong. This article builds an Expert Advisor for MetaTrader 5 that supplies the missing pieces. It anchors a repeating time grid to New York, so "twenty minutes ago" becomes a precisely defined quarter of a cycle. It measures the disagreement between the traded symbol and a correlated one, bar by bar. It turns the disagreement into a concrete trigger price. And it moves each idea through a small state machine that decides between a confirmation entry and a retest entry.
Throughout, the code is presented as excerpts, following one bearish trade from the first tick of the day to the closing trail. The complete, compilable file is attached, and it contains everything that is only described here in prose, such as the drawing helpers and the logger.
A ten-second glossary
| Term | Meaning in this program | Where it lives |
|---|---|---|
| Cycle | A block of time, 90 minutes by default (InpCycleMinutes) | QuarterOf |
| Quarter | One quarter of a cycle, 22.5 minutes by default (1,350 seconds) | quarterSeconds |
| Anchor | 18:00 New York time, the moment the daily grid starts counting | QuarterOf |
| True Open | The open of the second quarter (Q2) of each cycle | UpdateCycles |
| SSMT | The traded symbol and the correlated symbol disagree on whether the previous quarter's high (or low) was taken out | DetectSSMT |
| tCISD level | The open of the most recent opposing candle: the last up candle for a sell, the last down candle for a buy | FindTcisdLevel |
| Confirmation | A bar closes through the tCISD level | ProgressSetup |
| Retest | After confirmation, price trades back to the level | ProgressSetup |
| SSMT extreme | The traded symbol's quarter high (sell) or low (buy) when the setup arms; the stop is anchored beyond it | ssmtExtreme |
How the clock is divided
Quarterly Theory treats the trading day as a stack of repeating cycles, each split into four quarters. The usual reading is that the first quarter accumulates, the second delivers the initial move (and gives us the True Open), the third tends to reverse or manipulate, and the fourth distributes. You do not need to believe the narrative to use the grid. What matters for the program is that it converts vague timing into fixed, testable windows that do not depend on your broker's clock.

The machine on one page
The robot is a pipeline that runs once per closed bar, plus one job that runs on every tick.
On every new bar of the entry timeframe:
- Update the quarter and cycle ranges for both symbols
- If nothing is armed, look for a new SSMT divergence
- If something is armed, advance it one step toward entry (or cancel it)
- Refresh the chart
On every tick: trail any open position.
The armed setup lives in a three-state machine:
| State | Meaning | Leaves the state when |
|---|---|---|
STATE_IDLE | Nothing armed | An SSMT arms a setup |
STATE_CONFIRM | Waiting for a close through the tCISD level | It closes through (enter now, or move to retest), the divergence resolves, or time runs out |
STATE_RETEST | Waiting for price to come back to the level | Price returns (enter), the SSMT extreme is violated, or time runs out |
The whole state machine rests on two small enumerations:
enum EntryMode
{
ENTRY_RETEST, // Enter on a retest of the tCISD level
ENTRY_CONFIRM // Enter on the confirmation close
};
enum SetupState
{
STATE_IDLE, // No active setup
STATE_CONFIRM, // Awaiting the confirmation close through the level
STATE_RETEST // Awaiting the retest of the level
};
Case file: one bearish setup, start to finish
Stage 0: Preparing the desk
Before any logic runs, OnInit does four small jobs: it caches the symbol's digits and point size, gives the trade object your magic number, derives the quarter length from the cycle length, and selects the correlated symbol.
quarterSeconds = MathMax(60, (InpCycleMinutes * 60) / 4);
correlatedSymbol = InpCorrelatedSymbol;
correlatedReady = SymbolSelect(correlatedSymbol, true);
if(!correlatedReady)
Log("WARNING: correlated symbol '" + correlatedSymbol + "' could not be selected - SSMT disabled until it is available.");If the correlated symbol cannot be selected, the robot keeps running but the divergence test stays disabled, and the Journal says so. That warning is worth reading the first time you attach the EA.
The inputs that matter most, grouped by what they control:
| Group | Key inputs | Default | Note |
|---|---|---|---|
| Correlated symbol | InpCorrelatedSymbol | XAGUSDm | The suffix is broker-specific. Match it to your Market Watch name. |
| Time grid | InpCycleMinutes, InpBrokerGmtOffset | 90, 0 | Set the offset to your server's real GMT offset. |
| Stops | InpStopBufferPoints, InpMinStopPoints | 300, 3000 | Both are in points and instrument-specific. |
| Target | InpRewardRiskRatio | 2.0 | Target is a multiple of the risk distance. |
| Entry | InpEntryMode, InpMaxConfirmBars, InpMaxRetestBars, InpMaxScanBars | Confirm, 24, 24, 100 | Patience limits and lookback for the trigger candle. |
| Filters | InpUse2StageSSMT, InpUseTrueOpen, InpUsePremiumDiscount | all off | Optional quality gates. |
| Sizing | InpLotSizingMode, InpRiskPercent, InpFixedLots | Risk %, 0.5, 0.01 | Half a percent of balance by default. |
| Trailing | InpUseTrailingStop, InpMinProfitPoints, InpTrailPoints | on, 1000, 300 | Trailing is enabled out of the box. |
Stage 1: Putting a bar on the grid
Everything downstream depends on knowing which quarter of which cycle a bar belongs to. The function QuarterOf answers that. It first walks the bar's server time to UTC, then to New York time using an offset that accounts for US daylight saving:
datetime utc = barServer - InpBrokerGmtOffset * 3600;
int offset = NewYorkOffsetCached(utc);
datetime newYork = utc + offset * 3600;
int secondsSinceAnchor = ((secondsOfDay - 18 * 3600) % 86400 + 86400) % 86400;
int quarterIndex = secondsSinceAnchor / quarterSeconds;
outQuarterOfCycle = quarterIndex % 4;Two helpers stand behind that offset. One finds the Nth Sunday of a month at a given UTC hour, and the other uses it to bracket US daylight saving, from the second Sunday of March to the first Sunday of November, returning minus four hours inside the window and minus five outside. The result is cached and refreshed only when the calendar day changes. Because the changeovers happen on Sundays, when the forex market is largely shut, a once-a-day refresh is enough.
The important line is the anchor arithmetic. Subtracting 18 hours and wrapping around 24 hours gives "seconds since the anchor". Dividing by the quarter length gives a running quarter index, and the remainder after dividing that index by four says whether you are in Q1, Q2, Q3 or Q4. The start times of the quarter and the cycle come from the same numbers, and are then shifted back into server time so they can be compared directly with bar times:
int intoQuarter = secondsSinceAnchor - quarterIndex * quarterSeconds;
int intoCycle = secondsSinceAnchor % cycleLength;
datetime quarterStartNewYork = newYork - intoQuarter;
datetime cycleStartNewYork = newYork - intoCycle;
outQuarterStart = quarterStartNewYork - offset * 3600 + InpBrokerGmtOffset * 3600;
outCycleStart = cycleStartNewYork - offset * 3600 + InpBrokerGmtOffset * 3600;A note on bar boundaries: with the default 90-minute cycle, a quarter is 22.5 minutes long, which is not a whole number of bars on most timeframes. Bars are assigned by their open time, so quarters on an M5 chart will contain four or five bars depending on where the grid falls. That is fine for the logic, but do not expect the dividers to line up with a fixed bar count.
Stage 2: Keeping score
With each closed bar, UpdateCycles reads the bar that just finished on the traded symbol, fetches the matching bar on the correlated symbol, asks QuarterOf where the bar belongs, and then does one of two things for the cycle and, separately, for the quarter: extend the running range, or archive it and start fresh.
The program tracks a lot of numbers, but they follow a simple pattern:
| Traded symbol | Correlated symbol | |
|---|---|---|
| Current quarter high / low | primaryQuarterHigh / Low | correlatedQuarterHigh / Low |
| Previous quarter high / low | primaryPrevQuarterHigh / Low | correlatedPrevQuarterHigh / Low |
| Current cycle high / low | primaryCycleHigh / Low | correlatedCycleHigh / Low |
| Previous cycle high / low | primaryPrevCycleHigh / Low | correlatedPrevCycleHigh / Low |
The archive-and-restart rhythm for quarters looks like this. The cycle version is identical in shape:
if(newQuarterStart != quarterStart)
{
if(quarterStart != 0)
{
primaryPrevQuarterHigh = primaryQuarterHigh; primaryPrevQuarterLow = primaryQuarterLow;
correlatedPrevQuarterHigh = correlatedQuarterHigh; correlatedPrevQuarterLow = correlatedQuarterLow;
havePreviousQuarter = true;
}
quarterStart = newQuarterStart;
quarterOfCycle = newQuarterOfCycle;
primaryQuarterHigh = primaryHigh; primaryQuarterLow = primaryLow;
correlatedQuarterHigh = (haveCorrelated ? correlatedHigh : 0); correlatedQuarterLow = (haveCorrelated ? correlatedLow : 0);
if(newQuarterOfCycle == 1) trueOpen = primaryOpen;
// ... quarter dividers, labels and the True Open line are drawn here
}The last line inside the excerpt captures the True Open: when the bar that opens a new quarter is the second one of its cycle (index 1), its open price is stored. It stays available for the optional True Open filter until the next cycle clears it.
The same block draws the grid on the chart: a dotted divider at each quarter start, a "Q1" to "Q4" label, and a dotted True Open line across the cycle. Behind those drawings sits a small kit of helpers (a horizontal-level drawer, a label drawer, a marker drawer that uses triangle glyphs from the Wingdings 3 font, a vertical-line drawer, and a trade-levels drawer). Each one creates its object the first time and moves it on later calls, and each marks the object as hidden and non-selectable so the chart stays clean. The marker glyphs are ordinary characters in the symbol font, so you can swap them for any other glyph that suits your taste.

Stage 3: Lining up the second market
A divergence is only meaningful if both symbols are measured over the same bar. Because two symbols do not always have identical bar histories, the program maps our bar time onto the correlated symbol's series instead of assuming index equality:
if(!correlatedReady) return false;
int shift = iBarShift(correlatedSymbol, InpEntryTimeframe, barTime, false);
if(shift < 0) return false;
high = iHigh(correlatedSymbol, InpEntryTimeframe, shift);
low = iLow(correlatedSymbol, InpEntryTimeframe, shift);
return (high > 0 && low > 0);The final check matters as much as the lookup: a high and low are accepted only when both are positive. If the correlated symbol is missing or has a gap, the correlated ranges are seeded with zero, and the divergence test later refuses to run on zero data. The design principle is that missing data should silence the signal, never invent one.
Stage 4: The disagreement
Now the core test. While the state machine is idle, DetectSSMT compares each symbol's running quarter extremes against its own previous quarter, producing four true-or-false flags:
bool primarySweptHigh = (primaryQuarterHigh > primaryPrevQuarterHigh);
bool correlatedSweptHigh = (correlatedQuarterHigh > correlatedPrevQuarterHigh);
bool primarySweptLow = (primaryQuarterLow < primaryPrevQuarterLow);
bool correlatedSweptLow = (correlatedQuarterLow < correlatedPrevQuarterLow);The signal is an exclusive disagreement. If exactly one of the two symbols has swept the previous quarter's high, that is a bearish divergence. If exactly one has swept the low, it is a bullish one. When both swept, or neither did, there is no story to trade. For a bearish divergence the program looks up the trigger level, runs the optional filters, and if everything passes, arms the setup:
if(primarySweptHigh != correlatedSweptHigh)
{
double level = FindTcisdLevel(true);
if(level > 0 && PassFilters(-1, level))
{
setupDirection = -1; ssmtTime = barTime; ssmtExtreme = primaryQuarterHigh; tcisdLevel = level;
setupState = STATE_CONFIRM; barsInState = 0;
// ... log line and SSMT marker are drawn here
}
return;
}Two behaviours are worth knowing. First, the swept quarter high at the moment of arming is stored as ssmtExtreme, and it does not update afterwards. That fixed value later anchors the stop. Second, the high side is evaluated first, and the function returns after handling it, whether or not that setup armed. On a bar where both a high-side and a low-side divergence exist, only the high side is considered.
The bullish branch is the mirror image, using the swept low and the last down candle.

Stage 5: The trigger price
A divergence suggests the move is suspect but gives no price to act on. The tCISD level fills that gap. The function walks backward from the most recent closed bar, up to InpMaxScanBars bars, and returns the open of the first candle that ran against the expected reversal:
double FindTcisdLevel(bool bearish)
{
int limit = MathMin(InpMaxScanBars, iBars(_Symbol, InpEntryTimeframe) - 1);
for(int shift = 1; shift <= limit; shift++)
{
double openPrice = iOpen(_Symbol, InpEntryTimeframe, shift);
double closePrice = iClose(_Symbol, InpEntryTimeframe, shift);
if(bearish && closePrice > openPrice) return openPrice;
if(!bearish && closePrice < openPrice) return openPrice;
}
return 0;
}For a sell, that is the open of the last up candle. For a buy, it is the open of the last down candle. Reading it as a story: the last bullish candle's open is where buyers last held control at the start of their push. If price closes back below it, the market has given up that territory, and the "change in state of delivery" the model names has happened. The function returns zero if it finds nothing, and the caller treats zero as "no setup".
To make it concrete with round, made-up numbers: if a gold sell setup arms and the most recent up candle opened at 100.00, then 100.00 becomes the tCISD level. A later bar that closes at 99.60 confirms the shift.
Stage 6: Optional quality gates
Three filters can be layered on before a setup arms. They are combined in one expression, and each one returns true when it is switched off, so the default model runs unfiltered:
return PassTwoStageSSMT(direction) && PassTrueOpen(direction, level) && PassPremiumDiscount(direction, level);| Filter | Rule for a sell | Rule for a buy | Edge case |
|---|---|---|---|
| True Open | tCISD level above the True Open | tCISD level below it | Passes if no True Open is set yet |
| Premium / discount | Level in the upper half of the previous cycle's range | Level in the lower half | Passes if no valid previous cycle exists |
| Two-stage SSMT | The same divergence must also exist on the cycle highs | ...on the cycle lows | Fails if cycle data is not yet available |
The two-stage test is the cycle-level twin of the quarter test:
if(direction < 0)
return ((primaryCycleHigh > primaryPrevCycleHigh) != (correlatedCycleHigh > correlatedPrevCycleHigh));
return ((primaryCycleLow < primaryPrevCycleLow) != (correlatedCycleLow < correlatedPrevCycleLow));That last edge case is important: enabling the two-stage filter blocks all setups until the first full cycle has been archived, whereas the other two filters let setups through when their data is missing.
Stage 7: The waiting room
Once armed, the setup is handed to ProgressSetup, which runs on every new bar. It counts the bars spent in the current state, then applies the rules for whichever state is active.
In the confirmation state, three things can kill the setup before it ever trades:
if(setupDirection < 0 && primaryQuarterHigh > primaryPrevQuarterHigh && correlatedQuarterHigh > correlatedPrevQuarterHigh) { ResetSetup("SSMT resolved (both swept highs)"); return; }
if(setupDirection > 0 && primaryQuarterLow < primaryPrevQuarterLow && correlatedQuarterLow < correlatedPrevQuarterLow) { ResetSetup("SSMT resolved (both swept lows)"); return; }
if(barsInState > InpMaxConfirmBars) { ResetSetup("no close-through in time"); return; }The first two lines encode a sensible piece of logic: if both symbols have now swept the same extreme, the disagreement that justified the trade has disappeared, so the setup is cancelled. The third is a simple patience limit.
If the setup survives, the test is a single comparison, and the entry mode decides what happens next:
bool confirmed = (setupDirection < 0) ? (closePrice < tcisdLevel) : (closePrice > tcisdLevel);
if(InpEntryMode == ENTRY_CONFIRM) { OpenTrade(setupDirection > 0); return; }
setupState = STATE_RETEST; barsInState = 0;In confirm mode the order goes out immediately. In retest mode the state advances and the counter restarts, and the program waits for price to come back. Note that arming and confirming can happen on the same bar, because DetectSSMT and ProgressSetup both run inside the same new-bar pass.
In the retest state, the guard rails are different. The setup dies if price breaks beyond the stored SSMT extreme, or if the retest does not arrive in time. Otherwise a touch of the level triggers the entry:
if(setupDirection < 0 && highPrice > ssmtExtreme) { ResetSetup("SSMT high violated before retest"); return; }
if(setupDirection > 0 && lowPrice < ssmtExtreme) { ResetSetup("SSMT low violated before retest"); return; }
if(barsInState > InpMaxRetestBars) { ResetSetup("no retest in time"); return; }
if(setupDirection < 0 && highPrice >= tcisdLevel) OpenTrade(false);
else if(setupDirection > 0 && lowPrice <= tcisdLevel) OpenTrade(true);Notice that the retest uses the bar's high (for sells) or low (for buys), so a wick that reaches the level is enough. The confirm mode gets you in earlier with less certainty. The retest mode gets you a better price but may never fill.

Stage 8: Sending the order
OpenTrade gets one attempt per setup. It enters at the market and places the stop beyond the SSMT extreme, then applies a personal guard before anything else:
double stop = isBull ? ssmtExtreme - buffer : ssmtExtreme + buffer;
if(MathAbs(entry - stop) / symbolPoint < InpMinStopPoints) { ResetSetup("stop below minimum"); return; }The first guard rejects any trade whose stop is closer than InpMinStopPoints, on the theory that a very tight stop is noise rather than structure. Because this is measured in points, the default means very different things on different instruments, so treat it as a placeholder.
A second guard respects the broker. The minimum legal distance is the larger of the symbol's stops level and its current spread, and both the stop and the target are pushed out to it if they fall short:
long stopsLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
long spread = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
double minPoints = (double)MathMax(stopsLevel, spread);
if(minPoints < 1) minPoints = 1;
double minDistance = minPoints * symbolPoint;
if(isBull) { if(entry - stop < minDistance) stop = entry - minDistance; }
else { if(stop - entry < minDistance) stop = entry + minDistance; }The target is a multiple of the resulting risk distance:
double takeProfit = isBull ? entry + InpRewardRiskRatio * riskDistance
: entry - InpRewardRiskRatio * riskDistance;Position size then comes from the risk percentage. The arithmetic is short: convert the tick value into money per point, then divide the money at risk by the stop distance in points times that value. The result is floored to the volume step and clamped between the broker's minimum and maximum:
double riskMoney = AccountInfoDouble(ACCOUNT_BALANCE) * InpRiskPercent / 100.0;
double stopPoints = MathAbs(entry - stop) / symbolPoint;
double valuePerPoint = tickValue / tickSize * symbolPoint;
double lots = riskMoney / (stopPoints * valuePerPoint);
if(volumeStep > 0) lots = MathFloor(lots / volumeStep) * volumeStep;Whatever the outcome, OpenTrade finishes by resetting the setup, so a rejected or failed order is not retried automatically. On success it draws the entry, stop and target lines and prints the fill to the Journal.
Stage 9: Riding the trade
Trailing runs on every tick, separate from the per-bar pipeline. For each position carrying our magic number on the current symbol, it measures the open profit in points and, once that exceeds the activation profit plus the trail distance, proposes a stop one trail distance behind price. The stop moves only if the new level improves protection:
double profitPoints = isBull ? (bid - entry) / symbolPoint : (entry - ask) / symbolPoint;
if(profitPoints >= InpMinProfitPoints + InpTrailPoints)
{
double newStop = isBull ? bid - InpTrailPoints * symbolPoint : ask + InpTrailPoints * symbolPoint;
newStop = NormalizeDouble(newStop, symbolDigits);
bool improves = isBull ? (newStop > curStop) : (curStop == 0 || newStop < curStop);
if(improves) trade.PositionModify(ticket, newStop, curTP);
}The condition profitPoints >= InpMinProfitPoints + InpTrailPoints means trailing starts only after the trade has earned both the activation cushion and the room to trail. The short side also accepts a current stop of zero.

Stage 10: The heartbeat
Finally, the tick handler wires the two clocks together. The new-bar gate keeps the heavy work to once per bar, and trailing stays outside it:
if(IsNewBar())
{
UpdateCycles();
DetectSSMT();
ProgressSetup();
if(VisualsAllowed()) ChartRedraw(0);
}
ManageTrailing();On shutdown, the EA removes only the chart objects that carry its own TC_ prefix, and only when it is genuinely removed or the chart closes. A parameter change leaves your drawings in place.
Running it
A short checklist before your first run:
- Add the correlated symbol to Market Watch, and set
InpCorrelatedSymbolto its exact name on your broker. - Set
InpBrokerGmtOffsetto your server's real offset from GMT. - Choose an entry timeframe. The default follows the chart.
- Scale
InpStopBufferPointsandInpMinStopPointsto your instrument's point size. - In the Strategy Tester, make sure both symbols have history for the test period.
Run visual mode first, because the drawings are skipped in non-visual runs, and this model is much easier to judge when you can watch the quarters form and the divergences arm.

While it plays, check that the grid dividers and the True Open appear where you expect, that setups arm only when the two symbols genuinely disagree, that confirm mode enters on the bar after a close through the level, that retest mode waits for the touch, and that trailing starts only after its activation threshold.


Sharp edges worth knowing
- No cap on open positions. Only one setup is active at a time, but once a setup fills, the machine returns to idle and a later divergence can open another trade while the first is still running. Add a position count check if you want strictly one trade at a time.
- Running extremes can trigger early. The divergence test compares the current quarter's running high and low with the previous quarter's. A disagreement can therefore appear in the first bars of a quarter, not only at its end.
- One side per bar. When both a high-side and a low-side divergence exist, only the high side is evaluated on that bar.
- Gaps on the correlated symbol are tolerated by nearest-bar lookup, so a symbol with missing bars can align imperfectly.
- Broker-specific defaults. The correlated symbol name, the minimum stop and the buffer are all instrument-dependent.
- Time rules. Daylight saving follows US rules. The broker offset is manual and will not adjust itself if your broker changes its server time.
- Sizing. Risk uses account balance rather than equity, and the minimum-volume clamp can push real risk above the requested percentage on small accounts.
Tuning notes
The cycle length is the main structural lever. Ninety minutes is the default, and other lengths change the size of every quarter. The entry mode is the main behavioural lever, trading earlier and less certain for later and cleaner. The three filters are worth testing one at a time, since each one removes setups. InpMaxScanBars decides how far back the program will look for the opposing candle, and the two wait limits decide how patient it is once armed.
Closing thoughts
The tCISD idea starts as a feeling: something looks off about a high, and the moment feels significant. This program forces every part of that feeling to become a rule. The time is a grid anchored to New York. The "off" is an exclusive disagreement between two symbols. The moment is a price, the open of the last opposing candle. And the patience is a state machine with explicit ways to give up. Each rule can be watched on the chart, logged in the Journal and tuned on its own.
Good next steps include capping open positions, adding a spread or news filter, and testing other correlated pairs and cycle lengths. The full source file is attached.
For educational purposes only. Trading involves substantial risk, and backtested results do not guarantee future performance. Test thoroughly on a demo account and size your risk carefully before using any automated system live.