Clear signals. Locked targets. One alert to your phone.
Open Legacy is a free TradingView indicator for any market. When a signal fires it locks your entry, take profit and stop loss, shows them in a live panel, and tells you when the trade ends.
Start hereSet Up in 5 Minutesโผ
Add it to your chart
Copy Open Legacy from Get the Scripts. In TradingView open the Pine Editor, delete the template, paste, and tap Add to Chart.
Set your timezone
Settings โ Timezone โ your region, e.g. Europe/Dublin.
Pick a strategy
FVG Pullback or EMA Trend, starting on Balanced.
Set your targets
Stop Loss and Take Profit in pips โ see Settings.
Add one alert
So every signal and every TP / SL lands on your phone โ see Alerts.
The engineHow It Finds Tradesโผ
Two well-known strategies โ the only ones that held up when tested on three months of real 1-minute data across gold, indices and BTC. One dropdown picks the strategy; one Sensitivity dial sets how picky it is.
SettingsEvery Setting, Explainedโผ
Twelve settings in four groups. Everything else is handled for you.
What to type for each pair, with examples: SL & TP โ
TargetsWhat to Type for SL & TPโผ
The indicator, the Side-Kick and the Auto SL/TP EA all read your numbers the same way. The one thing to remember: FX pairs, type the pips as they are. Gold, indices and BTC, add a 0.
Two examples
Cheat sheet
Direction
Indicator vs EA
XAUUSD=63/43, AUDUSD=9.4/5.4, with SL first, then TPThe panelReading the HUDโผ
The HUD's Setup Score is the chance price reaches your TP before your SL, from where price is right now. It updates live through the trade.
๐ฏ At entry
Starts at your SL รท (TP + SL). With TP twice your SL that's about 33% โ honest, because a bigger target is harder to reach. With TP equal to SL it starts near 50%.
๐ Rising
Price is moving toward TP. 80%+ means TP is close.
๐ Falling
Price is moving toward SL. Below about 20% the trade is close to its stop.
Benchmark & Structure rows
Open Legacy checks a related market automatically โ DXY for USD pairs and gold, VIX for stock indices, a currency index for JPY / GBP / EUR / CAD / CHF pairs.
Scoreboard + layeringOpen Legacy Side-Kickโผ
Two jobs in one indicator: a weekly Scoreboard of your trades, and a box on the chart showing where layering a trade makes sense, from the moment an Open Legacy trade starts until it ends.
One box, three colours
Teal waiting. Green layer window open. Red too risky, don't add.
Three settings
Where the box starts, where it ends, and how picky to be. Hover any setting for a plain explanation.
8 sessions
Same sessions as Open Legacy, so the box follows the very same trades.
Add it to the same chart as Open Legacy
Copy Open Legacy Side-Kick from Get the Scripts into its own Pine Editor tab and add it to the same chart.
Match Open Legacy
Use the same Entry Method, Sensitivity, SL, TP, sessions and timezone as Open Legacy, so it follows the very same trades. You set these once: the Scoreboard and the layer box both use them.
Choose the box
At the bottom of its settings: Zone starts 20 and Zone ends 55 (% of the way from entry to your stop). How picky to be: Normal.
Read the Scoreboard
The table shows your wins and losses by day, plus a โ Layers row with the wins, losses and win rate of your layers. Pick the week range in Show Results For. Each layer counts once per trade with the same TP and SL as the trade. There is no link to pick.
Set the alert (optional)
On the chart, tap the Alert icon, then Create Alert. Set Condition to Open Legacy Side-Kick and choose Any alert() function call. Tick Notify on app and save. Do this once for each pair's chart. Entry alerts still come from the Open Legacy indicator's own alert.
Auto-layer on MT5 (optional)
Using the All-in-One EA? Update the relay and EA to the latest, set UseLayering to true in the EA, and turn on Send layer to MT5 robot in Open Legacy Side-Kick. In the Open Legacy Side-Kick alert, add the same relay Webhook URL you use for Open Legacy. When the box turns green the EA adds one half-size trade with the same SL and TP. Leave all of this off to just get notifications.
Can't see "Send layer to MT5 robot"? You have an older copy, so grab the latest Side-Kick from Get the Scripts and re-add it to your chart. Turned it on after making the alert? Delete the Side-Kick alert and create it again. An alert keeps the settings it was created with.
What the alerts mean
โ Layer window open arrives the moment the box turns green, even mid-candle, once per trade. โ ๏ธ Too risky to layer arrives when price goes past the zone and the box turns red: don't layer that trade.
Day to dayFour Good Habitsโผ
Wait for the candle to close
A signal only counts once its candle finishes. Mid-candle labels can vanish.
Trade your best hours
Use Sessions 1โ6 to only see signals when the market moves well for you.
Skip big news
The All-in-One EA skips trades around Forex Factory red and orange news (CPI, NFP, Fed days) by itself, and can optionally close open trades before it too.
Trade small
Size from your stop loss. Small and steady beats one big swing.
NotificationsAlerts to Your Phoneโผ
One alert per chart covers everything: new BUY, new SELL, TP hit and SL hit.
Open the alert menu
Tap the โฐ alarm icon (or right-click the chart โ Add Alert).
Pick the condition
Condition: Open Legacy โ Any alert() function call.
Turn on notifications
In the Notifications tab, switch on app push, then tap Create.
๐ฑ Backtest anywhereYour Backtest, In Your Pocketโผ
Full backtesting, straight from your phone.
The Open Legacy Side-Kick replays every signal on your chart with your exact settings and tallies how each trade ended โ no desktop, no Strategy Tester, no extra apps. Just add it on TradingView mobile and the results are there.
Change anything โ strategy, sensitivity, TP and SL, your sessions and their days โ and the whole history re-scores instantly. Flip between This Week, Last 4 Weeks or All Time to see how your setup really holds up.
๐งฎ Plan your numbersProfit Calculatorโผ
The Side-Kick counts wins and losses but not money. Fill in the three steps below with the same numbers you use on your Side-Kick and the calculator shows what that could mean in profit.
More options
More detail
Week by week
๐ MT5 toolAuto-Trade โ Signals Straight to Your Accountโผ
Every Open Legacy signal can now open the trade for you in MT5 โ SL and TP included โ and keep running on the MetaQuotes VPS while your computer is off. You choose the maximum number of trades allowed at once, so two signals at the same moment never overload your account.
Indicator fires
Open Legacy spots a signal on your chart.
Your relay
A free Cloudflare inbox catches the alert.
The MT5 robot
Checks the inbox every second and places the trade.
OL;BUY;XAUUSD;10.00;20.00;0.10 (side, pair, SL distance, TP distance, lot size).Set it up โ 8 steps, about 20 minutes
Refresh your indicator
Copy Open Legacy again from Get the Scripts and re-add it to your chart. This is the version with the Lot Size setting and the robot's alert line. Open its settings โ Targets and set Lot Size for that pair โ each chart keeps its own, so XAUUSD and SP500 can differ. Invent a secret key now โ letters and numbers only, about 20 characters โ and keep it private. You'll use it three times.
Open your free signal inbox
At dash.cloudflare.com: Storage & Databases โ D1 โ Create database, name it ol-signals. Open it โ Console, paste the line below, and tap Execute.CREATE TABLE IF NOT EXISTS signals (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER, side TEXT, sym TEXT, sl TEXT, tp TEXT, lots TEXT);
Launch the relay
Workers & Pages โ Create โ Worker, start from Hello World, name it open-legacy-relay, tap Deploy, then Edit code. Delete everything, paste the relay code from below, and tap Deploy.
Plug in the database and your key
In the Worker: Settings โ Bindings โ Add โ D1 database. Variable name DB (capitals), database ol-signals. Then Variables and Secrets โ Add: type Secret, name KEY, value = your secret key. Deploy. (To change a secret later, tap it and use Rotate.)
Check it's alive
Open https://YOUR-WORKER.workers.dev/?key=YOUR-SECRET-KEY in your browser (your Worker's address is on its Overview page). You should see M;0. If you see forbidden, the key doesn't match โ rotate it again.
Point TradingView at it
On each chart (e.g. XAUUSD, SP500): tap the โฐ alarm โ Condition Open Legacy โ Any alert() function call. In Notifications, tick Webhook URL and paste the address from the last step. Leave the message box alone โ the indicator writes the message itself. Tap Create. One alert per chart; they all share the same URL. Changed Lot Size later? Open that chart's alert and tap Save (or delete and re-create it) โ an alert keeps the settings it was created with.
Switch on the MT5 robot
In desktop MT5: Tools โ Options โ Expert Advisors, tick Allow WebRequest for listed URL and add your Worker address (without the ?key=). Save the robot file into File โ Open Data Folder โ MQL5 โ Experts, press F4, Compile, then drag it onto any chart. Fill in the settings below and turn AutoTrading on. The chart shows Status: Connected.
Test, then go 24/7
Test on a demo account first. When the next signal fires, a trade should appear within a couple of seconds with SL and TP. Then register a MetaQuotes VPS and Migrate (same as the Auto SL/TP steps below). Check the VPS Journal โ if it complains about WebRequest, re-add the Worker address under Allow WebRequest and migrate again.
Install the robot in MT5 โ compile it first
MT5 only lists compiled robots, so a plain .mq5 file will not appear until you compile it once in MetaEditor.
Put the file in the Experts folder
In MT5: File โ Open Data Folder, open MQL5 โ Experts, and paste OpenLegacy_All_In_One_EA.mq5 there.
Compile it in MetaEditor
In MT5 press F4 to open MetaEditor. In its left panel open Experts, double-click OpenLegacy_All_In_One_EA.mq5, then press F7. The bottom panel should say 0 errors. Two harmless 'status' hides global variable warnings are normal.
Refresh the terminal
Back in MT5, right-click Expert Advisors in the Navigator and choose Refresh. OpenLegacy_All_In_One_EA now appears in the list.
Drag it onto one chart
Drag the robot onto one chart (any pair is fine). In the Common tab tick Allow Algo Trading, then open the Inputs tab and set it to suit you: Role (Trader or Copy Receiver), RelayURL, SecretKey, and the other settings from the tables below, such as MaxOpenTrades, ShareToReceiver and Channel. Press OK.
Check it is running
Make sure the AutoTrading button at the top of MT5 is green. The chart panel should say Status: Connected. If it does not, allow your relay address under Tools โ Options โ Expert Advisors โ Allow WebRequest.
Copy trading โ Master and Receiver in two MT5 windows
The same robot file does both jobs. You run one copy in each MT5 window, both talking to the same relay. Only the Role and a few settings change.
Same file, both windows
Compile OpenLegacy_All_In_One_EA.mq5 (the all-in-one robot) in each MT5 and attach it to one chart per window. In both, add your relay address under Tools โ Options โ Expert Advisors โ Allow WebRequest, and switch AutoTrading on. Remove the old separate Master, Receiver and Auto SL/TP robots.
Window 1 โ the Master (e.g. PU Prime)
Role = Trader (it keeps taking your indicator signals). Set ShareToReceiver = true. Fill in RelayURL, SecretKey and Channel (e.g. main). The panel on the chart shows Copy share: Connected when it works.
Window 2 โ the Receiver (e.g. FTMO)
Role = Copy Receiver. Use the same RelayURL, SecretKey and Channel as the Master. Pick the lot size (LotMode, LotMultiplier or FixedLot) and set RSymbolMap if the broker names differ, e.g. XAUUSD.s=XAUUSD. Needs a hedging account.
Test on demo first
Open a small trade in window 1. It should appear in window 2 within a couple of seconds, and its SL/TP edits, partial closes and close should follow. On first start the Receiver ignores trades already open, so only new trades are copied.
main. Use a different name for a second Master/Receiver pair.XAUUSD=60/40.The robot's settings
?key= and without a trailing slash.SP500=US500, or a suffix like .s.XAUUSD, SP500. Blank = any pair the indicator sends.PAIR=amount. Pairs not listed use TPBufferPoints.XAUUSD=-0.20, BTCUSD=20 (gold stop 0.20 closer, Bitcoin stop 20 further). Pairs not listed use SLBufferPoints. Applies to the extra layer trade too.The code
// Open Legacy Relay v1.6 โ Cloudflare Worker + D1 (signals, layers, copy trading, Forex Factory news at ?ff=1).
// Root path: TradingView webhook (POST) / All-in-One EA poll (GET). /copy/push + /copy/pull: Copy Master / Copy Receiver.
// Bindings: D1 database -> DB Secret -> KEY
// Tables (already created on your account):
// signals(id,ts,side,sym,sl,tp,lots) copy_events(id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER, ch TEXT, ev TEXT) copy_state(ch TEXT PRIMARY KEY, ts INTEGER, snap TEXT)
const EV = /^(OPEN;\d+;[A-Za-z0-9._]+;(BUY|SELL);[0-9.]+;[0-9.]+;[0-9.]+;[0-9.]+|MODIFY;\d+;[0-9.]+;[0-9.]+;[0-9.]+|CLOSE;\d+|REDUCE;\d+;[0-9.]+;[0-9.]+)$/;
async function copy(req, env, url, path) {
const ch = (url.searchParams.get("ch") || "main").replace(/[^A-Za-z0-9_-]/g, "").slice(0, 32) || "main";
const now = Date.now();
if (path === "/copy/push" && req.method === "POST") {
const lines = (await req.text()).slice(0, 6000).split("\n").map((l) => l.trim());
const stmts = [];
for (const l of lines.filter((l) => EV.test(l)).slice(0, 40)) {
stmts.push(env.DB.prepare("INSERT INTO copy_events (ts, ch, ev) VALUES (?1, ?2, ?3)").bind(now, ch, l));
}
const snap = lines.find((l) => /^SNAP;[0-9,]*$/.test(l));
if (snap) {
stmts.push(env.DB.prepare("INSERT INTO copy_state (ch, ts, snap) VALUES (?1, ?2, ?3) ON CONFLICT(ch) DO UPDATE SET ts = ?2, snap = ?3").bind(ch, now, snap.slice(5)));
}
stmts.push(env.DB.prepare("DELETE FROM copy_events WHERE ts < ?1").bind(now - 86400000));
await env.DB.batch(stmts);
return new Response("ok");
}
if (path === "/copy/pull") {
const since = parseInt(url.searchParams.get("since") || "0", 10) || 0;
const [top, ev, st] = await env.DB.batch([
env.DB.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM copy_events"),
env.DB.prepare("SELECT id, ts, ev FROM copy_events WHERE id > ?1 AND ch = ?2 ORDER BY id LIMIT 50").bind(since, ch),
env.DB.prepare("SELECT ts, snap FROM copy_state WHERE ch = ?1").bind(ch),
]);
let out = "M;" + top.results[0].m + "\n";
if (st.results.length) out += "S;" + Math.round((now - st.results[0].ts) / 1000) + ";" + st.results[0].snap + "\n";
for (const r of ev.results) out += r.id + ";" + Math.round((now - r.ts) / 1000) + ";" + r.ev + "\n";
return new Response(out, { headers: { "content-type": "text/plain" } });
}
return new Response("not found", { status: 404 });
}
export default {
async fetch(req, env) {
const url = new URL(req.url);
if (!env.KEY || url.searchParams.get("key") !== env.KEY) {
return new Response("forbidden", { status: 403 });
}
if (url.pathname.startsWith("/copy/")) return copy(req, env, url, url.pathname);
// Forex Factory calendar (red/orange/yellow) for the EA news filter.
// Saved in your D1 database: refreshed at most every 30 min, retried every 5 min if Forex Factory refuses,
// and the last good copy is always served meanwhile, so the EA never goes without news data.
if (url.searchParams.get("ff")) {
const txt = (s, st) => new Response(s, { status: st || 200, headers: { "content-type": "text/plain" } });
await env.DB.prepare("CREATE TABLE IF NOT EXISTS ffcache (k TEXT PRIMARY KEY, v TEXT, ts INTEGER)").run();
const now = Date.now();
const week = await env.DB.prepare("SELECT v, ts FROM ffcache WHERE k = 'week'").first();
if (week && now - week.ts < 30 * 60 * 1000) return txt(week.v);
const cool = await env.DB.prepare("SELECT ts FROM ffcache WHERE k = 'cool'").first();
if (!cool || now - cool.ts > 5 * 60 * 1000) {
let arr = null, last = "";
const urls = ["https://nfs.faireconomy.media/ff_calendar_thisweek.json", "https://cdn-nfs.faireconomy.media/ff_calendar_thisweek.json"];
const uas = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15"];
for (let i = 0; i < 4 && !arr; i++) {
try {
const x = await fetch(urls[i % 2], { headers: { "user-agent": uas[i % 2], "accept": "application/json,text/plain,*/*", "accept-language": "en-US,en;q=0.9" } });
if (x.ok) { const j = await x.json(); if (Array.isArray(j) && j.length) arr = j; else last = "empty"; }
else last = "ff " + x.status;
} catch (e) { last = "ff " + e.message; }
}
if (arr) {
let o = "FF;" + arr.length + "\n";
for (const e of arr) {
const imp = e.impact === "High" ? 3 : e.impact === "Medium" ? 2 : e.impact === "Low" ? 1 : 0;
const t = Math.floor(Date.parse(e.date) / 1000);
if (!imp || !t) continue;
o += [t, String(e.country || "").toUpperCase(), imp, String(e.title || "").replace(/[;\n]/g, " ")].join(";") + "\n";
}
await env.DB.prepare("INSERT OR REPLACE INTO ffcache (k, v, ts) VALUES ('week', ?1, ?2)").bind(o, now).run();
return txt(o);
}
await env.DB.prepare("INSERT OR REPLACE INTO ffcache (k, v, ts) VALUES ('cool', ?1, ?2)").bind(last, now).run();
}
if (week) return txt(week.v); // older but real data is better than none
return txt("FF;0\n"); // nothing yet: the EA uses the MT5 calendar until the feed comes back
}
if (req.method === "POST") {
const text = (await req.text()).slice(0, 4000);
const m = text.match(/OL(L?);(BUY|SELL);([A-Za-z0-9._]+);([0-9.]+);([0-9.]+)(?:;([0-9.]+))?/);
const now = Date.now();
if (!m) {
// "Take Profit Hit" / "Stop Loss Hit" alert from the main indicator -> tell the EA to close that trade now
const x = text.match(/([A-Za-z0-9._]+) \(([A-Za-z0-9]+)\) (Take Profit|Stop Loss) Hit/);
if (!x) return new Response("ignored", { status: 200 });
await env.DB.prepare("INSERT INTO signals (ts, side, sym, sl, tp, lots) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
.bind(now, (x[3] === "Take Profit" ? "XTP" : "XSL") + "@" + x[2], x[1].toUpperCase(), "0", "0", "0").run();
return new Response("ok");
}
// chart timeframe from the entry alert's first line, e.g. "XAUUSD (15) New BUY Active!"
const tf = m[1] ? null : text.match(/\(([A-Za-z0-9]+)\) New/);
await env.DB.prepare("INSERT INTO signals (ts, side, sym, sl, tp, lots) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
.bind(now, (m[1] ? "L" : "") + m[2] + (tf ? "@" + tf[1] : ""), m[3].toUpperCase(), m[4], m[5], m[6] || "0").run();
await env.DB.prepare("DELETE FROM signals WHERE ts < ?1").bind(now - 86400000).run();
return new Response("ok");
}
const since = parseInt(url.searchParams.get("since") || "0", 10) || 0;
const top = await env.DB.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM signals").first();
const { results } = await env.DB
.prepare("SELECT id, ts, side, sym, sl, tp, lots FROM signals WHERE id > ?1 ORDER BY id LIMIT 20")
.bind(since).all();
const now = Date.now();
let out = "M;" + top.m + "\n";
for (const r of results) {
out += [r.id, r.side, r.sym, r.sl, r.tp, Math.round((now - r.ts) / 1000), r.lots || "0"].join(";") + "\n";
}
return new Response(out, { headers: { "content-type": "text/plain" } });
},
};
//+------------------------------------------------------------------+
//| Open Legacy All-in-One EA |
//| v1.70: ONE EA = webhook trader + instant TP/SL close + Auto SL/TP |
//| + Copy Master (ShareToReceiver) + Copy Receiver (Role). |
//| Opens trades from Open Legacy indicator alerts. TradingView sends |
//| the alert to your relay (Cloudflare Worker); this EA checks the |
//| relay every second and places the trade. Runs on the MQL5 VPS. |
//| Needs: Tools > Options > Expert Advisors > Allow WebRequest, with |
//| your Relay URL added to the list. |
//+------------------------------------------------------------------+
#property copyright "Open Legacy"
#property version "1.84"
#property description "Open Legacy All-in-One EA - trades the indicator's alerts (lot size comes from the indicator), with a max open trades limit and an optional waiting list."
#include <Trade\Trade.mqh>
void OLComment(const string txt);
void OLPanelClear();
enum ENUM_ROLE { ROLE_TRADER=0, ROLE_RECEIVER=1 };
enum ENUM_NEWS_LEVEL { NEWS_RED_ONLY=0, NEWS_ORANGE_RED=1, NEWS_ALL_COLOURS=2 };
enum ENUM_NEWS_SRC { SRC_FOREX_FACTORY=0, SRC_MT5_CALENDAR=1 };
input group "Role"
input ENUM_ROLE Role = ROLE_TRADER; // Role: Trader or Copy Receiver
input group "Splash screen"
input bool ShowSplash = true; // Show the Open Legacy splash screen on start
input bool SplashStay = false; // Keep it on the chart permanently
input int SplashSeconds = 6; // Seconds shown (0 = until clicked)
input int SplashOpacity = 90; // Opacity % (lower = see more chart)
input group "Webhook"
input string RelayURL = "https://your-relay.workers.dev"; // Relay URL (Cloudflare Worker)
input string SecretKey = ""; // Secret key
input int PollSeconds = 1; // Check for signals every (sec)
input int MaxSignalAge = 120; // Ignore signals older than (sec)
input group "Trade limits"
input int MaxOpenTrades = 1; // Max trades open at once
input bool CountAllTrades = false; // Count manual/other trades too
input bool CloseOnOpposite = true; // Opposite signal closes + flips
input bool CloseOnAlert = true; // Close the trade the moment the indicator alerts TP hit / SL hit
input bool QueueSignals = true; // Hold signals until a slot is free
input int QueueExpiryMin = 30; // Drop held signal after (min)
input string AllowedSymbols = ""; // Only trade pairs (blank = all)
input group "Symbols (lot set in indicator)"
input string SymbolMap = ""; // Name map, e.g. SP500=US500
input string SymbolSuffix = ""; // Pair suffix, e.g. .s
input int SlippagePoints = 30; // Max slippage (points)
input group "Match TP / SL (price differences)"
input bool MatchChartMove = true; // Match indicator TP/SL distance
input int TPBufferPoints = 0; // TP closer by (points)
input int SLBufferPoints = 0; // SL further by (points), minus = closer
input string TPBufferMap = "XAUUSD=0.30,BTCUSD=15,NAS100=2,AUDUSD=0.00006,GBPUSD=0.00008"; // Per-pair TP buffer (price)
input string SLBufferMap = ""; // Per-pair SL buffer (price), e.g. XAUUSD=-0.20
input group "News filter (skips trades near news)"
input bool UseNewsFilter = true; // Skip trades near news
input int NewsBeforeMin = 40; // Pause this many min before news
input int NewsAfterMin = 30; // ...and this many min after
input bool CloseBeforeNews = false; // Also close open trades when the pause starts
input ENUM_NEWS_SRC NewsSource = SRC_FOREX_FACTORY; // News source
input ENUM_NEWS_LEVEL NewsLevel = NEWS_ORANGE_RED; // Colours to avoid
input bool NewsKeyOnly = false; // Key words only (off = all events)
input string NewsKeywords = "CPI,PPI,PCE,FOMC,Fed,Powell,Non-Farm,Nonfarm,NFP,PMI,ISM,Interest Rate,Rate Decision,Rate Statement,GDP,Retail Sales,Unemployment,Jobless Claims,Employment Change,Consumer Confidence,Bailey,Lagarde"; // Key event words
input string NewsExtraCcy = "USD"; // Always watch these currencies
input string NewsAlwaysWords = ""; // Always-pause words (any colour)
input string NewsIgnoreOrange = "Speaks,Speech"; // Ignore orange words (not red)
input int NewsShiftMin = 0; // News clock offset (min)
input group "Auto SL/TP for manual trades"
input bool UseAutoSLTP = false; // Turn on Auto SL/TP
input string AutoRules = "XAUUSD=60/40, NAS100=1400/1000"; // Pair=SL/TP in pips, comma separated
input int AutoPointsPerPip = 10; // Points per pip (10 for gold, BTC, indices)
input bool AutoManualOnly = true; // Only touch trades you open yourself (not the EA's)
input group "Copy Master (share trades)"
input bool ShareToReceiver = false; // Share every trade here with a Copy Receiver
input string Channel = "main"; // Channel name (receiver must use the same)
input long OnlyMagic = -1; // Share only this magic number (-1 = all)
input bool ShareExisting = false; // Also share trades already open when this EA starts
input string OnlySymbols = ""; // Only share these pairs, e.g. XAUUSD.s (blank = all)
input int ScanMs = 250; // How often to check this account (ms)
input int SnapshotSeconds = 10; // Safety snapshot every (sec)
enum LOT_MODE { LOT_MULTIPLIER = 0, LOT_FIXED = 1 };
input group "Copy Receiver settings"
input group "Receiver lot size"
input LOT_MODE LotMode = LOT_MULTIPLIER; // Lot sizing
input double LotMultiplier = 1.0; // Multiplier x the Master's lots
input double FixedLot = 0.01; // Fixed lot (when mode = Fixed)
input double MaxLotPerTrade = 0; // Cap per trade (0 = no cap)
input group "Safety"
input int RMaxOpenTrades = 0; // Max copied trades open at once (0 = no limit)
input int PollMs = 1000; // Receiver: check for new trades every (ms)
input int MaxOpenAgeSec = 20; // Skip copy if Master opened it over (sec) ago
input bool SLTPFromEntry = true; // Keep SL/TP distance from entry
input bool SyncOrphans = true; // Close copies whose Master trade no longer exists
input string RAllowedSymbols = ""; // Only copy these Master pairs (blank = all)
input group "Symbols"
input string RSymbolMap = ""; // Master=This broker, e.g. XAUUSD.s=XAUUSD
input string RSymbolSuffix = ""; // Added to the base name if needed, e.g. .cash
input long RMagic = 777002; // Magic number for copied trades
input group "Layering (extra half-size trade from Open Legacy Side-Kick)"
input bool UseLayering = false; // Accept layer signals from Open Legacy Side-Kick
input double LayerLotPct = 50; // Layer size (% of first trade lots)
input long MagicNumber = 777001; // Magic number
CTrade trade;
ulong nextWh = 0;
// ---- Auto SL/TP (merged from the Auto SL/TP EA) ----
string aSym[];
double aSl[];
double aTp[];
ulong aDone[];
ulong aTryT[];
int aTryN[];
bool AIsDone(ulong t){ for(int i=0;i<ArraySize(aDone);i++) if(aDone[i]==t) return true; return false; }
void AMarkDone(ulong t){ int n=ArraySize(aDone); ArrayResize(aDone,n+1); aDone[n]=t; }
int ATries(ulong t){ for(int i=0;i<ArraySize(aTryT);i++) if(aTryT[i]==t) return ++aTryN[i]; int n=ArraySize(aTryT); ArrayResize(aTryT,n+1); ArrayResize(aTryN,n+1); aTryT[n]=t; aTryN[n]=1; return 1; }
bool AParse()
{
ArrayResize(aSym,0); ArrayResize(aSl,0); ArrayResize(aTp,0);
string parts[];
int n = StringSplit(AutoRules, ',', parts);
for(int i=0;i<n;i++)
{
string p = parts[i];
StringTrimLeft(p); StringTrimRight(p);
if(StringLen(p)==0) continue;
string kv[];
if(StringSplit(p, '=', kv)!=2) { Print("Open Legacy Auto SL/TP: can't read rule '", p, "' (use PAIR=SL/TP)"); return false; }
string key = kv[0]; StringTrimLeft(key); StringTrimRight(key); StringToUpper(key);
string v[];
if(StringSplit(kv[1], '/', v)!=2) { Print("Open Legacy Auto SL/TP: can't read '", p, "' (use PAIR=SL/TP)"); return false; }
int k = ArraySize(aSym);
ArrayResize(aSym,k+1); ArrayResize(aSl,k+1); ArrayResize(aTp,k+1);
aSym[k] = key; aSl[k] = StringToDouble(v[0]); aTp[k] = StringToDouble(v[1]);
}
return ArraySize(aSym) > 0;
}
int AFind(string sym)
{
string s = sym; StringToUpper(s);
for(int i=0;i<ArraySize(aSym);i++) if(StringFind(s, aSym[i])==0) return i;
return -1;
}
void AutoApply()
{
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0 || AIsDone(t)) continue;
if(AutoManualOnly && PositionGetInteger(POSITION_MAGIC)!=0) { AMarkDone(t); continue; }
string sym = PositionGetString(POSITION_SYMBOL);
int r = AFind(sym);
if(r<0) { AMarkDone(t); continue; }
double curSl = PositionGetDouble(POSITION_SL), curTp = PositionGetDouble(POSITION_TP);
if(curSl!=0.0 && curTp!=0.0) { AMarkDone(t); continue; } // already has both: leave it
bool buy = PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY;
double open = PositionGetDouble(POSITION_PRICE_OPEN);
double pt = SymbolInfoDouble(sym, SYMBOL_POINT);
int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double dSl = aSl[r] * AutoPointsPerPip * pt;
double dTp = aTp[r] * AutoPointsPerPip * pt;
double sl = curSl!=0.0 ? curSl : (aSl[r]>0 ? (buy ? open-dSl : open+dSl) : 0.0);
double tp = curTp!=0.0 ? curTp : (aTp[r]>0 ? (buy ? open+dTp : open-dTp) : 0.0);
// keep levels outside the broker's minimum distance
double minD = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * pt;
double bid = SymbolInfoDouble(sym, SYMBOL_BID), ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double ref = buy ? bid : ask;
if(sl!=0.0) sl = buy ? MathMin(sl, ref-minD) : MathMax(sl, ref+minD);
if(tp!=0.0) tp = buy ? MathMax(tp, ref+minD) : MathMin(tp, ref-minD);
sl = NormalizeDouble(sl, dg); tp = NormalizeDouble(tp, dg);
if(trade.PositionModify(t, sl, tp))
{
AMarkDone(t);
PrintFormat("Open Legacy Auto SL/TP: %s #%I64u SL %s TP %s", sym, t, DoubleToString(sl,dg), DoubleToString(tp,dg));
}
else if(ATries(t)>=10)
{
AMarkDone(t);
PrintFormat("Open Legacy Auto SL/TP: gave up on #%I64u (%s): %s", t, sym, trade.ResultRetcodeDescription());
}
}
}
long lastId = 0;
string status = "Starting...";
string lastSig = "none yet";
string gvName;
// Signals waiting for a free slot (one per pair, newest wins)
string qSide[], qTv[];
double qSl[], qTp[], qLots[];
datetime qTime[];
// Looks up a pair in a buffer map (price units). Returns EMPTY_VALUE if the pair isn't listed.
double MapBuf(const string map, const string tv, const string sym)
{
string parts[];
int n = StringSplit(map, ',', parts);
string a = tv, b = sym;
StringToUpper(a); StringToUpper(b);
int dot = StringFind(b, "."); if(dot>0) b = StringSubstr(b, 0, dot);
for(int i=0;i<n;i++)
{
string kv[];
if(StringSplit(parts[i], '=', kv)!=2) continue;
string k = kv[0]; StringTrimLeft(k); StringTrimRight(k); StringToUpper(k);
if(k==a || k==b) return StringToDouble(kv[1]);
}
return EMPTY_VALUE;
}
string Trim(string s){ StringTrimLeft(s); StringTrimRight(s); return s; }
string Up(string s){ StringToUpper(s); return s; }
void Note(const string msg);
// readable signal name for on-screen messages, e.g. "LSELL" -> "layer SELL", "XTP@15" -> "TP hit (15)"
string NiceSide(const string sd)
{
string s = sd, tf = "";
int at = StringFind(s, "@");
if(at>0) { tf = StringSubstr(s, at+1); s = StringSubstr(s, 0, at); }
string r = s;
if(s=="LBUY") r = "layer BUY";
if(s=="LSELL") r = "layer SELL";
if(s=="XTP") r = "TP hit";
if(s=="XSL") r = "SL hit";
if(tf!="") r += " (" + tf + ")";
return r;
}
// ---- news filter ----
bool KeyMatch(const string name)
{
string n = name; StringToUpper(n);
string w[];
int k = StringSplit(NewsKeywords, ',', w);
for(int i=0;i<k;i++)
{
string x = Trim(w[i]); StringToUpper(x);
if(x!="" && StringFind(n, x)>=0) return true;
}
return false;
}
bool IgnoreMatch(const string name)
{
string n = name; StringToUpper(n);
string w[];
int k = StringSplit(NewsIgnoreOrange, ',', w);
for(int i=0;i<k;i++)
{
string x = Trim(w[i]); StringToUpper(x);
if(x!="" && StringFind(n, x)>=0) return true;
}
return false;
}
bool AlwaysMatch(const string name)
{
string n = name; StringToUpper(n);
string w[];
int k = StringSplit(NewsAlwaysWords, ',', w);
for(int i=0;i<k;i++)
{
string x = Trim(w[i]); StringToUpper(x);
if(x!="" && StringFind(n, x)>=0) return true;
}
return false;
}
bool calWarned = false;
// ---- Forex Factory feed (fetched through your relay, refreshed every 10 min) ----
datetime ffT[]; string ffC[]; int ffI[]; string ffN[];
int ffCount = 0; datetime ffLast = 0; bool ffOk = false;
void FFLoad()
{
if(NewsSource!=SRC_FOREX_FACTORY) return;
if(ffLast!=0 && TimeLocal()-ffLast < 600) return;
ffLast = TimeLocal();
string url = Trim(RelayURL); url += "/?key=" + SecretKey + "&ff=1";
char post[], res[]; string rh;
ResetLastError();
int code = WebRequest("GET", url, "", 8000, post, res, rh);
if(code!=200) { if(!ffOk) Note(code==-1 ? "News: allow the relay URL under Tools > Options > Expert Advisors > WebRequest. Using MT5 calendar" : "News: Forex Factory feed unavailable (code " + (string)code + "). Using MT5 calendar"); ffLast = TimeLocal() - 540; return; }
string txt = CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8);
string lines[]; int n = StringSplit(txt, '\n', lines);
ArrayResize(ffT, 0); ArrayResize(ffC, 0); ArrayResize(ffI, 0); ArrayResize(ffN, 0);
int k = 0;
for(int i=0;i<n;i++)
{
string f[]; if(StringSplit(lines[i], ';', f) < 4) continue;
if(f[0]=="FF") continue;
ArrayResize(ffT, k+1); ArrayResize(ffC, k+1); ArrayResize(ffI, k+1); ArrayResize(ffN, k+1);
ffT[k] = (datetime)StringToInteger(f[0]); ffC[k] = f[1]; ffI[k] = (int)StringToInteger(f[2]);
ffN[k] = f[3]; for(int j=4;j<ArraySize(f);j++) ffN[k] += ";" + f[j];
k++;
}
ffCount = k;
if(k>0){ if(!ffOk) Note("Forex Factory news loaded: " + (string)k + " events this week"); ffOk = true; }
}
bool FFBlock(const string &cur[], int nc, string &why)
{
int minImp = (NewsLevel==NEWS_RED_ONLY) ? 3 : (NewsLevel==NEWS_ORANGE_RED ? 2 : 1);
datetime g = TimeGMT();
for(int i=0;i<ffCount;i++)
{
if(ffT[i] < g - NewsAfterMin*60 || ffT[i] > g + NewsBeforeMin*60) continue;
bool ok = false;
for(int c=0;c<nc;c++) if(cur[c]==ffC[i]) ok = true;
if(!ok) continue;
if(!AlwaysMatch(ffN[i]))
{
if(ffI[i] < minImp) continue;
if(ffI[i] < 3 && IgnoreMatch(ffN[i])) continue;
if(NewsKeyOnly && !KeyMatch(ffN[i])) continue;
}
string col = ffI[i]==3 ? "RED" : (ffI[i]==2 ? "ORANGE" : "YELLOW");
why = "Forex Factory " + col + " " + ffC[i] + " " + ffN[i] + " at " + TimeToString(ffT[i], TIME_DATE|TIME_MINUTES) + " GMT";
return true;
}
return false;
}
// True if a qualifying event for this pair's currencies is inside the pause window.
bool NewsBlock(const string sym, string &why)
{
if(!UseNewsFilter) return false;
string cur[]; int nc = 0;
string list = SymbolInfoString(sym, SYMBOL_CURRENCY_BASE) + "," + SymbolInfoString(sym, SYMBOL_CURRENCY_PROFIT) + "," + NewsExtraCcy;
string raw[]; int rn = StringSplit(list, ',', raw);
for(int i=0;i<rn;i++)
{
string c = Trim(raw[i]); StringToUpper(c);
if(c=="") continue;
bool dup = false;
for(int j=0;j<nc;j++) if(cur[j]==c) dup = true;
if(dup) continue;
ArrayResize(cur, nc+1); cur[nc++] = c;
}
if(NewsSource==SRC_FOREX_FACTORY){ FFLoad(); if(ffOk) return FFBlock(cur, nc, why); }
datetime nowS = TimeTradeServer();
datetime from = nowS - NewsAfterMin*60 + NewsShiftMin*60, to = nowS + NewsBeforeMin*60 + NewsShiftMin*60;
for(int c=0;c<nc;c++)
{
MqlCalendarValue v[];
ResetLastError();
int got = CalendarValueHistory(v, from, to, NULL, cur[c]);
if(got<0)
{
if(!calWarned){ calWarned = true; Note("News filter: calendar not available (error " + (string)GetLastError() + ") - trading without it"); }
continue;
}
for(int i=0;i<got;i++)
{
MqlCalendarEvent ev;
if(!CalendarEventById(v[i].event_id, ev)) continue;
if(ev.type==CALENDAR_TYPE_HOLIDAY) continue;
bool force = AlwaysMatch(ev.name); // your own must-pause words, any colour
if(!force)
{
bool okImp = (ev.importance==CALENDAR_IMPORTANCE_HIGH) || (NewsLevel==NEWS_ORANGE_RED && ev.importance==CALENDAR_IMPORTANCE_MODERATE);
if(!okImp) continue;
if(ev.importance==CALENDAR_IMPORTANCE_MODERATE && IgnoreMatch(ev.name)) continue; // medium speeches never pause trading
if(NewsKeyOnly && !KeyMatch(ev.name)) continue;
}
why = cur[c] + " " + ev.name + " at " + TimeToString(v[i].time, TIME_MINUTES) + " (server time now " + TimeToString(nowS, TIME_MINUTES) + ", shift " + (string)NewsShiftMin + ")";
return true;
}
}
return false;
}
void Note(const string msg)
{
lastSig = TimeToString(TimeLocal(), TIME_SECONDS) + " " + msg;
Print("Open Legacy All-in-One EA: ", msg);
}
// Reads "A=1, B=2" style lists. key must be upper case.
string ListGet(const string list, const string key, const string def)
{
string parts[];
int n = StringSplit(list, ',', parts);
for(int i=0;i<n;i++)
{
string kv[];
if(StringSplit(parts[i], '=', kv)!=2) continue;
if(Up(Trim(kv[0]))==key) return Trim(kv[1]);
}
return def;
}
bool Allowed(const string tv)
{
if(Trim(AllowedSymbols)=="") return true;
string parts[];
int n = StringSplit(AllowedSymbols, ',', parts);
for(int i=0;i<n;i++) if(Up(Trim(parts[i]))==tv) return true;
return false;
}
// TradingView name -> your broker's symbol (handles XAUUSD vs XAUUSD.s / XAUUSDm)
string Resolve(const string tv)
{
string b = ListGet(SymbolMap, tv, tv + SymbolSuffix);
if(SymbolSelect(b, true)) return b;
int total = SymbolsTotal(false);
for(int i=0;i<total;i++)
{
string s = SymbolName(i, false);
if(StringFind(Up(s), tv)==0 && SymbolSelect(s, true)) return s;
}
return "";
}
double LotFor(const string sym, const double want)
{
double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
double mn = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
double mx = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
double v = (want > 0) ? want : mn; // no lot in the alert -> smallest allowed
if(step>0) v = MathFloor(v/step + 1e-9)*step;
v = MathMax(mn, MathMin(mx, v));
return NormalizeDouble(v, 8);
}
int CountOpen()
{
int n = 0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(StringFind(PositionGetString(POSITION_COMMENT), "OL Layer")==0) continue;
if(CountAllTrades || PositionGetInteger(POSITION_MAGIC)==MagicNumber) n++;
}
return n;
}
ulong FindOurs(const string sym, ENUM_POSITION_TYPE &type)
{
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber) continue;
if(PositionGetString(POSITION_SYMBOL)!=sym) continue;
if(StringFind(PositionGetString(POSITION_COMMENT), "OL Layer")==0) continue;
type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
return t;
}
return 0;
}
void QRemove(const int i)
{
int n = ArraySize(qTv);
for(int j=i; j<n-1; j++)
{
qSide[j]=qSide[j+1]; qTv[j]=qTv[j+1]; qSl[j]=qSl[j+1]; qTp[j]=qTp[j+1]; qLots[j]=qLots[j+1]; qTime[j]=qTime[j+1];
}
ArrayResize(qSide,n-1); ArrayResize(qTv,n-1); ArrayResize(qSl,n-1); ArrayResize(qTp,n-1); ArrayResize(qLots,n-1); ArrayResize(qTime,n-1);
}
void QDropPair(const string tv)
{
for(int i=ArraySize(qTv)-1; i>=0; i--) if(qTv[i]==tv) QRemove(i);
}
void QPush(const string side, const string tv, const double sl, const double tp, const double lots)
{
QDropPair(tv); // one held signal per pair: the newest
int n = ArraySize(qTv);
ArrayResize(qSide,n+1); ArrayResize(qTv,n+1); ArrayResize(qSl,n+1); ArrayResize(qTp,n+1); ArrayResize(qLots,n+1); ArrayResize(qTime,n+1);
qSide[n]=side; qTv[n]=tv; qSl[n]=sl; qTp[n]=tp; qLots[n]=lots; qTime[n]=TimeLocal();
}
// Close every trade of ours on a symbol (the first trade and its layer)
bool CloseAllOurs(const string sym)
{
bool ok = true;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber) continue;
if(PositionGetString(POSITION_SYMBOL)!=sym) continue;
if(!trade.PositionClose(t)) { Note("FAILED to close " + sym + ": " + trade.ResultRetcodeDescription()); ok = false; }
}
return ok;
}
// News: when a pair enters its news pause window (NewsBeforeMin before the event), close our open trades on it.
// New trades stay blocked until NewsAfterMin after the event.
void CloseForNews()
{
if(!UseNewsFilter || !CloseBeforeNews) return;
string done[]; int nd = 0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber) continue;
string sym = PositionGetString(POSITION_SYMBOL);
bool seen = false;
for(int j=0;j<nd;j++) if(done[j]==sym) seen = true;
if(seen) continue;
ArrayResize(done, nd+1); done[nd++] = sym;
string why = "";
if(NewsBlock(sym, why))
{
Note("NEWS - closing " + sym + " before news: " + why);
CloseAllOurs(sym);
}
}
}
// Side-Kick says "layer now": add ONE extra trade, same SL and TP as the first trade, half the lots.
void HandleLayer(const string side, const string tv)
{
bool buy = (side=="LBUY");
if(!UseLayering) { Note("IGNORED layer " + tv + " - layering is off"); return; }
if(!Allowed(tv)) return;
string sym = Resolve(tv);
if(sym=="") { Note("IGNORED layer " + tv + " - symbol not found on this broker"); return; }
string nwhy;
if(NewsBlock(sym, nwhy)) { Note("SKIPPED layer " + sym + " - news pause: " + nwhy); return; }
ulong mt = 0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber || PositionGetString(POSITION_SYMBOL)!=sym) continue;
if(StringFind(PositionGetString(POSITION_COMMENT), "OL Layer")==0) continue;
if((PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)!=buy) continue;
mt = t; break;
}
if(mt==0) { Note("IGNORED layer " + sym + " - no matching open trade"); return; }
string gv = "OLWH_L_" + (string)mt;
// Also look at the open trades themselves, so a second copy of the EA (another terminal) can never add a second layer
bool hasLayer = false;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetString(POSITION_COMMENT)=="OL Layer " + (string)mt) { hasLayer = true; break; }
}
if(hasLayer) GlobalVariableSet(gv, 1);
if(hasLayer || GlobalVariableCheck(gv)) { Note("IGNORED layer " + sym + " - this trade already has its layer"); return; }
PositionSelectByTicket(mt);
double vol = PositionGetDouble(POSITION_VOLUME), sl = PositionGetDouble(POSITION_SL), tp = PositionGetDouble(POSITION_TP);
double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP), mn = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
double lots = vol * LayerLotPct / 100.0;
if(step>0) lots = MathFloor(lots/step + 1e-9)*step;
if(lots < mn) { Note("LAYER skipped " + sym + " - half lots is below the minimum lot"); GlobalVariableSet(gv, 1); return; }
lots = MathMin(lots, SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX));
double ask = SymbolInfoDouble(sym, SYMBOL_ASK), bid = SymbolInfoDouble(sym, SYMBOL_BID), margin = 0;
if(!OrderCalcMargin(buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, sym, lots, buy ? ask : bid, margin) || margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
{ Note("LAYER skipped " + sym + " - not enough free margin"); return; }
string cm = "OL Layer " + (string)mt;
bool ok = buy ? trade.Buy(lots, sym, 0, sl, tp, cm) : trade.Sell(lots, sym, 0, sl, tp, cm);
int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
if(ok) { GlobalVariableSet(gv, 1); Note("LAYER " + (buy ? "BUY " : "SELL ") + sym + " " + DoubleToString(lots,2) + " lots SL " + DoubleToString(sl,dg) + " TP " + DoubleToString(tp,dg)); }
else Note("LAYER FAILED " + sym + ": " + trade.ResultRetcodeDescription());
}
// Indicator says TP hit / SL hit: close that chart's trade (and its layer) right away.
// Only trades opened before the alert was sent are closed, so a newer trade is never hit by a late alert.
void HandleExit(const string sd, const string tv, const long age)
{
if(!CloseOnAlert) return;
string tf = "", s = sd;
int at = StringFind(s, "@");
if(at>0) { tf = StringSubstr(s, at+1); s = StringSubstr(s, 0, at); }
if(!Allowed(tv)) return;
string sym = Resolve(tv);
if(sym=="") return;
datetime cutoff = TimeTradeServer() - (datetime)age + 2;
string mainCm = "Open Legacy " + tf;
ulong mains[]; int nm = 0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber || PositionGetString(POSITION_SYMBOL)!=sym) continue;
string c = PositionGetString(POSITION_COMMENT);
if(StringFind(c, "OL Layer")==0) continue;
if(tf!="" && c!=mainCm) continue;
if((datetime)PositionGetInteger(POSITION_TIME) > cutoff) continue;
ArrayResize(mains, nm+1); mains[nm++] = t;
}
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetInteger(POSITION_MAGIC)!=MagicNumber || PositionGetString(POSITION_SYMBOL)!=sym) continue;
string c = PositionGetString(POSITION_COMMENT);
bool hit = false;
for(int j=0;j<nm;j++) if(t==mains[j] || c=="OL Layer " + (string)mains[j]) hit = true;
if(!hit) continue;
if(trade.PositionClose(t)) Note("CLOSED " + sym + " #" + (string)t + " - indicator said " + (s=="XTP" ? "TP hit" : "SL hit"));
else Note("FAILED to close " + sym + ": " + trade.ResultRetcodeDescription());
}
}
bool Block(const string side, const string tv, const string sym, const double sl, const double tp, const double lots, const string why, const bool fromQueue)
{
if(!QueueSignals) { Note("IGNORED " + side + " " + sym + " - " + why); return false; }
if(fromQueue) return true; // already waiting, stay quiet
QPush(side, tv, sl, tp, lots);
Note("HELD " + side + " " + sym + " - " + why + ". Opens when a slot is free.");
return true;
}
// Returns true while the signal is still waiting (held). open = trades currently open, kept current across a batch.
bool Handle(const string sideIn, const string tv, const double slD, const double tpD, const double lotsWanted, int &open, const bool fromQueue)
{
string side = sideIn, sideTf = sideIn, tf = "";
int at = StringFind(sideTf, "@");
if(at>0) { tf = StringSubstr(sideTf, at+1); side = StringSubstr(sideTf, 0, at); }
bool buy = (side=="BUY");
if(!Allowed(tv)) { Note("IGNORED " + side + " " + tv + " - not in AllowedSymbols"); return false; }
string sym = Resolve(tv);
if(sym=="") { Note("IGNORED " + side + " " + tv + " - symbol not found on this broker (use SymbolMap)"); return false; }
string nwhy;
if(NewsBlock(sym, nwhy)) { Note("SKIPPED " + side + " " + sym + " - news pause: " + nwhy); return false; }
ENUM_POSITION_TYPE pt;
ulong t = FindOurs(sym, pt);
if(t!=0)
{
bool same = ((pt==POSITION_TYPE_BUY)==buy);
if(same) { Note("IGNORED " + side + " " + sym + " - already in that trade"); return false; }
if(!CloseOnOpposite)
return Block(sideTf, tv, sym, slD, tpD, lotsWanted, "opposite trade is running", fromQueue);
if(!CloseAllOurs(sym)) return false;
open--;
}
if(open >= MaxOpenTrades)
return Block(sideTf, tv, sym, slD, tpD, lotsWanted, "max trades reached (" + (string)open + "/" + (string)MaxOpenTrades + ")", fromQueue);
double lots = LotFor(sym, lotsWanted);
double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double bid = SymbolInfoDouble(sym, SYMBOL_BID);
if(ask<=0 || bid<=0) { Note("IGNORED " + side + " " + sym + " - no price yet"); return false; }
double margin = 0;
if(!OrderCalcMargin(buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, sym, lots, buy ? ask : bid, margin) || margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
return Block(sideTf, tv, sym, slD, tpD, lotsWanted, "not enough free margin", fromQueue);
double pnt = SymbolInfoDouble(sym, SYMBOL_POINT);
int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double minD = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL)*pnt + (ask-bid);
double sl = 0, tp = 0;
// A buy closes at the bid and a sell closes at the ask, so measuring from that side
// makes the trade move exactly the distance the indicator drew (no spread offset).
double base = MatchChartMove ? (buy ? bid : ask) : (buy ? ask : bid);
double mb = MapBuf(TPBufferMap, tv, sym), ms = MapBuf(SLBufferMap, tv, sym);
double tpB = (mb!=EMPTY_VALUE) ? mb : TPBufferPoints*pnt, slB = (ms!=EMPTY_VALUE) ? ms : SLBufferPoints*pnt;
if(slD>0) { double d = MathMax(slD + slB, minD); sl = NormalizeDouble(buy ? base-d : base+d, dg); }
if(tpD>0) { double d = MathMax(tpD - tpB, minD); tp = NormalizeDouble(buy ? base+d : base-d, dg); }
string ocm = (tf!="") ? "Open Legacy " + tf : "Open Legacy";
bool ok = buy ? trade.Buy(lots, sym, 0, sl, tp, ocm) : trade.Sell(lots, sym, 0, sl, tp, ocm);
if(ok) { open++; Note((fromQueue ? "OPENED (was waiting) " : "OPENED ") + side + " " + sym + " " + DoubleToString(lots,2) + " lots SL " + DoubleToString(sl,dg) + " TP " + DoubleToString(tp,dg)); }
else Note("FAILED " + side + " " + sym + ": " + trade.ResultRetcodeDescription());
return false;
}
void Poll()
{
string url = Trim(RelayURL);
while(StringLen(url)>0 && StringSubstr(url, StringLen(url)-1, 1)=="/") url = StringSubstr(url, 0, StringLen(url)-1);
url += "/?key=" + SecretKey + "&since=" + (string)lastId;
char post[], res[];
string rh;
ResetLastError();
int code = WebRequest("GET", url, "", 5000, post, res, rh);
if(code==-1)
{
int e = GetLastError();
status = (e==4014) ? "Add your Relay URL in Tools > Options > Expert Advisors > Allow WebRequest"
: "Can't reach the relay (error " + (string)e + ")";
return;
}
if(code==403) { status = "Wrong secret key"; return; }
if(code!=200) { status = "Relay error " + (string)code; return; }
status = "Connected";
string body = CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8);
string lines[];
int n = StringSplit(body, '\n', lines);
int open = CountOpen();
for(int i=0;i<n;i++)
{
string line = Trim(lines[i]);
if(line=="") continue;
string f[];
int k = StringSplit(line, ';', f);
if(k<2) continue;
if(f[0]=="M") // newest id on the relay; if it's behind ours the relay was reset
{
if(StringToInteger(f[1]) < lastId) { lastId = 0; GlobalVariableSet(gvName, 0); }
continue;
}
if(k<6) continue;
long id = StringToInteger(f[0]);
string sd = Up(Trim(f[1]));
string tv = Up(Trim(f[2]));
double slD = StringToDouble(f[3]);
double tpD = StringToDouble(f[4]);
long age = StringToInteger(f[5]);
double lts = (k>=7) ? StringToDouble(f[6]) : 0;
if(age > MaxSignalAge) Note("Skipped old " + NiceSide(sd) + " " + tv + " (" + (string)age + "s old)");
else if(sd=="LBUY" || sd=="LSELL") HandleLayer(sd, tv);
else if(StringFind(sd, "X")==0) HandleExit(sd, tv, age);
else { QDropPair(tv); Handle(sd, tv, slD, tpD, lts, open, false); }
lastId = id;
GlobalVariableSet(gvName, (double)lastId);
}
}
// Runs every cycle: hands out free slots to held signals, oldest first
void ProcessQueue()
{
if(ArraySize(qTv)==0) return;
int open = CountOpen();
int i = 0;
while(i < ArraySize(qTv))
{
if(TimeLocal() - qTime[i] > QueueExpiryMin*60)
{ Note("DROPPED held " + qSide[i] + " " + qTv[i] + " - no slot opened in time"); QRemove(i); continue; }
string sd = qSide[i], tv = qTv[i];
double sl = qSl[i], tp = qTp[i], lt = qLots[i];
if(Handle(sd, tv, sl, tp, lt, open, true)) i++;
else QRemove(i);
}
}
void Panel()
{
string pt = "";
StringConcatenate(pt, "Open Legacy All-in-One EA\n",
"Status: ", status, "\n",
"Open trades: ", CountOpen(), " / ", MaxOpenTrades, " Waiting: ", ArraySize(qTv), "\n",
"Last signal: ", lastSig, (ShareToReceiver ? "\nCopy share: " + mStatus + " (" + (string)ArraySize(kTk) + " trade(s), ch " + Channel + ")" : ""));
OLComment(pt);
}
string OLBase()
{
string u = Trim(RelayURL);
while(StringLen(u)>0 && StringSubstr(u, StringLen(u)-1, 1)=="/") u = StringSubstr(u, 0, StringLen(u)-1);
return u;
}
// ---- Copy Master (merged) ----
ulong kTk[];
double kVol[], kSl[], kTp[];
bool mPrimed = false;
datetime mLastSnap = 0;
ulong mNextTry = 0;
string mStatus = "Starting...";
string mLastEv = "none yet";
bool MSymbolOK(const string s)
{
if(Trim(OnlySymbols)=="") return true;
string parts[];
int n = StringSplit(OnlySymbols, ',', parts);
for(int i=0;i<n;i++) if(Up(Trim(parts[i]))==Up(s)) return true;
return false;
}
int MFindKnown(const ulong t)
{
for(int i=0;i<ArraySize(kTk);i++) if(kTk[i]==t) return i;
return -1;
}
void MCommit(const int n, ulong &tk[], double &vol[], double &sl[], double &tp[])
{
ArrayResize(kTk,n); ArrayResize(kVol,n); ArrayResize(kSl,n); ArrayResize(kTp,n);
for(int i=0;i<n;i++){ kTk[i]=tk[i]; kVol[i]=vol[i]; kSl[i]=sl[i]; kTp[i]=tp[i]; }
}
bool MPost(const string body)
{
string url = OLBase() + "/copy/push?key=" + SecretKey + "&ch=" + Channel;
char data[], res[];
string rh;
StringToCharArray(body, data, 0, StringLen(body), CP_UTF8);
ResetLastError();
int code = WebRequest("POST", url, "Content-Type: text/plain\r\n", 5000, data, res, rh);
if(code==-1)
{
int e = GetLastError();
mStatus = (e==4014) ? "Add your Relay URL in Tools > Options > Expert Advisors > Allow WebRequest" : "Can't reach the relay (error " + (string)e + ")";
return false;
}
if(code==403) { mStatus = "Wrong secret key"; return false; }
if(code!=200) { mStatus = "Relay error " + (string)code; return false; }
mStatus = "Connected";
return true;
}
void MScan()
{
if(GetTickCount64() < mNextTry) return;
ulong cTk[]; double cVol[], cSl[], cTp[], cOp[]; string cSym[]; int cTy[];
int n = 0;
for(int i=0;i<PositionsTotal();i++)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(OnlyMagic>=0 && PositionGetInteger(POSITION_MAGIC)!=OnlyMagic) continue;
if(StringFind(PositionGetString(POSITION_COMMENT), "CP")==0 && PositionGetInteger(POSITION_MAGIC)==RMagic) continue; // never re-share copied trades (stops copy loops)
string s = PositionGetString(POSITION_SYMBOL);
if(!MSymbolOK(s)) continue;
ArrayResize(cTk,n+1); ArrayResize(cVol,n+1); ArrayResize(cSl,n+1); ArrayResize(cTp,n+1);
ArrayResize(cOp,n+1); ArrayResize(cSym,n+1); ArrayResize(cTy,n+1);
cTk[n]=t; cSym[n]=s; cTy[n]=(int)PositionGetInteger(POSITION_TYPE);
cVol[n]=PositionGetDouble(POSITION_VOLUME); cSl[n]=PositionGetDouble(POSITION_SL);
cTp[n]=PositionGetDouble(POSITION_TP); cOp[n]=PositionGetDouble(POSITION_PRICE_OPEN);
n++;
}
if(!mPrimed)
{
mPrimed = true;
if(!ShareExisting) { MCommit(n, cTk, cVol, cSl, cTp); return; }
}
string body = "";
int ev = 0;
for(int j=0;j<n;j++)
{
int k = MFindKnown(cTk[j]);
int dg = (int)SymbolInfoInteger(cSym[j], SYMBOL_DIGITS);
string tk = (string)cTk[j];
if(k<0)
{
body += "OPEN;" + tk + ";" + cSym[j] + ";" + (cTy[j]==POSITION_TYPE_BUY ? "BUY" : "SELL") + ";" + DoubleToString(cVol[j],4) + ";" +
DoubleToString(cSl[j],dg) + ";" + DoubleToString(cTp[j],dg) + ";" + DoubleToString(cOp[j],dg) + "\n";
ev++;
}
else
{
if(MathAbs(cSl[j]-kSl[k])>1e-9 || MathAbs(cTp[j]-kTp[k])>1e-9)
{ body += "MODIFY;" + tk + ";" + DoubleToString(cSl[j],dg) + ";" + DoubleToString(cTp[j],dg) + ";" + DoubleToString(cOp[j],dg) + "\n"; ev++; }
if(cVol[j] < kVol[k]-1e-9)
{ body += "REDUCE;" + tk + ";" + DoubleToString(kVol[k],4) + ";" + DoubleToString(cVol[j],4) + "\n"; ev++; }
}
}
for(int k=0;k<ArraySize(kTk);k++)
{
bool found = false;
for(int j=0;j<n;j++) if(cTk[j]==kTk[k]) { found = true; break; }
if(!found) { body += "CLOSE;" + (string)kTk[k] + "\n"; ev++; }
}
bool snapDue = (TimeLocal() - mLastSnap >= SnapshotSeconds);
if(ev==0 && !snapDue) return;
if(snapDue)
{
string list = "";
for(int j=0;j<n;j++) list += (j>0 ? "," : "") + (string)cTk[j];
body += "SNAP;" + list + "\n";
}
if(MPost(body))
{
MCommit(n, cTk, cVol, cSl, cTp);
if(snapDue) mLastSnap = TimeLocal();
if(ev>0) mLastEv = TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS) + " sent " + (string)ev + " update(s)";
}
else mNextTry = GetTickCount64() + 2000;
}
// ---- Copy Receiver (merged) ----
CTrade rTrade;
long rLastId = 0;
bool rNeedInit = false;
string rGv;
string rStatus = "Starting...";
string rLastEv = "none yet";
void RNote(const string m){ rLastEv = TimeToString(TimeLocal(), TIME_DATE|TIME_SECONDS) + " " + m; Print("Open Legacy Copy: ", m); }
string RListGet(const string list, const string key, const string def)
{
string parts[];
int n = StringSplit(list, ',', parts);
for(int i=0;i<n;i++)
{
string kv[];
if(StringSplit(parts[i], '=', kv)!=2) continue;
if(Up(Trim(kv[0]))==key) return Trim(kv[1]);
}
return def;
}
bool RAllowed(const string msym)
{
if(Trim(RAllowedSymbols)=="") return true;
string parts[];
int n = StringSplit(RAllowedSymbols, ',', parts);
for(int i=0;i<n;i++) if(Up(Trim(parts[i]))==Up(msym)) return true;
return false;
}
// Master symbol -> this broker's symbol (XAUUSD.s -> XAUUSD, US500 -> US500.cash, ...)
string RResolve(const string msym)
{
string mapped = RListGet(RSymbolMap, Up(msym), "");
if(mapped!="" && SymbolSelect(mapped, true)) return mapped;
if(SymbolSelect(msym, true)) return msym;
string bs = msym;
int d = StringFind(bs, ".");
if(d>0) bs = StringSubstr(bs, 0, d);
if(SymbolSelect(bs + RSymbolSuffix, true)) return bs + RSymbolSuffix;
if(SymbolSelect(bs, true)) return bs;
int total = SymbolsTotal(false);
for(int i=0;i<total;i++)
{
string s = SymbolName(i, false);
if(StringFind(Up(s), Up(bs))==0 && SymbolSelect(s, true)) return s;
}
return "";
}
double RLotsFor(const string sym, const double masterVol)
{
double v = (LotMode==LOT_FIXED) ? FixedLot : masterVol*LotMultiplier;
if(MaxLotPerTrade>0) v = MathMin(v, MaxLotPerTrade);
double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
double mn = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
double mx = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
if(step>0) v = MathFloor(v/step + 1e-9)*step;
if(v < mn) return 0; // too small for this broker -> skip, never round up
return NormalizeDouble(MathMin(v, mx), 8);
}
int RCountOpen()
{
int n = 0;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t!=0 && PositionGetInteger(POSITION_MAGIC)==RMagic) n++;
}
return n;
}
ulong RFindMirror(const ulong mt)
{
string cm = "CP" + (string)mt;
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0) continue;
if(PositionGetInteger(POSITION_MAGIC)!=RMagic) continue;
if(PositionGetString(POSITION_COMMENT)==cm) return t;
}
return 0;
}
void RCalcStops(const string sym, const bool buy, const double entry, const double mpr, const double msl, const double mtp, double &sl, double &tp)
{
int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double pnt = SymbolInfoDouble(sym, SYMBOL_POINT);
double ask = SymbolInfoDouble(sym, SYMBOL_ASK), bid = SymbolInfoDouble(sym, SYMBOL_BID);
double minD = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL)*pnt + (ask-bid);
sl = 0; tp = 0;
if(msl>0)
{
double r = SLTPFromEntry ? entry + (msl - mpr) : msl;
sl = NormalizeDouble(buy ? MathMin(r, bid-minD) : MathMax(r, ask+minD), dg);
}
if(mtp>0)
{
double r = SLTPFromEntry ? entry + (mtp - mpr) : mtp;
tp = NormalizeDouble(buy ? MathMax(r, ask+minD) : MathMin(r, bid-minD), dg);
}
}
void RDoOpen(const ulong mt, const string msym, const string side, const double mvol, const double msl, const double mtp, const double mpr, const long age)
{
bool buy = (side=="BUY");
if(age > MaxOpenAgeSec) { RNote("SKIPPED " + side + " " + msym + " - opened " + (string)age + "s ago"); return; }
if(RFindMirror(mt)!=0) return;
if(!RAllowed(msym)) { RNote("IGNORED " + side + " " + msym + " - not in RAllowedSymbols"); return; }
string sym = RResolve(msym);
if(sym=="") { RNote("IGNORED " + side + " " + msym + " - symbol not found here (use RSymbolMap)"); return; }
if(RMaxOpenTrades>0 && RCountOpen()>=RMaxOpenTrades) { RNote("IGNORED " + side + " " + sym + " - max trades reached"); return; }
double lots = RLotsFor(sym, mvol);
if(lots<=0) { RNote("IGNORED " + side + " " + sym + " - lot size too small for this broker"); return; }
double ask = SymbolInfoDouble(sym, SYMBOL_ASK), bid = SymbolInfoDouble(sym, SYMBOL_BID);
if(ask<=0 || bid<=0) { RNote("IGNORED " + side + " " + sym + " - no price yet"); return; }
double entry = buy ? ask : bid, margin = 0;
if(!OrderCalcMargin(buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, sym, lots, entry, margin) || margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
{ RNote("IGNORED " + side + " " + sym + " - not enough free margin"); return; }
double sl, tp;
RCalcStops(sym, buy, entry, mpr, msl, mtp, sl, tp);
string cm = "CP" + (string)mt;
bool ok = buy ? rTrade.Buy(lots, sym, 0, sl, tp, cm) : rTrade.Sell(lots, sym, 0, sl, tp, cm);
int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
if(ok) RNote("COPIED " + side + " " + sym + " " + DoubleToString(lots,2) + " lots SL " + DoubleToString(sl,dg) + " TP " + DoubleToString(tp,dg));
else RNote("FAILED " + side + " " + sym + ": " + rTrade.ResultRetcodeDescription());
}
void RDoModify(const ulong mt, const double msl, const double mtp, const double mop)
{
ulong t = RFindMirror(mt);
if(t==0 || !PositionSelectByTicket(t)) return;
string sym = PositionGetString(POSITION_SYMBOL);
bool buy = (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY);
double sl, tp;
RCalcStops(sym, buy, PositionGetDouble(POSITION_PRICE_OPEN), mop, msl, mtp, sl, tp);
double pnt = SymbolInfoDouble(sym, SYMBOL_POINT);
if(MathAbs(sl-PositionGetDouble(POSITION_SL))<pnt/2 && MathAbs(tp-PositionGetDouble(POSITION_TP))<pnt/2) return;
if(rTrade.PositionModify(t, sl, tp)) RNote("UPDATED SL/TP " + sym);
else RNote("FAILED SL/TP update " + sym + ": " + rTrade.ResultRetcodeDescription());
}
void RDoClose(const ulong mt)
{
ulong t = RFindMirror(mt);
if(t==0) return;
string sym = PositionSelectByTicket(t) ? PositionGetString(POSITION_SYMBOL) : "";
if(rTrade.PositionClose(t)) RNote("CLOSED " + sym + " (Master closed)");
else RNote("FAILED to close " + sym + ": " + rTrade.ResultRetcodeDescription());
}
void RDoReduce(const ulong mt, const double oldv, const double newv)
{
ulong t = RFindMirror(mt);
if(t==0 || oldv<=0 || !PositionSelectByTicket(t)) return;
string sym = PositionGetString(POSITION_SYMBOL);
double cur = PositionGetDouble(POSITION_VOLUME);
double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP), mn = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
double cv = cur*(oldv-newv)/oldv;
if(step>0) cv = MathFloor(cv/step + 1e-9)*step;
if(cv < mn) return;
bool ok = (cur-cv < mn) ? rTrade.PositionClose(t) : rTrade.PositionClosePartial(t, NormalizeDouble(cv,8));
if(ok) RNote("PARTIAL CLOSE " + sym);
else RNote("FAILED partial close " + sym + ": " + rTrade.ResultRetcodeDescription());
}
// Close copies whose Master rTrade is gone (only trusts a fresh Master snapshot, and ignores copies < 30s old)
void RSweep(const string list)
{
string ids[];
int n = StringSplit(list, ',', ids);
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0 || PositionGetInteger(POSITION_MAGIC)!=RMagic) continue;
string cm = PositionGetString(POSITION_COMMENT);
if(StringSubstr(cm,0,2)!="CP") continue;
string mt = StringSubstr(cm,2);
bool found = false;
for(int k=0;k<n;k++) if(ids[k]==mt) { found = true; break; }
if(found) continue;
if(TimeCurrent() - (datetime)PositionGetInteger(POSITION_TIME) < 30) continue;
string sym = PositionGetString(POSITION_SYMBOL);
if(rTrade.PositionClose(t)) RNote("CLOSED " + sym + " (Master no longer has it)");
}
}
void RPoll()
{
string url = OLBase() + "/copy/pull?key=" + SecretKey + "&ch=" + Channel + "&since=" + (string)rLastId;
char post[], res[];
string rh;
ResetLastError();
int code = WebRequest("GET", url, "", 5000, post, res, rh);
if(code==-1)
{
int e = GetLastError();
rStatus = (e==4014) ? "Add your Relay URL in Tools > Options > Expert Advisors > Allow WebRequest" : "Can't reach the relay (error " + (string)e + ")";
return;
}
if(code==403) { rStatus = "Wrong secret key"; return; }
if(code!=200) { rStatus = "Relay error " + (string)code; return; }
rStatus = "Connected";
string lines[];
int n = StringSplit(CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8), '\n', lines);
bool haveSnap = false; string snap = ""; long snapAge = 0;
for(int i=0;i<n;i++)
{
string line = Trim(lines[i]);
if(line=="") continue;
string f[];
int k = StringSplit(line, ';', f);
if(k<2) continue;
if(f[0]=="M")
{
long mx = StringToInteger(f[1]);
if(rNeedInit) { rLastId = mx; GlobalVariableSet(rGv, (double)rLastId); rNeedInit = false; return; } // first start: ignore history
if(mx < rLastId) { rLastId = 0; GlobalVariableSet(rGv, 0); }
continue;
}
if(f[0]=="S") { haveSnap = true; snapAge = StringToInteger(f[1]); snap = (k>=3) ? f[2] : ""; continue; }
if(k<3) continue;
long id = StringToInteger(f[0]);
long age = StringToInteger(f[1]);
string ty = f[2];
if(ty=="OPEN" && k>=10) RDoOpen((ulong)StringToInteger(f[3]), f[4], f[5], StringToDouble(f[6]), StringToDouble(f[7]), StringToDouble(f[8]), StringToDouble(f[9]), age);
else if(ty=="MODIFY" && k>=7) RDoModify((ulong)StringToInteger(f[3]), StringToDouble(f[4]), StringToDouble(f[5]), StringToDouble(f[6]));
else if(ty=="CLOSE" && k>=4) RDoClose((ulong)StringToInteger(f[3]));
else if(ty=="REDUCE" && k>=6) RDoReduce((ulong)StringToInteger(f[3]), StringToDouble(f[4]), StringToDouble(f[5]));
rLastId = id;
GlobalVariableSet(rGv, (double)rLastId);
}
if(SyncOrphans && haveSnap && snapAge<=60) RSweep(snap);
}
void RPanel()
{
string pt = "";
StringConcatenate(pt, "Open Legacy EA - Copy Receiver\n",
"Status: ", rStatus, "\n",
"Copied trades open: ", RCountOpen(), (RMaxOpenTrades>0 ? " / " + (string)RMaxOpenTrades : ""), " Channel: ", Channel, "\n",
"Last: ", rLastEv);
OLComment(pt);
}
int RInit()
{
if(StringLen(Trim(SecretKey))==0 || StringFind(RelayURL, "your-relay")>=0)
{ Alert("Open Legacy EA: fill in RelayURL and SecretKey."); return INIT_PARAMETERS_INCORRECT; }
if(AccountInfoInteger(ACCOUNT_MARGIN_MODE)!=ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
{ Alert("Open Legacy Copy Receiver needs a hedging account."); return INIT_FAILED; }
if(LotMode==LOT_MULTIPLIER && LotMultiplier<=0) { Alert("LotMultiplier must be above 0."); return INIT_PARAMETERS_INCORRECT; }
if(LotMode==LOT_FIXED && FixedLot<=0) { Alert("FixedLot must be above 0."); return INIT_PARAMETERS_INCORRECT; }
rTrade.SetExpertMagicNumber(RMagic);
rTrade.SetDeviationInPoints(SlippagePoints);
rGv = "OLCP_" + (string)AccountInfoInteger(ACCOUNT_LOGIN) + "_" + Channel;
if(GlobalVariableCheck(rGv)) rLastId = (long)GlobalVariableGet(rGv); else { rLastId = 0; rNeedInit = true; }
EventSetMillisecondTimer(MathMax(250, PollMs));
RPanel();
return INIT_SUCCEEDED;
}
// ---- info panel drawn as labels so it stays visible above the splash ----
#define OL_PNL "OLEA_P"
#define OL_PBG "OLEA_PanelBG"
int olPanelN = 0, pbW = 0, pbH = 0;
// rounded dark box behind the info text (same look as the splash card)
void OLPanelBG(const int W, const int H)
{
uint px[];
ArrayResize(px, W*H);
ArrayInitialize(px, 0);
double rad = 12.0, hx = W/2.0 - 1.0, hy = H/2.0 - 1.0;
for(int y=0; y<H; y++)
for(int x=0; x<W; x++)
{
double qx = MathAbs(x+0.5-W/2.0) - (hx-rad), qy = MathAbs(y+0.5-H/2.0) - (hy-rad);
double ox = MathMax(qx,0.0), oy = MathMax(qy,0.0);
double d = MathSqrt(ox*ox+oy*oy) + MathMin(MathMax(qx,qy),0.0) - rad;
double c = SPClamp(0.5-d);
if(c<=0) continue;
uint fill = SPMix(0x0F1626, 0x060910, (double)y/H);
px[y*W+x] = SPBlend(0, fill, c*0.9);
double ring = c - SPClamp(0.5-(d+1.6));
if(ring>0) px[y*W+x] = SPBlend(px[y*W+x], 0x2FD480, ring*0.6);
}
if(!ResourceCreate("olpanelbg", px, W, H, 0, 0, W, COLOR_FORMAT_ARGB_NORMALIZE)) return;
ObjectDelete(0, OL_PBG);
if(!ObjectCreate(0, OL_PBG, OBJ_BITMAP_LABEL, 0, 0, 0)) return;
ObjectSetString(0, OL_PBG, OBJPROP_BMPFILE, "::olpanelbg");
ObjectSetInteger(0, OL_PBG, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, OL_PBG, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
ObjectSetInteger(0, OL_PBG, OBJPROP_XDISTANCE, 6);
ObjectSetInteger(0, OL_PBG, OBJPROP_YDISTANCE, 16);
ObjectSetInteger(0, OL_PBG, OBJPROP_BACK, false);
ObjectSetInteger(0, OL_PBG, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, OL_PBG, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, OL_PBG, OBJPROP_ZORDER, 0);
}
void OLPanelClear()
{
for(int i=0;i<olPanelN;i++) ObjectDelete(0, OL_PNL + (string)i);
ObjectDelete(0, OL_PBG);
olPanelN = 0; pbW = 0; pbH = 0;
}
void OLComment(const string txt)
{
string raw[], ln[];
int rn = StringSplit(txt, '\n', raw);
if(rn<=0 || StringLen(txt)==0) { OLPanelClear(); return; }
int n = 0;
ArrayResize(ln, 16);
for(int r=0; r<rn && n<14; r++)
{
string t = raw[r];
while(StringLen(t)>52 && n<14)
{
int cut = 52;
for(int c=52; c>20; c--) if(StringGetCharacter(t, c)==' ') { cut = c; break; }
ln[n++] = StringSubstr(t, 0, cut);
t = " " + StringSubstr(t, cut);
StringTrimRight(t);
}
if(n<14) ln[n++] = t;
}
int mx = 0;
for(int i=0;i<n;i++) mx = MathMax(mx, StringLen(ln[i]));
int bw = (int)(mx*9.3) + 32, bh = n*19 + 16;
if(bw!=pbW || bh!=pbH || ObjectFind(0, OL_PBG)<0)
{
OLPanelClear(); // rebuild box first, then labels on top of it
OLPanelBG(bw, bh);
pbW = bw; pbH = bh;
}
for(int i=0;i<n;i++)
{
string nm = OL_PNL + (string)i;
if(ObjectFind(0, nm)<0)
{
ObjectCreate(0, nm, OBJ_LABEL, 0, 0, 0);
ObjectSetInteger(0, nm, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, nm, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
ObjectSetInteger(0, nm, OBJPROP_XDISTANCE, 12);
ObjectSetInteger(0, nm, OBJPROP_YDISTANCE, 24 + i*19);
ObjectSetString(0, nm, OBJPROP_FONT, "Consolas");
ObjectSetInteger(0, nm, OBJPROP_FONTSIZE, 10);
ObjectSetInteger(0, nm, OBJPROP_COLOR, (i==0) ? 0x80D42F : 0xF5EBE0);
ObjectSetInteger(0, nm, OBJPROP_SELECTABLE, false);
ObjectSetInteger(0, nm, OBJPROP_HIDDEN, true);
ObjectSetInteger(0, nm, OBJPROP_BACK, false);
ObjectSetInteger(0, nm, OBJPROP_ZORDER, 0);
}
ObjectSetString(0, nm, OBJPROP_TEXT, ln[i]);
}
for(int i=n;i<olPanelN;i++) ObjectDelete(0, OL_PNL + (string)i);
olPanelN = n;
}
// ================= Open Legacy splash screen (drawn in code, no image files) =================
#define OL_SPL "OLEA_Splash"
#define OL_VER "1.84"
datetime splEnd = 0;
bool splOn = false;
double SPClamp(const double v){ return v<0 ? 0 : (v>1 ? 1 : v); }
uint SPBlend(const uint dst, const uint col, double sa)
{
if(sa<=0) return dst;
if(sa>1) sa = 1;
double da = ((dst>>24)&255)/255.0;
double oa = sa + da*(1.0-sa);
if(oa<=0) return dst;
double k = da*(1.0-sa);
uint r = (uint)((((col>>16)&255)*sa + ((dst>>16)&255)*k)/oa + 0.5);
uint g = (uint)((((col>>8)&255)*sa + ((dst>>8)&255)*k)/oa + 0.5);
uint b = (uint)(((col&255)*sa + (dst&255)*k)/oa + 0.5);
uint a = (uint)(oa*255.0 + 0.5);
return (a<<24)|(r<<16)|(g<<8)|b;
}
uint SPMix(const uint c1, const uint c2, double t)
{
t = SPClamp(t);
uint r = (uint)(((c1>>16)&255)*(1-t) + ((c2>>16)&255)*t + 0.5);
uint g = (uint)(((c1>>8)&255)*(1-t) + ((c2>>8)&255)*t + 0.5);
uint b = (uint)((c1&255)*(1-t) + (c2&255)*t + 0.5);
return (r<<16)|(g<<8)|b;
}
// diamond (rotated square); ringW <= 0 = filled, otherwise an outline of that width
void SPDiamond(uint &px[], const int W, const int H, const double cx, const double cy, const double r, const uint col, const double alpha, const double ringW)
{
int x0 = (int)MathMax(0, cx-r-3), x1 = (int)MathMin(W-1, cx+r+3);
int y0 = (int)MathMax(0, cy-r-3), y1 = (int)MathMin(H-1, cy+r+3);
for(int y=y0; y<=y1; y++)
for(int x=x0; x<=x1; x++)
{
double d = MathAbs(x+0.5-cx) + MathAbs(y+0.5-cy);
double c = SPClamp((r-d)/1.4142 + 0.5);
if(ringW>0) c -= SPClamp((r-ringW*1.4142-d)/1.4142 + 0.5);
if(c>0) px[y*W+x] = SPBlend(px[y*W+x], col, c*alpha);
}
}
void SPGlow(uint &px[], const int W, const int H, const double cx, const double cy, const double r, const double reach, const uint col, const double alpha)
{
int x0 = (int)MathMax(0, cx-r-reach-2), x1 = (int)MathMin(W-1, cx+r+reach+2);
int y0 = (int)MathMax(0, cy-r-reach-2), y1 = (int)MathMin(H-1, cy+r+reach+2);
for(int y=y0; y<=y1; y++)
for(int x=x0; x<=x1; x++)
{
double d = MathAbs(x+0.5-cx) + MathAbs(y+0.5-cy);
if(d<=r) continue;
double g = 1.0 - (d-r)/reach;
if(g>0) px[y*W+x] = SPBlend(px[y*W+x], col, g*g*alpha);
}
}
void SPRoundCard(uint &px[], const int W, const int H)
{
double a = MathMax(40, MathMin(100, SplashOpacity))/100.0;
double rad = 26.0, hx = W/2.0 - 1.0, hy = H/2.0 - 1.0;
for(int y=0; y<H; y++)
for(int x=0; x<W; x++)
{
double qx = MathAbs(x+0.5-W/2.0) - (hx-rad), qy = MathAbs(y+0.5-H/2.0) - (hy-rad);
double ox = MathMax(qx,0.0), oy = MathMax(qy,0.0);
double d = MathSqrt(ox*ox+oy*oy) + MathMin(MathMax(qx,qy),0.0) - rad;
double c = SPClamp(0.5-d);
if(c<=0) continue;
uint fill = SPMix(0x0F1626, 0x060910, (double)y/H);
px[y*W+x] = SPBlend(0, fill, c*a);
double ring = c - SPClamp(0.5-(d+1.8));
if(ring>0) px[y*W+x] = SPBlend(px[y*W+x], 0x2FD480, ring*0.6);
}
}
void SPText(uint &px[], const int W, const int H, const string txt, const int cx, const int y, const uint rgb)
{
TextOut(txt, cx, y, TA_CENTER|TA_TOP, px, W, H, ColorToARGB((color)(((rgb&255)<<16)|(rgb&0xFF00)|((rgb>>16)&255)), 255), COLOR_FORMAT_ARGB_NORMALIZE);
}
void SplashRemove()
{
if(!splOn) return;
ObjectDelete(0, OL_SPL);
ResourceFree("::olsplash");
splOn = false; splEnd = 0;
ChartRedraw();
}
void SplashShow()
{
if(!ShowSplash) return;
const int W = 540, H = 372;
uint px[];
ArrayResize(px, W*H);
ArrayInitialize(px, 0);
SPRoundCard(px, W, H);
// logo: same diamonds as the site preload screen
double cx = W/2.0, cy = 104.0, s = 1.35;
SPGlow(px, W, H, cx, cy, 40*s, 28, 0x2FD480, 0.22);
SPDiamond(px, W, H, cx, cy, 40*s, 0x2FD480, 0.92, 2.5*s);
SPDiamond(px, W, H, cx, cy, 20*s, 0x0E1420, 1.0, 0);
SPDiamond(px, W, H, cx, cy, 20*s, 0xF5B942, 1.0, 2.5*s);
SPDiamond(px, W, H, cx, cy, 13*s, 0xF5B942, 0.22, 0);
// title, white -> amber -> green like the site
string title = "Open Legacy";
TextSetFont("Segoe UI", 52, FW_BOLD);
uint tw=0, th=0;
TextGetSize(title, tw, th);
int sx = (W - (int)tw)/2, n = StringLen(title);
for(int i=0; i<n; i++)
{
uint pw=0, ph=0;
if(i>0) TextGetSize(StringSubstr(title, 0, i), pw, ph);
double t = (n>1) ? (double)i/(n-1) : 0;
uint rgb = (t<0.6) ? SPMix(0xF4F7FB, 0xF5B942, t/0.6) : SPMix(0xF5B942, 0x2FD480, (t-0.6)/0.4);
uint argb = ColorToARGB((color)(((rgb&255)<<16)|(rgb&0xFF00)|((rgb>>16)&255)), 255);
TextOut(StringSubstr(title, i, 1), sx+(int)pw, 172, TA_LEFT|TA_TOP, px, W, H, argb, COLOR_FORMAT_ARGB_NORMALIZE);
}
TextSetFont("Consolas", 17, FW_NORMAL);
SPText(px, W, H, "making trader's dreams into reality", W/2, 250, 0x9AA7BA);
for(int x=70; x<W-70; x++) px[300*W+x] = SPBlend(px[300*W+x], 0x2FD480, 0.30);
TextSetFont("Segoe UI", 14, FW_NORMAL);
string role = (Role==ROLE_RECEIVER) ? "Copy Receiver" : (ShareToReceiver ? "Trader + Copy Master" : "Trader");
SPText(px, W, H, "All-in-One EA v" + OL_VER + " | " + role, W/2, 316, 0x7C8AA0);
if(!ResourceCreate("olsplash", px, W, H, 0, 0, W, COLOR_FORMAT_ARGB_NORMALIZE)) return;
ObjectDelete(0, OL_SPL);
if(!ObjectCreate(0, OL_SPL, OBJ_BITMAP_LABEL, 0, 0, 0)) return;
ObjectSetString(0, OL_SPL, OBJPROP_BMPFILE, "::olsplash");
ObjectSetInteger(0, OL_SPL, OBJPROP_CORNER, CORNER_LEFT_UPPER);
ObjectSetInteger(0, OL_SPL, OBJPROP_ANCHOR, ANCHOR_CENTER);
ObjectSetInteger(0, OL_SPL, OBJPROP_XDISTANCE, (int)(ChartGetInteger(0, CHART_WIDTH_IN_PIXELS)/2));
ObjectSetInteger(0, OL_SPL, OBJPROP_YDISTANCE, (int)(ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS)/2));
ObjectSetInteger(0, OL_SPL, OBJPROP_BACK, false);
ObjectSetInteger(0, OL_SPL, OBJPROP_SELECTABLE, !SplashStay);
ObjectSetInteger(0, OL_SPL, OBJPROP_SELECTED, false);
ObjectSetInteger(0, OL_SPL, OBJPROP_ZORDER, 100);
splOn = true;
splEnd = (SplashSeconds>0 && !SplashStay) ? TimeLocal() + SplashSeconds : 0;
OLPanelClear(); // info panel labels are re-created on top of the splash
ChartRedraw();
}
void SplashTick()
{
if(splOn && splEnd>0 && TimeLocal()>=splEnd) SplashRemove();
}
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
if(!splOn) return;
if(id==CHARTEVENT_OBJECT_CLICK && sparam==OL_SPL && !SplashStay) SplashRemove();
else if(id==CHARTEVENT_CHART_CHANGE)
{
ObjectSetInteger(0, OL_SPL, OBJPROP_XDISTANCE, (int)(ChartGetInteger(0, CHART_WIDTH_IN_PIXELS)/2));
ObjectSetInteger(0, OL_SPL, OBJPROP_YDISTANCE, (int)(ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS)/2));
}
}
int OnInit()
{
if(Role==ROLE_RECEIVER) { int rr = RInit(); if(rr==INIT_SUCCEEDED) { SplashShow(); RPanel(); } return rr; }
if(ShareToReceiver && AccountInfoInteger(ACCOUNT_MARGIN_MODE)!=ACCOUNT_MARGIN_MODE_RETAIL_HEDGING) Print("Open Legacy EA: sharing by position ticket works best on hedging accounts.");
if(StringLen(Trim(SecretKey))==0 || StringFind(RelayURL, "your-relay")>=0)
{ Alert("Open Legacy All-in-One EA: fill in RelayURL and SecretKey in the settings."); return INIT_PARAMETERS_INCORRECT; }
if(MaxOpenTrades<1) { Alert("Open Legacy All-in-One EA: MaxOpenTrades must be 1 or more."); return INIT_PARAMETERS_INCORRECT; }
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)) Print("Open Legacy Webhook: AutoTrading is OFF - turn it on to place trades.");
trade.SetExpertMagicNumber(MagicNumber);
trade.SetDeviationInPoints(SlippagePoints);
gvName = "OLWH_" + (string)AccountInfoInteger(ACCOUNT_LOGIN);
lastId = GlobalVariableCheck(gvName) ? (long)GlobalVariableGet(gvName) : 0;
if(UseAutoSLTP && !AParse()) { Alert("Open Legacy EA: check AutoRules, e.g. XAUUSD=60/40, NAS100=1400/1000"); return INIT_PARAMETERS_INCORRECT; }
EventSetMillisecondTimer(ShareToReceiver ? MathMax(100, ScanMs) : MathMax(1, PollSeconds)*1000);
Panel();
SplashShow();
Panel();
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason){ EventKillTimer(); OLPanelClear(); Comment(""); SplashRemove(); }
void OnTimer()
{
SplashTick();
if(Role==ROLE_RECEIVER) { RPoll(); RPanel(); return; }
if(ShareToReceiver) MScan();
if(GetTickCount64() >= nextWh)
{
nextWh = GetTickCount64() + (ulong)MathMax(1, PollSeconds)*1000;
FFLoad(); CloseForNews(); Poll(); ProcessQueue(); if(UseAutoSLTP) AutoApply(); Panel();
}
}
void OnTick(){ if(Role==ROLE_TRADER && UseAutoSLTP) AutoApply(); }
void OnTradeTransaction(const MqlTradeTransaction &tr, const MqlTradeRequest &rq, const MqlTradeResult &rs){ if(Role==ROLE_TRADER && UseAutoSLTP) AutoApply(); }
โก MT5 toolAuto SL / TP โ Tap Buy, Targets Setโผ
Open a trade from the MT5 phone app and your Stop Loss and Take Profit appear by themselves, within a second โ fixed to whatever you set for each pair. No typing levels on a tiny screen, no forgetting a stop.
You tap Buy or Sell
In the MT5 app, on any pair in your list.
The EA spots it
Running 24/7 on a MetaQuotes VPS โ your computer can be off.
SL & TP are set
Your fixed levels, measured from your entry price.
The only setting that matters: Rules
List each pair as PAIR = SL / TP in pips, separated by commas:
Red = Stop Loss ยท green = Take Profit. Add as many pairs as you like. Use the plain name โ XAUUSD also matches your broker's XAUUSD.s.
One-time setup (about 10 minutes)
You need desktop MT5 once, to install the EA and send it to the VPS. After that, everything runs without your computer.
Add the EA to MT5
In desktop MT5: File โ Open Data Folder โ MQL5 โ Experts, and save the file below there (download it, or copy the code into a new file named OpenLegacy_AutoSLTP.mq5).
Compile it
Press F4 (or Fn + F4 on laptops) from MT5 to open MetaEditor, open the file, and click Compile. The bottom panel should say 0 errors.
Attach it to one chart
Back in MT5, right-click Expert Advisors โ Refresh in the Navigator, then drag OpenLegacy_AutoSLTP onto any chart. Tick Allow Algo Trading, type your Rules in the Inputs tab, and click OK. The chart shows โOpen Legacy Auto SL/TP โ runningโ.
Rent the MetaQuotes VPS
In the Navigator, right-click your account number โ Register a virtual server. Pick the server with the lowest ping and the basic plan (around $15 a month).
Migrate
Choose Migrate experts and click Migrate. Wait for Last migration to show a time. You can now close MT5 and switch the computer off.
Test it
Open a small trade from the MT5 phone app. Within a second, SL and TP appear on it.
//+------------------------------------------------------------------+
//| Open Legacy Auto SL/TP |
//| Adds your fixed SL and TP to every new trade โ including trades |
//| opened from the MT5 phone app. Run it on one chart in MT5 on a |
//| VPS or a computer that stays on. |
//+------------------------------------------------------------------+
#property copyright "Open Legacy"
#property version "1.00"
#include <Trade\Trade.mqh>
input string Rules = "XAUUSD=60/40, NAS100=1400/1000"; // Pair=SL/TP in pips, comma separated
input int PointsPerPip = 10; // 10 for gold, indices, BTC and 5-decimal FX
input bool ManualTradesOnly = true; // Only touch trades you open yourself (app/manual)
CTrade trade;
string rSym[];
double rSl[];
double rTp[];
ulong doneT[];
ulong tryT[];
int tryN[];
bool IsDone(ulong t){ for(int i=0;i<ArraySize(doneT);i++) if(doneT[i]==t) return true; return false; }
void MarkDone(ulong t){ int n=ArraySize(doneT); ArrayResize(doneT,n+1); doneT[n]=t; }
int Tries(ulong t){ for(int i=0;i<ArraySize(tryT);i++) if(tryT[i]==t) return ++tryN[i]; int n=ArraySize(tryT); ArrayResize(tryT,n+1); ArrayResize(tryN,n+1); tryT[n]=t; tryN[n]=1; return 1; }
bool ParseRules()
{
ArrayResize(rSym,0); ArrayResize(rSl,0); ArrayResize(rTp,0);
string parts[];
int n = StringSplit(Rules, ',', parts);
for(int i=0;i<n;i++)
{
string p = parts[i];
StringTrimLeft(p); StringTrimRight(p);
if(StringLen(p)==0) continue;
string kv[];
if(StringSplit(p, '=', kv)!=2) { Print("Open Legacy Auto SL/TP: can't read rule '", p, "' (use PAIR=SL/TP)"); return false; }
string key = kv[0]; StringTrimLeft(key); StringTrimRight(key); StringToUpper(key);
string v[];
if(StringSplit(kv[1], '/', v)!=2) { Print("Open Legacy Auto SL/TP: can't read '", p, "' (use PAIR=SL/TP)"); return false; }
int k = ArraySize(rSym);
ArrayResize(rSym,k+1); ArrayResize(rSl,k+1); ArrayResize(rTp,k+1);
rSym[k] = key; rSl[k] = StringToDouble(v[0]); rTp[k] = StringToDouble(v[1]);
}
return ArraySize(rSym) > 0;
}
// Matches "XAUUSD" to XAUUSD, XAUUSD.s, XAUUSDm etc.
int FindRule(string sym)
{
string s = sym; StringToUpper(s);
for(int i=0;i<ArraySize(rSym);i++) if(StringFind(s, rSym[i])==0) return i;
return -1;
}
void Apply()
{
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong t = PositionGetTicket(i);
if(t==0 || IsDone(t)) continue;
if(ManualTradesOnly && PositionGetInteger(POSITION_MAGIC)!=0) { MarkDone(t); continue; }
string sym = PositionGetString(POSITION_SYMBOL);
int r = FindRule(sym);
if(r<0) { MarkDone(t); continue; }
double curSl = PositionGetDouble(POSITION_SL), curTp = PositionGetDouble(POSITION_TP);
if(curSl!=0.0 && curTp!=0.0) { MarkDone(t); continue; } // already has both: leave it
bool buy = PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY;
double open = PositionGetDouble(POSITION_PRICE_OPEN);
double pt = SymbolInfoDouble(sym, SYMBOL_POINT);
int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double dSl = rSl[r] * PointsPerPip * pt;
double dTp = rTp[r] * PointsPerPip * pt;
double sl = curSl!=0.0 ? curSl : (rSl[r]>0 ? (buy ? open-dSl : open+dSl) : 0.0);
double tp = curTp!=0.0 ? curTp : (rTp[r]>0 ? (buy ? open+dTp : open-dTp) : 0.0);
// keep levels outside the broker's minimum distance
double minD = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * pt;
double bid = SymbolInfoDouble(sym, SYMBOL_BID), ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double ref = buy ? bid : ask;
if(sl!=0.0) sl = buy ? MathMin(sl, ref-minD) : MathMax(sl, ref+minD);
if(tp!=0.0) tp = buy ? MathMax(tp, ref+minD) : MathMin(tp, ref-minD);
sl = NormalizeDouble(sl, dg); tp = NormalizeDouble(tp, dg);
if(trade.PositionModify(t, sl, tp))
{
MarkDone(t);
PrintFormat("Open Legacy Auto SL/TP: %s #%I64u SL %s TP %s", sym, t, DoubleToString(sl,dg), DoubleToString(tp,dg));
}
else if(Tries(t)>=10)
{
MarkDone(t);
PrintFormat("Open Legacy Auto SL/TP: gave up on #%I64u (%s): %s", t, sym, trade.ResultRetcodeDescription());
}
}
}
int OnInit()
{
if(!ParseRules()) { Alert("Open Legacy Auto SL/TP: check the Rules setting, e.g. XAUUSD=60/40, NAS100=1400/1000"); return INIT_PARAMETERS_INCORRECT; }
string txt = "Open Legacy Auto SL/TP โ
running\n";
for(int i=0;i<ArraySize(rSym);i++) txt += StringFormat("%s SL %.1f / TP %.1f pips\n", rSym[i], rSl[i], rTp[i]);
Comment(txt);
EventSetMillisecondTimer(500);
Apply();
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason){ EventKillTimer(); Comment(""); }
void OnTimer(){ Apply(); }
void OnTick(){ Apply(); }
void OnTradeTransaction(const MqlTradeTransaction &tr, const MqlTradeRequest &rq, const MqlTradeResult &rs){ Apply(); }
Copy & pasteGet the Scriptsโผ
Full Pine Script v6 source for each. Copy each into its own Pine Editor tab as described in How to Install.
//@version=6
indicator("Open Legacy Official", overlay = true)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// OPEN LEGACY โ manual signals with a live HUD.
// Two strategies, one Sensitivity dial, optional trading
// sessions, and fixed TP / SL levels for every signal.
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโ 1. STRATEGY โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G1 = "1. Strategy"
entryMethod = input.string("FVG Pullback", "Entry Method", options = ["FVG Pullback", "EMA Trend"], group = G1,
tooltip = "FVG Pullback โ price leaves a fair value gap (a candle so fast it leaves an untouched gap), then a signal fires when price pulls back into the gap and turns.\n\nEMA Trend โ signals at the start of a new trend leg: fast EMA above slow EMA, price above the fast EMA and RSI above 50 (the reverse for sells).")
sensitivity = input.string("Conservative", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G1,
tooltip = "Aggressive โ the most signals, any timeframe.\n\nBalanced โ only signals that agree with the 50 EMA trend.\n\nConservative โ also needs the trend on a timeframe 4x your chart to agree, and real trend strength (ADX 20+). The fewest signals, the highest quality.")
// โโ 2. TARGETS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G2 = "2. Targets"
slPips = input.float(60, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G2)
tpPips = input.float(40, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G2,
tooltip = "Keep Take Profit larger than Stop Loss.")
pipPoints = input.int(10, "Points Per Pip", minval = 1, group = G2,
tooltip = "10 for gold, indices, BTC and 5-decimal FX.")
lotSize = input.float(0.08, "Lot Size (MT5 Auto-Trade)", minval = 0.01, step = 0.01, group = G2,
tooltip = "Only used by the MT5 Auto-Trade robot. Set it separately on each pair's chart. After changing it, open your alert and tap Save so the alert picks up the new size.")
// โโ 3. FILTERS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G4 = "3. Filters"
hoursOn = input.bool(true, "Session 1", group = G4, inline = "h1",
tooltip = "Up to 8 sessions. Tick a session, pick its start and end time (overnight works, e.g. 22:00-02:00) and its days (your Timezone below). Each session has its own days, e.g. Session 1 Mon-Fri 07:00-12:00 and Session 2 Thu-Fri 14:00-18:00. Leave all unticked to trade any time.")
hoursWin = input.session("0130-0400", "", group = G4, inline = "h1")
hoursDays = input.string("Tue-Thu", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h1")
hours2On = input.bool(true, "Session 2", group = G4, inline = "h2")
hoursWin2 = input.session("0430-0630", "", group = G4, inline = "h2")
hoursDays2 = input.string("Mon-Wed", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h2")
hours3On = input.bool(true, "Session 3", group = G4, inline = "h3")
hoursWin3 = input.session("0330-0600", "", group = G4, inline = "h3")
hoursDays3 = input.string("Fri", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h3")
hours4On = input.bool(true, "Session 4", group = G4, inline = "h4")
hoursWin4 = input.session("0800-1130", "", group = G4, inline = "h4")
hoursDays4 = input.string("Mon-Fri", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h4")
hours5On = input.bool(true, "Session 5", group = G4, inline = "h5")
hoursWin5 = input.session("1230-1430", "", group = G4, inline = "h5")
hoursDays5 = input.string("Mon-Wed", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h5")
hours6On = input.bool(true, "Session 6", group = G4, inline = "h6")
hoursWin6 = input.session("1200-1700", "", group = G4, inline = "h6")
hoursDays6 = input.string("Fri", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h6")
hours7On = input.bool(true, "Session 7", group = G4, inline = "h7")
hoursWin7 = input.session("1630-2300", "", group = G4, inline = "h7")
hoursDays7 = input.string("Tue", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h7")
hours8On = input.bool(true, "Session 8", group = G4, inline = "h8")
hoursWin8 = input.session("1830-2030", "", group = G4, inline = "h8")
hoursDays8 = input.string("Wed-Thu", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h8")
// โโ 4. DISPLAY โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G3 = "4. Display"
buyColor = input.color(#4CAF50, "BUY", group = G3, inline = "c")
sellColor = input.color(#FF5252, "SELL", group = G3, inline = "c")
hudPos = input.string("Top Right", "HUD Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G3)
sessionTz = input.string("Europe/Dublin", "Timezone", group = G3,
tooltip = "Your timezone, IANA format (e.g. Europe/Dublin, America/New_York). Used for Trading Hours and the market-closed status.")
replayMode = input.bool(false, "Bar Replay Mode", group = G3,
tooltip = "Turn on while using Bar Replay so the HUD keeps updating.")
//โโ Internal constants โโ
useExchangeTz = false
useCorrFilter = true
buyBgColor = buyColor
buyTextColor = color.white
sellBgColor = sellColor
sellTextColor = color.white
corrEmaLen = 9
corrConfBars = 3
gracePeriodBars = 6
maxRampBars = 12
getTablePosition(string pos) =>
switch pos
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.bottom_right
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ UNIVERSAL HANDS-FREE BENCHMARK ROUTER
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Returns [benchmarkSymbol, isInverseRelationship]
// isInverseRelationship = true -> benchmark moving UP pushes asset toward SL if asset is a BUY
// (i.e. benchmark should move OPPOSITE the asset to favor TP)
// isInverseRelationship = false -> benchmark should move WITH the asset to favor TP
getUniversalInverseBenchmark() =>
string p = syminfo.prefix
string t = str.upper(syminfo.ticker)
string base = syminfo.basecurrency
string quote = syminfo.currency
string symbol = "TVC:DXY"
bool inverse = true
if t == "USDX" or t == "DXY" or t == "USDOLLAR" or t == "DX"
symbol := "TVC:GOLD"
inverse := true
else if p == "NSE" or p == "BSE" or quote == "INR"
symbol := "NSE:INDIAVIX"
inverse := true
else if str.contains(t, "SPX") or str.contains(t, "US500") or str.contains(t, "SP500") or str.contains(t, "NDX") or str.contains(t, "US100") or str.contains(t, "NAS100") or str.contains(t, "US30") or str.contains(t, "DJI") or str.contains(t, "GER") or str.contains(t, "DAX") or str.contains(t, "UK100") or str.contains(t, "EU50") or p == "NASDAQ" or p == "NYSE"
symbol := "TVC:VIX"
inverse := true
else if base == "USD"
if quote == "JPY"
symbol := "TVC:JXY"
inverse := true
else if quote == "CAD"
symbol := "TVC:CXY"
inverse := true
else if quote == "CHF"
symbol := "TVC:SXY"
inverse := true
else
// USD is the BASE here (USDSEK, USDMXN, USDZAR, USDTRY, USDHKD, etc.)
// DXY moves WITH these pairs, not against them โ DIRECT correlation
symbol := "TVC:DXY"
inverse := false
else if quote == "USD"
symbol := "TVC:DXY"
inverse := true
else if quote == "JPY"
symbol := "TVC:JXY"
inverse := true
else if quote == "GBP"
symbol := "TVC:BXY"
inverse := true
else if quote == "EUR"
symbol := "TVC:EXY"
inverse := true
[symbol, inverse]
getBenchmarkDisplayName(string symbol) =>
switch symbol
"NSE:INDIAVIX" => "India VIX"
"TVC:VIX" => "VIX"
"TVC:DXY" => "DXY"
"TVC:GOLD" => "Gold"
"TVC:JXY" => "Yen Index"
"TVC:BXY" => "Pound Index"
"TVC:EXY" => "Euro Index"
"TVC:CXY" => "CAD Index"
"TVC:SXY" => "CHF Index"
=> symbol
[routedBenchSymbol, routedBenchInverse] = getUniversalInverseBenchmark()
string activeBenchSymbol = routedBenchSymbol
bool activeBenchInverse = routedBenchInverse
string activeBenchName = getBenchmarkDisplayName(activeBenchSymbol)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ MARKET-CLOSE DETECTOR โ scheduled weekly close OR unscheduled outage
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
bool isCrypto = syminfo.type == "crypto" or str.contains(syminfo.ticker, "BTC") or str.contains(syminfo.ticker, "ETH")
// Scheduled weekly close, evaluated against the REAL current clock (timenow) in
// the chosen timezone. DST is handled automatically via IANA tz names.
// โข Mon-Fri: closed 22:00-22:59 local (daily break), reopens 23:00
// โข Fri 22:00 onward through all of Sat through Sun 22:59: weekend closed
// โข Reopens Sunday 23:00 local
f_isScheduledClose(string tz) =>
int dow = dayofweek(timenow, tz) // Pine: 1 = Sunday ... 7 = Saturday
int hr = hour(timenow, tz)
bool weekdayBreak = (dow >= 2 and dow <= 6) and (hr == 22)
bool weekendClosed = (dow == 6 and hr >= 22) or (dow == 7) or (dow == 1 and hr < 23)
weekdayBreak or weekendClosed
bool scheduledClosedNow = f_isScheduledClose(useExchangeTz ? syminfo.timezone : sessionTz)
// Live "no fresh data" detector โ catches an UNSCHEDULED outage or maintenance
// break of any length (not a fixed window): as long as no new bar has printed
// for 15+ minutes on a genuinely live last bar, it stays flagged closed for
// however long that gap continues, and clears the moment fresh data resumes.
// Only ever evaluated on barstate.isrealtime, so historical/replay bars never
// trigger this regardless of how old their timestamps are.
bool dataStaleNow = barstate.isrealtime and barstate.islast and (timenow - time_close > 900000)
// DXY/forex benchmark closes on the standard schedule even when crypto itself
// keeps trading โ bypass the correlation filter during that window.
bool isCryptoDxyOffline = not replayMode and isCrypto and scheduledClosedNow
// Main HUD "market closed" status:
// โข non-crypto: closed if EITHER the scheduled weekly window applies OR the
// feed has genuinely gone stale (unscheduled maintenance/outage)
// โข crypto: trades 24/7, so the fixed weekly schedule doesn't apply to the
// asset itself โ only genuine exchange downtime (stale feed) marks it closed
bool isMarketClosedRT = not replayMode and (dataStaleNow or (not isCrypto and scheduledClosedNow))
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ SIGNAL ENGINE
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Sensitivity presets (literal values keep lengths "simple" for ta.* calls)
fvgLife = sensitivity == "Aggressive" ? 12 : sensitivity == "Balanced" ? 24 : 40
fvgMin = sensitivity == "Aggressive" ? 0.10 : sensitivity == "Balanced" ? 0.25 : 0.40
emaFastL = sensitivity == "Aggressive" ? 8 : sensitivity == "Balanced" ? 13 : 21
emaSlowL = sensitivity == "Aggressive" ? 21 : sensitivity == "Balanced" ? 34 : 55
atrV = ta.atr(14)
ema50 = ta.ema(close, 50)
[diP, diM, adxV] = ta.dmi(14, 14)
// Higher-timeframe trend (4x chart), previous completed candle โ never repaints.
htfTf = timeframe.from_seconds(timeframe.in_seconds() * 4)
htfC = request.security(syminfo.tickerid, htfTf, close[1], lookahead = barmerge.lookahead_on)
htfE = request.security(syminfo.tickerid, htfTf, ta.ema(close, 50)[1], lookahead = barmerge.lookahead_on)
bool htfUp = not na(htfE) and htfC > htfE
bool htfDn = not na(htfE) and htfC < htfE
// โโ FVG Pullback โโ
var float bullTop = na
var float bullBot = na
var int bullBar = na
var float bearTop = na
var float bearBot = na
var int bearBar = na
bool fvgBuy = not na(bullBar) and bar_index - bullBar > 0 and bar_index - bullBar <= fvgLife and low <= bullTop and close > open and close > bullBot
bool fvgSell = not na(bearBar) and bar_index - bearBar > 0 and bar_index - bearBar <= fvgLife and high >= bearBot and close < open and close < bearTop
if fvgBuy
bullBar := na
if fvgSell
bearBar := na
if low > high[2] and (low - high[2]) >= fvgMin * atrV
bullBot := high[2]
bullTop := low
bullBar := bar_index
if high < low[2] and (low[2] - high) >= fvgMin * atrV
bearTop := low[2]
bearBot := high
bearBar := bar_index
// โโ EMA Trend โโ
emaF = ta.ema(close, emaFastL)
emaS = ta.ema(close, emaSlowL)
rsiV = ta.rsi(close, 14)
bool trUp = emaF > emaS and close > emaF and rsiV > 50
bool trDn = emaF < emaS and close < emaF and rsiV < 50
bool trendBuy = trUp and not trUp[1]
bool trendSell = trDn and not trDn[1]
// โโ Sensitivity filter โโ
bool rawBuy = entryMethod == "FVG Pullback" ? fvgBuy : trendBuy
bool rawSell = entryMethod == "FVG Pullback" ? fvgSell : trendSell
bool qBuy = sensitivity == "Aggressive" or (close > ema50 and (sensitivity == "Balanced" or (htfUp and adxV >= 20)))
bool qSell = sensitivity == "Aggressive" or (close < ema50 and (sensitivity == "Balanced" or (htfDn and adxV >= 20)))
bool sigBuy = rawBuy and qBuy
bool sigSell = rawSell and qSell and not sigBuy
slowEma = ema50
rawBenchClose = request.security(activeBenchSymbol, timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
rawBenchEma = request.security(activeBenchSymbol, timeframe.period, ta.ema(close, corrEmaLen), barmerge.gaps_off, barmerge.lookahead_off)
benchClose = nz(rawBenchClose, close)
benchEma = nz(rawBenchEma, ta.ema(close, corrEmaLen))
bool rawBenchBullish = benchClose > benchEma
bool rawBenchBearish = benchClose < benchEma
bool benchBullish = ta.lowest(rawBenchBullish ? 1 : 0, corrConfBars) == 1
bool benchBearish = ta.lowest(rawBenchBearish ? 1 : 0, corrConfBars) == 1
// benchFavorsBuy/Sell = benchmark is moving in the direction that supports price
// heading toward TP (not SL) for the current trade direction.
bool benchFavorsBuy = activeBenchInverse ? benchBearish : benchBullish
bool benchFavorsSell = activeBenchInverse ? benchBullish : benchBearish
bool corrBuyConfirm = not useCorrFilter or isCryptoDxyOffline or benchFavorsBuy
bool corrSellConfirm = not useCorrFilter or isCryptoDxyOffline or benchFavorsSell
// โโ Filters: trading hours (sessions) โโ
f_dayList(string opt) =>
string nm = "MonTueWedThuFriSatSun"
string res = "1234567"
if opt != "Every Day"
int a = int(str.pos(nm, str.substring(opt, 0, 3)) / 3)
int b = str.length(opt) > 3 ? int(str.pos(nm, str.substring(opt, 4, 7)) / 3) : a
res := ""
int i = a
for k = 0 to 6
res += str.tostring(i == 6 ? 1 : i + 2)
if i == b
break
i := (i + 1) % 7
res
f_hhmm(string s, int p) =>
int(str.tonumber(str.substring(s, p, p + 2)))
int barMins = hour(time, sessionTz) * 60 + minute(time, sessionTz)
f_inWin(string w) =>
int hs = f_hhmm(w, 0) * 60 + f_hhmm(w, 2)
int he = f_hhmm(w, 5) * 60 + f_hhmm(w, 7)
he > hs ? (barMins >= hs and barMins < he) : (barMins >= hs or barMins < he)
string dowNow = str.tostring(dayofweek(time, sessionTz))
bool inS1 = hoursOn and str.contains(f_dayList(hoursDays), dowNow) and f_inWin(hoursWin)
bool inS2 = hours2On and str.contains(f_dayList(hoursDays2), dowNow) and f_inWin(hoursWin2)
bool inS3 = hours3On and str.contains(f_dayList(hoursDays3), dowNow) and f_inWin(hoursWin3)
bool inS4 = hours4On and str.contains(f_dayList(hoursDays4), dowNow) and f_inWin(hoursWin4)
bool inS5 = hours5On and str.contains(f_dayList(hoursDays5), dowNow) and f_inWin(hoursWin5)
bool inS6 = hours6On and str.contains(f_dayList(hoursDays6), dowNow) and f_inWin(hoursWin6)
bool inS7 = hours7On and str.contains(f_dayList(hoursDays7), dowNow) and f_inWin(hoursWin7)
bool inS8 = hours8On and str.contains(f_dayList(hoursDays8), dowNow) and f_inWin(hoursWin8)
bool inHours = (not hoursOn and not hours2On and not hours3On and not hours4On and not hours5On and not hours6On and not hours7On and not hours8On) or inS1 or inS2 or inS3 or inS4 or inS5 or inS6 or inS7 or inS8
// โโ Signals โโ
bool confirmedBar = barstate.isconfirmed or replayMode
bool buy1 = sigBuy and inHours
bool sell1 = sigSell and inHours
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ MULTI-TIER PERSISTENT FIXED RISK ENGINE
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var bool tradeActive = false
var string activeSignalTag = "WAITING"
var float lockedEntry = na
var float lockedTpPrice = na
var float lockedSlPrice = na
var bool activeIsBuy = false
var string lastTpText = "---"
var string lastSlText = "---"
var int benchConfirmStreak = 0
var int benchInvalidStreak = 0
var int trendConfirmStreak = 0
var int trendInvalidStreak = 0
var line lineSL = na
var line lineTP = na
var label labelSL = na
var label labelTP = na
var int tradeEntryBar = na
// One trade at a time: while a trade is open, a signal in the
// same direction is ignored. An opposite signal still flips it.
// (tradeActive / activeIsBuy still hold the previous candle's state here.)
bool exitsThisBar = tradeActive and bar_index > tradeEntryBar and not na(lockedTpPrice) and
(activeIsBuy ? (high >= lockedTpPrice or low <= lockedSlPrice) : (low <= lockedTpPrice or high >= lockedSlPrice))
bool flat = not tradeActive or exitsThisBar
newBuySignal = buy1 and (flat or not activeIsBuy)
newSellSignal = sell1 and (flat or activeIsBuy)
string masterAlertMsg = ""
bool entryAlert = false
varip int lastEntryAlertBar = -1 // one entry alert per candle, even if TradingView runs the script twice on it
if (newBuySignal or newSellSignal) and (barstate.isconfirmed or replayMode)
activeIsBuy := newBuySignal
finalTpDist = tpPips * pipPoints * syminfo.mintick
finalSlDist = slPips * pipPoints * syminfo.mintick
lockedEntry := close
lockedTpPrice := activeIsBuy ? close + finalTpDist : close - finalTpDist
lockedSlPrice := activeIsBuy ? close - finalSlDist : close + finalSlDist
tradeEntryBar := bar_index
string tag = newBuySignal ? "BUY" : "SELL"
activeSignalTag := tag + " ACTIVE"
entryAlert := true
tradeActive := true
lastTpText := "---"
lastSlText := "---"
benchConfirmStreak := 0
benchInvalidStreak := 0
trendConfirmStreak := 0
trendInvalidStreak := 0
masterAlertMsg := "๐ " + syminfo.ticker + " (" + timeframe.period + ") New " + tag + " Active!" + "\n๐ Entry: " + str.tostring(lockedEntry, format.mintick) + "\n๐ฏ TP: " + str.tostring(lockedTpPrice, format.mintick) + "\n๐ก๏ธ SL: " + str.tostring(lockedSlPrice, format.mintick)
// Machine line for the MT5 All-in-One EA: OL;SIDE;SYMBOL;SL distance;TP distance;LOTS
masterAlertMsg += "\nOL;" + tag + ";" + syminfo.ticker + ";" + str.tostring(finalSlDist, format.mintick) + ";" + str.tostring(finalTpDist, format.mintick) + ";" + str.tostring(lotSize)
if not na(lineSL)
line.delete(lineSL)
if not na(lineTP)
line.delete(lineTP)
if not na(labelSL)
label.delete(labelSL)
if not na(labelTP)
label.delete(labelTP)
int endX = bar_index + 12
lineSL := line.new(bar_index, lockedSlPrice, endX, lockedSlPrice, color = color.red, width = 2, style = line.style_dashed)
labelSL := label.new(endX, lockedSlPrice, tag + " SL: " + str.tostring(lockedSlPrice, format.mintick), style = label.style_label_left, color = color.red, textcolor = color.white, size = size.tiny)
lineTP := line.new(bar_index, lockedTpPrice, endX, lockedTpPrice, color = color.green, width = 2, style = line.style_dashed)
labelTP := label.new(endX, lockedTpPrice, tag + " TP: " + str.tostring(lockedTpPrice, format.mintick), style = label.style_label_left, color = color.green, textcolor = color.white, size = size.tiny)
if tradeActive and not na(lockedTpPrice) and not na(lockedSlPrice) and bar_index > tradeEntryBar
bool tpHit = activeIsBuy ? (high >= lockedTpPrice) : (low <= lockedTpPrice)
bool slHit = activeIsBuy ? (low <= lockedSlPrice) : (high >= lockedSlPrice)
if tpHit or slHit
if tpHit
float tpDistance = math.abs(lockedTpPrice - lockedEntry)
activeSignalTag := "TP HIT ๐"
lastTpText := "Hit (+ " + str.tostring(tpDistance, format.mintick) + ")"
masterAlertMsg := "๐ฏ " + syminfo.ticker + " (" + timeframe.period + ") Take Profit Hit!\nโจ Reached Target (+ " + str.tostring(tpDistance, format.mintick) + " pts)"
else if slHit
float slDistance = math.abs(lockedSlPrice - lockedEntry)
activeSignalTag := "SL HIT โ"
lastSlText := "Hit (- " + str.tostring(slDistance, format.mintick) + ")"
masterAlertMsg := "๐ " + syminfo.ticker + " (" + timeframe.period + ") Stop Loss Hit!\nโ ๏ธ Breached (- " + str.tostring(slDistance, format.mintick) + " pts)"
tradeActive := false
if not na(lineSL)
line.delete(lineSL)
lineSL := na
if not na(lineTP)
line.delete(lineTP)
lineTP := na
if not na(labelSL)
label.delete(labelSL)
labelSL := na
if not na(labelTP)
label.delete(labelTP)
labelTP := na
if masterAlertMsg != ""
// Entries always fire (one per closed candle), so a stop-loss alert earlier in the same
// candle can no longer swallow the next entry. Exit alerts stay once per candle.
if entryAlert
if lastEntryAlertBar != bar_index
lastEntryAlertBar := bar_index
alert(masterAlertMsg, alert.freq_all)
else
alert(masterAlertMsg, alert.freq_once_per_bar)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ง SETUP SCORE + BENCHMARK STATUS
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
bool isCorrelationConfirmedNow = (activeIsBuy and benchFavorsBuy) or (not activeIsBuy and benchFavorsSell)
bool isTrendAlignedNow = (activeIsBuy and close > slowEma) or (not activeIsBuy and close < slowEma)
if tradeActive
if isCorrelationConfirmedNow
benchConfirmStreak := benchConfirmStreak + 1
benchInvalidStreak := 0
else
benchInvalidStreak := benchInvalidStreak + 1
benchConfirmStreak := 0
if isTrendAlignedNow
trendConfirmStreak := trendConfirmStreak + 1
trendInvalidStreak := 0
else
trendInvalidStreak := trendInvalidStreak + 1
trendConfirmStreak := 0
// Setup Score = the chance price reaches TP before SL from where it is NOW.
// It's the classic first-passage ("gambler's ruin") probability: with no
// built-in edge assumed, the odds equal the SL distance divided by the total
// TP + SL distance from the current price. Tested on 12,000+ trade snapshots
// (gold, SP500, NAS100), this beat the old blended score โ adding trend,
// momentum or benchmark bonuses made the prediction LESS accurate, so they
// are shown on their own HUD lines instead of being mixed in.
float tpOdds = na
if activeSignalTag == "TP HIT ๐"
tpOdds := 100.0
else if activeSignalTag == "SL HIT โ"
tpOdds := 0.0
else if tradeActive and not na(lockedTpPrice) and not na(lockedSlPrice)
float toTp = activeIsBuy ? lockedTpPrice - close : close - lockedTpPrice
float toSl = activeIsBuy ? close - lockedSlPrice : lockedSlPrice - close
tpOdds := toTp <= 0 ? 99.0 : toSl <= 0 ? 1.0 : math.min(99.0, math.max(1.0, 100.0 * toSl / (toTp + toSl)))
// HUD label uses the same streaks as the odds score โ only flips to Invalid once
// the benchmark has pushed toward SL for longer than the grace period, and flips
// back to Confirmed as soon as it favors TP again.
bool isCorrelationConfirmedForLabel = benchConfirmStreak > 0 or benchInvalidStreak <= gracePeriodBars
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ฑ DYNAMIC HUD TABLE RENDERER
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var table hud = table.new(position = getTablePosition(hudPos), columns = 2, rows = 7, bgcolor = color.rgb(18, 18, 24, 10), border_color = color.rgb(40, 40, 50), border_width = 1)
if barstate.islast or replayMode
color headerBg = color.rgb(25, 30, 45)
color rowBg1 = color.rgb(20, 20, 28)
color rowBg2 = color.rgb(14, 14, 20)
color baseBg = color.rgb(8, 8, 12)
bool hasHitTargetOrStop = (activeSignalTag == "TP HIT ๐" or activeSignalTag == "SL HIT โ")
string idleNote = not inHours ? "Off Hours ๐" : "Waiting โณ"
string topHeaderStatus = isMarketClosedRT ? "CLOSED ๐ค" : (hasHitTargetOrStop or activeSignalTag == "WAITING" ? idleNote : activeSignalTag)
color topHeaderColor = isMarketClosedRT ? color.rgb(150, 150, 160) : (hasHitTargetOrStop ? color.rgb(241, 196, 15) : (str.contains(activeSignalTag, "BUY") ? color.rgb(46, 204, 113) : color.rgb(231, 76, 60)))
string correlStatus = isCryptoDxyOffline ? "CLOSED ๐ค" : (isMarketClosedRT ? "CLOSED ๐ค" : (not tradeActive ? "Ready โณ" : (isCorrelationConfirmedForLabel ? "Confirmed โ
" : "Invalid โ")))
table.cell(hud, 0, 0, "Open Legacy (" + syminfo.ticker + ")", text_color=color.rgb(220, 225, 235), bgcolor=headerBg, text_size=size.small)
table.cell(hud, 1, 0, topHeaderStatus, text_color=topHeaderColor, bgcolor=headerBg, text_size=size.small)
string statusOddsVal = isMarketClosedRT ? "Market Closed ๐ค" : (hasHitTargetOrStop ? "Waiting โณ" : (activeSignalTag == "WAITING" ? "Waiting..." : str.tostring(tpOdds, "#") + "% to TP"))
string fixedEntryVal = isMarketClosedRT ? "CLOSED ๐ค" : (hasHitTargetOrStop ? "Waiting โณ" : (na(lockedEntry) ? "Waiting..." : str.tostring(lockedEntry, format.mintick)))
string takeProfitVal = isMarketClosedRT ? "CLOSED ๐ค" : (hasHitTargetOrStop ? "Waiting โณ" : (lastTpText != "---" ? lastTpText : (na(lockedTpPrice) ? "Waiting..." : str.tostring(lockedTpPrice, format.mintick))))
string stopLossVal = isMarketClosedRT ? "CLOSED ๐ค" : (hasHitTargetOrStop ? "Waiting โณ" : (lastSlText != "---" ? lastSlText : (na(lockedSlPrice) ? "Waiting..." : str.tostring(lockedSlPrice, format.mintick))))
string benchStructVal = correlStatus
table.cell(hud, 0, 1, "๐ฏ Setup Score", text_color=color.rgb(180, 185, 195), bgcolor=rowBg1, text_size=size.small)
table.cell(hud, 1, 1, statusOddsVal, text_color=isMarketClosedRT ? color.rgb(150, 150, 160) : (hasHitTargetOrStop ? color.rgb(241, 196, 15) : color.rgb(241, 196, 15)), bgcolor=rowBg1, text_size=size.small)
table.cell(hud, 0, 2, "๐ Fixed Entry", text_color=color.rgb(180, 185, 195), bgcolor=rowBg2, text_size=size.small)
table.cell(hud, 1, 2, fixedEntryVal, text_color=isMarketClosedRT ? color.rgb(150, 150, 160) : color.white, bgcolor=rowBg2, text_size=size.small)
table.cell(hud, 0, 3, "๐ Take Profit", text_color=color.rgb(180, 185, 195), bgcolor=rowBg1, text_size=size.small)
table.cell(hud, 1, 3, takeProfitVal, text_color=isMarketClosedRT ? color.rgb(150, 150, 160) : color.rgb(46, 204, 113), bgcolor=rowBg1, text_size=size.small)
table.cell(hud, 0, 4, "๐ก๏ธ Stop Loss", text_color=color.rgb(180, 185, 195), bgcolor=rowBg2, text_size=size.small)
table.cell(hud, 1, 4, stopLossVal, text_color=isMarketClosedRT ? color.rgb(150, 150, 160) : color.rgb(231, 76, 60), bgcolor=rowBg2, text_size=size.small)
table.cell(hud, 0, 5, "๐ " + activeBenchName + " Structure", text_color=color.rgb(200, 210, 230), bgcolor=rowBg1, text_size=size.small)
table.cell(hud, 1, 5, benchStructVal, text_color=isCryptoDxyOffline ? color.rgb(150, 150, 160) : (isMarketClosedRT ? color.rgb(150, 150, 160) : (correlStatus == "Ready โณ" ? color.rgb(150, 150, 160) : (isCorrelationConfirmedForLabel ? color.rgb(46, 204, 113) : color.rgb(231, 76, 60)))), bgcolor=rowBg1, text_size=size.small)
bool structTrendUp = close > slowEma
bool structTrendDown = close < slowEma
bool structCorrBull = activeBenchInverse ? benchBearish : benchBullish
bool structCorrBear = activeBenchInverse ? benchBullish : benchBearish
bool structAgree = (structTrendUp and structCorrBull) or (structTrendDown and structCorrBear)
bool structConflict = (structTrendUp and structCorrBear) or (structTrendDown and structCorrBull)
string structureLabel = not tradeActive ? "Waiting โณ" : (structAgree ? "Strong" : (structConflict ? "Weak" : "Decent"))
color structureColor = not tradeActive ? color.rgb(150, 150, 160) : (structAgree ? color.rgb(46, 204, 113) : (structConflict ? color.rgb(231, 76, 60) : color.rgb(241, 196, 15)))
table.cell(hud, 0, 6, "Overall Structure", text_color=color.rgb(180, 185, 195), bgcolor=baseBg, text_size=size.small)
table.cell(hud, 1, 6, structureLabel, text_color=structureColor, bgcolor=baseBg, text_size=size.small)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐จ SIGNAL LABELS โ only on a closed candle, so a label never vanishes.
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
plotshape(newBuySignal and confirmedBar, title = "BUY Label", style = shape.labelup, location = location.belowbar, color = buyBgColor, text = "BUY", textcolor = buyTextColor, size = size.small)
plotshape(newSellSignal and confirmedBar, title = "SELL Label", style = shape.labeldown, location = location.abovebar, color = sellBgColor, text = "SELL", textcolor = sellTextColor, size = size.small)//@version=6
indicator("Open Legacy Side-Kick", overlay = true, max_labels_count = 500, max_boxes_count = 500)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// OPEN LEGACY SIDE-KICK (Scoreboard + Side-Kick) โ one indicator, one set of settings.
// Set it up exactly like Open Legacy (same entry method, sensitivity, SL / TP,
// sessions and timezone). It follows the same trades, shows the weekly Scoreboard
// (wins, losses and layers) and runs Side-Kick: a green box and alert when a
// dip is a good place to add one layer. No link to pick โ layers feed the Scoreboard directly.
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโ 1. STRATEGY โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G1 = "1. Strategy"
entryMethod = input.string("FVG Pullback", "Entry Method", options = ["FVG Pullback", "EMA Trend"], group = G1,
tooltip = "FVG Pullback โ price leaves a fair value gap (a candle so fast it leaves an untouched gap), then a signal fires when price pulls back into the gap and turns.\n\nEMA Trend โ signals at the start of a new trend leg: fast EMA above slow EMA, price above the fast EMA and RSI above 50 (the reverse for sells).")
sensitivity = input.string("Conservative", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G1,
tooltip = "Aggressive โ the most signals, any timeframe.\n\nBalanced โ only signals that agree with the 50 EMA trend.\n\nConservative โ also needs the trend on a timeframe 4x your chart to agree, and real trend strength (ADX 20+). The fewest signals, the highest quality.")
// โโ 2. TARGETS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G2 = "2. Targets"
slPips = input.float(60, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G2,
tooltip = "Use the same number as Open Legacy.")
tpPips = input.float(40, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G2,
tooltip = "Use the same number as Open Legacy.")
pipPoints = input.int(10, "Points Per Pip", minval = 1, group = G2,
tooltip = "10 for gold, indices, BTC and 5-decimal FX.")
// โโ 3. FILTERS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G4 = "3. Filters"
hoursOn = input.bool(true, "Session 1", group = G4, inline = "h1",
tooltip = "Up to 8 sessions. Tick a session, pick its start and end time (overnight works, e.g. 22:00-02:00) and its days (your Timezone below). Each session has its own days, e.g. Session 1 Mon-Fri 07:00-12:00 and Session 2 Thu-Fri 14:00-18:00. Leave all unticked to trade any time.")
hoursWin = input.session("0130-0400", "", group = G4, inline = "h1")
hoursDays = input.string("Tue-Thu", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h1")
hours2On = input.bool(true, "Session 2", group = G4, inline = "h2")
hoursWin2 = input.session("0430-0630", "", group = G4, inline = "h2")
hoursDays2 = input.string("Mon-Wed", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h2")
hours3On = input.bool(true, "Session 3", group = G4, inline = "h3")
hoursWin3 = input.session("0330-0600", "", group = G4, inline = "h3")
hoursDays3 = input.string("Fri", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h3")
hours4On = input.bool(true, "Session 4", group = G4, inline = "h4")
hoursWin4 = input.session("0800-1130", "", group = G4, inline = "h4")
hoursDays4 = input.string("Mon-Fri", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h4")
hours5On = input.bool(true, "Session 5", group = G4, inline = "h5")
hoursWin5 = input.session("1230-1430", "", group = G4, inline = "h5")
hoursDays5 = input.string("Mon-Wed", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h5")
hours6On = input.bool(true, "Session 6", group = G4, inline = "h6")
hoursWin6 = input.session("1200-1700", "", group = G4, inline = "h6")
hoursDays6 = input.string("Fri", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h6")
hours7On = input.bool(true, "Session 7", group = G4, inline = "h7")
hoursWin7 = input.session("1630-2300", "", group = G4, inline = "h7")
hoursDays7 = input.string("Tue", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h7")
hours8On = input.bool(true, "Session 8", group = G4, inline = "h8")
hoursWin8 = input.session("1830-2030", "", group = G4, inline = "h8")
hoursDays8 = input.string("Wed-Thu", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h8")
// โโ 4. DISPLAY โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G3 = "4. Display"
buyColor = input.color(#4CAF50, "BUY", group = G3, inline = "c")
sellColor = input.color(#FF5252, "SELL", group = G3, inline = "c")
sessionTz = input.string("Europe/Dublin", "Timezone", group = G3,
tooltip = "Your timezone, IANA format (e.g. Europe/Dublin, America/New_York). Used for Trading Hours and the market-closed status.")
replayMode = input.bool(false, "Bar Replay Mode", group = G3,
tooltip = "Turn on while using Bar Replay so the HUD keeps updating.")
sbShow = input.bool(true, "๐ Show Scoreboard", group = G3)
sbPeriod = input.string("This Week", "๐
Show Results For", options = ["This Week", "Last Week", "2 Weeks Ago", "3 Weeks Ago", "4 Weeks Ago", "Last 2 Weeks", "Last 4 Weeks", "Last 8 Weeks", "Last 12 Weeks", "All Time"], group = G3,
tooltip = "๐
One week: This Week, Last Week, 2-4 Weeks Ago.\n๐ Several weeks added up: Last 2/4/8/12 Weeks (this week included).\nโพ๏ธ All Time: every trade on the chart, best for backtesting.")
showMarks = input.bool(true, "Show Trade Markers", group = G3,
tooltip = "Marks each counted entry, and where it settled.")
layersOn = input.bool(true, "โ Count Layers on the Scoreboard", group = G3,
tooltip = "Each layer is counted once per trade and uses the same TP and SL as the trade, as the MT5 robot does.")
// โโ 5. PULSE โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G5 = "5. Layers"
layerMin = input.float(20, "Zone starts (% of the way to your stop)", minval = 5, maxval = 90, group = G5,
tooltip = "WHERE THE BOX BEGINS.\nThe box is drawn between your entry and your stop. 20 means it starts 20% of the way from your entry to your stop.\nSmaller number = box starts closer to your entry.")
layerMax = input.float(55, "Zone ends (% of the way to your stop)", minval = 10, maxval = 95, group = G5,
tooltip = "WHERE THE BOX ENDS.\n55 means it ends 55% of the way to your stop. If price goes deeper than this, the box turns red: too close to the stop to add.")
layerWhen = input.string("Normal", "How picky to be", options = ["Relaxed", "Normal", "Strict"], group = G5,
tooltip = "HOW OFTEN THE BOX TURNS GREEN (layer window open).\nRelaxed = green more often.\nNormal = recommended.\nStrict = green only on the cleanest dips.\n\nBox colours: teal = waiting, green = layer window open, red = too risky, don't add.")
sendMt5 = input.bool(true, "Send layer to MT5 robot", group = G5,
tooltip = "Turn on only if you auto-trade with the Open Legacy All-in-One EA. When the box turns green, the alert also carries a hidden layer order for the robot (it adds one half-size trade with the same SL and TP).\nIn the alert, add your relay Webhook URL, the same one Open Legacy uses.\nOff = you just get a notification.")
int layerMinHealth = layerWhen == "Relaxed" ? 45 : (layerWhen == "Strict" ? 75 : 60)
pivLen = 5
rangeLen = 50
stallHours = 6.0
showFlags = false
showZone = true
showDetail = false
alertsOn = true
//โโ Internal constants โโ
useExchangeTz = false
useCorrFilter = true
buyBgColor = buyColor
buyTextColor = color.white
sellBgColor = sellColor
sellTextColor = color.white
corrEmaLen = 9
corrConfBars = 3
gracePeriodBars = 6
maxRampBars = 12
getTablePosition(string pos) =>
switch pos
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.bottom_right
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ UNIVERSAL HANDS-FREE BENCHMARK ROUTER
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Returns [benchmarkSymbol, isInverseRelationship]
// isInverseRelationship = true -> benchmark moving UP pushes asset toward SL if asset is a BUY
// (i.e. benchmark should move OPPOSITE the asset to favor TP)
// isInverseRelationship = false -> benchmark should move WITH the asset to favor TP
getUniversalInverseBenchmark() =>
string p = syminfo.prefix
string t = str.upper(syminfo.ticker)
string base = syminfo.basecurrency
string quote = syminfo.currency
string symbol = "TVC:DXY"
bool inverse = true
if t == "USDX" or t == "DXY" or t == "USDOLLAR" or t == "DX"
symbol := "TVC:GOLD"
inverse := true
else if p == "NSE" or p == "BSE" or quote == "INR"
symbol := "NSE:INDIAVIX"
inverse := true
else if str.contains(t, "SPX") or str.contains(t, "US500") or str.contains(t, "SP500") or str.contains(t, "NDX") or str.contains(t, "US100") or str.contains(t, "NAS100") or str.contains(t, "US30") or str.contains(t, "DJI") or str.contains(t, "GER") or str.contains(t, "DAX") or str.contains(t, "UK100") or str.contains(t, "EU50") or p == "NASDAQ" or p == "NYSE"
symbol := "TVC:VIX"
inverse := true
else if base == "USD"
if quote == "JPY"
symbol := "TVC:JXY"
inverse := true
else if quote == "CAD"
symbol := "TVC:CXY"
inverse := true
else if quote == "CHF"
symbol := "TVC:SXY"
inverse := true
else
// USD is the BASE here (USDSEK, USDMXN, USDZAR, USDTRY, USDHKD, etc.)
// DXY moves WITH these pairs, not against them โ DIRECT correlation
symbol := "TVC:DXY"
inverse := false
else if quote == "USD"
symbol := "TVC:DXY"
inverse := true
else if quote == "JPY"
symbol := "TVC:JXY"
inverse := true
else if quote == "GBP"
symbol := "TVC:BXY"
inverse := true
else if quote == "EUR"
symbol := "TVC:EXY"
inverse := true
[symbol, inverse]
getBenchmarkDisplayName(string symbol) =>
switch symbol
"NSE:INDIAVIX" => "India VIX"
"TVC:VIX" => "VIX"
"TVC:DXY" => "DXY"
"TVC:GOLD" => "Gold"
"TVC:JXY" => "Yen Index"
"TVC:BXY" => "Pound Index"
"TVC:EXY" => "Euro Index"
"TVC:CXY" => "CAD Index"
"TVC:SXY" => "CHF Index"
=> symbol
[routedBenchSymbol, routedBenchInverse] = getUniversalInverseBenchmark()
string activeBenchSymbol = routedBenchSymbol
bool activeBenchInverse = routedBenchInverse
string activeBenchName = getBenchmarkDisplayName(activeBenchSymbol)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ MARKET-CLOSE DETECTOR โ scheduled weekly close OR unscheduled outage
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
bool isCrypto = syminfo.type == "crypto" or str.contains(syminfo.ticker, "BTC") or str.contains(syminfo.ticker, "ETH")
// Scheduled weekly close, evaluated against the REAL current clock (timenow) in
// the chosen timezone. DST is handled automatically via IANA tz names.
// โข Mon-Fri: closed 22:00-22:59 local (daily break), reopens 23:00
// โข Fri 22:00 onward through all of Sat through Sun 22:59: weekend closed
// โข Reopens Sunday 23:00 local
f_isScheduledClose(string tz) =>
int dow = dayofweek(timenow, tz) // Pine: 1 = Sunday ... 7 = Saturday
int hr = hour(timenow, tz)
bool weekdayBreak = (dow >= 2 and dow <= 6) and (hr == 22)
bool weekendClosed = (dow == 6 and hr >= 22) or (dow == 7) or (dow == 1 and hr < 23)
weekdayBreak or weekendClosed
bool scheduledClosedNow = f_isScheduledClose(useExchangeTz ? syminfo.timezone : sessionTz)
// Live "no fresh data" detector โ catches an UNSCHEDULED outage or maintenance
// break of any length (not a fixed window): as long as no new bar has printed
// for 15+ minutes on a genuinely live last bar, it stays flagged closed for
// however long that gap continues, and clears the moment fresh data resumes.
// Only ever evaluated on barstate.isrealtime, so historical/replay bars never
// trigger this regardless of how old their timestamps are.
bool dataStaleNow = barstate.isrealtime and barstate.islast and (timenow - time_close > 900000)
// DXY/forex benchmark closes on the standard schedule even when crypto itself
// keeps trading โ bypass the correlation filter during that window.
bool isCryptoDxyOffline = not replayMode and isCrypto and scheduledClosedNow
// Main HUD "market closed" status:
// โข non-crypto: closed if EITHER the scheduled weekly window applies OR the
// feed has genuinely gone stale (unscheduled maintenance/outage)
// โข crypto: trades 24/7, so the fixed weekly schedule doesn't apply to the
// asset itself โ only genuine exchange downtime (stale feed) marks it closed
bool isMarketClosedRT = not replayMode and (dataStaleNow or (not isCrypto and scheduledClosedNow))
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ SIGNAL ENGINE
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Sensitivity presets (literal values keep lengths "simple" for ta.* calls)
fvgLife = sensitivity == "Aggressive" ? 12 : sensitivity == "Balanced" ? 24 : 40
fvgMin = sensitivity == "Aggressive" ? 0.10 : sensitivity == "Balanced" ? 0.25 : 0.40
emaFastL = sensitivity == "Aggressive" ? 8 : sensitivity == "Balanced" ? 13 : 21
emaSlowL = sensitivity == "Aggressive" ? 21 : sensitivity == "Balanced" ? 34 : 55
atrV = ta.atr(14)
ema50 = ta.ema(close, 50)
[diP, diM, adxV] = ta.dmi(14, 14)
// Higher-timeframe trend (4x chart), previous completed candle โ never repaints.
htfTf = timeframe.from_seconds(timeframe.in_seconds() * 4)
htfC = request.security(syminfo.tickerid, htfTf, close[1], lookahead = barmerge.lookahead_on)
htfE = request.security(syminfo.tickerid, htfTf, ta.ema(close, 50)[1], lookahead = barmerge.lookahead_on)
bool htfUp = not na(htfE) and htfC > htfE
bool htfDn = not na(htfE) and htfC < htfE
// โโ FVG Pullback โโ
var float bullTop = na
var float bullBot = na
var int bullBar = na
var float bearTop = na
var float bearBot = na
var int bearBar = na
bool fvgBuy = not na(bullBar) and bar_index - bullBar > 0 and bar_index - bullBar <= fvgLife and low <= bullTop and close > open and close > bullBot
bool fvgSell = not na(bearBar) and bar_index - bearBar > 0 and bar_index - bearBar <= fvgLife and high >= bearBot and close < open and close < bearTop
if fvgBuy
bullBar := na
if fvgSell
bearBar := na
if low > high[2] and (low - high[2]) >= fvgMin * atrV
bullBot := high[2]
bullTop := low
bullBar := bar_index
if high < low[2] and (low[2] - high) >= fvgMin * atrV
bearTop := low[2]
bearBot := high
bearBar := bar_index
// โโ EMA Trend โโ
emaF = ta.ema(close, emaFastL)
emaS = ta.ema(close, emaSlowL)
rsiV = ta.rsi(close, 14)
bool trUp = emaF > emaS and close > emaF and rsiV > 50
bool trDn = emaF < emaS and close < emaF and rsiV < 50
bool trendBuy = trUp and not trUp[1]
bool trendSell = trDn and not trDn[1]
// โโ Sensitivity filter โโ
bool rawBuy = entryMethod == "FVG Pullback" ? fvgBuy : trendBuy
bool rawSell = entryMethod == "FVG Pullback" ? fvgSell : trendSell
bool qBuy = sensitivity == "Aggressive" or (close > ema50 and (sensitivity == "Balanced" or (htfUp and adxV >= 20)))
bool qSell = sensitivity == "Aggressive" or (close < ema50 and (sensitivity == "Balanced" or (htfDn and adxV >= 20)))
bool sigBuy = rawBuy and qBuy
bool sigSell = rawSell and qSell and not sigBuy
slowEma = ema50
rawBenchClose = request.security(activeBenchSymbol, timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
rawBenchEma = request.security(activeBenchSymbol, timeframe.period, ta.ema(close, corrEmaLen), barmerge.gaps_off, barmerge.lookahead_off)
benchClose = nz(rawBenchClose, close)
benchEma = nz(rawBenchEma, ta.ema(close, corrEmaLen))
bool rawBenchBullish = benchClose > benchEma
bool rawBenchBearish = benchClose < benchEma
bool benchBullish = ta.lowest(rawBenchBullish ? 1 : 0, corrConfBars) == 1
bool benchBearish = ta.lowest(rawBenchBearish ? 1 : 0, corrConfBars) == 1
// benchFavorsBuy/Sell = benchmark is moving in the direction that supports price
// heading toward TP (not SL) for the current trade direction.
bool benchFavorsBuy = activeBenchInverse ? benchBearish : benchBullish
bool benchFavorsSell = activeBenchInverse ? benchBullish : benchBearish
bool corrBuyConfirm = not useCorrFilter or isCryptoDxyOffline or benchFavorsBuy
bool corrSellConfirm = not useCorrFilter or isCryptoDxyOffline or benchFavorsSell
// โโ Filters: trading hours (sessions) โโ
f_dayList(string opt) =>
string nm = "MonTueWedThuFriSatSun"
string res = "1234567"
if opt != "Every Day"
int a = int(str.pos(nm, str.substring(opt, 0, 3)) / 3)
int b = str.length(opt) > 3 ? int(str.pos(nm, str.substring(opt, 4, 7)) / 3) : a
res := ""
int i = a
for k = 0 to 6
res += str.tostring(i == 6 ? 1 : i + 2)
if i == b
break
i := (i + 1) % 7
res
f_hhmm(string s, int p) =>
int(str.tonumber(str.substring(s, p, p + 2)))
int barMins = hour(time, sessionTz) * 60 + minute(time, sessionTz)
f_inWin(string w) =>
int hs = f_hhmm(w, 0) * 60 + f_hhmm(w, 2)
int he = f_hhmm(w, 5) * 60 + f_hhmm(w, 7)
he > hs ? (barMins >= hs and barMins < he) : (barMins >= hs or barMins < he)
string dowNow = str.tostring(dayofweek(time, sessionTz))
bool inS1 = hoursOn and str.contains(f_dayList(hoursDays), dowNow) and f_inWin(hoursWin)
bool inS2 = hours2On and str.contains(f_dayList(hoursDays2), dowNow) and f_inWin(hoursWin2)
bool inS3 = hours3On and str.contains(f_dayList(hoursDays3), dowNow) and f_inWin(hoursWin3)
bool inS4 = hours4On and str.contains(f_dayList(hoursDays4), dowNow) and f_inWin(hoursWin4)
bool inS5 = hours5On and str.contains(f_dayList(hoursDays5), dowNow) and f_inWin(hoursWin5)
bool inS6 = hours6On and str.contains(f_dayList(hoursDays6), dowNow) and f_inWin(hoursWin6)
bool inS7 = hours7On and str.contains(f_dayList(hoursDays7), dowNow) and f_inWin(hoursWin7)
bool inS8 = hours8On and str.contains(f_dayList(hoursDays8), dowNow) and f_inWin(hoursWin8)
bool inHours = (not hoursOn and not hours2On and not hours3On and not hours4On and not hours5On and not hours6On and not hours7On and not hours8On) or inS1 or inS2 or inS3 or inS4 or inS5 or inS6 or inS7 or inS8
// โโ Signals โโ
bool confirmedBar = barstate.isconfirmed or replayMode
bool buy1 = sigBuy and inHours
bool sell1 = sigSell and inHours
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐๏ธ MARKET STRUCTURE REFERENCES
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
float plV = ta.pivotlow(low, pivLen, pivLen)
float phV = ta.pivothigh(high, pivLen, pivLen)
var float lastPL = na
var float lastPH = na
if not na(plV)
lastPL := plV
if not na(phV)
lastPH := phV
float lowN = ta.lowest(low, 10)
float highN = ta.highest(high, 10)
float rangeHi = ta.highest(high, rangeLen)
float rangeLo = ta.lowest(low, rangeLen)
float mF9 = ta.ema(close, 9)
float mS21 = ta.ema(close, 21)
float atrAvg = ta.sma(atrV, 50)
int timeoutBars = math.max(2, int(math.round(stallHours * 3600 / timeframe.in_seconds())))
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ SAME TRADE ENGINE AS OPEN LEGACY (one trade at a time)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var bool tradeActive = false
var bool activeIsBuy = false
var float lockedEntry = na
var float lockedTpPrice = na
var float lockedSlPrice = na
var int tradeEntryBar = na
var float entryGuard = na
var float entryBarrier = na
var int benchBad = 0
var int prevKey = 0
var int prevVerdict = 0
var bool layerTaken = false
varip bool layerAlerted = false // varip: remembered tick-by-tick, so a layer alert that was sent is never repeated on later candles
var string lastResult = "WAITING"
var box zBox = na
bool exitsThisBar = tradeActive and bar_index > tradeEntryBar and not na(lockedTpPrice) and
(activeIsBuy ? (high >= lockedTpPrice or low <= lockedSlPrice) : (low <= lockedTpPrice or high >= lockedSlPrice))
bool flat = not tradeActive or exitsThisBar
bool newBuySignal = buy1 and (flat or not activeIsBuy)
bool newSellSignal = sell1 and (flat or activeIsBuy)
if (newBuySignal or newSellSignal) and (barstate.isconfirmed or replayMode)
activeIsBuy := newBuySignal
float tpDist = tpPips * pipPoints * syminfo.mintick
float slDist = slPips * pipPoints * syminfo.mintick
lockedEntry := close
lockedTpPrice := activeIsBuy ? close + tpDist : close - tpDist
lockedSlPrice := activeIsBuy ? close - slDist : close + slDist
tradeEntryBar := bar_index
tradeActive := true
benchBad := 0
prevKey := 0
prevVerdict := 0
layerTaken := false
layerAlerted := false
lastResult := activeIsBuy ? "BUY ACTIVE" : "SELL ACTIVE"
// swing the trade leans on (below a buy, above a sell), kept 0.3-3 ATR away
if activeIsBuy
float cand = (not na(lastPL) and lastPL <= close - 0.3 * atrV and lastPL >= close - 3 * atrV) ? lastPL : math.min(lowN, close - 0.3 * atrV)
entryGuard := cand
float b1 = (not na(lastPH) and lastPH > close and lastPH < lockedTpPrice) ? lastPH : 1e10
float b2 = (rangeHi > close and rangeHi < lockedTpPrice) ? rangeHi : 1e10
float bb = math.min(b1, b2)
entryBarrier := bb >= 1e10 ? na : bb
else
float cand = (not na(lastPH) and lastPH >= close + 0.3 * atrV and lastPH <= close + 3 * atrV) ? lastPH : math.max(highN, close + 0.3 * atrV)
entryGuard := cand
float b1 = (not na(lastPL) and lastPL < close and lastPL > lockedTpPrice) ? lastPL : -1e10
float b2 = (rangeLo < close and rangeLo > lockedTpPrice) ? rangeLo : -1e10
float bb = math.max(b1, b2)
entryBarrier := bb <= -1e10 ? na : bb
if showZone
float zA = activeIsBuy ? close - slDist * layerMin / 100.0 : close + slDist * layerMin / 100.0
float zB = activeIsBuy ? close - slDist * layerMax / 100.0 : close + slDist * layerMax / 100.0
zBox := box.new(bar_index, math.max(zA, zB), bar_index + 1, math.min(zA, zB), border_color = color.new(#26C6DA, 40), bgcolor = color.new(#26C6DA, 88), text = "layer zone", text_color = color.new(#26C6DA, 20), text_size = size.tiny, text_halign = text.align_right)
if tradeActive and not na(lockedTpPrice) and bar_index > tradeEntryBar
bool tpHit = activeIsBuy ? (high >= lockedTpPrice) : (low <= lockedTpPrice)
bool slHit = activeIsBuy ? (low <= lockedSlPrice) : (high >= lockedSlPrice)
if tpHit or slHit
lastResult := tpHit ? "TP HIT ๐" : "SL HIT โ"
tradeActive := false
if not na(zBox)
box.set_right(zBox, bar_index)
zBox := na
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ THE PULSE โ nine checks on how the trade is holding
// 1 = green (supports the trade) 2 = orange (caution) 3 = red (against it)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
bool live = tradeActive and not na(lockedEntry)
float dirV = activeIsBuy ? 1.0 : -1.0
float slD = live ? math.abs(lockedEntry - lockedSlPrice) : na
float tpD = live ? math.abs(lockedTpPrice - lockedEntry) : na
float pnlV = live ? dirV * (close - lockedEntry) : na
float ddF = (live and pnlV < 0) ? -pnlV / slD : 0.0
float prF = (live and pnlV > 0) ? pnlV / tpD : 0.0
int barsIn = live ? bar_index - tradeEntryBar : 0
f_px(float p) => str.tostring(p, format.mintick)
f_val(int f) => f == 1 ? 1.0 : f == 2 ? 0.5 : 0.0
f_em(int f) => f == 1 ? "๐ข" : f == 2 ? "๐ " : f == 3 ? "๐ด" : "โช"
f_col(int f) => f == 1 ? color.rgb(46, 204, 113) : f == 2 ? color.rgb(245, 166, 35) : f == 3 ? color.rgb(255, 82, 82) : color.rgb(150, 150, 160)
// 1. Position โ where price sits between entry, TP and SL
int fPos = not live ? 0 : (pnlV >= 0 ? 1 : (ddF < 0.25 ? 1 : (ddF < 0.6 ? 2 : 3)))
string tPos = not live ? "โ" : (pnlV >= 0 ? "In profit, " + str.tostring(prF * 100, "#") + "% to TP" : (ddF < 0.25 ? "Normal dip, " : "Drawdown ") + str.tostring(ddF * 100, "#") + "% of SL")
// 2. Structure โ is the swing the trade leans on still intact?
float guardGap = live ? dirV * (close - entryGuard) : na
int fStruct = not live ? 0 : (guardGap <= 0 ? 3 : (guardGap < 0.25 * atrV ? 2 : 1))
string tStruct = not live ? "โ" : (fStruct == 3 ? "Broke swing " + f_px(entryGuard) : (fStruct == 2 ? "Testing swing " + f_px(entryGuard) : "Swing " + f_px(entryGuard) + " holding"))
// 3. SL map โ is the stop sitting behind that structure?
int fSL = not live ? 0 : (dirV * (entryGuard - lockedSlPrice) >= 0 ? 1 : 2)
string tSL = not live ? "โ" : (fSL == 1 ? "SL sits behind the swing" : "SL inside the swing (tight)")
// 4. TP path โ anything in the way of the target?
bool barrierCleared = not na(entryBarrier) and dirV * (close - entryBarrier) > 0
int fTP = not live ? 0 : ((na(entryBarrier) or barrierCleared) ? 1 : 2)
string tTP = not live ? "โ" : (fTP == 1 ? "Path to TP is clear" : "Barrier " + f_px(entryBarrier) + " before TP")
// 5. Momentum โ price vs 21 EMA, RSI, and EMA 9/21 alignment
bool alP = dirV * (close - mS21) > 0
bool alR = dirV * (rsiV - 50) > 0
bool alF = dirV * (mF9 - mS21) > 0
int momCnt = (alP ? 1 : 0) + (alR ? 1 : 0) + (alF ? 1 : 0)
int fMom = not live ? 0 : ((momCnt == 3 or (momCnt == 2 and alP)) ? 1 : (momCnt == 0 ? 3 : 2))
string tMom = not live ? "โ" : (fMom == 1 ? "Momentum with you" : (fMom == 3 ? "Momentum against you" : "Momentum mixed"))
// 6. Trend โ the timeframe 4x your chart
bool htfWith = activeIsBuy ? htfUp : htfDn
bool htfOpp = activeIsBuy ? htfDn : htfUp
int fHtf = not live ? 0 : (htfWith ? 1 : (htfOpp ? 3 : 2))
string tHtf = not live ? "โ" : (fHtf == 1 ? "Bigger trend agrees" : (fHtf == 3 ? "Bigger trend against" : "Bigger trend unclear"))
// 7. Strength โ ADX / DI
bool diAl = activeIsBuy ? diP > diM : diM > diP
int fStr = not live ? 0 : ((adxV >= 20 and diAl) ? 1 : ((adxV >= 25 and not diAl) ? 3 : 2))
string tStr = not live ? "โ" : (fStr == 1 ? "Trending your way" : (fStr == 3 ? "Strong trend against" : (adxV < 15 ? "Choppy market" : "Weak trend")))
// 8. Backdrop โ the benchmark (DXY / VIX / etc.) that suits your pair
bool benchOk = activeIsBuy ? benchFavorsBuy : benchFavorsSell
if live
benchBad := (benchOk or isCryptoDxyOffline) ? 0 : benchBad + 1
int fBack = not live ? 0 : (benchBad == 0 ? 1 : (benchBad <= gracePeriodBars ? 2 : 3))
string tBack = not live ? "โ" : (fBack == 1 ? activeBenchName + " supports it" : (fBack == 2 ? activeBenchName + " wobbling" : activeBenchName + " against it"))
// 9. Pace โ rejection candles, stalling, volatility spikes
bool rej1 = barsIn >= 1 and dirV * (open - close) >= 1.2 * atrV
bool rej2 = barsIn >= 2 and dirV * (open[1] - close[1]) >= 1.2 * atrV
bool rej3 = barsIn >= 3 and dirV * (open[2] - close[2]) >= 1.2 * atrV
bool rejected = live and (rej1 or rej2 or rej3)
bool volSpike = atrV > 1.8 * atrAvg
int fPace = not live ? 0 : (rejected ? 3 : ((barsIn > timeoutBars and prF < 0.3) ? (ddF > 0.4 ? 3 : 2) : (volSpike ? 2 : 1)))
string tPace = not live ? "โ" : (rejected ? "Strong rejection candle" : ((barsIn > timeoutBars and prF < 0.3) ? "Stalling " + str.tostring(barsIn) + " bars" : (volSpike ? "Volatility spike" : "Normal pace")))
// Health score and verdict
float healthPct = live ? 100.0 * (1.5 * f_val(fPos) + 2.0 * f_val(fStruct) + 0.5 * f_val(fSL) + 0.5 * f_val(fTP) + 1.5 * f_val(fMom) + 1.0 * f_val(fHtf) + 1.0 * f_val(fStr) + 1.0 * f_val(fBack) + 1.0 * f_val(fPace)) / 10.0 : na
bool hardRed = live and (fStruct == 3 or (fMom == 3 and fHtf == 3) or ddF > 0.8 or (fHtf == 3 and ddF >= 0.25))
bool layerOK = live and pnlV < 0 and ddF * 100 >= layerMin and ddF * 100 <= layerMax and fStruct < 3 and fHtf == 1 and fMom < 3 and fStr < 3 and fPace < 3 and healthPct >= layerMinHealth
// 1 = layer, 2 = hold, 3 = expect worse
int verdict = not live ? 0 : ((hardRed or healthPct < 40) ? 3 : (layerOK ? 1 : 2))
int flagState = not live ? 0 : (verdict == 1 ? 4 : (verdict == 3 ? 3 : (healthPct >= 65 ? 1 : 2)))
string verdictText = verdict == 0 ? lastResult : (verdict == 1 ? "LAYER โ" : (verdict == 3 ? "EXPECT WORSE โ ๏ธ" : (pnlV >= 0 ? "LET IT RUN โ
" : "HOLD โ DON'T ADD โณ")))
string guideText = verdict == 0 ? "Waiting for the next signal" : (verdict == 1 ? "Dip into support, trend intact: one layer is OK" : (verdict == 3 ? "Don't add. Protect the account" : (pnlV >= 0 ? "Healthy: let it run" : "Normal dip: wait, don't add yet")))
color verdictColor = verdict == 1 ? color.rgb(38, 198, 218) : (verdict == 3 ? color.rgb(255, 82, 82) : (verdict == 2 ? (healthPct >= 65 ? color.rgb(46, 204, 113) : color.rgb(245, 166, 35)) : color.rgb(150, 150, 160)))
// โโ Chart flags: a labelled flag whenever the picture changes โโ
string reasonTxt = fStruct == 3 ? tStruct : (fMom == 3 ? tMom : (fHtf == 3 ? tHtf : (fPace == 3 ? tPace : (fPos == 3 ? tPos : (fStr == 3 ? tStr : (fStruct == 2 ? tStruct : (fMom == 2 ? tMom : (fHtf == 2 ? tHtf : (fPos == 2 ? tPos : "All checks green")))))))))
string reasonShow = reasonTxt == "All checks green" ? reasonTxt : "Watch: " + reasonTxt
int stateKey = flagState * 10 + verdict
if live and (barstate.isconfirmed or replayMode) and stateKey != prevKey
if showFlags
color fc = flagState == 4 ? color.rgb(38, 198, 218) : (flagState == 3 ? color.rgb(255, 82, 82) : (flagState == 2 ? color.rgb(245, 166, 35) : color.rgb(46, 204, 113)))
string head = flagState == 4 ? "๐ข LAYER" : (flagState == 3 ? "๐ด WORSE" : (flagState == 2 ? "๐ CAUTION" : "๐ข HEALTHY"))
label.new(bar_index, high, head + " " + str.tostring(healthPct, "#") + "%\n" + reasonShow, style = label.style_label_down, color = color.new(fc, 12), textcolor = color.white, size = size.small)
prevKey := stateKey
// Alert fires only when a real layer opens (box turns green), once per trade. No "too risky" alerts.
if live and alertsOn and verdict != prevVerdict and verdict == 1 and not layerAlerted and not layerTaken
if verdict == 1
layerAlerted := true
string layerTag = (sendMt5 and verdict == 1) ? "\nOLL;" + (activeIsBuy ? "BUY" : "SELL") + ";" + syminfo.ticker + ";" + str.tostring(slPips * pipPoints * syminfo.mintick, "#.#####") + ";" + str.tostring(tpPips * pipPoints * syminfo.mintick, "#.#####") : ""
alert((verdict == 1 ? "โ " + syminfo.ticker + " (" + timeframe.period + ") LAYER WINDOW OPEN. Price is in the zone." : "โ ๏ธ " + syminfo.ticker + " (" + timeframe.period + ") Too risky to layer. Don't add.") + layerTag, alert.freq_once_per_bar)
if live and verdict != prevVerdict and barstate.isconfirmed
prevVerdict := verdict
// Hidden layer link for the Scoreboard: +1 (buy) or -1 (sell) on the candle that closes with the box green, once per trade.
// Past candles: TradingView can't replay what happened inside a candle, so a layer is
// counted when the candle's own high/low swept through the layer zone (same rules otherwise).
float ddWorst = live ? math.max(0.0, -dirV * ((dirV == 1 ? low : high) - lockedEntry) / slD) : 0.0
float ddBest = live ? math.max(0.0, -dirV * ((dirV == 1 ? high : low) - lockedEntry) / slD) : 0.0
bool layerOKh = live and not hardRed and healthPct >= layerMinHealth and fStruct < 3 and fHtf == 1 and fMom < 3 and fStr < 3 and fPace < 3 and ddWorst * 100 >= layerMin and ddBest * 100 <= layerMax
// Live latch: varip is not rolled back between ticks, so the layer is remembered the
// instant the window opens, even if the candle later closes without it.
varip int lkBar = -1
varip float lkVal = 0.0
if barstate.isrealtime and lkBar != bar_index
lkBar := bar_index
lkVal := 0.0
float layerLink = 0.0
if barstate.isrealtime
if live and verdict == 1 and not layerTaken and lkVal == 0.0
lkVal := activeIsBuy ? 1.0 : -1.0
layerLink := lkVal
if barstate.isconfirmed and lkVal != 0.0
layerTaken := true
// A layer can only open on a candle AFTER the entry candle: the entry candle's own wick happened before the trade existed.
else if live and barstate.isconfirmed and bar_index > tradeEntryBar and (verdict == 1 or layerOKh) and not layerTaken
layerTaken := true
layerLink := activeIsBuy ? 1.0 : -1.0
// Fast layers on PAST candles: a layer that opens and the trade ends inside one candle (e.g. a layer a few
// seconds after entry, then TP or SL) never shows as "live" on that candle. 1-minute data shows whether price
// reached the zone BEFORE TP/SL. Same health checks as above, taken from the last live candle. Not used in real time.
[m1Hl, m1Ll] = request.security_lower_tf(syminfo.tickerid, "1", [high, low])
bool exitedNow = tradeActive[1] and not tradeActive and bar_index > tradeEntryBar
if not barstate.isrealtime and barstate.isconfirmed and exitedNow and not layerTaken and live[1] and not hardRed[1] and healthPct[1] >= layerMinHealth and fStruct[1] < 3 and fHtf[1] == 1 and fMom[1] < 3 and fStr[1] < 3 and fPace[1] < 3 and array.size(m1Hl) > 0
float zStart = lockedEntry - dirV * math.abs(lockedEntry - lockedSlPrice) * layerMin / 100.0
bool hitZone = false
bool doneM = false
for m = 0 to array.size(m1Hl) - 1
if not doneM
float mh = array.get(m1Hl, m)
float ml = array.get(m1Ll, m)
bool mTp = activeIsBuy ? mh >= lockedTpPrice : ml <= lockedTpPrice
bool mSl = activeIsBuy ? ml <= lockedSlPrice : mh >= lockedSlPrice
bool mZn = activeIsBuy ? ml <= zStart : mh >= zStart
if mZn and (not mTp or mSl)
hitZone := true
if mTp or mSl
doneM := true
if hitZone
layerTaken := true
layerLink := activeIsBuy ? 1.0 : -1.0
plot(layerLink, "Layer link", display = display.none)
if live and not na(zBox)
box.set_right(zBox, bar_index)
box.set_bgcolor(zBox, verdict == 1 ? color.new(#2ECC71, 66) : (verdict == 3 ? color.new(#FF5252, 84) : color.new(#26C6DA, 90)))
box.set_border_color(zBox, verdict == 1 ? color.new(#2ECC71, 20) : (verdict == 3 ? color.new(#FF5252, 40) : color.new(#26C6DA, 40)))
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ OPEN LEGACY SCOREBOARD (layers come from the same script)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Signals the Scoreboard replays: the same entries Layer Master follows
bool sigB = buy1
bool sigS = sell1
// Scoreboard period -> weeks to add up (0 = all) and weeks back
int sbSpan = switch sbPeriod
"Last 2 Weeks" => 2
"Last 4 Weeks" => 4
"Last 8 Weeks" => 8
"Last 12 Weeks" => 12
"All Time" => 0
=> 1
int sbWeeksBack = switch sbPeriod
"Last Week" => 1
"2 Weeks Ago" => 2
"3 Weeks Ago" => 3
"4 Weeks Ago" => 4
=> 0
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// TRADE REPLAY
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
float sbTpDist = tpPips * pipPoints * syminfo.mintick
float sbSlDist = slPips * pipPoints * syminfo.mintick
// 1-minute data (loaded once, above) decides which level came first when one candle hits both.
// Per week: 7 days x 4 outcomes (0 TP hit, 1 Partial +, 2 Partial -, 3 SL hit).
var array<int> sbOut = array.new_int(28, 0)
// Layers per week: 7 days x 2 (0 win, 1 loss).
var array<int> sbLay = array.new_int(14, 0)
var int sbWeek = 0
f_dayIdx(int t) =>
int d = dayofweek(t, sessionTz)
d == dayofweek.sunday ? 6 : d - 2
wkNow = weekofyear(time, sessionTz)
if wkNow != wkNow[1] and bar_index > 0
sbWeek += 1
for i = 0 to 27
array.push(sbOut, 0)
for i = 0 to 13
array.push(sbLay, 0)
f_record(int et, int kind) =>
int slot = (sbWeek * 7 + f_dayIdx(et)) * 4 + kind
array.set(sbOut, slot, array.get(sbOut, slot) + 1)
f_recLay(int et, int kind) =>
int slot = (sbWeek * 7 + f_dayIdx(et)) * 2 + kind
array.set(sbLay, slot, array.get(sbLay, slot) + 1)
f_mark(bool won, string txt, bool atHigh) =>
if showMarks
label.new(bar_index, atHigh ? high : low, txt, style = atHigh ? label.style_label_down : label.style_label_up,
color = won ? color.new(color.green, 20) : color.new(color.red, 20), textcolor = color.white, size = size.tiny)
var int posDir = 0
var float posEnt = na
var int posEt = na
var int posBar = na
var bool layOpen = false
var float layEnt = na
// Live latch: remembers which level price touched FIRST on the forming candle.
// varip isn't rolled back between ticks, so the result locks the instant price
// touches TP or SL and can't flip if price reverses before the candle closes.
varip int liveBar = -1
varip int liveRes = 0
if barstate.isrealtime and liveBar != bar_index
liveBar := bar_index
liveRes := 0
// 0. Layer link: counted the MOMENT Side-Kick latches it (live), not at candle close.
// On past candles it reads the closed value of the previous candle, as before.
if layersOn and posDir != 0 and not layOpen and bar_index > posBar
float lk = barstate.isrealtime ? layerLink : layerLink[1]
if (lk == 1.0 and posDir == 1) or (lk == -1.0 and posDir == -1)
layOpen := true
layEnt := barstate.isrealtime ? close : close[1]
if showMarks
int lb = barstate.isrealtime ? bar_index : bar_index - 1
label.new(lb, posDir == 1 ? low[bar_index - lb] : high[bar_index - lb], "+LAYER", style = posDir == 1 ? label.style_label_up : label.style_label_down,
color = color.new(color.teal, 20), textcolor = color.white, size = size.tiny)
// 1. TP / SL โ checked on EVERY tick, so it registers the moment price touches
// the level, not only at candle close. (The entry candle itself is skipped.)
if posDir != 0 and bar_index > posBar
float tpL = posEnt + posDir * sbTpDist
float slL = posEnt - posDir * sbSlDist
bool tpHit = posDir == 1 ? high >= tpL : low <= tpL
bool slHit = posDir == 1 ? low <= slL : high >= slL
if tpHit or slHit
bool won = tpHit and not slHit
if barstate.isrealtime and liveRes != 0
won := liveRes == 1
else
if tpHit and slHit and array.size(m1Hl) > 0
bool done = false
for m = 0 to array.size(m1Hl) - 1
if not done
bool mTp = posDir == 1 ? array.get(m1Hl, m) >= tpL : array.get(m1Ll, m) <= tpL
bool mSl = posDir == 1 ? array.get(m1Ll, m) <= slL : array.get(m1Hl, m) >= slL
if mTp or mSl
won := mTp and not mSl
done := true
if barstate.isrealtime
liveRes := won ? 1 : -1
// Past candles: a layer that opened and ended inside this exit candle (Side-Kick marks it on the exit candle itself)
if layersOn and not barstate.isrealtime and not layOpen and ((layerLink == 1.0 and posDir == 1) or (layerLink == -1.0 and posDir == -1))
layOpen := true
if showMarks
label.new(bar_index, posEnt - posDir * sbSlDist * layerMin / 100.0, "+LAYER", style = label.style_label_left,
color = color.new(color.teal, 20), textcolor = color.white, size = size.tiny)
f_record(posEt, won ? 0 : 3)
f_mark(won, won ? "โ TP" : "โ SL", won == (posDir == 1))
if layOpen
f_recLay(posEt, won ? 0 : 1)
layOpen := false
posDir := 0
// 2. Entries โ evaluated at candle close only (signals need the closed candle)
if barstate.isconfirmed
// an opposite signal closes the open trade first
int want = sigB ? 1 : sigS ? -1 : 0
if want != 0 and want != posDir
if posDir != 0
bool won3 = (close - posEnt) * posDir > 0
f_record(posEt, won3 ? 1 : 2)
f_mark(won3, won3 ? "โ Partial +" : "โ Partial -", true)
if layOpen
f_recLay(posEt, (close - layEnt) * posDir > 0 ? 0 : 1)
layOpen := false
posDir := want
posEnt := close
posEt := time
posBar := bar_index
if showMarks
label.new(bar_index, want == 1 ? low : high, want == 1 ? "BUY" : "SELL", style = want == 1 ? label.style_label_up : label.style_label_down,
color = want == 1 ? color.new(color.green, 0) : color.new(color.red, 0), textcolor = color.white, size = size.small)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ SCOREBOARD
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var table sb = table.new(position.bottom_right, 3, 16, border_width = 1, frame_width = 2,
frame_color = color.new(#2A3350, 0), border_color = color.new(#1C2334, 0))
if (barstate.islastconfirmedhistory or barstate.isrealtime) and sbShow
bg = color.new(#0E1320, 0)
alt = color.new(#121829, 0)
head = color.new(#18203A, 0)
sub = color.new(#141B2E, 0)
green = color.rgb(47, 212, 128)
red = color.rgb(255, 93, 108)
teal = color.rgb(46, 196, 182)
amber = color.rgb(245, 185, 66)
dim = color.rgb(118, 126, 146)
ts = size.small
int lastWk = sbWeek - sbWeeksBack
int firstWk = sbSpan == 0 ? 0 : math.max(0, lastWk - sbSpan + 1)
bool single = sbSpan == 1
string hdr = sbSpan == 0 ? "๐
All" : single ? (sbWeeksBack == 0 ? "๐
This Wk" : sbWeeksBack == 1 ? "๐
Last Wk" : "๐
" + str.tostring(sbWeeksBack) + " Wks Ago") : "๐
" + str.tostring(sbSpan) + " Wks"
array<int> win = array.new_int(7, 0)
array<int> loss = array.new_int(7, 0)
array<int> oc = array.new_int(4, 0)
if lastWk >= 0
for w = firstWk to lastWk
for d = 0 to 6
for k = 0 to 3
int v = array.get(sbOut, (w * 7 + d) * 4 + k)
if v > 0
if k <= 1
array.set(win, d, array.get(win, d) + v)
else
array.set(loss, d, array.get(loss, d) + v)
array.set(oc, k, array.get(oc, k) + v)
table.cell(sb, 0, 0, hdr, text_color = color.rgb(214, 220, 234), bgcolor = head, text_size = ts)
table.cell(sb, 1, 0, "โ
Wins", text_color = green, bgcolor = head, text_size = ts)
table.cell(sb, 2, 0, "โ Losses", text_color = red, bgcolor = head, text_size = ts)
names = array.from("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
int today = f_dayIdx(time)
int tw = 0
int tl = 0
for d = 0 to 6
bool isNowDay = d == today and sbWeeksBack == 0 and single
color rbg = isNowDay ? color.new(#1A2440, 0) : (d % 2 == 0 ? bg : alt)
int wv = array.get(win, d)
int lv = array.get(loss, d)
table.cell(sb, 0, d + 1, (isNowDay ? "โธ " : "") + array.get(names, d),
text_color = isNowDay ? color.rgb(77, 232, 255) : color.rgb(205, 212, 228), bgcolor = rbg, text_size = ts)
table.cell(sb, 1, d + 1, wv == 0 ? "-" : str.tostring(wv), text_color = wv == 0 ? dim : green, bgcolor = rbg, text_size = ts)
table.cell(sb, 2, d + 1, lv == 0 ? "-" : str.tostring(lv), text_color = lv == 0 ? dim : red, bgcolor = rbg, text_size = ts)
tw += wv
tl += lv
int totN = tw + tl
float winPct = totN > 0 ? tw * 100.0 / totN : 0.0
color totCol = totN == 0 ? dim : winPct > 50 ? green : winPct < 50 ? red : amber
table.cell(sb, 0, 8, totN == 0 ? (single ? "๐ Week" : "๐ Total") : "๐ " + str.tostring(winPct, "#") + "%", text_color = totCol, bgcolor = head, text_size = ts)
table.cell(sb, 1, 8, str.tostring(tw), text_color = green, bgcolor = head, text_size = ts)
table.cell(sb, 2, 8, str.tostring(tl), text_color = red, bgcolor = head, text_size = ts)
table.cell(sb, 0, 9, "๐ Outcome", text_color = color.rgb(214, 220, 234), bgcolor = head, text_size = ts, text_halign = text.align_left)
table.cell(sb, 1, 9, "Trades", text_color = dim, bgcolor = head, text_size = ts)
table.cell(sb, 2, 9, "Share", text_color = dim, bgcolor = head, text_size = ts)
oNames = array.from("๐ฏ TP Hit", "โ Partial +", "โ Partial โ", "๐ SL Hit")
oCols = array.from(green, teal, amber, red)
for k = 0 to 3
int vt = array.get(oc, k)
float pct = totN > 0 ? vt * 100.0 / totN : 0.0
int nb = int(math.round(pct / 20.0))
string meter = ""
for q = 1 to 5
meter += q <= nb ? "โฐ" : "โฑ"
color cc = array.get(oCols, k)
color rbg = k % 2 == 0 ? bg : alt
table.cell(sb, 0, 10 + k, array.get(oNames, k), text_color = cc, bgcolor = rbg, text_size = ts, text_halign = text.align_left)
table.cell(sb, 1, 10 + k, vt == 0 ? "-" : str.tostring(vt), text_color = vt == 0 ? dim : cc, bgcolor = rbg, text_size = ts)
table.cell(sb, 2, 10 + k, totN == 0 ? "โฑโฑโฑโฑโฑ" : meter + " " + str.tostring(pct, "#") + "%", text_color = totN == 0 ? dim : cc, bgcolor = sub, text_size = ts, text_halign = text.align_left)
// Layers row (only when the Side-Kick link is switched on)
int lw = 0
int ll = 0
if layersOn and lastWk >= 0
for w = firstWk to lastWk
for d = 0 to 6
lw += array.get(sbLay, (w * 7 + d) * 2)
ll += array.get(sbLay, (w * 7 + d) * 2 + 1)
if layersOn
int lt = lw + ll
table.cell(sb, 0, 14, lt == 0 ? "โ Layers" : "โ Layers " + str.tostring(lw * 100.0 / lt, "#") + "%", text_color = teal, bgcolor = head, text_size = ts, text_halign = text.align_left)
table.cell(sb, 1, 14, lw == 0 ? "-" : str.tostring(lw), text_color = lw == 0 ? dim : green, bgcolor = head, text_size = ts)
table.cell(sb, 2, 14, ll == 0 ? "-" : str.tostring(ll), text_color = ll == 0 ? dim : red, bgcolor = head, text_size = ts)
else
for col = 0 to 2
table.cell(sb, col, 14, " ", bgcolor = color.new(color.black, 100), text_size = ts)
// spacer so the TradingView footer never covers the last row
for col = 0 to 2
table.cell(sb, col, 15, " ", bgcolor = color.new(color.black, 100), text_size = ts)
One indicator for your whole timetable. It replays every chart set-up (pair, timeframe, entry method, SL / TP and hours) and shows one compact line per pair (Gold, Nasdaq, Bitcoin) plus an overall result, for the weeks you pick. Add it to any chart. It uses the Vantage feed by default. It can also show profit and loss in money: set your account balance and lot size per pair, and it adds up what your TPs and SLs earn, per pair, per week and per day. Win % is very close to each Side-Kick. It also counts layers with the Side-Kick's own layer logic: pick Relaxed, Normal or Strict, set the zone and the layer size (% of the main trade, 50 = half size), and the layer results are added to the P&L. Use the same layer settings as your Side-Kick so the numbers line up.
//@version=6
indicator("Open Legacy Master Scoreboard", overlay = true)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// OPEN LEGACY MASTER SCOREBOARD
// One indicator that replays ALL of your chart set-ups (every pair, timeframe, entry method,
// SL / TP and trading hours from your weekly schedule) and adds the results up:
// trades, wins, losses and win % per chart, per pair and in total, for as many weeks back as you pick.
// Put it on ANY chart (a daily chart is fine). Wins/losses are counted exactly like the Side-Kick Scoreboard
// (Wins = TP hit + Partial +, Losses = SL hit + Partial -), counted in the week the trade ENDS, same as the Side-Kick.
// LAYERS: uses the Side-Kick's own layer logic (zone, 9-point health check, Relaxed / Normal / Strict) on every chart.
// Same signals, same one-trade-at-a-time engine and same week counting as the Side-Kick, so trade counts match it.
// Only a candle that touches both TP and SL can differ (decided by candle colour here, 1-minute data in the Side-Kick).
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
G0 = "0. Display"
sbPeriod = input.string("Last 12 Weeks", "๐
Show Results For", options = ["This Week", "Last Week", "2 Weeks Ago", "3 Weeks Ago", "4 Weeks Ago", "Last 2 Weeks", "Last 4 Weeks", "Last 8 Weeks", "Last 12 Weeks", "All Time"], group = G0,
tooltip = "One week: This Week, Last Week, 2-4 Weeks Ago.\nSeveral weeks added up: Last 2/4/8/12 Weeks (this week included).\nAll Time: every trade the chart data holds.")
sessionTz = input.string("Europe/Dublin", "Timezone", group = G0, tooltip = "IANA timezone used for the trading hours and for the week boundaries (Monday 00:00).")
tblPos = input.string("Top Right", "Table position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = G0)
showDetail = input.bool(false, "Show every chart under its pair", group = G0, tooltip = "Off = one compact line per pair (default). On = also lists each chart under its pair.")
G0b = "0b. ๐ฐ Profit and loss"
showPnl = input.bool(true, "Show profit / loss", group = G0b, tooltip = "Adds every trade's result in money: a TP hit earns its take-profit distance, an SL hit loses its stop distance, a partial close earns or loses what it actually moved. Layers are added at the layer size below when Include layers in profit / loss is on. Spread and commission are not included.")
acctBal = input.float(1000, "Account balance", minval = 1, step = 100, group = G0b)
lotXAU = input.float(0.06, "Gold lot per trade", minval = 0.001, step = 0.01, group = G0b)
lotNAS = input.float(0.6, "Nasdaq lot per trade", minval = 0.001, step = 0.01, group = G0b)
lotBTC = input.float(0.2, "Bitcoin lot per trade", minval = 0.001, step = 0.01, group = G0b)
valXAU = input.float(100, "Gold: $ per 1.00 price move per 1 lot", minval = 0.0001, group = G0b, tooltip = "Gold on Vantage: 100 (a 1.00 move on 1 lot = $100). Check your broker's contract size.")
valNAS = input.float(1, "Nasdaq: $ per 1.00 price move per 1 lot", minval = 0.0001, group = G0b, tooltip = "Nasdaq on Vantage: usually 1 ($1 per point per lot). Check your broker's contract size.")
showRisk = input.bool(true, "Show margin and risk rows", group = G0b, tooltip = "Shows the margin your trades hold (lots x contract x price / leverage) and a verdict (SAFE / CAREFUL / DANGER). The verdict also weighs the loss if every open trade hit its stop at once. Measured against your balance after the selected period's profit, so set Account balance to your balance at the start of the period.")
levXAU = input.int(1000, "Gold leverage (1:x)", minval = 1, group = G0b, tooltip = "Check your Vantage account leverage.")
levNAS = input.int(1000, "Nasdaq leverage (1:x)", minval = 1, group = G0b)
levBTC = input.int(1000, "Bitcoin leverage (1:x)", minval = 1, group = G0b, tooltip = "Crypto leverage is usually lower. Check your account.")
maxOpen = input.int(1, "Worst case: trades open per pair at once", minval = 1, maxval = 5, group = G0b, tooltip = "1 = one trade per pair at a time. Raise it if you run overlapping charts on the same pair.")
valBTC = input.float(1, "Bitcoin: $ per 1.00 price move per 1 lot", minval = 0.0001, group = G0b, tooltip = "Bitcoin on Vantage: usually 1 ($1 per $1 move per lot). Check your broker's contract size.")
G0c = "0c. โ Layers (same logic as the Side-Kick)"
layersOn = input.bool(true, "โ Count layers", group = G0c, tooltip = "Counts layers exactly the way the Side-Kick does: one layer per trade, same TP and SL as the trade, added when the dip is in the zone and the health checks are green.")
layWhen = input.string("Normal", "How picky to be", options = ["Relaxed", "Normal", "Strict"], group = G0c, tooltip = "HOW OFTEN A LAYER OPENS.\nRelaxed = more layers.\nNormal = recommended.\nStrict = only the cleanest dips.\nUse the same setting as your Side-Kick.")
layMinIn = input.float(20, "Zone starts (% of the way to your stop)", minval = 5, maxval = 90, group = G0c, tooltip = "Same as the Side-Kick. 20 = the zone starts 20% of the way from entry to stop.")
layMaxIn = input.float(55, "Zone ends (% of the way to your stop)", minval = 10, maxval = 95, group = G0c, tooltip = "Same as the Side-Kick. Deeper than this is too close to the stop to add.")
laySizePct = input.float(50, "Layer size (% of the main trade)", minval = 1, maxval = 300, step = 5, group = G0c, tooltip = "How much of the main trade's lot a layer trades. 50 = half size, 100 = same size. Used for the layer profit / loss, which shows on the โ Layers lines.")
layPnl = input.bool(true, "Include layers in profit / loss", group = G0c, tooltip = "Adds each layer's result (its own entry to the trade's TP or SL, at the layer size above) to the P&L. Layers opened and closed inside one candle use the zone start as their entry.")
layPairs = input.bool(false, "Show layers per pair", group = G0c, tooltip = "Adds a layers line under the total for Gold, Nasdaq and Bitcoin.")
int layHealthIn = layWhen == "Relaxed" ? 45 : (layWhen == "Strict" ? 75 : 60)
G1 = "1. Symbols (Vantage feed)"
symXAU = input.symbol("VANTAGE:XAUUSD", "Gold", group = G1, tooltip = "Vantage by default. Pick the same feed your chart uses so the numbers match.")
symNAS = input.symbol("VANTAGE:NAS100", "Nasdaq (NQ)", group = G1)
symBTC = input.symbol("VANTAGE:BTCUSD", "Bitcoin", group = G1)
G2 = "2. Chart 1"
on1 = input.bool(true, "Chart 1 on", group = G2)
nm1 = input.string("XAU 15m", "Name", group = G2)
pr1 = input.string("XAU", "Pair", options = ["XAU", "NAS", "BTC"], group = G2)
tf1 = input.timeframe("15", "Timeframe", group = G2)
me1 = input.string("FVG Pullback", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G2)
se1 = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G2)
sl1 = input.float(79, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G2)
tp1 = input.float(55, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G2)
ss1 = input.text_area("Mon 0200-1200; Mon 1400-1500; Mon 1900-2200; Tue 0130-1200; Wed 0100-0700; Wed 1200-1430; Wed 1500-2100; Thu 0300-0700", "Sessions", group = G2, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G3 = "3. Chart 2"
on2 = input.bool(true, "Chart 2 on", group = G3)
nm2 = input.string("XAU 10m", "Name", group = G3)
pr2 = input.string("XAU", "Pair", options = ["XAU", "NAS", "BTC"], group = G3)
tf2 = input.timeframe("10", "Timeframe", group = G3)
me2 = input.string("EMA Trend", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G3)
se2 = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G3)
sl2 = input.float(84, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G3)
tp2 = input.float(70, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G3)
ss2 = input.text_area("Wed 1500-1600; Wed 2030-2330; Thu 0900-1130; Thu 1430-1600", "Sessions", group = G3, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G4 = "4. Chart 3"
on3 = input.bool(true, "Chart 3 on", group = G4)
nm3 = input.string("XAU Fri am 5m", "Name", group = G4)
pr3 = input.string("XAU", "Pair", options = ["XAU", "NAS", "BTC"], group = G4)
tf3 = input.timeframe("5", "Timeframe", group = G4)
me3 = input.string("EMA Trend", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G4)
se3 = input.string("Conservative", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G4)
sl3 = input.float(65, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G4)
tp3 = input.float(45, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G4)
ss3 = input.text_area("Fri 0130-0600; Fri 0730-1100", "Sessions", group = G4, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G5 = "5. Chart 4"
on4 = input.bool(true, "Chart 4 on", group = G5)
nm4 = input.string("XAU Fri pm 5m", "Name", group = G5)
pr4 = input.string("XAU", "Pair", options = ["XAU", "NAS", "BTC"], group = G5)
tf4 = input.timeframe("5", "Timeframe", group = G5)
me4 = input.string("FVG Pullback", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G5)
se4 = input.string("Conservative", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G5)
sl4 = input.float(45, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G5)
tp4 = input.float(30, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G5)
ss4 = input.text_area("Fri 1130-1800", "Sessions", group = G5, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G6 = "6. Chart 5"
on5 = input.bool(true, "Chart 5 on", group = G6)
nm5 = input.string("NQ 15m", "Name", group = G6)
pr5 = input.string("NAS", "Pair", options = ["XAU", "NAS", "BTC"], group = G6)
tf5 = input.timeframe("15", "Timeframe", group = G6)
me5 = input.string("FVG Pullback", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G6)
se5 = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G6)
sl5 = input.float(680, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G6)
tp5 = input.float(400, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G6)
ss5 = input.text_area("Mon-Wed 0200-0430; Mon-Wed 0530-0700; Mon-Wed 1100-1200; Thu-Fri 0430-1300; Mon-Fri 1700-1830; Mon-Fri 2130-2400", "Sessions", group = G6, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G7 = "7. Chart 6"
on6 = input.bool(true, "Chart 6 on", group = G7)
nm6 = input.string("NQ 10m", "Name", group = G7)
pr6 = input.string("NAS", "Pair", options = ["XAU", "NAS", "BTC"], group = G7)
tf6 = input.timeframe("10", "Timeframe", group = G7)
me6 = input.string("EMA Trend", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G7)
se6 = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G7)
sl6 = input.float(550, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G7)
tp6 = input.float(450, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G7)
ss6 = input.text_area("Mon 1300-1400; Mon 2100-2400; Tue 1200-1300; Tue 1500-1600; Tue 1700-1800; Tue 1830-2000", "Sessions", group = G7, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G8 = "8. Chart 7"
on7 = input.bool(true, "Chart 7 on", group = G8)
nm7 = input.string("BTC 15m FVG", "Name", group = G8)
pr7 = input.string("BTC", "Pair", options = ["XAU", "NAS", "BTC"], group = G8)
tf7 = input.timeframe("15", "Timeframe", group = G8)
me7 = input.string("FVG Pullback", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G8)
se7 = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G8)
sl7 = input.float(700, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G8)
tp7 = input.float(500, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G8)
ss7 = input.text_area("Mon 2200-2300; Tue 0700-0800; Wed 0600-0700; Thu 0300-0500; Thu 2100-2200", "Sessions", group = G8, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G9 = "9. Chart 8"
on8 = input.bool(true, "Chart 8 on", group = G9)
nm8 = input.string("BTC 30m EMA", "Name", group = G9)
pr8 = input.string("BTC", "Pair", options = ["XAU", "NAS", "BTC"], group = G9)
tf8 = input.timeframe("30", "Timeframe", group = G9)
me8 = input.string("EMA Trend", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G9)
se8 = input.string("Aggressive", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G9)
sl8 = input.float(800, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G9)
tp8 = input.float(800, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G9)
ss8 = input.text_area("Tue 0400-0500; Tue 0800-0900; Sun 0100-0300; Sun 2300-2400", "Sessions", group = G9, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G10 = "10. Chart 9"
on9 = input.bool(true, "Chart 9 on", group = G10)
nm9 = input.string("BTC 10m EMA", "Name", group = G10)
pr9 = input.string("BTC", "Pair", options = ["XAU", "NAS", "BTC"], group = G10)
tf9 = input.timeframe("10", "Timeframe", group = G10)
me9 = input.string("EMA Trend", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G10)
se9 = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G10)
sl9 = input.float(800, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G10)
tp9 = input.float(600, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G10)
ss9 = input.text_area("Mon 0000-0100; Mon 1800-1900; Fri 0700-0800; Fri 2200-2400", "Sessions", group = G10, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
G11 = "11. Chart 10"
on10 = input.bool(true, "Chart 10 on", group = G11)
nm10 = input.string("BTC 30m FVG", "Name", group = G11)
pr10 = input.string("BTC", "Pair", options = ["XAU", "NAS", "BTC"], group = G11)
tf10 = input.timeframe("30", "Timeframe", group = G11)
me10 = input.string("FVG Pullback", "Entry method", options = ["FVG Pullback", "EMA Trend"], group = G11)
se10 = input.string("Aggressive", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G11)
sl10 = input.float(700, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G11)
tp10 = input.float(600, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G11)
ss10 = input.text_area("Tue 1400-1500; Wed 0700-0800; Fri 1100-1200; Sat 2100-2200; Sun 2200-2300", "Sessions", group = G11, tooltip = "One session per entry, separated by ; Format: Day HHMM-HHMM (Irish time). Days: Mon, or a range like Mon-Fri, or Every Day. Example: Mon 0200-1200; Wed-Thu 1830-2030. Leave empty to trade any time.")
//โโ Shared helpers โโ
f_dayList(string opt) =>
string nm = "MonTueWedThuFriSatSun"
string res = "1234567"
if opt != "Every Day"
int a = int(str.pos(nm, str.substring(opt, 0, 3)) / 3)
int b = str.length(opt) > 3 ? int(str.pos(nm, str.substring(opt, 4, 7)) / 3) : a
res := ""
int i = a
for k = 0 to 6
res += str.tostring(i == 6 ? 1 : i + 2)
if i == b
break
i := (i + 1) % 7
res
f_hhmm(string s, int p) =>
int(str.tonumber(str.substring(s, p, p + 2)))
int sbSpan = switch sbPeriod
"Last 2 Weeks" => 2
"Last 4 Weeks" => 4
"Last 8 Weeks" => 8
"Last 12 Weeks" => 12
"All Time" => 0
=> 1
int sbWeeksBack = switch sbPeriod
"Last Week" => 1
"2 Weeks Ago" => 2
"3 Weeks Ago" => 3
"4 Weeks Ago" => 4
=> 0
// Start / end (ms) of the period being counted: weeks run Monday 00:00 to Sunday 24:00 in your timezone
f_win() =>
int dn = dayofweek(timenow, sessionTz)
int dI = dn == dayofweek.sunday ? 6 : dn - 2
int mon = timestamp(sessionTz, year(timenow, sessionTz), month(timenow, sessionTz), dayofmonth(timenow, sessionTz), 0, 0, 0) - dI * 86400000
int ws = sbSpan == 0 ? 0 : mon - (sbWeeksBack + sbSpan - 1) * 604800000
int we = mon - sbWeeksBack * 604800000 + 604800000
[ws, we]
f_fv(int f) => f == 1 ? 1.0 : f == 2 ? 0.5 : 0.0
f_isClose(string tz) =>
int dow = dayofweek(timenow, tz)
int hr = hour(timenow, tz)
bool wkB = (dow >= 2 and dow <= 6) and (hr == 22)
bool wkE = (dow == 6 and hr >= 22) or (dow == 7) or (dow == 1 and hr < 23)
wkB or wkE
bool schedClosed = f_isClose(sessionTz)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ONE CHART SET-UP, REPLAYED (runs on the chart's own symbol and timeframe)
// Returns [TP hits, SL hits, Partial +, Partial -, P&L (price units), stop distance, last price, layer wins, layer losses, layer P&L (price units)]
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
f_chart(string meth, string sens, float slP, float tpP, string sessStr, int fvgLife, float fvgMin, int emaFastL, int emaSlowL, string benchSym, bool cryOff, bool lyOn, float lyMin, float lyMax, int lyHealth) =>
// sessions, read once
var array<string> sD = array.new_string()
var array<int> sS = array.new_int()
var array<int> sE = array.new_int()
if barstate.isfirst
array<string> parts = str.split(sessStr, ";")
if array.size(parts) > 0
for i = 0 to array.size(parts) - 1
string t = str.trim(array.get(parts, i))
if str.length(t) > 8
int sp = str.pos(t, " ")
if sp > 0
string w = str.trim(str.substring(t, sp + 1))
array.push(sD, f_dayList(str.trim(str.substring(t, 0, sp))))
array.push(sS, f_hhmm(w, 0) * 60 + f_hhmm(w, 2))
array.push(sE, f_hhmm(w, 5) * 60 + f_hhmm(w, 7))
int barMins = hour(time, sessionTz) * 60 + minute(time, sessionTz)
string dowNow = str.tostring(dayofweek(time, sessionTz))
bool inHours = array.size(sD) == 0
if array.size(sD) > 0
for i = 0 to array.size(sD) - 1
int hs = array.get(sS, i)
int he = array.get(sE, i)
bool inT = he > hs ? (barMins >= hs and barMins < he) : (barMins >= hs or barMins < he)
if inT and str.contains(array.get(sD, i), dowNow)
inHours := true
// indicators
float atrV = ta.atr(14)
float ema50 = ta.ema(close, 50)
[diP, diM, adxV] = ta.dmi(14, 14)
float emaF = ta.ema(close, emaFastL)
float emaS = ta.ema(close, emaSlowL)
float rsiV = ta.rsi(close, 14)
// Side-Kick market-structure references
float plV = ta.pivotlow(low, 5, 5)
float phV = ta.pivothigh(high, 5, 5)
var float lastPL = na
var float lastPH = na
if not na(plV)
lastPL := plV
if not na(phV)
lastPH := phV
float lowN = ta.lowest(low, 10)
float highN = ta.highest(high, 10)
float rangeHi = ta.highest(high, 50)
float rangeLo = ta.lowest(low, 50)
float mF9 = ta.ema(close, 9)
float mS21 = ta.ema(close, 21)
float atrAvg = ta.sma(atrV, 50)
int timeoutBars = math.max(2, int(math.round(6.0 * 3600 / timeframe.in_seconds())))
// Side-Kick backdrop (DXY for Gold and Bitcoin, VIX for Nasdaq), inverse relationship
[bcRaw, beRaw] = request.security(benchSym, timeframe.period, [close, ta.ema(close, 9)], barmerge.gaps_off, barmerge.lookahead_off)
float bClose = nz(bcRaw, close)
float bEma = nz(beRaw, mF9)
bool bBull = ta.lowest(bClose > bEma ? 1 : 0, 3) == 1
bool bBear = ta.lowest(bClose < bEma ? 1 : 0, 3) == 1
// higher timeframe (4x) trend: previous completed candle's close vs its EMA 50
int htfSec = timeframe.in_seconds() * 4
int bucket = int(math.floor(time / 1000.0 / htfSec))
var int curB = na
var float lastC = na
var float doneC = na
var float htfE = na
if na(curB)
curB := bucket
if bucket != curB
doneC := lastC
htfE := na(htfE) ? doneC : (2.0 / 51.0) * doneC + (1.0 - 2.0 / 51.0) * htfE
curB := bucket
lastC := close
bool htfUp = not na(htfE) and doneC > htfE
bool htfDn = not na(htfE) and doneC < htfE
// FVG Pullback
var float bullTop = na
var float bullBot = na
var int bullBar = na
var float bearTop = na
var float bearBot = na
var int bearBar = na
bool fvgBuy = not na(bullBar) and bar_index - bullBar > 0 and bar_index - bullBar <= fvgLife and low <= bullTop and close > open and close > bullBot
bool fvgSell = not na(bearBar) and bar_index - bearBar > 0 and bar_index - bearBar <= fvgLife and high >= bearBot and close < open and close < bearTop
if fvgBuy
bullBar := na
if fvgSell
bearBar := na
if low > high[2] and (low - high[2]) >= fvgMin * atrV
bullBot := high[2]
bullTop := low
bullBar := bar_index
if high < low[2] and (low[2] - high) >= fvgMin * atrV
bearTop := low[2]
bearBot := high
bearBar := bar_index
// EMA Trend
bool trUp = emaF > emaS and close > emaF and rsiV > 50
bool trDn = emaF < emaS and close < emaF and rsiV < 50
bool trendBuy = trUp and not trUp[1]
bool trendSell = trDn and not trDn[1]
bool rawBuy = meth == "FVG Pullback" ? fvgBuy : trendBuy
bool rawSell = meth == "FVG Pullback" ? fvgSell : trendSell
bool qBuy = sens == "Aggressive" or (close > ema50 and (sens == "Balanced" or (htfUp and adxV >= 20)))
bool qSell = sens == "Aggressive" or (close < ema50 and (sens == "Balanced" or (htfDn and adxV >= 20)))
bool sigB = rawBuy and qBuy and inHours
bool sigS = rawSell and qSell and not (rawBuy and qBuy) and inHours
// trade replay (one trade at a time)
float tpD = tpP * 10 * syminfo.mintick
float slD = slP * 10 * syminfo.mintick
[ws, we] = f_win()
var int posDir = 0
var float posEnt = na
var int posEt = na
var int posBar = na
var int cTP = 0
var int cSL = 0
var int cPP = 0
var int cPM = 0
var float cPnL = 0.0
var int cLW = 0
var int cLL = 0
var float cLP = 0.0
var bool layOpen = false
var float layEnt = na
var bool layTaken = false
var float linkPrev = 0.0
var bool fastGate = false
var float eGuard = na
var float eBarrier = na
var int bBad = 0
// 0. Layer link from the previous candle opens the layer (same order as the Side-Kick Scoreboard)
if lyOn and posDir != 0 and not layOpen and bar_index > posBar and linkPrev == float(posDir)
layOpen := true
layEnt := close[1]
// 1. TP / SL
if posDir != 0 and bar_index > posBar
float tpL = posEnt + posDir * tpD
float slL = posEnt - posDir * slD
bool tpHit = posDir == 1 ? high >= tpL : low <= tpL
bool slHit = posDir == 1 ? low <= slL : high >= slL
if tpHit or slHit
// Both levels inside one candle: no 1-minute data here, so use the candle's likely path
// (green candle: low first, then high. Red candle: high first, then low).
bool tpFirst = tpHit and (not slHit or (posDir == 1 ? close < open : close > open))
// Fast layer: opened and ended inside this exit candle. Side-Kick checks 1-minute data;
// here a stop-out always passed through the zone, and a TP counts when the candle dipped into the zone first.
float zS = posEnt - posDir * slD * lyMin / 100.0
if lyOn and not layOpen and not layTaken and fastGate
bool zT = posDir == 1 ? low <= zS : high >= zS
bool zF = posDir == 1 ? close > open : close < open
if not tpFirst or (zT and zF)
layOpen := true
layTaken := true
layEnt := zS
if time >= ws and time < we
if tpFirst
cTP += 1
cPnL += tpD
else
cSL += 1
cPnL -= slD
if layOpen
if tpFirst
cLW += 1
cLP += (tpL - layEnt) * posDir
else
cLL += 1
cLP += (slL - layEnt) * posDir
layOpen := false
posDir := 0
// 2. Entries (candle close only)
if barstate.isconfirmed
int want = sigB ? 1 : sigS ? -1 : 0
if want != 0 and want != posDir
if posDir != 0 and time >= ws and time < we
if (close - posEnt) * posDir > 0
cPP += 1
else
cPM += 1
cPnL += (close - posEnt) * posDir
if layOpen
if (close - layEnt) * posDir > 0
cLW += 1
else
cLL += 1
cLP += (close - layEnt) * posDir
layOpen := false
posDir := want
posEnt := close
posEt := time
posBar := bar_index
layTaken := false
bBad := 0
if want == 1
float cand = (not na(lastPL) and lastPL <= close - 0.3 * atrV and lastPL >= close - 3 * atrV) ? lastPL : math.min(lowN, close - 0.3 * atrV)
eGuard := cand
float b1 = (not na(lastPH) and lastPH > close and lastPH < close + tpD) ? lastPH : 1e10
float b2 = (rangeHi > close and rangeHi < close + tpD) ? rangeHi : 1e10
float bb = math.min(b1, b2)
eBarrier := bb >= 1e10 ? na : bb
else
float cand = (not na(lastPH) and lastPH >= close + 0.3 * atrV and lastPH <= close + 3 * atrV) ? lastPH : math.max(highN, close + 0.3 * atrV)
eGuard := cand
float b1 = (not na(lastPL) and lastPL < close and lastPL > close - tpD) ? lastPL : -1e10
float b2 = (rangeLo < close and rangeLo > close - tpD) ? rangeLo : -1e10
float bb = math.max(b1, b2)
eBarrier := bb <= -1e10 ? na : bb
// 3. Side-Kick health checks on the open trade -> layer link for the next candle
float linkNow = 0.0
bool gateNow = false
if lyOn and posDir != 0
float dirV = posDir * 1.0
float slPrice = posEnt - dirV * slD
float pnlV = dirV * (close - posEnt)
float ddF = pnlV < 0 ? -pnlV / slD : 0.0
float prF = pnlV > 0 ? pnlV / tpD : 0.0
int barsIn = bar_index - posBar
int fPos = pnlV >= 0 ? 1 : (ddF < 0.25 ? 1 : (ddF < 0.6 ? 2 : 3))
float guardGap = dirV * (close - eGuard)
int fStruct = guardGap <= 0 ? 3 : (guardGap < 0.25 * atrV ? 2 : 1)
int fSL = dirV * (eGuard - slPrice) >= 0 ? 1 : 2
bool barCl = not na(eBarrier) and dirV * (close - eBarrier) > 0
int fTP = (na(eBarrier) or barCl) ? 1 : 2
bool alP = dirV * (close - mS21) > 0
bool alR = dirV * (rsiV - 50) > 0
bool alF = dirV * (mF9 - mS21) > 0
int momCnt = (alP ? 1 : 0) + (alR ? 1 : 0) + (alF ? 1 : 0)
int fMom = (momCnt == 3 or (momCnt == 2 and alP)) ? 1 : (momCnt == 0 ? 3 : 2)
bool htfWith = posDir == 1 ? htfUp : htfDn
bool htfOpp = posDir == 1 ? htfDn : htfUp
int fHtf = htfWith ? 1 : (htfOpp ? 3 : 2)
bool diAl = posDir == 1 ? diP > diM : diM > diP
int fStr = (adxV >= 20 and diAl) ? 1 : ((adxV >= 25 and not diAl) ? 3 : 2)
bool bOk = posDir == 1 ? bBear : bBull
bBad := (bOk or cryOff) ? 0 : bBad + 1
int fBack = bBad == 0 ? 1 : (bBad <= 6 ? 2 : 3)
bool rej1 = barsIn >= 1 and dirV * (open - close) >= 1.2 * atrV
bool rej2 = barsIn >= 2 and dirV * (open[1] - close[1]) >= 1.2 * atrV
bool rej3 = barsIn >= 3 and dirV * (open[2] - close[2]) >= 1.2 * atrV
bool rejected = rej1 or rej2 or rej3
bool volSpike = atrV > 1.8 * atrAvg
int fPace = rejected ? 3 : ((barsIn > timeoutBars and prF < 0.3) ? (ddF > 0.4 ? 3 : 2) : (volSpike ? 2 : 1))
float health = 100.0 * (1.5 * f_fv(fPos) + 2.0 * f_fv(fStruct) + 0.5 * f_fv(fSL) + 0.5 * f_fv(fTP) + 1.5 * f_fv(fMom) + 1.0 * f_fv(fHtf) + 1.0 * f_fv(fStr) + 1.0 * f_fv(fBack) + 1.0 * f_fv(fPace)) / 10.0
bool hardRed = fStruct == 3 or (fMom == 3 and fHtf == 3) or ddF > 0.8 or (fHtf == 3 and ddF >= 0.25)
bool layerOK = pnlV < 0 and ddF * 100 >= lyMin and ddF * 100 <= lyMax and fStruct < 3 and fHtf == 1 and fMom < 3 and fStr < 3 and fPace < 3 and health >= lyHealth
bool verdict1 = not (hardRed or health < 40) and layerOK
float ddWorst = math.max(0.0, -dirV * ((posDir == 1 ? low : high) - posEnt) / slD)
float ddBest = math.max(0.0, -dirV * ((posDir == 1 ? high : low) - posEnt) / slD)
bool layerOKh = not hardRed and health >= lyHealth and fStruct < 3 and fHtf == 1 and fMom < 3 and fStr < 3 and fPace < 3 and ddWorst * 100 >= lyMin and ddBest * 100 <= lyMax
gateNow := not hardRed and health >= lyHealth and fStruct < 3 and fHtf == 1 and fMom < 3 and fStr < 3 and fPace < 3
if barstate.isconfirmed and bar_index > posBar and (verdict1 or layerOKh) and not layTaken
layTaken := true
linkNow := dirV
linkPrev := linkNow
fastGate := gateNow
[cTP, cSL, cPP, cPM, cPnL, slD, close, cLW, cLL, cLP]
int life1 = se1 == "Aggressive" ? 12 : se1 == "Balanced" ? 24 : 40
float fmin1 = se1 == "Aggressive" ? 0.10 : se1 == "Balanced" ? 0.25 : 0.40
int ef1 = se1 == "Aggressive" ? 8 : se1 == "Balanced" ? 13 : 21
int es1 = se1 == "Aggressive" ? 21 : se1 == "Balanced" ? 34 : 55
string sy1 = pr1 == "XAU" ? symXAU : pr1 == "NAS" ? symNAS : symBTC
string bs1 = pr1 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp1h, sl1h, pp1h, pm1h, pn1h, sd1h, px1h, lw1h, ll1h, lp1h] = request.security(sy1, tf1, f_chart(me1, se1, sl1, tp1, ss1, life1, fmin1, ef1, es1, bs1, pr1 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life2 = se2 == "Aggressive" ? 12 : se2 == "Balanced" ? 24 : 40
float fmin2 = se2 == "Aggressive" ? 0.10 : se2 == "Balanced" ? 0.25 : 0.40
int ef2 = se2 == "Aggressive" ? 8 : se2 == "Balanced" ? 13 : 21
int es2 = se2 == "Aggressive" ? 21 : se2 == "Balanced" ? 34 : 55
string sy2 = pr2 == "XAU" ? symXAU : pr2 == "NAS" ? symNAS : symBTC
string bs2 = pr2 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp2h, sl2h, pp2h, pm2h, pn2h, sd2h, px2h, lw2h, ll2h, lp2h] = request.security(sy2, tf2, f_chart(me2, se2, sl2, tp2, ss2, life2, fmin2, ef2, es2, bs2, pr2 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life3 = se3 == "Aggressive" ? 12 : se3 == "Balanced" ? 24 : 40
float fmin3 = se3 == "Aggressive" ? 0.10 : se3 == "Balanced" ? 0.25 : 0.40
int ef3 = se3 == "Aggressive" ? 8 : se3 == "Balanced" ? 13 : 21
int es3 = se3 == "Aggressive" ? 21 : se3 == "Balanced" ? 34 : 55
string sy3 = pr3 == "XAU" ? symXAU : pr3 == "NAS" ? symNAS : symBTC
string bs3 = pr3 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp3h, sl3h, pp3h, pm3h, pn3h, sd3h, px3h, lw3h, ll3h, lp3h] = request.security(sy3, tf3, f_chart(me3, se3, sl3, tp3, ss3, life3, fmin3, ef3, es3, bs3, pr3 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life4 = se4 == "Aggressive" ? 12 : se4 == "Balanced" ? 24 : 40
float fmin4 = se4 == "Aggressive" ? 0.10 : se4 == "Balanced" ? 0.25 : 0.40
int ef4 = se4 == "Aggressive" ? 8 : se4 == "Balanced" ? 13 : 21
int es4 = se4 == "Aggressive" ? 21 : se4 == "Balanced" ? 34 : 55
string sy4 = pr4 == "XAU" ? symXAU : pr4 == "NAS" ? symNAS : symBTC
string bs4 = pr4 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp4h, sl4h, pp4h, pm4h, pn4h, sd4h, px4h, lw4h, ll4h, lp4h] = request.security(sy4, tf4, f_chart(me4, se4, sl4, tp4, ss4, life4, fmin4, ef4, es4, bs4, pr4 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life5 = se5 == "Aggressive" ? 12 : se5 == "Balanced" ? 24 : 40
float fmin5 = se5 == "Aggressive" ? 0.10 : se5 == "Balanced" ? 0.25 : 0.40
int ef5 = se5 == "Aggressive" ? 8 : se5 == "Balanced" ? 13 : 21
int es5 = se5 == "Aggressive" ? 21 : se5 == "Balanced" ? 34 : 55
string sy5 = pr5 == "XAU" ? symXAU : pr5 == "NAS" ? symNAS : symBTC
string bs5 = pr5 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp5h, sl5h, pp5h, pm5h, pn5h, sd5h, px5h, lw5h, ll5h, lp5h] = request.security(sy5, tf5, f_chart(me5, se5, sl5, tp5, ss5, life5, fmin5, ef5, es5, bs5, pr5 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life6 = se6 == "Aggressive" ? 12 : se6 == "Balanced" ? 24 : 40
float fmin6 = se6 == "Aggressive" ? 0.10 : se6 == "Balanced" ? 0.25 : 0.40
int ef6 = se6 == "Aggressive" ? 8 : se6 == "Balanced" ? 13 : 21
int es6 = se6 == "Aggressive" ? 21 : se6 == "Balanced" ? 34 : 55
string sy6 = pr6 == "XAU" ? symXAU : pr6 == "NAS" ? symNAS : symBTC
string bs6 = pr6 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp6h, sl6h, pp6h, pm6h, pn6h, sd6h, px6h, lw6h, ll6h, lp6h] = request.security(sy6, tf6, f_chart(me6, se6, sl6, tp6, ss6, life6, fmin6, ef6, es6, bs6, pr6 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life7 = se7 == "Aggressive" ? 12 : se7 == "Balanced" ? 24 : 40
float fmin7 = se7 == "Aggressive" ? 0.10 : se7 == "Balanced" ? 0.25 : 0.40
int ef7 = se7 == "Aggressive" ? 8 : se7 == "Balanced" ? 13 : 21
int es7 = se7 == "Aggressive" ? 21 : se7 == "Balanced" ? 34 : 55
string sy7 = pr7 == "XAU" ? symXAU : pr7 == "NAS" ? symNAS : symBTC
string bs7 = pr7 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp7h, sl7h, pp7h, pm7h, pn7h, sd7h, px7h, lw7h, ll7h, lp7h] = request.security(sy7, tf7, f_chart(me7, se7, sl7, tp7, ss7, life7, fmin7, ef7, es7, bs7, pr7 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life8 = se8 == "Aggressive" ? 12 : se8 == "Balanced" ? 24 : 40
float fmin8 = se8 == "Aggressive" ? 0.10 : se8 == "Balanced" ? 0.25 : 0.40
int ef8 = se8 == "Aggressive" ? 8 : se8 == "Balanced" ? 13 : 21
int es8 = se8 == "Aggressive" ? 21 : se8 == "Balanced" ? 34 : 55
string sy8 = pr8 == "XAU" ? symXAU : pr8 == "NAS" ? symNAS : symBTC
string bs8 = pr8 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp8h, sl8h, pp8h, pm8h, pn8h, sd8h, px8h, lw8h, ll8h, lp8h] = request.security(sy8, tf8, f_chart(me8, se8, sl8, tp8, ss8, life8, fmin8, ef8, es8, bs8, pr8 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life9 = se9 == "Aggressive" ? 12 : se9 == "Balanced" ? 24 : 40
float fmin9 = se9 == "Aggressive" ? 0.10 : se9 == "Balanced" ? 0.25 : 0.40
int ef9 = se9 == "Aggressive" ? 8 : se9 == "Balanced" ? 13 : 21
int es9 = se9 == "Aggressive" ? 21 : se9 == "Balanced" ? 34 : 55
string sy9 = pr9 == "XAU" ? symXAU : pr9 == "NAS" ? symNAS : symBTC
string bs9 = pr9 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp9h, sl9h, pp9h, pm9h, pn9h, sd9h, px9h, lw9h, ll9h, lp9h] = request.security(sy9, tf9, f_chart(me9, se9, sl9, tp9, ss9, life9, fmin9, ef9, es9, bs9, pr9 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int life10 = se10 == "Aggressive" ? 12 : se10 == "Balanced" ? 24 : 40
float fmin10 = se10 == "Aggressive" ? 0.10 : se10 == "Balanced" ? 0.25 : 0.40
int ef10 = se10 == "Aggressive" ? 8 : se10 == "Balanced" ? 13 : 21
int es10 = se10 == "Aggressive" ? 21 : se10 == "Balanced" ? 34 : 55
string sy10 = pr10 == "XAU" ? symXAU : pr10 == "NAS" ? symNAS : symBTC
string bs10 = pr10 == "NAS" ? "TVC:VIX" : "TVC:DXY"
[tp10h, sl10h, pp10h, pm10h, pn10h, sd10h, px10h, lw10h, ll10h, lp10h] = request.security(sy10, tf10, f_chart(me10, se10, sl10, tp10, ss10, life10, fmin10, ef10, es10, bs10, pr10 == "BTC" and schedClosed, layersOn, layMinIn, layMaxIn, layHealthIn), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// ๐ TABLE
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
f_pos(string p) =>
switch p
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.top_right
int nOn = (on1 ? 1 : 0) + (on2 ? 1 : 0) + (on3 ? 1 : 0) + (on4 ? 1 : 0) + (on5 ? 1 : 0) + (on6 ? 1 : 0) + (on7 ? 1 : 0) + (on8 ? 1 : 0) + (on9 ? 1 : 0) + (on10 ? 1 : 0)
int nPairs = ((on1 and pr1 == "XAU") or (on2 and pr2 == "XAU") or (on3 and pr3 == "XAU") or (on4 and pr4 == "XAU") or (on5 and pr5 == "XAU") or (on6 and pr6 == "XAU") or (on7 and pr7 == "XAU") or (on8 and pr8 == "XAU") or (on9 and pr9 == "XAU") or (on10 and pr10 == "XAU") ? 1 : 0) + ((on1 and pr1 == "NAS") or (on2 and pr2 == "NAS") or (on3 and pr3 == "NAS") or (on4 and pr4 == "NAS") or (on5 and pr5 == "NAS") or (on6 and pr6 == "NAS") or (on7 and pr7 == "NAS") or (on8 and pr8 == "NAS") or (on9 and pr9 == "NAS") or (on10 and pr10 == "NAS") ? 1 : 0) + ((on1 and pr1 == "BTC") or (on2 and pr2 == "BTC") or (on3 and pr3 == "BTC") or (on4 and pr4 == "BTC") or (on5 and pr5 == "BTC") or (on6 and pr6 == "BTC") or (on7 and pr7 == "BTC") or (on8 and pr8 == "BTC") or (on9 and pr9 == "BTC") or (on10 and pr10 == "BTC") ? 1 : 0)
int nRows = 1 + nPairs + 1 + (layersOn ? 1 : 0) + (layersOn and layPairs ? nPairs : 0) + (showPnl ? 3 : 0) + (showRisk ? 1 : 0) + (showDetail ? nOn : 0)
var table tb = table.new(position.top_right, 4, nRows, border_width = 1, frame_width = 2, frame_color = color.new(#2A3350, 0), border_color = color.new(#1C2334, 0))
f_cell(int c, int r, string txt, color tc, color bg) =>
table.cell(tb, c, r, txt, text_color = tc, bgcolor = bg, text_size = size.small, text_halign = c == 0 ? text.align_left : text.align_center)
f_money(float v) =>
(v < 0 ? "-$" : "+$") + str.tostring(math.abs(v), "#,###")
f_pcCol(float pc, int n) =>
n == 0 ? color.rgb(118, 126, 146) : pc >= 70 ? color.rgb(47, 212, 128) : pc >= 60 ? color.rgb(245, 185, 66) : color.rgb(255, 93, 108)
if barstate.islast
color bg = color.new(#0E1320, 0)
color alt = color.new(#121829, 0)
color head = color.new(#18203A, 0)
color green = color.rgb(47, 212, 128)
color red = color.rgb(255, 93, 108)
color dim = color.rgb(118, 126, 146)
color wht = color.rgb(214, 220, 234)
table.set_position(tb, f_pos(tblPos))
string hdr = sbSpan == 0 ? "๐
All" : sbSpan == 1 ? (sbWeeksBack == 0 ? "๐
This Wk" : sbWeeksBack == 1 ? "๐
Last Wk" : "๐
" + str.tostring(sbWeeksBack) + " Wks Ago") : "๐
" + str.tostring(sbSpan) + " Wks"
f_cell(0, 0, hdr, wht, head)
f_cell(1, 0, "Win%", wht, head)
f_cell(2, 0, "โ
/ โ", wht, head)
f_cell(3, 0, showPnl ? "๐ฐ P&L" : " ", wht, head)
array<bool> ons = array.from(on1, on2, on3, on4, on5, on6, on7, on8, on9, on10)
array<string> nms = array.from(nm1, nm2, nm3, nm4, nm5, nm6, nm7, nm8, nm9, nm10)
array<string> prs = array.from(pr1, pr2, pr3, pr4, pr5, pr6, pr7, pr8, pr9, pr10)
array<int> ws_ = array.from(tp1h + pp1h, tp2h + pp2h, tp3h + pp3h, tp4h + pp4h, tp5h + pp5h, tp6h + pp6h, tp7h + pp7h, tp8h + pp8h, tp9h + pp9h, tp10h + pp10h)
array<int> ls_ = array.from(sl1h + pm1h, sl2h + pm2h, sl3h + pm3h, sl4h + pm4h, sl5h + pm5h, sl6h + pm6h, sl7h + pm7h, sl8h + pm8h, sl9h + pm9h, sl10h + pm10h)
array<float> pu_ = array.from(pn1h, pn2h, pn3h, pn4h, pn5h, pn6h, pn7h, pn8h, pn9h, pn10h)
array<int> lw_ = array.from(lw1h, lw2h, lw3h, lw4h, lw5h, lw6h, lw7h, lw8h, lw9h, lw10h)
array<int> ll_ = array.from(ll1h, ll2h, ll3h, ll4h, ll5h, ll6h, ll7h, ll8h, ll9h, ll10h)
array<float> lp_ = array.from(lp1h, lp2h, lp3h, lp4h, lp5h, lp6h, lp7h, lp8h, lp9h, lp10h)
array<float> sd_ = array.from(sd1h, sd2h, sd3h, sd4h, sd5h, sd6h, sd7h, sd8h, sd9h, sd10h)
array<float> px_ = array.from(px1h, px2h, px3h, px4h, px5h, px6h, px7h, px8h, px9h, px10h)
array<float> pairSd = array.from(0.0, 0.0, 0.0)
array<float> pairPx = array.from(0.0, 0.0, 0.0)
array<float> pairLev = array.from(float(levXAU), float(levNAS), float(levBTC))
array<float> pairVal = array.from(valXAU, valNAS, valBTC)
array<float> pairLot = array.from(lotXAU, lotNAS, lotBTC)
array<float> pairMult = array.from(lotXAU * valXAU, lotNAS * valNAS, lotBTC * valBTC)
array<int> pairLw = array.new_int(3, 0)
array<int> pairLl = array.new_int(3, 0)
array<bool> pairOn = array.new_bool(3, false)
array<float> pairLp = array.new_float(3, 0.0)
int row = 1
int gLW = 0
int gLL = 0
float gLP = 0.0
int gW = 0
int gL = 0
float gP = 0.0
array<string> pairs = array.from("XAU", "NAS", "BTC")
array<string> pairNames = array.from("๐ฅ Gold", "๐ Nasdaq", "โฟ Bitcoin")
for p = 0 to 2
int pw = 0
int pl = 0
float pp = 0.0
int plw = 0
int pll = 0
float plp = 0.0
int cnt = 0
for k = 0 to 9
if array.get(prs, k) == array.get(pairs, p) and array.get(ons, k)
pw += nz(array.get(ws_, k))
pl += nz(array.get(ls_, k))
pp += (nz(array.get(pu_, k)) + (layPnl ? nz(array.get(lp_, k)) * laySizePct / 100.0 : 0.0)) * array.get(pairMult, p)
plw += nz(array.get(lw_, k))
pll += nz(array.get(ll_, k))
plp += nz(array.get(lp_, k)) * laySizePct / 100.0 * array.get(pairMult, p)
cnt += 1
array.set(pairSd, p, math.max(array.get(pairSd, p), nz(array.get(sd_, k))))
array.set(pairPx, p, nz(array.get(px_, k)))
array.set(pairLw, p, plw)
array.set(pairLl, p, pll)
array.set(pairOn, p, cnt > 0)
array.set(pairLp, p, plp)
gLP += plp
gLW += plw
gLL += pll
if cnt > 0
int pn = pw + pl
float ppc = pn > 0 ? pw * 100.0 / pn : 0.0
f_cell(0, row, array.get(pairNames, p), wht, head)
f_cell(1, row, pn > 0 ? str.tostring(ppc, "#") + "%" : "-", f_pcCol(ppc, pn), head)
f_cell(2, row, str.tostring(pw) + " / " + str.tostring(pl), wht, head)
f_cell(3, row, showPnl ? f_money(pp) : " ", pp >= 0 ? green : red, head)
row += 1
gW += pw
gL += pl
gP += pp
if showDetail
for k = 0 to 9
if array.get(prs, k) == array.get(pairs, p) and array.get(ons, k)
int w = nz(array.get(ws_, k))
int l = nz(array.get(ls_, k))
int n = w + l
float pc = n > 0 ? w * 100.0 / n : 0.0
color rbg = row % 2 == 0 ? bg : alt
f_cell(0, row, " " + array.get(nms, k), dim, rbg)
f_cell(1, row, n > 0 ? str.tostring(pc, "#") + "%" : "-", f_pcCol(pc, n), rbg)
f_cell(2, row, str.tostring(w) + " / " + str.tostring(l), dim, rbg)
float kp = (nz(array.get(pu_, k)) + (layPnl ? nz(array.get(lp_, k)) * laySizePct / 100.0 : 0.0)) * array.get(pairMult, p)
f_cell(3, row, showPnl ? f_money(kp) : " ", kp >= 0 ? green : red, rbg)
row += 1
int gn = gW + gL
float gpc = gn > 0 ? gW * 100.0 / gn : 0.0
f_cell(0, row, "๐ All", wht, head)
f_cell(1, row, gn > 0 ? str.tostring(gpc, "#") + "%" : "-", f_pcCol(gpc, gn), head)
f_cell(2, row, str.tostring(gW) + " / " + str.tostring(gL), wht, head)
f_cell(3, row, showPnl ? f_money(gP) : " ", gP >= 0 ? green : red, head)
row += 1
if layersOn
color tealC = color.rgb(46, 196, 182)
int gln = gLW + gLL
float glp = gln > 0 ? gLW * 100.0 / gln : 0.0
f_cell(0, row, "โ Layers", tealC, head)
f_cell(1, row, gln > 0 ? str.tostring(glp, "#") + "%" : "-", gln == 0 ? dim : (gLP >= 0 ? green : red), head)
f_cell(2, row, str.tostring(gLW) + " / " + str.tostring(gLL), wht, head)
f_cell(3, row, gln > 0 ? f_money(gLP) : "-", gLP >= 0 ? green : red, head)
row += 1
if layPairs
for p = 0 to 2
if array.get(pairOn, p)
int lw0 = array.get(pairLw, p)
int ll0 = array.get(pairLl, p)
int ln0 = lw0 + ll0
float lp0 = ln0 > 0 ? lw0 * 100.0 / ln0 : 0.0
color rbg2 = row % 2 == 0 ? bg : alt
f_cell(0, row, " โ " + array.get(pairNames, p), dim, rbg2)
float lm0 = array.get(pairLp, p)
f_cell(1, row, ln0 > 0 ? str.tostring(lp0, "#") + "%" : "-", ln0 == 0 ? dim : (lm0 >= 0 ? green : red), rbg2)
f_cell(2, row, str.tostring(lw0) + " / " + str.tostring(ll0), dim, rbg2)
f_cell(3, row, ln0 > 0 ? f_money(lm0) : "-", lm0 >= 0 ? green : red, rbg2)
row += 1
if showPnl
float perWk = sbSpan > 0 ? gP / sbSpan : na
float perDay = sbSpan > 0 ? gP / (sbSpan * 7.0) : na
f_cell(0, row, "๐ Per week", wht, bg)
f_cell(1, row, " ", wht, bg)
f_cell(2, row, " ", wht, bg)
f_cell(3, row, na(perWk) ? "-" : f_money(perWk), perWk >= 0 ? green : red, bg)
row += 1
f_cell(0, row, "๐
Per day", wht, alt)
f_cell(1, row, " ", wht, alt)
f_cell(2, row, " ", wht, alt)
f_cell(3, row, na(perDay) ? "-" : f_money(perDay), perDay >= 0 ? green : red, alt)
row += 1
float retPct = gP * 100.0 / acctBal
f_cell(0, row, "๐ฆ Balance", wht, head)
f_cell(1, row, (retPct >= 0 ? "+" : "") + str.tostring(retPct, "#.#") + "%", retPct >= 0 ? green : red, head)
f_cell(2, row, " ", wht, head)
f_cell(3, row, "$" + str.tostring(acctBal + gP, "#,###"), wht, head)
row += 1
if showRisk
float mgn = 0.0
float worst = 0.0
for p = 0 to 2
mgn += array.get(pairLot, p) * array.get(pairVal, p) * array.get(pairPx, p) / array.get(pairLev, p)
worst += array.get(pairLot, p) * array.get(pairVal, p) * array.get(pairSd, p)
mgn *= maxOpen
worst *= maxOpen
float eqNow = math.max(acctBal + gP, 1.0)
float mgnPct = mgn * 100.0 / eqNow
float wPct = worst * 100.0 / eqNow
int lvl = wPct < 10 and mgnPct < 30 ? 0 : wPct < 25 and mgnPct < 60 ? 1 : 2
color lc = lvl == 0 ? green : lvl == 1 ? color.rgb(245, 185, 66) : red
string lt = lvl == 0 ? "๐ข SAFE" : lvl == 1 ? "๐ก CAREFUL" : "๐ด DANGER"
f_cell(0, row, "๐ก๏ธ Safety", wht, head)
f_cell(1, row, lt, lc, head)
f_cell(2, row, " ", wht, head)
table.merge_cells(tb, 1, row, 2, row)
f_cell(3, row, lvl == 0 ? "๐ Chill" : lvl == 1 ? "๐ Watch it" : "๐จ Too heavy", lc, head)
row += 1
//@version=6
indicator("Galaxy Theme", overlay=true)
// Create a 10x10 grid. The table background is 100% transparent so your candles remain completely visible!
var table space = table.new(position.top_left, 10, 10, bgcolor=color.new(color.black, 100), border_width=0)
// Deterministic seeds so the stars stay perfectly still and don't flicker when the price moves
var int seed1 = 17
var int seed2 = 23
if barstate.islast
for r = 0 to 9
for c = 0 to 9
// Complex pseudo-randomization for a highly natural scatter effect
int starRand = (r * seed1 + c * seed2) % 12
string stardust = ""
color starColor = color.new(color.white, 100)
string tSize = size.small
// Organic placement using varied line breaks (\n) and spacing so it doesn't look like a grid
if starRand == 0
stardust := "โฆ"
starColor := color.new(#babbff, 30) // Soft glowing purple
tSize := size.normal
else if starRand == 1
stardust := " \n\n โ
"
starColor := color.new(color.white, 50)
else if starRand == 2
stardust := " ยท"
starColor := color.new(#ffd1ff, 30) // Faint pink nebula dust
else if starRand == 3
stardust := " \n โฆ \n "
starColor := color.new(#9bf6ff, 30) // Distant cyan twinkle
else if starRand == 5
stardust := "โ
\n\n"
starColor := color.new(color.white, 60)
tSize := size.tiny
else if starRand == 7
stardust := " ยท "
starColor := color.new(#c8b6ff, 40) // Lavender
else
// Leave empty cells to create the dark void of deep space
stardust := ""
// THE MAGIC TRICK: width=10.0 and height=10.0 forces each cell to stretch.
// 10 cells x 10% = exactly 100% full screen coverage edge-to-edge!
table.cell(space, c, r, text=stardust, text_color=starColor, text_size=tSize, width=10.0, height=10.0)
Finish the look
Optional ยท CosmeticGalaxy Background Setupโผ
Galaxy Theme draws the stars โ this is the last step to get the deep-space look behind them, straight from TradingView's own chart settings.
Open chart settings
Click the gear icon (โ๏ธ) at the top of your chart, or right-click anywhere on the chart and choose Settings.
Go to the "Canvas" tab
This is where TradingView controls the chart's overall background.
Set Background to "Gradient"
You'll see a background style dropdown โ switch it from Solid to Gradient. Two color swatches will appear next to it.
Set the two gradient colors
Set the first color swatch to a dark purple, and the second to pure black. This gives the chart a deep-space fade that Galaxy Theme's stars sit beautifully on top of.
Build It YourselfThe Open Legacy Recipeโผ
๐ Build your own "Open Legacy" in Claude ๐
From a blank chart to your own indicators and a trading bot. Follow it step by step and have fun with it.
Tell Claude Code what you want
Open Claude Code and describe your indicator in plain words:
The time zone!
Tell Claude:
Use the same time zone in every indicator so they stay in sync. โฐ
The Side-Kick
Ask for a second indicator with identical settings that works as your Scoreboard. It tracks wins, losses, TP hits and SL hits by day and week. ๐
The Layers
In that same Side-Kick, ask for a box showing where adding to a trade makes sense, an alert when it turns green and a layers row on the Scoreboard. Use the same settings and time zone as the first indicator. ๐ฆ
Cloudflare
TradingView can't talk to MT5 directly, so you need a middleman, and Cloudflare does the job. Its free plan covers light use, but it has a 100,000 requests a day limit, so have your robot check every 5 to 10 seconds, or move to the small paid plan if you want it every second. Ask Claude:
Claude will give you the Worker code, the database table and the click-by-click setup. ๐ ๏ธ
TradingView webhook
In TradingView, create an alert on your indicator, tick Webhook URL and paste your Worker link with your secret key. Make the alert message carry the trade details (buy or sell, symbol, SL distance, TP distance, lot size) in a simple format that Claude and the robot agree on.
๐ Keep your key private and never post it anywhere. (Webhooks need a paid TradingView plan with 2FA switched on.)
MT5 Expert Advisor
Ask Claude:
In MT5, go to Tools > Options > Expert Advisors, tick Allow WebRequest and add your Worker's address. ๐
Trade while you sleep
Use the built-in MetaTrader VPS: log in to your free MQL5 account in MT5, open View > Terminal > VPS, subscribe and migrate your chart and robot with one click. It's a small monthly fee and far simpler than renting your own server. ๐ด๐ฐ
Demo first
Test everything on a DEMO account first. Check one alert end to end (TradingView > Cloudflare > MT5), then leave it running for a week or two before going anywhere near real money. ๐
๐ญ The journey
It started in ChatGPT, got new ideas in Gemini and came together in Claude. Test it, tweak it, back-test it and stay humble. No system wins every time.
๐ BUILD YOUR OWN "OPEN LEGACY" IN CLAUDE ๐ ๐ฑ Step 1: Tell Claude Code what you want. "Build me a TradingView Pine v6 indicator with two modes: FVG Pullback and EMA Trend. Add settings for up to 8 trading sessions, each with its own days and hours (at least 6). Add TP and SL inputs. Make it universal for any pair and any timeframe. Add a HUD showing market structure, the TP and SL zones and the correlated pair, adapting automatically to whatever pair is on the chart. Add alerts that send the full trade details." ๐ง ๐ Don't forget the time zone! Tell Claude: "Add a time zone setting using proper names like Europe/Dublin, Europe/Paris, America/New_York or Asia/Tokyo, so my sessions always run on MY local time, including daylight saving." Use the same time zone in every indicator so they stay in sync. โฐ ๐ Step 2: Ask for a second indicator with identical settings that works as your Scoreboard. It tracks wins, losses, TP hits and SL hits by day and week. ๐ ๐งฉ Step 3: In that same Side-Kick, ask for a box showing where adding to a trade makes sense, an alert when it turns green and a layers row on the Scoreboard. Use the same settings and time zone as the first indicator. ๐ฆ ๐ค BONUS: TURN IT INTO A BOT ๐ค โ๏ธ The relay (Cloudflare). TradingView can't talk to MT5 directly, so you need a middleman, and Cloudflare does the job. Its free plan covers light use, but it has a 100,000 requests a day limit, so have your robot check every 5 to 10 seconds, or move to the small paid plan if you want it every second. Ask Claude: "Create a Cloudflare Worker with a D1 database that receives TradingView webhook alerts, stores each signal (id, time, side, symbol, SL, TP, lots) and lets an MT5 robot fetch new signals with a secret key. Walk me through setting it up step by step, with no coding knowledge needed." Claude will give you the Worker code, the database table and the click-by-click setup. ๐ ๏ธ ๐ก The alert. In TradingView, create an alert on your indicator, tick Webhook URL and paste your Worker link with your secret key. Make the alert message carry the trade details (buy or sell, symbol, SL distance, TP distance, lot size) in a simple format that Claude and the robot agree on. ๐ Keep your key private and never post it anywhere. (Webhooks need a paid TradingView plan with 2FA switched on.) ๐ฆพ The robot (MT5 EA). Ask Claude: "Write an MQL5 Expert Advisor that polls my Cloudflare relay every few seconds and trades each new signal. Include: ๐ก๏ธ Duplicate protection, so each signal trades once, and an age limit so stale signals are ignored โ๏ธ Lot size taken from the indicator's Lot Size input (sent in the alert), so the robot has no lot setting ๐ฏ SL and TP placed exactly as the alert says, with a per-pair TP buffer to pull targets slightly closer ๐ Max open trades, plus a waiting list: when every slot is full, a new signal waits and opens when a trade ends, so no running trade is closed to make room. Plus a switch for flipping on an opposite signal ๐ฐ A news filter that reads the Forex Factory calendar through my relay and skips orange and red events, pausing new trades for a set time before and after the news (MT5's built-in calendar as the backup) ๐ Match chart move, so entries follow the actual price on the day โ An optional layering mode that adds a half-size trade with the same SL and TP when my Side-Kick alert says go (off by default) ๐ฅ๏ธ A small on-chart panel showing status, open trades and the last signal ๐ซ No DLLs, so it runs on the VPS." In MT5, go to Tools > Options > Expert Advisors, tick Allow WebRequest and add your Worker's address. ๐ ๐ The VPS. So it trades while you sleep, use the built-in MetaTrader VPS: log in to your free MQL5 account in MT5, open View > Terminal > VPS, subscribe and migrate your chart and robot with one click. It's a small monthly fee and far simpler than renting your own server. ๐ด๐ฐ ๐งช Golden rule: test everything on a DEMO account first. Check one alert end to end (TradingView > Cloudflare > MT5), then leave it running for a week or two before going anywhere near real money. ๐ ๐ญ The journey: it started in ChatGPT, got new ideas in Gemini and came together in Claude. Test it, tweak it, back-test it and stay humble. No system wins every time. Now go build your legacy! ๐๐