Paired Switching

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

namespace ScriptCode {
	/// <summary>
	/// This is a long-only rotational strategy that switches between holding one of two negatively correlated symbols based on their relative performance. 
	/// The rationale behind this strategy is that by switching between the two symbols, it is possible to generate a better return profile than by using static weights. 
	/// The strategy compares the return of each symbol over the specified period and invests in the symbol with the higher return. The strategy rebalances after the specified holding period.
	/// 
	/// Paired switching was studied by Akhilesh Maewal and Joel R. Bock in the paper titled, “Paired-Switching for Tactical Portfolio Allocation.”
	/// 
	/// Trading Rules:
	/// 
	/// Long Entry: A buy market order is generated when the return of the symbol over the specified period is the higher of the two symbols.
	/// Long Exit: A sell market order is generated when the position has been held for the specified number of bars and the symbol no longer has the higher return.
	/// </summary>
	public partial class MyMultiSymbolTradingStrategy : MultiSymbolTradingStrategyScriptBase  // NEVER CHANGE THE CLASS NAME 
	{
#region Variables
		// Use for holding return indicators indexed by symbol index.
		private Indicator [] _ROC;
		// The number of periods used to calculate return.
		private int _returnPeriods;
		// The number of bars to hold the selected symbols.
		private int _holdBars;
		// Use for counting the number of bars the current open positions have been held.
		private int _heldBars;
		// 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;
		// Use for holding whether enough symbols were supplied.
		private bool _minimumSymbolsSupplied;
		// Indicates whether the strategy is waiting for an open position to close.
		private bool [] _waitingToClose;
#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="returnPeriods" type="Integer" default="24" min="1" max="10000000">The number of periods used to calculate return.</param>
		/// <param name="holdBars" type="Integer" default="1" min="1" max="10000000">The number of bars to hold the selected 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(
			int returnPeriods,
			int holdBars,
			double stopLoss,
			double takeProfit) {
			// Set the script parameters to script variables.
			_returnPeriods = returnPeriods;
			_holdBars = holdBars;
			_stopLoss = stopLoss;
			_takeProfit = takeProfit;
			// Create an array large enough to hold a single indicator for each symbol.
			_ROC = new Indicator[SymbolCount()];
			// Iterate over all of the symbol indexes.
			for (int symbolIndex = 0; symbolIndex < SymbolCount(); symbolIndex++) {
				// Create a copy for the current symbol index.
				_ROC[symbolIndex] = IndicatorROC(IndicatorCLOSE(symbolIndex), returnPeriods);
			}
			// Record whether enough symbols have been supplied.
			_minimumSymbolsSupplied = SymbolCount() >= 2;
			// Create for holding whether the strategy is waiting for an open position to close.
			_waitingToClose = new bool[SymbolCount()];
		}
#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) {
			// Check whether all of the symbols have been updated and enough symbols have been supplied.
			if(isLastSymbol && _minimumSymbolsSupplied){
				// Switch the API functions to work with the current symbol.
				SymbolSwitch(symbolIndex);
				// Check whether an open position exists and whether the bar is complete.
				if(PositionCountByStatusAll(C_PositionStatus.OPEN) > 0 && DataIsComplete()){
					// Increase the number of held bars.
					_heldBars++;
				}
				// Check whether there are no open positions or whether the number of held bars matches the specified number of hold bars.
				if (PositionCountByStatusAll(C_PositionStatus.OPEN) == 0 || _heldBars == _holdBars) {
					// Switch the API functions to work with the first symbol.
					SymbolSwitch(0);
					// Record the earlier close that is used to calculate the return.
					double firstSymbolClose = DataClose(_returnPeriods);
					// Switch the API functions to work with the second symbol.
					SymbolSwitch(1);
					// Record the earlier close that is used to calculate the return.
					double secondSymbolClose = DataClose(_returnPeriods);
					// Check whether both symbols have closes from which returns can be calculated.
					if(firstSymbolClose != 0 && secondSymbolClose != 0){
						// Check whether the first symbol outperforms the second.
						if(_ROC[0][0] > _ROC[1][0]){
							// Switch the API functions to work with the first symbol.
							SymbolSwitch(0);
							// Check to ensure there is not an open position or pending order.
							if(!PositionExists(C_PositionStatus.OPEN) && !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");
							}
							// Switch the API functions to work with the second symbol.
							SymbolSwitch(1);
							// Check whether the strategy is not waiting for a position to be closed and there is currently an open position.
							if(!_waitingToClose[1] && PositionExists(C_PositionStatus.OPEN)){
								// Close any open position.
								BrokerClosePosition("Time to close");
								// Record that the strategy is waiting for the position to be closed.
								_waitingToClose[1] = true;
							}
						// Check whether the second symbol outperforms the first.
						} else if(_ROC[0][0] < _ROC[1][0]){
							// Switch the API functions to work with the second symbol.
							SymbolSwitch(1);
							// Check to ensure there is not an open position or pending order.
							if(!PositionExists(C_PositionStatus.OPEN) && !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");
							}
							// Switch the API functions to work with the first symbol.
							SymbolSwitch(0);
							// Check whether the strategy is not waiting for a position to be closed and there is currently an open position.
							if(!_waitingToClose[0] && PositionExists(C_PositionStatus.OPEN)){
								// Close any open position.
								BrokerClosePosition("Time to close");
								// Record that the strategy is waiting for the position to be closed.
								_waitingToClose[0] = true;
							}
						}
					}
					// Clear the number of held bars.
					_heldBars = 0;
				}
			}
		}
#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) {
			// Switch the API functions to work with the current symbol.
			SymbolSwitch(symbolIndex);
			// Check whether the position just closed.
			if(status == C_PositionStatus.CLOSED){
				// Record that the strategy is no longer waiting for the position to be closed.
				_waitingToClose[symbolIndex] = false;
			}
		}
#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
	}
}