本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=5
//@Kveie
strategy('3C QFL Mean reversal', shorttitle='3C QFL', pyramiding=999, calc_on_every_tick=false, default_qty_type=strategy.percent_of_equity, default_qty_value=1, initial_capital=1000, commission_value = 0.04, slippage = 2, overlay=true)
f_secureSecurity(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[1], lookahead=barmerge.lookahead_on)
import jason5480/time_filters/1 as tif
// 📆📈 FILTERS =====================================================================================================
// Description: Module responsible for filtering out long and short open signals that do not meet user defined rules
// Dependencies: NONE
// Results: longFiltersApproval, shortFiltersApproval
// INPUT ============================================================================================================
show_table = input(true, title='Show table')
text_size_switch = input(true, title='Small text in the table')
usefromDate = input.bool(defval = true, title = 'From', inline = 'From Date', group = '📆 Filters - Time')
fromDate = input.time(defval = timestamp('01 Jan 2022 00:00 UTC'), title = '', inline = 'From Date', group = '📆 Filters - Time')
usetoDate = input.bool(defval = false, title = 'To ', inline = 'To Date', group = '📆 Filters - Time')
toDate = input.time(defval = timestamp('31 Dec 2121 23:59 UTC'), title = '', inline = 'To Date', group = '📆 Filters - Time')
useSessionDay = input.bool(defval = false, title = 'Session Days', inline = 'Session Days', group = '📆 Filters - Time')
mon = input.bool(defval = true, title = 'Mon', inline = 'Session Days', group = '📆 Filters - Time')
tue = input.bool(defval = true, title = 'Tue', inline = 'Session Days', group = '📆 Filters - Time')
wed = input.bool(defval = true, title = 'Wed', inline = 'Session Days', group = '📆 Filters - Time')
thu = input.bool(defval = true, title = 'Thu', inline = 'Session Days', group = '📆 Filters - Time')
fri = input.bool(defval = true, title = 'Fri', inline = 'Session Days', group = '📆 Filters - Time')
sat = input.bool(defval = true, title = 'Sat', inline = 'Session Days', group = '📆 Filters - Time')
sun = input.bool(defval = true, title = 'Sun', inline = 'Session Days', group = '📆 Filters - Time')
useSessionStart = input.bool(defval = false, title = 'Session Start', inline = 'Session Start', group = '📆 Filters - Time')
sessionStartHour = input.int(defval = 12, title = '', minval = 0, maxval = 23, step = 1, inline = 'Session Start', group = '📆 Filters - Time')
sessionStartMinute = input.int(defval = 00, title = ':', minval = 0, maxval = 59, step = 1, tooltip = 'Start time of the session.', inline = 'Session Start', group = '📆 Filters - Time')
useSessionEnd = input.bool(defval = false, title = 'Session End', inline = 'Session End', group = '📆 Filters - Time')
sessionEndHour = input.int(defval = 20, title = '', minval = 0, maxval = 23, step = 1, inline = 'Session End', group = '📆 Filters - Time')
sessionEndMinute = input.int(defval = 00, title = ':', minval = 0, maxval = 59, step = 1, tooltip = 'End time of the session.', inline = 'Session End', group = '📆 Filters - Time')
bool dateFilterApproval = tif.is_in_date_range(fromDate, toDate, usefromDate, usetoDate)
bool sessionFilterApproval = tif.is_in_session(useSessionStart, sessionStartHour, sessionStartMinute, useSessionEnd, sessionEndHour, sessionEndMinute, useSessionDay, mon, tue, wed, thu, fri, sat, sun)
bool timeFilterApproval = dateFilterApproval and sessionFilterApproval
var g_strategy = "Strategy"
i_chkLong = input.bool(true, title = 'Long', inline ='1', group = g_strategy)
i_chkShort = input.bool(true, title = 'Short', inline='1', group= g_strategy)
tf = input.timeframe(title='QFL timeframe', defval='current', tooltip='Do not select a timeframe below the current timeframe (example: if the chart is in 15m do no select 5m in this option, you can select 30m or higher TFs).')
vamp = input(title='QFL volume MA', defval=6)
maxbaseage = input.int(0, 'Max candle age', tooltip='It won\'t open a deal if the price is below a base that has lived for longer than X candles. Use 0 to disable this condition.')
allowConsecutiveSignals = input.bool(false, 'Allow consecutive signals', tooltip='If the conditions are met in to consecutive candles, allow both to trigger the signal and not only the first candle.')
plotSignal = input(true, 'plot signal')
plotLevels = input(true, 'plot bases')
// Strategy Inputs
// Long
var g_long = "Long"
percentage = input.float(0.5, step=0.1, group= g_long, title='QFL percentage to buy', tooltip='When the price falls below the current base this percentage a buy signal will be triggered.')
price_deviation = input.float(0.5, group= g_long, step=0.1, title='Price deviation to open safety orders (%)', minval=0.0) / 100
take_profit = input.float(1.2, group= g_long, step=0.1, title='Target Take Profit (%)', step=0.1, minval=0.0) / 100
base_order = input(10, title='base order', group= g_long)
safe_order = input(20, title='safe order', group= g_long)
safe_order_volume_scale = input.float(2, step=0.1, title='SO volume scale', group= g_long)
safe_order_step_scale = input.float(2, step=0.1, title='SO step scale', group= g_long)
max_safe_order = input(4, title='max no. of safe orders', group= g_long)
// Short
var g_short = "Short"
percentageSell = input.float(0.5, step=0.1, group= g_short, title='QFL percentage to sell', tooltip='When the price goes above the current base this percentage a sell signal will be triggered.')
price_S_deviation = input.float(0.5, group= g_short, title='Price deviation to open short safety orders (%)', step=0.1, minval=0.0) / 100
take_S_profit = input.float(1.2, group= g_short, title='Short Target Take Profit (%)', step=0.1, minval=0.0) / 100
base_S_order = input(10, group= g_short, title='base sell order')
safe_S_order = input(20, group= g_short, title='safe sell order')
safe_S_order_volume_scale = input.float(2, step=0.1, group= g_short, title='Safety sell order volume scale')
safe_S_order_step_scale = input.float(2, step=0.1, group= g_short, title='Safety sell order step scale')
max_S_safe_order = input(4, group= g_short, title='max no. of sell safe orders')
// QFL magic
vam = ta.sma(volume, vamp)
up = high[3] > high[4] and high[4] > high[5] and high[2] < high[3] and high[1] < high[2] and volume[3] > vam[3]
down = low[3] < low[4] and low[4] < low[5] and low[2] > low[3] and low[1] > low[2] and volume[3] > vam[3]
// we need to use functions so we don't upset security. In pine 4 you can only pass unmutable values to security!
fractaldownF() =>
fd = 0.0
fd := down ? low[3] : nz(fd[1])
fd
fractalupF() =>
fu = 0.0
fu := up ? high[3] : nz(fu[1])
fu
fuptf = f_secureSecurity(syminfo.tickerid, tf == 'current' ? timeframe.period : tf, fractalupF())
fdowntf = f_secureSecurity(syminfo.tickerid, tf == 'current' ? timeframe.period : tf, fractaldownF())
plot(fuptf, 'FractalUp', color=color.new(color.lime, plotLevels ? 0 : 100), linewidth=1, style=plot.style_cross, offset=-3, join=false)
plot(fdowntf, 'FractalDown', color=color.new(color.red, plotLevels ? 0 : 100), linewidth=1, style=plot.style_cross, offset=-3, join=false)
// bars since
age = ta.barssince(fuptf != fuptf[1])
agecond = maxbaseage == 0 or age < maxbaseage
buy = 100 * (close / fdowntf) < 100 - percentage and agecond
sell = 100 * (close / fuptf) > 100 + percentageSell and agecond
signal = buy and (allowConsecutiveSignals or not buy[1] or fdowntf != fdowntf[1])
sellSignal = sell and (allowConsecutiveSignals or not sell[1] or fuptf != fuptf[1])
plotshape(signal and plotSignal, title='B', text='B', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.new(color.blue, 0), textcolor=color.new(color.white, 0))
plotshape(sellSignal and plotSignal, title='S', text='S', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
source_type = input.string('Close', 'Source', options=['Close', 'Open', 'High', 'Low', 'HL2', 'HLC3', 'OHLC4', 'Median Body', 'Weighted Close', 'Trend Biased', 'Trend Biased Extreme'])
source_function(type) =>
if type == 'Close'
close
else if type == 'Open'
open
else if type == 'High'
high
else if type == 'Low'
low
else if type == 'HL2'
hl2
else if type == 'HL3'
hlc3
else if type == 'OHLC4'
ohlc4
else if type == 'Median Body'
(open + close) / 2
else if type == 'Weighted Close'
(high + low + 2 * close) / 4
else if type == 'Trend Biased'
close > open ? (high + close) / 2 : (low + close) / 2
else if type == 'Trend Biased Extreme'
close > open ? high : low
truncate(number, decimals) =>
factor = math.pow(10, decimals)
int(number * factor) / factor
var long = true
var short = true
var current_so = 0
var current_S_so = 0
var initial_order = 0.0
var initial_S_order = 0.0
var original_ttp_value = 0.0
var quantity = 0.0
var entry_price = 0.0
var firstBarTime = 0.0
var maxDiffDays = 0.0
var soCount = 0
var SO1 = 0
var SO2 = 0
var SO3 = 0
var SO4 = 0
var SO5 = 0
var SO6 = 0
var SO7 = 0
var noSO = 0
var initial_price = 0.0
var initial_S_price = 0.0
var price_drop = 0.0
var price_pump = 0.0
var max_drop = 0.0
var max_pump = 0.0
var pump_date = 0
var pump_month = 0
var drop_date = 0
var drop_month = 0
var longest_trade_day = 0
var longest_trade_month = 0
var take_profit_level = 0.0
var take_S_profit_level = 0.0
var tp_plot = 0.0
var tp_S_plot = 0.0
var threshold = 0.0
var S_threshold = 0.0
timeDiff = time - firstBarTime
maxDev = 0.0
maxSDev = 0.0
closedTrades = 0
var tradeCount = 0
var i = 0
var avg_price = 0.0
var total_funds_in_trade = 0.0
var total_qty_in_trade = 0.0
var capital = 100.0
// Turn that time difference into days
diffDays = timeDiff / 86400000
// Calculate our TP levels
take_profit_level := avg_price * (1 + take_profit)
take_S_profit_level := avg_price * (1 - take_S_profit)
// First Position
for i = 0 to max_safe_order - 1 by 1
maxDev := int((maxDev + price_deviation * 100 * math.pow(safe_order_step_scale, i)) * 100) / 100
maxDev
for i = 0 to max_S_safe_order - 1 by 1
maxSDev := int((maxSDev + price_S_deviation * 100 * math.pow(safe_S_order_step_scale, i)) * 100) / 100
maxSDev
// Get strategy direction and set time
strategy.risk.allow_entry_in(i_chkLong and i_chkShort ? strategy.direction.all : i_chkLong ? strategy.direction.long : strategy.direction.short)
strategy.close_all(math.abs(strategy.position_size) != 0 and current_so[1] == 0)
bool longFiltersApproval = signal and timeFilterApproval and i_chkLong
bool shortFiltersApproval = sellSignal and timeFilterApproval and i_chkShort
if long and strategy.position_size == 0 and source_function(source_type) > 0 and longFiltersApproval
strategy.entry('Long' + str.tostring(source_function(source_type)), strategy.long, qty=strategy.equity * base_order / 100 / source_function(source_type))
initial_order := source_function(source_type)
current_so := 1
initial_price := close
price_drop := close
original_ttp_value := 0
firstBarTime := time
tradeCount += 1
avg_price := close
total_funds_in_trade := avg_price * base_order
total_qty_in_trade := base_order
total_qty_in_trade
else if short and strategy.position_size == 0 and source_function(source_type) > 0 and shortFiltersApproval
strategy.entry('Short' + str.tostring(source_function(source_type)), strategy.short, qty=strategy.equity * base_S_order / 100 / source_function(source_type))
initial_S_order := source_function(source_type)
current_so := 1
firstBarTime := time
tradeCount += 1
initial_S_price := close
price_pump := close
avg_price := close
total_funds_in_trade := avg_price * base_S_order
total_qty_in_trade := base_S_order
total_qty_in_trade
Long = ' { "message_type": "bot", "bot_id": 1234567, "email_token": "your-email-token-from-3commas", "delay_seconds": 1} ' //start long deal
Short = ' { "message_type": "bot", "bot_id": 7654321, "email_token": "your-email-token-from-3commas", "delay_seconds": 1} ' // start short deal
//makes the red and green line plot pretty at the position opening
if strategy.position_size == 0
threshold := low[1]
S_threshold := high[1]
S_threshold
//Safety order levels
//Long
if strategy.position_size > 0 and i == 0
if safe_order_step_scale == 1.0
threshold := initial_order - initial_order * price_deviation * safe_order_step_scale * current_so
threshold
else
threshold := initial_order - initial_order * (price_deviation * (math.pow(safe_order_step_scale, current_so) - 1) / (safe_order_step_scale - 1))
threshold
//Short
else if strategy.position_size < 0 and i == 0
if safe_S_order_step_scale == 1.0
S_threshold := initial_S_order * (1 + price_S_deviation * current_so)
S_threshold
else
S_threshold := initial_S_order * (1 + price_S_deviation * (math.pow(safe_S_order_step_scale, current_so) - 1) / (safe_S_order_step_scale - 1))
S_threshold
// Average Down
if current_so > 0 and i == 0 and strategy.position_size > 0 and low <= threshold and current_so <= max_safe_order
strategy.entry('SO ' + str.tostring(current_so) + '@' + str.tostring(source_function(source_type)), strategy.long, qty=strategy.equity * safe_order / 100 * math.pow(safe_order_volume_scale, current_so - 1) / source_function(source_type))
total_funds_in_trade += threshold * safe_order * math.pow(safe_order_volume_scale, current_so - 1)
total_qty_in_trade += safe_order * math.pow(safe_order_volume_scale, current_so - 1)
avg_price := total_funds_in_trade / total_qty_in_trade
current_so += 1
tradeCount += 1
tradeCount
// Short Average Up
if current_so > 0 and i == 0 and strategy.position_size < 0 and high >= S_threshold and current_so <= max_S_safe_order
strategy.entry('SSO ' + str.tostring(current_so) + '@' + str.tostring(source_function(source_type)), strategy.short, qty=strategy.equity * safe_S_order / 100 * math.pow(safe_S_order_volume_scale, current_so - 1) / source_function(source_type))
total_funds_in_trade += S_threshold * safe_S_order * math.pow(safe_S_order_volume_scale, current_so - 1)
total_qty_in_trade += safe_S_order * math.pow(safe_S_order_volume_scale, current_so - 1)
avg_price := total_funds_in_trade / total_qty_in_trade
current_so += 1
tradeCount += 1
tradeCount
// Take Profit!
if i == 1
strategy.close_all()
i := 0
i
if take_profit_level <= high and strategy.position_size > 0
strategy.close_all(comment='Close @' + str.tostring(source_function(source_type)))
soCount := current_so
current_so := 0
original_ttp_value := 0
price_drop := na
initial_price := na
diffDays := time - firstBarTime
if diffDays > maxDiffDays
maxDiffDays := diffDays
longest_trade_day := dayofmonth
longest_trade_month := month
longest_trade_month
i := 1
initial_order := 0.0
avg_price := na
capital *= (1 + total_qty_in_trade * take_profit / 100)
capital
// Take Short Profit!
if take_S_profit_level >= low and strategy.position_size < 0
strategy.close_all(comment='Close Short @' + str.tostring(source_function(source_type)))
soCount := current_so
current_so := 0
price_pump := na
initial_S_price := na
diffDays := time - firstBarTime
if diffDays > maxDiffDays
maxDiffDays := diffDays
maxDiffDays
initial_S_order := 0.0
avg_price := na
capital *= (1 + total_qty_in_trade * take_S_profit / 100)
capital
//Table building and calculations
if strategy.position_size == 0
if soCount == 1
noSO += 1
noSO
else if soCount == 2
SO1 += 1
SO1
else if soCount == 3
SO2 += 1
SO2
else if soCount == 4
SO3 += 1
SO3
else if soCount == 5
SO4 += 1
SO4
else if soCount == 6
SO5 += 1
SO5
else if soCount == 7
SO6 += 1
SO6
else if soCount == 8
SO7 += 1
SO7
soCount := 0
soCount
closedTrades := noSO + SO1 * 2 + SO2 * 3 + SO3 * 4 + SO4 * 5 + SO5 * 6 + SO6 * 7 + SO7 * 8
if low < price_drop and timeFilterApproval and strategy.position_size > 0
price_drop := low
if max_drop < int((1 - price_drop / initial_price) * 10000) / 100
max_drop := int((1 - price_drop / initial_price) * 10000) / 100
drop_date := dayofmonth(time)
drop_month := month(time)
drop_month
bgcolor(max_drop[1] < max_drop ? color.aqua : na, transp=50)
if high > price_pump and timeFilterApproval and strategy.position_size < 0
price_pump := high
if max_pump < int((price_pump / initial_S_price - 1) * 10000) / 100
max_pump := int((price_pump / initial_S_price - 1) * 10000) / 100
pump_date := dayofmonth(time)
pump_month := month(time)
pump_month
bgcolor(max_pump[1] < max_pump ? color.purple : na, transp=70)
if take_profit_level > 0 and strategy.position_size > 0
tp_plot := take_profit_level
tp_plot
else
tp_plot := close
tp_plot
if take_S_profit_level > 0 and strategy.position_size < 0
tp_S_plot := take_S_profit_level
tp_S_plot
else
tp_S_plot := close
tp_S_plot
//Plotting the levels
p1 = plot(strategy.position_size > 0 ? tp_plot : na, style=plot.style_linebr, color=#00f0f0, linewidth=1, title="Long Take Profit")
p2 = plot(strategy.opentrades>0 ? avg_price : na, style=plot.style_linebr, color=color.white, linewidth=1, title="Entry")
p3 = plot(threshold, color = strategy.position_size <=0 ? na : #00f0f0)
p4 = plot(strategy.position_size < 0 ? tp_S_plot : na, style=plot.style_linebr, color=#00f0f0, linewidth=1, title="Short Take Profit")
p5 = plot(S_threshold, color = strategy.position_size >= 0 ? na : #00f0f0)
//PLOT FIXED SLTP LINE
fill(p1, p2, color=strategy.position_size > 0 ? color.new(#1fff00,75) : na)
fill(p2, p3, strategy.position_size > 0 ? color.new(#fe0a0a,75) : na)
fill(p4, p2, color=strategy.position_size < 0 ? color.new(#1fff00,75) : na)
fill(p5, p2, color=strategy.position_size < 0 ? color.new(#fe0a0a,75) : na)
profit_color = strategy.openprofit < 0 ? color.red : color.green
// plot(strategy.opentrades)
// plot(current_so, color = color.yellow)
// plot(abs(strategy.position_size), color = color.red)
// plot(quantity, color=color.purple)
text_size = text_size_switch ? size.small : size.normal
//Table formatting
if show_table
var Table = table.new(position.top_right, columns=2, rows=20, border_width=1, bgcolor=color.black, border_color=color.gray)
table.cell(table_id=Table, column=0, row=0, text_color=color.gray, text_size=text_size, text='Net Profit')
table.cell(table_id=Table, column=1, row=0, text=str.tostring(int((capital - 100) * 100) / 100) + '%', text_size=text_size, text_color=color.lime)
table.cell(table_id=Table, column=0, row=1, text_color=color.gray, text_size=text_size, text='Max Deviation ')
table.cell(table_id=Table, column=1, row=1, text=str.tostring(maxDev) + '%', text_size=text_size, text_color=color.orange)
table.cell(table_id=Table, column=0, row=2, text_color=color.gray, text_size=text_size, text='Max Short Dev ')
table.cell(table_id=Table, column=1, row=2, text=str.tostring(maxSDev) + '%', text_size=text_size, text_color=color.orange)
table.cell(table_id=Table, column=0, row=3, text='No SO ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=3, text=str.tostring(noSO), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=4, text='SO 1 ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=4, text=str.tostring(SO1), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=5, text='SO 2 ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=5, text=str.tostring(SO2), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=6, text='SO 3 ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=6, text=str.tostring(SO3), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=7, text='SO 4 ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=7, text=str.tostring(SO4), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=8, text='SO 5 ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=8, text=str.tostring(SO5), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=9, text='SO 6 ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=9, text=str.tostring(SO6), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=10, text='SO 7 ', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=10, text=str.tostring(SO7), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=11, text='Closed/Open trades', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=11, text=str.tostring(strategy.closedtrades) + '/' + str.tostring(strategy.opentrades), text_size=text_size, text_color=color.olive)
table.cell(table_id=Table, column=0, row=12, text='Current Deal Time', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=12, text=strategy.position_size != 0 ? str.tostring(int((time - firstBarTime) / 8640000) / 10) + ' days' : '0', text_size=text_size, text_color=color.green)
table.cell(table_id=Table, column=0, row=13, text='Unrealized position', text_size=text_size, text_color=color.gray)
table.cell(table_id=Table, column=1, row=13, text=str.tostring(int(strategy.openprofit / (strategy.initial_capital + strategy.netprofit) * 10000) / 100) + ' %', text_size=text_size, text_color=profit_color)
table.cell(table_id=Table, column=0, row=14, text='Longest deal:', text_size=text_size, text_color=color.orange)
table.cell(table_id=Table, column=1, row=14, text=str.tostring(int(maxDiffDays / 8640000) / 10) + ' days, ' + str.tostring(longest_trade_day) + '/' + str.tostring(longest_trade_month), text_size=text_size, text_color=color.red)
table.cell(table_id=Table, column=0, row=15, text='Max price drop:', text_size=text_size, text_color=color.orange)
table.cell(table_id=Table, column=1, row=15, text=str.tostring(max_drop) + ' %, ' + str.tostring(drop_date) + '/' + str.tostring(drop_month), text_size=text_size, text_color=color.red)
table.cell(table_id=Table, column=0, row=16, text='Max price pump:', text_size=text_size, text_color=color.orange)
table.cell(table_id=Table, column=1, row=16, text=str.tostring(max_pump) + ' %, ' + str.tostring(pump_date) + '/' + str.tostring(pump_month), text_size=text_size, text_color=color.red)
// Let's plot 1 for Buy signal so it's compatible with the backtest script
backtestingCompatible = input.bool(false, 'Backtesting compatible', tooltip='Enable this to plot 1 for buys so you can use this indicator with the backtest script.')
plot(backtestingCompatible and signal ? 1 : backtestingCompatible and sellSignal ? 2 : 0, 'QFL signal')