本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// BOCS Channel Scalper - Strategy Version
//@version=6
strategy("BOCS Channel Scalper Strategy", "BOCS-Strat", overlay=true, max_boxes_count=500, max_lines_count=500, default_qty_type=strategy.fixed, default_qty_value=1)
import TradingView/ta/10
// ============================================================================
// INPUTS - POSITION SIZING
// ============================================================================
qty_type = input.string("Fixed Contracts", "Position Size Type", options=["Fixed Contracts", "% of Equity", "Cash Amount"], group="Position Sizing")
fixed_contracts = input.int(1, "Number of Contracts", minval=1, group="Position Sizing", tooltip="Number of contracts/shares to trade")
equity_pct = input.float(10.0, "% of Equity", minval=1, maxval=100, step=1, group="Position Sizing", tooltip="Percentage of equity to risk per trade")
cash_amount = input.float(10000, "Cash Amount ($)", minval=100, step=100, group="Position Sizing", tooltip="Dollar amount to trade per position")
// ============================================================================
// INPUTS - CHANNEL SETTINGS
// ============================================================================
overlap = input.bool(false, "Nested Channels", group="Channel Settings")
length_ = input.int(100, "Normalization Length", minval=1, group="Channel Settings")
length = input.int(14, "Box Detection Length", minval=1, group="Channel Settings")
// ============================================================================
// INPUTS - SCALPING SETTINGS
// ============================================================================
enable_long = input.bool(true, "Enable Long Scalps", group="Scalping Settings")
enable_short = input.bool(true, "Enable Short Scalps", group="Scalping Settings")
entry_zone_pct = input.float(0.2, "Entry Zone % from Edge", minval=0.05, maxval=0.5, step=0.05, group="Scalping Settings")
sl_offset_ticks = input.int(5, "SL Offset (Ticks)", minval=1, group="Scalping Settings")
cooldown_bars = input.int(0, "Cooldown Period (Bars)", minval=0, group="Scalping Settings", tooltip="Minimum bars between signals. 0 = no cooldown")
// ATR Filter
use_atr_filter = input.bool(false, "Enable ATR Filter", group="ATR Filter")
atr_timeframe = input.timeframe("1", "ATR Timeframe", group="ATR Filter", tooltip="Timeframe for ATR calculation (e.g., 1, 5, 15)")
atr_length = input.int(14, "ATR Length", minval=1, group="ATR Filter")
atr_min_value = input.float(10.0, "Min ATR Value", minval=0.1, step=0.5, group="ATR Filter", tooltip="Only trade if ATR is above this value")
// TP Method Selection
tp_method = input.string("Fixed Points", "TP Method", options=["Fixed Points", "% of Channel"], group="Take Profit Settings")
tp_fixed_ticks = input.int(30, "TP Fixed (Ticks)", minval=1, group="Take Profit Settings")
tp_channel_pct = input.float(0.5, "TP % of Channel", minval=0.1, maxval=1.0, step=0.1, group="Take Profit Settings")
// ============================================================================
// INPUTS - APPEARANCE
// ============================================================================
show_zones = input.bool(true, "Show Entry Zones", group="Appearance")
show_info_table = input.bool(true, "Show Info Table", group="Appearance")
table_position = input.string("Top Right", "Table Position", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group="Appearance")
long_color = input.color(#00ffbb, "Long Color", group="Appearance")
short_color = input.color(#ff1100, "Short Color", group="Appearance")
tp_color = input.color(color.green, "TP Color", group="Appearance")
sl_color = input.color(color.red, "SL Color", group="Appearance")
// ============================================================================
// VARIABLES
// ============================================================================
var boxes = array.new_box()
var boxes_u = array.new_box()
var boxes_l = array.new_box()
var line[] centerLines = array.new<line>()
var string lastSignalType = "None"
var float lastEntryPrice = na
var float lastTPPrice = na
var float lastSLPrice = na
var int lastLongBar = na
var int lastShortBar = na
// ============================================================================
// FUNCTIONS
// ============================================================================
f_can_create(float tNew, float bNew) =>
ok = true
if array.size(boxes) > 0
for j = 0 to array.size(boxes)-1
boxObj = array.get(boxes, j)
if (tNew > box.get_bottom(boxObj)) and (bNew < box.get_top(boxObj))
ok := false
break
ok
getTablePosition(pos) =>
switch pos
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.top_right
// ============================================================================
// CHANNEL CALCULATIONS
// ============================================================================
lowestLow = ta.lowest(low, length_)
highestHigh = ta.highest(high, length_)
normalizedPrice = (close - lowestLow) / (highestHigh - lowestLow)
vol = ta.stdev(normalizedPrice, 14)
upper = (ta.highestbars(vol, length + 1) + length)/length
lower = (ta.lowestbars(vol, length + 1) + length)/length
duration = math.max(nz(ta.barssince(ta.crossover(lower, upper))), 1)
h = ta.highest(duration)
l = ta.lowest(duration)
vola = ta.atr(length)/2
bool newChannelFormed = false
bool longScalpSignal = false
bool shortScalpSignal = false
// Get ATR from specified timeframe
float atr_value = request.security(syminfo.tickerid, atr_timeframe, ta.atr(atr_length))
// Check if ATR filter allows trading
bool atrOK = not use_atr_filter or (atr_value >= atr_min_value)
// Form new channels
if ta.crossover(upper, lower) and duration > 10
if overlap or f_can_create(h, l)
array.unshift(boxes, box.new(bar_index-duration, h, bar_index, l, bgcolor=color.new(chart.fg_color, 90), border_color=na))
array.unshift(boxes_u, box.new(bar_index-duration, h, bar_index, h-vola, bgcolor=color.new(short_color, 70), border_color=na))
array.unshift(boxes_l, box.new(bar_index-duration, l+vola, bar_index, l, bgcolor=color.new(long_color, 70), border_color=na))
float centerY = (h + l) / 2
array.unshift(centerLines, line.new(bar_index-duration, centerY, bar_index, centerY, color=color.new(chart.fg_color, 50), width=1, style=line.style_dashed))
newChannelFormed := true
// ============================================================================
// STRATEGY LOGIC
// ============================================================================
// Calculate position size based on user selection
float position_size = fixed_contracts
if qty_type == "% of Equity"
position_size := (strategy.equity * equity_pct / 100) / close
else if qty_type == "Cash Amount"
position_size := cash_amount / close
if array.size(boxes) > 0
for i = 0 to array.size(boxes)-1
boxObj = array.get(boxes, i)
boxObjU = array.get(boxes_u, i)
boxObjL = array.get(boxes_l, i)
centerLineObj = array.get(centerLines, i)
float topBound = box.get_top(boxObj)
float bottomBound = box.get_bottom(boxObj)
float channelRange = topBound - bottomBound
float entryZoneSize = channelRange * entry_zone_pct
// Define entry zones
float longEntryZone = bottomBound + entryZoneSize
float shortEntryZone = topBound - entryZoneSize
// Check for breakout (remove channel) - only on strong breaks
bool breakout = false
if close > topBound + (syminfo.mintick * 10) or close < bottomBound - (syminfo.mintick * 10)
breakout := true
if breakout
array.remove(boxes, i)
array.remove(boxes_u, i)
array.remove(boxes_l, i)
array.remove(centerLines, i)
break
else
// Update channel visuals
box.set_right(boxObj, bar_index)
box.set_right(boxObjU, bar_index)
box.set_right(boxObjL, bar_index)
line.set_x2(centerLineObj, bar_index)
// LONG ENTRY
bool longCooldownOK = cooldown_bars == 0 or na(lastLongBar) or (bar_index - lastLongBar) >= cooldown_bars
if enable_long and low <= longEntryZone and longCooldownOK and atrOK and strategy.position_size == 0
longScalpSignal := true
lastSignalType := "LONG"
lastLongBar := bar_index
// Calculate TP/SL
entry_price = longEntryZone
sl_price = bottomBound - (sl_offset_ticks * syminfo.mintick)
float tp_price = na
if tp_method == "Fixed Points"
tp_price := entry_price + (tp_fixed_ticks * syminfo.mintick)
else
tp_price := entry_price + (channelRange * tp_channel_pct)
// Store for table display
lastEntryPrice := entry_price
lastTPPrice := tp_price
lastSLPrice := sl_price
// Execute strategy entry
strategy.entry("Long", strategy.long, qty=position_size)
strategy.exit("Long Exit", "Long", stop=sl_price, limit=tp_price)
// SHORT ENTRY
bool shortCooldownOK = cooldown_bars == 0 or na(lastShortBar) or (bar_index - lastShortBar) >= cooldown_bars
if enable_short and high >= shortEntryZone and shortCooldownOK and atrOK and strategy.position_size == 0
shortScalpSignal := true
lastSignalType := "SHORT"
lastShortBar := bar_index
// Calculate TP/SL
entry_price = shortEntryZone
sl_price = topBound + (sl_offset_ticks * syminfo.mintick)
float tp_price = na
if tp_method == "Fixed Points"
tp_price := entry_price - (tp_fixed_ticks * syminfo.mintick)
else
tp_price := entry_price - (channelRange * tp_channel_pct)
// Store for table display
lastEntryPrice := entry_price
lastTPPrice := tp_price
lastSLPrice := sl_price
// Execute strategy entry
strategy.entry("Short", strategy.short, qty=position_size)
strategy.exit("Short Exit", "Short", stop=sl_price, limit=tp_price)
// Show entry zones if enabled
if show_zones
box.set_text(boxObjL, "LONG ZONE ▲")
box.set_text_color(boxObjL, color.new(long_color, 0))
box.set_text_size(boxObjL, size.small)
box.set_text(boxObjU, "SHORT ZONE ▼")
box.set_text_color(boxObjU, color.new(short_color, 0))
box.set_text_size(boxObjU, size.small)
// ============================================================================
// VISUALS
// ============================================================================
plotshape(longScalpSignal, "Long Scalp Signal", shape.labelup, location.belowbar, long_color, text="LONG", textcolor=chart.fg_color, size=size.small)
plotshape(shortScalpSignal, "Short Scalp Signal", shape.labeldown, location.abovebar, short_color, text="SHORT", textcolor=chart.fg_color, size=size.small)
// Plot TP/SL levels
plot(strategy.position_size != 0 and not na(lastTPPrice) ? lastTPPrice : na, "Take Profit", tp_color, 1, plot.style_linebr)
plot(strategy.position_size != 0 and not na(lastSLPrice) ? lastSLPrice : na, "Stop Loss", sl_color, 1, plot.style_linebr)
plot(strategy.position_size != 0 and not na(lastEntryPrice) ? lastEntryPrice : na, "Entry", color.white, 2, plot.style_linebr)
// ============================================================================
// INFO TABLE
// ============================================================================
if show_info_table
var infoTable = table.new(position=getTablePosition(table_position), columns=2, rows=8, bgcolor=color.new(chart.bg_color, 10), border_width=1)
// Clear table
table.clear(infoTable, 0, 0, 1, 7)
// Header
table.cell(infoTable, 0, 0, "BOCS STRATEGY", text_color=chart.fg_color, text_size=size.normal, bgcolor=color.new(chart.fg_color, 80))
table.cell(infoTable, 1, 0, "", bgcolor=color.new(chart.fg_color, 80))
table.merge_cells(infoTable, 0, 0, 1, 0)
// Position Status
string posStatus = strategy.position_size > 0 ? "LONG" : strategy.position_size < 0 ? "SHORT" : "No Position"
color posColor = strategy.position_size > 0 ? long_color : strategy.position_size < 0 ? short_color : color.gray
table.cell(infoTable, 0, 1, "Position:", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 1, posStatus, text_color=posColor, text_size=size.small)
// Channel Status
bool channelActive = array.size(boxes) > 0
string channelStatus = channelActive ? "Active" : "No Channel"
color channelColor = channelActive ? color.yellow : color.gray
table.cell(infoTable, 0, 2, "Channel:", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 2, channelStatus, text_color=channelColor, text_size=size.small)
// Last Signal
color signalColor = lastSignalType == "LONG" ? long_color : lastSignalType == "SHORT" ? short_color : color.gray
table.cell(infoTable, 0, 3, "Last Signal:", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 3, lastSignalType, text_color=signalColor, text_size=size.small)
// Entry Price
string entryText = na(lastEntryPrice) ? "N/A" : str.tostring(lastEntryPrice)
table.cell(infoTable, 0, 4, "Entry:", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 4, entryText, text_color=color.white, text_size=size.small)
// TP Price
string tpText = na(lastTPPrice) ? "N/A" : str.tostring(lastTPPrice)
table.cell(infoTable, 0, 5, "Take Profit:", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 5, tpText, text_color=tp_color, text_size=size.small)
// SL Price
string slText = na(lastSLPrice) ? "N/A" : str.tostring(lastSLPrice)
table.cell(infoTable, 0, 6, "Stop Loss:", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 6, slText, text_color=sl_color, text_size=size.small)
// ATR Status
if use_atr_filter
string atrText = str.tostring(math.round(atr_value, 2))
color atrColor = atr_value >= atr_min_value ? color.green : color.red
string atrStatus = atr_value >= atr_min_value ? atrText + " ✓" : atrText + " ✗"
table.cell(infoTable, 0, 7, "ATR (" + atr_timeframe + "):", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 7, atrStatus, text_color=atrColor, text_size=size.small)
else
table.cell(infoTable, 0, 7, "ATR Filter:", text_color=chart.fg_color, text_size=size.small)
table.cell(infoTable, 1, 7, "Disabled", text_color=color.gray, text_size=size.small)