Tuesday, September 07, 2010

Kelly Formula [KF]

Descripton
Summary:
This position sizing script risks a specified fraction of the account equity on each trade, it does so by using an approximate formula to determine the fixed fractional that maximizes the equity growth rate.


Variables
TypeIdentifierDescription
Number_defaultRiskRatioUse for the percentage of the account to be risked on each trade.
Number_defaultTradeRiskUse for the default maximum amount of equity to risk on a single share / contract / unit, before one is calculated by the formula.
Boolean_enableExitSizingUse to indicate whether to enable the Kelly Formula to determine the size of exit orders.
Integer_minimumTradesUse for the minimum number of trades to use for calculating the formula instead of using the default values.

OnInitialize
Function Parameters
TypeIdentifierDescription
IntegerdefaultRiskRatioUse for the percentage of the account to be risked on each trade. [Default 15]
IntegerdefaultTradeRiskUse for the default maximum amount of equity to risk on a single share / contract / unit, before one is calculated by the formula. [Default 100]
IntegerminimumTradesUse for the minimum number of trades to use for calculating the formula instead of using the default values. [Default 50]
BooleanenableExitSizingUse to indicate whether to enable the Kelly Formula to determine the size of exit orders. [Default True]
Implementation
	 ' Assign the parameters to script variables.
	_defaultTradeRisk = defaultTradeRisk
	_defaultRiskRatio = defaultRiskRatio
	_minimumTrades = minimumTrades
	_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
		Define kelly As Number
		 ' Use for the ratio between the average winning trade and the average losing trad.
		Define averageRatio As Number
		 ' Use for the average winning trade amount.
		Define averageWinningTrade As Number
		 ' Use for counting the winning trades.
		Define winningTrades As Integer
		 ' Use for the average losing trade amount.
		Define averageLosingTrade As Number
		 ' Use for counting the losing trades.
		Define losingTrades As Integer
		 ' Use for the probability of winning a trade.
		Define probabilityOfWinningTrade As Number
		 ' Use for the maximum trade loss, which defines the trade risk.
		Define tradeRisk As Number
		 ' Use for the P/L of the current trade.
		Define profitLoss As Number
		 ' Get the closed trades indexes.
		Define closedTrades() As Integer = TradeIndexList(C_CLOSED)
		 ' Iterate over all of the closed trades.
		For i As Integer = 0 To closedTrades.Length - 1
			 ' Get the P/L of the current closed trade.
			profitLoss = TradeProfitLoss(closedTrades(i))
			 ' Count the winning and losing trades, and sum their values.
			If (profitLoss > 0) Then
				winningTrades += 1
				averageWinningTrade += profitLoss
			Else
				losingTrades += 1
				averageLosingTrade += MathAbs(profitLoss)
				 ' Keep track of the largest loss.
				If (profitLoss < tradeRisk) Then
					tradeRisk = profitLoss
				End If
			End If
		Next
		 ' Calculate the kelly f value using historical information.
		If (winningTrades + losingTrades  > _minimumTrades) Then
			averageWinningTrade = averageWinningTrade / winningTrades
			averageLosingTrade = averageLosingTrade / losingTrades
			probabilityOfWinningTrade = winningTrades / (winningTrades + losingTrades)
			averageRatio = averageWinningTrade / averageLosingTrade
			kelly = ((averageRatio + 1) * probabilityOfWinningTrade - 1) / averageRatio
			OutputWriteLine(averageWinningTrade & " " & averageLosingTrade & " " & probabilityOfWinningTrade & " " & averageRatio & " " & kelly)
		Else
		 ' Assign the kelly f value from the user specified default value.
			kelly = _defaultRiskRatio / 100
			tradeRisk = -1 * _defaultTradeRisk		
		End If
		Return MathFloor((kelly * AccountEquity()) / MathAbs(tradeRisk))
	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

Copyright © 2010 IQBroker, LLC. All rights reserved.