# Untitled

unknown
plain_text
a year ago
2.0 kB
2
Indexable
Never
```//@version=4
strategy("2min MA Cross Strategy with SL, TP, and Trailing Stop", overlay=true)

// Calculate Moving Averages
ma20 = ema(close, 20)
ma200 = ema(close, 200)

// Determine if it's the first 2 min candle after market open
firstCandle = (hour(time) == 9 and minute(time) == 30)

// Determine if it's before 10:00
beforeTenAM = hour(time) < 15

// Conditions for entry LONG
greenCandle = close[0] > low[0]
aboveMA20 = close[0] > ma20[0]
aboveMA200 = close[0] > ma200[0]

// Conditions for entry SHORT
redCandle = open[0] > high[0]
belowMA20 = close[0] < ma20[0]
belowMA200 = close[0] < ma200[0]

// Initialize stop loss, risk, and take profit levels for LONG and SHORT
var float longStopLevel = na
var float longRisk = na
var float longTakeProfitLevel = na
var float shortStopLevel = na
var float shortRisk = na
var float shortTakeProfitLevel = na

if (firstCandle and greenCandle and aboveMA20 and aboveMA200)
longStopLevel := low[0]
longRisk := close[0] - longStopLevel
longTakeProfitLevel := close[0] + 4 * longRisk

if (firstCandle and redCandle and belowMA20 and belowMA200)
strategy.entry("Sell", strategy.short)
shortStopLevel := high[0]
shortRisk := shortStopLevel - close[0]
shortTakeProfitLevel := close[0] - 4 * shortRisk

// Check if the price has reached 2R and update stop loss accordingly
if (strategy.position_size > 0)
if (close[0] >= (strategy.position_avg_price +  2* longRisk))
longStopLevel := strategy.position_avg_price + longRisk

if (strategy.position_size < 0)
if (close[0] <= (strategy.position_avg_price - 2 * shortRisk))
shortStopLevel := strategy.position_avg_price - shortRisk

// Set exit orders