Equally Balance Cash Monthly

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

namespace ScriptCode
{
    /// <summary>
    /// Dynamic allocation scripts are used for systematically redistributing cash between desktop strategies
    /// based on their performance or some other heuristic.
    /// </summary>
    public partial class MyDynamicAllocation : DynamicAllocationScriptBase // NEVER CHANGE THE CLASS NAME 
    {
        #region Variables
        // The day of month in which the cash rebalancing is done. (1 to 31)
		private int _day;
		// The base currency code to use for transferring cash between strategies.
		private string _currencyCode;
        #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[]'

        /// 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="day" type="Integer" default="1"> The day of month in which the cash rebalancing is done. (1 to 31)</param>		
		/// <param name="currencyCode" type="String" default="USD">The base currency code to use for transferring cash between strategies.</param>        
		public void OnInitialize(
			int day,
			string currencyCode)
        {
		    // Set the script parameters 
			_day = day;
			_currencyCode = currencyCode;
        }
        #endregion

        #region OnDynamicAllocation
        /// <summary>
        /// This function is called daily at the desktop EOD time, 
        /// at which point it may redistribute cash between desktop strategies (see the StrategyTransfer function).
        /// </summary>
        public override void OnDynamicAllocation()
        {
		    // Check whether this is not the day for rebalancing.
			if (DateTimeDay(DateTimeCurrent()) != _day)
				return ;

			// Use for counting the number of active strategies.
			int activeStrategies = 0;
			// The average strategy balance in the specified currency code.
			double averageStrategyBalance = 0;
			// Use for holding the strategies free cash in the specified currency code indexed by strategy number. 
			double[] strategiesCash = new double[StrategyCount()];
			// Calculate the free cash of each strategy.
			for (int i = 0; i < StrategyCount(); i++) {
				// Check whether the strategy is active.
				if (StrategyIsActive(i)) {
					// Advance the number of active strategies.
					activeStrategies++;
					// Set the cash of the current strategy in the specified currency code.
					strategiesCash[i] = StrategyGetExchangeRate(StrategyCurrencyCode(i), _currencyCode) * StrategyCash(i);
					// Add the cash of the current strategy to the balance.
					averageStrategyBalance += strategiesCash[i];
				}
			}
			// Check whether at least one active strategy exists.
			if (activeStrategies > 0)
				// Calculate the average strategy balance. 
				averageStrategyBalance = averageStrategyBalance / activeStrategies;

			double fromCredit = 0;
			double toDebit = 0;
			double debitAmount = 0;
			// Iterate over all of the strategies while moving cash from one strategy to the other in order to even them out. 
			for (int i = 0; i < StrategyCount(); i++) {
				// Check whether the strategy is active and it has more cash than the average.
				if (StrategyIsActive(i) && strategiesCash[i] > averageStrategyBalance) {
					// Calculate the extra cash that can be redistributed. 
					fromCredit = strategiesCash[i] - averageStrategyBalance;
					// Iterate over all the strategies while searching for strategies that have less cash than the average strategy. 
					for (int j = 0; j < StrategyCount(); j++) {
						// Check whether the strategy is active, there is more credit to be redistributed and the current strategy has less cash than the average strategy.
						if (StrategyIsActive(j) && fromCredit > 0 && strategiesCash[j] < averageStrategyBalance) {
							// Calculate the cash required by the other strategy. 
							toDebit = averageStrategyBalance - strategiesCash[j];
							// Calculate the cash that will be transfered in the specified amount.
							debitAmount = Math.Min(fromCredit, toDebit);
							// Transfer the cash between the strategies. 
							StrategyTransferCash(i, j, StrategyGetExchangeRate(_currencyCode, StrategyCurrencyCode(i)) * debitAmount, "Strategy balance");
							// Reduce the amount left to distribute. 
							fromCredit -= debitAmount;
							// Reduce the strategy cash from the source strategy. 
							strategiesCash[i] -= debitAmount;
							// Increase the strategy cash of the destination strategy. 
							strategiesCash[j] += debitAmount;
						}
					}
				}
			}
        }
        #endregion

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