Sierra Chart | Persistent Variables

Sierra Chart | Persistent Variables with Sierra Chart

It is common when programming indicators to have to retain a value between subsequent calls to your study function. These are cases where you need to store some value that has just been calculated for some future use. Some examples of this include:

  • Retain the index on which a cross over occurred
  • Retain the id of an order that was submitted so that order might be modified in the future
  • In the case of a system that pyramids, store the number of entries that have been executed since first initiating a position
  • You are accumulating a sum of volume over a certain range of bars and need to continuously add to the previous sum
  • You calculate an average of historical values and you compute it per bar. Moving averages work this way. You recalculate the value of some bar based on the values or X number of previous bars (I.e., you need to remember the values of all previous bars).

As stated above, the general need to remember “previous” values is quite common and quite varied.

Now, there are basically two ways to go about this. One method uses subgraphs and the second uses the Sierra Chart persistant varaibles. Which one to use depends on the type of data you need to store.

The first method is good if your data is time series or you have an array of data. The example with the average above. In this case you store your data in a subgraph.

The second method involves using persistant varaibles. This is mostly good when the data shared is one dimensional – i.e., you need to share a single number, string, date, etc.

For an example, see this video. The complete code from the video is pasted below for convenience.


// simple example of using persistent vars

SCSFExport scsf_Persist_Vars_TemplateFunction(SCStudyGraphRef sc)
        // set a reference to the subgraph
	SCSubgraphRef cummumativeVol = sc.Subgraph[0];

	if (sc.SetDefaults)
	    // Set the configuration and defaults

	    sc.GraphName = "Demo Study Persist Vars";
	    sc.StudyDescription = "This is a demo study";		
	    sc.AutoLoop = 1;
	    cummumativeVol.Name = "Cummulative Volume";

	    sc.FreeDLL = 0;


	// set a reference to the persistent var
	int& cumVol = sc.PersistVars->i1;

        // initialize the persistent value
        // the following code will run once and only once
        // whenever the chart is drawn
	if (sc.Index == 0) {
            cumVol = 0;

        // update the value of the persistent variable
        // we add the current volume to the previous accumulated volume
        cumVol = cumVol + sc.BaseDataIn[SC_VOLUME][sc.Index];

	// set the cummulative volume subgraph
        // to the current sum
        cummumativeVol[sc.Index] = cumVol;