Hi, I seem to be getting some further errors for the strategy for the buy & sell signals and notifications. The strategy is as follows:-
A buy signal is generated when the MACD crosses up over the MACD Signal line and the signal line and MACD are below the Zero line, and price closes above the 200 Exponential Moving Average. An email notification is to be generated when the condition is met and an alert is to appear on the chart.
A sell signal is generated when the MACD crosses under the MACD signal line and the signal line and MACD are above the MACD Zero line, and price closes below the 200 EMA. An email notification is to be generated when the condition is met and an alert is to appear on the chart.
A stop loss for a buy signal is based on the most recent swing low and/or the 200 period Exponential Moving Average whichever is nearest the price when the trade is taken.
A stop loss for a sell signal is based on the most recent swing high and/or the 200 period Exponential Moving average whichever is nearest the price when the trade is taken.
Take Profit can be option 1 an adjustable Risk/Reward ratio (Trailing Stop loss to be at 0) and option 2 an adjustable Trailing Stop loss percentage (risk /reward ratio to be at 0).
My code is as follows:-
fastLength = 12
slowLength = 26
signalLength = 9
emaLength = 200
stopLossPercentage = 1 // Stop loss percentage
takeProfitPercentage = 2 // Take profit percentage
useRiskRewardRatio = 1 // Use risk/reward ratio
riskRewardRatio = 2 // Risk/reward ratio
// Calculate MACD
MyMACD = MACDline[fastLength, slowLength, signalLength](close)
// Calculate 200 EMA
ema200 = average[close, emaLength]
// Generate buy signal
buySignal = crossOver(macdLine, signalLine) and macdLine < 0 and signalLine < 0 and close > ema200
// Generate sell signal
sellSignal = crossUnder(macdLine, signalLine) and macdLine > 0 and signalLine > 0 and close < ema200
// Generate alerts and email notifications
if buySignal then
alert(“Buy Signal”)
sendmail(“Buy Signal”, “A buy signal has been generated.”)
if sellSignal then
alert(“Sell Signal”)
sendmail(“Sell Signal”, “A sell signal has been generated.”)
// Calculate stop loss for buy signal
buyStopLoss = close – (close * stopLossPercentage / 100)
// Calculate stop loss for sell signal
sellStopLoss = close + (close * stopLossPercentage / 100)
// Calculate take profit levels
if useRiskRewardRatio then
buyTakeProfit = close + (close – buyStopLoss) * riskRewardRatio
sellTakeProfit = close – (sellStopLoss – close) * riskRewardRatio
else
buyTakeProfit = close + (close * takeProfitPercentage / 100)
sellTakeProfit = close – (close * takeProfitPercentage / 100)
// Place trades
if buySignal then
buy at close stoploss buyStopLoss takeprofit buyTakeProfit
if sellSignal then
sell at close stoploss sellStopLoss takeprofit sellTakeProfit