Trend-Volatility Multi-Currency Portfolio Strategy with Risk Control

Back

Hi,

So, using my initial framework, this time I tried a trend based strategy for trading which makes use of a profit target to exit and an rsi indicator for its entry. The strategy performs very well achieving a return of over 1400%. Starting with cash $2000 I end up with just over $30000 over a period of almost 10 years. It achieves a win rate of 89% which a constant amount of risk per trade. To balance the portfolio, I use a few symbols at a time. The strategy performs very well and with better indicators may perform even better. 

It would be fun to discuss what other indicators may do and may perform even better.

 

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.


@Deval - Very cool strategy! Seems to avoid a large drawdown on a regular basis thanks to your volatility code. Can you elaborate more on what your risk control method is? Also, I tried running the algo as its original form but it only trades in 2007..have you had such an issue? Not sure what to do. 

1

@Daniel Thanx for appreciating the strategy. 
My risk control method takes into consideration the volatility of the market. To measure volatility it simply uses standard deviation. So if the market is highly volatile, the strategy would tend to buy accordingly so that it doesn't risk more than it is designed to. So, in this way no matter how fluctuating or unpredictable the market is you would never lose more than you tell it to but if it wins it could win big. This gives you the control on how much you want to risk per trade no matter which strategy you implement or how the market behaves. It is meant to give you more control over your losses. All of these calculations are made in the TradeProfile class.

I haven't faced any issues with the backtest. I think because the backtest is so big and it makes so many trades that it appear on a year by year basis. Just let it run it works well.

If you have more questions, feel free to let me know.

2

Hi @Deval 

I like how your strategy looks. So I am trying to mimic your strategy in LEAN environment. As I don't have an FXCM demo account, and I had to download several years of Forex history, and I did have an Oanda demo account, I used it to download history for EURUSD, GBPUSD, NZDUSD and AUDUSD.

I have not tried yet to backtest your strategy in LEAN through the whole period 2007 - now, but I have backtest from 2015 until now and my results are very different from yours, and I don't know why...

These statistics are from a backtest from 20150101 until now.

Maybe the history is different from FXCM to Oanda and I must adjust it before backtesting?

Any ideas? 

20160704 13:52:41 Trace:: Debug: Algorithm Id:(TrendVolatilityForex) completed in 973,64 seconds at 2k data points per second. Processing total of 2.408.249 data points.
20160704 13:52:44 Trace:: STATISTICS:: Total Trades 47024
20160704 13:52:44 Trace:: STATISTICS:: Average Win 0,02%
20160704 13:52:44 Trace:: STATISTICS:: Average Loss -0,16%
20160704 13:52:44 Trace:: STATISTICS:: Compounding Annual Return -0,710%
20160704 13:52:44 Trace:: STATISTICS:: Drawdown 12,800%
20160704 13:52:44 Trace:: STATISTICS:: Expectancy 0.000
20160704 13:52:44 Trace:: STATISTICS:: Net Profit -1,068%
20160704 13:52:44 Trace:: STATISTICS:: Sharpe Ratio -0.004
20160704 13:52:44 Trace:: STATISTICS:: Loss Rate 12%
20160704 13:52:44 Trace:: STATISTICS:: Win Rate 88%
20160704 13:52:44 Trace:: STATISTICS:: Profit-Loss Ratio 0.14
20160704 13:52:44 Trace:: STATISTICS:: Alpha -0.001
20160704 13:52:44 Trace:: STATISTICS:: Beta 0.054
20160704 13:52:44 Trace:: STATISTICS:: Annual Standard Deviation 0.095
20160704 13:52:44 Trace:: STATISTICS:: Annual Variance 0.009
20160704 13:52:44 Trace:: STATISTICS:: Information Ratio -0.121
20160704 13:52:44 Trace:: STATISTICS:: Tracking Error 0.111
20160704 13:52:45 Trace:: STATISTICS:: Treynor Ratio -0.007
20160704 13:52:45 Trace:: STATISTICS:: Total Fees $1880,96

 

1

Sorry, my fault. I've realized I had mistyped something, because I've rewritten again the whole CS program from scratch and now my backtest in LEAN looks equal to the one done in Algorithm Lab. 

Just one comment @Deval , do you think this is a feasible strategy in real? I've seen all the orders are opened and closed in the same minute... Wouldn't we be under the terrible effect of the spread of these forex pairs in real conditions?

0

Sorry, again, my fault.. Orders were not opened and closed in the same minute, I was mistaken with the STOP MARKET orders, which are triggered just after launching MARKET orders.

I'm testing this strategy live in a demo account. I'll let you know thoughts and achievements.

0

Thanx Joaquin for taking time and reading my strategy. Yes maybe the FXCM and Oanda data is different. Also the fee structure for the two brokerages maybe different. You can tinker around with the parameters to adjust for it. The main focus here is he risk control model and the volatility framework and how it saves you from huge losses. The strategy that I am currently using is a very simple one. Maybe with a better strategy it may perform better. 

I would love to know how your strategy does live on the market. :)

0

Have you tried this in a paper trading account with real-time pricing?

0

@daniel I have for a short time. It was pretty decent given how simple my signal was but my losses were minimal.

0

Deval. I changed the starting capital to $20,000 and minimum trade amount to $1,000,000 and the results were dramatically different. Any clue as to why?
0

Deval. I changed the starting capital to $20,000 and minimum trade amount to $1,000,000 and the results were dramatically different. Any clue as to why?
1

Do you mean value of the 'minimum trade amount' or the 'maximum trade amount'?

0

Sorry, Maximum Trade Amount 

0

Are you having any issues with the orignal settings you posted? Today I'm getting a lot of Runtime Errors 'Insufficient buying power to complete order' 

0

The insufficient buying power errors are because you've increased the maximum trade size to $1M and there isn't enough capital to buy the portfolio of assets (5 assets x $1M would require 250x leverage). You should use a small maximum trade to keep the risk per trade small.

There is a genuine error though because one of the orders is less than 1000 EUR (minimum quantity for the brokerage). The fix is to set the quantity to 1000 if the quantity is too small in the tradeProfile.Quantity. This was caused by a recent fix to LEAN (previously trade was placed and ignored, now the trade is simply not placed so cannot be found).

public int Quantity
{
get
{
if (_volatility == 0) return 0;
long quantity = (long)(_risk / _volatility);
if (quantity > _maximumTradeQuantity) return _maximumTradeQuantity;

if (quantity < 1000)
{ // The FIX
quantity = 1000;
}
return (int)quantity;
}
}

 

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 Jared. I guess the change also impacted @Deval's original model as

running that now has issues.
0

A quick update on my initial strategy. This time with some minor bug fixes.

1. Added a check for quantity and maximum trade quantity when they are below 1000 to avoid it being 0.

// Calclate the quantity based on the target risk in dollars.
public int Quantity
{
get
{
if (_volatility == 0) return 0;
long quantity = (long)(_risk / _volatility);
//Check if the value for the maximum trade quantity is less than zero to avoid placing 0 value trade
if (quantity > _maximumTradeQuantity)
{
return _maximumTradeQuantity < 1000 ? 1000 : _maximumTradeQuantity;
}

return (int) quantity < 1000 ? 1000 : (int) quantity;
}
}

2.  Added a check in OnData to see if all the tradeBars contains data while running. Previous implementation caused the program to crash on few occasions when the resolution was set to seconds since all the symbols may not be ready. The simple fix below fixes it. So you just wait until all the symbols have data.

public void OnData(TradeBars data)
{
//Checks if the tradebars for all the symbols are ready and present.
if (data.Count < Symbols.Length) return;

If any more bug are to be found in the future, I would be more than happy to fix them. Thanx to community for pointing them out. 

 

0


Hi @Jared, Hi @Deval,

regarding the "Insufficient buying power": I am testing the strategy in LEAN, with a demo account. Its balance is 99,000 €, and leverage is 50. I have RiskPerTrade set to 400, and MaximumTradeSize set to 100K. And I get lots of "Insuficient buying power". Sometimes I get 2 positions opened, even sometimes 3, but when these error emerges, even the stop orders are not always opened because the strategy "thinks" that it lacks buying power... Although only about 5% of leverage is being used. 

I think there must be a bug in the code, but I haven't had the time to debug it... @Deval maybe you have some hint of what could be happening?

 

0

I'm noticing the exact same issue using the paper trader.  Orders can't be opened due to insufficient buying power, including stop loss orders.  There have also been some wild swings in the portfolio equity from $100k to up to $200k and back down to $100k again.  I'm seeing in the logs that there have been many orders with a size of 0 being submitted as well.

0

@Roberto, stops show as 0 order quantity until they are filled.

The portfolio value swings was a bug fixed on Monday/Tuesday. If you stop and start your algorithm you'll get the new version. You may want to do a fresh clone so the charts don't show the swings (so the chart axis auto scales zoom into your area easier).

 

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.


@Roberto @Joaquin What brokerage are you using? What symbols are you using? Could you please post your algorithms here so I can debug them better? Looking at the code would help.

Thank You.

0

Hi @Deval, sadly there is a bug in the algorithm that makes it "too good to be true" :)

The following line:

Securities[symbol].FeeModel = new ConstantFeeModel(0.04m);

should be changed to:

 Securities[symbol].FeeModel = new FxcmFeeModel();


FXCM commissions are $0.04/$0.06 per 1K lot:
https://github.com/QuantConnect/Lean/blob/master/Common/Orders/Fees/FxcmFeeModel.cs#L44
so the original algorithm is only charging 1/10th of the real fees.
 

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.


@Stefano I set a constant fee because my quantity sizes were anyways about 3k-4k. With the current fxcm fee model it was charging me fees even for submitting my stop orders which is not the case in reality. Fees are only charged when the order gets filled. since it was amplifying my fees for just submitting the stop order I kept the fee value constant.

0

@Deval, with the current master code, no fees are charged for limit or stop orders, if they are not filled.

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 have shared it with you. It's basically your strategy, with some minor changes, as I use Oanda as my broker. As you can see, backtests work ok, the strange behaviour is when trading live.

I know your strategy maybe would give better results with other setups (other indicators and different entries/exits), but I do like your risk mgmt and would like to try this risk mgmt with other already winning strategies.

0


Hey @Joaquin the Oanda data set isn't quite processed all the way! We're tidying up our FX data now and it should be ready for an Oanda market test / downloading within a week or two.

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.


cheers

1

Deval, if there was an award for well-organized code, you would win it :-)

2

@Stephen Thanks a lot man. Much appreciated.

0

@Deval the fees is much lower than the live trade,please check the total lot and fee of a backtest result, it's a profitable stragery though, but the equity curve is no so smooth and the profit is lower.

0

^
0

Cheers!
0

I am getting errors with this line of code from the clone above:

Securities[symbol].VolatilityModel = new ThreeSigmaVolatilityModel(STD(symbol, 390, _dataResolution));

and the error reads: Cannot implicitly convert type ...ThreeSigmaVolatilityModel to ...IVolatilityModel.

How do I properly cast that line of code so that they match?  Thanks.

 

V/R,

Geno

0

Genorse Gilbert, the IVolatilityModel interface changed since Deval Keralia developed this algorithm.

Now you have to implement the GetHistoryRequirements method.

If you'll not use the algorithm in live mode you can just add the following code to ThreeSigmaVolatilityModel:

public IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime
{
return Enumerable.Empty<HistoryRequest>();
}

 

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.


.
0

This algorithm is no more working, I got the following errors when I backtest :

Backtest Error: Error initializing algorithm: This may be because history is using fake data while pre-analyzing an algorithm for a backtest

Backtest Error: Error initializing algorithm: Calling this method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter.

Could you please provide some workarround ?

Thanks for your help.

0

hi, have you tried it with the changes mentioned above by jayjayd?

0

Yes, I made this implementation based in Deval Keralia work.

 

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.


Still have same error at backtest init : Error initializing algorithm: This may be because history is using fake data while pre-analyzing an algorithm for a backtest

I have implemented interface GetHistoryRequirements has mentionned

0

Got same error as Mat L.

ERROR:: Calling this method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter.

Any Idea please?

1

Hi Deval, when I clone it I get the below build error:
public class ThreeSigmaVolatilityModel : IVolatilityModel

Suggestions?
0

Hi Deval, when I clone it I get the below build error:
public class ThreeSigmaVolatilityModel : IVolatilityModel

Suggestions?
0

Hello I have this error :

Build Error: File: Volatility.cs Line:27 Column:45 - 'ThreeSigmaVolatilityModel' does not implement interface member 'IVolatilityModel.GetHistoryRequirements(Security, DateTime)'

What can I do ? Thank you !
0

Ryan Brickey and Viann,  above I addressed the IVolatilityModel issue.

 

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.


Got same error as Mat L. and JianWei

ERROR:: Calling this method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter.

Any help would be appreciated.  Thanks!

0

JayJayD where exactly are you saying one should implement the code into to the three sigma volatility model?

1

Sebastain Bugal, in the Volatility.cs file, you should add the following code at the end of the ThreeSigmaVolatilityModel class:

public IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime
{
return Enumerable.Empty<HistoryRequest>();
}
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.


JayJayD 

i am now trying to backtest and am getting the following error message"

Calling this method on a Forex or CFD or crypto security will return an empty result. Please use the generic version with QuoteBar type parameter

"

0

Check where you're using TradeBars and change it for QuoteBars.

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.


how would you make this strategey tradable with a real money account

1

Still errors adding: 

  1. public IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime
  2. {
  3. return Enumerable.Empty<HistoryRequest>();
  4. }
It is incomplete, looks like missing var after DateTime and the closing ")" Regards
0

I added quotebars but algo has not the same behavior

0


 - This is a big reason why we added QuoteBars! They are really important in FX.

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.


So you are stating that the previous successful results were due to not having small enough time segments under backtest? And we should always be using Quotebars in our future Algo's?

0

Tad Johnson - The initial backtest was done before we added Quotebar data; now all FX modelling is done with quotebars in the fill models. We maintained the "tradebar" midpoints algorithm helpers for backwards compatibility with old algorithms, 

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 for clearing that up. I wondered why the backtests were different. Of course I'm coming from MT4 where backtests either don't work consistently or not at all = )

1

Has anyone had luck with the ThreeSigmaVolatilityModel error?

It seems the following format needs to be used: IVolatilityModel.GetHistoryRequirements(Security, DateTime)

However I've been having trouble implementing it into the following part of the code. 

public class ThreeSigmaVolatilityModel : IVolatilityModel

Any help would be appreciated. 

0

Nevermind, it seems I was able to make it work by adding QuoteBars along with

public IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime dateTime)
{
return Enumerable.Empty<HistoryRequest>();
}

However it seems the backtest doesn't perform nearly as well anymore, and stops after September 2008. 

Does this mean that it cannot be live traded anymore?

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...

To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!