Skip to content

Strategy Samples

This section provides ready-to-use Pine Script strategy samples that demonstrate Algo Trade Analytics integration. These samples serve as excellent starting points for your own strategies.

A clean, professional MA crossover strategy that demonstrates:

  • Basic moving average crossover entry signals
  • Stop loss and take profit management
  • Webhook integration with both TraderPost and Algo Trade Analytics
  • Clean, readable code structure
  • Dual Platform Support: Choose between TraderPost and Algo Trade Analytics webhook formats
  • Risk Management: Configurable stop loss and take profit levels
  • Time Filtering: Restrict trading to specific sessions
  • Visual Feedback: Clear entry/exit signals and position indicators
  • Professional Structure: Well-organized, documented code
  1. Copy the strategy code below
  2. Paste into TradingView Pine Script editor
  3. Configure your webhook settings
  4. Select your preferred platform (TraderPost or Algo Trade Analytics)
  5. Adjust MA lengths and risk parameters as needed
//@version=5
strategy("Sample MA Crossover Strategy",
overlay=true,
max_bars_back=5000,
slippage=1,
pyramiding=0,
use_bar_magnifier=true,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=50)
// ==================
// STRATEGY OVERVIEW
// ==================
// This is a sample Moving Average Crossover strategy that demonstrates:
// 1. Basic MA crossover entry signals
// 2. Stop loss and take profit management
// 3. Webhook integration with Algo Trade Analytics
// 4. Clean, readable code structure
// ==================
// WEBHOOK PLATFORM SELECTION
// ==================
g_platform = "Webhook Platform"
i_webhookPlatform = input.string("Algo Trade Analytics", "Webhook Platform", options=["TraderPost", "Algo Trade Analytics"], group=g_platform,
tooltip="Select the webhook platform format: TraderPost or Algo Trade Analytics")
// ==================
// WEBHOOK CONFIGURATION SETTINGS
// ==================
g_webhook = "Webhook Configuration"
i_authKey = input.string("your_auth_key_here", "Webhook Auth Key", group=g_webhook,
tooltip="Authentication key for your webhook endpoint")
i_defaultAccountId = input.string("default", "Account ID", group=g_webhook,
tooltip="Default account ID for trading")
i_webhookQty = input.int(10, "Webhook Quantity", minval=1, group=g_webhook,
tooltip="Number of shares/units to trade in webhook orders")
i_extendedHours = input.bool(false, "Extended Hours Trading", group=g_webhook,
tooltip="Allow trading in extended hours")
// ==================
// UNIFIED WEBHOOK CREATION FUNCTIONS
// ==================
// TraderPost webhook format (uses TraderPost's own format)
createTraderPostEntryAlert(direction, isStopLimit, float stopPrice = na, float limitPrice = na) =>
ticker = syminfo.ticker
sentiment = direction == "buy" ? "bullish" : "bearish"
orderType = isStopLimit ? "stop_limit" : "market"
longShort = direction == "buy" ? "Long" : "Short"
baseMsg = '"ticker": "' + ticker + '", "action": "' + direction + '", "sentiment": "' + sentiment +
'", "orderType": "' + orderType + '", "timeInForce": "gtc"'
stopLimitInfo = isStopLimit ? ', "stopPrice": ' + str.tostring(stopPrice) + ', "limitPrice": ' + str.tostring(limitPrice) : ''
extrasMsg = '"message": "MA Crossover ' + longShort + ' Entry", "price": ' + str.tostring(close)
extrasMsg := extrasMsg + ', "timeframe": "' + timeframe.period + '"'
'{' + baseMsg + stopLimitInfo + ', "extras": {' + extrasMsg + '}}'
createTraderPostExitAlert(direction, exitType) =>
ticker = syminfo.ticker
longShort = direction == "buy" ? "Long" : "Short"
baseMsg = '"ticker": "' + ticker + '", "action": "exit", ' +
'"orderType": "market", "timeInForce": "gtc"'
extrasMsg = '"message": "MA Crossover ' + longShort + ' ' + exitType + '", "price": ' + str.tostring(close)
extrasMsg := extrasMsg + ', "timeframe": "' + timeframe.period + '"'
'{' + baseMsg + ', "extras": {' + extrasMsg + '}}'
// Algo Trade Analytics webhook format (Universal Webhook Standard)
createAlgoTradeAnalyticsEntryAlert(side, isStopLimit, float stopPrice = na, float limitPrice = na) =>
ticker = syminfo.ticker
direction = side == "buy" ? "long" : "short"
positionDirection = side == "buy" ? "entryLong" : "entryShort"
orderType = isStopLimit ? "stop_limit" : "market"
longShort = side == "buy" ? "Long" : "Short"
clientOrderId = "tv-" + ticker + "-" + str.tostring(timenow)
// Required fields (Universal Webhook Standard)
requiredFields = '"auth_key": "' + i_authKey + '", "ticker": "' + ticker + '", "direction": "' + direction + '", "side": "' + side + '", "positionDirection": "' + positionDirection + '", "marketPrice": ' + str.tostring(close) + ', "qty": ' + str.tostring(i_webhookQty)
// Order configuration
orderConfig = ', "orderType": "' + orderType + '"'
orderConfig := orderConfig + (isStopLimit and not na(stopPrice) ? ', "stopPrice": ' + str.tostring(stopPrice) : '')
orderConfig := orderConfig + (isStopLimit and not na(limitPrice) ? ', "limitPrice": ' + str.tostring(limitPrice) : '')
// Order management
orderMgmt = ', "timeInForce": "gtc", "extendedHours": ' + str.tostring(i_extendedHours) + ', "clientOrderId": "' + clientOrderId + '", "accountId": "' + i_defaultAccountId + '"'
// Metadata
metadata = ', "metadata": {"strategy": "MA Crossover Sample", "signal": "MA Crossover", "signalPlatform": "tradingview", "brokerPlatform": "alpaca", "timestamp": "' + str.format_time(timenow, "yyyy-MM-dd'T'HH:mm:ss.000'Z'", "UTC") + '", "comment": "MA Crossover ' + longShort + ' Entry Signal", "timeframe": "' + timeframe.period + '"}'
'{' + requiredFields + orderConfig + orderMgmt + metadata + '}'
createAlgoTradeAnalyticsExitAlert(side, exitType) =>
ticker = syminfo.ticker
direction = side == "buy" ? "long" : "short"
positionDirection = side == "buy" ? "exitLong" : "exitShort"
longShort = side == "buy" ? "Long" : "Short"
clientOrderId = "tv-exit-" + ticker + "-" + str.tostring(timenow)
// Required fields for exit
requiredFields = '"auth_key": "' + i_authKey + '", "ticker": "' + ticker + '", "direction": "' + direction + '", "side": "' + side + '", "positionDirection": "' + positionDirection + '", "marketPrice": ' + str.tostring(close) + ', "qty": ' + str.tostring(i_webhookQty)
// Order configuration (exits are typically market orders)
orderConfig = ', "orderType": "market"'
// Order management
orderMgmt = ', "timeInForce": "gtc", "extendedHours": ' + str.tostring(i_extendedHours) + ', "clientOrderId": "' + clientOrderId + '", "accountId": "' + i_defaultAccountId + '"'
// Metadata for exits
metadata = ', "metadata": {"strategy": "MA Crossover Sample", "signal": "' + exitType + '", "signalPlatform": "tradingview", "brokerPlatform": "alpaca", "timestamp": "' + str.format_time(timenow, "yyyy-MM-dd'T'HH:mm:ss.000'Z'", "UTC") + '", "comment": "MA Crossover ' + longShort + ' ' + exitType + ' Signal", "exitReason": "' + exitType + '", "timeframe": "' + timeframe.period + '"}'
'{' + requiredFields + orderConfig + orderMgmt + metadata + '}'
// Unified webhook creation functions that route to the appropriate format
createEntryAlert(side, isStopLimit, float stopPrice = na, float limitPrice = na) =>
if i_webhookPlatform == "TraderPost"
// TraderPost uses 'direction' parameter (buy/sell format)
createTraderPostEntryAlert(side, isStopLimit, stopPrice, limitPrice)
else
// Algo Trade Analytics uses Universal Webhook Standard
createAlgoTradeAnalyticsEntryAlert(side, isStopLimit, stopPrice, limitPrice)
createExitAlert(side, exitType) =>
if i_webhookPlatform == "TraderPost"
// TraderPost uses 'direction' parameter (buy/sell format)
createTraderPostExitAlert(side, exitType)
else
// Algo Trade Analytics uses Universal Webhook Standard
createAlgoTradeAnalyticsExitAlert(side, exitType)
// ==================
// DATE RANGE SETTINGS
// ==================
g_date = "Date Range"
i_from = input.time(defval = timestamp("1 Jan 2024 00:00 +0000"), title = "From", group=g_date,
tooltip="Start date for strategy testing")
i_thru = input.time(defval = timestamp("31 Dec 2024 00:00 +0000"), title = "Thru", group=g_date,
tooltip="End date for strategy testing")
// Session time settings
i_useTimeFilter = input.bool(true, "Enable Time Filter", group=g_date,
tooltip="Restrict trading to specific session times")
i_session = input.session("1000-1630:23456", "Trading Session", group=g_date,
tooltip="Trading hours HHMM-HHMM:days (23456=Mon-Fri)")
// ==================
// MA SETTINGS
// ==================
g_ma = "Moving Average Settings"
i_maType = input.string("EMA", "MA Type", options=["EMA", "SMA", "VWMA"], group=g_ma)
i_fastMALength = input.int(10, "Fast MA Length", minval=1, group=g_ma)
i_slowMALength = input.int(20, "Slow MA Length", minval=1, group=g_ma)
// ==================
// RISK MANAGEMENT
// ==================
g_risk = "Risk Management"
i_useStopLoss = input.bool(true, "Enable Stop Loss", group=g_risk)
i_stopLossPerc = input.float(2.0, "Stop Loss %", minval=0.1, step=0.1, group=g_risk)
i_useProfitTarget = input.bool(true, "Enable Take Profit", group=g_risk)
i_profitTargetPerc = input.float(4.0, "Take Profit %", minval=0.1, step=0.1, group=g_risk)
// ==================
// TRADING DIRECTION
// ==================
g_direction = "Trading Direction"
i_tradingDirection = input.string("Both", "Trading Direction", options=["Both", "Long Only", "Short Only"], group=g_direction)
// ==================
// HELPER FUNCTIONS
// ==================
// Time filter functions
timeInRange() =>
time >= i_from and time <= i_thru
inTradeSession() =>
if not timeInRange()
false
else if not i_useTimeFilter
true
else
not na(time(timeframe.period, i_session))
// MA calculation function
calcMA(length) =>
switch i_maType
"EMA" => ta.ema(close, length)
"SMA" => ta.sma(close, length)
"VWMA" => ta.vwma(close, length)
=> ta.ema(close, length)
// ==================
// MA CALCULATIONS
// ==================
fastMA = calcMA(i_fastMALength)
slowMA = calcMA(i_slowMALength)
// ==================
// ENTRY CONDITIONS
// ==================
longCondition = inTradeSession() and ta.crossover(fastMA, slowMA) and i_tradingDirection != "Short Only"
shortCondition = inTradeSession() and ta.crossunder(fastMA, slowMA) and i_tradingDirection != "Long Only"
// ==================
// EXIT CONDITIONS
// ==================
// Exit on opposite crossover
longExitCondition = strategy.position_size > 0 and ta.crossunder(fastMA, slowMA)
shortExitCondition = strategy.position_size < 0 and ta.crossover(fastMA, slowMA)
// ==================
// STRATEGY LOGIC
// ==================
// Entry logic
if longCondition and strategy.position_size == 0
strategy.entry("Long", strategy.long, alert_message = createEntryAlert("buy", false))
if shortCondition and strategy.position_size == 0
strategy.entry("Short", strategy.short, alert_message = createEntryAlert("sell", false))
// Exit logic
if strategy.position_size != 0
isLong = strategy.position_size > 0
entryPrice = strategy.opentrades.entry_price(0)
// Calculate stop loss and take profit levels
stopLoss = isLong ?
entryPrice * (1 - i_stopLossPerc/100) :
entryPrice * (1 + i_stopLossPerc/100)
takeProfit = isLong ?
entryPrice * (1 + i_profitTargetPerc/100) :
entryPrice * (1 - i_profitTargetPerc/100)
// Exit on MA crossover
if (isLong and longExitCondition) or (not isLong and shortExitCondition)
strategy.close_all(
comment = isLong ? "Long MA Cross Exit" : "Short MA Cross Exit",
alert_message = createExitAlert(isLong ? "buy" : "sell", "MA Cross Exit"))
else
// Regular exit with stop loss and take profit
strategy.exit(
id = isLong ? "Long Exit" : "Short Exit",
from_entry = isLong ? "Long" : "Short",
stop = i_useStopLoss ? stopLoss : na,
profit = i_useProfitTarget ? takeProfit : na,
alert_message = createExitAlert(isLong ? "buy" : "sell", "Regular Exit"),
alert_profit = createExitAlert(isLong ? "buy" : "sell", "Take Profit"),
alert_loss = createExitAlert(isLong ? "buy" : "sell", "Stop Loss"))
// ==================
// PLOTTING
// ==================
// Plot MAs
plot(fastMA, "Fast MA", color=color.blue, linewidth=2)
plot(slowMA, "Slow MA", color=color.red, linewidth=2)
// Plot entry signals
plotshape(
longCondition,
title="Long Entry",
location=location.belowbar,
color=color.green,
style=shape.triangleup,
size=size.normal,
text="BUY")
plotshape(
shortCondition,
title="Short Entry",
location=location.abovebar,
color=color.red,
style=shape.triangledown,
size=size.normal,
text="SELL")
// Plot exit signals
plotshape(
longExitCondition,
title="Long Exit",
location=location.abovebar,
color=color.orange,
style=shape.xcross,
size=size.small,
text="EXIT")
plotshape(
shortExitCondition,
title="Short Exit",
location=location.belowbar,
color=color.orange,
style=shape.xcross,
size=size.small,
text="EXIT")
// Background color for active positions
bgcolor(strategy.position_size != 0 ?
(strategy.position_size > 0 ? color.new(color.green, 90) : color.new(color.red, 90)) :
na,
title="Position Active")
// ==================
// TABLE WITH STRATEGY INFO
// ==================
var table infoTable = table.new(position.top_right, 2, 7,
bgcolor = color.rgb(0, 0, 0, 80),
frame_color = color.white,
frame_width = 1)
if barstate.islast
table.cell(infoTable, 0, 0, "Strategy", text_color=color.white, text_size=size.small)
table.cell(infoTable, 1, 0, "MA Crossover", text_color=color.white, text_size=size.small)
table.cell(infoTable, 0, 1, "Platform", text_color=color.aqua, text_size=size.small)
table.cell(infoTable, 1, 1, i_webhookPlatform, text_color=color.aqua, text_size=size.small)
table.cell(infoTable, 0, 2, "Fast MA", text_color=color.blue, text_size=size.small)
table.cell(infoTable, 1, 2, str.tostring(i_fastMALength) + " " + i_maType, text_color=color.blue, text_size=size.small)
table.cell(infoTable, 0, 3, "Slow MA", text_color=color.red, text_size=size.small)
table.cell(infoTable, 1, 3, str.tostring(i_slowMALength) + " " + i_maType, text_color=color.red, text_size=size.small)
table.cell(infoTable, 0, 4, "Stop Loss", text_color=color.orange, text_size=size.small)
table.cell(infoTable, 1, 4, i_useStopLoss ? str.tostring(i_stopLossPerc) + "%" : "Disabled", text_color=color.orange, text_size=size.small)
table.cell(infoTable, 0, 5, "Take Profit", text_color=color.green, text_size=size.small)
table.cell(infoTable, 1, 5, i_useProfitTarget ? str.tostring(i_profitTargetPerc) + "%" : "Disabled", text_color=color.green, text_size=size.small)
table.cell(infoTable, 0, 6, "Direction", text_color=color.yellow, text_size=size.small)
table.cell(infoTable, 1, 6, i_tradingDirection, text_color=color.yellow, text_size=size.small)
  1. Select Platform: Choose between “TraderPost” or “Algo Trade Analytics” in the Webhook Platform dropdown
  2. Auth Key: Enter your webhook authentication key
  3. Account ID: Set your default trading account ID
  4. Quantity: Specify the number of shares/units to trade
  5. Extended Hours: Enable if you want to trade outside regular hours
  • Fast MA Length: Shorter moving average period (default: 10)
  • Slow MA Length: Longer moving average period (default: 20)
  • MA Type: Choose between EMA, SMA, or VWMA
  • Stop Loss: Percentage-based stop loss (default: 2%)
  • Take Profit: Percentage-based take profit (default: 4%)
  • Trading Direction: Long only, Short only, or Both
  • Date Range: Set start and end dates for backtesting
  • Trading Session: Restrict trading to specific hours and days
  • Time Filter: Enable/disable session-based trading

The strategy automatically adapts webhook format based on your platform selection:

  • TraderPost: Uses TraderPost’s specific JSON structure
  • Algo Trade Analytics: Uses the Universal Webhook Standard
  • Stop Loss: Automatically calculated as a percentage of entry price
  • Take Profit: Configurable profit targets
  • MA Cross Exit: Exits positions when moving averages cross in the opposite direction
  • Entry Signals: Green triangles for buy, red triangles for sell
  • Exit Signals: Orange X marks for exits
  • Position Background: Green/red background when position is active
  • Info Table: Real-time display of current settings
  1. Adjust MA Lengths: Try different combinations for your timeframe
  2. Risk Parameters: Modify stop loss and take profit percentages
  3. Time Filtering: Set specific trading hours for your strategy
  4. Platform Selection: Switch between platforms without code changes
  1. Test the strategy on historical data
  2. Adjust parameters based on your trading style
  3. Add additional indicators or conditions
  4. Implement position sizing rules
  5. Add more sophisticated exit conditions

This sample provides a solid foundation for building more complex strategies while maintaining clean, professional code structure.