Summary: This position sizing script risks a specified fraction of the account equity on each trade, it does so by using a percentage of the starting account equity plus a percentage of the total closed trade profit.
' Assign the parameters to script variables. _accountFraction = accountFraction _profitsFraction = profitsFraction _defaultRiskPerTrade = defaultRiskPerTrade _enableExitSizing = enableExitSizing
' 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 StatsRequest(DateTimeStart(), DateTimeCurrent(),True,True,True,True, True) ' Calculate the total amount of equity to risk on a single trade. Define totalRisk As Number = StatsStartingEquity() * _accountFraction + StatsNetProfit () * _profitsFraction ' Assign the default minimum risk per trade. Define riskPerTrade As Number = -1 * _defaultRiskPerTrade ' Get the closed trades indexes. Define closedTrades() As Integer = TradeIndexList(C_CLOSED) ' Use for the P/L of the current trade. Define profitLoss As Number ' 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)) ' Keep track of the largest loss. If (profitLoss < riskPerTrade) Then riskPerTrade = profitLoss End If Next Return MathFloor(totalRisk / MathAbs(riskPerTrade)) 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