In order to first export an indicator into a library script you must hard code the inputs, before putting it into the export.
Once in the export everything must be indented (or nested, how ever you want to say it)
For example you have an ema crossover
Pine Script®
This without the inputs and the scoring returned looks like this
Pine Script®
Now another thing is you cant have global variable functions inside of the main export function.
This would be like say you want to smooth your indicator with an exponential hull moving average.
So you put your EHMA function outside of the export like the following:
Pine Script®
If, on the rare occasion the indicator is just entirely a function, this is how you would do it
Pine Script®
There really isn't much complexity added when starting with these, there is just a few key things you need to learn, then if you have issues it just becomes problem solving.
Now in order to call these libraries out, you need to ensure your return is what you want, like the code above its returning a score of 1 or -1.
To bring it in, Publish, copy the import, give it an alias like trend or something (i think alias is the word)
e.gPine Script®
Call it really simplyPine Script®
IF you have a function, or indicator with arrays, its best to keep that in the main script since, there has been too many problems with them, trying to get the exact same values as the strategy not inside of a library script.
If you needPine Script® inside of the script, or you want to be able to change inputs, simply put it inside of the export function()
Like soPine Script®
When its called out,Pine Script®
This is simple, its good to have if you are going to tweak the inputs of the strategy later on, due to alpha decay etc, make sure your strat isnt overfit in the first place, and its capturing clear trends. Test on many assets to ensure its not liquidated.
To show you a full strategy example
Pine Script®
As you can see the VZO is defined outside and the miningRevenue and 365 moving average is in the export function.
In simple terms,
1. Take away inputs
2. indent in export
3. Get a score, or whatever you want out of it defined
4. put a return at the bottom
5. publish
Once in the export everything must be indented (or nested, how ever you want to say it)
For example you have an ema crossover
//@version=5
indicator("EMA Cross",
overlay = true,
format = format.price,
precision = 2,
timeframe = ""
)
// User Inputs
src = input.source(close, "Calculation Source", group = "CALCULATION")
len1 = input.int(50, "Periods - Ema 1", group = "CALCULATION", inline = "len")
len2 = input.int(100, "Ema 2", group = "CALCULATION", inline = "len")
// Calculation
ema1 = ta.ema(src, len1)
ema2 = ta.ema(src, len2)
// Crossovers
emaL = ema1 >= ema2
emaS = ema1 < ema2
var float crossover = na
if (crossover == 1)
crossover := na
else if (emaL[1] and emaL)
crossover := -1
else if (crossover == -1)
crossover := na
else if (emaS[1] and emaL)
crossover := 1
plot(ema1, "Ema 1", color = (emaL ? #00ff00 : #ff0000), style = plot.style_line, linewidth=1, offset=0)
plot(ema2, "Ema 2", color = (emaL ? #00ff00 : #ff0000), style=plot.style_line, linewidth=2, offset=0)
This without the inputs and the scoring returned looks like this
library("EMA_Cross")
export EMA_Cross() =>
src = close //input.source(close, "Calculation Source", group = "CALCULATION")
len1 = 50 //input.int(50, "Periods - Ema 1", group = "CALCULATION", inline = "len")
len2 = 100 //input.int(100, "Ema 2", group = "CALCULATION", inline = "len")
// Calculation
ema1 = ta.ema(src, len1)
ema2 = ta.ema(src, len2)
// Crossovers
emaL = ema1 >= ema2
emaS = ema1 < ema2
var score = 0.
if emaL
score:=1
if emaS
score:=-1
score // YOU NEED TO HAVE SOMETHING AT THE BOTTOM TO RETURN
Now another thing is you cant have global variable functions inside of the main export function.
This would be like say you want to smooth your indicator with an exponential hull moving average.
So you put your EHMA function outside of the export like the following:
ehma(series float src, simple int len) =>
ehma = ta.ema(2 * ta.ema(src, len / 2) - ta.ema(src, len), math.round(math.sqrt(len)))
ehma
export invehmarsi()=>
len = 14
sublen = 30
ehma = ehma(close, sublen)
rsi = ta.rsi(ehma, len)
stdev = ta.stdev(ehma , sublen)
u = ehma + stdev
d = ehma - stdev
supl = close > d
sups = close < u
L = rsi > 70 and not sups
S = rsi < 55
var score = 0.
if L and not S
score := 1
if S
score := -1
score
If, on the rare occasion the indicator is just entirely a function, this is how you would do it
// @function : Median SuperTrend
// @returns : Returns Score of 1 or -1
subject = 10
mul = 2.35
smooth = ta.percentile_nearest_rank(close, 9, 50)
median_supertrend(mul, atrPeriod) =>
src = smooth
atr = ta.atr(atrPeriod)
u = src + mul * atr
l = src - mul * atr
pl = nz(l[1])
pu = nz(u[1])
l := l > pl or close[1] < pl ? l : pl
u := u < pu or close[1] > pu ? u : pu
int d = na
float st = na
pt = st[1]
if na(atr[1])
d := 1
else if pt == pu
d := close > u ? -1 : 1
else
d := close < l ? 1 : -1
st := d == -1 ? l : u
[st, d]
[x, d] = median_supertrend(mul, subject)
export mst() =>
stl = ta.crossunder(d, 0)
sts = ta.crossover(d, 0)
L = stl
S = sts
var score = 0.
if L and not S
score := 1
if S
score := -1
score
There really isn't much complexity added when starting with these, there is just a few key things you need to learn, then if you have issues it just becomes problem solving.
Now in order to call these libraries out, you need to ensure your return is what you want, like the code above its returning a score of 1 or -1.
To bring it in, Publish, copy the import, give it an alias like trend or something (i think alias is the word)
e.g
import BackQuant/tech/1 as trend
Call it really simply
out = trend.tpi()
IF you have a function, or indicator with arrays, its best to keep that in the main script since, there has been too many problems with them, trying to get the exact same values as the strategy not inside of a library script.
If you need
request.security()
Like so
export bseth(series float miningRevenue,float ma365) =>
When its called out,
bs.bseth(miningRevenue, ma365)
This is simple, its good to have if you are going to tweak the inputs of the strategy later on, due to alpha decay etc, make sure your strat isnt overfit in the first place, and its capturing clear trends. Test on many assets to ensure its not liquidated.
To show you a full strategy example
//@version=5
// @description TODO: add library description here
library("eth_bs")
window = time >= timestamp('2018-01-01')
VZO(length, get_close, vol) =>
Volume_Direction = get_close > get_close[3] ? vol : -vol
VZO_volume = ta.linreg(Volume_Direction, int(length), 0)
Total_volume = ta.linreg(vol, int(length), 0)
100 * VZO_volume / Total_volume
// @returns TODO: add what function returns
export bseth(series float miningRevenue2,float ma3652) =>
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
MACD_group = "MACD"
macdLength = 14
emaLength = 99
signalSMA = 35
[macdLine, signalLine, _] = ta.macd(close, macdLength, emaLength, signalSMA)
MACDLong = ta.crossover(macdLine, signalLine)
MACDShort = ta.crossunder(macdLine, signalLine)
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
DMI_group = "DMI"
DMIlen = 5
DMIthreshold = 22.75
DMIemaLen = 67
DMIupperLevel = 30
DMIlowerLevel = -30
dmiLength = DMIlen
dmiH = high - high[1]
dmiL = low[1] - low
dmiTR = math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
dmiHMA = ta.hma(dmiH, dmiLength)
dmiLMA = ta.hma(dmiL, dmiLength)
dmiTRMA = ta.hma(dmiTR, dmiLength)
dmiPlus = ta.wma(dmiHMA, DMIemaLen) / ta.wma(dmiTRMA, DMIemaLen) * 100
dmiMinus = ta.wma(dmiLMA, DMIemaLen) / ta.wma(dmiTRMA, DMIemaLen) * 100
dmi = dmiPlus - dmiMinus
DMIlong=ta.crossover(dmi, DMIthreshold)
DMIshort=ta.crossunder(dmi, -DMIthreshold)
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
trix_group = "Trix"
TrixLength = 600
out = 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(close), TrixLength), TrixLength), TrixLength))
TrixLong=out>0
TrixShort=out<0
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
supertrend_group = "Supertrend"
atrPeriod = 5
factor = 2.09
[_, direction] = ta.supertrend(factor, atrPeriod)
supertrendLong=ta.change(direction) < 0
supertrendShort=ta.change(direction) > 0
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
RSI_group = "RSI"
length = 6
overSold = 20
overBought = 80
price = close
vrsi = ta.rsi(price, length)
rsiOS = ta.crossover(vrsi, overSold)
rsiOB= ta.crossunder(vrsi, overBought)
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
fsvzo_group = "FSVZO"
src0 = high
len = 18
flen = 6
bool repaint = true
get_close = close [repaint ? 0 : 1]
get_vol = volume[repaint ? 0 : 1]
sym = syminfo.tickerid
VZO_ = VZO(len, get_close, get_vol)
fsrc = VZO_
MaxH = ta.highest (fsrc , flen)
MinL = ta.lowest (fsrc , flen)
var nValue1 = 0.0
var nFish = 0.0
nValue1 := 0.33 * 2 * ((fsrc - MinL) / (MaxH - MinL) - 0.5) + 0.67 * nz(nValue1[1])
nValue2 = (nValue1 > 0.99 ? 0.999 : (nValue1 < -0.99 ? -0.999: nValue1))
nFish := 0.5 * math.log((1 + nValue2) / (1 - nValue2)) + 0.5 * nz(nFish[1])
f1 = nFish
f2 = nz(nFish[1])
fsvzo_down = f1<f2
fsvzo_up = f1 > f2
fsvzoshort = ta.crossunder(f1, f2)
fsvzolong = ta.crossover(f1, f2)
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
var cumVol = 0.
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
efiLength = 17
efi = ta.ema(ta.change(close) * volume, efiLength)
efiLong = efi > 0
efiShort = efi < 0
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
stochastic_group = "Stochastic"
length2 = 9
overBought2 = 91
overSold2 = 20
smoothK = 3
smoothD = 3
k = ta.sma(ta.stoch(close, high, low, length2), smoothK)
d = ta.sma(k, smoothD)
co = ta.crossover(k,d)
cu = ta.crossunder(k,d)
stochasticLong = co and k < overSold2
stochasticShort = cu and k > overBought2
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
top = 5
bottom = 0.3
puellMultiple = miningRevenue2 / ma3652
upPuell = puellMultiple < top
downPuell = puellMultiple > bottom
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
AroonLength=15
AroonLengthX=16
AroonUpper=100*(ta.highestbars(high, AroonLength)+AroonLength)/AroonLength
Aroonlower=100*(ta.lowestbars(low, AroonLength)+AroonLength)/AroonLength
AroonSource = close
AroonLinRegOffset = 0
lsma=ta.linreg(AroonSource, AroonLengthX, AroonLinRegOffset)
Aroonshort=ta.crossunder(AroonUpper,Aroonlower) and close<lsma
/////////////////////////////////////////////////////////////// © backistan ///////////////////////////////////////////////////////////////
longcondition = DMIlong or (supertrendLong and fsvzo_up and efiLong) or (MACDLong and TrixLong and stochasticLong) and upPuell
shortcondition = DMIshort and downPuell and (supertrendShort and fsvzo_down and efiShort) or (stochasticShort and rsiOB or Aroonshort)
score = 0
if window and longcondition
score := 1
if window and shortcondition
score :=-1
var result = 0
if score == 1
result :=1
if score ==-1
result :=-1
result
As you can see the VZO is defined outside and the miningRevenue and 365 moving average is in the export function.
In simple terms,
1. Take away inputs
2. indent in export
3. Get a score, or whatever you want out of it defined
4. put a return at the bottom
5. publish
Check out whop.com/signals-suite for Access to Invite Only Scripts!
Отказ от ответственности
Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.
Check out whop.com/signals-suite for Access to Invite Only Scripts!
Отказ от ответственности
Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.