How to Get Balance in TradingView Pine Script?

Tracking your balance within TradingView’s Pine Script environment is essential for developing and backtesting trading strategies. While Pine Script doesn’t directly expose a real-time account balance, you can simulate it to evaluate the performance of your strategies.

Why Balance Tracking is Tricky in Pine Script

Pine Script primarily focuses on strategy execution and indicator calculations based on historical or real-time market data. It isn’t designed to interface directly with brokerage accounts or to receive real-time balance updates.

Limitations of Native Balance Information

Pine Script offers built-in variables like strategy.netprofit and strategy.equity, but these are simulated values based on the strategy’s trades, not your actual account balance. These values reset when the strategy is removed from the chart, losing the historical context of your balance. So, we can say that those properties are not designed to track the account balance as in real trading.

Alternative Approaches to Simulating Balance

The main technique involves initializing a balance variable, updating it with each trade’s profit or loss, and plotting the balance over time to visualize the strategy’s performance. This is the best available approach for backtesting.

Simulating a Trading Balance: Strategy Properties and Initial Capital

Setting Initial Capital in Strategy Settings

When creating a strategy, you can specify an initial capital amount in the strategy settings panel. This represents the starting balance for your backtesting simulations.

Understanding strategy.initial_capital

The strategy.initial_capital variable reflects the initial capital defined in the strategy settings. You can use this value to initialize your simulated balance.

Using strategy.netprofit to Calculate Simulated Balance

strategy.netprofit returns the total net profit of all closed trades. While useful, it doesn’t give you a dynamic balance reflecting ongoing trades.

Here’s an example:

//@version=5
strategy("Balance Simulation", overlay=true, initial_capital=10000)

// Initial balance
balance = strategy.initial_capital + strategy.netprofit

plot(balance, title="Simulated Balance")

This simple script calculates the balance after all trades and plots it. It will update after the last trade is closed.

Calculating Dynamic Balance Using Order Results

Tracking Trades with strategy.opentrades and strategy.closetrades

  • strategy.opentrades gives the number of currently open trades.
  • strategy.closetrades gives the number of closed trades.

Calculating Profit/Loss per Trade

To dynamically update the balance, you need to track each trade’s profit or loss individually.

Dynamically Updating the Simulated Balance

The approach involves maintaining a variable representing the current balance and updating it whenever a trade is closed.

Here’s a more complete example demonstrating this:

//@version=5
strategy("Dynamic Balance", overlay=true, initial_capital=10000)

var float balance = strategy.initial_capital
var float currentProfit = 0.0

if strategy.position_size == 0
    strategy.close_all()

if ta.crossover(ta.sma(close, 20), ta.sma(close, 50))
    strategy.entry("Long", strategy.long)

if ta.crossunder(ta.sma(close, 20), ta.sma(close, 50))
    strategy.close("Long")


// Calculate profit/loss on trade closure
if strategy.position_size == 0 and strategy.opentrades == 0
    currentProfit := strategy.netprofit - nz(currentProfit[1])
    balance := balance + currentProfit

plot(balance, title="Simulated Balance")

This improved example dynamically updates the balance whenever a trade is closed.

Accounting for Commission Costs

Real trading involves commissions. You can factor this into your balance calculations by subtracting the commission amount when a trade closes.

// Example with commission
commission = 2.0 // Example commission per trade

if strategy.position_size == 0 and strategy.opentrades == 0
    currentProfit := strategy.netprofit - nz(currentProfit[1])
    balance := balance + currentProfit - commission

Visualizing Balance and Equity Curves

Plotting the Simulated Balance Over Time

The plot() function is used to visualize the balance over time, creating a balance curve.

Creating an Equity Curve Chart

An equity curve chart shows the strategy’s equity (balance + unrealized profit/loss of open positions) over time. Because balance tracking is emulated, the equity will more or less coincide with it.

Comparing Balance and Equity

Comparing the balance curve (closed trades) with an equity curve provides a complete view of the strategy’s risk and reward profile. The difference between the two show unrealized profits or losses.

Advanced Techniques and Considerations

Handling Compound Interest

For longer-term strategies, you can implement compound interest by reinvesting a percentage of the profits.

// Example of Balance recalculation with compound interest
reinvest_percentage = 0.5 // 50%
if strategy.position_size == 0 and strategy.opentrades == 0
    currentProfit := strategy.netprofit - nz(currentProfit[1])
    balance := balance + currentProfit
    balance := balance + (balance * reinvest_percentage * currentProfit)

Implementing Risk Management Strategies (e.g., position sizing based on balance)

Effective risk management is critical. You can use the simulated balance to dynamically adjust your position size.

// Example of position sizing based on balance
risk_per_trade = 0.02 // Risk 2% of balance per trade
position_size = math.floor((balance * risk_per_trade) / (atr(14)))

Backtesting Considerations and Limitations

  • Historical Data Quality: The accuracy of your backtest depends on the quality of historical data.
  • Slippage and Execution Costs: Simulated backtests often don’t fully account for slippage and execution costs.
  • Overfitting: Be wary of overfitting your strategy to historical data. Robust strategies perform well across different market conditions.
  • Data Lookahead Bias: Ensure your calculations don’t inadvertently use future data. Use ta.barssince and other appropriate functions to avoid it. Make sure to recalculate order results correctly.

In conclusion, while TradingView Pine Script doesn’t offer direct access to your account balance, simulating it allows you to thoroughly backtest and refine your strategies. Remember to consider commissions, risk management, and the limitations of backtesting when interpreting the results. With careful implementation, you can gain valuable insights into your strategy’s potential performance. Backtesting must always be taken with the understanding that it’s only a simulation and real trading may bring different results.


Leave a Reply