Back

Consolidator on non-built-in indicator


I want to use HMA indicator on, say 30, mins bars. I have copied the HMA class from Opening Breakout Algo and the consolidator from the Indicator Examples (BB, MACD, SMA, EMA, RSI, ATR) example. I thought the attached code would work but the trades are not evaluated on the consolidated bar I specified. I have verified the HMA logic using purely Hourly resolution and it worked.
//Add as many securities as you like. All the data will be passed into the event handler:
AddSecurity(SecurityType.Equity, Symbol, Resolution.Hour);
HMA = new HullMovingAverage(Symbol+"_HMA_",40);
RegisterIndicator(Symbol,HMA,Resolution.Hour,Field.Close);

but I do not know what went wrong with this consolidator codes. Actually I was trying to use
AddSecurity(SecurityType.Equity, Symbol, Resolution.Minute);
HMA = new HullMovingAverage(Symbol+"_HMA_",40);
RegisterIndicator(Symbol,HMA,Resolution.Hour,Field.Close);
which I thought would be a system based on Hourly price but placing trade on the next minute as I have used on built-in indicators before. And that is why I switched to consolidator to see if could solve the problem
If I use the same consolidator with built-in indicator like SMA in the following style I can see all the trades evaluated every 30 mins and executed at every 31 and 01 minute as I wanted. I do not know what went wrong with my use of consolidators in the HMA case. Any suggestion is appreciated. Thanks.


private SimpleMovingAverage fast;
private SimpleMovingAverage slow;

TradeBar _spyMinutes;

public override void Initialize()
{
SetStartDate(2015, 01, 01);
SetEndDate(2015, 12, 31);
SetCash(10000);
AddSecurity(SecurityType.Equity, Symbol, Resolution.Minute);

// define our daily trade bar consolidator. we can access the daily bar
// from the DataConsolidated events, this consolidator can only be used
// for a single symbol!
var minConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(30));

// attach our event handler. the event handler is a function that will be called each time we produce
// a new consolidated piece of data.
minConsolidator.DataConsolidated += OnFiveMinutes;

// this call adds our daily consolidator to the manager to receive updates from the engine
SubscriptionManager.AddConsolidator(Symbol, minConsolidator);

int fastPeriod = 2;
int slowPeriod = 16;
fast = new SimpleMovingAverage(Symbol + "_SMA_" + fastPeriod, fastPeriod);
slow = new SimpleMovingAverage(Symbol + "_SMA_" + slowPeriod, slowPeriod);

// we need to manually register these indicators for automatic updates
RegisterIndicator(Symbol, fast, minConsolidator);
RegisterIndicator(Symbol, slow, minConsolidator);
}


private void OnFiveMinutes(object sender, TradeBar consolidated)
{
_spyMinutes = consolidated;
//Log(consolidated.Time.ToString("o") + " >> " + Symbol + ">> LONG >> 100 >> " + Portfolio[Symbol].Quantity);

// if you want code to run every five minutes then you can run it inside of here
}
Update Backtest








It looks like all of your buying logic is in your OnData method. Your OnData method will fire every minute since you've used AddSecurity to subscribe to minute level data. If you want to make trading decisions on the consolidated event, you'll need to place your buy/sell logic in the consolidator's even handler, which in this case, is the OnFiveMinutes method.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Hi Michael,

Thank you for your help and it is working now. I have learned that it is best to put all the logic in the consolidator event handler.

On one related issue, if I use minute resolution in Addsecurity but use Hour resolution in built-in SMA indicator all the trades occur at XX:01 time stamp. Is that because we only have hourly SMA so even though the onData is on minute resolution the SMA value keeps the same for 60 mins and it appears like we are only evaluating the trade once per hour?

Further on, in one of my weird experiment before I did something "stupid" like following:

public class QCUMovingAverageCross : QCAlgorithm
{
private const string Symbol = "SPY";

private SimpleMovingAverage fast;
private SimpleMovingAverage slow;

TradeBar _spyMinutes;

public override void Initialize()
{
SetStartDate(2015, 01, 01);
SetEndDate(2015, 12, 31);
SetCash(10000);
AddSecurity(SecurityType.Equity, Symbol, Resolution.Minute);

// define our daily trade bar consolidator. we can access the daily bar
// from the DataConsolidated events, this consolidator can only be used
// for a single symbol!
var minConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(30));

// attach our event handler. the event handler is a function that will be called each time we produce
// a new consolidated piece of data.
minConsolidator.DataConsolidated += OnFiveMinutes;

// this call adds our daily consolidator to the manager to receive updates from the engine
SubscriptionManager.AddConsolidator(Symbol, minConsolidator);

int fastPeriod = 2;
int slowPeriod = 16;
fast = new SimpleMovingAverage(Symbol + "_SMA_" + fastPeriod, fastPeriod);
slow = new SimpleMovingAverage(Symbol + "_SMA_" + slowPeriod, slowPeriod);

// we need to manually register these indicators for automatic updates
RegisterIndicator(Symbol, fast, minConsolidator);
RegisterIndicator(Symbol, slow, minConsolidator);
}


private void OnFiveMinutes(object sender, TradeBar consolidated)
{
_spyMinutes = consolidated;
//Log(consolidated.Time.ToString("o") + " >> " + Symbol + ">> LONG >> 100 >> " + Portfolio[Symbol].Quantity);

// if you want code to run every five minutes then you can run it inside of here
}


private DateTime previous;
public void OnData(TradeBars data)
{


if (!slow.IsReady) return;

// only once per day
// Commented the following line to simulate intraday - Vats
//if (previous.Date == data.Time.Date) return;

// in OnData, returns outside of 9am - 2pm
//if (Time.Hour <= 9 || Time.Hour > 16) return;


const decimal tolerance = 0*0.10000m;
var holdings = Portfolio[Symbol].Quantity;




{
if (fast > slow * (1 + tolerance))
{
if (holdings <= 0)
{
Log (System.DateTime.Now.Hour.ToString()) ;
Log("BUY >> " + holdings + "@ price " + Securities[Symbol].Price);
SetHoldings(Symbol, 1);
Log("NET POSITION BEFORE NEXT TRANSACTION >> " + holdings);
}
}


if (fast < slow)
{
if (holdings > 0)
{
Log (System.DateTime.Now.Hour.ToString()) ;
Log("SELL >> " + holdings + "@ price " + Securities[Symbol].Price);
SetHoldings(Symbol, -1);
//Liquidate(Symbol);
}
}
}

Plot(Symbol, "Price", data[Symbol].Price);
Plot(Symbol, fast, slow);
previous = data.Time;
}
}
}


Basically I did not put the logic in the event handler. However, the trades were only happening at 30 minutes interval. I am curious what makes this example work accidentally. Thank you.
0

Jiaqi, please post code as an attached backtest wth result. An hourly indicator will emit data each hour, so that means that it will maintain the same value (no updates) for the entire hour (or longer if it doesn't receive new data). The event handler will fire each time we consolidate a new bar on the requested interval, in this case, an hour. So since your trade logic fires each hour you'll see the trades all on the hour. The :01 artifact is due to the resolution of your data. What happens is we receive a minute bar from 10:00 to 10:01 and the consolidator decides that since we've passed 10:00, we should emit an hourly bar, but the current time of the algorithm is 10:01, so trades will happen there. If you change your resolution to Resolution.Second you'll see this drop to 10:00:01.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Thanks Michael. Re-posting the code in the attachment I have a further question for another use of consolidator. Basically I did not put the logic in the event handler. However, the trades were only happening at 30 minutes interval. I am curious what makes this example work accidentally. Thank you very much.
0


This is caused by your indicators being registered on the 30 minute consolidator, so their values will only update every 30 minutes, so the decisions your algorithm makes will only change every 30 minutes.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed