Sei sulla pagina 1di 18
016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing AmiBroker — Users' Knowledge Base or Windows 9798 MENT 2K? Shate your experience, cade and everything with other AmiBroker Users" ‘April 22, 2011 IIF(. IFO) and Swit functions ‘Many newcomers to AFL are confused by the IFQ, IIFQ and Switch), This pot gives afew simple examples of their use. The IFQ and Switsh() are program flow control statements, the ITF) is a function that gets on all elements of an input aray and returns an output array. In all but the simplest applications the Switch() is the preferred method to the IF( to change program flow. It can be used te code complex decision ‘uses and state machines, for example as these are often needed in automated trading systems. For more detailed explanations click JED, IFO, or Switch. A search ofthe af brary wil also get you many more examples. The IIFO function I is possible to use ifs to individually test and modify each bar in an array for a condition. An example on how this would be dane is shown in the function below (copied from the AmiBroker help), Ths function is an AFL equivalent forthe IIFQ function, ‘function TIF_AFL( condition, inputa, input ) ‘ result = Will; ‘for( bar = @; sar < Barcount; baree ) ‘ 5 conattiont ber 1.) esule[ bar ] = inputa[ bar J; ise result bar ] = Snputal 89 J; > While the above approach works, using the IF() function always provides a better and faster solution. The IIF( is very powerful and should be used ‘whenever possible. Below are afew simple examples to get started. btw, Its highly unlikely that you wil beable to improve on execution time by using # Toop or writing a DLL. ‘To color all bars that fall on @ Monday White Color = HLFt bayorWeck()es2, colorinite, colorslack); Plet{ €, *Clese", color, stylesar )} IIF()s Can be nested. This exemple colors Monday bars White, Wednesday bars Blue and Friday bars Yellow D = oayorieek( Color» TF {D= Plot €, “Clos s colorihite, 11f(0r-3, colorBlue, I1¢{D--5, colervellow, colerBiack)))s S colors stylebar by ‘The IFQ Statement ‘One ofthe most common applications forthe if) is to select what you want to see on your chart Plot( ¢, “Close”, colorbiack, styleBar )s Showal® = Paranfoggle( “Moving Average’, “MAIEMA", ©) se (shows) Plott MAC Cy 18 ), "MAIO", colorkhite, styleLine }5 d ase ‘ Plot BMC Cy 18 ), "MAIO", colorwnite, styleLine ): ? In the above example the IF() basically selects one of two sections of cade, To select one of many options you could the use the elseif extension: Selectedtndicator = ParanList( ‘Show", "mauo,.aSe,nAte0", 2); 4€ ( Setectedinateator smase" ) ‘ Plott MAC Cy 18 ), "MAIO", colorBlue, styleLine }5 phew amibrokororgusurkbcatogoyiat-progamming! 18 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing d aise IF ( setectedinateator susie" ) ‘ Plott BAC Cy 50 J, "MAIO", colomRed, styleLine }5 > ase IF ( seiectedinateator ‘wase0" ) { Plott BAC Cy 100 9, colorveliow, styletine 35 > ‘The Switch Statement ‘When there are many conditions, the lengthy If) expressions can become confusing, difficult to compote, and difficult to modify, Ix such cases it is often better to use the SwitehO) statement, Using a simple Switch) the last example looks much cleaner: Selectedtndicator = ParanList( "Show", "MAi0,AS@,MA1G0", 2 95 Seiten ( SelectedInaiestor ) ‘ Plet( ACC, 18 ), "MAIO", colorslue, styleLine }; breaks case "MAO": Plott MAC C, 58 ), "NASW", colorBlue, styleLine )5 breaks 1Se{ MAC, 100 ), "MAIBD", colorslue, styleLine }5 breaks } ‘Tere ar times that you will have many individually named variables that you would like to process ina Switch() statement. Even though the ‘Switch can only accept a single variable name as argument you can use the method below to work around this limitation ‘function Sayoncet Text ) £6 ( statievarcettext( Lastsay" ) t= Text ) ‘ say Text, False 9; staticvarSetText( “Lastsay", Text ): } > equestTsnedRefresh(1); ‘Triggers = ParanTrigger( “Teigges 1", “TRIGGER” ); ‘Teigger2 = ParanTrigger( “Trigge= 2°, "TRIGGER2” )} Triggers = ParanTeigger( Se) sTarccer3® 3 ‘niggers = Paraniriger( “Trigaes &°, "TRIGGERE™ ) swtteh( 2) t case Trigger Ssyonce( one" )s breaks case trigger? fase Trager: Sayonce(.'2 or 4" 95 breaks case triggers Saynce( Three" 5 breaks efautt: Sayoncet "veraule” 95 77 Were you can place code that will execute 11 wepeatedly wile no other case is true ) ‘The Switch? argument ean be a string or number. Using strings makes code easier to ead. Another advantage of using the Switeb() is that they {oxmat nicely using Edit->Pretify Selection in you editor window, using too many elseif statements tends to run the ifs of the page. As shown above you can stack case statements to have multiple conditions tigger the same task. ‘To implementa simple State Machine you pass the system “state” to the Switeh(). This way you can have any event trigger any sequence of task, and o so in any desired order. Ina teal application the SayOnce() functions in the example code below would be replaced by the task you want to be performed in the state. The next state Would usually be conditionally set inside each state for example you only want to proceed tothe next state after phew amibrokororgusurkbcatogoyiat-progamming! ane 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing an order is filled, ora price is crossed. You can use multilevel Switch) or iff) inside each case section, This use of Switch() statements is very ‘useful in Automated Trading systems. For example to process order status (Pending, Filled Eror, ec) and parsing TWS error messages ‘Since states are saved in a Static Variables they remain valid over multiple AFL executions, and can last indefinitely. You can also save states in Persistent Variables States are processed in Sequential afl executions, ie, you change the state ina case statement tis next state willbe processed in the next AFL reffesh, In some applications this delay can cause problems. To ensue responsive code you might want fo use @ 0.1 sevond reffesh rate. You could remove the delay by using the Switch( inside @loop/whil statement, anf Toop uatilasiable state is reached, ‘function Sayonce( Text) 4 ( StatievarcetText( “Lastsay" ) t= Text } Soy( Text, False 9; StaticvardetText( “Lastsay", Text 5 ? ? oguestsnedefresn(2)3 4{ Parantrigger( "Reset Syster*, "RESET" ) ) staticvarSetText{ “state, “AESET™ A¢( parantragger( "Task 2", “TASK 1") ) SteticvarsetTexc( "state", "TASKI" 3 ¢( Porantrigger( "Task 2°, “TASK 2" } ) StaticvarsetText( "State", "TASC" ); $4¢ arantedggert ok 2°) “Task 3") } Staticvarsetrons( "state"; "ASG" Jy State = StaticvarcetText( state" ); swien( state } ‘ : Sayoncet “Reset” ); StattevarsetTexe( *state", "READY" 5 break Sayoncet. "Ready"; StattevarsetText( *State™, “IOLE™ ); breaks Seyoncet "Task 1" 95 StatrevarsetText( "State", “IOLE™ ); breaks Sayoncet "Task 2" ); StattevarsetText( "State", "TASK" 5 breaks case "TASKS" Sayoncet "Task 3° ); StattevarsatText( "State", "TAS€2" ); breaks case “101 Seyonce( "sale" )5 breaks ? Filed by Herman at 10:20 am under AFL. The Basies ‘Comments Of on Using ILF0), IFO and SwitebQ)Funetions seve G votes, average: 3.33 out of 5) Mareh 7, 2011 Equalize X-Range for all windows, ‘This funetion was requested on the main list, and was solved withthe help of several expert programmers fom thelist. Thanks guys! ‘This function ean be copied to an include file that is included in each program from which you might want to synchronize the datetime range for all visible windows. The funetion places a small [R] button atte right top of Your chart. Clicking this button will set the datetime ranges of all windows ‘equal to the one you click the button in. Note that this window has to be active for the button to work, i, if the window was not active (selected) it will require two clicks forthe button to respond, ‘anction Rangeatlwinows() 4 I = GetcursorsPosittont 2 95 Hy = GetcursoryPositsont 43 leetcliek = cotcursorsouseavetons() 11 Pace Ranging Sutton phew amibrokororgusurkbcatogoyiat-progamming! ate 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing Xa = status( “oxchartright™ Jets Xi Tag's auttonsizes Yo IA 4 suttonsizes GheSelectront( "Tahoma", Buttonsize / 2.5, 600 ); GfuselectPen( colorsiack 4 1)3 GfeselectSoliddrush( colotvellow ); Gfenectangle( x1, Yi, KZ, ¥2 95 Gfasetrextcolor("cotorblack 95 Ghesetbitoget 1.9) Gfedrawext( "Ry Xby Yay X25 Y2, 41); AF ( onbutton aN Lertctick ) ‘ or = oaverine()s BE 2 Barindexd)s Firstaarindex > status( “Firstvisibiebarindex” ); Lastiarindex » status( “Iastvisiblebarindex” FiestOaterine = Lastvalue( Valueahen( Firstaarindex Lastoaterine = Lastvalue( Valuennen( Lastaarrncex = FiestOaterineser = DateTiretoser( FirstOateline }5 Lastbaterinestr = bateTinerostr( Lastoatetine AB » Createobject( "Broker toplication™ )i ty = docs. county Br, oT) ys er, OT) Ds for (4 = 9) 1 € Qty; S44) // Range all windows c doe = does.tten( 5.93 Ig = doe.Activenindows activates ‘A Zoontonange( FirstOateTineste, LastoateTineste 5 11 correct shift due to blank bars ieishell = Crestedasece( "wSeript. shell” )3 WsisnelL.appaetivate( "anibroker wsHnel1.Senckeys(- "(0600)" i > ? ? 1/000 Code anges nsrdows()5 Plattcy24228); [Filed by Herman at 7:17 am under AFL. - Utilities nd Functions ‘Comments Of on Equalize X-Range forall windows settee (2 votes, average: 4.50 out of 5) January 26,2011 Adding Help-Tips to your programs you write AmiBiroker programs that are used by others you have undoubtedly found that documenting your program and answering hundreds of ‘emails can be very ime consuming. You ean save yourself, and those who use your code, alot of time by adding Help popups (Tips) to your programs. No longer will users have to search though manuals andior write emails to find basic instructions. Of course you will save time as well singe you don’t have to answer all those emails) IF you don’s program for others, read on, because there are some other applications that may intrest you, When Tips are enabled they will display asa balloon when hovering the cursor over a defined abject or area, no clicks are required. Here is atypical Tp: phew amibrokororgusurkbcatogoyiat-progamming! ane 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing Tips can be used with gfe Control panels trading dashboards, charts (function like the interpretation screen and now defunct Too!Tip), tabular data, system status displays, gfx menus, caution and alert messages, ec. Your imagination sets the limits. Of course you can change the balloon size, colors, fonts, shape, etc to your requirements. The code forthe trading buttons shown is aot provided inthis post - that could be another topic. ‘Tips can display real-time market and system information. Inthe above example the Last price and a cautionary warning that Transmit is turned ON reflect real-time status, In this post Tips ae placed relative to the mouse’scutsor position. In chart applications you might want to use dynamically placed Tips tht point to a critical event or condition on your char. You would do this by converting price ané hars to pixels and replace the MX and MY variables inthe code with calculated values. For more on this see Hovs to convert {rom bar-value to pixel coordinates an the AmiBroker Knowledge Base, ‘When I write button functions [add Tip information asthe last argument to the function, this way the information is right where itis defined by the cade, This is also helpful when reading the cade. The actual Tip text can be repeated in your manual asa text box so that a clear association exists ‘The code inthis post demonstrates how the balloon reorients itself depending on ia which quadrant of the pane the cursor i locled, This is done to ep tips within the pane area, even when hovering over an object close to the edge ofthe pane. Here is a short video to see how this works. I, on your computer, the Tip tracks the mouse cursor slower than inthe video ths is because I have enabled the higher refresh rate of 0.1 second. "Tomasz explained this in post 151255 on the main Amiroker lst. Making errors while editing your Registry can cause serious computer problems, if {you haven't done this before, please sek professional help All code in this pot is solely intended to show you how to develop Tips. They serve no other purpose. To help you experiment I used Param() instead ‘of hard-coding Tip properties: Have fun! anction ShouTin( TipColor, TipOutlinetolor, Tiptextcolor } 4 {Blobel 1, My, Pxdth, Patlesgnt, THoWLcth, TépHedght, Tipson, Tépronthane, Taprontsize; Tipag = YarsecText( "Tspisg” 3 46 ( ripson AND Tite I= > ) ‘ Quadrant = ( mo alt; prwidth / 2) + (MY ats pxheignt / 2) * 25 BS Ses 1/‘Rounding Staneter phew amibrokororgusurkbcatogoyiat-progamming! st6 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing sch ( quadrant ) t Tiphidth; Tpleignt +0 * 0.753 Tipkiatns Tipleigne +0 * 0.753 Tipteagne - 0 + 0.755, Tipiaens Tiphetants 2" 0; ipusaens Tapfelgnt - 0 * 6.75; // Rectangle Tipiaens Tiphesents 35.11 Pointer Yea yee 0" 0.75; reaky default Medea nda yaya syne yh ays =; > xsetabtode( © )4 GfaxSelectPent Tip0sttineCotor }3 GhsetTextcolor( TipTexttoLer }} GheselectFont( TipFonenane, TipfontSize 95 Gfselectsolidarusn( Tiptolor }3 GGhetounaect( x1, yy X2y 92, By 0 Ji GeePalygon( 8, ¥3) Ky ¥6,'X5) V5 Ys If Pointer GerselectPen( T1scolet ); // Wide Line between RoundReet and Pointer ‘Shoovero( KS, ¥3 )s Ghabinero( sa, va Di Ghorowrertt Hipheg: xL + 18, y1 43, 02-20, y2 = 5, 16+ 65 95 } } fereton Testbjct( Label, 8, v1, 12, ¥2, Color) //Gosating Ueno freon only GfxselectPent colortlack 5 Ghselectsalidarusn( Color}; GGhetectangle( x1, yy x25 92.05 Overdnject 5.18 Age; 2c AND HKALE; 32 AND MY gts yt AND MY ARS y23 iF ( overobiect ) VarSetText( “Tipsy “The cursos 4s now over the * + Label + ""guacrant and te shape of the Tip #5 adjusted accorcingly.” 05 return overonjects phew amibrokororgusurkbcatogoyiat-progamming! are 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing > 11 Gtobat variables and paraneters can be hard-coded 19 the final application global me, nv, Paden, Patesgnt, Tiowiceh, rsphedght, Tipson, ronthane, FontSizes Tipcotor = Patancoior( “Tip Background Color, cotoruhite }; Tipoutlinecoles = Parancolor( "Tip Outline Color", colorsiack Tiptextcoter = Parancoior( “Tip Text Color™, colorslack )5 Tipson Paranroggle( "Tips On", “OFF [ON", 1-93 Tipfortsize = paran( “Font size", 9, 8, 24, 2.)3, Tipaigth s'Paran( “Tip width", 228, 58, 568, 10 ); Tpietghe = Paran( “Tip neignt®, 60, 58, 5e2, 10); Tipfontiiane = Paranstr( "Tip Font’ rane”, eléa Console”): cfxsersltode( 1); asetOveriaytode( @ ): fequest¥inedtesresn( @-2 ) m GetcursorsPosition( 1); tv 1 GetcursorvPositiont 13} Pruterh = Status( "peasath” )s Proetghe “status "pxheight™ ): {1 1n a real application each colores area could bes snall button ‘TostOnject( “Upperteft", 8, 8, prwigen / 2, prhesgnt / 2, colorked ); TestOvject{ “Uppernight®, pocdth 7 2, 8, puidth, pereight 2, coloralue J; TestObject{ “Lowertef«",'0, pxheight / 2, poridth’/'2, pxheight, colorvellow )5 Teseovject( “Loverrighe®, pawidtn 7 2, pubesght / 2, paaiath, ptheighe, //'Loeated in your derault Include Folder 11 exanpte to draw crossshair cursor Yortce = GetCursorvPosition(@); Xingex = SelectedValve(GetVisualBarincex( ))5 gAePLovi inet Getvetxels{ YPrice ), colorRee )s BePLotvL inet GewrPLxels( index }, colored ‘The include file listed below defines the following variables: 17 pswkdth, pxhelgh, Winy, Minx, YRange, VisBarindex, NunBarsvisible, pxPanekidth, pxSanehetght, PixelsPerdar, PixelsPerPrice ‘AmiBeoker Users’ Knowlodgo Base » AFL programing ‘You may want to copy the above comment line below the include statement in your code to refresh your memory. You should copy the Include file to your default AmiBroker Include folder. 17 GpxincLude-0e1. af copy to default include folder function gfsPlothtine( YPixels, Color ) lobad powtatn; Gfeselectren¢ Colon ) ; Sfotovero( @, Yeixels Js GhaLinere( prulath, YPixels ); ) function gfaPlotvLine( xPixels, Color ) 4 Blobel pxnetgnt; Gfaselectren( color ) 5 Ghoovero( x>Leels, 8 }s Ghetinerot xodnels, pxhesght } fonction GetVisvalBarindex( ) 4 vb = status( “Lastwisiblebar" ); ‘fo = status( “firstvisiblebar” 5 Bie earindext) ‘Staticvarset( "Mnberbarsvisible", Lvb - vo +1): return bi = Si 8] = Abs > Function Getvosxels( ¥ ) { lobal PixelsPerPrice, pxToptrea, ax; Feturn (banv - ¥) * PixeleParprice + pxToptrea; ? Fanctdon Getxosxels( x ) { Blobal PixelsPersar, prtertireas Feturn KX PixelsPerbar = pxLeftArea; Y phew amlbroker.orgusorkbcatogoylaf-programming! ae 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing SECTION, BEGINC“GFX INTTTALTZATION"); 7i these Paranaters will change depending on screen layout/fonts pxtigresrea = paran(. "Right Axas Area", 93, 8, 200, 1 )3 // Depends on font Sroatearea = Paran( "Date Axis Area", it, 8, 188, 1); 1/' Depends on font DBateaxison = Parantoggle( “Date Axis", "MUDE|SHOK", 1"); pxtertanes = 53 pxtopires = 93 patottontrea = 5p Te aateaxason plottondrea = pOatesrea + pxdottontress Setchartoptions( 2, chartshowoates }; : ase ‘setchartoptions( 3, chartshowoates ): puwteth = status( “pestath” bxhelght = Status( “prhedght” D5 11 clalculate charting area width and height hing = status( "axisminy” 3 Many = status( “axismany” 3 ange = ax ~ fins Visnurindex = “cetVisualaarindex( J; Nunarsvisible = statievarcet{ "Nunberbarsvisible" ); 1/ calculate Pane wath and hesgnt bxvarewieth = pewidth ~ prlertirea ~ pxkightarea; bxbaneletght = pevelght * pxTopArea ~ pxBottonérea; 11 calculate conversion factors PixelsPerbar = axPaneddth / NuaBarsvisible; PixelsPerrice = pxPanetesght / YRanges [SeCTION 00s Edited by Al Venose. [Filed by Herman at 1:07 po under GFX Programming ‘Comments Off on Using a GEX Include file nee votes, average: §:00 out of 5) ‘March 20,2008 ‘Creating GEX Chart-Overlays (v3) Important note: The Auiftinker 5.09.0 Beta introduced the ftlowing new GFX functions Status(“pxcharlet”) ~ retums x-coordinate of top-left comer of chat area Status(“pxchartop”) —retums y-coordinate of top-left comer of chart atea ‘Status(“pxchartright") — returns x-coordinate of bottom-right comer of chart area Status(“pxchartbottom") ~ returns y-coordinate of bottom-right corner of chart area ‘Status(“pxchartwidth”) ~ returns width chart area (rght-leM) ‘Status(“pxchartheight”)—retums width chart atea(bottom-top) Since this release appeared afer tis post was published these functions are not used inthe examples below, This post as been le unchanged for educational purposes. For examples using the new funetions please see the 5.09.0 Read Me file, Creating an exact chart overlay using GFX funetions can be a daunting task forthe non-professional programmer. The solutions presented here were derived through experimentation; if there is aetter way, please make a comment. Once the pixel layout is flly understood, GEX becomes an extremely powerful tool and may just give you an additional trading edge. The frst and most importent step in using GFX functions is to understand ‘bow pixels make up your display. In AmiBroker the width and height of your charting pane can be retrieved using the following two functions prwicth = Status(prwiath) Dpxheight = status("pxhelght"); Horizontal pixels count lft o right, | to pxwidth; vertical pixels count top to bottom, Ito pxheight, The area covered by these two numbers is shown, in Yellow below. Fora high esolution monitor this area may cover about 2000 (11) x 1000 (V) pixels. This pixel area includes the areas used by the X and Y axis, and the blank top and bottom margins, phew amibrokororgusurkbcatogoyiat-progamming! wie 016 ‘AmiBrokee Users’ Knowlodgo Base » AFL programming EN) ain (GE Ble Est en tome Feat Syntol Arai Tacs esos ty -ax 2 -pi@@i tld meh ee love oomA Soni ag Fetes TSE, Cowon ode, Franc, west GPOaE 4| [Next isthe standard charting area, which isthe area where your price chars ae located, This area excludes the surrounding blank margins and the areas used for axis labeling. ITyou want to keep your overlay within the standard chart boundaries, you have to place your images within the above ‘boundaries. This area is highlighted in Blue inthe image below. EN) ain (GE Ble Est en tome Feat Syntol Arai Tacs esos ty -ax # -pi@@i tale mele ve LovgoomA Soni ag TSE, Coonon ode, Fran Swe ‘The boundaries for this area can be determined by running the example code listed in Finding Pixel Boundaries, Bight parameters must be known to create pixel overlays: prwicth = status baleftirea = Paran( "Left Blank Margin", 5, 8, 100, 1); // constant Prkipnthrea = Paran( "Right Axis Area", 93, 8, 200, 1.33 // Depends on fort PxTopsrea = Parar( "Top Blank Margin",'s, 8, ie, i); // Constant prostetrea = Paran( "Date fads Area", "11, 8, 188, 1); 17 Depends on fo Prtottonarea = Paran( "Botton Blank hargin', 5, 8, 182, 1 5/7 constant Dateaxison = Parantoggle( "Date els", "HIDE Show", 1); Since adding date labels to your DateTime axis changes the size of your pixel plosting area, you need to compensate for this 4#( pateaxtson ‘ PuBottondrea = prOatesrea + pxlottontreas Setchartoptions(2,chartshoxo3tes);, { Setchartoptions(3,chartShowoates); ? The pixel plotting area's width and height can now be calculated pxPanewicth = pruidth prLeftarea pxRightareas ‘The dimension ofthe Blue ates shown earlier changes when you resize AmiBroker, open additional windows or panes, change the fons in your axis, ‘or tum On/OA date labels. When this happens you will have to recalibrate the boundaries. To convert prices to pixels, so that you can ereate an exact ‘overlay, you also need t0 define the wicth and height of your regular chart pane. These are expressed in DateTime and Price units, They will change ‘when you zoom your chart. When you have at leat one price plot displayed, so thatthe values for miny and maxy are define, you can calculate these ‘boundaries a follows: Niny = Statustaxisminy")s Naxy = Stotus("aelsnay")} hispihwww amibrckororguserkbcatogorylal-progamming! 8 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing ange = Max - hin Sarsvisibie = Status(*sarvisibie"); Nanbarsvistbie = Can(Sarsvisible)} ‘You now have all the information needed to calculate the PixelsPrice and Pixel/Bar conversion factors: PlxelsPersar = pxPanedidth / Nundarsvisible; PixelsPerPrice = pxPanenesght / YRanEe; Puting i all together in a demo program (listed at the end ofthis post) produces the price-chart overlay shown below. The regular price plot is plotted using dots, so that the overlay is clearly visible, When you plot both traces i lines, you will see minor deviations that are probably due to rounding to the nearest pixel. The pixel price plots shown in Red, The purpose ofthis exercise is to learn to work with pixels and be able to produce an exact ‘overlay on the price chart. The Param window below the charts shows typical parameters; they will ikely be different for your sereen layout. "GG Be Mr tet Feat Syninl Srayie Tee Wn Heb id Lae POOmA SOM AE [ve a>) Set «(See E) See € Ses? Ses 8) Tope eaan Cae Fate sss) Forty, ess RideAicaos Dalene 11 Let ini Msth 5 TepslekMagn Sutonstarknaan 5 {function gfaPlothline( YPixels, Color ) 4 lobal pacicsns Gfaselectrent color ) 5 Ghotvero( @, YPixels }; SheLinerot pawlsth, YPSxels 95 > function gfxPlotvLine( xPixels, Color ) 4 lobal pxneiants EfeseiectPent color ) 5 Ghotvero( sels, ¢ } fab ineroe xebeels, pxbeieht 5 > function Getvisualartndex( ) 4 Ivo » statust ‘ab = Status bi warindexd) |astvisiblebar" irstvisiblebor" 5 phew amibrokororgusurkbcatogoyiat-progamming! wate 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing staticvarset( ‘NumberbareVisible", Lvb - f¥b + 1); return bi = Bip @] ~ fb; Function GetyPixels( ¥ ) { lobal PixelsPerPrice, pxTophrea, Hexs Feturn (tanY - ¥) * Pixtlaperprice + paTaptrea; ? Function Getxosxels( x) { Blobel PixelsPerdar, peLertares; Feturn KX" PinelsPergar » pxLertArea} } Graphxspace = 5; Setchartoptions( @, chartiideQuetekarker )3 prsteth = Status( “poriath” 95 brheight = statas( "phesght™ )3 1] These Paraneters wilt change depending on screen layout/fonts pxtightarea = paran( "Right fais Area", 93, 8, 208, 1); // Depends on font pxoateares = Paran( "ate Axis Area", it, 8, 188, 1); 1/ Depends on font Bateaxison = Parantoggie( “Date axis, "MIDE SHO", 1); 11 These Paraneters appear constant and can probably be hardcoded pxvertares = Paran( “Left lank Margin", 5, 8, 108, 1.);_// Constant Dpxlopires = Paran( "op blank bargin", $, 8, 408, 1); // Constant Patottontrea = Paran( “Botton Blank Margin®, 5, 8, 180, 4 )p 1) Constant 1 ( boteaxison ) // Size of bottom bounéary depends on whether dates are shown prBottonarea = pxoatesrea + pxscttontres: Setchartoptions( 2, chartshowoates. 3; > ase. Ssetchartoptions( 3, chartshowoates ); UJ Test Plots to help Line up boundary Lines Co1or = colorvnite; ghxPlowL inet pxLertArea, color i GAPLotvL inet puviaeh = pxRightarea, color); BeePlotHLinet peTopAres, ‘color ); EFPTOtHL inet pereighe ~ prbottondrea, color J; 1/ calculate ane wisth and hesgnt bxanewidth = puvidth ~ prlertarea ~ pxRightarea; pxvanelletght = puvelght © prTopheea - pxSottontreas JJ ciateuiate charting area width and deight Plott cy", 1s, styleets bs Ning = Status(”*axdsminy® 3 Many = status( “axismaxy" 3 ange = sax ins Visnurindex = “cetVisualBarindex( J; Nunsarsvistble = staticvarcet{."Munberbarsvisible" ); Uf calculate conversion factors PixelsPersar = pxPaneatdth / NunBarsVisible; PixelsPerPrice = pxPaneiesght / YRanges 11 For verification: Overlay pixel on price plot Fm’ = status( “sirstvistblebar” )3 Lvs = Status( “lastvisibleber" ); GfasetectPent coloraed ); for (b= FVD +1) bce (VB AND b & Garcount; bee ) ‘ PrevbinelY = GetvPixets( clo-1] )i Paxely = etvedxels( cI] 03 Prevbixelx = cevpixeis( vissartncex{b-<} }5 PixelX = GetxPixels( Vistarindext] )5 cfetovero( Preveixelt, PrevPixelY ); Ghat inerot Pixetx, Patel 5 > Edited by Al Venose [Filed by Herman at 8:10 pm under GEX Programming ‘Comments Off on Creating GEX Chari-Overlays (v3) ‘event votes, average: §.00 out of 5) phew amibrokororgusurkbcatogoyiat-progamming! ai8 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing March 15, 2008 AFL Shapes Cheat Sheet ‘The ploishapes0 can be used to plot shapes on your chart to indiate signal, stops, and other events and conditions. Figure 1 below gives a quick ‘overview of the shapes that are available and includes a few undocumented ones. A PDF version suitable for printing is here: AEL Shapes Cheat Sheet ‘Shape Name Syntax for PlotShapes() ‘Shape(Holiow){SmallamefeshapePosition Above] examples: ShapeNone ShapeDigid + shapaPostionAbove + 2giNumbor seers shape | Hotiow | sma] name | shapePostionsbove | Default on ° ao + | KY oer v | mw @vl + | oem er v baw Al | em own Wve comin woe i or Tie pe me wane i aw vy | ew L wowme |e ea “Notes: The folowing constants need o be dete to use these undocumented shape ‘ates inthe char ‘ShapeSmelUpArrow «57; // Hollow not aval with sr rows ShapesmalDownArow = 38; Hollow net avalacie win small arews ‘ShapoLofPutior = 53, Shapehighuter = 8; Figure 1 Figure 2 shows the small AFL program that was used to explore all the buil-n shapes and their numerical values, for (4 = 0; 1 alt; sarcounts 4+) ‘ oft] = cls) = ts says aes: sats 46 (522000) (Plottext( numoser( $5 2.0, False J, 44 Lf4]-2, colorvarksrey ):} clse “(PlotText( NanTostr( 4, 1-8, False }, 4, Mil#-5, colorbaccrey d Protsnapes( C, colorted, 8, Cy -20 3 Plet('Cy “=, colerLightGrey, stylesar ); Title = “Wollon = "4 NunToStr( shapevotlowcircle ~ shapeCérele, @ @ ) 4 "\n ‘sali = "+ NunTostr( shapesmalicirele ~ shapacirele, 8, 8°); phew amibrokororgusurkbcatogoyiat-progamming! wie ‘AmiBeoker Users’ Knowlodgo Base » AFL programming wo oo Figure 2 ‘With additions by Herman [Filed by Dennis Brown at 5:01 pm under AFL - The Basi ‘Comments Of on AFL Shapes Cheat Sheet “soteml (5 votes, average: 4.80 out of 5) March 14, 2008 Finding Pixel Boundaries [Important note: The AmilBroker 5.09.0 Bots introduced the following new GFX functions: Status(‘pxcharlet”) ~ retums x-coordinateof top-left comer of chart area Status(“pxchartop”) — returns y-coordinate of top-left comer of chart atea ‘Status(“pxcharright")—retums x-coordinate of bottom-right comer of chart area Status(“pxchartbottom") ~ returns y-coordinate of bottom-right corner of chart area Status(“pxchartwith”) ~returns width chart area (right-leQ) Status(“pxchartheight”)—retums width ehart area (bottom-top) Since this release appeared ater tis post was published these functions are not used inthe examples below. This post bas been lef unchanged for ‘educational purposes, For examples using the new funetions please see the 5.09.0 Read Me file, ‘The first requirement when designing chart overlays andor control panels isto know the exact dimensions of your charting pane. These ae expressed in ixels. The numerical values where the margins (the four edges of your charting pane) are located depends onthe resolution of your monitor, the sie ofthe chart pane, and the fonts used to label your axis. Currently the only way to obtain the values is as far as I know, to determine the pane bounderies manually. The code below plots four lines that you «an position using sliders in the Param window. When te lines fall exactly onthe edges of your charting pane you can read the pixel value in the Param window and in the chart Title, See the image below and note how the bie lines hide the regular black chart frame phew amibrokororgusurkbcatogoyiat-progamming! wie 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing ‘Try changing the size of your charting pane, the overall Amiiroker window, andthe font for the axis, to see how the pixel values change. le aware ‘that opening multiple chart panes andlor windows wil also change pixel values. Also, probably to ensue thatthe first bar shows, the left edge of y charting pane is located at the third pixel, while actual bars start plotting athe fifth pixel. This means that trying to overlay the Blue line to determine the let boundary will be offset tothe left by two pixels, To use the code below copy it to a new Indicator formula window and click Apply function gfsPlotitine( YPixels, Color ) ‘ Eisselectren( eter ) 5 Stotoveot 85 Ytael® bz Sterinetot panty Wwhtels 95 , sanction gfePloWLine( XPxe1s, Color) ‘ slobal pxhel Edeseectrent olor ) 5 Storoverot toiselsy @ 35 Stetina xobceley pehight 3s ) raphispace = Setchartoptions( 2, chartiidequotekarker )5 prigth = status( "puatdth” Duhetght = Statos( “pxhesght 35 Sottontargin = Paran( "Botton Margin", 14, 8, 100 )5 aAPIoULSne( penelghe = Bottontargin, 6 33, AightMiorgin = Paran( "Right Margin”, 77, % 300-95 BAPLotL inet puwiath ~ RightMargin, 6) Lefutargin = Paran( “Left margin", 3, 8 100 95 gePLotLine( Lertrargin, 6°95 ‘optargin = Paran( “Top Margin’, 5, @ 100); ghePlotit inet Tophrgin, 6): er Pixel width: "wunToste(prcidth,1.0,False)s"\n"+ Pixel height: "sMunTostr(pxheight,.8,Faise}e" a" ‘Top nanging: "ssunoste(Tophargin,i.6,false)+”\n"+ night sorging: “swumTostr{aigneherging?8,Falseder\ne sovton nanging: "+nToStr(Gottertargin, .0,False)s\0"* eft marging: “wNemiaste(vertiargin,-0,F81s0)3 [Filed by Herman at 1:35 am under GEX Programming ‘Comments Off on Finding Pixel Boundaries ” a0 (4 votes, average: 4.80 out of 5) March 6, 2008 Weekly High or Low Days [Filed by brin_zat 11:36 prm under APL. ‘Comments Off on Weekly Tigh or Low Days he Basics semen (8 votes, average: 2.67 out of 5) Next Page » . oo + Info + Table OF Contents Abo Author Guide Contacis * FAQ © Toms of Use + Recent Posts © HOD Gap-Trading Portfolio system phew amibrokororgusurkbcatogoyiat-progamming! wie 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing © A Long-only EOD Gap trading idea Bollinger Band ZieZag Indicator A Subliminal Intraday Trading To «Using IED. IFO and Switeh0 function + Recent Comments © Richand Dale on Data Resources = Forex Herman on Request Real-Time Topies here © Mike B on Request Real-Time Topics here © Tomase Janeceko on UIS-Siocks Database (02 ¢ brian_z on Setup A Custom Datahase = Nasdag + Categories Categories AFL programming 7 + Archives © October 2011 (1) © September 2011 (1) © August 2011 (1) uly 2011 (1) © Apil20i1 2) March 2011 (6) Ecbouary 2011 @) January 201 2) Eebnuary 2009 (2) August 2008 (1) April 2008 (1) Mach 2008 (20) Ecbnuary 2008 (6) January 2008 (1) December 2007 (4) ‘November 2007 (18) tober 2007 (17) September 2007 (17) ‘August 2007 (26) 2007 20) Sane 2003 (17) May 2007 (8) ‘April 2007 (16) January 2007 (1) + Meta Copyright (€)2006 AmiBiroker. ‘This site uses WordPress Page generated in 0.510 seconds. phew amibrokororgusurkbcatogoyiat-progamming! ame 016 ‘AmiBeoker Users’ Knowlodgo Base » AFL programing phew amibrokororgusurkbcatogoyiat-progamming! wie

Potrebbero piacerti anche