Back

Momentum Algorithm

Hello,

I like to build a simple momentum algorithm for the Forex to get familiar with QuantConnect. The algorithm is as follows...

Step #1: Define the Trend. An Uptrend is defined by a Series of HH Followed by a Series of HL. Say the USD/EUR and USD/JPY
Step #2: In an Uptrend Look for Bold Candlesticks that Close Near the Higher End of the Candlestick.
Step #3: Wait for the Williams %R Indicator to get oversold (below -80). Then rallies above the -50 level before Buying.
Step #4: Place Your Protective Stop Loss below the Recent Higher Low.
Step #5: Take Profit once we break below the Previous Higher Low
(For the Sell, we would inverse the process. LH followed by LL, overbought, etc.)

How to best implement this algorithm to leverage best in class practice with QuantConnect? Why do I mean by best practice? I want to use QuantConnect features such as the RiskModel for portfolio risk. This would be "simple" in straight python but don't get all the bells and whistle of QuantConnect. 

Thanks in advance!

Bo

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.


Hi Bo,

To learn how to implement this algorithm, I recommend reviewing our Forex Bootcamp lesson. It is a great place to start, and even comes with an example algorithm.

In regards to the indicators, the QCAlgorithm class has built-in indicators for momentum and Williams %R that can be used quite easily. Just review our documentation on indicators to see how. Our momentum indicator does not track a trailing series of HH, HL, LH, and LL, but it is an easily alternative for what would require the use of a RollingWindow.

For the specific orders this algorithm needs, review our documentation on order types for examples on setting stop losses and take profit levels.

Best,
Derek Melchin

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 Derek,

I went through all the lessons and documentation. What I found would be the closes to HH, HL would be to use the RenkoConsolidator.  This way time is removed and I can see the price delta. However, I ran into a few issues for which I found conflicting information within the forum. Hope your and/or community can help clarify...

  • Most out of the box momentum indicators don't work with Futures Contracts?
  • QC doesn't support graphing them Renko Chart
  • Can't pass an ATR using the RenkoConsolidator. Divided by Zero issue even though warming up
0


Hi Bo Vargas,

The out-of-the-box momentum indicators work with futures contracts. See the attached backtest for an example.

In regards to plotting renko bars, see this related thread.

It is possible to pass in the trailing ATR to the RenkoConsolidator constructor. However, the BarSize property of the class is fixed, so it won't change as the trailing ATR is updated.

Can you provide an example backtest which encounters the divide by zero issue? This could be a number of things.

Best,
Derek Melchin

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.


I can't attached the Backtest for divided by Zero, but it's basically the code I have with the the different being...

consolidator = RenkoConsolidator(self.renkoATR.Current.Value)

I've reviewed your example. The question is then where doesn't one put the Consolidators within the OnSecuritiesChanged or OnData? Where's the best place to update the charts for Futures Contract? 

Does the self.SetRiskManagement(TrailingStopRiskManagementModel(0.08)) still functions as it should given that you seems to be moving the History loading and MOM to the OnData vis keep it within the Initialize?

0

Hi Bo,

The divide by zero error occurs because the ATR indicator is applied to the canonical symbol instead of a tradeable futures contract.

Setting up the consolidators can go in either OnData or OnSecuritiesChanged. Its location depends on if the intention is to setup a consolidator for every available futures contract (in OnSecuritiesChanged) or just the one we're interested in trading after filtering and sorting (in OnData). Either way, we'd recommend removing consolidators in OnSecuritiesChanged.

Code for updating the charts would be best placed in OnData or OnEndOfDay, depending on how often we'd like to update the chart.

The risk management module will function as we expect, regardless of the location of indicator initialization/warmup. It just monitors trailing stop loss levels after we have entered a position.

Best,
Derek Melchin

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.


k, makse sense. Do I need to load the history for the indicators myself or is this handle by the framework? You seem to load the history for the Mom indicator in your example. 

In my Initialize I've set trading for March 1 2020 and resolution is a tick. Will all my indicators below be updated automatically or do I need to back date the SetStartDate back 30 days to warm up the indicators with the data?

def OnData(self, data):
"""Method called when new data is ready for each period."""

for chain in data.FutureChains:
self.popularContracts = [contract for contract in chain.Value if contract.OpenInterest > 1000]

# If the length of contracts in this chain is zero, continue to the next chain
if len(self.popularContracts) == 0:
continue

# Sort our contracts by open interest in descending order and save to sortedByOIContracts
sortedByOIContracts = sorted(self.popularContracts, key=lambda k : k.OpenInterest, reverse=True)

# Save the contract with the highest open interest to self.liquidContract
self.liquidContract = sortedByOIContracts[0]


# All the indicators
self.fourteenDayATR = self.ATR(self.liquidContract.Symbol, 14, MovingAverageType.Simple, Resolution.Daily)

# define a slow and fast moving average indicator
# slow moving average indicator: 200 periods
# fast moving average indicator: 50 periods
# these indicator objects are automatically updated
self.hourlySlowSMA = self.SMA(self.liquidContract.Symbol, 200, Resolution.Hour)
self.hourlyFastSMA = self.SMA(self.liquidContract.Symbol, 50, Resolution.Hour)

# define a pair of moving averages in order to confirm an
# alignment trend in the daily charts
# If both the hourly trend (using the 2 hourly SMAs above) and daily
# trend show the same trend direction,
# then the trend is a strong trend
self.dailySlowSMA = self.SMA(self.liquidContract.Symbol, 21, Resolution.Daily)
self.dailyFastSMA = self.SMA(self.liquidContract.Symbol, 7, Resolution.Daily)


# stochastic indicator
# stochastic period: 9
# stochastic k period: 9
# stochastic d period: 5
self.stoch = self.STO(self.liquidContract.Symbol, 9, 9, 5, Resolution.Hour)

# only trade when the indicators are ready
if not self.hourlySlowSMA.IsReady or not self.hourlyFastSMA.IsReady or not self.stoch.IsReady or not self.fourteenDayATR.IsReady:
return None

 

0

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