can you add daily ATR for this strategy for confirmation? //@version=4
strategy(title="Magic MA Strategy", shorttitle="Magic MA Strat", overlay=true, max_bars_back=2000)
//
// Description:
// A trend-following strategy that uses fast QQE crosses with Moving Averages
// for trend direction filtering.
//
To incorporate the Average True Range (ATR) for confirmation in your strategy, you can use the ATR indicator to validate entries and exits. Here's an updated version of your code with the ATR logic integrated:
pinescript
User
add buy and sell bottom
Assistant
To add buy and sell buttons to your Pine Script strategy, you can use strategy.order within if conditions that check for manual inputs from users. In TradingView, these inputs can serve the purpose of simulating manual control through checkboxes, which can mimic the pressing of buy and sell buttons.
Here's how you can implement buy and sell buttons using checkboxes:
pinescript
User
show stoploss
Assistant
Adding a stop-loss to your strategy involves defining a price level at which your position will be exited automatically to prevent further losses. In Pine Script, this is typically done using the strategy.exit function, where you can specify a stop-loss and a profit target. Here's how you can incorporate a stop-loss into the strategy:
pinescript
User
show entry buy or sell
Assistant
To visually indicate buy and sell entries on a TradingView chart, you can use the plotshape function. This function places shapes (like arrows) on the chart at locations where entries occur. Below is your script modified to include visual markers for buy and sell entries:
pinescript
User
trade once a day
Assistant
To ensure that your strategy only executes one trade per day, you can introduce a mechanism that checks if a trade has already occurred for the current day and prevents further trades until the next day. This can be achieved by using a variable to track the number of trades per day and resetting it at the start of each new day.
Here's how you can modify your script to trade only once a day:
pinescript
User
show entry and exit
Assistant
To effectively show both the entry and exit points on your chart, you can utilize labeled shapes for clarity. We'll use plotshape for marking entry and exit events specifically. Here's how you can modify your script to visually display these entries and exits on your chart:
pinescript
User
show buy and sell entry, buy for blue and red for sell
Assistant
To visually differentiate buy and sell entries using specific colors (blue for buy and red for sell), you can modify the plotting of entry and exit markers. Below is an updated version of your strategy script with these changes:
pinescript
User
take profit at 40pips stoploss at 20pips
Assistant
In order to implement a fixed take profit and stop loss in pips for your strategy, you need to convert the pip value into price units based on the security you're trading. Here’s a step-by-step guide to set a take profit at 40 pips and a stop loss at 20 pips:
Define Units: Depending on the market (Forex, Stocks, etc.), a pip might be defined differently. For most currency pairs in Forex, 1 pip is 0.0001 for pairs quoted to four decimal places, and 0.01 for those quoted to two decimal places like JPY pairs.
Calculate Price Levels: Use the defined pip value to calculate price levels for your stop loss and take profit.
Here's the updated script with take profit at 40 pips and stop loss at 20 pips:
pinescript
User
fixed line 98 Undeclared identifier 'atrMultiplier';
Assistant
I apologize for the oversight. It looks like the atrMultiplier variable was intended to be used but was not declared in your current setup. If you want to keep this for any reason or adjust it in any way, make sure to declare it as an input or remove its usage if it’s unnecessary for your logic.
Let's update the script to ensure it's correct. I'll declare an input variable for atrMultiplier, so if you use it elsewhere (or plan to), it'll be set appropriately:
pinescript
User
starting balance is 25,0000 lotsize use is 0.35
Assistant
To set the starting balance and specify the lot size (position size) in Pine Script, you'll need to adjust both the script's settings and the order execution functions. While Pine Script's built-in strategy tester lets you set the initial balance manually from the strategy tester's settings menu, the script can control the order size.
Here's how you can implement the initial setup with a starting balance of 250,000 and a lot size of 0.35:
Set the initial capital of the strategy from the TradingView interface, usually under properties.
Use strategy.order or strategy.entry functions to specify the amount or quantity for lot size.
Here's the script with these considerations:
pinescript
User
buy entry, candle close above slow ma, stoploss 30 pips, take profit is 60pips. sell entry, candle close below slowma stoploss 30 pips, take profit is 60 pips.
Assistant
To implement the specified trading strategy, consisting of entering a buy trade when the candle closes above a slow moving average (MA), and entering a sell trade when the candle closes below the slow MA, you can follow these steps:
Buy/Sell Conditions: Determine if the candle's close price is above or below the slow moving average.
Take Profit & Stop Loss: Implement a take profit of 60 pips and a stop loss of 30 pips.
Here's the updated script for your strategy:
pinescript
Not yet included in a published release.
//@version=4
strategy(title="Magic MA Strategy with ATR Confirmation", shorttitle="Magic MA Strat ATR", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1) // Updated default slow length to 70
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings
atrLength = input(14, title="ATR Length")
atrMultiplier = input(1.5, title="ATR Multiplier")
// - INPUTS END
// - FUNCTIONS
// Returns MA input selection variant, default to SMA if blank or typo.
variant(type, src, len) =>
v1 = sma(src, len) // Simple
v2 = ema(src, len) // Exponential
v3 = wma(src, len) // Weighted
v4 = vwma(src, len) // Volume Weighted
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len // Smoothed
v6 = 2 * v2 - ema(v2, len) // Double Exponential
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len) // Triple Exponential
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len))) // Hull
v11 = sma(sma(src, len), len) // Triangular
// SuperSmoother filter
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
// Zero Lag Exponential
e = ema(v1, len)
v10 = v1 + (v1 - e)
// return variant, defaults to SMA if input invalid.
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// ATR Calculation
atrValue = atr(atrLength)
// Trading logic series variable
var int tradeCount = 0
var int lastTradeDay = na
currentDay = dayofweek(time)
// Reset the trade count at the beginning of a new day
if na(lastTradeDay) or (currentDay != lastTradeDay)
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atrValue
entryCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and tradeCount < 1
exitCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
if entryCondition
strategy.entry("Buy", strategy.long)
tradeCount := tradeCount + 1
if exitCondition
strategy.close("Buy")
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Explanation:
ATR Calculation:
The ATR is calculated using the atr() function with a default length of 14 periods.
The ATR value is then multiplied by a user-defined multiplier (atrMultiplier) for comparison.
Entry Condition:
The entryCondition now includes an additional atrCondition that ensures the difference between the RSI and its trend line exceeds a threshold defined by the ATR. This helps in confirming potential entries with sufficient volatility.
Plot:
The ATR isn't directly plotted, but its value is used as a condition in the entry logic. You can plot it if needed for visual analysis.
This integration adds an ATR-based confirmation to your trading strategy, helping to filter trades further by ensuring the market is experiencing a certain level of volatility before entering a position.
The script includes two checkboxes (buyButton and sellButton) as input to simulate manual buying and selling.
Manual Buy/Sell Execution:
When buyButton is checked, a buy order (strategy.entry) is executed.
When sellButton is checked, any existing manual buy order is closed (strategy.close).
The inclusion of manual buy and sell controls allows users to simulate manual trading through the TradingView interface. Remember to uncheck the boxes after the desired action is triggered, as the script continues to evaluate them on each bar. While these controls allow for a basic manual interaction, they are primarily for testing and prototyping as the TradingView platform is designed more for automated strategy testing than for manual trading execution.
//@version=4
strategy(title="Magic MA Strategy with ATR Confirmation, Manual Controls, and Stop-Loss", shorttitle="Magic MA Strat ATR", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings
atrLength = input(14, title="ATR Length")
atrMultiplier = input(1.5, title="ATR Multiplier")
// Stop-Loss Settings
stopLossATRMultiplier = input(2.0, title="Stop-Loss ATR Multiplier") // Stop-loss based on ATR
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// ATR Calculation
atrValue = atr(atrLength)
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
currentDay = dayofweek(time)
// Reset the trade count at the beginning of a new day
if na(lastTradeDay) or (currentDay != lastTradeDay)
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atrValue
entryCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and tradeCount < 1
exitCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate stop loss based on ATR
stopLossLevel = close - stopLossATRMultiplier * atrValue
// Execute trades based on strategy logic
if entryCondition
strategy.entry("Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
if exitCondition
strategy.close("Buy")
// Manual Buy/Sell execution
if buyButton
strategy.entry("Manual Buy", strategy.long, stop=stopLossLevel)
if sellButton
strategy.close("Manual Buy")
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
// Indicate stop-loss level on chart
plot(series=stopLossLevel, title="Stop Loss Level", color=color.red, linewidth=1, transp=50, style=plot.style_cross)
//EOF
Explanation:
Stop-Loss Calculation:
The stop-loss level is calculated dynamically based on the ATR value and a user-defined multiplier (stopLossATRMultiplier). This multiplier determines how many ATRs below the entry the stop-loss will be set.
strategy.entry:
The strategy.entry function has an additional stop parameter, which is used to define the stop-loss price level.
Plotting the Stop-Loss Level:
The stop-loss level is plotted on the chart using plot with a red line for easy visualization.
This setup ensures that each position entered has a predefined exit level based on market volatility, helping manage risks associated with trading. Adjust the stopLossATRMultiplier to fit your risk management preferences.
//@version=4
strategy(title="Magic MA Strategy with ATR Confirmation, Manual Controls, and Stop-Loss", shorttitle="Magic MA Strat ATR", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings
atrLength = input(14, title="ATR Length")
atrMultiplier = input(1.5, title="ATR Multiplier")
// Stop-Loss Settings
stopLossATRMultiplier = input(2.0, title="Stop-Loss ATR Multiplier") // Stop-loss based on ATR
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// ATR Calculation
atrValue = atr(atrLength)
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
currentDay = dayofweek(time)
// Reset the trade count at the beginning of a new day
if na(lastTradeDay) or (currentDay != lastTradeDay)
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atrValue
entryCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and tradeCount < 1
exitCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate stop loss based on ATR
stopLossLevel = close - stopLossATRMultiplier * atrValue
// Execute trades based on strategy logic
if entryCondition
strategy.entry("Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
if exitCondition
strategy.close("Buy")
// Manual Buy/Sell execution
if buyButton
strategy.entry("Manual Buy", strategy.long, stop=stopLossLevel)
if sellButton
strategy.close("Manual Buy")
// Plotting the stop-loss level
plot(series=stopLossLevel, title="Stop Loss Level", color=color.red, linewidth=1, transp=50, style=plot.style_cross)
// Plotting entry markers
buySignal = entryCondition or buyButton
sellSignal = exitCondition or sellButton
plotshape(series=buySignal, location=location.belowbar, color=color.green, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=sellSignal, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Explanation:
Buy and Sell Markers:
plotshape is used to place a labeled shape ("BUY" or "SELL") on the chart.
location.belowbar and location.abovebar position the labels beneath and above the price bar to indicate buy and sell entries, respectively.
Signals:
buySignal consolidates the logic for both strategy and manual buy actions.
sellSignal does the same for sell actions.
This setup will visually indicate when a buy or sell entry is executed on the chart, helping you quickly identify the points of trade execution based on the strategy conditions as well as manual inputs.
//@version=4
strategy(title="Magic MA Strategy with ATR Confirmation, Manual Controls, and Stop-Loss", shorttitle="Magic MA Strat ATR", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings
atrLength = input(14, title="ATR Length")
atrMultiplier = input(1.5, title="ATR Multiplier")
// Stop-Loss Settings
stopLossATRMultiplier = input(2.0, title="Stop-Loss ATR Multiplier") // Stop-loss based on ATR
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// ATR Calculation
atrValue = atr(atrLength)
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
var int currentDay = 0
// Detect new day
currentDay := dayofweek(time)
// Reset the trade count at the beginning of a new day
if (na(lastTradeDay) or (currentDay != lastTradeDay))
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atrValue
entryCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and (tradeCount < 1)
exitCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate stop loss based on ATR
stopLossLevel = close - stopLossATRMultiplier * atrValue
// Execute trades based on strategy logic
if entryCondition
strategy.entry("Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Handle exit and manual selling
if exitCondition
strategy.close("Buy")
if sellButton
strategy.close("Manual Buy")
// Manual Buy execution with trade count check
if buyButton and (tradeCount < 1)
strategy.entry("Manual Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Plotting entry markers
plotshape(series=entryCondition, location=location.belowbar, color=color.green, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=exitCondition, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// Plotting the stop-loss level
plot(series=stopLossLevel, title="Stop Loss Level", color=color.red, linewidth=1, transp=80)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Key Modifications:
Daily Trade Limit:
Introduced a daily trade limit by checking the tradeCount variable and resetting it at the beginning of each new day.
New Day Detection:
Used the dayofweek(time) function to detect changes in the day and reset the trade counter when a new day is detected.
entryCondition and Manual Buy Logic:
Both the automatic and manual buy conditions now check if the tradeCount is less than 1 before entering a new trade.
This approach ensures that the strategy will only enter one trade per day, applicable to both automated signals and manual entries initiated through the "Manual Buy" control.
//@version=4
strategy(title="Magic MA Strategy with ATR Confirmation, Manual Controls, and Stop-Loss", shorttitle="Magic MA Strat ATR", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings
atrLength = input(14, title="ATR Length")
atrMultiplier = input(1.5, title="ATR Multiplier")
// Stop-Loss Settings
stopLossATRMultiplier = input(2.0, title="Stop-Loss ATR Multiplier") // Stop-loss based on ATR
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// ATR Calculation
atrValue = atr(atrLength)
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
var int currentDay = 0
// Detect new day
currentDay := dayofweek(time)
// Reset the trade count at the beginning of a new day
if (na(lastTradeDay) or (currentDay != lastTradeDay))
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atrValue
entryCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and (tradeCount < 1)
exitCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate stop loss based on ATR
stopLossLevel = close - stopLossATRMultiplier * atrValue
// Execute trades based on strategy logic
if entryCondition
strategy.entry("Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Handle exit and manual selling
if exitCondition
strategy.close("Buy")
if sellButton
strategy.close("Manual Buy")
// Manual Buy execution with trade count check
if buyButton and (tradeCount < 1)
strategy.entry("Manual Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Plotting entry and exit markers
plotshape(series=entryCondition or (buyButton and (tradeCount < 1)), location=location.belowbar, color=color.green, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=exitCondition or sellButton, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// Plotting the stop-loss level
plot(series=stopLossLevel, title="Stop Loss Level", color=color.red, linewidth=1, transp=80)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Key Features of the Script:
Entry and Exit Markers:
Entry (Buy) markers are displayed using plotshape with a green label below bars.
Exit (Sell) markers are displayed using plotshape with a red label above bars.
Marker Logic:
Entry markers appear when either the entryCondition is met or the manual buy button (buyButton) is activated, provided no trades have occurred yet on the current day.
Exit markers appear when the exitCondition is met or when the manual sell button (sellButton) is activated.
Single Trade per Day Constraint:
A trade count mechanism ensures that only one trade is taken each day. This includes both strategy-based and manually-triggered trades.
This approach will help you visualize the precise points on your chart where the strategy enters and exits trades based on both automated and manual conditions.
//@version=4
strategy(title="Magic MA Strategy with ATR Confirmation, Manual Controls, and Stop-Loss", shorttitle="Magic MA Strat ATR", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings
atrLength = input(14, title="ATR Length")
atrMultiplier = input(1.5, title="ATR Multiplier")
// Stop-Loss Settings
stopLossATRMultiplier = input(2.0, title="Stop-Loss ATR Multiplier") // Stop-loss based on ATR
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// ATR Calculation
atrValue = atr(atrLength)
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
var int currentDay = 0
// Detect new day
currentDay := dayofweek(time)
// Reset the trade count at the beginning of a new day
if (na(lastTradeDay) or (currentDay != lastTradeDay))
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atrValue
buyCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and (tradeCount < 1)
sellCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate stop loss based on ATR
stopLossLevel = close - stopLossATRMultiplier * atrValue
// Execute trades based on strategy logic
if buyCondition
strategy.entry("Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Handle sell and manual selling
if sellCondition
strategy.close("Buy")
if sellButton
strategy.close("Manual Buy")
// Manual Buy execution with trade count check
if buyButton and (tradeCount < 1)
strategy.entry("Manual Buy", strategy.long, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Plotting entry and exit markers
plotshape(series=buyCondition or (buyButton and (tradeCount < 1)), location=location.belowbar, color=color.blue, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=sellCondition or sellButton, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// Plotting the stop-loss level
plot(series=stopLossLevel, title="Stop Loss Level", color=color.red, linewidth=1, transp=80)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Explanation:
Buy and Sell Markers:
Buy Markers:plotshape is used with color=color.blue and style=shape.labelup to display a blue label below bars where buy conditions are met.
Sell Markers:plotshape is used with color=color.red and style=shape.labeldown to display a red label above bars where sell conditions are met.
This setup will display blue markers for buy and red markers for sell entries on your chart, making it easy to visualize trade actions within the strategy.
//@version=4
strategy(title="Magic MA Strategy with Fixed Take Profit and Stop-Loss", shorttitle="Magic MA Strat TP/SL", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// Pip value settings
pipValue = input(0.0001, title="Pip Value") // Adjust for different pairs, e.g., 0.01 for JPY pairs
// Trading parameters
takeProfitPips = input(40, title="Take Profit (Pips)")
stopLossPips = input(20, title="Stop Loss (Pips)")
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
var int currentDay = 0
// Detect new day
currentDay := dayofweek(time)
// Reset the trade count at the beginning of a new day
if (na(lastTradeDay) or (currentDay != lastTradeDay))
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atrValue
buyCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and (tradeCount < 1)
sellCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate take profit and stop loss levels based on pip values
takeProfitLevel = strategy.position_avg_price + (takeProfitPips * pipValue)
stopLossLevel = strategy.position_avg_price - (stopLossPips * pipValue)
// Execute trades based on strategy logic with fixed TP/SL
if buyCondition
strategy.entry("Buy", strategy.long)
strategy.exit("TP/SL", "Buy", limit=takeProfitLevel, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Handle sell and manual selling
if sellCondition
strategy.close("Buy")
if sellButton
strategy.close("Manual Buy")
// Manual Buy execution with trade count check
if buyButton and (tradeCount < 1)
strategy.entry("Manual Buy", strategy.long)
strategy.exit("Manual TP/SL", "Manual Buy", limit=takeProfitLevel, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Plotting entry and exit markers
plotshape(series=buyCondition or (buyButton and (tradeCount < 1)), location=location.belowbar, color=color.blue, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=sellCondition or sellButton, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Key Adjustments:
Pip Calculation:
The pipValue is set to 0.0001 for most Forex pairs; adjust to 0.01 for JPY pairs.
Take Profit and Stop Loss Levels:
Calculated from the entry price, using the specified number of pips.
Trade Execution:
strategy.exit is used to apply both the take profit and stop loss levels once a trade is entered.
This setup ensures that every trade adheres to the defined risk and reward structures by using fixed pip-based take profit and stop loss levels. Adjust the pipValue based on the instrument you are trading to ensure accurate pip calculations.
//@version=4
strategy(title="Magic MA Strategy with Fixed Take Profit and Stop-Loss", shorttitle="Magic MA Strat TP/SL", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings (if needed)
atrMultiplier = input(1.5, title="ATR Multiplier")
// Pip value settings
pipValue = input(0.0001, title="Pip Value") // Adjust for different pairs, e.g., 0.01 for JPY pairs
// Trading parameters
takeProfitPips = input(40, title="Take Profit (Pips)")
stopLossPips = input(20, title="Stop Loss (Pips)")
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
var int currentDay = 0
// Detect new day
currentDay := dayofweek(time)
// Reset the trade count at the beginning of a new day
if (na(lastTradeDay) or (currentDay != lastTradeDay))
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atr(RSILen)
buyCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and (tradeCount < 1)
sellCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate take profit and stop loss levels based on pip values
takeProfitLevel = strategy.position_avg_price + (takeProfitPips * pipValue)
stopLossLevel = strategy.position_avg_price - (stopLossPips * pipValue)
// Execute trades based on strategy logic with fixed TP/SL
if buyCondition
strategy.entry("Buy", strategy.long)
strategy.exit("TP/SL", "Buy", limit=takeProfitLevel, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Handle sell and manual selling
if sellCondition
strategy.close("Buy")
if sellButton
strategy.close("Manual Buy")
// Manual Buy execution with trade count check
if buyButton and (tradeCount < 1)
strategy.entry("Manual Buy", strategy.long)
strategy.exit("Manual TP/SL", "Manual Buy", limit=takeProfitLevel, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Plotting entry and exit markers
plotshape(series=buyCondition or (buyButton and (tradeCount < 1)), location=location.belowbar, color=color.blue, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=sellCondition or sellButton, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Explanation:
ATR Multiplier Input: An atrMultiplier input has been added if you require it in further calculations.
Pip-Based TP/SL: Ensure the pipValue matches the instrument you are trading (e.g., 0.0001 for most Forex pairs, 0.01 for JPY pairs).
Trade Execution: Contains a strategy.exit for managing take profit and stop loss on trades using the calculated levels.
These changes should fix any issues with undeclared identifiers and allow your strategy to function with clearly set take profit and stop loss levels. Adjust the pipValue as necessary according to the market being traded to ensure accurate pip measurements.
//@version=4
strategy(title="Magic MA Strategy with Fixed Take Profit and Stop-Loss", shorttitle="Magic MA Strat TP/SL", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="HullMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=70, title="Slow Length", minval=1)
// QQE RSI Length, Smoothing, fast ATR factor, source
RSILen = input(6, title='RSI Length')
SF = input(3, title='RSI Smoothing Factor')
QQE = input(2.618, title='Fast QQE Factor')
threshhold = input(10, title="RSI Threshhold")
filter = input(false, title="Use Moving Average Filter")
dfilter = input(false, title="Use Trend Directional Filter")
ushunt = input(false, title="Use Shunt Alerts to prevent Repaint")
RSIsrc = input(close, title="Source")
srcclose = RSIsrc
shunt = ushunt ? (RSIsrc == open ? 0 : 1) : 0
// ATR Settings (if needed)
atrMultiplier = input(1.5, title="ATR Multiplier")
// Pip value settings
pipValue = input(0.0001, title="Pip Value") // Adjust for different pairs, e.g., 0.01 for JPY pairs
// Trading parameters
takeProfitPips = input(40, title="Take Profit (Pips)")
stopLossPips = input(20, title="Stop Loss (Pips)")
// Lot size for each trade
lotSize = 0.35
// Manual trade control inputs
buyButton = input(false, title="Manual Buy")
sellButton = input(false, title="Manual Sell")
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// - Fast ATR QQE
Wilders_Period = RSILen * 2 - 1
Rsi = rsi(RSIsrc, RSILen)
RSIndex = ema(Rsi, SF)
AtrRsi = abs(RSIndex[1] - RSIndex)
MaAtrRsi = ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ema(MaAtrRsi, Wilders_Period) * QQE
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? min(shortband[1], newshortband) : newshortband
trend := cross(RSIndex, shortband[1]) ? 1 : cross(longband[1], RSIndex) ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
// Trading logic series variables
var int tradeCount = 0
var int lastTradeDay = na
var int currentDay = 0
// Detect new day
currentDay := dayofweek(time)
// Reset the trade count at the beginning of a new day
if (na(lastTradeDay) or (currentDay != lastTradeDay))
tradeCount := 0
lastTradeDay := currentDay
// - SERIES VARIABLES
// MA's
ma_slow = variant(type3, srcclose, len3)
// - STRATEGY LOGIC
atrCondition = (RSIndex - FastAtrRsiTL) > atrMultiplier * atr(RSILen)
buyCondition = crossover(RSIndex, FastAtrRsiTL) and atrCondition and (not filter or (filter and RSIndex > ma_slow)) and (tradeCount < 1)
sellCondition = crossunder(RSIndex, FastAtrRsiTL) or (filter and RSIndex < ma_slow)
// Calculate take profit and stop loss levels based on pip values
takeProfitLevel = strategy.position_avg_price + (takeProfitPips * pipValue)
stopLossLevel = strategy.position_avg_price - (stopLossPips * pipValue)
// Execute trades based on strategy logic with fixed TP/SL
if buyCondition
strategy.entry("Buy", strategy.long, qty=lotSize)
strategy.exit("TP/SL", from_entry="Buy", limit=takeProfitLevel, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Handle sell and manual selling
if sellCondition
strategy.close("Buy")
if sellButton
strategy.close("Manual Buy")
// Manual Buy execution with trade count check
if buyButton and (tradeCount < 1)
strategy.entry("Manual Buy", strategy.long, qty=lotSize)
strategy.exit("Manual TP/SL", from_entry="Manual Buy", limit=takeProfitLevel, stop=stopLossLevel)
tradeCount := tradeCount + 1
// Plotting entry and exit markers
plotshape(series=buyCondition or (buyButton and (tradeCount < 1)), location=location.belowbar, color=color.blue, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=sellCondition or sellButton, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
//EOF
Additional Explanations:
Starting Balance: You need to manually set your starting balance to 250,000 via the TradingView strategy properties panel.
Lot Size: The qty=lotSize parameter in strategy.entry specifies how many lots to use per trade.
This configuration ensures that each trade uses the specified lot size, and the strategy operates with the set initial capital.
//@version=4
strategy(title="Moving Average Strategy with Fixed TP/SL", shorttitle="MA Strat TP/SL", overlay=true, max_bars_back=2000)
// - INPUTS START
// Slow MA - type, source, length
type3 = input(defval="SMA", title="Slow MA Type: ", options=["SMA", "EMA", "WMA", "VWMA", "SMMA", "DEMA", "TEMA", "HullMA", "ZEMA", "TMA", "SSMA"], type=input.string)
len3 = input(defval=100, title="Slow MA Length", minval=1) // Adjust the length as required
// Pip value settings
pipValue = input(0.0001, title="Pip Value") // Adjust for different pairs, e.g., 0.01 for JPY pairs
// Trading parameters
takeProfitPips = input(60, title="Take Profit (Pips)")
stopLossPips = input(30, title="Stop Loss (Pips)")
// Lot size for each trade
lotSize = 0.35
// - INPUTS END
// - FUNCTIONS
variant(type, src, len) =>
v1 = sma(src, len)
v2 = ema(src, len)
v3 = wma(src, len)
v4 = vwma(src, len)
v5 = 0.0
v5 := na(v5[1]) ? sma(src, len) : (v5[1] * (len - 1) + src) / len
v6 = 2 * v2 - ema(v2, len)
v7 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)
v8 = wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
v11 = sma(sma(src, len), len)
a1 = exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * cos(1.414 * 3.14159 / len)
c2 = b1
c3 = (-a1) * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
e = ema(v1, len)
v10 = v1 + (v1 - e)
type == "EMA" ? v2 : type == "WMA" ? v3 : type == "VWMA" ? v4 : type == "SMMA" ? v5 : type == "DEMA" ? v6 : type == "TEMA" ? v7 : type == "HullMA" ? v8 : type == "SSMA" ? v9 : type == "ZEMA" ? v10 : type == "TMA" ? v11 : v1
// - FUNCTIONS END
// Calculate slow MA
ma_slow = variant(type3, close, len3)
// Define conditions for buy and sell entries
buyCondition = crossover(close, ma_slow)
sellCondition = crossunder(close, ma_slow)
// Calculate take profit and stop loss levels based on pip values
takeProfitLong = strategy.position_avg_price + (takeProfitPips * pipValue)
stopLossLong = strategy.position_avg_price - (stopLossPips * pipValue)
takeProfitShort = strategy.position_avg_price - (takeProfitPips * pipValue)
stopLossShort = strategy.position_avg_price + (stopLossPips * pipValue)
// Execute trades based on buy/sell conditions with fixed TP/SL
if buyCondition
strategy.entry("Buy", strategy.long, qty=lotSize)
strategy.exit("Long TP/SL", from_entry="Buy", limit=takeProfitLong, stop=stopLossLong)
if sellCondition
strategy.entry("Sell", strategy.short, qty=lotSize)
strategy.exit("Short TP/SL", from_entry="Sell", limit=takeProfitShort, stop=stopLossShort)
// Plotting entry and exit markers
plotshape(series=buyCondition, location=location.belowbar, color=color.blue, style=shape.labelup, text="BUY", size=size.tiny)
plotshape(series=sellCondition, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", size=size.tiny)
// - PLOTTING
plot(ma_slow, title="MA Slow", color=color.orange, linewidth=2)
//EOF
Explanation:
Buy/Sell Conditions:
Buy when the close price crosses above the slow moving average (crossover(close, ma_slow)).
Sell when the close price crosses below the slow moving average (crossunder(close, ma_slow)).
Take Profit and Stop Loss:
For both long and short positions, take profit is set to 60 pips.
Stop loss is set to 30 pips.
The pip value is considered for different currency pairs or trading instruments.
Lot Size:
Fixed lot size of 0.35 is used for each trade.
Adjust the pipValue as necessary for the specific asset being traded. The script will visually mark buy and sell signals on the chart with blue and red markers, respectively.