A MultiCharts strategy can automatically submit orders to the broker when automate order execution is turned on. But there are unfortunately a couple of situations that disable automated trading. How do we create an alert whenever that happens?

In this article:

Generating MultiCharts alerts based on auto trading status

The Alert() keyword generates alerts programmatically (PowerLanguage Keyword Reference, 2016) as long as we’ve enabled the script’s alert setting. Then when that keyword executes, MultiCharts can generate a notification window, audio alert, and/or email alert (MultiCharts Wiki, 2013) depending on how alerts are configured.

We usually generate alerts based on price action (like a moving average crossover alert). But we can generate alerts based on anything that’s accessible in PowerLanguage, like creating an alert for data feed issues and triggering an alert when we haven’t enabled auto trading.

Another helpful way to use alerts is to generate a notification whenever a strategy’s automated trading goes from enabled to disabled. By being alerted of that, we can quickly intervene manually (whether by re-enabling automated trading or closing the position at the broker’s end). Let’s take a closer look at automated trading and generating alerts based on the auto trading status.

Enabling and monitoring automated trading in MultiCharts

With the ‘Automated Trade Execution’ feature a MultiCharts strategy can generate orders and submit these to the broker for execution (MultiCharts Wiki, 2015a). On a single chart, we enable (or disable) that feature with the ‘Auto Trading Status Switch’ (which is also called the ‘Automate Order Execution Switch’).

That setting’s button is in the top left of the chart, and either reads ‘SA’ (when using synchronous trading) or ‘AA’ (for asynchronous trading) (MultiCharts Wiki, 2014a). It looks like this when auto trading is off:

Automated trading on the MultiCharts chart disabled

And the button is green when automated trade execution is on:

MultiCharts automated trading on the chart enabled

When automated trade execution is enabled, the strategy processes all incoming price data and submits trades based on its order conditions. Unfortunately, there are several situations that automatically turn off auto trading (MultiCharts Wiki, 2016):

  • Changing the symbol or chart on which the strategy runs.
  • Turning one or more of the strategy’s signals on or off.
  • Changing (like adding or removing) the strategy’s signals.
  • Recompiling one of the strategy’s signals.
  • Changing strategy settings, auto trading settings, or one of the signal’s input options.
  • A connection loss between MultiCharts and the broker for an extended period of time.
Note: Besides these situations, other events that affect the MultiCharts program or computer (like a crash or power outage) also turn off automated trading.

Sadly, we cannot programmatically deal with several of these situations. But even if we could, there’s currently no way to turn on MultiCharts’ automated trade execution programmatically. And so a manual action is always needed to turn automated trading back on.

A helpful way to take those actions quickly is to generate an alert when automated trading gets disabled (while being turned on previously). With those alerts we reduce the risk of missing entries or keeping an open position unmanaged because a strategy is turned off.

To trigger an alert that notifies us of the automated trading status, we’ll first have to programmatically check whether automated trading is enabled or not. We do that by using he GetAppInfo() keyword with the aiStrategyAuto parameter. That makes that keyword return 1 when automated trading is enabled and 0 when it’s not (PowerLanguage Keyword Reference, 2016).

Note: We can also use GetAppInfo(aiStrategyAutoConf). The keyword with that parameter returns 1 when the signal has automated trade execution enabled and order confirmation turned off, while 0 is returned when one or both of these things aren’t the case (MultiCharts Wiki, 2015b).

Besides monitoring if auto trading stays enabled, we can create more meaningful alerts if we also track the strategy’s position. Then when the strategy gets disabled, we can generate an alert with information about the strategy’s position. That would immediately tell us how severe the situation is. To make that information even more meaningful, we can include the MultiCharts position as well as the broker’s open position.

To get the strategy’s position at MultiCharts’ end, we multiply the MarketPosition and CurrentContracts keywords. The first returns a numerical value that indicates the strategy’s current position (long, short, or flat), while the second returns the position size (PowerLanguage Keyword Reference, 2016). By combining them we know how many contracts, shares, lots, or units we’re long or short.

The open position at the broker is something we retrieve with MarketPosition_at_Broker_for_the_Strategy. That keyword returns a numerical value with the both the size and direction of the position that the strategy currently manages at the broker’s end (MultiCharts Wiki, 2012b).

Now let’s see how we can combine the above discussion in an example signal that monitors the status of automated order execution and generates alerts based on that.

Example: generate a MultiCharts alert when auto trading stops

In the signal below we generate an alert whenever automated trade execution gets turned off. It also periodically recalculates the script, independent of when or how often a new tick arrives. That way when the internet connection goes down or there are data feed issues, the signals remains updated.

The signal doesn’t perform other tasks. And so for order generation we’ll need to add other signals to the same chart or portfolio. This has the advantage that we can use the example signal with any other signal, instead of having to copy and paste the code into other signals.

The image below shows how the alerts generated by the script look like. After discussing the code we’ll take a closer look at the signal’s behaviour.

Example alert when MultiCharts automated trading gets disabled

[IntrabarOrderGeneration = true];

Inputs:
    Recalculate_After(10);
    
Variables:
    IntrabarPersist prevStatus(0),
    strategyStatus(0),
    strategyPos(""),
    IntrabarPersist prevBrokerPos("0");

if (CheckAlert) then begin

    strategyStatus = GetAppInfo(aiStrategyAuto);
    
    // Generate an alert when automated trading is switched off
    if (strategyStatus = 0) and (prevStatus = 1) then begin
    
        strategyPos = NumToStr(MarketPosition * CurrentContracts, 0);
    
        Alert("The strategy's automated order execution is turned OFF. " + 
            "Strategy position is " + strategyPos + 
            "; broker position is " + prevBrokerPos + ".");
    
    end;

    // Store the values for the next script calculation
    if (strategyStatus = 1) then
        prevBrokerPos = NumToStr(MarketPosition_at_Broker_for_The_Strategy, 0);

    prevStatus = strategyStatus;
    
    RecalcLastBarAfter(Recalculate_After);

end; 

We start with the IntrabarOrderGeneration attribute set to true. That makes the signal calculate with every real-time tick instead of only on bar close (MultiCharts Wiki, 2012a). Since that increases how often the signal calculates, the script can generate alerts much sooner.

Then we create an input option and several variables:


Inputs:
    Recalculate_After(10);
    
Variables:
    IntrabarPersist prevStatus(0),
    strategyStatus(0),
    strategyPos(""),
    IntrabarPersist prevBrokerPos("0");

We use the Recalculate_After input option later to specifying how often the script should recalculate. With its default value of 10, our script calculates at least once every 10 seconds.

Then come the variables. The first, prevStatus, will hold the status of automated trade execution when the script calculated the last time. With that stored in a variable, we can compare how the current status of auto trading differs from the previous script calculation. And with that we can see if automated trading went from enabled to disabled.

The strategyStatus variable will hold the strategy’s current auto trading status. And the strategyPos string variable will hold the strategy’s current position size for when we generate an alert.

With the prevBrokerPos variable we track what the strategy’s position at the broker was during the last time the script calculated. By tracking the previous instead of the current position, we can include the broker’s open position in the alert message just before automated trading got disabled. Because we cannot retrieve the broker position when auto trading is off, we’ll need to work with what the broker position was the last moment automated order execution was on.

Both the prevStatus and prevBrokerPos variables are marked with IntrabarPersist. When that keyword is placed before a variable, the variable remembers any value assigned to it during an intra-bar calculation as opposed to only remembering the on-bar-close value (PowerLanguage Keyword Reference, 2016). Since this makes it possible to access the variable’s value from when the script calculated last, we can make comparisons between the current and previous script calculation. Since we won’t use the value of the strategyStatus and strategyPos variables from one intra-bar script calculation to the next, we don’t mark them with IntrabarPersist.

After making the variables, we arrive at the signal’s code. All of the code is placed inside the following if statement:


if (CheckAlert) then begin

    // ...

end; 

Here we programmatically check if alerts are enabled with CheckAlert. That keyword returns true when the script’s ‘Enable Alerts’ checkbox is enabled and when the current bar is the last on the chart, while CheckAlert returns false when one or both of these things aren’t the case (PowerLanguage Keyword Reference, 2016).

Due to that if statement, a large part of the signal’s code only executes when we can actually fire an alert. When alerts are enabled, the code inside that if statement begins with generating one:


strategyStatus = GetAppInfo(aiStrategyAuto);

if (strategyStatus = 0) and (prevStatus = 1) then begin

    strategyPos = NumToStr(MarketPosition * CurrentContracts, 0);

    Alert("The strategy's automated order execution is turned OFF. " + 
        "Strategy position is " + strategyPos + 
        "; broker position is " + prevBrokerPos + ".");

end;

For easy access later on, we first set the strategyStatus variable to the value returned by GetAppInfo(aiStrategyAuto). When that keyword uses that parameter, it returns 1 when the signal uses automated trade execution and 0 when that feature isn’t enabled (PowerLanguage Keyword Reference, 2016).

Next there’s another if statement. This one evaluates two true/false expressions that we combine with the and logical keyword. That keyword returns true when both the value on its left and the value on its right are true too. When one or both values are false, and returns false too (PowerLanguage Keyword Reference, 2016). That means both expressions have to be true before the code inside this if statement runs.

The first expression checks whether the strategyStatus variable equals (=) 0, which it does when automated trade execution is off. The other true/false expression evaluates if prevStatus equals 1. As we’ll see later on when we update that variable, prevStatus holds 1 when auto trading was enabled the previous time the script calculated.

Combined, those two expressions check whether auto trading got turned off (compared to when the signal calculated last). When that happens, we first set the strategyPos variable to a textual string with the chart’s current position. We get that position by multiplying two keywords. The first, MarketPosition, returns -1 when the strategy is short, 1 when long, and 0 when flat (PowerLanguage Keyword Reference, 2016). We multiply the position’s direction with CurrentContracts, a keyword that returns the position size as an absolute value (PowerLanguage Keyword Reference, 2016).

That multiplication gives, depending on the strategy’s direction, a positive value (like ‘5’ for 5 long contracts), a negative value (like ‘-300’ for short 300 shares), or 0 when the strategy is flat. To make this value appear nicely in the alert message, we convert it to a string with NumToStr(). That keyword requires two parameters: the number to convert to text and the number of decimals it should get (PowerLanguage Keyword Reference, 2016). Here we perform that conversion with 0 decimals, and we store that nicely formatted position size in the strategyPos variable.

Next we generate an alert with Alert(). Inside that keyword’s parentheses we specify an alert message that consists out of static strings and the strategyPos and prevBrokerPos variables, combined together with the + operator. (That prevBrokerPos variable holds the strategy’s position at the broker and is updated later on in the script.) By including both the chart’s (strategyPos) and broker’s (prevBrokerPos) position size in the alert message, we can immediately see if there’s an open position when the alert fires.

Note: Based on how we coded the if statement, the alert fires only when the strategy gets turned off (from being enabled previously). See generating an alert when auto trading isn’t enabled for the situation in which automated trade execution was never enabled to begin with.

After the if statement for generating an alert, we update the variables for the next script calculation:


if (strategyStatus = 1) then
    prevBrokerPos = NumToStr(MarketPosition_at_Broker_for_The_Strategy, 0);

prevStatus = strategyStatus;

We set prevBrokerPos here to the strategy’s current position at the broker’s end with MarketPosition_at_Broker_for_The_Strategy. That keyword can return one of three kind of values: a positive value with the broker’s long position size, a negative value with how big the open short position is, and 0 when the strategy is flat at the broker or when automated trading is turned off (MultiCharts Wiki, 2012b).

To have the prevBrokerPos variable accurately reflect the strategy’s open position at the broker, we use an if statement to only update it when automated trading is enabled (strategyStatus = 1). That way we know that whichever value that variable holds, it’s directly retrieved from the broker – and not the 0 that MarketPosition_at_Broker_for_the_Strategy returns when automated trading is off.

We format the value of that keyword here to a 0-decimal string with NumToStr(), which makes it look better in the alert message. Then we store that text in the prevBrokerPos variable for use in the next script calculation.

Then we update the prevStatus variable to the value held by the strategyStatus variable. Because we do this at the end of the signal’s code, the next time the script calculates the prevStatus variable will hold the automated order execution status of when the script calculated last. Then by comparing that previous value with the current status of auto trading, we can see if automated trading has been turned off.

One thing left to do is keeping the signal up to date:


RecalcLastBarAfter(Recalculate_After);

We periodically recalculate our script with RecalcLastBarAfter(). That keyword has one parameter: the number of seconds how often the script should at least calculate (MultiCharts Wiki, 2014b). Here we configure that with the Recalculate_After input option set to 10 earlier. And so this line of code keeps our script calculating once every 10 seconds. This keeps the signal up to date when the instrument trades slow or when there’s an issue with the data feed or internet connection.

Alerts that fire whenever MultiCharts’ automated trading is off

Now let’s see how our above example signal behaves. First, when we add it to a chart we’ll enable the alert setting and then we configure the alert options as follows:

Configuring the alert settings of the MultiCharts trading strategy

While we use the ‘Every Tick’ option here, our signal doesn’t generate an alert with every tick. Since the alert condition requires that automated trading is off (from on previously), the alerts don’t happen repeatedly after each other.

With the Recalculate_After option we configure the maximum number of seconds between two script calculations:

Example of the signal's input option

Because our signal only generates alerts we’ll need to add other signals to the chart for generating trades. For instance, we can add the ‘RSI LE’ and ‘RSI SE’ signals to the chart and then enable automated order execution like this:

Example chart with the MultiCharts signals

Now when automated trading gets disabled, our example script generates an alert like:

Example alert that triggers when auto trading gets disabled

Let’s look at another situation. Here our strategy opened a short position of 1 contract:

Price chart with the strategy opening a short position in MultiCharts

Now when automated trading is turned off, our example signal generates this alert:

Example alert for when MultiCharts' automated trading gets turned off

Another way to use alerts with automated trading is triggering an alert when auto trading isn’t enabled. That way we prevent accidentally forgetting to enable automated trading one of the charts.

Summary

We generate MultiCharts alerts with Alert(), but this keyword only triggers alerts when we’ve turned the ‘Enable Alerts’ setting on. When a strategy is traded automatically, several situations can turn off automated trade execution. To trigger an alert that warns us of that, we need to monitor the automated trade execution status in the script. For that we use GetAppInfo(), a keyword that, with the aiStrategyAuto parameter, returns 1 when the signal has automated trade execution on and 0 in all other cases. With that value stored in a variable, we can compare if the auto trading status changed from one script calculation to the next. When it did, we generate a notification with Alert(). To make those alerts more useful, we can include the position in MultiCharts and the one currently held at the broker. For the first we multiple the MarketPosition and CurrentContracts keywords; the second one is returned by the MarketPosition_at_Broker_for_the_Strategy keyword when automated trading is enabled.

Learn more:


References

MultiCharts Wiki (2012a, August 31). IntraBarOrderGeneration. Retrieved on August 1, 2016, from http://www.multicharts.com/trading-software/index.php/IntraBarOrderGeneration

MultiCharts Wiki (2012b, February 13). MarketPosition at Broker for The Strategy. Retrieved on August 3, 2016, from http://www.multicharts.com/trading-software/index.php/MarketPosition_at_Broker_for_The_Strategy

MultiCharts Wiki (2013, May 10). Using Alerts. Retrieved on June 11, 2016, from https://www.multicharts.com/trading-software/index.php/Using_Alerts

MultiCharts Wiki (2014a, November 4). Getting Started with AutoTrading. Retrieved on July 29, 2016, from http://www.multicharts.com/trading-software/index.php/Getting_Started_with_AutoTrading

MultiCharts Wiki (2014b, September 3). RecalcLastBarAfter. Retrieved on August 2, 2016, from http://www.multicharts.com/trading-software/index.php/RecalcLastBarAfter

MultiCharts Wiki (2015a, October 13). Understanding Automated Trade Execution. Retrieved on July 29, 2016, from http://www.multicharts.com/trading-software/index.php/Understanding_Automated_Trade_Execution

MultiCharts Wiki (2015b, January 30). GetAppInfo. Retrieved on July 29, 2016, from http://www.multicharts.com/trading-software/index.php/GetAppInfo

MultiCharts Wiki (2016, June 14). Auto Trading. Retrieved on July 29, 2016, from http://www.multicharts.com/trading-software/index.php/Auto_Trading

PowerLanguage Keyword Reference (2016). Retrieved on May 25, 2016, from http://www.multicharts.com/trading-software/images/c/c6/PowerLanguage_Keyword_Reference.pdf