MQL5 Site - 'The Algorithm of Ticks' Generation Within The Strategy Tester of The MetaTrader 5 Terminal - MQL5 Articles
MQL5 Site - 'The Algorithm of Ticks' Generation Within The Strategy Tester of The MetaTrader 5 Terminal - MQL5 Articles
MQL5Site/'TheAlgorithmofTicks'GenerationwithintheStrategyTesteroftheMetaTrader5TerminalMQL5Articles
TheAlgorithmofTicks'GenerationwithintheStrategyTesteroftheMetaTrader5Terminal
MetaQuotesSoftwareCorp.|2June,2010
CreatingExpertAdvisorsautomatedtradingsystemsinMQL5
TheMetaTrader5terminalcontainsanintegrateddevelopmentenvironmentforthedevelopmentoffullyautomatedstrategies(tradingrobots),
which can perform trading without any human intervention. Another name for these trading robots is Expert Advisors. Expert Advisors and
technicalindicatorsfortheMetaTrader5terminalarewrittenusingtheMQL5language,whichencompassesalloftheadvantagesofthemodern
programminglanguages.
executionspeed
supportofobjectorientedprogramming(OOP)
abilitytodebug.
TheabilitytodebugprogramsinMQL5allowsyoutocreateacodewiththemaximumsecuritylevelpossible,butthoughnecessary,thisisnotthe
only condition required for the development of a profitable trading system. Trading systems, which are able to demonstrate positive results
throughoutalargeintervalofhistoricaldata,arecalledrobust,whichisderivedfromtheEnglishword"robust",meaningtoleranttofaultsand
errors.
Testingtradingstrategies
PriortoentrustingyourcapitaltoanExpertAdvisor,youmustmakesurethatitsrulesforopeningandclosingpositions,aswellasrulesofmoney
managing,allowforprofitexpectation.ThesimplestwaytotestthisistosimulatetheworkoftheAdvisorusinganavailablehistoricaldata.
TheMetaTrader5clientterminalhasaspecialintegratedcomponent,astrategytesterforobtainingresultsoftheAdvisor'sworkwithhistorical
data. The process of a onetime run of the Expert Advisor on an interval of dates is called the testing of the Expert Advisor. This onetime test
providesuswithalargeamountofusefulinformation,necessaryfordrawingconclusionsabouttherobustnessoftheExpertAdvisor.
But to be able to trust these results, the process of testing must model the actual current environment, in which the Expert Advisor is run, as
closelyaspossible.TheMetaTrader5testerusesatickbytickmodelingofprices,usingthehistoricalvaluesofspreadsforeachinstrument,on
whichatradingoperationtakesplace.
Alittlehistoryaboutthestrategytester
MetaTrader3
ThefirststrategytesterinitiallyappearedintheMetaTrader3terminal.Thiswasarelativelysimpletesterbymodernstandardsitperformed
testingbasedonthreemodelsofpricesdevelopmentatthebar:
ModeloffourpricesthepriceconsecutivelywentthroughstagesofOpen,Low,HighandCloseforthebullishcandle,andforthebearish
candleitwentthroughOpen,High,LowandClose
Themodel"Every1point"usesawavemodel353,inwhichthepriceconsecutivelygoesthroughathreewave,thenafivewave,and
thenanotherthreewave,withanincrementof1point
Model"Spread/2"usesthesamemodelas"Everyonepoint",butthepriceincrementishalfofthespread,indicatedbytheuser.
Pricemodelinghasalwaysbeenbasedonthebarsofthetestedtimeframe,informationfromlowertimeframeswerenotused.Thetesterfrom
the MetaTrader 3 terminal had many shortcomings, including slow testing speed, low accuracy, and the lack of Expert Advisor optimization by
inputparameters.
MetaTrader4
TheMetaTrader4terminalreplacedthethirdterminalandincludedanewcompiledlanguageMQL4(PreviousMQLIIwasinterpreted),aswellas
tookanabsolutelynewapproachtotesting.Nowtestingcouldbecarriedoutinthreemodes:
Everytick(EveryTick)generationoftickswithinthecandle,allowsforamaximumclosemodelingofExpertAdvisor'sworktorealtrading,
withinthetestingenvironment
Checkpoints(Controlpoints)acompromisebetweenaccuracyandspeedoftesting
Byopeningprices(OpenPrice)thelaunchoftheExpertAdvisorismadeonlyattheopeningofthecandle,thisallowsforaveryrapid
assessmentofthestrategy.
AnimportantdifferencefromthetesterofthethirdterminalwasthatthetestingstrategyoftheMetaTrader4terminalusedthepricedataofthe
youngestavailabletimeframefortradingsimulation.Therefore,withthepresenceoftheminutehistory,throughoutthetestedinterval,thetest
resultsaremaximallyclosetotheresultsobtainedonline.Intheabsenceoftheunderlyingtimeframes,simulationofpricedevelopmentwithin
thebarisgeneratedinthesamewayasinthetesterterminalofMetaTrader3.
Inaddition,wegainedanopportunitytoperformoptimizationbydirectenumerationofinputparameters,aswellasusingagenetic algorithm.
This gave us an opportunity to significantly accelerate the process of optimization, especially for strategies with a large number of input
parameters.Itisnowpossibletoconducttheactualtestinginthevisualregime.Thiswasahugestep,whichwasappreciatedbytraders.
ThenewMetaTraderterminalofthe5thgenerationisbasedontheexperiencegainedfromthedesignofthepreviousterminals,andthisapplies
tothestrategytester.Nowthereisanopportunitytoconducttestingofmulticurrencystrategies,i.e.strategieswhicharesimultaneouslytraded
onmultipleinstruments.
Strategyoptimizationcannowbeconductednotonlyonallavailableprocessorcores,butalsoonremoteagents,locatedonothercomputersin
the LAN and the global Internet network. This allows you to build up the powers of the tester and perform cloud calculations, which were
https://www.mql5.com/en/articles/75?print=
1/6
23/09/2015
MQL5Site/'TheAlgorithmofTicks'GenerationwithintheStrategyTesteroftheMetaTrader5TerminalMQL5Articles
previouslyinaccessible,directlyinthelanguageofMQL5.
ButforabasicunderstandingofthetestingprocessintheMetaTrader5terminal,itiscriticaltobeabletounderstandhowthemodelingofprices
inastrategytestertakesplace.
Algorithmofticks'generation
StrategyTesteroftheMetaTrader5terminalusesonlyonemodeofpricemodelingintestingthegenerationofticksonthebasisofexisting
historicaldataonminutetimeframesoftheusedsymbols.TheremainingmodesofsimulationsinMetaTrader4wereremovedbecausedespite
theirhighspeed,theyfailedtoprovideahighaccuracyoftesting.
UsinganM1timeframeinthetester,allowsforaveryaccuratesimulationofthepricemovement,withaminimumnumberoferrors,incontrast
tothesimulationofticksbasedonseniortimeframes.Asaresult,theerrorsinthemodelingofpricesintheMetaTrader5strategytesterare
trivial,andthedifferencesbetweenthesimulatedpriceandthepricethattookplaceinreality,canonlybewithinthescaleofaminutebar.
Theabilitytoperformoptimizationonlocalandremoteagents,inthisapproach,cancompensatefortheincreaseintestingtime.Thegeneration
ofticksisbasedonthecachedminuteentriesinanintegerformat.Therefore,thegenerationofticksismadeveryquickly.
Thebarsofalltherequiredtimeframesareformedinthehistoricaldatabaseofthetesterintheusualway(justlikeintheclientterminal)with
thereceivingofthegeneratedticks.Theminutebartickvolume1isnotsubjectedtoanygenerationitcanbewrittenwithavalueofClose.
Abarwith2ticksalsoisn'tgeneratedfirstitstickvalueisrecordedasOpen,thenatickwithavalueofCloseisrecorded.
Abarwith3ticksisgeneratedaccordingtoascheme,forthreetickbarsthereareonly4patternofbardevelopment:
1. WentinonedirectionandreturnedtothelevelofOpen
2. Wenttooneside,fellback,andreachedalevelOpen
3. Wentinonedirection,fellback,butdidnotreachedthelevelofOpen
4. Severalpointsinonedirection
Supportpoint
https://www.mql5.com/en/articles/75?print=
2/6
23/09/2015
MQL5Site/'TheAlgorithmofTicks'GenerationwithintheStrategyTesteroftheMetaTrader5TerminalMQL5Articles
Ifthebarhasmorethan3ticks,thenfirstthesupportpointsaregenerated.Thenumberofsupportpointscannotbegreaterthanthevolumeof
thetick.Theopeningpriceisnotincludedincountingthenumberofsupportpoints,sinceitisthestartingpoint.Maximumnumberofsupport
points11.
Supportingpointsaredistributedbetweentheopeningshadow,thescaleofthecandle,andtheclosingcandleshadow.
Dependingonthenumberofticksthedistributionofsupportpointsisasfollows(openingshadowthescopeofthecandleclosingtheshadow):
353
262
252
242
232
141
131
121
111
Ifthecandledoesnothaveoneoftheshadows,thenthesupportpointsoftheseshadowsaregiventothemagnitudeofthecandles.
Thescopeofthecandleisgeneratedbyanoddnumberofsupportpoints.Ifthescopehasanevennumberofsupportpoints,thenthe"extra"
pointisgiventooneoftheshadowsundertheconditionthattheshadowalreadyhas2points.Otherwise,the"extra"pointsimplydisappears.
Thevaluesofthesupportpointsrepresentthedifferencebetweenthepriceofthesupportpointandtheopeningpriceofthecandles.Theideal
distribution(353)ofsupportpointsforabull(white)candleisasfollows:
Forabear(black)candlegenerationofsupportpointsonthe353patternissimilar:
Ifthecandleisadoji,thatisClose==Open,thenthepreviouscandlesareanalyzed,ifthepreviouscandlewasrising,thenthisdojiis
consideredtobeacandledownwardcandle.
https://www.mql5.com/en/articles/75?print=
3/6
23/09/2015
MQL5Site/'TheAlgorithmofTicks'GenerationwithintheStrategyTesteroftheMetaTrader5TerminalMQL5Articles
Iftheshadowisgeneratedusingthreesupportpointsandintegervalues3/4thesizeoftheshadowand1/2thesizeoftheshadowareequal
(thishappenswhenthedifferencebetweenOpenandLoworOpenandHighisnotgreaterthan2points),thenthegenerationoftheshadow
changesinthefollowingway:
Iftheshadowisgeneratedbytwosupportpoints,thenthecontrolpointsarearrangedinthefollowingway:
Theclosingshadowisgeneratedinasimilarway.
FormationofagroundofsupportpointsfromLowtoHigh
Thescopeofthecandleisgeneratedbyimpulsewaves,thenumberofwavesiscalculatedas:
numberofwaves=(numberofsupportpointsinthescope+1)/2.
Forexample,ifthenumberofsupportpointsinthescopeofthecandleisequalto5(Figure353),then3waveswillbegenerated=(5+1)/2.
Eachimpulsewavehasalengthstepinpoints,whichiscalculatedbytheformula:
step=(HighLow1)/(quantityofwaves)+1
Forexample,thescopeofthecandles(HighLow)=(1.31131.3100)=0.0013is13points,whilethewavelengthstep=(131)/3+1=5
points.
Aftertheimpulsesteppointsshouldberolledbackby1point.Furtherinthecyclethepositionsofsupportpointsarecalculated(forabullcandle):
prev=low
cycle
n1=prev+step
n2=prev+step1
prev=n2
where:
n1firstimpulsepointofsupport
n2secondsupportpointthepointofrollback.
Let'sapplythisalgorithmtoabullcandlesina353scheme,wherethenumberofwavesequalsto3andthestep=5points,point=0.0001:
1. Firststep.Variableprev=Low=1.3100,enterthecycle.
2. Calculatethedataforthefirstwave
https://www.mql5.com/en/articles/75?print=
4/6
23/09/2015
MQL5Site/'TheAlgorithmofTicks'GenerationwithintheStrategyTesteroftheMetaTrader5TerminalMQL5Articles
Wecalculatethepositionofpointn1=prev+step=1.3100+5*0.0001=1.3105.
Wecalculatethepositionofpointn2=prev+step1=1.3100+5*0.00011*0.0001=1.3104
Assignthevaluen2:prev=1.3104totheprevvariable
3. Calculatethedataforthesecondwave
Calculatethepositionofpointn1=prev+step=1.3104+5*0.0001=1.3109.
Wecalculatethepositionofpointn2=prev+step1+5=1.3104*0.00011*0.0001=1.3108
Assignthevalueofn2:prev=1.3108totheprevvariable
4. Calculatethedataforthethirdwave
Wecalculatethepositionofpointn1=prev+step=1.3108+5*0.0001=1.3113.
Exitthecycle,prev=n2=1.3112
Alloftheaboveisdemonstratedforclarityonthepicture:
Calculatingthesupportpointsforbearcandlesisdoneinthesamemanner:
prev=high
cycle
n1=prevstep
n2=prevstep+1
prev=n2
Thegenerationofticksiscarriedoutbasedonsupportpoints
Intermediateticksbetweensupportpointsaregeneratedaccordingtothefollowingrules:
Ifthenumberofticksislargerthanthenumberofpointsbetweenthesupportpoints,thena"saw"isgenerated.
Ifthereareanumberofpointsbetweenthesupportpoints,thenalinearsequenceofticksisgenerated.
Checkticksequence
Inconclusion,letuscomparethetickhistory,recordedfromtheMetaQuotesDemoserveronMay13,2010from13:00to13:30,withthetick
sequencegeneratedbythetesterintheMetaTrader5clientterminal.AnExpertAdvisorwasusedtorecordticksintotheagentlog:
//++
//|Write_Ticks.mq5|
//|CopyrightCopyright2010,MetaQuotesSoftwareCorp.|
//|http://www.mql5.com|
//++
inputdatetimestart=D'2010.05.1313:00:00'
inputdatetimeend=D'2010.05.1314:00:00'
//++
//|Experttickfunction|
//++
voidOnTick()
{
MqlTicktick
datetimetime=TimeCurrent()
//
SymbolInfoTick(Symbol(),tick)
Print(time,tick.bid)
//
if(time>end)ExpertRemove()
//
}
Thehistoryoftickswascollectedonline,usingtheindicatordescribedinthearticleCreatingtickindicators.
https://www.mql5.com/en/articles/75?print=
5/6
23/09/2015
MQL5Site/'TheAlgorithmofTicks'GenerationwithintheStrategyTesteroftheMetaTrader5TerminalMQL5Articles
Bothoftheticksequencestheonefromthetesterandtheonestoredinafilearerepresentedonthechart.Ticksobtainedduringtestingare
representedbyagreencolor,andticksobtainedonthetradingserverMetaQuotesDemo,andrecordedinthefileindicator,arerepresentedbya
bluecolor.
Youcanpointthemousetoanypointonthegraphandreadinformationoneachtickinthepopupwindows:
origin(TesterorHistory)
timeofthetick
priceofthetick.
The graph clearly shows that the quality of simulation ticks in the tester MetaTrader 5 client terminal allows for adequate testing of Expert
Advisorsonhistoricaldata.
https://www.mql5.com/en/articles/75?print=
6/6