The simplest PineScript strategy requires the
strategy() declaration, input parameters for entry and exit conditions, and
strategy.entry() or
strategy.exit() calls to execute trades. This minimal structure allows traders on TradingView to backtest basic logic without unnecessary complexity, providing a foundational template for algorithmic trading development.
Core Structure of a Strategy
Every PineScript strategy begins with a version declaration and a specific function call that distinguishes it from a standard indicator. While indicators calculate values for display, strategies simulate trade execution based on those values. The most critical line is
strategy(), which initializes the strategy engine. Without this line, the script will not have access to functions like
strategy.entry or
strategy.close.
You must specify the title of the strategy and the timeframe on which it operates. For example:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © YourName
//@version=5
strategy("Simplest Strategy", overlay=true)
The
overlay=true parameter ensures the strategy lines appear directly on the price chart rather than in a separate pane below. This is essential for visual confirmation of entry and exit points relative to candle prices. The version number
5 is mandatory for modern scripts and ensures compatibility with the latest features available in the Pine Editor.
Defining Entry Conditions
A strategy needs clear rules for when to enter a long position (buy). In the simplest form, you can use a boolean variable to determine if the condition is met. A common beginner approach uses moving averages or simple price crosses. However, for the absolute simplest code, we can use a placeholder condition that triggers every N bars or based on a basic mathematical operation.
To make it practical, let us assume a simple crossover of two exponential moving averages (EMAs). You first define the EMAs using the
ta.ema() function. Then, you check if the fast EMA crosses above the slow EMA.
fastEMA = ta.ema(close, 9)
slowEMA = ta.ema(close, 21)
longCondition = ta.crossover(fastEMA, slowEMA)
The
ta.crossover() function returns true only when the first series crosses above the second series. This single boolean value becomes the trigger for your entry command. It is crucial to understand that these calculations happen on every bar update, ensuring real-time logic application during backtesting.
Executing Trades
Once the condition is defined, you must instruct the strategy to act. The
strategy.entry() function is used to open a position. For a long entry, you would write:
if longCondition
strategy.entry("Long", strategy.long)
This code checks if
longCondition is true on the current bar. If it is, it opens a long position labeled "Long". The label is optional but helpful for debugging and identifying specific orders in the strategy report. Similarly, you need an exit condition to close the trade. A simple exit might be when the fast EMA crosses below the slow EMA.
shortCondition = ta.crossunder(fastEMA, slowEMA)
if shortCondition
strategy.close("Long")
The
strategy.close() function closes all open positions for the specified label. This completes the basic loop of entering and exiting a trade. You can also use
strategy.exit() to set stop-loss and take-profit levels simultaneously, but for the simplest code, closing on signal reversal is sufficient.
Integrating with Advanced Logic
While this guide focuses on simplicity, many traders eventually want to add more complex exit criteria. For instance, you might want to combine this basic strategy with other technical indicators like Supertrend for better risk management. If you are looking to expand your strategy's capabilities beyond basic crossovers, you may find
How to Add Exit XBar Sell Supertrend Strategy on TradingView useful for understanding how to layer additional exit conditions onto your existing code. This allows you to keep the core entry logic simple while refining exits for better performance.
Testing and Optimization
After writing the code, click the "Add to Chart" button in the Pine Editor. The strategy will run over historical data, plotting buy and sell markers on the chart. You can view detailed statistics by opening the "Strategy Tester" tab at the bottom of the screen. This tab shows metrics such as net profit, total trades, and win rate.
It is important to note that PineScript strategies are event-driven. They do not predict the future; they react to closed bars. Therefore, results are based on the close price of the previous bar unless you explicitly use
calc_on_every_tick=true in the
strategy() declaration. For beginners, sticking to default settings (calculating on bar close) is recommended to avoid repainting issues and ensure consistent backtesting results.
Frequently Asked Questions
Why does my strategy show no trades?
Check if your entry condition is ever true by adding
plotshape() to visualize signals. Ensure the timeframes of your chart and strategy match, and verify that the moving average lengths are appropriate for the asset's volatility.
Can I use this code for live trading?
Yes, but you must ensure your strategy logic is stable and tested extensively. Live trading requires careful consideration of slippage, commissions, and execution speed, which are simulated differently in backtests versus live environments.
What is the difference between strategy.entry and order.market?
strategy.entry is specific to the PineScript strategy framework and handles position sizing and margin automatically. Standard order functions are used in custom execution engines, but
strategy.entry is the standard for built-in TradingView strategy simulation.
How do I add a stop loss to this simple code?
You can modify the
strategy.exit() call to include a
stoploss parameter. For example,
strategy.exit("Exit", "Long", stoploss=10) would close the position if the price drops by 10 units from the entry price.
Does the strategy recalculate on every tick?
By default, PineScript strategies calculate on bar close to prevent repainting. If you need intrabar precision, you can add
calc_on_every_tick=true to the
strategy() declaration, but this increases computation load and may produce different results.