Hello
I’m trying to adapt some code (that incorporates ATR based risk management) in order to backtest a strategy that picks a certain H4 candle (in this case 1200 candle) and then buys/sells the break of that candle and then holds the position for 1 bar (or period) and then closes out the position. I’m not sure of the command/code to achieve this, but have started as below.
It’s a very simple strategy that just trades the break of the signal candle and then closes the trade on the close of the entry candle period (so in effect only holds trade open for 1 candle length). It should only trade once per 24hr period.
defparam cumulateorders=false
// --- settings
balance = 10000 //balance of the strategy when activated the first time
minlot = 1 //minimum lot size for the current instrument (example: 1 for DAX)
riskpercent = 2 //risk percent per trade
activationtime = 160000 //Close time of the candle to activate the strategy
//set days of week to trade
if dayofweek=1 then //Monday
daytrading=1
endif
if dayofweek=2 then // Tuesday
daytrading=1
endif
if dayofweek=3 then // Wednesday
daytrading=1
endif
if dayofweek=4 then //Thursday
daytrading=1
endif
if dayofweek=5 then // Friday
daytrading=1
endif
//set ema and atr for risk management
ema = exponentialaverage[1]
atr = averagetruerange[24]
if intradaybarindex=0 then
alreadytraded = 0
case = 0
levelhi = 0
levello = 0
endif
if onmarket or (onmarket[1] and not onmarket) or (currentprofit<>strategyprofit) then
alreadytraded = 1
endif
if time=activationtime then
// If price candle touches MA (even wicks) then look at high or low of signal candle
if high>ema and low<ema then
case = 1
levelhi = CALL"#floor and ceil"[high,10.0,1]
levello = CALL"#floor and ceil"[low,10.0,-1]
endif
endif
//position sizing
Risk = riskpercent/100
//calculate contracts
equity = balance + StrategyProfit
maxrisk = round(equity*Risk)
size = max(minlot,abs(round((maxrisk/StopLoss)/PointValue)*pipsize))
//in all cases put pending orders on market
while case <> 0 and time >=activationtime and daytrading=1 do
if levelhi>0 then
buy size contract at levelhi stop
endif
if levello>0 then
sellshort size contract at levello stop
endif
wend
// Friday 22:00 Close ALL operations.
IF onmarket and (DayOfWeek = 5 AND time >= 220000) THEN
SELL AT MARKET
EXITSHORT AT MARKET
ENDIF
//set target and profit
if onmarket and time>=200000 then
sell at market
set stop loss StopLoss
endif
currentprofit = strategyprofit
Many thanks in advance