ProRealCode - Trading & Coding with ProRealTime™
Hi.
There are so many great snippets here.
I use
RobertoGozzi TS with cumulative orders
but i need help.
It starts trailing until in profit but then stops trailing.
Would it be posible to follow the highest candle (bar position) with X-distance.
Se my attached picture
IF MyCOndition THEN
BUY PositionSize CONTRACTS AT MARKET
SET STOP %LOSS 1
set target %profit 2
ENDIF
trailingstopRTS=trail
//RobertoGozzi TS with cumulative orders
IF trailingstopRTS then
ONCE UseCLOSE = 0 //1=use CLOSE, 0=use High/Low
srcH = close //defaults to CLOSE
srcL = close //defaults to CLOSE
IF UseCLOSE = 0 THEN
srcH = high
srcL = low
ENDIF
ONCE UsePerCentage = 1 //0=use Pips (default), 1=use Percentages
ONCE UseEquity = 0 //0=use price (default), 1=use current Equity (initial Capital + StrategyProfit, as defined by variable MyEquity)
MyEquity = 1000
DirectionSwitch = (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket) //True when there's been a change in the direction (likely to be due to a Stop & Reverse)
//
IF Not OnMarket OR DirectionSwitch THEN // when NOT OnMarket or thare's been a change in direction, reset values to their default settings
StartPerCent = 0.25//pc //0.25 = 0.25% movement to trigger Trailing Stop (when UsePerCentage=1)
StepPerCent = 50//spc //50 = 50% (of the 0.25% above) as a Trailing Step (when UsePerCentage=1) (set to 100 to make StepSize=TrailStart, set to 200 to make it twice TrailStart)
TrailStart = 30 //30 Start trailing profits from this point (when UsePerCentage=0)
MinStart = 10 //10 Minimum value for TrailStart (when UseEquity=1, to prevent TrailStart from dropping below ZERO when Equity turns negative)
IF UsePerCentage THEN
TrailStart = (close / PipSize) * StartPerCent / 100 //use current price (CLOSE) for calculations
IF UseEquity THEN //alternative calculations using EQUITY
TrailStart = Max(MinStart,(MyEquity / PipValue) * StartPerCent / 100) //MyEquity is the variable (feel free to use a different name) retaining your current equity
ENDIF
ENDIF
//
BasePerCent = 0.11 //BPC 0.08 - 0.2 Profit percentage to keep when setting BerakEven
StepSize = 10 //ss //5 - 15 Pip chunks to increase Percentage
IF UsePerCentage THEN
StepSize = TrailStart * StepPerCent / 100
ENDIF
PerCentInc = 0.16 //0.16//pci //0.06 - 0.14 PerCent increment after each StepSize chunk
RoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviour
PriceDistance = 12 * pipsize //IG minimum stop distance: DAX = 5, DJ = 12, NAS = 4, SP500 = 1
y1 = 0 //reset to 0
y2 = 0 //reset to 0
ProfitPerCent = BasePerCent //reset to desired default value
//PositionCount = 0
SellPrice = 0
SellPriceX = 0
ExitPrice = 9999999
ExitPriceX = 9999999
ELSE
//------------------------------------------------------
// --- Update Stop Loss after accumulating new positions
//------------------------------------------------------
//PositionCount = max(PositionCount,abs(CountOfPosition))
//
// update Stop Loss only when PositionPrice has changed (actually when increased, we don't move it if there's been some positions exited)
//
//IF PositionCount <> PositionCount[1] AND (ExitPrice + SellPrice)<>9999999 THEN //go on only if Trailing Stop had already started trailing
IF PositionPrice <> PositionPrice[1] AND (ExitPrice + SellPrice) <> 9999999 THEN //go on only if Trailing Stop had already started trailing
IF LongOnMarket THEN
q1 = PositionPrice + ((srcH - PositionPrice) * ProfitPerCent) //calculate new SL
SellPriceX = max(max(SellPriceX,SellPrice),q1)
SellPrice = max(max(SellPriceX,SellPrice),PositionPrice + (y1 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous one
ELSIF ShortOnMarket THEN
r1 = PositionPrice - ((PositionPrice - srcL) * ProfitPerCent) //calculate new SL
ExitPriceX = min(min(ExitPriceX,ExitPrice),r1)
ExitPrice = min(min(ExitPriceX,ExitPrice),PositionPrice - (y2 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous one
ENDIF
ENDIF
// --- Update END
ENDIF
//
IF LongOnMarket AND srcH > (PositionPrice + (y1 * pipsize)) THEN //LONG positions
//
// compute the value of the Percentage of profits, if any, to lock in for LONG trades
//
x1 = (srcH - PositionPrice) / pipsize //convert price to pips
IF x1 >= TrailStart THEN // go ahead only if N+ pips
Diff1 = abs(TrailStart - x1) //difference from current profit and TrailStart
Chunks1 = max(0,round((Diff1 / StepSize) + RoundTO)) //number of STEPSIZE chunks
ProfitPerCent = BasePerCent + (BasePerCent * (Chunks1 * PerCentInc)) //compute new size of ProfitPerCent
ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%
y1 = max(x1 * ProfitPerCent, y1) //y1 = % of max profit
ENDIF
ELSIF ShortOnMarket AND srcL < (PositionPrice - (y2 * pipsize)) THEN //SHORT positions
//
// compute the value of the Percentage of profits, if any, to lock in for SHORT trades
//
x2 = (PositionPrice - srcL) / pipsize //convert price to pips
IF x2 >= TrailStart THEN // go ahead only if N+ pips
Diff2 = abs(TrailStart - x2) //difference from current profit and TrailStart
Chunks2 = max(0,round((Diff2 / StepSize) + RoundTO)) //number of STEPSIZE chunks
ProfitPerCent = BasePerCent + (BasePerCent * (Chunks2 * PerCentInc)) //compute new size of ProfitPerCent
ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%
y2 = max(x2 * ProfitPerCent, y2) //y2 = % of max profit
ENDIF
ENDIF
//------------------------------------------------------------------------------
// manage actual Exit, if needed
//------------------------------------------------------------------------------
IF y1 THEN //Place pending STOP order when y1 > 0 (LONG positions)
SellPrice = max(SellPrice,PositionPrice + (y1 * pipsize)) //convert pips to price
//
// check the minimun distance between ExitPrice and current price
//
IF abs(close - SellPrice) > PriceDistance THEN
//
// place either a LIMIT or STOP pending order according to current price positioning
//
IF close >= SellPrice THEN
SELL AT SellPrice STOP
ELSE
SELL AT SellPrice LIMIT
ENDIF
ELSE
//
//sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
//
SELL AT Market
ENDIF
ENDIF
IF y2 THEN //Place pending STOP order when y2 > 0 (SHORT positions)
ExitPrice = min(ExitPrice,PositionPrice - (y2 * pipsize)) //convert pips to price
//
// check the minimun distance between ExitPrice and current price
//
IF abs(close - ExitPrice) > PriceDistance THEN
//
// place either a LIMIT or STOP pending order according to current price positioning
//
IF close <= ExitPrice THEN
EXITSHORT AT ExitPrice STOP
ELSE
EXITSHORT AT ExitPrice LIMIT
ENDIF
ELSE
//
//ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
//
EXITSHORT AT Market
ENDIF
Endif
ENDIF
Post the values that you used for MyConditions and PositionsSize and the date and time of those candles in your pics.
Timefrem 15
Wallstreet
Date of picture: Today
Follow the highest candle with X distance
DEFPARAM CUMULATEORDERS = false
//=== Risk Management ===
PositionSize=1
//=== Max Monthly Loss ===
ONCE MyProfit = 0
ONCE TradeON = 1
IF Month <> Month[1] THEN
MyProfit = STRATEGYPROFIT //store profits/losses at the beginning of each month
TradeON = 1 //enable trading each new month
ENDIF
IF (STRATEGYPROFIT - MyProfit) < -3500 THEN //disable trading when losing > 200 currency units
TradeON = 0
ENDIF
//=== Entry Filter ===
//Filter 1
indicator1=average[75,7]
indicator2=average[125,7]
indicator3=average[150,7]
F1 = indicator1>indicator2
F2 = indicator2>indicator3
//=== Entry Criteria ===
//Entry Criteria 1
entrylen = 5
LowVol = round(volume[4])
E1 = volume < LowVol
bullish = close>lowest[entrylen](low)
IF E1 AND bullish AND F1 AND F2 AND opendayofweek <> 3 AND opendayofweek <> 4 AND opendayofweek <> 0 AND opendayofweek <> 6 AND TradeON THEN
BUY PositionSize CONTRACTS AT MARKET
SET STOP %LOSS 1
set target %profit 2
ENDIF
trailingstopRTS=1
//RobertoGozzi TS with cumulative orders
IF trailingstopRTS then
ONCE UseCLOSE = 0 //1=use CLOSE, 0=use High/Low
srcH = close //defaults to CLOSE
srcL = close //defaults to CLOSE
IF UseCLOSE = 0 THEN
srcH = high
srcL = low
ENDIF
ONCE UsePerCentage = 1 //0=use Pips (default), 1=use Percentages
ONCE UseEquity = 0 //0=use price (default), 1=use current Equity (initial Capital + StrategyProfit, as defined by variable MyEquity)
MyEquity = 1000
DirectionSwitch = (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket) //True when there's been a change in the direction (likely to be due to a Stop & Reverse)
//
IF Not OnMarket OR DirectionSwitch THEN // when NOT OnMarket or thare's been a change in direction, reset values to their default settings
StartPerCent = 0.25//pc //0.25 = 0.25% movement to trigger Trailing Stop (when UsePerCentage=1)
StepPerCent = 50//spc //50 = 50% (of the 0.25% above) as a Trailing Step (when UsePerCentage=1) (set to 100 to make StepSize=TrailStart, set to 200 to make it twice TrailStart)
TrailStart = 30 //30 Start trailing profits from this point (when UsePerCentage=0)
MinStart = 10 //10 Minimum value for TrailStart (when UseEquity=1, to prevent TrailStart from dropping below ZERO when Equity turns negative)
IF UsePerCentage THEN
TrailStart = (close / PipSize) * StartPerCent / 100 //use current price (CLOSE) for calculations
IF UseEquity THEN //alternative calculations using EQUITY
TrailStart = Max(MinStart,(MyEquity / PipValue) * StartPerCent / 100) //MyEquity is the variable (feel free to use a different name) retaining your current equity
ENDIF
ENDIF
//
BasePerCent = 0.11 //BPC 0.08 - 0.2 Profit percentage to keep when setting BerakEven
StepSize = 10 //ss //5 - 15 Pip chunks to increase Percentage
IF UsePerCentage THEN
StepSize = TrailStart * StepPerCent / 100
ENDIF
PerCentInc = 0.16 //0.16//pci //0.06 - 0.14 PerCent increment after each StepSize chunk
RoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviour
PriceDistance = 12 * pipsize //IG minimum stop distance: DAX = 5, DJ = 12, NAS = 4, SP500 = 1
y1 = 0 //reset to 0
y2 = 0 //reset to 0
ProfitPerCent = BasePerCent //reset to desired default value
//PositionCount = 0
SellPrice = 0
SellPriceX = 0
ExitPrice = 9999999
ExitPriceX = 9999999
ELSE
//------------------------------------------------------
// --- Update Stop Loss after accumulating new positions
//------------------------------------------------------
//PositionCount = max(PositionCount,abs(CountOfPosition))
//
// update Stop Loss only when PositionPrice has changed (actually when increased, we don't move it if there's been some positions exited)
//
//IF PositionCount <> PositionCount[1] AND (ExitPrice + SellPrice)<>9999999 THEN //go on only if Trailing Stop had already started trailing
IF PositionPrice <> PositionPrice[1] AND (ExitPrice + SellPrice) <> 9999999 THEN //go on only if Trailing Stop had already started trailing
IF LongOnMarket THEN
q1 = PositionPrice + ((srcH - PositionPrice) * ProfitPerCent) //calculate new SL
SellPriceX = max(max(SellPriceX,SellPrice),q1)
SellPrice = max(max(SellPriceX,SellPrice),PositionPrice + (y1 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous one
ELSIF ShortOnMarket THEN
r1 = PositionPrice - ((PositionPrice - srcL) * ProfitPerCent) //calculate new SL
ExitPriceX = min(min(ExitPriceX,ExitPrice),r1)
ExitPrice = min(min(ExitPriceX,ExitPrice),PositionPrice - (y2 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous one
ENDIF
ENDIF
// --- Update END
ENDIF
//
IF LongOnMarket AND srcH > (PositionPrice + (y1 * pipsize)) THEN //LONG positions
//
// compute the value of the Percentage of profits, if any, to lock in for LONG trades
//
x1 = (srcH - PositionPrice) / pipsize //convert price to pips
IF x1 >= TrailStart THEN // go ahead only if N+ pips
Diff1 = abs(TrailStart - x1) //difference from current profit and TrailStart
Chunks1 = max(0,round((Diff1 / StepSize) + RoundTO)) //number of STEPSIZE chunks
ProfitPerCent = BasePerCent + (BasePerCent * (Chunks1 * PerCentInc)) //compute new size of ProfitPerCent
ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%
y1 = max(x1 * ProfitPerCent, y1) //y1 = % of max profit
ENDIF
ELSIF ShortOnMarket AND srcL < (PositionPrice - (y2 * pipsize)) THEN //SHORT positions
//
// compute the value of the Percentage of profits, if any, to lock in for SHORT trades
//
x2 = (PositionPrice - srcL) / pipsize //convert price to pips
IF x2 >= TrailStart THEN // go ahead only if N+ pips
Diff2 = abs(TrailStart - x2) //difference from current profit and TrailStart
Chunks2 = max(0,round((Diff2 / StepSize) + RoundTO)) //number of STEPSIZE chunks
ProfitPerCent = BasePerCent + (BasePerCent * (Chunks2 * PerCentInc)) //compute new size of ProfitPerCent
ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%
y2 = max(x2 * ProfitPerCent, y2) //y2 = % of max profit
ENDIF
ENDIF
//------------------------------------------------------------------------------
// manage actual Exit, if needed
//------------------------------------------------------------------------------
IF y1 THEN //Place pending STOP order when y1 > 0 (LONG positions)
SellPrice = max(SellPrice,PositionPrice + (y1 * pipsize)) //convert pips to price
//
// check the minimun distance between ExitPrice and current price
//
IF abs(close - SellPrice) > PriceDistance THEN
//
// place either a LIMIT or STOP pending order according to current price positioning
//
IF close >= SellPrice THEN
SELL AT SellPrice STOP
ELSE
SELL AT SellPrice LIMIT
ENDIF
ELSE
//
//sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
//
SELL AT Market
ENDIF
ENDIF
IF y2 THEN //Place pending STOP order when y2 > 0 (SHORT positions)
ExitPrice = min(ExitPrice,PositionPrice - (y2 * pipsize)) //convert pips to price
//
// check the minimun distance between ExitPrice and current price
//
IF abs(close - ExitPrice) > PriceDistance THEN
//
// place either a LIMIT or STOP pending order according to current price positioning
//
IF close <= ExitPrice THEN
EXITSHORT AT ExitPrice STOP
ELSE
EXITSHORT AT ExitPrice LIMIT
ENDIF
ELSE
//
//ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
//
EXITSHORT AT Market
ENDIF
Endif
ENDIF
The last trade was closed last Tuesday and no more trades have been opened since then.
Se attached
I prefer not to show all my code.
Do you really need all of it 🙂
Its just about the trail-funtion?
Is it possbile to trail with x-distance from highest canlde?
Explain me what your trailing stop should do, from the start to the end of a trade.
My code was not meant to follow candlesticks. I think it’s better to code a new one.
I like a trailing stoploss function that keep a disctance X from highest candle.
It only trail one way thats up for bulltrade. If the candles goes down it finaly hits the stolploss.
There you go:
DEFPARAM CUMULATEORDERS = false
PositionSize=1
//=== Max Monthly Loss ===
ONCE MyProfit = 0
ONCE TradeON = 1
IF Month <> Month[1] THEN
MyProfit = STRATEGYPROFIT //store profits/losses at the beginning of each month
TradeON = 1 //enable trading each new month
ENDIF
IF (STRATEGYPROFIT - MyProfit) < -3500 THEN //disable trading when losing > 200 currency units
TradeON = 0
ENDIF
//=== Entry Filter ===
//Filter 1
indicator1=average[75,7]
indicator2=average[125,7]
indicator3=average[150,7]
F1 = indicator1>indicator2
F2 = indicator2>indicator3
//=== Entry Criteria ===
//Entry Criteria 1
entrylen = 5
LowVol = round(volume[4])
E1 = volume < LowVol
bullish = close>lowest[entrylen](low)
IF E1 AND bullish AND F1 AND F2 AND opendayofweek <> 3 AND opendayofweek <> 4 AND opendayofweek <> 0 AND opendayofweek <> 6 AND TradeON THEN
BUY PositionSize CONTRACTS AT MARKET
SET STOP %LOSS 1
set target %profit 2
ENDIF
//
trailingstopRTS=1
IF trailingstopRTS then
IF Not OnMarket THEN
PriceDistance = 10 * PipSize //PriceDistance from price as required by the broker
StopDistance = 30 * PipSize //Distance from HIGH
SellPrice = close - StopDistance //The first bar StopDistance is from CLOSE
ELSE
SellPrice = max(SellPrice,high - StopDistance)
IF abs(close - SellPrice) > PriceDistance THEN
IF close >= SellPrice THEN
SELL AT SellPrice STOP
ELSE
SELL AT SellPrice LIMIT
ENDIF
ELSE
SELL AT Market
ENDIF
ENDIF
ENDIF
//
graphonprice SellPrice coloured(0,128,0,150)
at the beginning the stoploss distance is from CLOSE (the entry price), not from HIGH obviously. From then on it starts following any higher high.
Thanks robertogozzi.
I thoght this would be a great idea för tariling, but backtest proves me wrong 🙁
I prefer not to show all my code.
Do you really need all of it 🙂
Its just about the trail-funtion?
Is it possbile to trail with x-distance from highest canlde?
murre87 “I prefer not to show all my code” 🙂 That’s all you ask people to do on this site! Hahahaha Think you should share it to e fair
Shame to waste Roberto kindness, so link to above added as Log 304 here
I’ll have a go using it later on a few of my Algos. Never seen much improvement with any trailing stop.
We could do with a dedicate topic to try and bottom out what TS’s work and with what type of strategy.
Hello everybody,
May I ask you something please ?
How to code capital protection? For example, if I have an initial capital of €5000, and after a few days I earn €1000,
I must protect this new capital and put a stop for example at €1100. If my new capital subsequently drops to €800, I will leave the program.
Thank you and have a good day.
Below is the post above … easier for readers …
Hello everybody,
May I ask you something please ?
Try this one:
ONCE LockingPC = 20 //20% of profits to be locked in
ONCE TotalProfits = 0
ONCE LockTreshold = 0
MyLongConditions = close CROSSES OVER average[20,0](close) AND Not OnMarket
IF MyLongConditions THEN
BUY 1 CONTRACT AT MARKET
SL = close - (100 / PipSize)
TP = close + (200 / PipSize)
SET STOP PRICE SL
SET TARGET PRICE TP
//after any gain, the SL can't exceedd the locked profits treshold
IF LockTreshold > 0 THEN
SL = TradePrice - min(100,LockTreshold / PipValue)
ENDIF
SET STOP PRICE SL
ENDIF
//check profits and set the treshold accordingly
IF (StrategyProfit - StrategyProfit[1]) THEN
TotalProfits = TotalProfits + (StrategyProfit - StrategyProfit[1])
IF TotalProfits > 0 THEN
LockTreshold = max(0,max(LockTreshold,(TotalProfits * LockingPC / 100)))
ENDIF
ENDIF
//debugging instructions
graph StrategyProfit - StrategyProfit[1]
graph TotalProfits coloured("Blue")
graph LockTreshold coloured("Red")
graphonprice SL coloured("Red")
graphonprice TP coloured("Blue")
RobertoGozzi Trail – Stops trailing
This topic contains 14 replies,
has 5 voices, and was last updated by
robertogozzi
1 year, 4 months ago.
| Forum: | ProOrder: Automated Strategies & Backtesting |
| Language: | English |
| Started: | 09/23/2021 |
| Status: | Active |
| Attachments: | 3 files |
The information collected on this form is stored in a computer file by ProRealCode to create and access your ProRealCode profile. This data is kept in a secure database for the duration of the member's membership. They will be kept as long as you use our services and will be automatically deleted after 3 years of inactivity. Your personal data is used to create your private profile on ProRealCode. This data is maintained by SAS ProRealCode, 407 rue Freycinet, 59151 Arleux, France. If you subscribe to our newsletters, your email address is provided to our service provider "MailChimp" located in the United States, with whom we have signed a confidentiality agreement. This company is also compliant with the EU/Swiss Privacy Shield, and the GDPR. For any request for correction or deletion concerning your data, you can directly contact the ProRealCode team by email at privacy@prorealcode.com If you would like to lodge a complaint regarding the use of your personal data, you can contact your data protection supervisory authority.