Page 1 of 1

Pine Script: How to get net profit (deducting commission) using strategy.closedtrades.profit()

Posted: Mon Sep 28, 2026 7:48 am
by PTScalper
The official TradingView documentation for strategy.closedtrades.profit() leaves out a critical detail for accurate backtesting: it returns the gross profit of the trade, completely ignoring the commission costs you defined in your strategy settings.

If you are building custom performance dashboards or logging trade-by-trade metrics, relying only on closedtrades.profit() will artificially inflate your win rate and expectancy. To get the actual net profit, you have to manually pull the commission for that specific trade index and subtract it.

The Logic & Parameters

The strategy.closedtrades namespace tracks all historical trades. By targeting the most recently closed trade (strategy.closedtrades - 1), we can extract both the gross profit and the exact commission paid for that specific execution using the often-overlooked strategy.closedtrades.commission() function.

Re: Pine Script: How to get net profit (deducting commission) using strategy.closedtrades.profit()

Posted: Mon Sep 28, 2026 7:48 am
by PTScalper
The Code Solution

Here is the exact snippet to correctly calculate the net profit on your last closed position. You can drop this directly into your existing v5 scripts:

Code: Select all

//@version=5
strategy("Commission Net Profit Example", overlay=true, commission_type=strategy.commission.cash_per_order, commission_value=3.00)

// [Your strategy entry and exit conditions here]

// Calculate Net Profit on the most recently closed trade
if strategy.closedtrades > 0
    // 1. Get the index of the last closed trade (zero-based array)
    last_trade_index = strategy.closedtrades - 1
    
    // 2. Extract gross profit and commission
    gross_pnl = strategy.closedtrades.profit(last_trade_index)
    paid_commission = strategy.closedtrades.commission(last_trade_index)
    
    // 3. Calculate true Net Profit
    net_pnl = gross_pnl - paid_commission
    
    // 4. (Optional) Log the data to verify against the built-in Strategy Tester
    if barstate.islast
        log.info("Trade #{0} | Gross: {1} | Comm: {2} | Net: {3}", last_trade_index, gross_pnl, paid_commission, net_pnl)

Re: Pine Script: How to get net profit (deducting commission) using strategy.closedtrades.profit()

Posted: Mon Sep 28, 2026 7:49 am
by PTScalper
Why this matters for your backtest

Make sure your commission_type (e.g., strategy.commission.percent vs strategy.commission.cash_per_order) accurately reflects your broker's fee structure. If you are scalping on lower timeframes, the paid_commission variable will often flip a marginally winning gross_pnl into a negative net_pnl.

Re: Pine Script: How to get net profit (deducting commission) using strategy.closedtrades.profit()

Posted: Mon Sep 28, 2026 7:51 am
by PTScalper
Plus for you, which need more pro solution, here you have another three options:

Here is how to extract the exact commission paid per trade and three solutions ranging from a basic fix to a pro-level dynamic tracker.

Solution 1: The Basic Trade-by-Trade Calculation

To get the true net profit of the most recently closed position, you must manually pair the gross profit with the strategy.closedtrades.commission() function using the same trade index.

Code: Select all

//@version=5
strategy("Net Profit - Basic", overlay=true, commission_type=strategy.commission.cash_per_order, commission_value=3.00)

// [Your entry and exit logic]

if strategy.closedtrades > 0 and strategy.closedtrades > nz(strategy.closedtrades[1])
    // Target the most recent trade index (zero-based array)
    last_trade_index = strategy.closedtrades - 1
    
    // Extract both values
    gross_pnl = strategy.closedtrades.profit(last_trade_index)
    paid_comm = strategy.closedtrades.commission(last_trade_index)
    
    // Calculate True Net
    net_pnl = gross_pnl - paid_comm

Re: Pine Script: How to get net profit (deducting commission) using strategy.closedtrades.profit()

Posted: Mon Sep 28, 2026 7:51 am
by PTScalper
Pro Solution 1: Handling Multiple Exits on a Single Bar (Pyramiding/Partial TPs)

The basic solution above breaks if your strategy closes multiple trades on the exact same candle (e.g., hitting TP1 and TP2 simultaneously). If you only check strategy.closedtrades - 1, you will completely miss the other trades that closed on that bar.

The professional approach is to calculate the difference in closed trades between the current and previous bar, and loop through all of them.

Code: Select all

//@version=5
strategy("Net Profit - Pro Loop", overlay=true, pyramiding=3, commission_type=strategy.commission.percent, commission_value=0.005)

var float custom_total_net = 0.0

// [Your entry and exit logic]

// Calculate how many trades closed on this specific bar
trades_closed_diff = strategy.closedtrades - nz(strategy.closedtrades[1])

if trades_closed_diff > 0
    // Loop through every trade that just closed
    for i = 0 to trades_closed_diff - 1
        // Step backward through the index to catch them all
        trade_idx = strategy.closedtrades - 1 - i
        
        gross_pnl = strategy.closedtrades.profit(trade_idx)
        paid_comm = strategy.closedtrades.commission(trade_idx)
        
        net_pnl = gross_pnl - paid_comm
        custom_total_net += net_pnl // Aggregate your true net equity

Re: Pine Script: How to get net profit (deducting commission) using strategy.closedtrades.profit()

Posted: Mon Sep 28, 2026 7:52 am
by PTScalper
Pro Solution 2: The "Commission Drag" Visual Dashboard

When developing a scalping algorithm, you need to see exactly how much of your gross profit is being destroyed by broker fees in real-time.

Here is a Pine Script snippet that builds a UI table in the corner of your chart, comparing your Gross PnL against your Net PnL and calculating the total "Commission Drag" percentage.

(Note: We use input.string() with position.top_right so you can easily move the dashboard around in your script settings without touching the code).

Code: Select all

//@version=5
strategy("Commission Drag Dashboard", overlay=true, commission_type=strategy.commission.cash_per_order, commission_value=2.50)

// User input for table location
table_pos_input = input.string(position.top_right, title="Dashboard Position", options=[position.top_right, position.top_left, position.bottom_right])

// Aggregate variables
var float total_gross = 0.0
var float total_comm = 0.0

trades_closed_diff = strategy.closedtrades - nz(strategy.closedtrades[1])
if trades_closed_diff > 0
    for i = 0 to trades_closed_diff - 1
        trade_idx = strategy.closedtrades - 1 - i
        total_gross += strategy.closedtrades.profit(trade_idx)
        total_comm  += strategy.closedtrades.commission(trade_idx)

// Initialize the dashboard table
var table perfTable = table.new(table_pos_input, 2, 4, border_width = 1, border_color=color.gray, frame_color=color.black, frame_width=1)

// Update the table on the last historical bar or in real-time
if barstate.islast
    total_net = total_gross - total_comm
    comm_drag_pct = total_gross > 0 ? (total_comm / total_gross) * 100 : 0.0
    
    // Headers
    table.cell(perfTable, 0, 0, "Metric", text_color=color.white, bgcolor=color.blue)
    table.cell(perfTable, 1, 0, "Value", text_color=color.white, bgcolor=color.blue)
    
    // Data Rows
    table.cell(perfTable, 0, 1, "Gross Profit", text_color=color.white, bgcolor=color.black)
    table.cell(perfTable, 1, 1, str.tostring(total_gross, "#.##"), text_color=color.green, bgcolor=color.black)
    
    table.cell(perfTable, 0, 2, "Net Profit", text_color=color.white, bgcolor=color.black)
    table.cell(perfTable, 1, 2, str.tostring(total_net, "#.##"), text_color=total_net > 0 ? color.green : color.red, bgcolor=color.black)
    
    table.cell(perfTable, 0, 3, "Commission Drag", text_color=color.white, bgcolor=color.black)
    table.cell(perfTable, 1, 3, str.tostring(comm_drag_pct, "#.##") + "%", text_color=color.red, bgcolor=color.black)

Re: Pine Script: How to get net profit (deducting commission) using strategy.closedtrades.profit()

Posted: Mon Sep 28, 2026 7:52 am
by PTScalper
Key Takeaway for Scalpers:

Always test your lower-timeframe strategies with your broker's exact commission structure built into the strategy() declaration. If your "Commission Drag" in the dashboard above exceeds 30-40% of your Gross Profit, your strategy is hyper-sensitive to slippage and will likely fail in live conditions, regardless of what the gross equity curve looks like.