Strategy Generator in Pine Script V5
Fill out the form and receive the code for a strategy with averages, RSI, Stop and Take, commented on and ready for TradingView.
In short: This generator assembles the code of a strategy in Pine Script V5 for TradingView from a form: crossing of averages, RSI or both combined, with direction, stop loss, take profit, position size and commission. The code is commented on in Portuguese and ready to paste in the Pine Editor and test it in the Strategy Tester.
How to put code in TradingView
- Generate and copyAdjust the form, check the summary and click Copy Code. If the button doesn't work in your browser, select the frame text and copy it.
- Open the Pine EditorIn the TradingView chart, open the Pine Editor tab at the bottom of the screen and create a new script.
- Paste and add to the chartDelete the sample content, paste the code, save it, and click Add to chart. The averages and signal triangles appear on the price.
- Read the Strategy TesterIn the Strategy Tester tab are the net profit, the maximum drawdown, the list of trades and the hit percentage. Change active and chart time to see if the rule is sustained.
All form entries have become input fields in the code. So, after adding to the chart, you can change periods, RSI levels, Stop and Target by the settings gear, without editing the text.

What each block of code does
The code follows the structure that the TradingView documentation uses in the strategy examples. Understanding each block helps to safely modify.
| Block | Function |
|---|---|
| //@version=5 and strategy() | They declare the version of the language and that the script is a strategy. Strategy() defines initial capital, position size in % of equity (strategy.percent_of_equity) and commission in percentage (strategy.commission.percent). |
| Entries | input.int and input.float create the editable fields of periods, levels and percentages. |
| Calculations | ta.sma or ta.ema calculate the averages; ta.rsi calculates the relative strength index. |
| Signs | ta.crossover is true in the candlestick in which the first series crosses the second upwards; ta.crossunder, down. |
| Instructions | Strategy.entry opens the position; Strategy.close closes an entry by name. In purchase and sale, a contrary entry reverses the position. |
| Stop and target | Strategy.exit with STOP and LIMIT creates two output orders, one from STOP and the other from the target, linked to the input by from_entry. |
| Visual | Plot draws the averages and plotshape marks the signs with triangles. |
Why Stop uses a base that changes
In the signal candlestick, the position does not yet exist: By default, the Strategy Tester evaluates the script at the candlestick and the order is executed in the next candlestick. For the position not to be unprotected in this range, the code already sends the stop and the target in the signal candlestick, using the closing as a base. When the position exists, the base becomes Strategy.position_avg_price, the actual average entry price, and the levels are recalculated.
The three types of signals available
- Average crossover: Classic trend follower. Buy when the fast average crosses the slow upwards. It works well on long trends and suffers in the lateral market. You can have a quick preview at moving average simulator before going to TradingView.
- Averages with RSI filter: same crossing, but ignores the purchase if the RSI is already above the overbought, and the sale if it is below the oversold. The idea is to avoid entering when the movement is already stretched.
- RSI Oversold and Overbought: reversal logic. Purchase when the RSI rises above the oversold level and leaves when the RSI drops below the overbought level. It tends to hit more often, but with smaller gains, and suffers from strong trends.
If you want to understand the indicators before testing, read the moving averages and of IFR (relative strength index).
Common customizations after generating
The generated code is a dry starting point. Some changes that traders usually make later, already within the Pine Editor:
- Trend Filter: Calculate a third long average, like the one with 200 periods, and only accept purchases with the price above it.
- Date filter: Create an input with Input.Time and only operate from the chosen date, to separate the adjustment period from the validation period.
- Mobile Stop: Swap the fixed stop for the Trailing parameters of Strategy.exit, which accompany the price in favor of the position.
- Risk size: instead of fixed percentage of the equity, calculate the amount from the distance from the stop, as the Position size calculator.
Make one change at a time and compare the Strategy Tester before and after. If several changes come together, it is impossible to know which one helped or hindered.
Pine script v5 or v6?
TradingView released Pine Script V6 on December 10, 2024. According to the official announcement, the v6 changes do not affect scripts written in previous versions, so the V5 code generated here continues to work. New features, however, only come to the latest version. If you want to migrate, Pine Editor has the option to convert code to V6 in the script management menu, and TradingView warns that not all scripts automatically convert.
To learn how to write and edit strategies from scratch, follow the Pine Script Tutorial e o TradingView Guide. who prefers the MetaTrader finds the equivalent logic in the guide of Expert Advisor in MQL5.
How to evaluate the result without making a mistake
- Look at the maximum drawdown before profit. If you couldn't handle that fall with real money, the strategy doesn't work for you.
- Check the number of trades. With few operations, the result is statistically fragile.
- Test on other assets and chart times, and in periods you haven't used to adjust the parameters.
- Be wary of perfect curves. adjusting parameters until the curve looks beautiful is overfitting, and live performance often disappoints.
The guide of backtest Explains in-sample, out-of-sample and walk-forward. And if you intend to automate, see before How to create a trading robot and the step by step of BingX Signal Trading with TradingView.
Transparency: The Boletim Bitcoin can receive commission for registrations made through BingX's links, at no extra cost for you. That doesn't change what we write about risks and costs.
Frequently asked questions
Does the generated code work in free TradingView?
Yes. The Pine Editor and Strategy Tester are available in the TradingView free plan, with resource limits that vary by plan.
Why generate in V5 if V6 already exists?
Because V5 scripts keep working and most tutorials still use V5. If you want, convert to V6 by the Pine Editor itself.
Can I use the code to create alerts?
Yes. In TradingView, create an alert by choosing the strategy as a condition. Alerts fire when the strategy generates orders.
The stop is calculated at what price?
On the average price of the open position. In the signal candlestick, before execution, use the closure as a basis for the position not to be unprotected.
Does a good result in Strategy Tester guarantee profit?
No. The test shows the past and may be too adjusted to the data. Validate in other periods and assets and operate small at the beginning.
References
This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.