ProRealCode - Trading & Coding with ProRealTime™
Sorry for the delay, I’ll be back to you in a couple of days.
Hi Roberto.
If i understand your code correct it moves limit and stolploss.
Would you make a version with trailing limit. Where stoploss is not part of the code at all?
This is the working strategy I created for testing:
SL = 300
TP = SL * 5
Sma = average[50,0](close)
IF close CROSSES OVER Sma and Not OnMarket THEN
BUY at Market
ELSIF close CROSSES UNDER Sma and Not OnMarket THEN
SELLSHORT at Market
ENDIF
SET STOP pLOSS SL
SET TARGET pPROFIT TP
//
//------------------------------------------------------------------------------------------------------------------------------------------------
// Trailing Start
//------------------------------------------------------------------------------------------------------------------------------------------------
If 1 = 1 then
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
//
StartPerCentLong = 0.25 //0.25% to start triggering Trailing Stop
StartPerCentShort = 0.25
StepPerCent = 0.5 //50% (of the 0.25% above) as a Trailing Step (set to 100 to make StepSize=TrailStart, set to 200 to make it twice TrailStart)
BasePerCent = 0.08 //0.1-1 Profit percentage to keep when setting BreakEven
PerCentInc = 0.1 // 0.1-1 PerCent increment after each StepSize chunk
//
TrailStartLong = (close / PipSize) * StartPerCentLong / 100 //use current price (CLOSE) for calculations
TrailStartShort = (close / PipSize) * StartPerCentShort / 100 //use current price (CLOSE) for calculations
StepSizeLong = TrailStartLong * StepPerCent / 100
StepSizeShort = TrailStartShort * StepPerCent / 100
//
RoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviour
PriceDistance = 8 * pipsize //7 minimun distance from current price
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 + ((Close - 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 - Close) * 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 Close > (PositionPrice + (y1 * pipsize)) THEN //LONG positions
//
// compute the value of the Percentage of profits, if any, to lock in for LONG trades
//
x1 = (Close - PositionPrice) / pipsize //convert price to pips
IF x1 >= TrailStartLong THEN // go ahead only if N+ pips
Diff1 = abs(TrailStartLong - x1) //difference from current profit and TrailStart
Chunks1 = max(0,round((Diff1 / StepSizeLong) + 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 Close < (PositionPrice - (y2 * pipsize)) THEN //SHORT positions
//
// compute the value of the Percentage of profits, if any, to lock in for SHORT trades
//
x2 = (PositionPrice - Close) / pipsize //convert price to pips
IF x2 >= TrailStartShort THEN // go ahead only if N+ pips
Diff2 = abs(TrailStartShort - x2) //difference from current profit and TrailStart
Chunks2 = max(0,round((Diff2 / StepSizeShort) + 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
//
EntryPrice = TradePrice
IF Not OnMarket THEN
EntryPrice = 0
StopPrice = 0
TargetPrice = 0
TrailPrice = 0
ENDIF
IF LongOnMarket THEN
StopPrice = EntryPrice - (SL * PipSize)
TargetPrice = EntryPrice + (TP * PipSize)
TrailPrice = SellPrice
ELSIF ShortOnMarket THEN
StopPrice = EntryPrice + (SL * PipSize)
TargetPrice = EntryPrice - (TP * PipSize)
TrailPrice = ExitPrice
ENDIF
IF OnMarket THEN
graphonprice TradePrice
graphonprice StopPrice coloured(255,0,0,255)
graphonprice TargetPrice coloured(0,128,0,155)
graphonprice TrailPrice coloured(155,48,255,255)
ENDIF
change values in lines 1-3, then lines 22-26, according to your preferences.
Then post:
so that I can test it.
Hi one thing I notice is that you are coding for the markets allowed exit price – how do you know that for a given market?
As to your last question, YES, just replace the first ten lines with your code, as the trailing stop snippet is not tied to any code (provided you name your variables differently from mine).
As to the first part of your questions, will you please post a drawing with an example of what you mean. Thanks 🙂
I thought I had replied. Essentially with guaranteed stops there is a high ‘gap’ you cant set it in – and with ‘standard’ it still applies but is smaller. I have had issues with trailing stops (or if trailing stops are protecting profit) with the algo being stopped as its tried to place an ‘illegal order’. On charts I can see where I can place it and it wont let me move it to anywhere not allowed as per below. Is there a way of coding for this? ie knowing for that market what the closest I can go is? I think your algo above kind of does this?
When I trade manually (in this case IG) there is a minimum distance for stop loss- higher if guaranteed is selected. Sometimes my algos fail as they try to set it too close to current price. The number seems to be dynamic and is certainly different on each market. Is there a way to determine and code for this?
There’s no way to know when it changes. You must know it when you start your strategy and can’t change it while it’s running.
You may want to add some points to (try to) accomodate for those increases.
As far as I can tell this is related to the changing spread. Thus, when between USA Stock market’s closing and midnight (22:00 to 00:00 Amsterdam as long as daylight savings is equal to USA (which is not so the upcoming week)) … spread is increased to crazy numbers (e.g. 5 for NasDaq). This can be incorporated in the program, so you don’t need to deal with that distance (which is what it comes down to) throughout. Example :
// When daylight savings are equal for our side and USA :
If Time >= 153000 and Time < 220000 then
Spread = 1
elsif Time >= 220000 and Time < 235959 then // IG says that this is >= 230000 but this can't be correct, IMO.
Spread = 5
else
Spread = 2
endif
This in itself is to be incorporated in the stop distance.
… which I don’t do myself with the below as the result (Strategy stopped).
N.b.: I merely feel this is an anomaly at IG’s because the content of the message – 289 points – can’t be correct anyway, or I just don’t get it. What solves it, is not trading during that hour (only counts for 22:00 – 23:00 Amsterdam as after that it is closed for 1 hour), but net this is not worth it because it is a volatile time (earnings) and good trades may occur.
Only once in a while this error occurs and only during that time, BUT have your distance correct in the first place.
Important : When the Strategy is run in Demo (account) this goes far more often wrong (say 10 times more). So this is a bit misleading and not so comfortable.
Hi Roberto.
Is TP used in this code?
This is the same code as above (test code not included), with more comments:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 // NewTrade is true whenever a new trade is opened, be it://// – a trade when there was none previously// – a trade that has changed direction due to a Stop & Reverse (it’s Long and previously was Short and viceversa)//// This will be useful to reset variables to their initial values after a trade has been opened.//NewTrade = (OnMarket AND Not OnMarket[1]) OR (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket)//// Reset variables to their initial value when a new trade shows//IF Not OnMarket OR NewTrade THEN //reset to default values when a new trade has been opened (or none is OnMarket)PerCentTP= 2.0 //2.0% is TPPerCentStart= 0.2 //0.2% is the Trailing Stop trigger levelPerCentStep= 0.2 //0.2% is each subsequent stepPerCentSaved= 0.1 //0.1% is how much profit has to be saved when trailing starts and every stepMultiplier= 1.5 //1.5 is how much PerCentSaved is incremented each trailing step// 1.5 is a 50% increment, so that:// 0.1% becomes 0.15%, then// 0.15% becomes 0.225%, then// 0.225% becomes 0.3375%, etc…Distance= 6 //6 pip distance from current price (if required by the broker)MySL= 0ProfitPerCent= 0ENDIF//// The trailing stop can operate only when OnMarket//IF OnMarket THEN//// before the trailing stop is triggered some calculations need to be done, accordin to settings//IF MySL = 0 THENPCent= PositionPrice * PerCentTP / 100PStart= PositionPrice * PerCentStart / 100PStep= PositionPrice * PerCentStep / 100PSaved= PositionPrice * PerCentSaved / 100ENDIF//// check if Trailing Stop has to be triggered//IF MySL = 0 THENIF LongOnMarket THENIF (close – PositionPrice) >= PStart THENMySL= min(close,PositionPrice + PSaved)PSaved= PSaved * MultiplierENDIFELSIF ShortOnMarket THENIF (PositionPrice – close) >= PStart THENMySL= max(close,PositionPrice – PSaved)PSaved= PSaved * MultiplierENDIFENDIFELSE//// check if another Step has been triggered//IF LongOnMarket THENIF (close – MySL) >= PStep THENMySL= min(close,MySL + PSaved)PSaved= PSaved * MultiplierENDIFELSIF ShortOnMarket THENIF (MySL – close) >= PStep THENMySL= max(close,MySL – PSaved)PSaved= PSaved * MultiplierENDIFENDIFENDIF//// place Pending STOP orders//IF MySL > 0 THENIF (MySL = close) OR (abs(MySL – close) < Distance) THEN //exit immediately in case MySL has reached// the current price or there’s not enough DISTANCESELL AT MARKETEXITSHORT AT MARKETELSESELL AT MySL STOPEXITSHORT AT MySL STOPENDIFENDIFENDIFif you have more questions don’t hesitate to ask.
Is TP really used in this code?
It is used and set for sure.
It can be triggered, or not, depending on the settings of the trailing stop.
if CB then
BUY Positionsize CONTRACT AT MARKET
set target %profit TP
SET STOP %LOSS sl
endif
// NewTrade is true whenever a new trade is opened, be it:
//
// - a trade when there was none previously
// - a trade that has changed direction due to a Stop & Reverse (it's Long and previously was Short and viceversa)
//
// This will be useful to reset variables to their initial values after a trade has been opened.
//
NewTrade = (OnMarket AND Not OnMarket[1]) OR (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket)
//
// Reset variables to their initial value when a new trade shows
//
IF Not OnMarket OR NewTrade THEN //reset to default values when a new trade has been opened (or none is OnMarket)
PerCentTP = TP //2.0% is TP
PerCentStart = 0.2 //0.2% is the Trailing Stop trigger level
PerCentStep = 0.2 //0.2% is each subsequent step
PerCentSaved = 0.1 //0.1% is how much profit has to be saved when trailing starts and every step
Multiplier = 1.5 //1.5 is how much PerCentSaved is incremented each trailing step
// 1.5 is a 50% increment, so that:
// 0.1% becomes 0.15%, then
// 0.15% becomes 0.225%, then
// 0.225% becomes 0.3375%, etc...
PerCentTP1 = PerCentTP //2.0 //2.0% is TP
PerCentStart1 = PerCentStart //0.2 //0.2% is the Trailing Stop trigger level
PerCentStep1 = 0.2 //0.2% is each subsequent step
PerCentSaved1 = 0.1 //0.1% is how much profit has to be saved when trailing starts and every step
Multiplier1 = 1.5 //1.5 is how much PerCentSaved is incremented each trailing step
Distance = 4//6 //6 pip distance from current price (if required by the broker)
MySL = 0
MySL1 = 0
ProfitPerCent = 0
ENDIF
Hi. should i use TP like this? at 2 places in code (line 19) . and in line 3?
Line 3 is OK, but lines 28-32 are never used, so why did you add them?
Its from your post
I only coded those lines once, in lines 17-21.
BreakEven & Trailing Profit: complete function
This topic contains 137 replies,
has 23 voices, and was last updated by Wim
5 months, 1 week ago.
| Forum: | ProOrder support |
| Language: | English |
| Started: | 03/18/2019 |
| Status: | Active |
| Attachments: | 25 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.