Skip to main content

Debugging and Testing 🔍

Debugging Techniques

Visual Debugging

//@version=5
indicator("Visual Debug", overlay=true)

// Add visual markers for debugging
debugPoint(message) =>
if barstate.islast
label.new(bar_index, high, message,
color=color.blue,
textcolor=color.white,
style=label.style_label_down)

// Example usage
sma = ta.sma(close, 14)
if ta.crossover(close, sma)
debugPoint("Crossover: " + str.tostring(close))

Console Logging

//@version=5
indicator("Debug Logging")

// Create debug log
var string[] debugLog = array.new_string(0)

log(message) =>
if array.size(debugLog) > 100
array.shift(debugLog)
array.push(debugLog,
str.tostring(bar_index) + ": " + message)

// Example usage
log("SMA: " + str.tostring(ta.sma(close, 14)))
log("RSI: " + str.tostring(ta.rsi(close, 14)))

Testing Framework

Unit Testing

//@version=5
indicator("Unit Tests")

// Test case structure
type TestCase
string name
bool result
string message

// Test runner
var TestCase[] tests = array.new<TestCase>(0)

runTest(name, condition, message) =>
test = TestCase.new(name, condition, message)
array.push(tests, test)
condition

// Example tests
testSMA() =>
sma = ta.sma(close, 14)
runTest("SMA Test",
not na(sma),
"SMA should not be NA")

testRSI() =>
rsi = ta.rsi(close, 14)
runTest("RSI Range",
rsi >= 0 and rsi <= 100,
"RSI should be between 0 and 100")

Integration Testing

//@version=5
strategy("Integration Tests", overlay=true)

// Test complete strategy flow
testStrategyFlow() =>
var int successfulTrades = 0
var int failedTrades = 0

// Entry conditions
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if longCondition
strategy.entry("Long", strategy.long)

// Exit conditions
if strategy.position_size > 0
if close < strategy.position_avg_price * 0.95 // Stop loss
strategy.close("Long")
failedTrades += 1
else if close > strategy.position_avg_price * 1.05 // Take profit
strategy.close("Long")
successfulTrades += 1

[successfulTrades, failedTrades]

Error Handling

Robust Error Checking

//@version=5
indicator("Error Handling")

// Custom error type
type Error
string message
string code
int severity

// Error handling function
handleError(condition, message, code="ERR", severity=1) =>
if condition
error = Error.new(message, code, severity)
array.push(errorLog, error)
runtime.error(message)

// Example usage
price = request.security(syminfo.tickerid, "D", close)
handleError(na(price), "Failed to fetch price data", "DATA_ERR", 2)

Performance Testing

Load Testing

//@version=5
indicator("Load Test")

// Simulate heavy load
loadTest(iterations) =>
var float[] results = array.new_float(0)
startTime = timenow

for i = 1 to iterations
value = ta.sma(close, i)
array.push(results, value)

endTime = timenow
endTime - startTime

// Run tests with different loads
light = loadTest(10)
medium = loadTest(50)
heavy = loadTest(100)

Regression Testing

Historical Validation

//@version=5
strategy("Regression Test")

// Track historical performance
var float[] returns = array.new_float(0)
var float[] drawdowns = array.new_float(0)

// Calculate metrics
calculateMetrics() =>
if strategy.closedtrades > 0
array.push(returns, strategy.netprofit)
array.push(drawdowns, strategy.max_drawdown)

// Compare with baseline
compareBaseline() =>
avgReturn = array.avg(returns)
avgDrawdown = array.avg(drawdowns)
baselineReturn = 0.05 // 5% baseline return
baselineDrawdown = 0.10 // 10% baseline drawdown

[avgReturn > baselineReturn, avgDrawdown < baselineDrawdown]

Monitoring Tools

Performance Metrics

//@version=5
indicator("Performance Monitor")

// Track key metrics
type Metrics
float executionTime
int memoryUsage
int errorCount

// Monitor script performance
var Metrics metrics = Metrics.new(0.0, 0, 0)
startTime = timenow

// Your script logic here
result = ta.sma(close, 200)

// Update metrics
metrics.executionTime := timenow - startTime
metrics.memoryUsage := array.size(debugLog)
Testing Tips
  • Write tests for critical components
  • Use visual debugging for complex logic
  • Implement comprehensive error handling
  • Monitor performance metrics
  • Maintain test coverage
Common Testing Mistakes

❌ Insufficient test cases ❌ Missing edge case tests ❌ Poor error handling ❌ Inadequate performance testing ❌ Lack of regression tests

Next Steps

Ready to learn about publishing and sharing your scripts? Move on to the next chapter! 🚀