Algo Trading 101

How to Build an Algo Trading Strategy
— And Turn It Into Pine Script

By PointAlgo Quant Team 5 Min Read
Build Algorithmic Trading Strategy Pine Script

Algorithmic trading is the process of using coded rules to automatically execute trades based on price, time, volume, or other market conditions instead of manual decision-making. Its main advantages are speed, reduced emotional bias, the ability to backtest ideas, and the ability to monitor multiple setups systematically.

A good algo strategy is not just "an indicator with arrows." It is a complete decision system: what market to trade, what condition triggers entry, where to exit if right, where to exit if wrong, how much to risk, and when not to trade. Strong strategies are also tested across different market regimes before live deployment.

Start with the idea

Before writing code, define the strategy in plain language. Trading guides commonly recommend starting with a clear objective, selecting a market and timeframe, and choosing a setup type such as trend following, mean reversion, breakout, or arbitrage.

At this stage, write rules that are objective, not subjective. For example, "buy when fast EMA crosses above slow EMA and RSI is above 55" is codable, while "buy when trend looks strong" is not. This rule-based clarity is what makes a strategy suitable for automation.

Define the core parts

Every strategy should specify these components before coding: entry logic, exit logic, risk management, and execution assumptions. Practical algo-trading guides emphasize clearly defined entries and exits, stop-loss and take-profit logic, and parameters for risk control such as position sizing and daily limits.

A simple framework is:

Backtest before live trading

Once the rules are defined, test them on historical data. Backtesting helps evaluate how a strategy would have behaved in past market conditions and reveals issues such as weak expectancy, excessive drawdown, or fragile parameter choices.

In TradingView, strategies appear in the Strategy Tester, which includes an overview, performance summary, list of trades, and properties such as commission, slippage, pyramiding, and initial capital. TradingView also notes that its broker emulator uses chart data and default assumptions about intrabar movement, which matters when interpreting results.

Why Pine Script is useful

Pine Script is TradingView's scripting language for custom indicators and strategies. When a script is declared with strategy(), it gains access to the strategy.* namespace for order placement, position management, and performance analysis in the Strategy Tester.

This makes Pine Script ideal for rapid prototyping. You can define signals, plot them on the chart, simulate entries and exits, and inspect trade-by-trade results without leaving TradingView.

Your first Pine Script strategy

A Pine strategy starts with strategy() instead of indicator(). TradingView's documentation shows that a basic moving-average crossover strategy calculates two averages, enters long when the fast average crosses above the slow one, and enters short when the fast average crosses below the slow one.

Here is a clean starter example in Pine Script v6:

EMA_Strategy.pine
//@version=6
strategy("EMA Crossover Strategy", overlay=true, initial_capital=100000, pyramiding=1)

// Inputs
fastLen = input.int(20, "Fast EMA", minval=1)
slowLen = input.int(50, "Slow EMA", minval=1)
slPct   = input.float(1.0, "Stop Loss %", minval=0.1)
tpPct   = input.float(2.0, "Take Profit %", minval=0.1)

// Calculations
fastEMA = ta.ema(close, fastLen)
slowEMA = ta.ema(close, slowLen)

// Conditions
longCondition  = ta.crossover(fastEMA, slowEMA)
shortCondition = ta.crossunder(fastEMA, slowEMA)

// Entries
if longCondition
    strategy.entry("Long", strategy.long)
if shortCondition
    strategy.entry("Short", strategy.short)

// Exits
longStop  = strategy.position_avg_price * (1 - slPct / 100)
longTarget = strategy.position_avg_price * (1 + tpPct / 100)
shortStop  = strategy.position_avg_price * (1 + slPct / 100)
shortTarget = strategy.position_avg_price * (1 - tpPct / 100)

strategy.exit("Long Exit", from_entry="Long", stop=longStop, limit=longTarget)
strategy.exit("Short Exit", from_entry="Short", stop=shortStop, limit=shortTarget)

// Plots
plot(fastEMA, color=color.aqua, title="Fast EMA")
plot(slowEMA, color=color.orange, title="Slow EMA")

This uses strategy.entry() to open positions and strategy.exit() to place stop-loss and take-profit orders tied to the entry ID. TradingView documents that strategy.exit() can generate take-profit, stop-loss, trailing, and partial exits, while strategy.entry() can create market, limit, stop, and stop-limit entries.

How Pine Script orders work

TradingView's strategy engine simulates orders through a broker emulator. By default, orders are generally filled on the next available tick, which for historical bars usually means the next bar's open, not the same instant the signal appears.

This detail matters because many beginners overestimate strategy quality by ignoring execution assumptions. TradingView also explains that limit, stop, and stop-limit orders behave differently depending on whether price reaches the specified levels and whether intrabar assumptions or Bar Magnifier are used.

Improve the strategy step by step

After the basic version works, improve it carefully rather than adding random complexity. Good development practice is to test one improvement at a time, such as a trend filter, volatility filter, session filter, or better exit logic, and then compare whether the change improves drawdown, expectancy, or stability.

Useful upgrades include:

Common mistakes beginners make

One common mistake is coding first and thinking later. In practice, the strategy logic should be finalized in words before it is translated into code. Guides on algorithmic trading consistently recommend defining rules and risk parameters before deployment.

Another mistake is overfitting. A strategy that looks perfect on one symbol or one period may collapse in live trading if it was tuned too tightly to historical noise. Reliable testing includes out-of-sample validation, paper trading, and monitoring for slippage, delays, and rejected orders.

A practical workflow

If you want a clean workflow, use this sequence:

  1. Pick one setup, such as trend-following or mean reversion.
  2. Write exact entry, exit, and risk rules in plain English.
  3. Convert those rules into Pine Script using strategy(), strategy.entry(), and strategy.exit().
  4. Add the script to a TradingView chart and inspect the Strategy Tester tabs.
  5. Add realistic costs, refine one variable at a time, and avoid over-optimization.
  6. Paper trade before using real capital.

The Bottom Line

The best algo strategies are usually simple, testable, and disciplined rather than overly clever. Pine Script gives you a fast way to transform a market hypothesis into a working strategy, visualize it on charts, and evaluate whether it has real edge before connecting it to live execution.