Saturday, September 04, 2010

Fixed Fractional (Risk) [FF]

Descripton
Summary:
This position sizing script is used to allocate a fixed percentage of the account equity on each trade.


Variables
TypeIdentifierDescription
Number_fixedFractionalUse for the percentage of the equity to risk.
Number_maxUnitLoss
Boolean_enableExitSizingUse to indicate whether to enable the Fixed Fractional (Risk) to determine the size of exit orders.

OnInitialize
Function Parameters
TypeIdentifierDescription
NumberfixedFractionalUse for the percentage of the equity to risk. [Default 2]
NumbermaxUnitLossUse for the maximum number of units (shares / contracts) valued at their current market price to risk in each trade. [Default 10000]
BooleanenableExitSizingUse to indicate whether to enable the Fixed Fractional (Risk) to determine the size of exit orders. [Default True]
Implementation
	 ' Assign the parameters to script variables.
	_fixedFractional = fixedFractional
	_maxUnitLoss = maxUnitLoss
	_enableExitSizing = enableExitSizing
	

OnPositionSize
Function Parameters
TypeIdentifierDescription
IntegerorderIndex
Implementation
	 ' Get the order type.
	Define typeOrder As Integer = OrderType(orderIndex)
	 ' Get the order symbol index.
	Define symbolIndex As Integer = OrderSymbolIndex(orderIndex)
	 ' If the order type is an entry order then calculate the position size.
	If (typeOrder = C_BUY Or _
		typeOrder = C_SELL_SHORT) Then
		 ' Get the bar close of the current bar.
		Define close As Number = BarClose(symbolIndex)
		 ' Check whether the close exists.
		If (close <> 0) Then
			 ' Calculate the number of units to trade.
			Define units As Number = MathFloor((_fixedFractional / 100 * AccountEquity()) / close)
			 ' Check whether the number of units exceeds the specified maximum.
			If (units > _maxUnitLoss) Then
				Return _maxUnitLoss
			End If
			Return units
		Else
			Return 0
		End If
	 ' If the order type is an exit order and the script should handle those.
	Else If (_enableExitSizing)
		 ' If the order type is an exit order then calculate the position size.
		Define openPositions() As Integer = PositionIndexList(C_OPEN)
		For i As Integer = 0 To openPositions.Length - 1
			If (PositionSymbolIndex(openPositions(i)) = symbolIndex) Then
				Return PositionQuantity(openPositions(i))
			End If
		Next
	End If
	Return 0

Copyright © 2010 IQBroker, LLC. All rights reserved.