Home » Strategy Functions » Understanding the log.error() Function in Pine Script

Understanding the log.error() Function in Pine Script

Photo of author
Published on

The log.error() function is crucial for indicating serious issues or errors in your script’s logic. This article dives deep into how to use the log.error() function effectively.

Introduction to Logging in Pine Script

Before we examine the log.error() function specifically, let’s understand the context of logging in Pine Script. Logging functions in Pine Script allow you to print messages to the “Pine Logs” console, which can be immensely helpful for debugging purposes. There are different levels of logging, including info, warning, and error, each serving a distinct purpose:

  • Info (log.info()): Used for informational messages.
  • Warning (log.warning()): Indicates a potential issue that might not disrupt the script’s execution.
  • Error (log.error()): Highlights a critical problem that could affect the script’s functionality.

Syntax and Usage of log.error()

Basic Syntax

The log.error() function is used to log error messages. It can be invoked in two ways:

  1. Single Argument:
   log.error(message) → void

Here, message is a series string that represents the log message.

  1. Multiple Arguments (Formatted String):
   log.error(formatString, arg0, arg1, ...) → void

formatString contains the text to be logged with placeholders {} for dynamic values (arg0, arg1, …).

Understanding Placeholders

Placeholders in the formatString are replaced by the arguments (arg0, arg1, …) based on their index. An optional format specifier can further customize the formatting of these values.

Example

Let’s explore an example that incorporates the log.error() function within a trading strategy:

//@version=5
strategy("Enhanced Strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders_on_close = true)
stopLossTakeProfitDistance = input.int(1000, "SL/TP Distance (in ticks)")

bullishSignal = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (bullishSignal)
    entryPrice = close * 1.01
    log.info("Bullish order at {0}", entryPrice)
    strategy.order("Bullish Entry", strategy.long, limit = entryPrice)

    log.info("SL/TP set at: TP at {0}, SL at {1}", close)
    strategy.exit("Exit Strategy", "Bullish Entry", profit = stopLossTakeProfitDistance, loss = stopLossTakeProfitDistance)

if strategy.opentrades > 10
    log.warning("Excessive open trades ({0}). Adjust SL/TP Distance.", strategy.opentrades)

capitalLossThreshold = strategy.initial_capital / 10 > strategy.equity
if (capitalLossThreshold and not capitalLossThreshold[1])
    log.error("Critical loss: 90% of initial capital depleted!")
Example

Explanation of the Code

  • Strategy Declaration:
    • //@version=5 indicates that the script uses version 5 of Pine Script.
    • strategy("Enhanced Strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders_on_close = true) defines a new strategy named “Enhanced Strategy” that:
      • Overlays its output on the price chart (overlay = true).
      • Uses fixed margins for long and short positions (100 units each).
      • Processes orders at the close of the candle (process_orders_on_close = true).
  • Input for SL/TP Distance:
    • stopLossTakeProfitDistance = input.int(1000, "SL/TP Distance (in ticks)") creates an input for the user to specify the Stop Loss/Take Profit distance in ticks, with a default value of 1000.
  • Bullish Signal Detection:
    • bullishSignal = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) checks for a bullish signal, which occurs when a 14-period Simple Moving Average (SMA) crosses over a 28-period SMA.
  • Bullish Order Logic:
    • If a bullish signal is detected, the script calculates an entry price (entryPrice = close * 1.01), which is 1% above the current closing price.
    • Logs information about the bullish order and its entry price using log.info.
    • Places a bullish (long) order with the calculated limit price (strategy.order).
    • Sets a strategy exit condition (strategy.exit) with both profit and loss thresholds defined by stopLossTakeProfitDistance.
  • Excessive Open Trades Check:
    • Checks if the number of open trades exceeds 10 (if strategy.opentrades > 10) and logs a warning message to adjust the SL/TP distance accordingly.
  • Capital Loss Threshold Check:
    • Calculates whether the strategy’s equity has fallen below 90% of its initial capital (capitalLossThreshold = strategy.initial_capital / 10 > strategy.equity).
    • If the equity falls below this threshold and it’s the first time this condition is met (and not capitalLossThreshold[1]), it logs an error message indicating a critical loss situation.

Key Takeaways

  • The log.error() function is vital for identifying critical issues in your Pine Script strategies.
  • It allows for both simple and formatted error messages, enhancing the debugging process.
  • Proper use of logging functions like log.error() can significantly aid in the development and refinement of trading strategies in Pine Script.

By integrating log.error() judiciously within your scripts, you can ensure better error handling and script robustness, ultimately leading to more reliable trading strategies.

Leave a Comment