Help to program an idea that worked
Forums › ProRealTime English forum › ProOrder support › Help to program an idea that worked
- This topic has 42 replies, 4 voices, and was last updated 8 years ago by quo.
-
-
09/08/2016 at 6:43 PM #12869
Hello everyone.
I have been trading manually since 2011 this method with goods results and i would like to test it in PRT but it takes me long time to get to anywhere.
I would really appreciate if anyone could help me.
The idea is:
1.-Buy when price breaks up an historical maximum
2.- Once i have bought, i set the stop in the minimum between the historical máximun and when i bought (new maximum)
If we have a correction (today low is lower than previous low) we have a new historical high, so:
3.- When the price goes above that point again i move the stop upwards to the lowest of the new two points, ie the lowest of the new two maximums.
i have attached an example.
In have built this in PRT, but it doesn´t work 🙁
1234567891011121314defparam CumulateOrders = falseif not longonmarket and high>highest[300](close)thenbuy 2000 cash at high stopendifvelainicial= Barindex-1Velaactual = Barindexexit= lowest[velaactual-velainicial](low)if longonmarket and low<exit thensell at exit stopendifi know i have used highest of 300 bars instead of the historical high but i think PRT doesn´t allow us to set it.
(i have been thinking use this code given by Nicolas to find out the maximum price):
1234567891011once previousbar = 0once hh = 0once ll = lowif(barindex>previousbar) thenpreviousbar=barindexhh=MAX(hh[1],high)ll=MIN(ll[1],low)endifRETURN hhany help would be really appreciated.
thanks a lot
09/08/2016 at 6:46 PM #1287009/09/2016 at 1:41 PM #12896Hello quo,
Firstly, you are not the first one to get stuck with the comparison between current high and the highest one. You need to test the breach of the highest high from at least 1 period in the past, otherwise, you are testing if the current candlestick high is above its own value, it does not make sense:
123if not longonmarket and high>highest[300](high)[1] thenbuy 2000 cash at high stopendifThen to set a pending stop order with the calculation you made about your ‘exit’ level, don’t test if the current price is already below it to add it on market. Just add it on market and then price reach this level, the trade will exit.
123if longonmarket thensell at exit stopendifI don’t have verify your ‘exit’ variable calculation, maybe there is still a bug with it.
1 user thanked author for this post.
09/14/2016 at 6:53 PM #1310209/14/2016 at 7:07 PM #1310309/15/2016 at 1:17 AM #13106Hi quo, although I’m not by any means an expert (neither in fact an user except for some screeners) on this PRT platform , as a programming exercice and to leave Nicolas rest a bit, I’ve just coded a solution based approx. on your description of the strategy.
Maybe it’s not yet 100% depured and it’s taken me some time too. It’s not as straightforward as your idea so don’t despair if you don’t get it all at first glance.
Feel free to prove it , tamper with it and comment if you want or need (I’m Spanish… just in case…). For your information, I’ve used a correction in the high not the low of the following bar to define the precedent high as a new historic maximum.
This is my go, my excuses to the native English speakers for the odd wrong preposition!
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118// TS name: Historic_Maximum_BO// Description: Buy at historic maximum breakouts.// Sell at relative minimums (or lows) between consecutive historic// maximums.// A new historic maximum is defined by a correction in the// high value (high < high[1]) from a current maximum// Instruments: Stocks/ETFs// Time frame: Daily / Weekly// Features: Only long system. No money management in this version// Version: 01//// Comments: System should give a few operations with a low ratio wins/losses.// Profitability greatly depending on entering and riding at least// one big bullish movement.// minTradeBars should be > 0 (20 for instance for daily TF) to avoid the// effects of very close consecutive minimums with little inter-maximums// corrections (exitPrice too close to current prices).// Ditto for SL and the possible big corrections from very far-off// historic maximums (exitPrice too far from current prices).// *********************************************************************************DEFPARAM PRELOADBARS = 10000// customizable or optional parametersonce startDate = 20110101 // Example date in YYYYMMDD format for backtesting.// Today's date for productiononce size = 2000 // Example fixed capital to tradeonce enterFilter = 0 // Optional. % above maximum to enter positiononce exitFilter = 0 // Optional. % under minimum to exit positiononce TP = 0 // Optional. Take profit in %once SL = 0 // Recommended. Stop loss in %once minTradedBars = 0 // Recommended. Minimal trade span before selling// variables declarationonce historicMax = 0 // historic maximumonce currentMax = 0 // current maximum candidate to historic maximumonce barHistoricMax = 0 // historic maximum barIndexonce barCurrentMax = 0 // current maximum barIndexonce exitPrice = 0 // exit priceonce buyPrice = 0 // buy priceonce barOffset = 0 // aux counter used to set exitPriceonce countBars = 0 // idem for measuring trade durationonce waitForBuyPrice = 0 // semaphore to lock updating of historic maximum// find out historic maximum until startDateif date < startDate thenif high > historicMax thenhistoricMax = highbarHistoricMax = barIndexendifendifIF DATE >= STARTDATE THENif not onmarket then// open position at historic maximum plus filterbuyPrice = historicMax * (1 + enterFilter/100)buy size cash at buyPrice stop // set buy stop order// if price doesn't reach buyPrice because of the filter// not to update historic maximum until position is enteredif high > historicMax and high < buyPrice thenwaitForBuyPrice = 1 // updating not permittedendif// set new historic maximum after exitif not waitForBuyPrice thenif high > historicMax thenhistoricMax = highbarHistoricMax = barIndexendifendif// if position is exited precisely in the correction bar// that updates new historic maximumif currentMax > historicMax thenhistoricMax = currentMaxbarHistoricMax = barCurrentMaxendifcountBars = 0 // reset countBarsendif// if entered position, set new historic maximum and first exitPriceif onmarket and barIndex = TRADEINDEX(1) thenexitPrice = lowest[barIndex - barHistoricMax + 1](low) * (1 - exitFilter/100)historicMax = highbarHistoricMax = TRADEINDEX(1)waitForBuyPrice = 0 // updating permittedendif// set sell stop orderif onmarket thenif countBars >= minTradedBars thensell at exitPrice stopendifendif// manage updating of new historic maximum and new exitPriceif onmarket thencountBars = countBars + 1// keep track of candidates to new historic maximumif high > currentMax thencurrentMax = highbarCurrentMax = barIndexelsif high = currentMax then// keep track of bars with same high = current maximumbarOffset = barOffset + 1elsif high < currentMax and currentMax <> historicMax then// if correction from current maximum then updateexitPrice = lowest[barIndex - barHistoricMax + 1 + barOffset](low) * (1 - exitFilter/100)historicMax = currentMax // update historic maximumbarHistoricMax = barCurrentMax // update historic maximum barIndexendifendifENDIFSET TARGET %PROFIT TPSET STOP %LOSS SL09/16/2016 at 6:52 PM #13168Wow Tikitaka what an effort, thank you very much, amazing.
I have used this system with monthly graphs. No filter in the entry but a 3% filter at the exit. After a fundamental and sector filter i apply the rules i said. I exclude those trades with a big stop because as i risk a fix ammount the quantity sometimes is too little in these trades. Results 90% profit, 35% winning trades. Want to check through PRT rest of variables (DD,PF,etc).
I have been tamperig with it and i would like to say:
1.-Sometimes there is no entry because you put a start date in 2011 and preloads bar of 10.000. I would like the system detect a maximum from the beginning, in fact in the IPO this system works well.
2.- There isn´t SL or TP
3.- I don´t use a filter when i enter a position and 3% in the exit, so i put it directly in the formula. The same with size position, always 2000 cash. No MM to simplify.
4.- i don´t consider mintradebars necessary.
For these 4 points i erased your first part (hope i am not spoiling it)
It looks like gives good entries but it doesn´t go out where it should do. I don´t know why. Maybe was my fault and i didn´t explained it well. I attach the result code and another explanation of the exit process.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778// variables declarationonce historicMax = 0 // historic maximumonce currentMax = 0 // current maximum candidate to historic maximumonce barHistoricMax = 0 // historic maximum barIndexonce barCurrentMax = 0 // current maximum barIndexonce exitPrice = 0 // exit priceonce buyPrice = 0 // buy priceonce barOffset = 0 // aux counter used to set exitPriceonce countBars = 0 // idem for measuring trade durationonce waitForBuyPrice = 0 // semaphore to lock updating of historic maximum// find out historic maximum until startDateif high > historicMax thenhistoricMax = highbarHistoricMax = barIndexendifif not onmarket then// open position at historic maximum plus filterbuyPrice = historicMaxbuy 2000 cash at buyPrice stop // set buy stop order// if price doesn't reach buyPrice because of the filter// not to update historic maximum until position is enteredif high > historicMax and high < buyPrice thenwaitForBuyPrice = 1 // updating not permittedendif// set new historic maximum after exitif not waitForBuyPrice thenif high > historicMax thenhistoricMax = highbarHistoricMax = barIndexendifendif// if position is exited precisely in the correction bar// that updates new historic maximumif currentMax > historicMax thenhistoricMax = currentMaxbarHistoricMax = barCurrentMaxendifcountBars = 0 // reset countBarsendif// if entered position, set new historic maximum and first exitPriceif onmarket and barIndex = TRADEINDEX(1) thenexitPrice = lowest[barIndex - barHistoricMax + 1](low) * (1 - 3/100)historicMax = highbarHistoricMax = TRADEINDEX(1)waitForBuyPrice = 0 // updating permittedendif// set sell stop orderif onmarket thensell at exitPrice stopendif// manage updating of new historic maximum and new exitPriceif onmarket thencountBars = countBars + 1// keep track of candidates to new historic maximumif high > currentMax thencurrentMax = highbarCurrentMax = barIndexelsif high = currentMax then// keep track of bars with same high = current maximumbarOffset = barOffset + 1elsif high < currentMax and currentMax <> historicMax then// if correction from current maximum then updateexitPrice = lowest[barIndex - barHistoricMax + 1 + barOffset](low) * (1 - 3/100)historicMax = currentMax // update historic maximumbarHistoricMax = barCurrentMax // update historic maximum barIndexendifendifThanks for your patience. I didn´t know was so complicated. If we hit the exit we´ll have it, and i will have to invite something to all of you. 😉
09/17/2016 at 7:09 PM #13214Hi Quo.
Did you consider using the MFE trailingstop code?
just add it to the end of yours.
Cheers Kasper
12345678910111213141516171819202122232425262728293031323334//======================TralingSTOP MFE=======================//trailing stoptrailingstop = 20//x1//resetting variables when no trades are on marketif not onmarket thenMAXPRICE = 0MINPRICE = closepriceexit = 0endif//case SHORT orderif shortonmarket thenMINPRICE = MIN(MINPRICE,close) //saving the MFE of the current tradeif tradeprice(1)-MINPRICE>=trailingstop*pointsize then //if the MFE is higher than the trailingstop thenpriceexit = MINPRICE+trailingstop*pointsize //set the exit price at the MFE + trailing stop price levelendifendif//case LONG orderif longonmarket thenMAXPRICE = MAX(MAXPRICE,close) //saving the MFE of the current tradeif MAXPRICE-tradeprice(1)>=trailingstop*pointsize then //if the MFE is higher than the trailingstop thenpriceexit = MAXPRICE-trailingstop*pointsize //set the exit price at the MFE - trailing stop price levelendifendif//exit on trailing stop price levelsif onmarket and priceexit>0 thenEXITSHORT AT priceexit STOPSELL AT priceexit STOPendif//================================================================1 user thanked author for this post.
09/18/2016 at 4:39 PM #1323109/19/2016 at 7:51 PM #13325Hello quo, here I come again.
It’s taken me hours, but finally I’ve got ready the new slimmer version of your strategy, editing out what you don’t need or want and making the needed changes to meet your requirements. Well, at least me thinks. More than 15 years without writing a code line has taken its toll, evidently. That and probably the fact that I am not a boy anymore.
What has mainly kept me “entertained” for ages, and counting, it’s the trade showed in the attached picture. The position should be closed not at the bar selected by the system but at the previous one. Despite all my efforts, I’ve been unable to pin down where the problem is. It’s a minor issue that doesn’t happen, at least for that stock, in weekly test nor in diary with the exit filter set to 3%, but there it is to haunt me :-). If you or any other guy want to jump in and search for the answer, please be my guest.
Anyway, never mind the time long or short. This is the code and, apart from that rare case, should do the trick.
Or will it?
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071// TS name: Historical Maximum_Breakout// Description: Buy at historical maximum breakouts.// Sell at relative minimums (or lows) between consecutive historical// maximums.// A new historical maximum is defined by a correction in the// low value of the bar or bars (low < low[1]) after a new maximum// Instruments: Stocks/ETFs// Time frame: Daily / Weekly / Monthly// Features: Only long system. No money management// Version: 02.1// *********************************************************************************// customizable and optional parametersonce capital = 2000 // Fixed capitalonce exitFilter = 3 // % below minimum to exit position// variables declarationonce historicMax = 0 // historical maximumonce currentMax = 0 // current maximum candidate to historical maximumonce barHistoricMax = 0 // historical maximum barIndexonce barCurrentMax = 0 // current maximum barIndexonce exitPrice = 3 // exit priceonce buyPrice = 0 // buy price// let's begin losing money.. I mean, tradingif not onmarket and barindex > 0 thenif high >= currentMax then//keep track of candidates to new historical maximumcurrentMax = highbarCurrentMax = barIndexelsif high < currentMax and currentMax > historicMax thenif low < low[1] then// correction so update historical maximum and buyPricehistoricMax = currentMaxbarHistoricMax = barCurrentMaxbuyPrice = historicMaxendifendif// open position at new historical maximumif buyPrice > 0 thenbuy capital cash at buyPrice stop // set buy stop orderendifendif// ***************************************************************************// if position entered, calculate initial exitPrice and set sell stop orderif onmarket and barIndex = TRADEINDEX(1) thenexitPrice = lowest[barIndex - barHistoricMax + 1](low) * (1 - exitFilter/100)endifif onmarket and exitPrice > 0 thensell at exitPrice stop // set sell stop orderendif//manage updating of historical maximum and exitPriceif onmarket thenif high >= currentMax thencurrentMax = highbarCurrentMax = barIndexelsif high < currentMax and currentMax > historicMax thenif low < low[1] then// correction so update exit price and then the restexitPrice = lowest[barIndex - barHistoricMax + 1](low) * (1 - exitFilter/100)historicMax = currentMaxbarHistoricMax = barCurrentMaxbuyPrice = historicMaxendifendifendif09/20/2016 at 9:25 PM #13405Hi,
Now I’m getting the hack of it.
Here is the version 2.02 of the strategy: it’s more compact without repeated code and free of the issue mentioned in my previous post!
Should be the final one in no money management mode, if I’ve understood well your concept of correction. Indeed the solution was rather simple, but all is well that ends well.
Cheers
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152// TS name: Historical Maximum Breakout// Description: Buy at historical maximum breakouts.// Sell at relative minimums (or lows) between consecutive// historical maximums.// A new historical maximum is defined by a correction in the// low value of the bar or bars (low < low[1]) after a new maximum// Instruments: Stocks/ETFs// Time frame: Daily / Weekly / Monthly// Features: Only long system. No money management// Version: 02.2// ****************************************************************************// customizable and optional parametersonce capital = 2000 // Fixed capitalonce exitFilter = 3 // % below minimum to exit position// variables declarationonce historicMax = 0 // historical maximumonce currentMax = 0 // current maximum candidate to historical maximumonce barHistoricMax = 0 // historical maximum barIndexonce barCurrentMax = 0 // current maximum barIndexonce exitPrice = 0 // exit priceonce buyPrice = 0 // buy price// let's begin losing money.. I mean, tradingif high >= currentMax then//keep track of candidates to new historical maximumcurrentMax = highbarCurrentMax = barIndexelsif high < currentMax and currentMax > historicMax thenif low < low[1] then// correction so update historical maximum and buy and exit pricesif historicMax = 0 thenexitPrice = lowest[barIndex - barHistoricMax](low) * (1 - exitFilter/100)elseexitPrice = lowest[barIndex - barHistoricMax + 1](low) * (1 - exitFilter/100)endifhistoricMax = currentMaxbarHistoricMax = barCurrentMaxbuyPrice = historicMaxendifendif// open position at new historical maximumif not onmarket and buyPrice > 0 thenbuy capital cash at buyPrice stop // set buy stop orderendif// close position at exitPriceif onmarket and exitPrice > 0 thensell at exitPrice stop // set sell stop orderendif09/29/2016 at 7:42 PM #13929Hi Kasper, thanks for the suggestion. I use trailing stops in other systems but i only trade stocks and long orders so i use percentages. What add this stop to a simply set trailing%stop 10 por example? Will this new modified code works in long stocks? thanks
1234567891011121314151617181920212223//======================TralingSTOP MFE=======================//trailing stoptrailingstop = 10//x1//resetting variables when no trades are on marketif not onmarket thenMAXPRICE = 0MINPRICE = closepriceexit = 0endif//case LONG orderif longonmarket thenMAXPRICE = MAX(MAXPRICE,close) //saving the MFE of the current tradeif MAXPRICE-tradeprice(1)>=trailingstop*close then //if the MFE is higher than the trailingstop thenpriceexit = MAXPRICE-trailingstop*close //set the exit price at the MFE - trailing stop price levelendifendif//exit on trailing stop price levelsif onmarket and priceexit>0 thenSELL AT priceexit STOPendif09/29/2016 at 9:37 PM #13938Hi Tikitaka, sorry for my late answer, too much work.
Thanks for your work. I´ve been checking it and it seen it doesn´t work well. Entry is almost always right but the main problem is the exit.
In graph one (ACX) entry is right but it never exit, i have written what the stop should do.
In graph 2 ACR entries are wrong (no historical max) and exit take place later.
I have tried to find out where is the error but is a lost cause.
thank you anyway, your welcome to come to Almeria and eat some prawns for the effort 🙂
Cheers
Nacho
10/05/2016 at 12:36 PM #14287Hi, back in town.
Bloody hell, you keep trying the system on monthly bars and I keep debugging it only in daily timeframes, where it seemed to be working well. But you’re so right, it doesn’t.
My time is limited now as I’have just begun painstakingly (a matter of try and error) to make changes to my own manual strategies after two losing months in a row but I’ll try and find where the problem is as soon as possible.
Cheers and saludos
10/13/2016 at 11:04 AM #14825High quo and all,
long time no see but as we say in Spanish, “first obligation than devotion” or in better English, business comes before pleasure.
So, I’ve made some little changes in the code to cope with the fact that, to my big surprise, functions (or constants as PRT calls them), such as barIndex, high and low, seem to behave differently for US stocks and for non-US stocks. Don’t ask me why, your guess is as good as mine. Maybe a bug in ProBacktest? I really don’t know.
Anyway, I’ve tested the new code on some Spanish (and US) stocks in monthly timeframe, your market and timeframe of election I presume, and it seems to do OK. Let me a couple of days to test it on daily bars too, for my peace of mind.
Meanwhile, just for wrapping up all, I’ve still got a doubt about your concept of correction: in the attached picture for instance, when does the correction happen, at the 08-apr-2004 bar or at the 12-apr-2004 one? I’ve been coding the first (low < low[1]) but the second seems more ‘canonical’ (you know, lower highs and lower lows). Please, do clarify.
Enough for now. Cheers
-
AuthorPosts
Find exclusive trading pro-tools on