Complete Strategy Vault Bundle
All 16 paid Classic Pack strategies on one receipt, $149 instead of $459.
Includes 16 packs, each delivered with its own license key.
$149.00
$459.00
Opening the product…
Catalog/TradingView
The free starter: a WaveTrend-style oscillator (channel length 10, average length 21) that buys WT1/WT2 up-crosses in oversold territory and sells down-crosses in overbought territory. Pine v5 and an MT5 Python port, no payment needed.
The bundle does not add the sample curves together. Open each included starter for its own sample study, and read the caption before you compare them.
The oscillator is an EMA channel index of hlc3: esa = EMA(hlc3, 10), d = EMA(|hlc3 - esa|, 10), ci = (hlc3 - esa) / (0.015 x d), WT1 = EMA(ci, 21) and WT2 = SMA(WT1, 4).
By default a long needs WT1 to cross above WT2 while WT1 is at or below -53, and a short needs a cross below while WT1 is at or above +53. The +/-60 levels are drawn for reference, and the zone requirement can be switched off. Default risk is a 2 ATR stop and a 2R target.
Every file is an original clean-room implementation by AlgoVault of a classic, publicly known trading concept. No third-party TradingView source code is included, so there are no open-source licence obligations on the files you receive.
This is a research and education starter, not a finished system. No win rate, profit figure or backtest is claimed or included. Test it on your own data before you risk money.
Free to read, copy and download. Paste the Pine file into the TradingView Pine Editor, or run the Python module offline.
Educational software, not financial advice. Nothing here is a recommendation to buy or sell any instrument. Backtests and simulations are hypothetical, leave out slippage, spreads and fees, and past or simulated performance does not guarantee future results. Trading leveraged products can lose more than your deposit.
Yes. Download the Pine strategy, the MT5 Python module and the guide directly from this page, with no payment and no account.
No. No win rate, profit factor or equity curve is published for this pack. The code was verified for structure and behaviour on synthetic data only. Run your own backtests.
Not by default. It builds order requests and returns them in dry-run mode. Live sending needs dry_run=False and a connected MetaTrader5 terminal, and it is entirely your decision and risk.
No. It is an original clean-room implementation of a classic, publicly known concept, written from the concept alone. Check that the Pine file compiles in your TradingView Pine Editor before use.
All 16 paid Classic Pack strategies on one receipt, $149 instead of $459.
Includes 16 packs, each delivered with its own license key.
$149.00
$459.00
//@version=5
// WaveTrend Oscillator Strategy Pack - AlgoVault Classic Pack (Pine v5 strategy)
// (c) 2026 AlgoVault. All rights reserved. Commercial license for AlgoVault customers.
// Original clean-room implementation by AlgoVault, inspired by classic, publicly known trading concepts (hlc3 EMA channel oscillator (10/21), WT1/WT2 crosses inside +/-53 and +/-60 bands). No third-party TradingView source code was copied; this file is free of CC BY-NC-SA / MPL / GPL obligations and is licensed commercially to AlgoVault customers.
// Concept: hlc3 EMA channel oscillator (10/21), WT1/WT2 crosses inside +/-53 and +/-60 bands.
// Execution: decisions on confirmed bar close (barstate.isconfirmed), fills at next bar open,
// calc_on_every_tick = false, process_orders_on_close = false, no request.security / lookahead, no repainting.
// Educational software. Not financial advice. Past or simulated performance does not guarantee future results.
strategy("AlgoVault - WaveTrend Oscillator Strategy Pack", shorttitle = "AV WaveTrend", overlay = true, initial_capital = 10000, default_qty_type = strategy.fixed, default_qty_value = 1, pyramiding = 0, calc_on_every_tick = false, process_orders_on_close = false, commission_type = strategy.commission.percent, commission_value = 0.02, slippage = 1, max_bars_back = 1000)
// ===================================================================================================
// Risk, sizing and execution inputs (shared AlgoVault engine)
// ===================================================================================================
grpRisk = "Risk & Execution"
allowLong = input.bool(true, "Allow Longs", group = grpRisk)
allowShort = input.bool(true, "Allow Shorts", group = grpRisk)
useExitSignals = input.bool(true, "Close On Exit Signal", group = grpRisk)
slMode = input.string("ATR", "Stop Mode", options = ["ATR", "Percent", "Structure", "None"], group = grpRisk)
slPct = input.float(1.0, "Stop %", minval = 0.01, step = 0.1, group = grpRisk)
atrLen = input.int(14, "Risk ATR Length", minval = 1, group = grpRisk)
atrSlMult = input.float(2.0, "ATR Stop Multiplier", minval = 0.1, step = 0.1, group = grpRisk)
tpMode = input.string("R-Multiple", "Target Mode", options = ["R-Multiple", "ATR", "Percent", "Structure", "None"], group = grpRisk)
tpPct = input.float(2.0, "Target %", minval = 0.01, step = 0.1, group = grpRisk)
atrTpMult = input.float(3.0, "ATR Target Multiplier", minval = 0.1, step = 0.1, group = grpRisk)
rrMult = input.float(2.0, "Single Target R", minval = 0.1, step = 0.1, group = grpRisk)
useMultiTp = input.bool(false, "TP1 / TP2 / TP3 Partials (R-Multiple mode)", group = grpRisk)
tp1R = input.float(1.0, "TP1 R", minval = 0.1, step = 0.1, group = grpRisk)
tp2R = input.float(2.0, "TP2 R", minval = 0.1, step = 0.1, group = grpRisk)
tp3R = input.float(3.0, "TP3 R", minval = 0.1, step = 0.1, group = grpRisk)
tp1Pct = input.float(40.0, "TP1 Close %", minval = 1, maxval = 100, group = grpRisk)
tp2Pct = input.float(30.0, "TP2 Close %", minval = 1, maxval = 100, group = grpRisk)
sizeMode = input.string("Risk %", "Position Sizing", options = ["Risk %", "% Equity", "Fixed"], group = grpRisk)
riskPct = input.float(1.0, "Risk % Of Equity", minval = 0.01, step = 0.1, group = grpRisk)
equityPct = input.float(10.0, "% Of Equity", minval = 0.1, step = 1, group = grpRisk)
fixedQty = input.float(1.0, "Fixed Quantity", minval = 0.0001, group = grpRisk)
maxLeverage = input.float(5.0, "Max Leverage Cap", minval = 0.1, step = 0.5, group = grpRisk)
grpInd = "Indicator"
// ===================================================================================================
// WaveTrend Oscillator Strategy Pack: indicator + signal block
// ===================================================================================================
wtN1 = input.int(10, "Channel Length", minval = 1, group = grpInd)
wtN2 = input.int(21, "Average Length", minval = 1, group = grpInd)
wtOb1 = input.float(60, "Overbought Level 1", group = grpInd)
wtOb2 = input.float(53, "Overbought Level 2", group = grpInd)
wtOs1 = input.float(-60, "Oversold Level 1", group = grpInd)
wtOs2 = input.float(-53, "Oversold Level 2", group = grpInd)
wtRequireZone = input.bool(true, "Only Cross Beyond Level 2", group = grpInd)
wtAp = hlc3
wtEsa = ta.ema(wtAp, wtN1)
wtD = ta.ema(math.abs(wtAp - wtEsa), wtN1)
wtCi = wtD > 0 ? (wtAp - wtEsa) / (0.015 * wtD) : na
wt1 = ta.ema(wtCi, wtN2)
wt2 = ta.sma(wt1, 4)
wtUp = ta.crossover(wt1, wt2)
wtDn = ta.crossunder(wt1, wt2)
bool longEntry = wtUp and (not wtRequireZone or wt1 <= wtOs2)
bool shortEntry = wtDn and (not wtRequireZone or wt1 >= wtOb2)
bool longExit = shortEntry
bool shortExit = longEntry
float longStructStop = na
float shortStructStop = na
float longStructTp = na
float shortStructTp = na
// Oscillator values are shown in the Data Window (overlay strategy keeps price-scale plots clean)
plot(wt1, "WT1", color.new(color.teal, 0), display = display.data_window)
plot(wt2, "WT2", color.new(color.orange, 0), display = display.data_window)
plot(wtOb1, "OB1", display = display.data_window)
plot(wtOs1, "OS1", display = display.data_window)
// ===================================================================================================
// Shared execution engine: bar-close decisions, fills at next open, SL / TP / sizing, alerts
// ===================================================================================================
atrR = ta.atr(atrLen)
f_stop(bool isLong, float ref, float structStop) =>
float dir = isLong ? 1.0 : -1.0
float atrStop = ref - dir * atrR * atrSlMult
float s = na
if slMode == "ATR"
s := atrStop
else if slMode == "Percent"
s := ref * (1 - dir * slPct / 100)
else if slMode == "Structure"
bool validS = not na(structStop) and (isLong ? structStop < ref : structStop > ref)
s := validS ? structStop : atrStop
s
f_target(bool isLong, float ref, float stopPx, float rMult, float structTp) =>
float dir = isLong ? 1.0 : -1.0
float risk = na(stopPx) ? atrR * atrSlMult : math.abs(ref - stopPx)
float t = na
if tpMode == "R-Multiple"
t := ref + dir * rMult * risk
else if tpMode == "ATR"
t := ref + dir * atrR * atrTpMult
else if tpMode == "Percent"
t := ref * (1 + dir * tpPct / 100)
else if tpMode == "Structure"
bool validT = not na(structTp) and (isLong ? structTp > ref : structTp < ref)
t := validT ? structTp : ref + dir * rrMult * risk
t
f_qty(float ref, float stopPx) =>
float q = fixedQty
if sizeMode == "% Equity"
q := strategy.equity * equityPct / 100 / ref
else if sizeMode == "Risk %"
float dist = na(stopPx) ? atrR * atrSlMult : math.abs(ref - stopPx)
q := dist > 0 ? strategy.equity * riskPct / 100 / dist : fixedQty
q := math.min(q, strategy.equity * maxLeverage / ref)
math.max(q, 0)
bool multiOn = useMultiTp and tpMode == "R-Multiple"
var float lStop = na
var float lTp1 = na
var float lTp2 = na
var float lTp3 = na
var float sStop = na
var float sTp1 = na
var float sTp2 = na
var float sTp3 = na
bool goLong = barstate.isconfirmed and allowLong and longEntry and strategy.position_size <= 0
bool goShort = barstate.isconfirmed and allowShort and shortEntry and strategy.position_size >= 0 and not goLong
if goLong
lStop := f_stop(true, close, longStructStop)
lTp1 := f_target(true, close, lStop, multiOn ? tp1R : rrMult, longStructTp)
lTp2 := multiOn ? f_target(true, close, lStop, tp2R, longStructTp) : na
lTp3 := multiOn ? f_target(true, close, lStop, tp3R, longStructTp) : na
strategy.entry("Long", strategy.long, qty = f_qty(close, lStop), comment = "BUY")
alert("AV WaveTrend BUY " + syminfo.ticker + " @ " + str.tostring(close) + " SL " + str.tostring(lStop) + " TP " + str.tostring(lTp1), alert.freq_once_per_bar_close)
if goShort
sStop := f_stop(false, close, shortStructStop)
sTp1 := f_target(false, close, sStop, multiOn ? tp1R : rrMult, shortStructTp)
sTp2 := multiOn ? f_target(false, close, sStop, tp2R, shortStructTp) : na
sTp3 := multiOn ? f_target(false, close, sStop, tp3R, shortStructTp) : na
strategy.entry("Short", strategy.short, qty = f_qty(close, sStop), comment = "SELL")
alert("AV WaveTrend SELL " + syminfo.ticker + " @ " + str.tostring(close) + " SL " + str.tostring(sStop) + " TP " + str.tostring(sTp1), alert.freq_once_per_bar_close)
bool longOpen = strategy.position_size > 0 or goLong
bool shortOpen = strategy.position_size < 0 or goShort
if longOpen and not goShort and (not na(lStop) or not na(lTp1))
if multiOn
strategy.exit("L-TP1", "Long", qty_percent = tp1Pct, stop = lStop, limit = lTp1, comment = "L TP1/SL")
strategy.exit("L-TP2", "Long", qty_percent = tp2Pct, stop = lStop, limit = lTp2, comment = "L TP2/SL")
strategy.exit("L-TP3", "Long", stop = lStop, limit = lTp3, comment = "L TP3/SL")
else
strategy.exit("L-Exit", "Long", stop = lStop, limit = lTp1, comment = "L SL/TP")
if shortOpen and not goLong and (not na(sStop) or not na(sTp1))
if multiOn
strategy.exit("S-TP1", "Short", qty_percent = tp1Pct, stop = sStop, limit = sTp1, comment = "S TP1/SL")
strategy.exit("S-TP2", "Short", qty_percent = tp2Pct, stop = sStop, limit = sTp2, comment = "S TP2/SL")
strategy.exit("S-TP3", "Short", stop = sStop, limit = sTp3, comment = "S TP3/SL")
else
strategy.exit("S-Exit", "Short", stop = sStop, limit = sTp1, comment = "S SL/TP")
if barstate.isconfirmed and useExitSignals and strategy.position_size > 0 and longExit and not goShort
strategy.close("Long", comment = "Exit signal")
alert("AV WaveTrend EXIT LONG " + syminfo.ticker + " @ " + str.tostring(close), alert.freq_once_per_bar_close)
if barstate.isconfirmed and useExitSignals and strategy.position_size < 0 and shortExit and not goLong
strategy.close("Short", comment = "Exit signal")
alert("AV WaveTrend EXIT SHORT " + syminfo.ticker + " @ " + str.tostring(close), alert.freq_once_per_bar_close)
plotshape(goLong, "BUY", shape.triangleup, location.belowbar, color.new(color.lime, 0), size = size.small)
plotshape(goShort, "SELL", shape.triangledown, location.abovebar, color.new(color.red, 0), size = size.small)
plot(strategy.position_size > 0 ? lStop : strategy.position_size < 0 ? sStop : na, "Active Stop", color.new(color.orange, 0), 1, plot.style_linebr)
plot(strategy.position_size > 0 ? lTp1 : strategy.position_size < 0 ? sTp1 : na, "Active TP1", color.new(color.aqua, 0), 1, plot.style_linebr)
#!/usr/bin/env python3
"""
WaveTrend Oscillator Strategy Pack -> standalone MetaTrader 5 Python port (AlgoVault Classic Pack).
(c) 2026 AlgoVault. All rights reserved. Commercial license for AlgoVault customers.
Original clean-room implementation by AlgoVault, inspired by classic, publicly known trading concepts (hlc3 EMA channel oscillator (10/21), WT1/WT2 crosses inside +/-53 and +/-60 bands). No third-party TradingView source code was copied; this file is free of CC BY-NC-SA / MPL / GPL obligations and is licensed commercially to AlgoVault customers.
Category: Momentum Oscillator
Concept: hlc3 EMA channel oscillator (10/21), WT1/WT2 crosses inside +/-53 and +/-60 bands.
Layout
1. Bars container + Pine-compatible series helpers (pure numpy / stdlib)
2. RiskConfig + stop / target / size maths (same rules as the Pine strategy)
3. Indicator + signal engine (compute -> Signals)
4. Offline bar simulator (signal at close, fill at next open, stop before targets)
5. MetaTrader 5 order-request scaffolding, DRY-RUN by default; only closed bars are evaluated
Educational software. Not financial advice. Past or simulated performance does not guarantee future results.
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
try: # pragma: no cover - MetaTrader5 only exists on Windows machines with a terminal installed
import MetaTrader5 as mt5 # type: ignore
except Exception: # noqa: BLE001
mt5 = None
NAN = float("nan")
# ======================================================================================================
# 1. Bars container + Pine-compatible series helpers (pure numpy / stdlib, causal, NaN == Pine na)
# ======================================================================================================
@dataclass
class Bars:
"""OHLCV(+time) arrays. time = bar OPEN time, epoch seconds (UTC)."""
open: np.ndarray
high: np.ndarray
low: np.ndarray
close: np.ndarray
volume: np.ndarray
time: np.ndarray
@classmethod
def from_arrays(cls, open_, high, low, close, volume=None, time=None) -> "Bars":
o = np.asarray(open_, dtype=float)
n = len(o)
v = np.zeros(n) if volume is None else np.asarray(volume, dtype=float)
t = (np.arange(n, dtype=np.int64) * 900) if time is None else np.asarray(time, dtype=np.int64)
return cls(o, np.asarray(high, dtype=float), np.asarray(low, dtype=float), np.asarray(close, dtype=float), v, t)
@classmethod
def from_mt5_rates(cls, rates) -> "Bars":
"""Convert the structured array returned by mt5.copy_rates_* into Bars."""
vol = rates["real_volume"] if "real_volume" in rates.dtype.names and np.any(rates["real_volume"]) else rates["tick_volume"]
return cls.from_arrays(rates["open"], rates["high"], rates["low"], rates["close"], vol, rates["time"])
def __len__(self) -> int:
return len(self.close)
def slice(self, k: int) -> "Bars":
"""First k bars (used to prove non-repainting: results on a prefix never change later)."""
return Bars(self.open[:k], self.high[:k], self.low[:k], self.close[:k], self.volume[:k], self.time[:k])
@dataclass
class Signals:
"""Bar-close signal arrays. Index i = decision taken at the CLOSE of bar i, filled at the OPEN of bar i+1."""
long_entry: np.ndarray
short_entry: np.ndarray
long_exit: np.ndarray
short_exit: np.ndarray
long_stop: np.ndarray # structural stop suggestion for a long opened on bar i (NaN = none)
short_stop: np.ndarray
long_target: np.ndarray # structural target suggestion (NaN = none)
short_target: np.ndarray
extras: Dict[str, np.ndarray] = field(default_factory=dict)
def _new_signals(n: int) -> Signals:
f = lambda: np.zeros(n, dtype=bool) # noqa: E731
g = lambda: np.full(n, NAN) # noqa: E731
return Signals(f(), f(), f(), f(), g(), g(), g(), g(), {})
def isna(x) -> bool:
return x is None or (isinstance(x, float) and math.isnan(x)) or (isinstance(x, np.floating) and np.isnan(x))
def nz(x, repl=0.0):
return repl if isna(x) else x
def sma(x: np.ndarray, n: int) -> np.ndarray:
"""ta.sma: NaN until n values; NaN whenever the window contains NaN."""
x = np.asarray(x, dtype=float)
out = np.full(len(x), NAN)
for i in range(n - 1, len(x)):
w = x[i - n + 1:i + 1]
if not np.isnan(w).any():
out[i] = w.mean()
return out
def rolling_sum(x: np.ndarray, n: int) -> np.ndarray:
x = np.asarray(x, dtype=float)
out = np.full(len(x), NAN)
for i in range(n - 1, len(x)):
w = x[i - n + 1:i + 1]
if not np.isnan(w).any():
out[i] = w.sum()
return out
def _smooth(x: np.ndarray, n: int, alpha: float) -> np.ndarray:
"""Recursive smoother seeded with an SMA (ta.ema / ta.rma semantics, re-seeds after na)."""
x = np.asarray(x, dtype=float)
out = np.full(len(x), NAN)
s = sma(x, n)
prev = NAN
for i in range(len(x)):
if np.isnan(x[i]):
prev = NAN
continue
prev = s[i] if np.isnan(prev) else alpha * x[i] + (1.0 - alpha) * prev
out[i] = prev
return out
def ema(x: np.ndarray, n: int) -> np.ndarray:
return _smooth(x, n, 2.0 / (n + 1.0))
def rma(x: np.ndarray, n: int) -> np.ndarray:
return _smooth(x, n, 1.0 / n)
def true_range(h: np.ndarray, l: np.ndarray, c: np.ndarray) -> np.ndarray:
"""ta.tr(true): first bar uses high-low."""
pc = np.concatenate([[NAN], c[:-1]])
tr = np.maximum(h - l, np.maximum(np.abs(h - pc), np.abs(l - pc)))
tr[0] = h[0] - l[0]
return tr
def atr(h, l, c, n: int) -> np.ndarray:
return rma(true_range(h, l, c), n)
def change(x: np.ndarray, k: int = 1) -> np.ndarray:
out = np.full(len(x), NAN)
out[k:] = x[k:] - x[:-k]
return out
def shift(x: np.ndarray, k: int) -> np.ndarray:
"""x[k] in Pine terms (value k bars ago)."""
out = np.full(len(x), NAN)
if k < len(x):
out[k:] = x[:len(x) - k]
return out
def rsi(x: np.ndarray, n: int) -> np.ndarray:
ch = change(x)
up = rma(np.where(np.isnan(ch), NAN, np.maximum(ch, 0.0)), n)
dn = rma(np.where(np.isnan(ch), NAN, np.maximum(-ch, 0.0)), n)
out = np.full(len(x), NAN)
for i in range(len(x)):
if np.isnan(up[i]) or np.isnan(dn[i]):
continue
out[i] = 100.0 if dn[i] == 0 else (0.0 if up[i] == 0 else 100.0 - 100.0 / (1.0 + up[i] / dn[i]))
return out
def mfi(src: np.ndarray, vol: np.ndarray, n: int) -> np.ndarray:
ch = change(src)
pos = np.where(np.isnan(ch), NAN, np.where(ch <= 0, 0.0, vol * src))
neg = np.where(np.isnan(ch), NAN, np.where(ch >= 0, 0.0, vol * src))
up, dn = rolling_sum(pos, n), rolling_sum(neg, n)
out = np.full(len(src), NAN)
for i in range(len(src)):
if np.isnan(up[i]) or np.isnan(dn[i]):
continue
out[i] = 100.0 if dn[i] == 0 else 100.0 - 100.0 / (1.0 + up[i] / dn[i])
return out
def cci(src: np.ndarray, n: int) -> np.ndarray:
out = np.full(len(src), NAN)
for i in range(n - 1, len(src)):
w = src[i - n + 1:i + 1]
if np.isnan(w).any():
continue
m = w.mean()
dev = np.abs(w - m).mean()
out[i] = 0.0 if dev == 0 else (src[i] - m) / (0.015 * dev)
return out
def stdev(x: np.ndarray, n: int) -> np.ndarray:
"""ta.stdev (population / biased)."""
out = np.full(len(x), NAN)
for i in range(n - 1, len(x)):
w = x[i - n + 1:i + 1]
if not np.isnan(w).any():
out[i] = w.std()
return out
def highest(x: np.ndarray, n: int) -> np.ndarray:
out = np.full(len(x), NAN)
for i in range(n - 1, len(x)):
out[i] = np.max(x[i - n + 1:i + 1])
return out
def lowest(x: np.ndarray, n: int) -> np.ndarray:
out = np.full(len(x), NAN)
for i in range(n - 1, len(x)):
out[i] = np.min(x[i - n + 1:i + 1])
return out
def crossover(a: np.ndarray, b) -> np.ndarray:
b = np.full(len(a), float(b)) if np.isscalar(b) else np.asarray(b, dtype=float)
out = np.zeros(len(a), dtype=bool)
with np.errstate(invalid="ignore"):
out[1:] = (a[1:] > b[1:]) & (a[:-1] <= b[:-1])
return out
def crossunder(a: np.ndarray, b) -> np.ndarray:
b = np.full(len(a), float(b)) if np.isscalar(b) else np.asarray(b, dtype=float)
out = np.zeros(len(a), dtype=bool)
with np.errstate(invalid="ignore"):
out[1:] = (a[1:] < b[1:]) & (a[:-1] >= b[:-1])
return out
def pivot_high(x: np.ndarray, left: int, right: int) -> np.ndarray:
"""Confirmed pivot high, reported on the CONFIRMATION bar i (pivot bar = i-right): the pivot value is
strictly above the `left` bars before it and >= the `right` bars after it. Mirrors f_pivotHigh() in Pine."""
out = np.full(len(x), NAN)
for i in range(left + right, len(x)):
c = x[i - right]
if all(x[i - right - k] < c for k in range(1, left + 1)) and all(x[i - right + k] <= c for k in range(1, right + 1)):
out[i] = c
return out
def pivot_low(x: np.ndarray, left: int, right: int) -> np.ndarray:
out = np.full(len(x), NAN)
for i in range(left + right, len(x)):
c = x[i - right]
if all(x[i - right - k] > c for k in range(1, left + 1)) and all(x[i - right + k] >= c for k in range(1, right + 1)):
out[i] = c
return out
def minute_of_day(t: int, utc_offset_hours: float = 0.0) -> int:
return int(((int(t) + int(utc_offset_hours * 3600)) // 60) % 1440)
def in_session(t: int, session: str, utc_offset_hours: float = 0.0) -> bool:
"""Pine-style "HHMM-HHMM[:days]" session test on the bar OPEN time (days suffix ignored = every day)."""
span = session.split(":")[0]
a, b = span.split("-")
s, e = int(a[:2]) * 60 + int(a[2:]), int(b[:2]) * 60 + int(b[2:])
m = minute_of_day(t, utc_offset_hours)
return (s <= m < e) if s < e else (m >= s or m < e)
# ======================================================================================================
# 2. Risk configuration, stop / target / size maths (identical rules to the Pine strategy)
# ======================================================================================================
@dataclass
class RiskConfig:
allow_long: bool = True
allow_short: bool = True
sl_mode: str = "atr" # "atr" | "pct" | "structure" | "none"
sl_pct: float = 1.0
atr_len: int = 14
atr_sl_mult: float = 2.0
tp_mode: str = "r" # "r" | "atr" | "pct" | "structure" | "none"
tp_pct: float = 2.0
atr_tp_mult: float = 3.0
rr: float = 2.0 # single-target R multiple
multi_tp: bool = False # TP1/TP2/TP3 partial exits (R-multiple mode only)
tp1_r: float = 1.0
tp2_r: float = 2.0
tp3_r: float = 3.0
tp1_pct: float = 40.0
tp2_pct: float = 30.0 # TP3 takes the remainder
size_mode: str = "risk_pct" # "risk_pct" | "equity_pct" | "fixed"
risk_pct: float = 1.0
equity_pct: float = 10.0
fixed_qty: float = 1.0
max_leverage: float = 5.0
use_exit_signals: bool = True
commission_pct: float = 0.02
def _finite(x) -> bool:
return x is not None and not isna(x) and math.isfinite(float(x))
def stop_price(is_long: bool, ref: float, atr_v: float, struct: float, rc: RiskConfig) -> float:
d = 1.0 if is_long else -1.0
atr_stop = ref - d * atr_v * rc.atr_sl_mult if _finite(atr_v) else NAN
if rc.sl_mode == "none":
return NAN
if rc.sl_mode == "pct":
return ref * (1.0 - d * rc.sl_pct / 100.0)
if rc.sl_mode == "structure":
valid = _finite(struct) and ((struct < ref) if is_long else (struct > ref))
return float(struct) if valid else atr_stop
return atr_stop
def target_levels(is_long: bool, ref: float, stop: float, atr_v: float, struct_tp: float, rc: RiskConfig) -> List[Tuple[float, float]]:
"""List of (price, percent_of_position). Empty list = no take-profit."""
d = 1.0 if is_long else -1.0
risk = abs(ref - stop) if _finite(stop) else (atr_v * rc.atr_sl_mult if _finite(atr_v) else NAN)
out: List[Tuple[float, float]] = []
if rc.tp_mode == "none":
return out
if rc.tp_mode == "r" and rc.multi_tp:
rest = max(0.0, 100.0 - rc.tp1_pct - rc.tp2_pct)
out = [(ref + d * rc.tp1_r * risk, rc.tp1_pct), (ref + d * rc.tp2_r * risk, rc.tp2_pct), (ref + d * rc.tp3_r * risk, rest)]
elif rc.tp_mode == "r":
out = [(ref + d * rc.rr * risk, 100.0)]
elif rc.tp_mode == "atr":
out = [(ref + d * atr_v * rc.atr_tp_mult, 100.0)]
elif rc.tp_mode == "pct":
out = [(ref * (1.0 + d * rc.tp_pct / 100.0), 100.0)]
elif rc.tp_mode == "structure":
valid = _finite(struct_tp) and ((struct_tp > ref) if is_long else (struct_tp < ref))
out = [(float(struct_tp) if valid else ref + d * rc.rr * risk, 100.0)]
return [(p, q) for p, q in out if _finite(p) and q > 0]
def position_qty(equity: float, ref: float, stop: float, atr_v: float, rc: RiskConfig) -> float:
"""Units (Pine strategy qty). Mirrors f_qty() in the Pine file, including the leverage cap."""
if ref <= 0:
return 0.0
if rc.size_mode == "fixed":
q = rc.fixed_qty
elif rc.size_mode == "equity_pct":
q = equity * rc.equity_pct / 100.0 / ref
else:
dist = abs(ref - stop) if _finite(stop) else (atr_v * rc.atr_sl_mult if _finite(atr_v) else NAN)
q = equity * rc.risk_pct / 100.0 / dist if _finite(dist) and dist > 0 else rc.fixed_qty
q = min(q, equity * rc.max_leverage / ref)
return max(q, 0.0)
# ======================================================================================================
# 3. Indicator + signal engine (pack specific)
# ======================================================================================================
PACK_NAME = 'WaveTrend Oscillator Strategy Pack'
PACK_SLUG = 'wavetrend-oscillator-strategy'
MAGIC = 710004
@dataclass
class Params:
n1: int = 10 # channel length
n2: int = 21 # average length
ob1: float = 60.0
ob2: float = 53.0
os1: float = -60.0
os2: float = -53.0
require_zone: bool = True # only take crosses beyond ob2 / os2
DEFAULT_RISK = RiskConfig(sl_mode="atr", tp_mode="r", rr=2.0)
def compute(bars: Bars, p: Optional[Params] = None) -> Signals:
p = p or Params()
ap = (bars.high + bars.low + bars.close) / 3.0
esa = ema(ap, p.n1)
d = ema(np.abs(ap - esa), p.n1)
with np.errstate(divide="ignore", invalid="ignore"):
ci = np.where(d > 0, (ap - esa) / (0.015 * d), NAN)
wt1 = ema(ci, p.n2)
wt2 = sma(wt1, 4)
up, dnx = crossover(wt1, wt2), crossunder(wt1, wt2)
with np.errstate(invalid="ignore"):
long_e = up & ((wt1 <= p.os2) if p.require_zone else True)
short_e = dnx & ((wt1 >= p.ob2) if p.require_zone else True)
n = len(ap)
s = _new_signals(n)
s.long_entry, s.short_entry = np.asarray(long_e, bool), np.asarray(short_e, bool)
s.long_exit, s.short_exit = s.short_entry.copy(), s.long_entry.copy()
s.extras = {"wt1": wt1, "wt2": wt2, "esa": esa, "ci": ci}
return s
# ======================================================================================================
# 4. Offline bar simulator (signal on bar close -> fill next bar open; stop checked before targets)
# ======================================================================================================
@dataclass
class Trade:
side: int
entry_bar: int
entry_price: float
qty: float
exit_bar: int = -1
exit_price: float = NAN
pnl: float = 0.0
reason: str = ""
legs: List[Tuple[int, float, float, str]] = field(default_factory=list) # (bar, price, qty, reason)
@dataclass
class SimResult:
trades: List[Trade]
equity: np.ndarray
stats: Dict[str, float]
def simulate(bars: Bars, params=None, risk: Optional[RiskConfig] = None, initial_capital: float = 10000.0,
signals: Optional[Signals] = None) -> SimResult:
rc = risk or DEFAULT_RISK
sig = signals if signals is not None else compute(bars, params)
o, h, l, c = bars.open, bars.high, bars.low, bars.close
n = len(c)
a = atr(h, l, c, rc.atr_len)
cash = initial_capital
fee = rc.commission_pct / 100.0
pos: Optional[dict] = None
pending: Optional[dict] = None
trades: List[Trade] = []
eq = np.full(n, initial_capital)
def close_qty(i: int, price: float, qty: float, reason: str):
nonlocal cash, pos
t: Trade = pos["trade"]
pnl = pos["side"] * (price - t.entry_price) * qty - fee * price * qty
cash += pnl
t.pnl += pnl
t.legs.append((i, price, qty, reason))
pos["open_qty"] -= qty
if pos["open_qty"] <= 1e-12:
t.exit_bar, t.exit_price, t.reason = i, price, reason
pos = None
for i in range(n):
# (1) pending market orders fill at this bar's open
if pending is not None:
if pos is not None and (pending["kind"] == "close" or pending["side"] != pos["side"]):
close_qty(i, o[i], pos["open_qty"], pending.get("reason", "reverse"))
if pending["kind"] == "enter" and pos is None and pending["qty"] > 0:
t = Trade(pending["side"], i, o[i], pending["qty"])
cash -= fee * o[i] * pending["qty"]
t.pnl -= fee * o[i] * pending["qty"]
trades.append(t)
tq = [[p, pending["qty"] * pct / 100.0, False] for p, pct in pending["targets"]]
pos = {"side": pending["side"], "open_qty": pending["qty"], "stop": pending["stop"], "targets": tq, "trade": t}
pending = None
# (2) protective stop, then take-profits (conservative ordering)
if pos is not None:
s = pos["side"]
stp = pos["stop"]
if _finite(stp) and ((s > 0 and l[i] <= stp) or (s < 0 and h[i] >= stp)):
fill = min(o[i], stp) if s > 0 else max(o[i], stp)
close_qty(i, fill, pos["open_qty"], "stop")
else:
for tg in pos["targets"]:
if pos is None or tg[2]:
continue
if (s > 0 and h[i] >= tg[0]) or (s < 0 and l[i] <= tg[0]):
tg[2] = True
fill = max(o[i], tg[0]) if s > 0 else min(o[i], tg[0])
close_qty(i, fill, min(tg[1], pos["open_qty"]), "target")
# (3) bar-close decisions
flat_or_short = pos is None or pos["side"] < 0
flat_or_long = pos is None or pos["side"] > 0
if rc.allow_long and sig.long_entry[i] and flat_or_short:
stp = stop_price(True, c[i], a[i], sig.long_stop[i], rc)
pending = {"kind": "enter", "side": 1, "stop": stp,
"targets": target_levels(True, c[i], stp, a[i], sig.long_target[i], rc),
"qty": position_qty(cash, c[i], stp, a[i], rc)}
elif rc.allow_short and sig.short_entry[i] and flat_or_long:
stp = stop_price(False, c[i], a[i], sig.short_stop[i], rc)
pending = {"kind": "enter", "side": -1, "stop": stp,
"targets": target_levels(False, c[i], stp, a[i], sig.short_target[i], rc),
"qty": position_qty(cash, c[i], stp, a[i], rc)}
elif pos is not None and rc.use_exit_signals and ((pos["side"] > 0 and sig.long_exit[i]) or (pos["side"] < 0 and sig.short_exit[i])):
pending = {"kind": "close", "side": 0, "reason": "exit_signal"}
eq[i] = cash + (pos["side"] * (c[i] - pos["trade"].entry_price) * pos["open_qty"] if pos is not None else 0.0)
closed = [t for t in trades if t.exit_bar >= 0]
wins = [t.pnl for t in closed if t.pnl > 0]
losses = [t.pnl for t in closed if t.pnl <= 0]
peak = np.maximum.accumulate(eq) if n else eq
dd = float(np.max((peak - eq) / peak)) * 100.0 if n else 0.0
stats = {
"trades": float(len(trades)),
"closed_trades": float(len(closed)),
"win_rate_pct": 100.0 * len(wins) / len(closed) if closed else 0.0,
"net_profit": float(eq[-1] - initial_capital) if n else 0.0,
"profit_factor": (sum(wins) / -sum(losses)) if losses and sum(losses) < 0 else (float("inf") if wins else 0.0),
"max_drawdown_pct": dd,
}
return SimResult(trades, eq, stats)
# ======================================================================================================
# 5. MetaTrader 5 scaffolding (dry-run by default; only CLOSED bars are evaluated)
# ======================================================================================================
@dataclass
class SymbolSpec:
name: str = "EURUSD"
digits: int = 5
tick_size: float = 0.00001
tick_value: float = 1.0 # account-currency value of one tick for 1.0 lot
contract_size: float = 100000.0
volume_min: float = 0.01
volume_max: float = 100.0
volume_step: float = 0.01
@classmethod
def from_mt5(cls, info) -> "SymbolSpec": # pragma: no cover - needs a live terminal
return cls(info.name, info.digits, info.trade_tick_size, info.trade_tick_value, info.trade_contract_size,
info.volume_min, info.volume_max, info.volume_step)
def mt5_lots(spec: SymbolSpec, equity: float, entry: float, stop: float, rc: RiskConfig, atr_v: float = NAN) -> float:
"""Broker lot size: risk money / (stop distance in ticks * tick value), rounded DOWN to volume_step."""
if rc.size_mode == "fixed":
lots = rc.fixed_qty
elif rc.size_mode == "equity_pct":
lots = equity * rc.equity_pct / 100.0 / (entry * spec.contract_size)
else:
dist = abs(entry - stop) if _finite(stop) else (atr_v * rc.atr_sl_mult if _finite(atr_v) else NAN)
if not _finite(dist) or dist <= 0:
return 0.0
lots = equity * rc.risk_pct / 100.0 / (dist / spec.tick_size * spec.tick_value)
lots = min(lots, equity * rc.max_leverage / (entry * spec.contract_size))
step = spec.volume_step
lots = math.floor(lots / step + 1e-9) * step
if lots < spec.volume_min:
return 0.0
return round(min(lots, spec.volume_max), 8)
def build_order_request(spec: SymbolSpec, side: int, lots: float, price: float, sl: float = NAN, tp: float = NAN,
magic: int = 0, comment: str = "", deviation: int = 20) -> dict:
buy_t = getattr(mt5, "ORDER_TYPE_BUY", 0) if mt5 else 0
sell_t = getattr(mt5, "ORDER_TYPE_SELL", 1) if mt5 else 1
req = {
"action": getattr(mt5, "TRADE_ACTION_DEAL", 1) if mt5 else 1,
"symbol": spec.name,
"volume": float(lots),
"type": buy_t if side > 0 else sell_t,
"price": round(float(price), spec.digits),
"deviation": int(deviation),
"magic": int(magic),
"comment": comment[:31],
"type_time": getattr(mt5, "ORDER_TIME_GTC", 0) if mt5 else 0,
"type_filling": getattr(mt5, "ORDER_FILLING_IOC", 1) if mt5 else 1,
}
if _finite(sl):
req["sl"] = round(float(sl), spec.digits)
if _finite(tp):
req["tp"] = round(float(tp), spec.digits)
return req
def send_order(request: dict, dry_run: bool = True):
"""Dry-run unless explicitly disabled AND the MetaTrader5 package is connected."""
if dry_run or mt5 is None:
return {"dry_run": True, "request": request}
return mt5.order_send(request) # pragma: no cover
def fetch_closed_bars(symbol: str, timeframe, count: int = 1000) -> Bars: # pragma: no cover - needs a terminal
"""start_pos=1 skips the forming bar, so the engine never sees an unfinished candle."""
if mt5 is None:
raise RuntimeError("MetaTrader5 package not available")
return Bars.from_mt5_rates(mt5.copy_rates_from_pos(symbol, timeframe, 1, count))
class LiveRunner:
"""Evaluate the last CLOSED bar and emit at most one order request (dry-run by default)."""
def __init__(self, spec: SymbolSpec, params=None, risk: Optional[RiskConfig] = None, dry_run: bool = True,
magic: int = 0, deviation: int = 20):
self.spec, self.params, self.risk = spec, params, risk or DEFAULT_RISK
self.dry_run, self.magic, self.deviation = dry_run, magic or MAGIC, deviation
self.last_bar_time: Optional[int] = None
def step(self, bars: Bars, equity: float, position_side: int = 0, drop_forming: bool = True):
closed = bars.slice(len(bars) - 1) if drop_forming else bars
if len(closed) < 3:
return None
bar_t = int(closed.time[-1])
if self.last_bar_time == bar_t:
return None # already evaluated this closed bar
self.last_bar_time = bar_t
sig = compute(closed, self.params)
i = len(closed) - 1
rc = self.risk
a = atr(closed.high, closed.low, closed.close, rc.atr_len)[i]
ref = float(closed.close[i])
if rc.allow_long and sig.long_entry[i] and position_side <= 0:
side, stp, st = 1, stop_price(True, ref, a, sig.long_stop[i], rc), sig.long_target[i]
elif rc.allow_short and sig.short_entry[i] and position_side >= 0:
side, stp, st = -1, stop_price(False, ref, a, sig.short_stop[i], rc), sig.short_target[i]
elif rc.use_exit_signals and ((position_side > 0 and sig.long_exit[i]) or (position_side < 0 and sig.short_exit[i])):
return {"dry_run": self.dry_run, "action": "close", "side": position_side}
else:
return None
tps = target_levels(side > 0, ref, stp, a, st, rc)
lots = mt5_lots(self.spec, equity, ref, stp, rc, a)
if lots <= 0:
return None
req = build_order_request(self.spec, side, lots, ref, stp, tps[0][0] if tps else NAN, self.magic,
f"{PACK_SLUG[:20]} {'BUY' if side > 0 else 'SELL'}", self.deviation)
return send_order(req, self.dry_run)
__all__ = ["Bars", "Signals", "Params", "RiskConfig", "DEFAULT_RISK", "compute", "simulate", "stop_price", "target_levels",
"position_qty", "SymbolSpec", "mt5_lots", "build_order_request", "send_order", "LiveRunner", "PACK_NAME", "PACK_SLUG"]
if __name__ == "__main__": # quick offline demo on synthetic data
rng = np.random.default_rng(7)
m = 1500
cl = 100 + np.cumsum(rng.normal(0, 0.4, m) + 0.05 * np.sin(np.arange(m) / 60))
op = np.concatenate([[cl[0]], cl[:-1]])
hi = np.maximum(op, cl) + rng.uniform(0, 0.3, m)
lo = np.minimum(op, cl) - rng.uniform(0, 0.3, m)
res = simulate(Bars.from_arrays(op, hi, lo, cl, rng.uniform(100, 1000, m)))
print(PACK_NAME, {k: round(v, 3) for k, v in res.stats.items()})
Want 16 more strategies? See the Complete Strategy Vault Bundle.
Higher-timeframe liquidity sweep, then a close back through the sweep bar.
Sample curve, not a live account
$149.00
Structure, order blocks, and fair value gaps on one overlay.
Sample curve, not a live account
$189.00