Double Death Cross

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

namespace ScriptCode {
	/// <summary>
	/// This is a multiple-entry reversal strategy that uses exponentially weighted moving average (EMA) indicators to determine when to buy and sell short as well as where to place profit target and stop loss orders. 
	/// 
	/// Normally, a Death Cross occurs when a shorter term moving average (usually 50 day) crosses below a longer term moving average (usually 200 day) and signals a reversal in trend. 
	/// Similar to this idea, the strategy takes its first short entry when the short-term EMA crosses below the medium-term EMA and price converges with both EMAs. 
	/// In order for price to converge with both EMAs, they must have been between the High and Low prices at some point over the specified period. 
	/// The second short entry is taken when price trades below the long-term EMA. For long trades, the first entry is taken when the short-term EMA crosses above the medium-term EMA and price converges with both EMAs.
	/// The second long entry is taken when price trades above the long-term EMA.
	/// 
	/// As the strategy takes the first entry, it generates a stop loss order one tick above the medium-term EMA for short trades or one tick below the medium-term EMA for long trades. 
	/// A profit target order is generated for short trades once the short-term EMA crosses below the long-term EMA and is placed one tick above the High of the bar where the crossover occurred.
	/// For long trades, a profit target order is generated when the short-term EMA crosses above the long-term EMA and is placed one tick below the Low of the bar where the crossover occurred.
	/// 
	/// Trading Rules: 
	/// 
	/// Long Entry 1: A buy market order is generated when the short-term EMA crosses above the medium-term EMA and price converges with both EMAs.
	/// Long Entry 2: A buy market order is generated when the symbol trades above the long-term EMA.
	/// Long Exit: A long position is exited when a stop loss or profit target is reached.
	/// 
	/// Short Entry 1: A sell short market order is generated when the short-term EMA crosses below the medium-term EMA and price converges with both EMAs.
	/// Short Entry 2: A sell short market order is generated when the symbol trades below the long-term EMA.
	/// Short Exit: A short position is exited when a stop loss or profit target is reached.
	/// </summary>
	public partial class MyTradingStrategy : TradingStrategyScriptBase  // NEVER CHANGE THE CLASS NAME 
	{
#region Variables
		// The short-term indicator with which trading signals will be generated.
		private Indicator _indicatorShort;
		// The medium-term indicator with which trading signals will be generated.
		private Indicator _indicatorMedium;
		// The long-term indicator with which trading signals will be generated.
		private Indicator _indicatorLong;
		// 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;
		// Indicates whether to enable Entry 2.
		private bool _enableEntry2;
		// Indicates whether the Entry 2 entry order has been fired.
		private bool _entry2Fired;
		// Pattern object indicating whether the Bearish Double Death Cross pattern holds true.
		private Pattern _bearishDDCPattern;
		// Pattern object indicating whether the Bullish Double Death Cross pattern holds true.
		private Pattern _bullishDDCPattern;
#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="indicatorShortPeriods" type="Integer" default="50">The number of periods in the short-term indicator.</param>
		/// <param name="indicatorMediumPeriods" type="Integer" default="100">The number of periods in the medium-term indicator.</param>
		/// <param name="indicatorLongPeriods" type="Integer" default="200">The number of periods in the long-term indicator.</param>
		/// <param name="priceActionConvergencePeriods" type="Integer" default="3" min="0">The number of periods used to determine if the price action has converged with the moving averages.</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="enableEntry2" type="Boolean" default="True">Indicates whether to enable Entry 2. Entry 2 occurs when the underlying symbol closes above the long-term indicator
		/// for long trades and closes below the long-term indicator for short trades.</param>
		public void OnInitialize(
			int indicatorShortPeriods,
			int indicatorMediumPeriods,
			int indicatorLongPeriods,
			int priceActionConvergencePeriods,
			bool enableShorting,
			bool enableLonging,
			bool enableEntry2) {
			// Set the script parameters to script variables. 
			_enableShorting = enableShorting;
			_enableLonging = enableLonging;
			_enableEntry2 = enableEntry2;
				
			// Remove all of the indicators from the chart so that we don't get duplicates.
			ChartIndicatorRemoveAll(SymbolIndex());
			// Create the short-term EMA indicator over the bar close indicator of the underlying symbol.
			_indicatorShort = IndicatorEMA(IndicatorCLOSE(SymbolIndex()), indicatorShortPeriods);
			// Plot the indicator on the underlying symbol's chart.
			int indicatorShortItemID = ChartIndicatorPlot(SymbolIndex(), _indicatorShort, "", - 1, 1);
			// Set the indicator pen.
			ChartIndicatorSetPenByIndex(SymbolIndex(), indicatorShortItemID, 0, C_Color.LAWN_GREEN, C_DashStyle.SOLID, 2);
			// Set the indicator style.
			ChartIndicatorSetPlotStyle(SymbolIndex(), indicatorShortItemID, C_PlotStyle.LINE);
			// Create the medium-term EMA indicator over the bar close indicator of the underlying symbol.
			_indicatorMedium = IndicatorEMA(IndicatorCLOSE(SymbolIndex()), indicatorMediumPeriods);
			// Plot the indicator on the underlying symbol's chart.
			int indicatorMediumItemID = ChartIndicatorPlot(SymbolIndex(), _indicatorMedium, "", - 1, 1);
			// Set the indicator pen.
			ChartIndicatorSetPenByIndex(SymbolIndex(), indicatorMediumItemID, 0, C_Color.ORANGE, C_DashStyle.SOLID, 2);
			// Set the indicator style.
			ChartIndicatorSetPlotStyle(SymbolIndex(), indicatorMediumItemID, C_PlotStyle.LINE);
			// Create the long-term EMA indicator over the bar close indicator of the underlying symbol.
			_indicatorLong = IndicatorEMA(IndicatorCLOSE(SymbolIndex()), indicatorLongPeriods);
			// Plot the indicator on the underlying symbol's chart.
			int indicatorLongItemID = ChartIndicatorPlot(SymbolIndex(), _indicatorLong, "", - 1, 1);
			// Set the indicator pen.
			ChartIndicatorSetPenByIndex(SymbolIndex(), indicatorLongItemID, 0, C_Color.BLUE_VIOLET, C_DashStyle.SOLID, 2);
			// Set the indicator style.
			ChartIndicatorSetPlotStyle(SymbolIndex(), indicatorLongItemID, C_PlotStyle.LINE);

			// Check whether it is necessary to create and graph the Bearish Double Death Cross pattern.
			if(_enableShorting){
				// Create the Bearish Double Death Cross pattern for the underlying symbol.
				_bearishDDCPattern = PatternDDDC(SymbolIndex(), indicatorShortPeriods, indicatorMediumPeriods, indicatorLongPeriods, priceActionConvergencePeriods);
				// Plot the pattern on the underlying symbol's chart to highlight instances of the pattern.
				ChartPatternPlot(SymbolIndex(), _bearishDDCPattern, "Bearish Double Death Cross", -1, 1);
			}
			// Check whether it is necessary to create and graph the Bullish Double Death Cross pattern.
			if(_enableLonging){
				// Create the Bullish Double Death Cross pattern for the underlying symbol.
				_bullishDDCPattern = PatternUDDC(SymbolIndex(), indicatorShortPeriods, indicatorMediumPeriods, indicatorLongPeriods, priceActionConvergencePeriods);
				// Plot the pattern on the underlying symbol's chart to highlight instances of the pattern.
				ChartPatternPlot(SymbolIndex(), _bullishDDCPattern, "Bullish Double Death Cross", -1, 1);
			}
		}
#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. (See the DataSeriesSwitch function).</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>
		public override void OnBarUpdate(
			int symbolIndex,
			int dataSeries,
			int completedBars) {
			// Check whether the strategy is allowed to short, the Bearish Double Death Cross holds true, and there are no open positions and pending orders.
			if (_enableShorting && _bearishDDCPattern[0] != 0 && !PositionExists(C_PositionStatus.OPEN) && !OrderExists(C_Status.PENDING)) {
				// Generate a sell market order for Entry 1 while assuming that a position sizing script will assign the quantity.
				BrokerMarket(C_ActionType.SELL_SHORT, 0, C_TIF.GTC, "Entry 1");
				// Generate a stop loss order one tick above the medium-term indicator while assuming that a position sizing script will assign the quantity.
				BrokerStop(C_ActionType.BUY_TO_COVER, 0, C_TIF.GTC, _indicatorMedium[0] + SymbolTickSize(), "Stop loss");
			}

			// Check whether the strategy is allowed to long, the Bullish Double Death Cross holds true, and there are no open positions and pending orders.
			if (_enableLonging && _bullishDDCPattern[0] != 0 && !PositionExists(C_PositionStatus.OPEN) && !OrderExists(C_Status.PENDING)) {
				// Generate a buy market order for Entry 1 while assuming that a position sizing script will assign the quantity.
				BrokerMarket(C_ActionType.BUY, 0, C_TIF.GTC, "Entry 1");
				// Generate a stop loss order one tick below the medium-term indicator while assuming that a position sizing script will assign the quantity.
				BrokerStop(C_ActionType.SELL, 0, C_TIF.GTC, _indicatorMedium[0] - SymbolTickSize(), "Stop loss");
			}

			// Check whether a position exists in the underlying symbol.
			if (PositionExists(C_PositionStatus.OPEN)) {

				// Create variable to hold whether the pending profit target order exists.
				bool profitTargetOrderExists = false;
				// Create an array to hold all pending orders for the underlying symbol.
				int[] pendingOrders = OrderByStatus(C_Status.PENDING);
				// Iterate through all pending orders for the underlying symbol.
				foreach (int pendingOrder in pendingOrders) {
					// Check whether the current order type is the same as that of a profit target order.
					if (OrderPriceType(pendingOrder) == C_OrderType.LIMIT) {
						// Record the existence of pending profit target order and exit the iteration.
						profitTargetOrderExists = true;
						break;
					}
				}
				
				// Check whether there is currently a pending profit target order.
				if (!profitTargetOrderExists) {
					// Check whether the short-term indicator crosses below the long-term indicator.
					if (_indicatorShort[0] < _indicatorLong[0] && _indicatorShort[1] >= _indicatorLong[1]) {
						// Generate profit target order one tick above the high of the current bar while assuming that a position sizing script will assign the quantity.
						BrokerLimit(C_ActionType.BUY_TO_COVER, 0, C_TIF.GTC, DataHigh() + SymbolTickSize(), "Profit target");
					// Check whether the short-term indicator crosses above the long-term indicator.
					} else if (_indicatorShort[0] > _indicatorLong[0] && _indicatorShort[1] <= _indicatorLong[1]) {
						// Generate profit target order one tick below the low of the current bar while assuming that a position sizing script will assign the quantity.
						BrokerLimit(C_ActionType.SELL, 0, C_TIF.GTC, DataLow() - SymbolTickSize(), "Profit target");
					}
				}
				
				// Check whether Entry 2 has been enabled and it has not already been generated.
				if (_enableEntry2 && !_entry2Fired) {
					// Check whether the underlying symbol closes below the long-term indicator and a short position already exists.
					if (DataClose() < _indicatorLong[0] && PositionExistsInDirection(C_PositionStatus.OPEN, C_Direction.SHORT_SIDE)) {
						// Generate a sell market order for Entry 2 while assuming that a position sizing script will assign the quantity.
						BrokerMarket(C_ActionType.SELL_SHORT, 0, C_TIF.GTC, "Entry 2");
						// Record that the Entry 2 entry order has been fired.
						_entry2Fired = true;
					}
					// Check whether the underlying symbol closes above the long-term indicator and a long position already exists.
					if (DataClose() > _indicatorLong[0] && PositionExistsInDirection(C_PositionStatus.OPEN, C_Direction.LONG_SIDE)) {
						// Generate a buy market order for Entry 2 while assuming that a position sizing script will assign the quantity.
						BrokerMarket(C_ActionType.BUY, 0, C_TIF.GTC, "Entry 2");
						// Record that the Entry 2 entry order has been fired.
						_entry2Fired = true;
					}
				}
			}
		}
#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 symbol index</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) {
			// Check whether the order is executed.
			if (status == C_Status.EXECUTED) {
				// Check whether the order is an exit order.
				if (OrderActionType(orderIndex) == C_ActionType.SELL || OrderActionType(orderIndex) == C_ActionType.BUY_TO_COVER) {
					// Create an array to hold all pending orders for the underlying symbol.
					int[] pendingOrders = OrderByStatus(C_Status.PENDING);
					// Cancel each pending order for the underlying symbol.
					foreach (int pendingOrder in pendingOrders)
							BrokerCancelOrder(pendingOrder, OrderComment(pendingOrder) + " - No longer needed");
					// Reset variable that holds whether the Entry 2 entry order has been fired back to false.
					_entry2Fired = false;
				} else {
					// Check whether the order is an Entry 2 entry order.
					if (OrderComment(orderIndex).Contains("Entry 2")) {
						// Create an array to hold all pending orders for the underlying symbol.
						int[] pendingOrders = OrderByStatus(C_Status.PENDING);
						// Update pending stop loss and profit target orders with share quantity of Entry 2 entry order.
						foreach (int pendingOrder in pendingOrders)
							if (OrderPriceType(pendingOrder) == C_OrderType.LIMIT || OrderPriceType(pendingOrder) == C_OrderType.STOP)
								BrokerModifyOrder(pendingOrder, OrderQuantityRemaining(pendingOrder) + OrderQuantityFilled(orderIndex), -1, -1);
					}
				}
			}
		}
#endregion

#region OnPositionUpdate
		/// <summary>
		/// This function is called when a position is opened or closed. 
		/// </summary>
		/// <param name="symbolIndex" type="Integer">The symbol index</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 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 update 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
	}
}