Sei sulla pagina 1di 12

ExpertAdvisorbasedonthe"NewTradingDimensions"byBillWilliams

AlexeyKlenov|11March,2011|Views:8542

Introduction
InthisarticleIwilldiscussthedevelopmentofatradingExpertAdvisor,basedonthebookNewTradingDimensions:Howto
ProfitfromChaosinStocks,Bonds,andCommoditiesbyB.WilliamsfortheMetaTrader5platformintheMQL5language.The
strategyitselfiswellknownanditsuseisstillcontroversialamongtraders.
Itattractsnewcomerswithitsreadystudyofsignalsthatare"almostentirely"deprivedofasubjectiveside,incontrastto,for
example,theinterpretationoftheElliottwavetheory.Butthisisonlyatfirstglance,insomeplacesthedecisionswillstillhaveto
bemadebythetrader.Andthiswillbediscussedfurtherinthearticle.
Theobjectivesofthisarticle:
Todevelop,usingOOPparadigm (Objectoriented programming), a class of EA, which implements trade, based on the
strategyofB.Williams.We'llcallitC_TS_BW
IntheclassC_TS_BWwhenpossible,usereadymadecodesfromtheStandardLibrary.
WriteanEA,whichusestheclassC_TS_BW
TestthedevelopedEAintheStrategyTesteronseveralForexandCFDinstruments
Finally,toconfirmorrefutetheaptitudeofthisstrategyinthecurrentmarketconditions.

1.Indicators
Inthebaseofthetradingsystemtherearesignalsfrom4indicators:
1.
2.
3.
4.

Alligator
Fractals
TheAwesomeOscillator
Acceleration/Deceleration.

1.1.Alligator
TheAlligatortechnicalindicatorisacombinationofBalanceLines(MovingAverages),whichusefractalgeometryandnonlinear
dynamics.
Theblueline(theAlligator'sJaw)istheBalanceLineforthetimeperiodthatwasusedforbuildingachart(a13period
smoothedmovingaverage,shiftedby8barsintothefuture)
The red line (the Alligator's Teeth) is the Balance Line for a significant time period, lower by an order (8period
smoothedmovingaverage,shiftedby5barsintothefuture)
The green line (Alligator's Lips) is the Balance Line for a significant time period, lower by another order (5period
smoothedmovingaverage,shiftedby3barsintothefuture).
TheLips,TeethandJawslinesoftheAlligatorillustratetheinteractionofdifferenttimeperiods.Sincethemarkettrendscanbe
identified only for 1530 percent of the time, we must follow the trends, and not work on markets that fluctuate only within
certainpriceperiods.
WhentheJaws,TeethandLipsareclosedorintertwined,theAlligatorisgoingtosleeporisalreadysleeping.Whenitsleeps,its
hungergrowssothemoreitsleeps,thehungrieritwillbewhenitwakesup.Whenitwakesup,thefirstthingitdoesisit
opensitsmouthandbeginstoyawn.Thenitbeginstohearthesmelloffood:meatofabullorbear,andbeginstohuntforit.
WhentheAlligatorsatisfiesitshunger,itbeginstoloseinterestinfoodprice(theBalanceLinesjointogether)thisisthetimeto
fixatetheprofit.
1.2.Fractals
Allofthemarketsarecharacterizedbythefactthat,forthemajorityoftime,thepricesdonotfluctuatemuch,andonlyfora
shorttimeperiod(1530percent)trendchangescanbeseen.Themostfavorableperiodsfortheextractionofprofitarewhen
themarketpriceschangeinaccordancewithacertaintrend.
Fractals(Fractals)isoneofthe4indicatorsofBillWilliams'tradingsystem,whichallowstodetectthebottomorandthetop.
Thetechnicaldefinitionofanupwardsfractalisaseriesofatleastfivesuccessivebars,inwhichtherearetwobars,beforeand
afterthehighestmaximum,thathavelowermaximums.Theoppositeconfiguration(seriesoffivebars,inwhichbeforeandafter
thelowestminimumtherearetwobarswithhigherminimums)isadownwardfractal.Onachartthefractalshavethevaluesof
HighandLow,andareindicatedbyupwardsordownwardsarrows.
The signals of the technical indicator Fractals need to be filtered, using the technical indicator Alligator. In other words, we
shouldnotconcludeadealtobuyifafractalislocatedbelowtheAlligator'steeth,andweshouldnotconcludeadealtosellifa
fractalislocatedabovetheAlligator'sTeeth.Afterthefractalsignalisformedandisinforce,whichisdeterminedbyitsposition
beyondtheAlligator'sJaws,itremainsasignaluntilitishit,oruntiltheappearanceofamorerecentfractalsignal.
1.3.TheAO(AwesomeOscillator)
TheAwesomeOscillatortechnicalindicatorbyBillWilliams(AwesomeOscillator,AO) is a 34period simple moving average,
builtbytheaveragepointsofthebars(H+L)/2,whichissubtractedfromthe5periodsimplemovingaverage,whichisbuiltby
thecentralpointsofthebars(H+L)/2.Itlet'susknowwhatishappeningatthecurrentmomentwiththemarket'sdrivingforce.
1.4.AO(AcceleratorOscillator)
Priceisthelastelementthatchanges.Beforethepricechanges,thedrivingforceofthemarketchanges,andbeforethedriving
forcechangesitsdirection,theaccelerationofthedrivingforceshouldslowdownandreachzero.Thenitbeginstoaccelerate
untilthepricebeginstochangedirection.

The Acceleration/Deceleration technical Indicator (Accelerator/Decelerator Oscillator, AC) measures the acceleration and
decelerationofthecurrentdrivingforce.Thisindicatorwillchangedirectionbeforethechangeofthedrivingforcetakesplace,
andit,inturn,willchangeitsdirectionbeforethechangeinpricetakesplace.UnderstandingthattheACisanearlierwarning
signal,hasobviousadvantages.

2.Signals
Thetradingsystem,describedinthe"NewTradingDimensions"bookbyB.Williams,usessignalsfromfivetradingdimensions.
Thefirstdimension:overcomingthefractalbeyondtheAlligator'sjaws
Theseconddimension:thesignalsfromtheAOindicator(AwesomeOscillator)
Thethirddimension:thesignalsfromtheACindicator(AcceleratorOscillator)
Thefourthdimension:tradeinzones
Thefifthdimension:balancelinetrade.
Moreaboutthesignalsfromeachdimension.

2.1.Descriptionoftradingbysignalsofthefirstdimension
The"A" fractal (buy signal) is false, because the price breaking occurs below the Jaw line of the Alligator. The "B" fractal is
executedandwehaveanopenedshortposition.Withtheappearenceof"C"fractal,wecloseourshortposition,andalready
haveanetlongposition.
Withthebreakingof"D"fractal,weagainswitchthepositionfrombuytosell.Overcoming"E"fractaltobuy,themarketonce
againtellsusthatthepositionneedstobechangesfromselltobuy.Withtheexecutionofsignalsfrom"G"and"J"fractals,we
addonemorecontracttothelongposition.

Figure1.Anexampleoftradeinsignalsofthefirstdimension

2.2.Descriptionoftradebysignalsoftheseconddimension
Two types of signals of the second dimension were implemented. This is the AO (Awesome Oscillator) indicator zero line
crossoverandthe"Saucer"signal.Let'saccepttheindexingofbarsaswedoinMetaTrader5,ieastimeseries.Thecheckofthe
signalwillbedoneonthezerothbar.
Fortheformationofa"Zerolinecrossover"pattern,theremustbetwobarsoftheindicator.
Thebuysignalisformedwhenthesecondbaroftheindicatorisbelowthezeroline,andthefirstbarisabovethezeroline.The
maximumpriceofthefirstbarwillbethesignal,andifitexceeds,thebuyorderwillbesenttotheserver,usingthecurrent
price.Thesellsignalisformedintheoppositecasecrossover.
Fortheformationofa"Saucer"pattern,theremustbethreeconsecutivebars,andthesecondoneshouldbeared color and
abovethezeroline,whilethefirstonemustbegreenandhigherthanthesecond.Signalingpricewillbethehighestpriceofthe
first bar, which will be valid until it is overcome by the current price or a new buy signal is formed. The sell signals of the
"saucer"patternareformedsimilarlybutontheoppositesideoftheindicator.
Fortheformationofa"Saucer"pattern,theremustbethreeconsecutivebars,andthesecondoneshouldbearedcolorand
abovethezeroline,whilethefirstonemustbegreenandhigherthanthesecond.Signalingpricewillbethehighestpriceofthe
firstbar,whichwillbevaliduntilitisovercomebythecurrentpriceoranewbuysignalisformed.Thesellsignalsof"saucer"
patternareformedsimilarlybutontheoppositesideoftheindicator.
The"TwinPeaks"and"Twinbottoms"signalsarenotconsideredinthisarticleandwillnotbeprogrammedintheEAbecauseof
thefactthattheirformationalmostalwaysoccursontheoppositesideoftheAlligator:thetwinbottomsisbelowthejawsline,
andthetwinpeaksisabovethisline.TradingonsuchsignalscontradictsthesystemisthatinordernottofeedtheAlligator,we
cannotbuybelowthejaws,andwecannotsellabovetheAlligator'sjaws.

ForamoredetaileddescriptionofthesignalsIencouragedyoutoseetheoriginalsource.

Figure2.Anexampleoftradingsignalsoftheseconddimension

2.3.Descriptionoftradesignalsofthethirddimension
In the third dimension there are the "buy above the zero line" and "buy below the zero line" signals, formed by AC indicator
(AcceleratorOscillator).
Firstwelookatthepattern,specifiedinFigure3.Checkingisdoneforazerothbar.Ifthefirstbarisabovethezeroline("A"
case),whichconsistsoftwogreenandoneredbarofahistogram.Meanwhilethepositionofthesecondandthirdbars,with
respecttothezeroline,doesn'tmatter.
Ifthefirstbarisbelowthezeroline("B"case),thenwewillneedthreegreenandoneredbarsfortheformationofabuysignal.
Italsodoesnottakeintoaccounttheremainingbars,withrespecttothezeroline.Thesellsignalsofthethirddimensionare
inverselyanalogous.
Foramoredetaileddescriptionandexamples,refertotheoriginalsource.

Figure3.Exampleoftradeofthethirddimensionsignals

2.4.Descriptionoftradesignalsofthefourthdimension("ZoneTrading")

Thegreenzoneisformedwhentwoindicators(AO+AC)aregreenforasomebar.
Theformationofatradingsignalrequirestwoconsecutivegreenzone,andtheclosingpriceofthefirstbarmustbehigherthan
theclosingpriceofthesecondbar.
Executionisimplementedonceanewbarisopened.Intheoriginal,theexecutionshouldbetheorderwhentheclosingofabar.
TherearesituationswhenthelasttickoftheclosingthebarcanchangethecoloroftheAOorACbars,andifthisoccurs,thenit
turnsoutthatthebuyaccordingtothesignalofthegreenzonewasfalse.Forthesereasons,Iusedtheopeningofanewbarto
buy.
Also,inthefourthdimension,thereisasignaltotrailastoporderforthelongposition.
Thisrequiresfiveconsecutivegreenzones.TheminimumvalueofthepriceofthefirstzoneisusedtosetaStopLoss.Ifthe
stop order does not triggered on the next bar (after it's closure), then we set the Stop Loss at the minimum price of the last
completedbar(shouldbehigherthanthestoporder)withtheopeningofanewone,withoutconsideringthezonecoloronthe
previousbar.
Also, we use a limitation on addition to the opened long position by the number of consecutive green zones: B. Williams
recommends6or8zone.Afterthis,weshouldwaitfortheappearanceofagray(thisiswhenthecolorsofcolumnsforAOand
ACaredifferent)orredzones,whichwillagainallowtofillthepositiontobuyfromthegreenzone.
Thesignaltosellformsa"redzone"amirrorimageofthegreenzone.Thecolorofthezonealsoaffectsthenumberofbars
thatformthesignalfromthe"BalanceLineTrade"(fifthdimension).Forthisline,B.Williamschosethe"teeth"oftheAlligator.
Inthissignal,Iwanttoemphasize,thattheOHLCpricesofthezerothbarparticipateintheformationofthesignal.

Figure4.Anexampleoftradeofthefourthdimensionsignals

2.5.Descriptionoftradesignalsofthefifthdimension
The"Buyabovethebalanceline"pattern(ifthezonegreen)isformedbytwobars.Iftheopeningpriceofazerobar(alsothe
highestpriceofthebaratthismoment)islowerthanthelasthighestpriceofthebar(canbefoundafewbarsback),thenthe
maximumpricefound,willbethepriceforopeningabuypositioninthegreenzone.
Theredorgrayzonesrequireanothermaximum,higherthenthepricetoenterinthegreenzone.Assoonaswefindit(usually
lessthan10barsbackandabovetheAlligator'steeth[Ididn'tfindhowmanybarsbackmustbelookedforsuchapatterninthe
author'stext]),rememberitasthepriceforenteringintheredorgrayzone,inthedirectiontobuy.
Toopenpositionbythe"buyabovethebalanceline"signal,wecheckforthecurrentpriceexceedingthepriceontheeachnew
bar(forthegreen/red/greyzones).

Figure5.Anexampleoftradeofthefifthdimensionsignals

3.TheC_TS_BWclass
3.1.Classpurpose:
Ifpossible,usetheStandardLibraryclasses
Largeamountsof"similardata"shouldbestoredinthestructures
Customizesettings
Obtaintherequirednumberofcalculateddatafromtheindicatorsforanalysis
Whenanewbar,checkforthesignalsfromthefivetradedimensions
Whenanewtick,checksforthesignalforopeningaposition
Calculatethelot,eitherfixedor"pyramiding"(youwilllearnaboutthisalgorithminthemethodCalcLotofthisclass)
AllowtochangethelotoftheEAdirectlyforeachtypeofasignal.Implementthecustomneedofmoneymanagement
algorithms
Trailastoporderoftheopenedposition.Ifnecessary,changethepriceoftheStopLoss,calculatedbytheuserfromthe
EA
Sendorderonthetradeserverandmakeasecondrequestiferror
Prohibittheduplicationoftradesignals(enteronlyonetimeperonesignal)
Minimizethenumberofpublicclassmethods
3.2.TheimplementationofclassC_TS_BW
...Ifpossible,useclassesandmethodsfromtheStandardlibrary
Toperformthistask,youfirstneedtoincludetheappropriatefilesfromtheStandardLibrary.
Thisisimplementedbythecodebelow.
#include<Trade\Trade.mqh>
#include<Trade\SymbolInfo.mqh>
#include<Trade\PositionInfo.mqh>
#include<Trade\HistoryOrderInfo.mqh

Intheprivatesectionoftheclass,declaretheobjectsfortheorganizationoftradingrequests,obtainingtheinformationonthe
symbolandopenedposition,aswellasaccessingthehistoryoforders.
CTradeexp_trade;//tradingmethodsfromtheStandardLibrary
CSymbolInfos_info;//methodsofaccessingtheinformationonsymbol
CPositionInfopos_info;//methodsofobtainingtheinformationonposition
CHistoryOrderInfoh_info;//methodsofaccessingthehistoryoforders

...Largeamountsof"similardata"arestoredinthestructures.
Thisclassusesfourstructures,twoofthemaredeclaredintheprivatesection.Thesearethestructures:
structl_signals//structureofsignalsandtimeofthebar,onwhichtheyappeared
structl_trade//structureofthetimeofthelasttriggeredsignals

Alsotherearetwostructuresinthepublicsection:
structs_input_parametrs//structureofthetuningparameters
structs_actual_action//structureoftheappropriatetradingorder

Theobjectsofthesetypesofstructures:

l_signalslast_signals;//signals
l_tradelast_trade;//processedsignals
s_input_parametrsinp_param;//internalstructureoftheacceptedsettings
s_input_parametrsinp_param_tmp;//receivingstructureofthesettings(receivedthroughalinkwiththeinitializa
s_actual_actionactual_action;//ordersontheserve

Moredetailsaboutthecodeofthestructurescanbefoundintheattachedheaderfile.
...customizesettings
ThistaskisimplementedusingtheInitmethodfromthepublicsection.ParametersforcallsfromtheEA:

stringSymbol_for_trade//symbol,onwhichtheclasswilltrade
ENUM_TIMEFRAMESPeriod_for_trade//theperiodofthechartsymbol,onwhichthesearchforsignalsanditsprocess
s_input_parametrs&inp_param_tmp//receivingstructureoftheclasssettings

Inthismethodalsooccurstheinitializationoftheinvolvedindicatorsandtheorganizingofthenecessarybuffersforreceiving
datafromthem.
...obtaintherequirednumberofcalculateddatafromtheindicatorsforanalysis
ThiscanbedoneusingtheCopyIndValuemethodfromtheprivatesection,theparameters
inttype//whatwerequest(0Alligator,2,3)
intcountValue//amountofdata

Depending on the parameter type, the receiving buffers are automatically substituted for the calculated data, organized as a
timeseriesforclassinitialization.
...duringtheopeningofanewbar...
Asearchforsignalswillbeperformedonlyonceafteropeninganewbar.Todothis,wemeedtodeterminethatmoment.The
NewBarmethoddoesthis,ithasnoinputparametersandinasituationwhenareceivedtickopensanewbar,itreturnstrue,
otherwise,itreturnsfalse.
...checkforthesignalsfromfivetradingdimensions
For each of the trading dimension, I started a separate method. The signals of the first dimension are checked for by
FindSignal_1_dimension.
Callingparameters:

inttype//directionofthefractalforthesearch(0tobuy,1tosell)
double&price_out[]//thisarray,afterasuccessfulsearch,willcontainthefractalprice
datetime&time_out[]//inthisarray,afterasuccessfulsearch,willcontainthetimeofthebaronwhichthefracta

TheanalysisoftheseconddimensionwillbedonebythemethodFindSignal_2_dimension.Callingparameters:
inttype//directionofthesearch(0inthedirectionoftobuy,1inthedirectiontosell)
intsub_type//subtypeofthesearch(0signaloftransferringthezeroline,1sign"saucer")
double&price_out[]//thisarray,afterasuccessfulsearch,willcontainthesignalprice
datetime&time_out[]//thisarray,afterasuccessfulsearch,willcontainthetimeofthebarsignal

TheanalysisofthethirddimensionisdoneusingthemethodFindSignal_3_dimensionwithinput/outputparameters:

inttype//directionofthesearch(0inthedirectionoftobuy,1inthedirectionoftosell)
intsub_type//subtypeofthesearch(0signalontwoidenticalbars,1signalfor"threeidenticalbars)
double&price_out[]//thisarray,afterasuccessfulsearch,willcontainthesignalprice
datetime&time_out[]//thisarray,afterasuccessfulsearch,willcontainthetimeofthebarsignal

TheprocessingofthefourthdimensionisdonebythemethodFindSignal_4_dimension,withinput/outputparameters:

inttype//directionofthesearch(0inthedirectiontobuy,1inthedirectiontosell)
intsub_type//whatwearelookingfor(0signalfromthezones,1tailingstopforfiveconsecutivezones
double&price_out[]//thisarray,afterasuccessfulsearch,willcontainthesignalprice
datetime&time_out[]//thisarray,afterasuccessfulsearch,willcontainthetimeofthesignalbar

ThefifthdimensionismonitoredbytheFindSignal_5_dimension.Parametersofthismethod:
inttype//directionofthesearch(0inthedirectiontobuy,1inthedirectiontosell)
intsub_type//subtypeofthesearch(0signalfortwobars,1signalforthreebars)
double&price_out[]//thisarray,afterasuccessfulsearch,willcontainthesignalprice
datetime&time_out[]//thisarray,afterasuccessfulsearch,willcontainthetimeofthebarsignal

TheentirecheckingisunitedbytheCheckSignalmethod,itdoesnothaveinputparametersandcontains:
Copyingofdatafromtheindicators
Acheckingfortheclosingofaposition(ifitisused)forsomelineoftheAlligator

Resetofthesignalsofthepreviousbar
Searchforactivefractalsinbothdirections
Dependingontheavailabilityofaposition,searchforthesignalsfromthesecondtothefifthdimension,inthedirectionof
anopenposition.
Thismethodisdeclaredinthepublicsection,itneedstobecalledfromtheEA.
withthearrivalofanewtick,checkforthepossibilityofsignaltriggeringforpositionopening
In this class, the method CheckForTradeSignal is implemented, which executes the search for the possibilities of entering a
positionbythecurrentprice.
Callingparameters:
intdimension//numberofthedimension(fromthefirsttothefifth)
inttype//directionofthetrade(0buy,1sell)
intsub_type//signalsubtypefromthetradingdimension(describedinthesignalsearch)
double&price_out[]//signalprice
datetime&time_out[]//timeofthesignalbar

Ifalloftheregulationfortheactivationofasignalarefollowed,thenwereturntrue,otherwisefalse.
The check of the capabilities of processing all of the signals is combined by the method CheckActionOnTick, announced in the
sectionpublic,itneedstobecalledfromtheEA.Therearenoparametersforthecall.Eachsuccessfulsignalisstoredinthe
objectactual_action,theywilllaterbeprocessedinthemethodTradeActualSignals.
calculatetheloteitherfixedor"pyramiding"
TheCalcLotmethodisdeclaredinthepublicsection,andcanbecalledfromtheEA.Itisintendedforthecalculationofthelot
andthefurthermodificationofthevariableLot,declaredintheprivatesectionoftheclass.Callingparameters:
boolexternal//fortheinstallationoftheexternalcalculatedlot,youneedtodirecttothisvariabletrue,
//thenthelotwillbesetbythevalueext_lot.
//Insidethisclass(calculatethelot),themethodiscalledwiththeparameterfalse.
doubleext_lot//externalsizeofthelot
inttype//typeoflotcalculation
//(0startinglot(usethevaluethatwastransferredduringtheinitializationoftheclass,
//1turnoverlot(thesumofthelotofthecurrentpositionandthestartinglot),
//thevaluesfrom5to2areusediftheaggressivetradingmodeisturnedon(meaning"pyramiding").
//Inthismode:5starting,multiplyby5,
//4starting,multiplyby4,
//3starting,multiplyby3,
//2starting,multiplyby2,
//1thefillinglotisequaltothestartinglot

Nowthatwehaveconsideredthefixedlot,let'stalkmoreaboutthe"pyramiding"lot.
Letthestartinglotequalto0.1.Forexample,openbythestartinglotforthesignalfromthefractal,outsidetheAlligator'sjaws,
thetotalpositionwillbe0.1lots.Afterwhichwebegintoanalyzetheincomingsignalsfromthesecondtofivedimensions.As
soonasthesignalistriggered,fillintotheopenpositionby0.5lots(starting,multipliedby5),andobtainthetotalvolumeofthe
positionas0.6lots.Duringthenextsignalinthedirectionoftheopenopenposition,fillinby0.4lots,andthetotalpositionwill
beequalto1.0lots.
Thenextsignalinthedirectionofthepositionwillgiveusanadditional0.3lots,anditsvolumewillbe1.3lots.Thefifthfillinwill
bedonefor0.2lots,andthetotalvolumeofthepositionwillbecome1.5lots.Thefollowingfillinsinthedirectionoftheposition
willoccuronlyby0.1lots.
Thisalgorithmofmoneymanagement()wasdescribedbyB.WilliamsintheTradingChaos.Thepossibilityofinstallationofa
userlotallowsustoimplementpractiallyanycapitalmanagement.
Foracorrectdeterminationofthesequenceofordersinadeal,IusevariousMaginumbers.
Number

Descriptionoftheorder

999

Turnoverorder

1000

Startingorder

1001

Fillingorder(starting1)

1002

Fillingorder(starting2)

1003

Fillingorder(starting3)

1004

Fillingorder(starting4)

1005

Fillingorder(starting5)

Theclasscalculatedtheneedednumber(usingtheCalcMagicmethod),whichlaterwillbeidentiyingthetradingoperationon
theserverbeforesendingofaneworder.
AllowtochangethelotfromtheEA,directlyforeachtypeofsignal.
Ifdesired,youcanimplementintheEAaqueryofthestructureactual_action,inwhichthetradingsignalsarestoresintheform
ofboolvariables.Eachtypeanddirectioniscorrespondedtobyavariable.Ifwehaveavalueoftrue,thenforthistick,theclass
willtrytoproduceatradingoperationbythespecifiedtradingsignal,afterwhichthelotforthissignalcanbechanged.Foreach
tickofthepricechange,theclasssendsonlyoneorderfortheopenpositionorafilling.
The setting of a lot is possible in the EA after the call of the CheckActionOnTick method and before the call of the

TradeActualSignals.Sinceonthecurrentticktherecanbeanumberofsignals,awaitingexecution,onlyonewillbeselected.
Thesequenceofsignalexecution:
Closingtheposition
Executionofoneofthesignalsfromthefractal(opening,refilling,overturnofposition)
The"Saucer"signal
The"Zerolinecrossover"signal
AC"twoequallycoloredbars"
AC"threeequallycoloredbars"
Tradeinzones
TheBalanceline(2barsignal)
TheBalanceline(3barsignal)
Itisthereforenecessarytoconsiderthissequenceduringtheinstallationofthe"user"lotsize.
...Trailingstopoftheopenedposition.Ifnecessary,changethepriceoftheStopLoss,calculatedbytheuserfromthe
EA.
Inthedescribedclass,thereismaintenanceofthestoppriceattheposition,bytheTrailingStopmethod,meaningthepullingup
oftheStopLoss,onlyinthedirectionofincreasingtheprofitsatthepositionforthetriggeringatthisprice.Therearefivemodels
ofmaintenance:
BytheAlligator'sLipsline
BytheAlligator'sTeethline
BytheAlligator'sJawsline
Byfiveconsecutivezonesofthesamecolor(greenzonestobuy,redtosell)
Externalsettingofstopprice.
ThefifthoptionoftheinstallationofaStopLossisimplementedbythemethodSetStopLoss,withasingleparameterdouble&
stoploss. The call must be made from the EA and before the executing method TrailingStop, which checks the prices for
modificationoftheposition,andsendstherequesttotheserver.Afterasuccessfulexecutionofthisprocedure,thevalueofthe
internalvariableStopLossisresetto1.
...Controlthesendingoftheorderoftheopeningdealtotheserver,andifitisunsuccessful,makeasecondrequest.
Forthesendingofatradingorderforopening,closingorturningoveraposition,themethodboolSendOrderisused.Thecalling
parameters:
ENUM_ORDER_TYPEtype//directionofthetradingoperation
double&price_out[]//pointertothesignalprice,afterasuccessfulexecutionoftheoperation,setin1;
datetime&time_out[]//thepointertothesignaltime,afterasuccessfulexecutionoftheoperation,setin1;
stringcomment//thecommentaryfortheorder

ThetestingofallofthetradingsignalsiscombinedbythemethodTradeActualSignals.Thestructureactual_actionstorestrading
orders.Afterthesuccessfullysendingtotheservertheorder(SendOrderreturnstrue),resetthetradingsignalinthestructure
actual_action.Thetradingsignalwillbeactiveuntilwegetapositiveresponseonthesend.
There is also a function in the structure actual_action init , without parameters, which resets all of the current signals. This
procedureisusedwhenopeninganewpositionoranoverturnintheexistingpositionoccurs.
...Prohibittheduplicationoftradesignals(enteronlyonceforeachsignal)
Thelast_tradestructurestoresthetimeofthelasttradingsignalforeachtypeanddirection.Beforeyousetatradingorderinto
the actual_action structure, check to see whether this signal is already trading in the last_trade structure, and if so, ignore it.
Thus,thisprovidestheimplementationofcontrolofthe"disposable"executionofatradingsituation.
Minimizethenumberofpublicclassmethods.
HereisalistofclassmethodsthatareavailablebycallingfromtheEA:
voidC_TS_BW();//Constructor
boolInit(stringSymbol_for_trade,
ENUM_TIMEFRAMESPeriod_for_trade,
s_input_parametrs&inp_param_tmp);//Initializationoftheclass
boolNewBar();//Checkforanewbaronthecurrentsymbol\timeframe
voidCheckSignal();//Searchforsignals
voidCheckActionOnTick();//Collectingthedesiredactionsonthecurrenttick
voidTrailingStop();//TrailingStop
voidTradeActualSignals();//Tradingbythecurrentsignals
voidSetStopLoss(double&stoploss);//SetStopLoss
voidCalcLot(boolexternal,doubleext_lot,inttype);//Calculationofthelot

Alsoavailablearethestructures:
actual_action//Currenttradingordersforexecution
inp_param_tmp;//Receptionofthestructureofsettings
//(receivesthedatabythelinkduringtheinitializationoftheclass)

4.TheimplementationoftheEA,usingtheclassC_TS_BW
Thefirstthingthatmustbedoneistoincludetheh_TS_BW.mqhfileintheExpertAdvisor.
#include<h_TS_BW.mqh>

Afterthis,declaretheobjectofC_TS_BWclass.LetthisbetheEA_TS_BW.

Youwillalsoneedthestructureoftheadjustableparameterssuchass_input_parametrs,forexample,input_parametrs.
Hereisadescriptionoftheparameters,incorporatedintothisstructure:

input_parametrs.alligator_jaw_period//TheAlligator:periodoftheJawsline
input_parametrs.alligator_jaw_shift//TheAlligatpr:shiftoftheJawsline
input_parametrs.alligator_teeth_period//Alligator:periodoftheTeethline
input_parametrs.alligator_teeth_shift//Alligator:shiftoftheTeethline
input_parametrs.alligator_lips_period//Alligator:periodoftheLipsline
input_parametrs.alligator_lips_shift//Alligator:shiftoftheLipsline
input_parametrs.add_1_dimension//AllowtheadditionbyFractals
input_parametrs.add_2_dimension_bludce//Allowtheadditionbythe"Saucer"()signal
input_parametrs.add_2_dimension_cross_zero//Allowtheadditionbythe"Crossingthezeroline"()signal
input_parametrs.add_3_dimension_use_2_bars//Allowtheadditionbythe"2bars"signal
input_parametrs.add_3_dimension_use_3_bars//Allowtheadditionbythe"3bars"signal
input_parametrs.add_4_dimension_zone//Allowtheadditionbytheredorthegreenzone
input_parametrs.add_5_dimension//AllowtheadditionbytheBalanceLine
input_parametrs.max_4_dimension_zone//Themaximumamountofconsecutivebarsofzonesofthesamecolor
input_parametrs.trall_4_dimension//Allowatrailpositionusing5consecutivebarsofzonesofthesamecol
input_parametrs.agress_trade_mm//Aggressivestyleoffillinginanopenposition
input_parametrs.support_position//Typeoftrailingstopoftheposition
input_parametrs.lot//Tradinglot

IntheOnInit()sectionoftheEA,youneedto:
Fillinalloftherequiredvaluesoftheinput_parametrsstructurewithdatathatwillthenbepassedtotheclass.
UsingtheInitmethodofclass,makeitsinitialization.Example:
expert_TS_BW.Init(Symbol(),PERIOD_CURRENT,input_parametrs)

Inthiscase,theEAwillworkonthecurrentsymbol/periodwhereitisinstalled.
ExampleoftheOnTick()sectionofExpertAdvisor:
//doubleSl[1];
if(expert_TS_BW.NewBar())//newbaronthechart
{
expert_TS_BW.CheckSignal();//signalsearch
}
expert_TS_BW.CheckActionOnTick();//checkfortherequiredactionsonthecurrenttick
//*******************theplaceofthebeginningofexternalcontrolofthelot,thestop
//exampleofsettingthelotfortradebythesignalfromthezones
//if(expert_TS_BW.actual_action.zone_buy||expert_TS_BW.actual_action.zone_sell)
//{expert_TS_BW.CalcLot(true,0.11,0);}
//settingthestopbytheparabolic
//CopyBuffer(h_parabolic,0,0,1,Sl);
//if(Sl[0]>0){expert_TS_BW.SetStopLoss(Sl[0]);}
//*******************theplaceoftheendofexternalcontrolofthelot,thestop
expert_TS_BW.TrailingStop();//pullingupthestop(ifnecessary)
expert_TS_BW.TradeActualSignals();//tradingofcurrentsignals

Inthiscase,theexamplesofexternalcontrolofthestoppriceandthetradinglot,fortheexecutionoftheclass,arecommented
on.

5.Sometestsonthehistory
The author of the book, based on which the EA was written, argues that this system is focused on stocks and commodity
markets.
First,let'schecktheExpertAdvisorontheCFD.SupposethetestingpolygonwillbepartofthehistoryofIBM.Thesystemis
aimedatthetrendingsegmentsofquotes.Itookthefirstavailablesegment,onwhichatrendcanbeseenbythenakedeye.

Figure6.IBMchart

RunthewrittenExpertAdvisoronthissegmentandhereiswhatweobtainasorders.

Figure7.ThetradingsignalsofBillWilliams(IBM)

Atfirstglance,therearemanytradesbythetrend,whichisgood.Hereisthechart,createdbytheStrategyTester.
Thetradewasdoneon0.1lots,withoutclosingbytheAlligatorlines,withoutatrailingstopusingthefiveconsecutivezonesof
onecolorandwithoutaggressivetrading(pyramiding).

Figure8.TestResults

Ingeneral,weobtainedprofit.
Nowlet'stakeaprotractedtrendwithalesserinclination.

Figure9.IBMchart(fragment2)

Letthisbethesamesymbolandperiodof13months(from2008.12to2010.01)
HereisachartfromtheStrategyTester:

Figure10.Theresultsoftestingthesystemonthehistory(fragment2)

Let'sjustsay,it's"notsatisfactory"or"hasnotmetourexpectations."
NextIwouldliketochecktheworkonthecurrencypairs.
Let'stakethewellknownEURUSDpairandtheH1periodofthechart.Thedepthofthehistoryistheyearof2010.

Figure11.Theresultsoftestingthesystemonthehistory,EURUSD,H1,2010

Let'stryitonthedailybarsofEURUSDforthesameyear(2010).
Thereportofthetesterlookslikethis:

Figure12.Theresultsoftestingthesystemonthehistory,EURUSD,D1,2010

Conclusion
TheaimofthisarticlewastochecktheperformanceofoneofthewellknowntradestrategiesbyBillWilliams,notonlyonthe
stockmarketsandcommodityexchanges,butalsoontheForexmarket.Thesystemworks"moreorless"ontheEURUSDdaily
chartsofthepastyear,butbringsnoprofitonsmallertimeframes,withoutattemptsofoptimization.
Themarketentrysignalsofthesystemarequietaccurate(ifwelookatthedaycharts),buttheexitsareclearlydelayed,since
morethanhalfoftheprofitisnotfixed.Thisfieldisfortherefiningofthegivensystemintermsofitsoptimizationforsmaller
timeframes.
Thecompletecodeoftheclasscanbefoundintheattachedfile.

TranslatedfromRussianbyMetaQuotesSoftwareCorp.
Originalarticle:https://www.mql5.com/ru/articles/139

Attachedfiles|
DownloadZIP
h_ts_bw.mqh(57.84KB)
tc_bw_new_version_202.mq5(5.16KB)
Warning:AllrightstothesematerialsarereservedbyMQL5Ltd.Copyingorreprintingofthesematerialsinwholeorinpartisprohibited.

JoinusdownloadMetaTrader5!

Windows

iPhone/iPad

MacOS

Android

Linux

MQL5StrategyLanguage|SourceCodeLibrary|HowtoWriteanExpertAdvisororanIndicator|OrderDevelopmentofExpertAdvisor
DownloadMetaTrader5|MetaTrader5TradePlatform|ApplicationStore|MQL5CloudNetwork
About|WebsiteHistory|TermsandConditions|PrivacyPolicy|Contacts
Copyright20002015,MQL5Ltd.

Potrebbero piacerti anche