Estimated reading time: 7 min

PrescienTrader includes multi-timeframe functions that integrate with AmiBroker’s powerful analysis and backtesting functionality. It also includes AFL scripts that demonstrate how to use the analysis functions. The analysis functions require a PrescientAPI Professional subscription.

The following video demonstrates how to setup and run an exploration. Please watch the video, then return to this article to continue with the tutorial.

Thumbnail

Exploration

When you run an exploration using the included PrescienTrader Backtesting script, AmiBroker scans through your specified list of instruments and your specified date range. It generates a row for each combination of an instrument and a date. In the example above, we’re just analyzing a single instrument (CHF/JPY) for the date range of October 1st through December 31st, 2018.

The scripts output the following exploration columns:

  • Ticker Symbol
  • Date/Time
  • Open, High, Low, Close, Volume, Open Interest
  • Saved – This column is highlighted in yellow for any row using saved parameter settings. When you save the parameters in PrescienTrader, the parameters are saved only for the selected instrument and time frame. This allows you to use custom parameter settings for each instrument and each time frame. When you run an exploration, PrescienTrader will automatically apply any custom parameter settings. The yellow highlight in the Saved column is to remind you that the row is using saved settings, not the settings you entered in the Parameters window.
  • PL Slope – This indicates the slope of the Prescient Line trend. Positive slopes predict an uptrend while negative slopes predict a downtrend.
  • FLD Score – The sum of the FLDs for all valid cycles multiplied by either the Strength or Amplitude of each cycle, depending on your PL Basis setting. Positive values indicate the market is in a cyclical uptrend. Negative values indicate the market is in a cyclical downtrend.
  • Trend Bar – The relative bar number within the current predicted trend. The first bar in a trend is bar zero.
  • Trend Bars – The total number of bars in the current predicted trend.
  • Trend Pct – The completion percentage for the current predicted trend. For example, if Trend Bar = 5 and Trend Bars = 10, Trend Pct would be 50%. Note that Trend Pct will never reach 100%, because that would mean a new trend has started. At the point of overlap between the old trend and the new trend, Trend Pct will be 0%. In addition to the numeric display, this column also displays a bar graph that shifts from green to red as the trend progresses.
  • Action – This is the signal, Buy/Sell/Short/Cover, for the current row. The signals generated from the included scripts are simply based on Trend Slope. When Trend Slope is positive, it will display a Buy signal and when Trend Slope is negative, it will display a Short signal. This is intended as a very simple example of how you could start to build a trading system using the PrescienTrader indicators. Do NOT use these example signals for live trading, as you will most likely lose money! The idea is to develop your own trading systems using our indicators and possibly other indicators, then backtest the system extensively. Once you have a valid backtested system, you can plug that system into the Action column to display your trading signals.

Backtesting

To run a backtest or an optimization, start by loading the PrescienTrader Backtesting AFL script. We suggest you make a copy of the script, rather than modifying the original script. Our analysis functions generate output for exploration columns and also create AFL arrays and matrices containing the results. When running a backtest or optimization, you’ll use the generated AFL arrays and matrices, which include the following:

  • ptStaticPL
  • ptStaticPLSlope
  • ptStaticFLDScore
  • ptStaticTrendBar
  • ptStaticTrendBars
  • ptStaticTrendPct
  • ptStaticFrequencies (Matrix)
  • ptStaticSlopes (Matrix)
  • ptStaticFLDPrices (Matrix)

If you’re running an analysis for multiple timeframes, the functions will create a separate set of arrays and matrices for each timeframe. The names will be the same as above, except each name will have an HTPx suffix, where x represents the higher time period index. For example, the arrays and matrices for the first higher time period will be named, ptStaticPLHTP1, ptStaticPLSlopeHTP1, etc… The arrays and matrices for the second higher time period will be named ptStaticPLHTP2, ptStaticPLSlopeHTP2, etc…

The AmiBroker backtester is extremely powerful. It supports true portfolio backtesting, walk-forward testing, Monte Carlo simulations, multiple timeframe testing, pyramiding and scaling, multiple currencies and more. All this functionality and power is available to you for backtesting and the output from PrescienTrader. It’s beyond the scope of this article to discuss the details of backtesting in AmiBroker. For that, it’s best to read the AmiBroker documentation.

Parameters and Parameter Variables

When running an analysis, PrescienTrader will use the parameter values you specify in the Parameters window. However, if you previously saved instrument settings for the current market and timeframe, the saved settings will override the settings displayed in the Parameters window. This allows you to perform a portfolio analysis using different parameter values for each instrument in the portfolio. When you view the Parameters window, it will display the last settings you entered, which may not necessarily be the saved settings. Click the Reset All button to display the saved instrument settings.

Additionally, you can save default settings. Unlike saved instrument settings, saved default settings do NOT override displayed settings. This allows you to take advantage of the fact that AmiBroker automatically remembers the last settings you entered, so if you’re testing a certain set of settings multiple times, you don’t have to re-enter them each time. However, you can always return to the saved default settings by clicking the Reset All button. Keep in mind that saved instrument settings take precedence over saved default settings, so if you click Reset All and it doesn’t display your default settings, that means you have saved instrument settings for the currently displayed instrument and timeframe.

Finally, you can override most of the parameters by setting an AFL variable corresponding to each parameter. The available variables include:

  • ptPolarity (0 = Positive, 1 = Negative)
  • ptPLBasis (0 = Amplitude, 1 = Strength)
  • ptLookbackRange
  • ptMinFrequency
  • ptMaxFrequency
  • ptHarmonicFilter
  • ptMinConfidence
  • ptBestXCycles

Each variable also has higher time period variations for multi-timeframe analysis. To set a higher time period variable, append HTP1, HTP2, HTP3, etc… to the variable name. For example:

  • ptMinFrequencyHTP1
  • ptMaxFrequencyHTP2
  • ptLookbackRangeHTP3
  • ptHarmonicFilterHTP2
  • ptMinConfidenceHTP1
  • ptPLBasisHTP4

Variables always override both Parameter window settings and any saved settings. If you set a parameter variable in AFL, the corresponding parameter will disappear from the Parameters window. You must set all your parameter variables PRIOR to calling the PrescientAnalysis or PrescientAnalysisPrepare functions.

Single-Thread vs Multi-Threaded Analysis

PrescienTrader supports both single-thread and multi-threaded analysis. The single-thread function only requires a single line of code, so it’s good for running quick explorations or simple backtests. The downside is that the analysis runs in a single thread, so it can only analyze one row at a time. However, if your analysis just consists of a few hundred rows, the time difference would be negligible. In this scenario, it would take you longer to write the additional code for a multi-threaded analysis than the time saved by running it.

PrescienTrader Backtester Script – Single-thread Section

The example analysis script is called PrescienTrader Backtester. If you view this script, you’ll see it contains a single-thread section and a multi-threaded section, which you can toggle between using a parameter setting. The singe-thread analysis section contains a single line of code:

PTBacktest();

The PTBacktest function takes no parameters because you configure all the parameters in the Parameters window. When it runs, it creates an API request, submits the request to PrescientAPI, parses the response, outputs the results to the exploration columns and generates the AFL arrays described above.

To perform a multi-timeframe analysis, simply call the PrescientAnalysis function multiple times. For example, if you want to analyze the base time period and two higher time periods, you’d use the following code:

PTBacktest();
PTBacktest();
PTBacktest();

Each instance of the function creates another timeframe in the Parameters window, so in the above example, your Parameters window would contain settings for the base time period, HTP1 and HTP2. Don’t confuse multi-threading with multi-timeframe; these are two completely different concepts. Multi-threading refers to running more than one analysis at a time, like analyzing a portfolio of instruments. Multi-timeframe refers to analyzing each instrument in more than one timeframe. For example, you could analyze the S&P 500 daily, weekly and monthly timeframes. In that example, you would also benefit from running in multi-threaded mode, since it would analyze all three timeframes simultaneously. However, you could run a multi-timeframe analysis in single-threaded mode, in which case it would analyze the timeframes sequentially.

PrescienTrader Analysis Script – Multi-threaded Section

The multi-threaded section is more complicated than the single-thread script and requires several lines of code:

postVars = PTBacktestPrepare();
if (StrLen(postVars) > 0) {
    ih = InternetPostRequest("https://api.prescientrading.com", postVars);
    if (ih) {
        response = "";
        while ((line = InternetReadString(ih)) != "" )
            response += line;
        PTBacktestExecute(response);
        InternetClose(ih);
    }
    else {
        msg = "No response from API - Possible timeout or Internet connectivity issue - Waiting 60 seconds";
        _TRACE(msg);
        PTLogToFile(msg);
        PTWait(60);
    }
}

The reason for the additional code is that AmiBroker doesn’t support multi-threading in plugins like PrescienTrader. So instead of performing the entire analysis operation in a single plugin function, the plugin handles everything except the API request, which is the most time-consuming part and therefore yields the greatest benefit from running in multiple threads.

Let’s break this down step-by-step…

  1. In the first step, we’re calling PTBacktestPrepare and assigning the result to the postVars variable. This function uses the parameters defined in the Parameters window to generate the data in the proper format for an API request.
  2. In the second step, we make the API request using the InternetPostRequest and InternetReadString functions. Since it’s interacting with a remote server, this is the slowest part of the process and thus benefits the most from running in multiple threads.
  3. In the final step, we run PTBacktestExecute on the data returned from the API. This function parses the data, outputs the results to the exploration columns and generates the AFL arrays described above.

As you can see, it’s not that complicated, but it requires a lot more code than the single-thread approach. If you’re analyzing a large amount of data, the multi-threaded approach can be up to 32 times faster, depending on the number of CPU cores your computer has.

As with the single-thread approach, you can analyze multiple time frames by inserting the above code block multiple times, or by wrapping the code block in a for loop.

Optimization

Optimization is the process of fine-tuning parameters to achieve the best results for a market or group of markets. AmiBroker allows for optimizing up to 64 parameters simultaneously, supports portfolio optimization and includes three smart optimization engines, Standard Particle Swarm Optimization, Tribes and CMA-ES.

PrescienTrader supports optimization of all its parameters without having to write code for each parameter. To set the optimization parameters, hold down the Shift key and click on the Parameters toolbar icon. This will display the optimization parameters window, where you can enter a range (From and To) for each parameter and a step for numerical parameters. The range represents the optimization range. For example, to optimize the Lookback Range, you could select something like:

LookBack Range From: 5
Lookback Range To: 10
Lookback Range Step: 1

Entering these parameters would optimize the Lookback Range between 5 and 10 with an increment of 1, so it would test values of 5, 6, 7, 8, 9, 10.

Logging

When running an analysis, PrescienTrader continuously outputs information to the Trace window. Each line contains the following information:

  • Analysis type (backtest, optimization, exploration, etc…)
  • Symbol of instrument being analyzed
  • Time Period (daily, weekly, monthly, etc…)
  • Data Series (Close, Average, etc…)
  • Parameter values:
    • Polarity
    • PL Basis
    • Min Frequency
    • Max Frequency
    • Lookback Range
    • Harmonic Filter
    • Min Confidence
    • Best X Cycles

For each parameter value, it indicates its source in parenthesis. The source can be one of the following:

  • Param – Value was taken from the Parameters window.
  • Opt – Value was generated based on the optimization settings specified in the Parameters window.
  • Saved – Saved value for this instrument and time period.
  • AFL – Value was taken from the AFL variable corresponding to the parameter.
  • Array – Value was taken from an AFL array. Since arrays can use a different value for each bar, no value will be displayed.

AFL variables have the highest precedence, followed by saved values and then values specified in the Parameters window.

In addition to the Trace window, you can enable logging to a file by entering the file path in the Parameters window.

Was this article helpful?
Dislike 0
Views: 1418
FOREVER FREE
Daily Trading Signals
by PrescientSignals
SUBSCRIBE
Subscribe to receive FREE trading signals delivered to your email inbox daily
Free signals are delayed by one-week. This allows you to evaluate our PrescientSignals service risk-free, by comparing the previous week's predictions with the actual results.
FOREVER FREE
Daily Trading Signals by PrescientSignals
SUBSCRIBE
Subscribe to receive FREE trading signals delivered to your email inbox daily
Free signals are delayed by one-week. This allows you to evaluate our PrescientSignals service risk-free, by comparing the previous week's predictions with the actual results.