write a trading view back testing code for me: from the stated date, use a fixed amount…
- User
write a trading view back testing code for me: from the stated date, use a fixed amount of money to buy the stock, sell 20% when the stock price drops 8% a day
- Assistant
Sure! Below is a code snippet to backtest the trading strategy you described using the Pine Script programming language on TradingView:
//@version=4 strategy("Backtesting Strategy", overlay=true) // Set the initial capital and position size initial_capital = input(10000, title="Initial Capital") position_size = initial_capital / close // Set the desired start date for backtesting start_date = timestamp(yyyy, mm, dd, 00, 00) // replace yyyy, mm, dd with desired start date // Define strategy variables var bool buy_signal = false var float stock_qty = na var float buy_price = na var float sell_threshold = na // Calculate percentage thresholds for buying and selling buy_threshold = close * 0.08 sell_threshold = close * 0.80 // Entry condition if timestamp >= start_date and not(na(buy_signal)) and not(buy_signal) buy_signal := true // Sell condition if buy_signal and low <= buy_price * 0.92 buy_signal := false stock_qty := position_size * 0.8 sell_price = close sell_signal = true // Buy condition if buy_signal and close <= sell_threshold buy_signal := false stock_qty := position_size buy_price := close sell_threshold := buy_price * 0.92 // Plotting plot(strategy.equity, title="Equity", color=color.blue, linewidth=2, style=plot.style_circles) // Debugging plot(buy_signal ? 1 : na, title="Buy Signal", color=color.green, linewidth=2, style=plot.style_cross, transp=0) plot(sell_signal ? -1 : na, title="Sell Signal", color=color.red, linewidth=2, style=plot.style_cross, transp=0)