wisebitcoin algorithmic tradingthe mt5 platform has its own built-in language for programming...

32
Wisebitcoin Algorithmic Trading Ver. 2018. 06. EN Copyright 2018 © Wisebitcoin. All rights reserved.

Upload: others

Post on 21-Jan-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

WisebitcoinAlgorithmic TradingVer. 2018. 06. EN

Copyright 2018 © Wisebitcoin. All rights reserved.

TABLE OF CONTENTS 1. What is EA

2. How to Create EA

3. How to Add Indicators in EA

4. How to Add Orders in EA

5. Sample EA Code

6. Strategy Testing

MQL5 Wizard

Data Type

Skeleton of the Code

Compile the File

Order Type

Order EA code

Standard Libraries

What is Strategy Testing

Parameters

Test Result

Visual Testing

7. How to Install EA on MT5

1. What is EA

TheMT5platformhasitsownbuilt-inlanguageforprogrammingtradingstrategies MetaQuotes Language5.Itallowsdeveloping ExpertAdvisors(EA)toautomatetradingprocesses,aswellasimplementingyourowntradingstrategies.

MQL5Features

• Thelanguageisobject-oriented;

• MQL5syntaxissimilartothatofC++;

• Itcontainsalargenumberoffunctionsnecessaryforanalyzingquotes,managingpositions,callingtechnicalindicators,etc.;

• Itisahigh-performancelanguage;

• Highprotectionagainstdecompilation :newcomplexencryptionalgorithms,fileintegritychecking,andthecomplexityofthelanguage;

• Integratedsoftwaredevelopmentenvironment MetaEditor includingadebugger.

1.WhatIsEA

1. What Is EA

2. How to Create EA

MQL5 Wizard

Data Type

Skeleton of the Code

Compile the File

2.HowtoCreateEA

MQL5Wizarda)Click"CreateinMetaEditor"inthecontextmenuofthe NavigatorwindowinsectionExpertAdvisors,IndicatorsorScripts.MetaEditor canalsobelaunchedbypressingF4.

b)press ”Ctrl+N” orclickonthe ”New” buttonontheMenubar

c)IntheMQL5Wizardwindow,selectExpertAdvisorandclick"Next":

2. How to Create EA

d)Inthenextwindow,typetheNameyouwanttogivetoyourEAintheNamebox.

e)Clickingthe“add”buttonandchangingparametersinordertoseewhichofthevaluescangivethebestresult.

ForExample,ifyouwanttoexperimentwithStopLoss,TakeProfit,andMovingAveragePeriodsettings,soyoucandefinethematthispoint. DoubleClickunderthe Name sectionandtypethenameoftheparameter,thendoubleclickunderthe Type toSelectthedatatypefortheparameter,anddoubleclickunderthe Initialvalue sectionandtypetheinitialvaluefortheparameter.

f)Onceyouaredone,itshouldlooksomethinglikethis:

2.HowtoCreateEA

DataType

Fromtheabovedescriptionofthevariousdatatypes,theunsignedintegertypesarenotdesignedforstoringnegativevalues.Anyattempttosetanegativevaluecanleadtounexpectederrors.

SkeletonofthecodeOnceyouaredonesettingallthenecessaryparameters,clickthe Finished buttonandtheMetaQuotes Editorwillcreatetheskeletonofthecodeforyouasshowninthenextfigure.

charThe char typetakes1byteofmemory(8bits)andallowsexpressinginthebinarynotation2^8=256values.The char typecancontainbothpositiveandnegativevalues.Therangeofvaluesisfrom-128to127

ucharThe uchar integertypealsooccupies1byteofmemory,aswellasthe char type,butunlikeit uchar isintendedonlyforpositivevalues.Theminimumvalueiszero,themaximumvalueis255.Thefirstletteruinthenameofthe uchar typeistheabbreviationfor unsigned.

shortThesizeofthe short typeis2bytes(16bits)and,accordingly,itallowsexpressingtherangeofvaluesequalto2tothepower16:2^16=65536.Sincethe short typeisasignone,andcontainsbothpositiveandnegativevalues,therangeofvaluesisbetween-32768and32767.

ushort Theunsigned short typeisthetype ushort,whichalsohasasizeof2bytes.Theminimumvalueis0,themaximumvalueis65535.

int Thesizeofthe int typeis4bytes(32bits).Theminimalvalueis-2147483648,themaximaloneis2147483647.

uint Theunsignedintegertypeis uint.Ittakes4bytesofmemoryandallowsexpressingintegersfrom0to4294967295.

long Thesizeofthe long typeis8bytes(64bits).Theminimumvalueis-9223372036854775808,themaximumvalueis9223372036

ulong The ulong typealsooccupies8bytesandcanstorevaluesfrom0to18446744073709551615.

2.HowtoCreateEA

• Thefirstfivelines(lines1through5)representcommentscontainingthenameoftheEA(filename),thenameofthemanufacturingcompanyanditswebsite.Youcanwritehereanythingyoulike.Thistextwillnotbeseenanywhereandcanevenbeskipped.Theinformationitcontainsonlytargetsthedeveloper;

• Thenext3lines(lines6through8)representthe ParameterBlock.ThisinformationcanbeobservedwhenstartingtheEAintheterminal.ParameterBlock containsinformationfortheterminalallowingittohandletheEAinaproperway.ThemostcommonparametersaretheEAversion,nameofmanufacturingcompanyandabriefdescription.

• Itisfollowedbythe OnInit()function ThisistheOnInit()Block.OnInit()Block gainscontroloncetheEAisloadedintotheterminal.ItcancontainvariousdatarelatedtotheinitializationoftheEA- declaringvariablesandarrays,gettingindicatorhandles,etc.Thatis,thisblockdoesnothaveanyfunctionsthatwouldbedirectlyassociatedwithtrading.

• The OnDeinit(const int reason)functiongoesnext. IthasoneparameterthatspecifiesthereasonforEAshutdown.IftheEAinitializationisunsuccessful,thisfunctionreceivesarelevantcodeasaparameter;

• Thelastfunctionis OnTick().Thisblockcanbesaidtobethe"brains"oftheEAasitcomprisesallfunctionsinchargeoftrades.

CompileTheFile

CompilethecodebypressingF7orclick“Compile”tabinthemenubar.TheexecutablefilehasanextensionEX5andcanberuninthetradingplatform.

2.HowtoCreateEA

ThesourcecodeissavedtothefolderMQL5\Experts\.

MT5EAfilecanbefoundinNavigatorwindow

2.HowtoCreateEA

3. How to Add Indicators in EA

Indicators aresmallprogramswritteninMQLthataredisplayedinthepricechartorinaseparatewindowbelowthepricechartandenableustoperformtechnicalanalysisofthemarket.

Allindicatorscanbeclassifiedintotwotypes: trend-followingindicators and oscillators.Trend-followingindicatorsare,asarule,drawninthepricechartandareusedtoidentifythetrenddirection,whileoscillatorscannormallybeseenbelowthepricechartandservetoidentifyentrypoints.

Mostindicatorshaveatleastonebuffer(indicatorbuffer)thatcontainsitsreadingdataatagiventime.LikeanEA,theindicatorhasitssymbolandtimeframeonwhichitiscalculated.

Indicatorbuffercanbeconsideredasaqueuethelastelementofwhichisarunningvalue.

Indicatorbufferisanarraywherethefirstelement(with0index)carriesdataontherightmostcandlestickandthefollowingelement(withindex1)carriesdataonthesecondcandlestickontheright,etc.Sucharrangementofelementsiscalled timeseries.

Takealookattheexampleasfollows:

AssumethecurrencypairwehaveisBTC/USD,timeframeis1hour.

Firstoff,weneedtoaddtheindicatortotheEAandgetitshandle.

*Handle isauniquepointertotheindicatorthatenablesustoaddressthatindicatoranywhereintheprogram.

Thefirstlinedefinesavariablethatisgoingtostoretheindicatorhandle.Thesecondlinecallstheindicator(here,the MovingAverageindicator),specifiesitsparametersandsavesthehandleintothevariableforfutureuse. Aftertyping"iMA("in MetaEditor,atooltipwillappearabovethatlineshowingcommaseparatedindicatorcallparameters

3. HowtoAddIndicatorsinEA

3. How to Add Indicators in EA

Fig.1.ExampleoftheMovingAverageIndicator

Wecanseethefollowingparameterslistedfromlefttoright:

1.symbolname (appearsinboldlettersinthetooltip)isatextparameter,currencypair(symbol);2.timeframe;3.indicatorperiod (here,theaveragingperiod);4.chartshift byNbarsforward/backward.ApositivenumberdenotesthechartshiftbyNbarsforward,whereasanegativenumberdenotesthechartshiftbyNbarsbackward;5.averagingmethod;6.priceapplied orahandleofadifferentindicator.

Thereisauniquesetofvariablesandtheirtypesforeveryindicator.Ifyoucomeacrossanunknownindicator,theinformationonitcanalwaysbefoundinthebuilt-incontextHelp.Forexample,onceyouhavetyped iMA andpressed F1,aHelpwindowwillopenprovidinginformationonthatspecificindicatorandadetaileddescriptionofallitsproperties.

AfterwritingthecodeandstartingtheEAintheterminal,wewillsee(oncetheEAappearsinthetoprightcornerofthepricechart)thattheindicatorismissingfromthechart.Thisisnotanerror- itwassointended.Inorderforitappear,weneedtoaddanotherline:

Letusnowseewhatitdoes.Hoverthecursoroverthe ChartIndicatorAdd commandandpressF1toreadtheHelpinformationonthepurposeofthecommand.Itsaysthatthiscommand:“Addsanindicatorwiththespecifiedhandleintoaspecifiedchartwindow”

3. HowtoAddIndicatorsinEA

Thesecondparameterwhichisequaltozeroisthesubwindow number.Subwindows usuallycontainoscillators,belowthepricechart.Remember?Therecanbealotofthem.Todisplaytheindicatorinthesubwindow,youonlyneedtospecifythesubwindow numbersothatitisgreaterthanthealreadyexistingnumberby1,i.e.thenumberfollowingthelastexistingone.Havingchangedthecodelineasfollows:

ourindicatorwillappearinthesubwindow belowthepricechart.Nowitistimetotrytogetsomedatafromtheindicator.Forthispurpose,wedeclareadynamicarray,arrangearrayindexingastimeseriesforthesakeofconvenienceandcopyindicatorvaluesintothisarray.

TheaboveexampleshowsthatwehavedeclaredthedynamicarrayiMA_buf[]ofdoubletypeastheMovingAverageindicatorisbasedonpricesandpriceshavefractions.Thenextlinesetstheindexingforthearraysothattheelementswithsmallerindicesstoreoldervalues,whiletheelementswithgreaterindicesstoremorerecentvalues.Thisisusedforconveniencetoavoidconfusionasindicatorbuffersinallindicatorsareindexedastimeseries.ThelastlineservestocopytheindicatorvaluesintotheiMA_buf[]array.Thesedataarenowreadytobeused.

3. HowtoAddIndicatorsinEA

4. How to Add Orders in EA

Order Type

Order EA Code

Standard Libraries

Ordertype

Orders aretraderequestsacceptedbythetradeserver.Iftherequestisinvalid,itwillberejected.

Thereare2typesoforders:marketandpendingorders

1. MarketOrder

Marketordersrepresentinstructionstosellorbuyacertainamountofaspecifiedfinancialinstrumentatthecurrentmarketprice.

2. PendingOrders

Pendingordersrepresentinstructionstoexecutethetradesubjecttocertainconditions.Pendingordershaveacertainexpirationtimeuponwhichtheyaredeleted.

Trades representtheresultsoftheexecutionoforders(instructionstoexecuteatrade).Everytradeisbasedonacertainsingleorder,whereasasingleordercanresultinmultipletrades.Forexample,anordertobuy10lotscanbeexecutedbyapartialexecutionofanumberofconsecutivetrades.Tradesarealwaysstoredinthetradehistoryandcannotbemodified.Theterminaldisplaystradesinthe"History"tab.

Positions representtheoutcomeofordersinaction.Onlyoneposition,eitherLongorShort,canbeopenedforeachsinglesymbol.

StopLossandTakeProfitStopLossandTakeProfitarespecialordersplacedasa"fallbackmeasure".I.e.incaseofmistakesorapositionopenedbytheExpertAdvisorthatisshowingaloss,aStopLossordercanlimitlossesatacertainpredefinedlevel.TakeProfitactsinasimilarway,onlylimitingprofitinthiscase.Itmaybecomenecessarytostopworryingaboutclosingaposition.Itwillgetcloseduponreachingacertainpricelevel.Inotherwords,theseordersrepresentour"insuranceplan",shouldthemarketturnagainstusorshouldwewanttotakeprofit.Thistypeoforderscannotbeplacedseparatelyonitsown- itcanonlymodifyalreadyexistingpositions.

4. HowtoAddOrdersinEA

4. How to Add Orders in EA

Sincetherearevariousorders,eachordertypehasitsownsetofmandatoryparameters.Wewouldnotaddressthesefieldsatlength.Ifevenoneofthemandatoryparametersforacertainordertypeisnotspecifiedorspecifiedincorrectly,therequestwillbefailed.

StandardLibrary

MQL5StandardLibraryiswritteninMQL5andisdesignedtofacilitatewritingprograms(indicators,scripts,experts)forendusers.LibraryprovidesconvenientaccesstothemostoftheinternalMQL5functions.

Tradelibrariesarelocatedinthefollowingpath:MQL5\Include\Trade\ andcanbeaddedusingthe#includedirective.

4. HowtoAddOrdersinEA

Example:

TheaboveclassescanbeconsideredasthebasiconesasthemajorityofExpertAdvisorscanbeprogrammedusingonlythesetwoclasses(libraries).

Thefirstoneisdesignedtoplacedandmodifyorders.Thesecondoneservestoobtaininformationonalreadyexistingpositions.

Attimes,anotherlibrarycanproveuseful:

Itcontainsfunctionsforworkingwithorders,if,say,ourstrategyrequirestheuseofpendingorders.

Hereisanexampleofatraderequestmadeusingthelibrary:

Thereisatotalof6parametershere,onlyoneofwhichismandatory(theordersize- thatisthefirstparameter).

lot isthesizeoftheordertobeplaced;

symbol_name isthesymbol(currencypair)theorderappliesto(ifnoneisspecified,thecurrentsymboloftheExpertAdvisorisused);

price istheopeningprice(sincethisisthefunctionforopeninganactiveorder,itspricemightbeunspecifiedinwhichcaseitwillautomaticallybeobtaineddirectlyfromthepricechart);

sl isthepriceatwhichtheorderwillclose,shouldthepricenotbetoouradvantage(itmaybeleftoutifthestrategydoesnotimplytheuseofstoploss);

tp isthepriceatwhichtheorderwillclose,shouldthepricetaketherequireddirection,i.e.ittakesprofit(itmaybeleftoutifthestrategydoesnotimplytheuseoftakeprofit);

comment isthecommenttotheorder,e.g.specifyingthereasonforplacingtheorder.

4. HowtoAddOrdersinEA

Thereisanumberofwaystocloseaposition:

1. toclosethewholeposition

2.toclosethepositionbyplacingareverseorderofthesamesize

3.byusingamorecomplicatedmethodwherebyallopenpositionsarefirstsearchedthroughtosingleouttheonethatmeetstherequiredparameters(symbol,type,magicnumber, positionidentifier,etc.)tobefurtherclosed.However,wewouldnotgiveanyexampleofthesecaseduetoitsdifficultyforbeginners.

4. HowtoAddOrdersinEA

5. Sample EA Code

5. SampleEAcode

5. SampleEAcode

5. SampleEAcode

6. Strategy Testing

What is Strategy Testing

Parameters

Test Result

Visual Testing

6.StrategyTesting

WhatisStrategyTesting

TheStrategyTesterallowsyoutotestandoptimizetradingstrategies(ExpertAdvisors)beforeusingthemforlivetrading.Duringtesting,anExpertAdvisorwithinitialparametersisoncerunonhistorydata.Duringoptimization,atradingstrategyisrunseveraltimeswithdifferentsetsofparameterswhichallowsselectingthemostappropriatecombinationthereof.

HowtoStartStrategyTest

Click"Test"inthecontextmenuofanExpertAdvisorinthe Navigator window.

Parameters

Beforeyoustarttesting,selectthefinancialinstrumenttotestthetradingrobotoperationon,theperiodandthemode.

6. Strategy Testing

6.StrategyTesting

§ Notethatsymbolspecificationdoesnotmeanthatthetesterwilluseonlythesehistorydata.ThetesterautomaticallydownloadsinformationonallthesymbolsusedintheExpertAdvisor.

§ Beforethestartoftesting/optimization,alltheavailablepricedataofthesymbolofthemainchartareautomaticallydownloadedfromtheserver.Itmaytakequitealongtimeiftheinternetconnectionisslow.

§ Downloadingofalldataisperformedonce,onlythemissinginformationisdownloadedduringthenextstarts.

§ Onlythesymbolsthatarecurrentlyselectedinthe MarketWatch areavailablefortesting/optimization.

§ Thepricedataofallnecessarysymbolsareautomaticallydownloadedfromtheserverduringtestingandoptimization.

§ Testingstartsandendsat00hr.00m.00s.ofthespecifieddates.Thusthestartdateoftesting/optimizationisincludedinthetestingperiod,whiletheenddateisnotincluded.Testingendsontheast tickofthepreviousdate.Alsoyoucannotspecifytheenddate,whichisgreaterthanthecurrentone.Insuchcase,thetestinganywaywillbeperformedtothecurrentdate(notincludingit).

SelectionofInputParameters

Inputparameters allowyoutocontrolthebehavioroftheExpertAdvisor,adaptingittodifferentmarketconditionsandaspecificfinancialinstrument.Forexample,youcanexploretheExpertAdvisorperformancewithdifferent StopLoss andTakeProfit values,differentperiodsofthemovingaverageusedformarketanalysisanddecision-making,etc.Specifyavalueforeachinputparameter.

Parametersets.YoucanatanytimereturntothecurrentsettingsofyourMQL5programbysavingasetofitsparametersusingacontextmenu:

§ Tosavetheparametersasaset-fileonyourcomputer,click"Save".Thesefilescanbemovedbetweenplatformsondifferentcomputersorsenttootherusers.

§ Tosaveparametersforfutureuseinthecurrentplatform,click"SaveVersion".Thesesavedpresetswillbeavailabletheninthe"LoadVersion"sub-menu.Theycanbeappliedatanytimebyselectinganappropriateversionfromthelist.

6.StrategyTesting

TestResult

Tostarttesting,click"Start"onthe"Settings"tab.Thetestingprogressisdisplayedtotheleft.

ResultsofanExpertAdvisortestingaredisplayedontabs"Backtest"and"Graph".

Backtest

Detailedtestingresultsaredisplayedonthe"Backtest "tab.Thetabcontainsgeneraltestingresults,includingprofitandthenumberoftrades,aswellasmanystatisticalvaluestohelpassesstheperformanceofthetradingrobot.Additionalchartsvisualizethedistributionofthenumberandsuccessoftradingoperationsbyhours,daysandmonths,aswellasdescribetheriskparameterofthetradingstrategy.

TestingGraph

Onthe"Graph"tab,youcanvisuallydeterminehowsuccessfullytheExpertAdvisorperformedontheselectedinstrumentintheselectedtimeinterval.Thebalancecurve(blueline)andtheequitycurve(green)areshowninthemainareaofthetab.Datesareshownonthehorizontalscale,balance/equityvaluesareshownontheverticalscale.Thebottompartofthetabfeaturesahistogramoftheloadondeposit,whichiscalculatedastheratioofmarginandequity(margin/equity).

§ Balancevaluesareshownonthecharteachtimetheyarechanged(whenapositionisclosed),equityvaluesareadditionallyshownwithacertainperiodicitybetweenbalancechanges.

§ Whentestingonaccountswiththe exchangeriskmanagementmodel.thechartonlyshowstheequity,whilethebalanceandthedepositloadarenotshown.Thetradingstatusofsuchaccountsisevaluatedbasedontheequitylevel.Thebalanceonlyshowstheamountofmoneyontheaccountandignoresthetrader'sassetsandliabilities.Depositload(margin/equity)isnotdisplayed,becauseintheexchangecalculationmodemarginisequaltothecurrentdiscountedvalueoftheasset/liability,anditchangesalongwithequity.

6.StrategyTesting

VisualTesting

Inthe StrategyTester ofthetradingplatform,youcantestExpertAdvisorsandindicatorsinthevisualmode.ThismodeallowstovisualizeexactlyhowtheExpertAdvisorperformstradeoperationsduringbacktesting.Eachtradeisdisplayedonthechartofafinancialsymbol.

Setup testingoptions and configurationparameters,thenclick"Start".

Visualtestingrunsinanewwindow,whichsimulatesaseparatetradingplatform:itcontainscharts,MarketWatchandtheToolboxwindowwhereyoucanviewtradingoperationsandtheJournal.

• Visualtestingisunavailablewhenoptimizationisenabled.

• Visualtestingcanonlybeperformedonlocalagents.Ifaremoteagentisselectedfortesting,choosealocaloneusingthe"Select"commandinitscontextmenu.

6.StrategyTesting

Testingprocesscontrol

Topause,speeduporslowdownthetesting,usethetoolbar.Youcanalsojumptoaspecificdateofthetest.Youcanconvenientlycontrolthetestingprocessviahotkeys,combinationsarelistednexttothemenucommands.

MonitoringExpertAdvisortestingonachart

ThemainpurposeofthistypeoftestingisthevisualanalysisoftheExpertAdvisorperformance.Achartisgeneratedinrealtimebasedonemulatedhistoricpricedata.Tradingrobotoperationsaredisplayedonthischart.

Tradingoperationsaredisplayedasicons

Adottedlineisdisplayedbetweenmarketentriesandexits.

§ Youcanchangetheappearanceofachart,showindicatorsorgraphicalobjectsonitusing templates.Foratemplatetobeapplied,itsnamemustmatchthenameofthetestedExpertAdvisor,forexampleExpertMACD.tpl.Thetemplateshouldbeplacedinfolder /profiles/templates ofthetradingplatform.

§ Alistofsymbolsavailableinthechartmodeislimitedtothemaintestingsymbol,aswellasthesymbolswhosedataareusedbytheExpertAdvisor.

§ Thecharttimeframe cannotbechanged.The period selectedinthesettingsisusedforthemaintestingchart.PeriodsrequestedbytheExpertAdvisorareusedforothersymbols

§ Toswitchbetweensymbols,usethe"View— Charts"menu.

ViewingpricedatainMarketWatch

TheMarketWatchwindowshowspricesgeneratedduringtesting.ItissimilartotheMarketWatchofthe tradingplatform,buthassomespecificfeatures.Toshow/hidethiswindow,usetheMarketWatchcommandintheViewmenuorpressCtrl+M.

TheSymbolstabfeaturesthecurrentpriceinformationoffinancialinstruments.Thelistofdisplayedsymbolsislimitedtothe maintestingsymbol,aswellasthesymbolswhosedataareusedbytheExpertAdvisor.TheTickstabcontainsachartofprices generated duringtesting.Thenumberofdisplayedticksislimitedto64,000

ViewingdetailsofbarsandindicatorvaluesintheDataWindow

Thedatawindowdisplaysinformationabouttheprices(OHLC),dateandtimeofabar,spread,volumeand indicators.Hereyoucanquicklyfindinformationaboutaparticularbarandappliedindicatorsataselectedpointofthechart.Thewindowcanbeenabledordisabledbyclicking"DataWindow"intheViewmenuorpressingCtrl+D.

(aBuydeal)and (aSelldeal).

7. How to Install EA on MT5

7.HowtoInstallEAonMT5

PleasereferbelowinstructionhowtoinstallanexpertadvisoronMetatrader 5ifyouhaveacompiledfileFirstopenyourMetatrader andclickintheaboveleftcorneron“File>OpenDataFolder”.

Thennavigateto“MQL5>Experts”respectively“MQL5>Experts”andcopyandpastthefileinhere.(ForindicatorscopythefileintotheIndicatorsfolderinstead)ThenrestartyourMetatrader.TheExpertAdvisorshouldshowupintheNavigatorunder“ExpertAdvisors”.Toopen the Navigatorclickon“View>Navigator”orwithCtrl+N.

Nowdouble-clicktheEAordraganddropittothechartandthebelowwindowappears.AllowlivetradingintheCommontabandsetyoursettingsintheInputstabandclickonOK.

7. How to Install EA on MT5

7.HowtoInstallEAonMT5

Thesmileintheaboverightcornerofthechartshouldnowsmile.Ifitdoesn’tclickonAutoTrading.