How to Develop a Simple Buy & Sell Strategy Using Pine Script for BTC/USDT

·

Creating a reliable trading strategy is a foundational skill for any aspiring algorithmic trader. In this guide, you’ll learn how to build a simple yet effective Buy & Sell strategy using Pine Script, the proprietary scripting language of TradingView, tailored for the BINANCE:BTCUSDT trading pair. This step-by-step tutorial walks you through setting up a strategy based on the 200-period Simple Moving Average (SMA), complete with entry and exit logic, risk management parameters, and visual output directly on your price chart.

Whether you're new to coding or looking to refine your algorithmic trading skills, this guide delivers practical insights into backtesting, condition logic, and execution—all within the powerful Pine Script framework.


Understanding the Strategy Logic

At its core, this strategy leverages price behavior relative to the 200-period SMA, a widely used indicator in technical analysis. The logic is straightforward:

This counter-trend approach assumes that prolonged moves below the long-term average may signal undervaluation, presenting a potential buying opportunity.

👉 Discover how algorithmic strategies can enhance your trading precision and execution speed.


Step 1: Define Strategy Parameters

Before diving into logic, it’s essential to configure the foundational settings of your Pine Script strategy. These parameters control how your script behaves during backtesting and visualization.

Start by declaring the strategy using the strategy() function, which allows for detailed customization:

//@version=6
strategy(
    "Buy & Sell Strategy Template [The Quant Science]",
    overlay = true,
    default_qty_type = strategy.percent_of_equity,
    default_qty_value = 5,
    currency = currency.USD,
    initial_capital = 10000,
    commission_type = strategy.commission.percent,
    commission_value = 0.07,
    slippage = 3,
    process_orders_on_close = true
)

Let’s break down each parameter:

These settings ensure your backtest mirrors real-market conditions as closely as possible.


Step 2: Data Extrapolation – Calculating the SMA

The next phase involves pulling historical price data and computing the 200-period Simple Moving Average using closing prices.

sma = ta.sma(close, 200)

Here, ta.sma() is Pine Script’s built-in function for calculating SMAs. It takes two arguments: the source (in this case, close) and the length (200 bars). This line generates a smooth line representing average price over the last 200 periods, serving as a dynamic support/resistance level.


Step 3: Define Entry and Exit Conditions

With the SMA calculated, we now define precise trading conditions using Pine Script’s powerful logical functions.

Entry Condition

A long position is triggered when the price crosses below the SMA:

entry_condition = ta.crossunder(close, sma)

ta.crossunder() returns true only on the bar where the close drops below the SMA—preventing repeated signals during extended downtrends.

Exit Condition

The trade closes when the price crosses above the SMA:

exit_condition = ta.crossover(close, sma)

ta.crossover() works symmetrically, detecting bullish reversals with precision.

These conditions ensure clean, unambiguous signals based on measurable price action.


Step 4: Execute Trades Based on Conditions

Now that we have our logic in place, it’s time to implement actual trade execution using Pine Script’s strategy.entry and strategy.exit.

if (entry_condition == true and strategy.opentrades == 0)
    strategy.entry(id = "Buy", direction = strategy.long, limit = close)

if (exit_condition == true)
    strategy.exit(id = "Sell", from_entry = "Buy", limit = close)

Key points:

This structure ensures disciplined trade management and avoids overlapping positions.


Step 5: Visual Design – Plotting the SMA on Chart

To enhance readability and real-time monitoring, plot the 200-period SMA directly on the chart:

plot(sma, title = "SMA", color = color.red, linewidth = 2)

This line draws a red line representing the moving average, making it easy to visually confirm crossovers and assess market positioning.

👉 See how real-time data visualization can transform your trading decisions.


Complete Pine Script Code

Here’s the full script ready for deployment in TradingView:

//@version=6
strategy(
    "Buy & Sell Strategy Template [The Quant Science]",
    overlay = true,
    default_qty_type = strategy.percent_of_equity,
    default_qty_value = 5,
    currency = currency.USD,
    initial_capital = 10000,
    commission_type = strategy.commission.percent,
    commission_value = 0.07,
    slippage = 3,
    process_orders_on_close = true
)

// Calculate 200-period SMA
sma = ta.sma(close, 200)

// Define trading conditions
entry_condition = ta.crossunder(close, sma)
exit_condition = ta.crossover(close, sma)

// Execute trades
if (entry_condition == true and strategy.opentrades == 0)
    strategy.entry(id = "Buy", direction = strategy.long, limit = close)

if (exit_condition == true)
    strategy.exit(id = "Sell", from_entry = "Buy", limit = close)

// Visualize SMA
plot(sma, title = "SMA", color = color.red, linewidth = 2)

Once applied, this script will display buy and sell signals overlaid on BTC/USDT price action along with the red SMA line.


Frequently Asked Questions (FAQ)

Q: Can I use this strategy for other cryptocurrencies or assets?

Yes. While designed for BTC/USDT, this logic applies universally across any tradable asset available on TradingView—such as ETH/USDT, gold, forex pairs, or stocks—simply by changing the symbol.

Q: Why use process_orders_on_close = true?

This setting ensures trades execute at the close of the detected signal candle, preventing lookahead bias and aligning with realistic trading behavior where decisions are made after candle confirmation.

Q: Is this a profitable strategy?

This is an educational template. While it demonstrates solid coding and logic principles, it has not been optimized for profitability. Always test strategies thoroughly with historical data and forward-testing before live deployment.

Q: How can I improve this strategy?

Consider adding:

Q: What are core keywords for SEO in this context?

Key SEO terms include: Pine Script, BTC/USDT trading strategy, Simple Moving Average, algorithmic trading, backtesting crypto strategies, TradingView script, SMA crossover strategy, and automated trading logic.

Q: Can I automate this on real exchanges?

Pine Script runs within TradingView and supports alerts that can trigger external bots or APIs (like OKX Webhooks), enabling semi-automated execution—but direct live trading requires integration beyond Pine Script.

👉 Learn how API integrations can bridge automated strategies with live markets.


Final Thoughts

Building a basic Buy & Sell strategy in Pine Script is an excellent starting point for exploring algorithmic trading. By combining clear logic—like SMA crossovers—with sound risk parameters and visual feedback, you lay the groundwork for more advanced systems.

Remember: This example is for educational purposes only. Real-world trading involves additional risks including market volatility, liquidity constraints, and emotional discipline. Always validate strategies through rigorous backtesting and paper trading first.

With tools like Pine Script and platforms like TradingView, anyone can begin developing intelligent trading logic—no advanced degree required. Start small, iterate often, and let data guide your evolution as a quant trader.