Vix Predicts Stock Index Returns

#region Namespaces 
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
#endregion

namespace ScriptCode {
	/// <summary> 
	/// This is a volatility strategy that uses an equity volatility index to predict returns in the equity market.
	/// The strategy is based on the idea that high risk in the market is an indicator of strong future performance and low risk in the market is an indicator of poor future performance. 
	/// By default, this strategy uses the VIX as a measure of volatility to predict returns in the SPY ETF. 
	/// Positions are opened in SPY when the VIX closes at historically high or low levels, as defined by the user, and closed when the VIX returns to normal levels.
	/// 
	/// Trading Rules: 
	/// 
	/// Long Entry: A buy market order is generated for the specified symbol representing the equity index (SPY by default) when the specified symbol representing the volatility index (VIX by default) closes at or above the specified upper percentile cutoff.
	/// Long Exit: A sell market order is generated when the volatility symbol closes below the specified upper percentile cutoff.
	/// 
	/// Short Entry: A sell short market order is generated for the specified symbol representing the equity index (SPY by default) when the specified symbol representing the volatility index (VIX by default) closes at or below the specified lower percentile cutoff.
	/// Short Exit: A buy market order is generated when the volatility symbol closes above the specified lower percentile cutoff. 
	/// </summary>
	public partial class MyMultiSymbolTradingStrategy : MultiSymbolTradingStrategyScriptBase  // NEVER CHANGE THE CLASS NAME 
	{
#region Variables
		// The index of the symbol representing the volatility index.
		private int _volatilitySymbolIndex = -1;
		// The index of the sorted volatility index close above which the close is considered high.
		private int _upperIndexCutoff;
		// The index of the sorted volatility index close below which the close is considered low.
		private int _lowerIndexCutoff;
		// The index of the symbol representing the equity index.
		private int _equitySymbolIndex = -1;
		// Create for holding whether both symbol indexes were provided.
		private bool _symbolsFound;
		// Create for holding the historical closes of the volatility index.
		private List<double> _volatilityIndexHistory;
		// The length the volatility index history.
		private int _volatilityLookback;
		// Indicates whether to enable the trading strategy to short symbols.
		private bool _enableShorting;
		// Indicates whether to enable the trading strategy to long symbols.
		private bool _enableLonging;
		// The percent distance from the entry price in which to place a stop loss order.
		private double _stopLoss;
		// The percent distance from the entry price in which to place a take profit order.
		private double _takeProfit;
#endregion

#region OnInitialize
		/// <summary>
		/// This function is used for accepting the script parameters and for initializing the script prior to all other function calls.
		/// Once the script is assigned to a Desktop, its parameter values can be specified by the user and can be selected for optimization. 
		/// </summary>
		/// --------------------------------------------------------------------------------------------------
		/// PLEASE USE THE SCRIPT WIZARD (CTRL+W) TO ADD, EDIT AND REMOVE THE SCRIPT PARAMETERS
		/// --------------------------------------------------------------------------------------------------
		/// YOU MUST SET A PARAM TAG FOR EACH PARAMETER ACCEPTED BY THIS FUNCTION.
		/// ALL PARAM TAGS SHOULD BE SET IN THE 'OnInitialize' REGION, RIGHT ABOVE THE 'OnInitialize' FUNCTION.
		/// THE ORDER OF THE TAGS MUST MATCH THE ORDER OF THE ACTUAL PARAMETERS.

		/// REQUIRED ATTRIBUTES:
		/// (1) name: The exact parameter name.
		/// (2) type: The type of data to collect from the user: 
		/// Set to "Integer" when the data type is 'int'
		/// Set to "IntegerArray" when the data type is 'int[]'
		/// Set to "DateTime" when the data type is 'long'  
		/// Set to "DateTimeArray" when the data type is 'long[]'  
		/// Set to "Boolean" when the data type is 'bool'
		/// Set to "BooleanArray" when the data type is 'bool[]'
		/// Set to "Double" when the data type is 'double'
		/// Set to "DoubleArray" when the data type is 'double[]'
		/// Set to "String" when the data type is 'string'
		/// Set to "StringArray" when the data type is 'string[]'
		/// Set to "Indicator" when the data type is 'Indicator'
		/// Set to "Pattern" when the data type is 'Pattern'
		/// Set to "Signal" when the data type is 'Signal'
		/// Set to "Drawing" when the data type is 'Drawing'

		/// OPTIONAL ATTRIBUTES:
		/// (3) default: The default parameter value is only valid when the type is Integer, Boolean, Double, String or an API Type. 
		/// (4) min: The minimum parameter value is only valid when the type is Integer or Double.
		/// (5) max: The maximum parameter value is only valid when the type is Integer or Double.

		/// EXAMPLE: <param name="" type="" default="" min="" max="">Enter the parameter description here.</param> 
		/// --------------------------------------------------------------------------------------------------
		/// <param name="volatilityIndexID" type="String" default="^VIX">The symbol ID used for the volatility index.</param>
		/// <param name="volatilityLookback" type="Integer" default="252" min="1">The length the volatility index history.</param>
		/// <param name="upperPercentileCutoff" type="Double" default="90" min="0" max="99.99">The percentile of the volatility index closes above which the close is considered high.</param>
		/// <param name="lowerPercentileCutoff" type="Double" default="10" min="0" max="99.99">The percentile of the volatility index closes below which the close is considered low.</param>
		/// <param name="equityIndexID" type="String" default="SPY">The symbol ID used for the equity index.</param>
		/// <param name="enableShorting" type="Boolean" default="True">Indicates whether to enable the trading strategy to short symbols. </param>
		/// <param name="enableLonging" type="Boolean" default="True">Indicates whether to enable the trading strategy to long symbols. </param>
		/// <param name="stopLoss" type="Double" default="0">The percent distance from the entry price in which to place a stop loss order. (0 to ignore). </param>
		/// <param name="takeProfit" type="Double" default="0">The percent distance from the entry price in which to place a take profit order. (0 to ignore). </param>
		public void OnInitialize(
			string volatilityIndexID,
			int volatilityLookback,
			double upperPercentileCutoff,
			double lowerPercentileCutoff,
			string equityIndexID,
			bool enableShorting,
			bool enableLonging,
			double stopLoss,
			double takeProfit) {
			// Set the script parameter to a variable.
			_volatilityLookback = volatilityLookback;
			// Set the script parameter to a variable.
			_enableShorting = enableShorting;
			// Set the script parameter to a variable.
			_enableLonging = enableLonging;
			// Set the script parameter to a variable.
			_stopLoss = stopLoss;
			// Set the script parameter to a variable.
			_takeProfit = takeProfit;
			// Create an array to hold all symbol indexes that match the volatility index ID.
			int [] volatilitySymbolIndexes = SymbolFindIndex(volatilityIndexID);
			// Check that at least one symbol index matching the volatility index ID was found.
			if(volatilitySymbolIndexes.Length >= 1){
				// Record the symbol index of the volatility index.
				_volatilitySymbolIndex = volatilitySymbolIndexes[0];
			}
			// Create an array to hold all symbol indexes that match the equity index ID.
			int [] equitySymbolIndexes = SymbolFindIndex(equityIndexID);
			// Check that at least one symbol index matching the equity index ID was found.
			if(equitySymbolIndexes.Length >= 1){
				// Record the symbol index of the equity index.
				_equitySymbolIndex = equitySymbolIndexes[0];
			}
			// Check whether both the volatility and equity indexes were provided.
			if(_volatilitySymbolIndex != -1 && _equitySymbolIndex != -1)
				_symbolsFound = true;
			// Create for holding the historical closes of the volatility index.
			_volatilityIndexHistory = new List<double>();
			// Calculate the index of the sorted volatility index close above which the close is considered high.
			_upperIndexCutoff = (int)(_volatilityLookback * upperPercentileCutoff / 100);
			// Calculate the index of the sorted volatility index close below which the close is considered low.
			_lowerIndexCutoff = (int)(_volatilityLookback * lowerPercentileCutoff / 100);
		}
#endregion

#region OnBarUpdate
		/// <summary>
		/// This function is called after each new bar of each symbol assigned to the Desktop strategy. 
		/// It should evaluate the specified symbol and its new bar in order to determine whether to generate new orders for it. 
		/// Never create indicators, signals or patterns from OnBarUpdate, for performance reasons those should be created from OnInitialize.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The index of the symbol in the strategy symbol table</param>
		/// <param name="dataSeries" type="Integer">The number indicating the data series from which the symbol was updated. 
		/// According to the Desktop strategy data series settings: 0 for the main data series, 1 for the second data series, etc.</param>
		/// <param name="completedBars" type="Integer">The number of completed bars for the specified symbol since the last call to OnBarUpdate.
		/// Always 1 unless the bar type can generate multiple completed bars from a single tick/minute/day update (depending on the underlying bar source).</param>
		/// <param name="isLastSymbol" type="Boolean">Indicates whether this is the last symbol to be updated for the current bar. 
		/// The parameter is valid when the bars for different symbols have matching timestamps, e.g. 1m, 5m, 1d, 1w, etc.</param>
		public override void OnBarUpdate(
			int symbolIndex,
			int dataSeries,
			int completedBars,
			bool isLastSymbol) {
			// Switch the API functions to work with the current symbol.
			SymbolSwitch(symbolIndex);
			// Check whether the bar is complete and the current symbol in the volatility index.
			if(DataIsComplete() && symbolIndex == _volatilitySymbolIndex){
				// Check whether the list is completely empty.
				if(_volatilityIndexHistory.Count() == 0){
					// Create a variable the hold the number of bar shifts used to fill the close history of the volatility index.
					int barShift = 0;
					// Iterate backwards until the volatility index is full or there is no more price history.
					while(_volatilityIndexHistory.Count() < _volatilityLookback && DataClose(barShift) != 0){
						// Add the current close to the list of historical closes.
						_volatilityIndexHistory.Add(DataClose(barShift));
						// Increment the bar shift variable.
						barShift++;
					}
				} else {
					// Add the current close to the list of historical closes.
					_volatilityIndexHistory.Add(DataClose());
					// Check whether the list of historical closes has too many elements.
					if(_volatilityIndexHistory.Count() > _volatilityLookback){
						// Remove the oldest close from the list.
						_volatilityIndexHistory.RemoveAt(0);
					}
				}
			}
			// Check whether all of the symbols have been updated, the volatility and equity indexes symbol IDs were found, and enough history has passed to calculate the percentile cutoffs.
			if(isLastSymbol && _symbolsFound && _volatilityIndexHistory.Count() == _volatilityLookback){
				// Switch the API functions to work with the current symbol.
				SymbolSwitch(symbolIndex);
				// Check whether the bar is complete.
				if(DataIsComplete()){
					// Record the most recent close of the volatility index.
					double volatilityIndexClose = _volatilityIndexHistory[_volatilityIndexHistory.Count() - 1];
					// Create a copy of the volatility index history to be sorted.
					List<double> _sortedVolatilityIndexHistory = new List<double>(_volatilityIndexHistory);
					// Sort the volatility index closes by ascending values.
					_sortedVolatilityIndexHistory.Sort();
					// Switch the API functions to work with the equity index symbol.
					SymbolSwitch(_equitySymbolIndex);
					// Check the volatility index closed at or above the upper cutoff.
					if(volatilityIndexClose >= _sortedVolatilityIndexHistory[_upperIndexCutoff]){
						// Check whether a short position exists. 
						if (PositionExistsInDirection(C_PositionStatus.OPEN, C_Direction.SHORT_SIDE)) {
							// Generate a closing buy to cover market order while assuming that a position sizing script will assign the quantity.
							BrokerMarket(C_ActionType.BUY_TO_COVER, 0, C_TIF.DAY, "Time to close.");
						}
						// Check whether the strategy can go long, there is not a long position open, and there is not a pending order.
						if(_enableLonging && !PositionExistsInDirection(C_PositionStatus.OPEN, C_Direction.LONG_SIDE) && !OrderExists(C_Status.PENDING)){
							// Buy the current symbol while assuming that a position sizing script will assign the quantity.
							int orderIndex = BrokerMarket(C_ActionType.BUY, 0, C_TIF.DAY, "Time to buy.");
							// Set a stop loss on the order.
							BrokerSetStopLossPercent(orderIndex, _stopLoss, true, "Stop loss");
							// Set a take profit on the order. 
							BrokerSetTakeProfitPercent(orderIndex, _takeProfit, true, "Profit target");
						}
					// Check whether the volatility index closed at or below the lower cutoff.
					} else if(volatilityIndexClose <= _sortedVolatilityIndexHistory[_lowerIndexCutoff]){
						// Check whether a long position exists. 
						if(PositionExistsInDirection(C_PositionStatus.OPEN, C_Direction.LONG_SIDE)){
							// Generate a closing sell market order while assuming that a position sizing script will assign the quantity.
							BrokerMarket(C_ActionType.SELL, 0, C_TIF.DAY, "Time to close.");
						}
						// Check whether the strategy can go short, there is not a short position open, and there is not a pending order.
						if(_enableShorting && !PositionExistsInDirection(C_PositionStatus.OPEN, C_Direction.SHORT_SIDE) && !OrderExists(C_Status.PENDING)){
							// Sell short the current symbol while assuming that a position sizing script will assign the quantity.
							int orderIndex = BrokerMarket(C_ActionType.SELL_SHORT, 0, C_TIF.DAY, "Time to sell.");
							// Set a stop loss on the order. 
							BrokerSetStopLossPercent(orderIndex, _stopLoss, true, "Stop loss");
							// Set a take profit on the order. 
							BrokerSetTakeProfitPercent(orderIndex, _takeProfit, true, "Profit target");
						}
					// Check whether the volatility index closed between the lower and upper cutoffs.
					} else if(_sortedVolatilityIndexHistory[_lowerIndexCutoff] < volatilityIndexClose && volatilityIndexClose < _sortedVolatilityIndexHistory[_upperIndexCutoff]){
						// Close any open positions.
						BrokerClosePosition("Time to close.");
					}
				}
			}
		}
#endregion

#region OnOrderFillUpdate
		/// <summary>
		/// This function is called for each new order fill.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index</param>
		/// <param name="orderIndex" type="Integer">The order index</param>
		/// <param name="orderFillIndex" type="Integer">The order fill index</param>
		public override void OnOrderFillUpdate(
			int symbolIndex,
			int orderIndex,
			int orderFillIndex) {
			// OnOrderFillUpdate Content
		}
#endregion

#region OnOrderUpdate
		/// <summary>
		/// This function is called when an order is executed or cancelled.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The underlying symbol index of the order</param>
		/// <param name="orderIndex" type="Integer">The order index</param>
		/// <param name="status" type="C_Status">The updated status of the order</param>
		public override void OnOrderUpdate(
			int symbolIndex,
			int orderIndex,
			C_Status status) {
			// OnOrderUpdate Content
		}
#endregion

#region OnPositionUpdate
		/// <summary>
		/// This function is called when a position is opened or closed. 
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The underlying symbol index of the position</param>
		/// <param name="positionIndex" type="Integer">The position index</param>
		/// <param name="status" type="C_PositionStatus">The updated status of the position</param>
		public override void OnPositionUpdate(
			int symbolIndex,
			int positionIndex,
			C_PositionStatus status) {
			// OnPositionUpdate Content
		}
#endregion

#region OnSessionUpdate
		/// <summary>
		/// This function is called when a session is opened or closed.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index whose session is updated</param>
		/// <param name="status" type="C_SessionStatus">The session status</param>
		public override void OnSessionUpdate(
			int symbolIndex,
			C_SessionStatus status) {
		}
#endregion

#region OnNewsUpdate
		/// <summary>
		/// This function is called when a news update is received and only if the NO_NEWS_UPDATES comment is removed.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index for the update</param>
		/// <param name="dateTime" type="DateTime">The date/time in which the update was received by the platform</param>
		/// <param name="title" type="String">The update title</param>
		/// <param name="message" type="String">The update message</param>   
		/// <param name="type" type="C_MessageType">The update message type</param>
		public override void OnNewsUpdate(
			int symbolIndex,
			long dateTime,
			string title,
			string message,
			C_MessageType type) {
			// OnNewsUpdate Content
			// [NO_NEWS_UPDATES] - Delete this comment to enable news updates to this strategy.
		}
#endregion

#region OnRSSUpdate
		/// <summary>
		/// This function is called when an RSS update is received and only if the NO_RSS_UPDATES comment is removed.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index for the update</param>
		/// <param name="dateTime" type="DateTime">The date/time in which the update was received by the platform</param>
		/// <param name="title" type="String">The update title</param>
		/// <param name="message" type="String">The update message</param>   
		/// <param name="type" type="C_MessageType">The update message type</param>
		public override void OnRSSUpdate(
			int symbolIndex,
			long dateTime,
			string title,
			string message,
			C_MessageType type) {
			// OnRSSUpdate Content
			// [NO_RSS_UPDATES] - Delete this comment to enable RSS updates to this strategy.
		}
#endregion

#region OnAlertUpdate
		/// <summary>
		/// This function is called when an alert update is received and only if the NO_ALERT_UPDATES comment is removed.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index for the update</param>
		/// <param name="dateTime" type="DateTime">The date/time in which the update was received by the platform</param>
		/// <param name="message" type="String">The update message</param>   
		/// <param name="type" type="C_MessageType">The update message type</param>
		public override void OnAlertUpdate(
			int symbolIndex,
			long dateTime,
			string message,
			C_MessageType type) {
			// OnAlertUpdate Content
			// [NO_ALERT_UPDATES] - Delete this comment to enable alert updates to this strategy.
		}
#endregion

#region OnJournalUpdate
		/// <summary>
		/// This function is called when a journal update is received and only if the NO_JOURNAL_UPDATES comment is removed.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index for the update</param>
		/// <param name="dateTime" type="DateTime">The date/time in which the update was received by the platform</param>
		/// <param name="title" type="String">The update title</param>
		/// <param name="message" type="String">The update message</param>   
		/// <param name="type" type="C_MessageType">The message type</param>
		public override void OnJournalUpdate(
			int symbolIndex,
			long dateTime,
			string title,
			string message,
			C_MessageType type) {
			// OnJournalUpdate Content
			// [NO_JOURNAL_UPDATES] - Delete this comment to enable journal updates to this strategy.
		}
#endregion

#region OnDataConnectionUpdate
		/// <summary>
		/// This function is called when a data connection update is received and only if the NO_DATA_CONNECTION_UPDATES comment is removed.
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index for the update</param>
		/// <param name="dateTime" type="DateTime">The date/time in which the update was received by the platform</param>
		/// <param name="message" type="String">The update message</param>   
		/// <param name="type" type="C_MessageType">The update message type</param>
		public override void OnDataConnectionUpdate(
			int symbolIndex,
			long dateTime,
			string message,
			C_MessageType type) {
			// OnDataConnectionUpdate Content
			// [NO_DATA_CONNECTION_UPDATES] - Delete this comment to enable data connection updates to this strategy.
		}
#endregion

#region OnBrokerConnectionUpdate
		/// <summary>
		/// This function is called when a broker connection update is received and only if the NO_BROKER_CONNECTION_UPDATES comment is removed.
		/// </summary>
		/// <param name="dateTime" type="DateTime">The date/time in which the update was received by the platform</param>
		/// <param name="message" type="String">The update message</param>   
		/// <param name="type" type="C_MessageType">The update message type</param>
		public override void OnBrokerConnectionUpdate(
			long dateTime,
			string message,
			C_MessageType type) {
			// OnBrokerConnectionUpdate Content
			// [NO_BROKER_CONNECTION_UPDATES] - Delete this comment to enable broker connection updates to this strategy.
		}
#endregion

#region OnShutdown
		/// <summary>
		/// This function is called when the script is shutdown.
		/// </summary>
		public override void OnShutdown() {
			// OnShutdown Content
		}
#endregion
	}
}