Simplest PineScript Strategy Code Explained

Abstract: Demonstrates how to write a minimal PineScript strategy using the strategy() function, entry conditions, and trade execution commands.

Created: 2026-08-18 by
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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More