Create switch Button

Hello everyone,

I'm trying to learn about GUI* and practice following the examples in the following document
http://www.amibroker.com/guide/h_gui.html

In this example I want to make a simple switch to plot MA20 and MA50. This is just an example for me to learn how to combine Switch and GUIbutton. However, when clicked, the MA lines appear and then disappear. Can someone explain it to me and figure out how to fix it?

idMyFirstButton = 1;
idMySecondButton = 2;
Plot(C,"",colorDefault,styleCandle);
function CreateGUI()
{
     GuiButton( "MA20", idMyFirstButton, 10, 60, 100, 30, notifyClicked );
     GuiButton( "MA50", idMySecondButton, 110, 60, 100, 30, notifyClicked );
}

function HandleEvents()
{
    for ( n = 0; id = GuiGetEvent( n, 0 ); n++ ) // get the id of the event
    {
         code = GuiGetEvent( n, 1 );

         switch ( id )
         {
             case idMyFirstButton:
			Plot(MA(C,20),"",colorBlue);
                break;

             case idMySecondButton:
             // do something else
             Plot(MA(C,50),"",colorRed);
                break;

             default:
                 break;
         }
     }
}

CreateGUI();

HandleEvents();

GUI is generally not required for such purposes, same thing can be achieved with very few lines -

Using ParamToggle:

_SECTION_BEGIN( "Multiple MA" );
	chMA = ParamToggle( "Choose MA period", "20|50", 0 );
	switch( chMA ) {
		case 0:
			perMA = 20;
			break;
		case 1:
			perMA = 50;
			break;
	}
	Plot( C, "Price", colorDefault, styleCandle );
	Plot( MA( C, perMA ), "MA(" + perMA + ")", ParamColor( "Choose MA color", colorCycle ) );
_SECTION_END();

More crispier using ParamList:

_SECTION_BEGIN( "Multiple MA" );
	perMA = StrToNum( ParamList( "Choose MA period", "20|50|100", 0 ) );
	Plot( C, "Price", colorDefault, styleCandle );
	Plot( MA( C, perMA ), "MA(" + perMA + ")", ParamColor( "Choose MA color", colorCycle ) );
_SECTION_END();

Thanks for your comment. However, I am looking to use Guibutton as an alternative to ParamToggle.

@Milosz: I tried searching other articles and found you have a lot of experience in this. Can you help me out a little bit.

Gui functions are NOT designed as alternative to Params(). They serve different purposes.
Your code does not work because you do not store the STATE. The formula
using Gui functions has to keep the state itself.

Params do all the work of maintaining state for you and you should stick with that.

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.