# Swing High / Swing Low AFL Code

Hi All,

Need help to develop AFL indicator code for Amibroker.

1st Indicator Logic… [Swing High / Swing Low]
On daily chart i need Green Down Arrow indication for swing high and Red Up Arrow indication for swing low.
Swing High = Previous High < High > Next High [Green Down Arrow Indication on High Candle]
Swing Low = Previous Low > Low < Next Low [Red UP Arrow Indication on Low Candle]

2nd Indicator Logic… [Risk Ratio Quantity]
Risk Ratio will be calculated on the Swing High and Swing Low, If BUY trade is executed then the Swing Low will be the SL [Stoploss] for the trade, divided by Risk Value. suppose my risk value is 1000 (this Risk should be in input Parameters), if the Buy trade is executed @ Rate 100 and my Swing Low is @ 90, then the 100-90 = 10 Points Risk, then 1000 (Risk Value) / 10 point (Risk ratio) = 100 is the Risk Ratio Quantity, It should give pop-up for the Risk Ratio Quantity. as "Quantity Risk Ratio - Buy 100 " and vice versa scenario for SHORT SELL Trade.

Thanks & Regards,

Vaibhav

1 Like

Hi … and well come to the forum.
Can you please tell us little bit of your coding background first?
I prefer to visit this link first to say hello to everybody, instead to say (In your very first thread) hello @Milosz and no hello to me.

Thank you, listen my thinking

on the other hand, Your coding background is important as Milosz or me has to know if you need the full code or just a kick start.

I have no background of coding AFL, i am doing this step manually in Other online trading platform. Here is the screenshot attached for your reference. Here the above green signs indicate the Swing High and below red sign indicate the Swing Lows in Daily Chart, then i draw a Horizontal line in two close Swing High for breakout buy trade...., i need 1st AFL Code for this swing high and swing lows, and another for Risk Quantity. Please help me with the code.......

2 Likes

Hi,
Please help with this code, the graphical presentation is attached for reference for logic Swing high Swing low

1 Like

@VAIBHAV007, the best way to learn AFL is to do it…

The best way to get help on the forum is to show us that your are DOING it…

Show us what you have tried, and what isn’t working the way you expect.

Also, check out the SEARCH (magnifying glass in top right by your avatar).

Don’t forget the Code Tags when showing us your AFL.

2 Likes

hello @VAIBHAV007

Visit the link, this one is important How to use this site

Now as snoopy said SEARCH… and this is, what i did

i just SEARCH for you very quicly and i found alot afl that will do what you need

i dond know what my old friend is doing? where are you @reinsley
Pivots, Prices And Swing Volume

this is the best place to have a GOOD look
here… . http://www.amibroker.com/kb/
and here http://www.amibroker.com/members/library/list.php

dond forget this one is important How to use this site

have a nice day.
have a nice reading and come back here if you need any extras

2 Likes

Dear PanoS;
Good Morning
and thanks for directing to afl "Automatic support and resistance lines9 …"

With this AFL, The swing high and low are plotted on the chart.

To get buy & sell signals as & when latest price breaks-out this level I tried to add
Sell = Close < lv;
Error 29:Variable "hv" used without having been initialized.
Error 29:Variable "lv" used without having been initialized.

So, I will be thankful if you please advice me how to generate signals /alarms as & when latest price breaks-out this level in Intraday chart.
Thanks...
Rao.

@rao
Your code doesn’t know the meaning of “hv & lv”…. that’s why throwing error.

Dear Fossil;
Hi.
Thanks.

Hello @rao
That is true as @Fossil said, it is easy to find where is this error, in your AFL code.
But always if you find any difficulty’s this forum is open to help you, drop your code here and we will see what extras you need.
Thank you

Dear Panos;
good evening.

Please find herewith the AFL code;

// define reusable function
function SupResLevels( bars, colorUp, ColorDn )
{
bi = BarIndex();
lvbi = LastValue( bi );

// return HHV value only for bars starting from the bar where HHV level was established
hv = IIf( bi >= lvbi - LastValue( HHVBars( High, bars ) ), LastValue( HHV( High, bars ) ), Null );

// the same approach for LLV
lv = IIf( bi >= lvbi - LastValue( LLVBars( Low, bars ) ), LastValue( LLV( Low, bars ) ), Null );

// plot levels
Plot( hv, "hv", colorUp, styleDashed );
Plot( lv, "lv", ColorDn, styleDashed );

}

// price plot
Plot( Close, "Close", colorDefault, styleBar );

// call function with various parameters
SupResLevels( 10, colorGreen, colorRed );
SupResLevels( 50, colorGreen, colorRed );

Sell = Close < lv;

This code is giving error 29 as mentioned earlier.

Thanks.

Hello
For your Question. The Hv and Lv are INSIDE the Function and you have to call your BUY with a different way.

I am going to give you another code to play little bit with it. I wrote the Buy condition with the Cross(). Also as I saw you are interest for scanner and I wrote few lines for exploration to start with.

Just remember this SUPPORT AND RESISTANCE version uses moving Avarage instead of pivots. There are many different S&R versions on the Net that you can find. I choose this one as I believe will keep you busy.

``````// You can also use other condition for buy/sell like a macd() for example
// System use MACD for Buy, Sell signals
Sell = Cross(Signal(), MACD());

``````

So here is the exercise code. @rao I hope you will enjoy

``````_SECTION_BEGIN("SUPPORT AND RESISTANCE (using moving Avarage)");

LB= Param("Back Periods HH,LL",10,0.25,30,0.25);
R=ValueWhen(Cross(MA(C,LB),C),HHV(H,LB),1);
S=ValueWhen(Cross(C,MA(C,LB)),LLV(L,LB),1);
SupResInclude = ParamToggle("SUPPORT AND RESISTANCE","HIDE|SHOW",1);

if( SupResInclude )
{
Plot( R, "Resistant", colorGreen, 24 );
Plot( s, "Support", colorRed, 24 );
}

// it is better to use Cross(Close ,R) Than Buy = Close > R
Sell = Cross(S ,Close);

// Plot arrows on the chart
shape = Buy * shapeUpArrow + Sell * shapeDownArrow;
PlotShapes( shape, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, Low, High ) );
// price plot
Plot( C, "Close", colorDefault, stylebar );

if( ParamToggle("Plot Mov Average ?", "No|Yes" ) ) Plot( MA(C,LB), "Mov", colorred, styleline );

//-- Code For Exploration
if( Status( "Action" ) == actionExplore )
{
Filter= Buy OR sell;  // short or Cover (you need to add in the filter later on)
SetOption( "NoDefaultColumns", True );
AddtextColumn( Name(), "Symbol", 1, colorDefault, ColGreen, 70 );
AddColumn( DateTime(), "Date / Time", formatDateTime , colorDefault, colorDefault, 150 );
AddColumn( SELL, "SELL", 1, colorDefault, colorDefault, 35 );
}

_SECTION_END();
``````

3 Likes

@rao

more in general, I suggest you review this part of the AmiBroker guide User-definable functions, procedures. Local/global scope.

It is crucial to correctly understand the "scope" of variables and how this relates to their use in user-defined functions.

Due to the fact that AFL does not require to declare variables the decision, whenever given variable is treated as local or global, is taken depends on where it is FIRST USED.
If given identifier appears first INSIDE function definition - then it is treated as a LOCAL variable.
If given identifier appears first OUTSIDE function definition - then it is treated as a GLOBAL variable.
This default behavior can be however overridden using global and local keywords (introduced in 4.36) - see example 2.

A very powerful and useful feature recently introduced in AmiBroker 6.25 Beta allows also to use functions passing variables by reference but this is a more advanced topic that you should study only when you are entirely comfortable with the above concepts.

2 Likes

@rao

``````function SupResLevels( bars, colorUp, ColorDn )
{
...........
...........
VarSet ("Highvalue",hv);
VarSet ("Lowvalue",lv);
return;
}
...........
...........
VarGet("Highvalue");
VarGet("Lowvalue");
``````

Moderator comment: this is wrong because VarSet should only be used for DYNAMIC variables, i.e. variables with dynamically constructed identifiers. For all other uses you should use normal variables and DECLARE them to have them global.

If you want hv and lv to be visible OUTSIDE the function where they first appeared, you need to DECLARE them as global.

``````function SupResLevels( bars, colorUp, ColorDn )
{
global hv, lv; // DECLARATION REQUIRED
....
}
// hv and lv would be visible outside the function because they are declared global
``````
4 Likes

Dear PanoS,

I tried your posted exercise code . The plotting is ok BUT after scanning / exploration nothing came out. The result is showing zero.

Thanks.

If you prefer to avoid globals and want to "simulate" multiple return values from a function it is possible to use the technique explained in this KB article:

A function with multiple return values

As said before, a recent beta AmiBroker introduced the "true" feature to pass parameters by reference.

Re this new feature I have a question for @Tomasz.

For testing purposes, I modified the Automatic support and resistance lines passing to the SupResLevels( ) function the 2 last params by reference (..., byRef1, byRef2)

Here is my modified code sample that works properly:

``````// requirements
Version( 6.27 );

function SupResLevels( bars, colorUp, ColorDn, byRef1, byRef2 )
{
bi = BarIndex();
lvbi = LastValue( bi );

// return HHV value only for bars starting from the bar where HHV level was established
hv = IIf( bi >= lvbi - LastValue( HHVBars( High, bars ) ), LastValue( HHV( High, bars ) ), Null );

// the same approach for LLV
lv = IIf( bi >= lvbi - LastValue( LLVBars( Low, bars ) ), LastValue( LLV( Low, bars ) ), Null );

// plot levels
Plot( hv, "hv", colorUp, styleDashed | styleThick);
Plot( lv, "lv", ColorDn, styleDashed | styleThick );

// Assing calculated local arrays to param passed by ref
byRef1 = hv;
byRef2 = lv;
}

// price plot
Plot( Close, "By Ref: USING Local Vars - Close", colorDefault, styleBar );

// call function with various parameters
SupResLevels(  20, colorBrightGreen, colorRed, &hv1, &lv1 );
SupResLevels( 100, colorBrightGreen, colorRed, &hv2, &lv2 );

// Exploration
Filter = 1;
SetSortColumns(1); // sort by ticker
``````

But, if I modify the code in the following way - NOT using local variables inside the function but doing the calculations directly to the passed by ref parameters - the main procedure arrays are filled with correct values (as it is possible to verify step by step with the debugger or using the exploration), but there is NO PLOTTING of the res/sup lines inside the function (and no warning or error messages).

``````// requirements
Version( 6.27 );

function SupResLevels( bars, colorUp, ColorDn, byRef1, byRef2 )
{
bi = BarIndex();
lvbi = LastValue( bi );

// return HHV value only for bars starting from the bar where HHV level was established
byRef1 = IIf( bi >= lvbi - LastValue( HHVBars( High, bars ) ), LastValue( HHV( High, bars ) ), Null );

// the same approach for LLV
byRef2 = IIf( bi >= lvbi - LastValue( LLVBars( Low, bars ) ), LastValue( LLV( Low, bars ) ), Null );

// plot levels
Plot( byRef1, "hv", colorUp, styleDashed | styleThick); // NO PLOT!
Plot( byRef2, "lv", ColorDn, styleDashed | styleThick); // NO PLOT!
}

// price plot
Plot( Close, "By Ref: NO Local Vars - Close", colorDefault, styleBar );

// call function with various parameters
SupResLevels(  20, colorBrightGreen, colorRed, &hv1, &lv1 );
SupResLevels( 100, colorBrightGreen, colorRed, &hv2, &lv2 );

// Exploration
Filter = 1;
SetSortColumns(1); // sort by ticker
``````

Here is what I see on my screen:

If possible, I would like to understand what is the reason for this different behavior.

(Test was done using AmiBroker 6.27.1 Beta - 64 Bits)

2 Likes

Dear @rao
I have to remind you that «exercise code» contain parameters.
You can right click over chart pane and select "Parameters" or press Ctrl+R allows to change chart parameters.
Now depend of the time frame you are looking your chart, most of the time YOU HAVE to adjust the parameters according to your needs – strategy.
Exactly the same parameters you have to declare TYPE when you are try to run scan or exploration. Otherwise you are going to have deferent results.

I bet that was your problem.
i try to avoid that and this is the reason that i include parameter window in my photo.

P.S aslo just remeber that i left alot of room for you to edit this code. as the SELL contition is not corect.... you must write your sell strategy...

EDIT:
Do not forget also the Backtester window settings, special where is the Periodicity tab