buy and sell if previous candle 4h close below or above the slowma depending on the trend
- User
buy and sell if previous candle 4h close below or above the slowma depending on the trend
- Assistant
- User
- Assistant
buy and sell if previous candle 4h close below or above the slowma depending on the trend
To implement a trading strategy that involves buying and selling based on a 4-hour candle close relative to a slow moving average (slowma), you would typically follow these steps. This strategy is based on the assumption that you have already defined a trend direction and a specific moving average to use as your slowma.
Select Your Moving Average: Choose the type (SMA, EMA) and the period for your slow moving average (e.g., 50, 100, 200). The choice depends on your trading style and the asset being traded.
Determine the Overall Trend:
Buy Signal (Long Position):
Sell Signal (Short Position):
Exiting a Long Position:
Exiting a Short Position:
Stop Loss: Always set a stop loss to limit potential losses. For example, you could place a stop loss below a recent swing low for long positions or above a recent swing high for short positions.
Take Profit: Set a take profit level to secure gains. This can be based on key resistance/support levels, fixed pips, or risk-reward ratios.
This strategy can be implemented manually by monitoring charts or automated using trading platforms and tools like MetaTrader, TradingView scripts, or custom algorithms in Python with libraries like Pandas and TA-Lib.
This approach helps traders enter positions in line with the prevailing market trend while using the slowma as a guide to confirm the trend's strength.
buy and sell if previous candle 4h close below or above the slowma depending on the trend , //@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. //
// - 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 // - 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 // © 2013 John F. Ehlers 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
// 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 entryCondition = crossover(RSIndex, FastAtrRsiTL) 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
To implement your strategy using the initial guidance you provided—buying and selling based on the previous 4-hour candle close in relation to a slow moving average (slowma) depending on the trend—you can adapt your existing Pine Script.
Below is a version of your script updated to execute buy and sell orders based on the previous 4-hour candle's relationship with a specified moving average. I will also incorporate checking if the candle closed above/below the moving average based on the current trend.
//@version=4
strategy(title="Magic MA Strategy", shorttitle="Magic MA Strat", overlay=true, max_bars_back=2000)
// MA Type, 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)
// Functions to select the MA type
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)
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
// Calculate slow moving average
ma_slow = variant(type3, close, len3)
// Determine trend (example: above MA is uptrend, below MA is downtrend)
trendUp = close > ma_slow
trendDown = close < ma_slow
// Buy Condition: Previous 4-hour candle closes above MA during uptrend
buyCondition = crossover(close[1], ma_slow[1]) and trendUp
// Sell Condition: Previous 4-hour candle closes below MA during downtrend
sellCondition = crossunder(close[1], ma_slow[1]) and trendDown
// Execute Buy Order
if (buyCondition)
strategy.entry("Buy", strategy.long)
// Execute Sell Order
if (sellCondition)
strategy.entry("Sell", strategy.short)
// Plot the moving average on the chart
plot(ma_slow, title="MA Slow", color=color.blue, linewidth=2, transp=0)
variant Function: Used to dynamically calculate different types of moving averages based on the selected type and length.trendUp and trendDown: Determine the trend based on the price's relationship with the moving average.buyCondition and sellCondition: Buy and sell signals are based on whether the previous candle closes above/below the moving average in the appropriate trend.strategy.entry: Executes buy or sell orders when conditions are met.This script assumes you are using it in a backtesting environment like TradingView. Adjust timeframes appropriately, and backtest your strategy thoroughly against historical data. Also, ensure you account for any additional risk management techniques (stop-loss, take-profit) as needed.
Not yet included in a published release.