Strategy Samples
Strategy Samples
Section titled “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.
Moving Average Crossover Strategy
Section titled “Moving Average Crossover Strategy”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
Features
Section titled “Features”- 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
Quick Start
Section titled “Quick Start”- Copy the strategy code below
- Paste into TradingView Pine Script editor
- Configure your webhook settings
- Select your preferred platform (TraderPost or Algo Trade Analytics)
- Adjust MA lengths and risk parameters as needed
Strategy Code
Section titled “Strategy Code”//@version=5strategy("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 formatcreateEntryAlert(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 settingsi_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 functionstimeInRange() => 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 functioncalcMA(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 crossoverlongExitCondition = strategy.position_size > 0 and ta.crossunder(fastMA, slowMA)shortExitCondition = strategy.position_size < 0 and ta.crossover(fastMA, slowMA)
// ==================// STRATEGY LOGIC// ==================// Entry logicif 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 logicif 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 MAsplot(fastMA, "Fast MA", color=color.blue, linewidth=2)plot(slowMA, "Slow MA", color=color.red, linewidth=2)
// Plot entry signalsplotshape( 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 signalsplotshape( 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 positionsbgcolor(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)Configuration Guide
Section titled “Configuration Guide”Webhook Setup
Section titled “Webhook Setup”- Select Platform: Choose between “TraderPost” or “Algo Trade Analytics” in the Webhook Platform dropdown
- Auth Key: Enter your webhook authentication key
- Account ID: Set your default trading account ID
- Quantity: Specify the number of shares/units to trade
- Extended Hours: Enable if you want to trade outside regular hours
Strategy Parameters
Section titled “Strategy Parameters”- 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
Time Filtering
Section titled “Time Filtering”- 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
Key Features Explained
Section titled “Key Features Explained”Dual Platform Support
Section titled “Dual Platform Support”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
Risk Management
Section titled “Risk Management”- 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
Visual Feedback
Section titled “Visual Feedback”- 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
Customization Tips
Section titled “Customization Tips”- Adjust MA Lengths: Try different combinations for your timeframe
- Risk Parameters: Modify stop loss and take profit percentages
- Time Filtering: Set specific trading hours for your strategy
- Platform Selection: Switch between platforms without code changes
Next Steps
Section titled “Next Steps”- Test the strategy on historical data
- Adjust parameters based on your trading style
- Add additional indicators or conditions
- Implement position sizing rules
- Add more sophisticated exit conditions
This sample provides a solid foundation for building more complex strategies while maintaining clean, professional code structure.