Quantower
Quantower Website
  • Welcome to Quantower Help
  • 🚀Getting Started
    • What's new
    • Installation
    • First start
    • Platform update
    • Quantower Beta
    • Quantower Account
    • Quantower Licenses
    • ⚖️License Comparison
    • Backup & restore manager
    • Reset settings to default
    • Payment FAQ
    • “Coinpayments” payment
    • Binance fresh account
    • Referral Program
    • You have found a bug. What’s next?
  • ⚙️General Settings
    • Quantower Main Toolbar
    • Workspaces
    • Single Panel
    • Link panels
    • Binds
    • Group of panels
    • Templates
    • Set as Default
    • Symbols lookup
    • Table management
    • Alerts
    • General settings
    • Custom hotkeys
    • Setup Actions & Advanced filters
    • 📢Notifications center
  • 🔗Connections
    • Connections manager
    • Connection to Binance Futures
      • Errors with Binance connection
    • Connection to CQG (AMP Futures)
      • Errors with CQG
    • Connection to OANDA
    • Connection to FXCM
    • Connection to cTrader
      • How to connect to FxPro via Quantower
      • How to connect to Pepperstone via Quantower
      • How to connect to IC Markets via Quantower
    • Connection to Rithmic
      • Rithmic Issues
    • Connection to Topstep
    • Connection to Interactive Brokers
      • Errors with Interactive Brokers
    • Connection to Bybit
    • Connection to OKEx
    • Connection to MetaStock
    • Connection to IQFeed
  • 💡Analytics Panels
    • Chart
      • Chart Overview
      • Chart Types
        • Tick Bars
        • Time aggregation
        • Renko
        • Heiken Ashi
        • Kagi
        • Points & Figures
        • Range bars
        • Line break
        • Volume Bars
        • Reversal Bars
      • Chart Settings
        • View settings
        • Data Style
        • Time Scale
        • Price Scale
        • Visual Trading
          • Positions
        • Order Entry
        • Quick Ruler
        • Info Window
        • Volume Bars
        • Hotkeys
      • Chart overlays
      • Technical indicators
        • Channels
          • Range Marker
          • Donchian Channel
          • High Low Indicator
          • Round Numbers
          • Highest High
          • Lowest Low
          • Bollinger Bands
          • Bollinger Bands Flat
          • Price Channel
          • Fair Value Gap (FVG)
          • Keltner Channel
          • Moving Average Envelope
        • Moving averages
          • Demand Index
          • Exponential Moving Average
          • FYL Indicator
          • Linearly Weighted Moving Average
          • McGinley Dynamic Indicator
          • Modified Moving Average Indicator
          • Pivot Point Moving Average Indicator
          • Regression Line Indicator
          • Simple Moving Average Indicator
          • Smoothed Moving Average Indicator
          • Guppy Multiple Moving Average Indicator
          • Trend Breakout System Indicator
          • Triple Exponential Moving Average Indicator
        • Oscillators
          • Delta Divergence Reversal
          • Aroon Indicator
          • Moving Average Convergence/Divergence
          • Awesome Oscillator
          • Accelerator Oscillator
          • %R Larry Williams
          • Momentum
          • Rate of Change
          • Relative Strength Index (RSI) Indicator
          • Relative Spread Strength (RSS)
          • Balance of Power (BOP)
          • Commodity Channel Index
        • Trend
          • Bionic Candle
          • Average Directional Movement Index (ADX) Indicator
          • Ichimoku Cloud Indicator
          • Directional Movement Index (DMI) Indicator
          • ZigZag
        • Volatility
          • Average True Range
          • Standard deviation
        • Volume
          • COT High/Low
          • Depth of Bid / Ask
          • Delta Flow
          • Delta Rotation
          • Level2 indicator
          • Abnormal Volume
          • Abnormal Trades
          • Volume Impulse
      • Drawing tools
      • Volume Analysis Tools | Volume Profiles | Footprint chart | VWAP
        • Cluster chart
        • Volume profiles
        • Time statistics
        • Time histogram
        • Historical Time & Sales
      • Power Trades
      • VWAP | Volume Weighted Average Price
      • Anchored VWAP
    • Watchlist
    • Time & Sales
    • Price Statistic
    • DOM Surface
    • Option Analytics
    • TPO Profile Chart
  • 💵Trading Panels
    • Chart Trading
    • Crypto Order Entry
    • Multiple Order Entry
    • Order Entry
      • Order entry for Bybit
      • Order Entry for CQG
      • Order Types
      • Order placing strategies
        • Local SL/TP
    • DOM Trader
      • DOM Trader Settings
        • View Settings
        • DOM Trader Columns
        • Order Entry
        • VWAP Settings
        • Positions Bar
        • Hotkeys
      • DOM Trader Columns
      • How to set up Dom for scalping
    • Copy Trading
    • Market depth
    • Trading simulator
    • Market Replay
    • FX Cell
    • Backtest & Optimize
    • Strategies manager
  • 💼Portfolio Panels
    • Positions
    • Working Orders
    • Trades
    • Orders History
    • Synthetic Symbols
    • Historical Symbols
  • 📊Information Panels
    • Account performance
    • Account info
    • Crypto balances
    • Symbol Info
    • Currencies Exposure
    • Event Log
    • RSS (News panel)
    • Reports
  • 📌Miscellaneous
    • Futures Rollover
    • History Exporter
    • Symbol Mapping Manager
    • Sessions manager
    • Live Support
    • Market Heat map
    • Stat matrix
    • Exchange times
    • Quote Board
    • Browser
    • Excel and RTD function
      • Changing RTD Throttle Interval in Excel
    • Quantower Telegram Bot
    • 🎨Themes editor
  • 🤖Quantower Algo
    • Introduction
    • Install for Visual Studio 2022
    • Strategies manager
    • Backtest & Optimize
    • Debugging in VS 2022
    • Simple Indicator
    • Simple strategy
    • Input Parameters
    • Built-In indicators access
    • Custom indicators access
    • Level2 data
    • Access Volume analysis data from indicators
    • Indicator with custom painting (GDI)
    • Access Chart from indicator
    • Using markers with indicators
    • Using Clouds in Indicator
    • Adding a custom indicator to Watchlist
    • Downloading history
    • Access to trading portfolio
    • Trading operations
    • Example: Simple Moving Average
    • Access to crypto account and balances
    • Access to advanced aggregations
    • Access to symbol/account additional fields
    • Strategy runner (deprecated)
  • 💫Customization
    • Localization
  • ⁉️FAQ
    • General Errors
Powered by GitBook
On this page
  • Theory
  • Available aggregation classes
  • Tick aggregation
  • Time aggregation
  • Heiken-Ashi aggregation
  • Range Bars aggregation
  • Renko aggregation
  • Line break aggregation
  • Kagi aggregation
  • Points & Figures aggregation
  • Volume Bars aggregation
  • Practice
  • Input parameters
  • OnRun method
  • OnGetMetrics method
  • OnStop method
  1. Quantower Algo

Access to advanced aggregations

Using the available aggregation types in your code

Last updated 4 years ago

Theory

As we know, chart aggregation is a type of displaying aggregated values. These values are price, volume and time. The main idea of each aggregation is to help traders analyze the state of the market in history and in real time.

At this moment, Quantower API supports 9 aggregation types. All of them you can use in your scripts easily. But before we continue, please read the article by using Quantower API.

To download aggregated history we need use method which takes instanse of class as input parameter. This class contains the necessary properties such as FromTime, ToTime, HistoryType, etc. with which we can flexibly customize our request. But today we are interested in the property. This property contains instance of class which is base class for all available aggregation types. All we need to get the aggregated history is to set to this property instance of required aggregation type.

Listed below are all available aggregation classes with examples of history requests.

Available aggregation classes

Tick aggregation

The class is used to buid simple Tick chart.

new HistoryAggregationTick(int ticksCount);
  • ticksCount - the number of ticks for aggregation.

var tickhistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddHours(-3),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.VolumeType == SymbolVolumeType.Volume ? HistoryType.Last : HistoryType.BidAsk,
    Period = Period.TICK1,
    Aggregation = new HistoryAggregationTick(1),
});

Time aggregation

new HistoryAggregationTime(Period period);
var timeBarHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddDays(-3),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.HistoryType,
    Period = Period.MIN15,
    Aggregation = new HistoryAggregationTime(Period.MIN15),
});

Heiken-Ashi aggregation

new HistoryAggregationHeikenAshi(HeikenAshiSource source, int value);
  • source - enum, base period of time (Tick, Seconds. Minutes etc).

  • value - the amount of 'source' time.

var heikenAshiHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddDays(-3),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.HistoryType,
    Aggregation = new HistoryAggregationHeikenAshi(HeikenAshiSource.Minute, 1),
});

Range Bars aggregation

new HistoryAggregationRangeBars(int rangeBars);
  • rangeBars - the height (in ticks) of each bar.

var rangeBarHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddHours(-3),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.HistoryType,
    Aggregation = new HistoryAggregationRangeBars(10),
});

Renko aggregation

new HistoryAggregationRenko(Period period, int brickSize, RenkoStyle renkoStyle, int extension = 100, int inversion = 100, bool showWicks = false, bool buildCurrentBar = true)
  • brickSize - required size of renko brick

  • renkoStyle - enum, calculation methods (Classic, HighLow, AdvancedClassic, AdvancedHighLow)

var renkoHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddDays(-1),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.HistoryType,
    Aggregation = new HistoryAggregationRenko(Period.MIN1, 10, RenkoStyle.AdvancedClassic, 100, 100, true, true),
});

Line break aggregation

new HistoryAggregationLineBreak(Period period, int lineBreak); 
  • lineBreak - line break value.

var lineBreakHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddDays(-1),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.HistoryType,
    Aggregation = new HistoryAggregationLineBreak(Period.MIN15, 3),
});

Kagi aggregation

new HistoryAggregationKagi(Period period, int reversal);
  • reversal - the amount of price movement that required for the Kagi line to reverse direction.

var kagiHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddDays(-1),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.HistoryType,
    Aggregation = new HistoryAggregationKagi(Period.MIN15, 10),
});

Points & Figures aggregation

new HistoryAggregationPointsAndFigures(Period period, int boxSize, int reversal, PointsAndFiguresStyle style);
  • boxSize - price range (the number of ticks) for X-Columns or O-Columns

  • reversal - a parameter that indicates the number of Box Sizes that the price should go in the opposite direction to begin a new column.

  • style - enum, calculation methods (Classic, HighLow)

var pointFiguresHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddDays(-1),
    ToTime = DateTime.Now,
    HistoryType = this.Symbol.HistoryType,
    Aggregation = new HistoryAggregationPointsAndFigures(Period.TICK1, 100, 50, PointsAndFiguresStyle.HighLow),
});

Volume Bars aggregation

new HistoryAggregationVolume(int volumeValue);
  • volumeValue - base volume value of bar

var volumeBarsHistoricalData = this.Symbol.GetHistory(new HistoryRequestParameters()
{
    Symbol = this.Symbol,
    FromTime = DateTime.Now.AddHours(-4),
    ToTime = DateTime.Now,
    Period = Period.TICK1,
    HistoryType = this.Symbol.HistoryType,
    Aggregation = new HistoryAggregationVolume(1000),
});

Practice

In this part of the article, we will create a simple strategy script in which we will try to apply the knowledge. Let's describe our actions step by step:

  1. Create HistoricalData instance by loading 6 hours of Renko history.

  2. Create Fast SMA and Slow SMA indicators and then attach them to our HistoricalData.

  3. Display metrics:

    1. Fast SMA value

    2. Slow SMA value

    3. Current brick high price

    4. Current brick low price

  4. Log high and low prices of each new brick.

Input parameters

First, let’s define input parameters. In this section, we want to be able to change the aggregation parameters and indicator base settigns.

[InputParameter("Symbol", 10)]
public Symbol Symbol;

[InputParameter("Renko period", 20)]
public Period RenkoPeriod = Period.MIN1;

[InputParameter("Brick size", 30)]
public int BrickSize = 10;

[InputParameter("Renko style", 40, variants: new object[]
{
    "Classic", RenkoStyle.Classic,
    "High/Low", RenkoStyle.HighLow,
    "Adv. Classic", RenkoStyle.AdvancedClassic,
    "Adv. High/Low", RenkoStyle.AdvancedHighLow,
})]
public RenkoStyle RenkoStyle = RenkoStyle.Classic;

[InputParameter("Fast SMA period", 50, 1, 9999, 1, 0)]
public int FastSmaPeriod = 10;

[InputParameter("Slow SMA period", 50, 1, 9999, 1, 0)]
public int SlowSmaPeriod = 30;

private HistoricalData renkoHistoricalData;
private Indicator fastSmaIndicator;
private Indicator slowSmaIndicator;

OnRun method

In this section, we will carry out the first, second and fourth points.

Pay attention to line 30. Here we subscribe 'NewHistoryItem' event. Another words, our 'RenkoHistoricalData_NewHistoryItem' handler will trigger on each new brick item.

protected override void OnRun()
{
    //
    // check is symbol is null
    //
    if (Symbol == null)
    {
        Log("Symbol is null", StrategyLoggingLevel.Error);
        Stop();
        return;
    }

    try
    {
        //
        // Download history (use Renko aggregation)
        //
        renkoHistoricalData = Symbol.GetHistory(new HistoryRequestParameters()
        {
            Symbol = Symbol,
            HistoryType = Symbol.HistoryType,
            FromTime = Core.Instance.TimeUtils.DateTimeUtcNow.AddHours(-6),
            ToTime = default,
            Aggregation = new HistoryAggregationRenko(RenkoPeriod, BrickSize, RenkoStyle)
        });

        //
        // Subscribe to 'NewHistoryItem' event 
        //
        renkoHistoricalData.NewHistoryItem += RenkoHistoricalData_NewHistoryItem;

        //
        // Create Fast/Slow SMA indicators
        //
        fastSmaIndicator = Core.Instance.Indicators.BuiltIn.SMA(FastSmaPeriod, PriceType.Close);
        slowSmaIndicator = Core.Instance.Indicators.BuiltIn.SMA(SlowSmaPeriod, PriceType.Close);

        //
        // Attach our indicators to downloaded HistoricalData
        //
        renkoHistoricalData.AddIndicator(fastSmaIndicator);
        renkoHistoricalData.AddIndicator(slowSmaIndicator);
    }
    catch (Exception ex)
    {
        Log(ex.Message, StrategyLoggingLevel.Error);
        Stop();
    }
}

private void RenkoHistoricalData_NewHistoryItem(object sender, HistoryEventArgs e)
{
    // get high price for new brick
    var highPrice = e.HistoryItem[PriceType.High];

    // get low price for new brick
    var lowPrice = e.HistoryItem[PriceType.Low];

    // print message
    Log($"New brick  --  High: {highPrice} | Low: {lowPrice}", StrategyLoggingLevel.Info);
}

OnGetMetrics method

Here we create required metrics.

Pay attention to line 10. Here we use 'FormatPrice' method to format indicator value to symbol tick size.

protected override List<StrategyMetric> OnGetMetrics()
{
    var result = base.OnGetMetrics();

    if (fastSmaIndicator != null)
    {
        result.Add(new StrategyMetric()
        {
            Name = "Fast SMA value",
            FormattedValue = Symbol.FormatPrice(fastSmaIndicator.GetValue())
        });
    }

    if (slowSmaIndicator != null)
    {
        result.Add(new StrategyMetric()
        {
            Name = "Slow SMA value",
            FormattedValue = Symbol.FormatPrice(slowSmaIndicator.GetValue())
        });
    }

    if (renkoHistoricalData != null)
    {
        result.Add(new StrategyMetric()
        {
            Name = "Current brick high price",
            FormattedValue = Symbol.FormatPrice(renkoHistoricalData[0][PriceType.High])
        });
        result.Add(new StrategyMetric()
        {
            Name = "Current brick low price",
            FormattedValue = Symbol.FormatPrice(renkoHistoricalData[0][PriceType.Low])
        });
    }

    return result;
}

OnStop method

Never forget to remove unused objects and unsubscribe form unused events.

protected override void OnStop()
{
    if (renkoHistoricalData != null)
    {
        //
        // remove 'fastSmaIndicator' instance
        //
        if (fastSmaIndicator != null)
            renkoHistoricalData.RemoveIndicator(fastSmaIndicator);

        //
        // remove 'slowSmaIndicator' instance
        //
        if (slowSmaIndicator != null)
            renkoHistoricalData.RemoveIndicator(slowSmaIndicator);
        
        //
        // unsubscribe from 'NewHistoryItem' event and dispose our HistoricalData instance
        //       
        renkoHistoricalData.NewHistoryItem -= RenkoHistoricalData_NewHistoryItem;
        renkoHistoricalData.Dispose();
    }
}

The class is used to build the chart.

period - period of time (8s, 30min, 4h etc). Instance of structure.

The class is used to build the chart.

The class is used to build the chart.

The class is used to build the chart.

period - base period of time. Instance of structure.

The class is used to build the chart.

period - base period of time. Instance of structure.

The class is used to build the chart.

period - base period of time. Instance of structure.

The class is used to build the chart.

period - base period of time. Instance of structure.

The HistoryAggregationVolume class is used to build the chart.

Pay attention to line 24. Here we create instance of class and pass required parameters.

🤖
how to download history
GetHistory
HistoryRequestParameters
Aggregation
HistoryAggregation
HistoryAggregationTick
HistoryAggregationTime
Time
Period
HistoryAggregationHeikenAshi
Heiken-Ashi
HistoryAggregationRangeBars
Range Bars
HistoryAggregationRenko
Renko
Period
HistoryAggregationLineBreak
Line break
Period
HistoryAggregationKagi
Kagi
Period
HistoryAggregationPointsAndFigures
Points & Figures
Period
Volume bars
HistoryAggregationRenko