Convert Pine-Script version 2.0 to version 5.0 - version

i need help to convert this Indicator from V2 to V5. It is very complex for me.
//#version=2
study("Heiken Ashi MTF")
ha_t = heikinashi(tickerid)
res = input('60', title="TM 1")
ha_open = security(ha_t, res, open)
ha_close = security(ha_t, res, close)
ha_dif = ha_open-ha_close
ha_diff=iff(ha_dif > 0, 1, iff(ha_dif<0, 2, 3))
res2 = input('240', title="TM 2")
ha_open2 = security(ha_t, res2, open)
ha_close2 = security(ha_t, res2, close)
ha_dif2 = ha_open2-ha_close2
ha_diff2=iff(ha_dif2 > 0, 1, iff(ha_dif2<0, 2, 3))
res3 = input('D', title="TM 3")
ha_open3 = security(ha_t, res3, open)
ha_close3 = security(ha_t, res3, close)
ha_dif3 = ha_open3-ha_close3
ha_diff3=iff(ha_dif3 > 0, 1, iff(ha_dif3<0, 2, 3))
plot(15, title="TF1", color=iff(ha_diff==1, red, iff(ha_diff==2, green, white)), style=circles, linewidth=5, join=true)
plot(14, title="TF2", color=iff(ha_diff2==1, red, iff(ha_diff2==2, green, white)), style=circles, linewidth=5, join=true)
plot(13, title="TF3", color=iff(ha_diff3==1, red, iff(ha_diff3==2, green, white)), style=circles, linewidth=5, join=true)
the code is v2 and i need v5. but this is so complicated. i need some features in v5.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © seriousCockato20483
//#version=5
indicator("Heiken Ashi MTF")
ha_t = ticker.heikinashi(syminfo.tickerid)
res = input('60', title="TM 1")
ha_open = request.security(ha_t, res, open, barmerge.gaps_off, barmerge.lookahead_on)
ha_close = request.security(ha_t, res, close, barmerge.gaps_off, barmerge.lookahead_on)
ha_dif = ha_open-ha_close
ha_diff=ha_dif > 0? 1: (ha_dif<0? 2: 3)
res2 = input('240', title="TM 2")
ha_open2 = request.security(ha_t, res2, open, barmerge.gaps_off, barmerge.lookahead_on)
ha_close2 = request.security(ha_t, res2, close, barmerge.gaps_off, barmerge.lookahead_on)
ha_dif2 = ha_open2-ha_close2
ha_diff2=ha_dif2 > 0? 1: (ha_dif2<0? 2: 3)
res3 = input('D', title="TM 3")
ha_open3 = request.security(ha_t, res3, open, barmerge.gaps_off, barmerge.lookahead_on)
ha_close3 = request.security(ha_t, res3, close, barmerge.gaps_off, barmerge.lookahead_on)
ha_dif3 = ha_open3-ha_close3
ha_diff3=ha_dif3 > 0? 1: (ha_dif3<0? 2: 3)
plot(15, title="TF1", color=ha_diff==1? color.red:(ha_diff==2? color.green: color.white), style=plot.style_circles, linewidth=5, join=true)
plot(14, title="TF2", color=ha_diff2==1? color.red:(ha_diff2==2? color.green: color.white), style=plot.style_circles, linewidth=5, join=true)
plot(13, title="TF3", color=ha_diff3==1? color.red:(ha_diff3==2? color.green: color.white), style=plot.style_circles, linewidth=5, join=true)

Related

pine cannot determine the referencing length of a series using barstate.islast

I receive the error "pine cannot determine the referencing length of a series. try using max_bars_back in the study or strategy function" when trying to perform a function on the barstate.islast condition.
I am using this condition in order to try and speed up my script as it does not need to perform all actions in the function until the last bar of the script. Even performing the function on the last bar is intensive, so I attempt to bypass unnecessary logic when able by using the stopPocIndexNo bool once the lines requested have been drawn.
If I remove the bool, then the loop on any particular bar takes to long > 500ms.
//#version=5
indicator("High Volume Candle Mid", overlay = true, max_lines_count = 100, max_labels_count = 100, max_bars_back = 5000)
maLengthInput = input.int(defval = 34, title = "Volume - Moving Average Length", group = "Options")
volLengthInput = input.int(defval = 5, title = "Volume - Look Back", group = "Options")
maMultiplierInput = input.float(defval = 2, title = "Volume - MA Multiplier", tooltip = "Filter's out weak volume candles that break MA", group = "Options")
qtyOfClosesInput = input.int(defval = 3, title = "(n) closes to cross POC to invalidate.", group = "Options")
qtyOfLinesInput = input.int(defval = 10, title = "(n) latest POC's to show", group = "Options")
qtyOfBrokenLinesInput = input.int(defval = 10, title = "(n) latest historical POC's to show", group = "Options")
barAlignInput = input.int(defval = 20, title = "Bar Index Offset", tooltip = "How many bars past price to extend labels/lines", group = "Options")
supplyColorInput = input.color(defval = #FF5252, title = "Supply Zone - POC's", group = "Options" )
demandColorInput = input.color(defval = #4CAF50, title = "Demand Zone - POC's", group = "Options")
///// Variables
var float maVol = na
var float highestVol = na
var bool pocCondition = false
var float[] barOpens = array.new_float()
var float[] barCloses = array.new_float()
var float[] barPocs = array.new_float()
var color[] barColors = array.new_color()
///// Functions
deleteLines() =>
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
deleteLabels() =>
a_allLabels = label.all
if array.size(a_allLabels) > 0
for i = 0 to array.size(a_allLabels) - 1
label.delete(array.get(a_allLabels, i))
createLines(arrayOfPocs, arrayOfOpens, arrayOfCloses, arrayOfColors, qtyOfCloses, maxLines, maxBrokenLines, barAlign, demandColor, supplyColor) =>
int qtyOfPocs = array.size(arrayOfPocs)
int supplyLinesCount = 0
int supplyBrokenLinesCount = 0
int demandLinesCount = 0
int demandBrokenLinesCount = 0
float lastClose = close[1]
bool stopPocIndexNo = false
deleteLines()
deleteLabels()
for pocIndexNo = (qtyOfPocs > 1 ? qtyOfPocs - 1 : na) to 0
int closeCount = 0
bool lineCrossed = false
int barsSince = (bar_index - pocIndexNo) - 1
float barPoc = array.get(arrayOfPocs, pocIndexNo)
cColor = array.get(arrayOfColors, pocIndexNo)
//string supplyCrossedCloses = na
//string demandCrossedCloses = na
if stopPocIndexNo == false
if barPoc > 0 and barsSince > 2
bool isDemand = barPoc < lastClose
int lineIndex = (bar_index - barsSince) > (bar_index - 2500) ? (bar_index - barsSince) : bar_index - 2500
for indexNo = barsSince to 1
if lineCrossed == false
fClose = array.get(arrayOfCloses, indexNo)
fOpen = array.get(arrayOfOpens, indexNo)
if (fClose > barPoc and fOpen < barPoc) or (fClose < barPoc and fOpen > barPoc)
closeCount := closeCount + 1
if (closeCount > qtyOfCloses)
lineCrossed := true
if lineCrossed
if isDemand and demandBrokenLinesCount < maxBrokenLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = color.new(color.white, 50), style = line.style_dotted, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = color.new(color.white, 50), textalign = text.align_right, style = label.style_none)
demandBrokenLinesCount := demandBrokenLinesCount + 1
else
if supplyBrokenLinesCount < maxBrokenLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = color.new(color.white, 50), style = line.style_dotted, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = color.new(color.white, 50), textalign = text.align_right, style = label.style_none)
supplyBrokenLinesCount := supplyBrokenLinesCount + 1
else
if lineCrossed == false
if isDemand and demandLinesCount < maxLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = cColor, style = line.style_dashed, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = cColor, textalign = text.align_right, style = label.style_none)
demandLinesCount := demandLinesCount + 1
else
if supplyLinesCount < maxLines
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = cColor, style = line.style_dashed, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc), textcolor = cColor, textalign = text.align_right, style = label.style_none)
supplyLinesCount := supplyLinesCount + 1
if supplyBrokenLinesCount == maxBrokenLines and demandBrokenLinesCount == maxBrokenLines and supplyLinesCount == maxLines and demandLinesCount == maxLines
stopPocIndexNo := true
///// Calculations
// Calculate moving average and highest volume bar in the last volLengthInput
maVol := ta.sma(volume, maLengthInput)
highestVol := ta.highest(volume, volLengthInput)
// Detect new POC Lines by finding vars that breached the Moving Average with Multiplier as well as being the most recent highest volume bar
pocCondition := (volume >= maVol * maMultiplierInput) and volume == highestVol
// Store bar POC's if poc condition is met, otherwise store nothing
if pocCondition
array.push(barPocs, (high + low)/2)
if close > open
array.push(barColors, demandColorInput)
else
array.push(barColors, supplyColorInput)
else
array.push(barPocs, 0)
array.push(barColors, na)
// Store opens/closes for later calculations to detect line crosses
array.push(barCloses, close)
array.push(barOpens, open)
// We don't want to calculate line breaches every bar as it would be too slow, so wait until its the last bar to look for POC's
if barstate.islast
aOpens = array.copy(barOpens)
aCloses = array.copy(barCloses)
array.reverse(aOpens)
array.reverse(aCloses)
createLines(barPocs, aOpens, aCloses, barColors, qtyOfClosesInput, qtyOfLinesInput/2, qtyOfBrokenLinesInput/2, barAlignInput, demandColorInput, supplyColorInput)
barcolor(color = pocCondition and close > open ? demandColorInput : pocCondition and open > close ? supplyColorInput : na)
If I remove some of the functionality to speed up the script, only checking for non crossed lines, it works without issue.
/#version=5
indicator("High Volume Candle Mid", overlay = true, max_lines_count = 100, max_labels_count = 100, max_bars_back = 5000)
maLengthInput = input.int(defval = 34, title = "Volume - Moving Average Length", group = "Options")
volLengthInput = input.int(defval = 5, title = "Volume - Look Back", group = "Options")
maMultiplierInput = input.float(defval = 2, title = "Volume - MA Multiplier", tooltip = "Filter's out weak volume candles that break MA", group = "Options")
qtyOfClosesInput = input.int(defval = 3, title = "(n) closes to cross POC to invalidate.", group = "Options")
qtyOfLinesInput = input.int(defval = 10, title = "(n) latest POC's to show", group = "Options")
qtyOfBrokenLinesInput = input.int(defval = 10, title = "(n) latest historical POC's to show", group = "Options")
barAlignInput = input.int(defval = 20, title = "Bar Index Offset", tooltip = "How many bars past price to extend labels/lines", group = "Options")
supplyColorInput = input.color(defval = #FF5252, title = "Supply Zone - POC's", group = "Options" )
demandColorInput = input.color(defval = #4CAF50, title = "Demand Zone - POC's", group = "Options")
///// Variables
var float maVol = na
var float highestVol = na
var bool pocCondition = false
var float[] barOpens = array.new_float()
var float[] barCloses = array.new_float()
var float[] barPocs = array.new_float()
var color[] barColors = array.new_color()
///// Functions
deleteLines() =>
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
deleteLabels() =>
a_allLabels = label.all
if array.size(a_allLabels) > 0
for i = 0 to array.size(a_allLabels) - 1
label.delete(array.get(a_allLabels, i))
createLines(arrayOfPocs, arrayOfOpens, arrayOfCloses, arrayOfColors, qtyOfCloses, maxLines, maxBrokenLines, barAlign, demandColor, supplyColor) =>
int qtyOfPocs = array.size(arrayOfPocs)
int supplyLinesCount = 0
int supplyBrokenLinesCount = 0
int demandLinesCount = 0
int demandBrokenLines = 0
float lastClose = close[1]
deleteLines()
deleteLabels()
for pocIndexNo = (qtyOfPocs > 1 ? qtyOfPocs - 1 : na) to 0
int supplyCloseCount = 0
int demandCloseCount = 0
bool supplyLineCrossed = false
bool demandLineCrossed = false
int barsSince = (bar_index - pocIndexNo) - 1
float barPoc = array.get(arrayOfPocs, pocIndexNo)
cColor = array.get(arrayOfColors, pocIndexNo)
//string supplyCrossedCloses = na
//string demandCrossedCloses = na
//if supplyLinesCount < maxLines or supplyBrokenLinesCount < maxBrokenLines
if barPoc > lastClose and barPoc > 0
if barsSince > 1
int lineIndex = (bar_index - barsSince) > (bar_index - 4999) ? (bar_index - barsSince) : bar_index - 4999
for indexNo = barsSince to 1
fClose = array.get(arrayOfCloses, indexNo)
fOpen = array.get(arrayOfOpens, indexNo)
if (fClose > barPoc and fOpen < barPoc) or (fClose < barPoc and fOpen > barPoc)
//supplyCrossedCloses := supplyCrossedCloses + "Crossed Count: " + str.tostring(supplyCloseCount) + "\n" + str.tostring(fClose) + " > " + str.tostring(barPoc) + " and " + str.tostring(fOpen) + " < " + str.tostring(barPoc) + " or " + str.tostring(fClose) + " < " + str.tostring(barPoc) + " and " + str.tostring(fOpen) + " > " + str.tostring(barPoc) + "\n"
supplyCloseCount := supplyCloseCount + 1
if (supplyCloseCount > qtyOfCloses)
supplyLineCrossed := true
// if supplyLineCrossed == true and supplyBrokenLinesCount < maxBrokenLines
// line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = color.new(color.white, 50), style = line.style_dotted, width = 1, extend = extend.none)
// label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc) + " [" + str.tostring(lineIndex) + "]", textcolor = color.new(color.white, 50), textalign = text.align_right, style = label.style_none)
// supplyBrokenLinesCount := supplyBrokenLinesCount + 1
if supplyLineCrossed == false and supplyLinesCount < maxLines
//label.new(lineIndex, close + (supplyLines * 400), text = "barPoc: " + str.tostring(barPoc) + "\nsupplyLines: " + str.tostring(supplyLines) + "\nsupplyCloseCount: " + str.tostring(supplyCloseCount) + "\n" + supplyCrossedCloses, textcolor = color.aqua, style = label.style_label_down, color = color.new(color.white, 100))
line.new(lineIndex, barPoc, bar_index + barAlign, barPoc, color = cColor, style = line.style_dashed, width = 1, extend = extend.none)
label.new(bar_index + barAlign, barPoc, text = str.tostring(barPoc) + " [" + str.tostring(lineIndex) + "]", textcolor = cColor, textalign = text.align_right, style = label.style_none)
supplyLinesCount := supplyLinesCount + 1
///// Calculations
// Calculate moving average and highest volume bar in the last volLengthInput
maVol := ta.sma(volume, maLengthInput)
highestVol := ta.highest(volume, volLengthInput)
// Detect new POC Lines by finding vars that breached the Moving Average with Multiplier as well as being the most recent highest volume bar
pocCondition := (volume >= maVol * maMultiplierInput) and volume == highestVol
// Store bar POC's if poc condition is met, otherwise store nothing
if pocCondition
array.push(barPocs, (high + low)/2)
if close > open
array.push(barColors, demandColorInput)
else
array.push(barColors, supplyColorInput)
else
array.push(barPocs, 0)
array.push(barColors, na)
// Store opens/closes for later calculations to detect line crosses
array.push(barCloses, close)
array.push(barOpens, open)
// We don't want to calculate line breaches every bar as it would be too slow, so wait until its the last bar to look for POC's
if barstate.islast
aOpens = array.copy(barOpens)
aCloses = array.copy(barCloses)
array.reverse(aOpens)
array.reverse(aCloses)
createLines(barPocs, aOpens, aCloses, barColors, qtyOfClosesInput, qtyOfLinesInput/2, qtyOfBrokenLinesInput/2, barAlignInput, demandColorInput, supplyColorInput)
barcolor(color = pocCondition and close > open ? demandColorInput : pocCondition and open > close ? supplyColorInput : na)
Not sure what I am missing about the barstate.islast and how it affects series lengths that could be causing me issue. I stopped referencing bar_index in the arrays I was utilizing to find the historical Mids I needed, but I still use it to create lines. If this is not supported does anyone have a better idea for creating the lines? Or if there is some issue with creating lines under multiple conditionals?

Fixing Plotting of Initial Balance Indicator in AmiBroker AFL

I am using the following AFL code for "Initial Balance with Range Extension" in AmiBroker -
_SECTION_BEGIN("Initial Balance with Range Extensions");
P11 = Param("IB Start Time",091500, 0 , 235959, 1 ) ;
P12 = Param("IB END Time",101500, 0 , 235959, 1 ) ;
START = (TimeNum()>= P11);
END = (TimeNum()<= P12);
ZONE = START AND END;
ST = (TimeNum()>= P12);
NewTime = ZONE!= Ref(ZONE, -1);
highestoftheday = HighestSince(NewTime,H,1);
Lowestoftheday = LowestSince(NewTime,L,1);
IBHigh = ValueWhen(ZONE,highestoftheday,1);
IBLow = ValueWhen(ZONE,lowestoftheday,1);
ORBClose = ValueWhen(zone,C,1);
IBrange = IBHigh - IBLow; // First Hour Range
IBM = IBLow+IBrange/2;
IB1xh = IBHigh+IBrange ; // Target 1 for range extension upside
IB2xh = IBHigh+2*IBrange ;
IB3xh = IBHigh+3*IBrange ;
IB1xl = IBLow-IBrange ;
IB2xl = IBLow-2*IBrange ; // target 1 for range extension downside
IB3xl = IBLow-3*IBrange ;
PlotGrid(LastValue(IBHigh, True), colorPlum, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IBLow, True), colorPlum, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IBM, True), colorBrown, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IB1xh, True), colorGreen, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IB2xh, True), colorGreen, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IB3xh, True), colorGreen, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IB1xl, True), colorRed, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IB2xl, True), colorRed, pattern=10, width = 2, label = True);
PlotGrid(LastValue(IB3xl, True), colorRed, pattern=10, width = 2, label = True);
_SECTION_END();
This code is plotting continuous horizontal lines. But I need disjointed horizontal lines for individual sessions. How can I get that? Please help me to fix this issue. Thanks for your time and effort. Regards.

Develope strategy Pinescript

I would transform this code in strategy, but I got continue errors about it.
Can u help me to fix?
Conditions:
open LONG: close >= simpleVMA
close LONG: crossunder and not na(vrsi) and isUp
open SHORT: close <= simpleVMA
close SHORT: crossover and not na(vrsi) and isDown
`//Input
showAMA=input(true, title="----------Show Averaged sma?")
showVMA =input(false, title="----------Show Simple sma?")
colorBlueSlate = #5674b9 //Slate blue
colorBlueDark = #311B92 //darkBlue
colorBlueLt = #2196F3 //Light Blue
colorYellow = #C1B82F //yellow
colorGreen = #007236 //Green
colorRed = #FF0000 //Red
colorWhite = #FFFFFF //White
colorGray = #dbdbdb //light gray
colorBlack = #000000 //Black
showVMA= ta.sma(ta.sma(hlc3), 50) //originale 55
simpleVMA= ta.sma(close)
plotsma = plot(showAVMA ? showVMA: na, color=colorRed, linewidth=3, title="Plot sma SMA")
plotsmaSimple = plot(showVMA ? simpleVMA: na, color=colorRed, linewidth=1, title="Plot sma Simple")
rsi = ta.rsi(close, 14)
isRsiOB = (close >= simplesma) and (rsi > 35)
isRsiOS = (close <= simplesma) and (rsi <= 65)
//showVMA= ta.sma(ta.sma(hlc3), 55)
//simpleVMA= ta.sma(close)
ma1 = ta.ema(close, 1)
//plotsma = plot(showAVMA ? showVMA: na, color=colorRed, linewidth=3, title="Plot sma SMA")
//plotsmaSimple = plot(showVMA ? simpleVMA: na, color=colorRed, linewidth=1, title="Plot sma Simple")
TrendUp1 = ma1 > showVMA //ma1 > averagedsma
TrendDown1 = ma1 <= showVMA//showVMA<= ma1
isUp = close >= simpleVMA
isDown = close <= simpleVMA
isInside = close < high[1] and low > low[1]
PULLUP = (close >= simplesma) and (rsi <= 65)
PULLDOWN = (close <= simplesma) and (rsi > 35)
barcolor(TrendUp1 ? color.yellow: TrendDown1 ? color.red: PULLUP ? color.black: PULLDOWN ? color.black: na)
length = input( 14 )
overSold = input( 30 )
overBought = input( 70 )
price = close
vrsi = ta.rsi(price, length)
crossover = ta.crossover(vrsi, overSold)
crossunder = ta.crossunder(vrsi, overBought)
long = crossover and not na(vrsi) and isDown
short = crossunder and not na(vrsi) and isUp
long1 = crossover and not na(vrsi) and isUp
short1 = crossunder and not na(vrsi) and isDown
plotshape(long, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text='Tp', textcolor=color.new(color.white, 0)) //plotting up arrow when buy/long conditions met
plotshape(short, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text='Tp', textcolor=color.new(color.white, 0)) //plotting down arrow when sell/short conditions met
plotshape(long1, style=shape.circle, location=location.belowbar, color=color.white, size=size.small, text='', textcolor=color.new(color.white, 0)) //plotting up arrow when buy/long conditions met
plotshape(short1, style=shape.circle, location=location.abovebar, color=color.white, size=size.small, text='', textcolor=color.new(color.white, 0)) //plotting down arrow when sell/short conditions met`

Historical Market Screener: Processing Array Data

I have a question with respect to arrays & tables on PineScript, please. To give an overview of what I am intending to do, I want to create a screener that will go through a set of symbols and output the annual performance at a historical date.
The idea behind this concept is that I would be able to identify top performing symbols from a historical perspective. I have researched online, and I was not able to find such a tool.
The reason why I would need a tool like this, is so that I can back-test my strategy on historical top-performers, considering that I would be rebalancing my portfolio at a fixed interval e.g. once per quarter.
So my questions with regards to the code below are basically 2 –
How can I filter the arrays to output only values above 10% yearly performance?
How do I sort the table so that the top performers come to the top of the list?
I have shortened the code for this post. However, this screener can go through a max of 40 symbols as you all know. My plan is to run this on basically all the major and minor FX pairs and for stocks, I will pick a balanced portfolio with stocks from each of the 11 S&P sectors. As liquidity rotates through each of sectors, this should keep me running my strategy on stocks with positive alpha potential.
//#version=5
indicator('Annual Performance Historical Screener', overlay=true)
////////////
// INPUTS //
//Year Input
input_year = input(2022, "Year")
/////////////
// SYMBOLS //
u01 = input.bool(true, title = "", group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = "", group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = "", group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = "", group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = "", group = 'Symbols', inline = 's05')
s01 = input.symbol('XRPUSDT', group = 'Symbols', inline = 's01')
s02 = input.symbol('BTCUSDT', group = 'Symbols', inline = 's02')
s03 = input.symbol('DOGEUSDT', group = 'Symbols', inline = 's03')
s04 = input.symbol('BNBUSDT', group = 'Symbols', inline = 's04')
s05 = input.symbol('ETHUSDT', group = 'Symbols', inline = 's05')
//////////////////
// CALCULATIONS //
// Get only symbol
only_symbol(s) =>
array.get(str.split(s, ":"), 1)
//price at the input
price_input_year = timestamp(input_year,10,12)
period = time >= price_input_year and time[1] < price_input_year
periodPrice = ta.valuewhen(period, close, 0)
//price at 1 year preceeding input
price_prev_year = timestamp(input_year-1,10,12)
period_prev = time >= price_prev_year and time[1] < price_prev_year
periodPrice_prev = ta.valuewhen(period_prev, close, 0)
screener_func() =>
//Yearly performance from input date
annual_perf=(periodPrice-periodPrice_prev)*100/periodPrice
[math.round_to_mintick(close), annual_perf]
// Security call
[cl01, ap01] = request.security(s01, timeframe.period, screener_func())
[cl02, ap02] = request.security(s02, timeframe.period, screener_func())
[cl03, ap03] = request.security(s03, timeframe.period, screener_func())
[cl04, ap04] = request.security(s04, timeframe.period, screener_func())
[cl05, ap05] = request.security(s05, timeframe.period, screener_func())
////////////
// ARRAYS //
s_arr = array.new_string(0)
u_arr = array.new_bool(0)
cl_arr = array.new_float(0)
ap_arr = array.new_float(0)
// Add Symbols
array.push(s_arr, only_symbol(s01))
array.push(s_arr, only_symbol(s02))
array.push(s_arr, only_symbol(s03))
array.push(s_arr, only_symbol(s04))
array.push(s_arr, only_symbol(s05))
///////////
// FLAGS //
array.push(u_arr, u01)
array.push(u_arr, u02)
array.push(u_arr, u03)
array.push(u_arr, u04)
array.push(u_arr, u05)
///////////
// CLOSE //
array.push(cl_arr, cl01)
array.push(cl_arr, cl02)
array.push(cl_arr, cl03)
array.push(cl_arr, cl04)
array.push(cl_arr, cl05)
/////////
// Annual performance //
array.push(ap_arr, ap01)
array.push(ap_arr, ap02)
array.push(ap_arr, ap03)
array.push(ap_arr, ap04)
array.push(ap_arr, ap05)
///////////
// PLOTS //
var tbl = table.new(position.top_right, 6, 41, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.white, 100))
if barstate.islast
table.cell(tbl, 0, 0, 'Symbol', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 1, 0, 'Price', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, 0, 'Annual Performance', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
for i = 0 to 4
if array.get(u_arr, i)
ap_col = array.get(ap_arr, i) >= 10 ? color.green : #aaaaaa
table.cell(tbl, 0, i + 1, array.get(s_arr, i), text_halign = text.align_left, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 1, i + 1, str.tostring(array.get(cl_arr, i)), text_halign = text.align_center, bgcolor = #aaaaaa, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, i + 1, str.tostring(array.get(ap_arr, i), "#.##"), text_halign = text.align_center, bgcolor = ap_col, text_color = color.white, text_size = size.small)

Import many files .txt in SAS

I built a code to import multiple data simultaneously into SAS, but I want to improve it does anyone have any suggestions?
filename indata pipe 'dir E:\Desafio_SAS\Dados /B';
data file_list;
length arquivos$20.;
infile indata truncover ;
input arquivos $20.;
call symput('num_files',_n_);
arquivos=compress(arquivos,',.txt');
run;
CRIANDO UMA MACRO POR PROC SQL PARA GUARDAR O NOME DOS ARQUIVOS
proc sql;
select arquivos into :lista separated by ' ' from file_list;
quit;
%let &lista;
%macro importar(arquivo=);
filename data "E:\Desafio_SAS\Dados\&arquivo..txt";
data &arquivo;
infile data dlm=" " missover dsd firstobs=2;
input v0 (v1 - v8) ($);
format v0 F16.;
run;
%mend importar;
%macro fileout;
%do i=1 %to &num_files;
%importar(arquivo=df&i);
data df&i;
set var_names df&i;
run;
%end;
%mend fileout;
%fileout;
%macro excluiv0;
%do i=1 %to &num_files;
data _null_;
data df&i(drop = v0);
set df&i;
run;
%end;
run;
%mend excluiv0;
%excluiv0;
It's just part of the code.
You can use a wildcard in the infile file-specification. As long as all the files meeting the wildcard are the same layout, you can use a single input to read all the files.
Example
* create three text files having same fields;
data _null_;
file '%temp%\1.txt';
put '1 2 3 abc';
put '3 4 5 def';
file '%temp%\2.txt';
put '6 7 8 ghi';
put '9 10 11 jkl';
file '%temp%\3.txt';
put '12 13 14 xyz';
put '15 16 17 tuv';
run;
* read all three using wildcard in infile. Save name of file whence
* data cometh frometh;
data want;
length _filename_ $250;
infile '%temp%\?.txt' filename=_filename_;
length source $250;
length a b c 8 s $20;
source = _filename_;
input a b c s;
run;
Wildcards are
?, 0 or 1 of any character
*, any number of any character
t1 <- ttheme_default(core=list(
fg_params=list(fontface=c("bold.italic")),
bg_params = list(fill=c("green", "grey90","blue","red"))))
grid.arrange(g1,
tableGrob(iris[1:5, 1:4], theme = t1,, rows=NULL),
g1, g1, nrow = 2)
---
title: "Column Orientation"
output: flexdashboard::flex_dashboard
---
```{r setup, include=FALSE}
library(ggplot2);library(knitr);library(kableExtra)
library(flexdashboard);library(gridExtra);library(grid)
```
<style>
.colored {
background-color: #002080;}
</style>
Column{data-width=200}
-------------------------------------
### Chart 1{.colored}
```{r}
gauge(10, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(50, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(20, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(15, min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
gauge(5 , min = 0, max = 100, sectors = gaugeSectors(colors = "#002080"))
```
Column
-------------------------------------
### Chart 2
```{r, include=FALSE}
tt1 <- ttheme_default()
tt2 <- ttheme_minimal()
tt3 <- ttheme_minimal(
core=list(bg_params = list(fill = blues9[1:4], col=NA),
fg_params=list(fontface=3)),
colhead=list(fg_params=list(col="navyblue", fontface=4L)),
rowhead=list(fg_params=list(col="orange", fontface=3L)))
tab <- grid.arrange(tableGrob(iris[c(1:4,1:2), c(1:3,1:2)], theme=tt3), nrow=1)
graf <- ggplot(data=mtcars, aes(x=drat, y=disp, group=vs)) +
geom_line() + ylab("") +
geom_point()
gg.gauge <- function(pos,breaks=c(0,10,25,100)) {
get.poly <- function(a,b,r1=0.5,r2=1.0) {
th.start <- pi*(1-a/100)
th.end <- pi*(1-b/100)
th <- seq(th.start,th.end,length=1000)
x <- c(r1*cos(th),rev(r2*cos(th)))
y <- c(r1*sin(th),rev(r2*sin(th)))
return(data.frame(x,y))
}
ggplot()+
geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="forestgreen", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="red", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y), colour = "white")+
annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+
coord_fixed()+
theme_bw()+
theme(axis.text=element_blank(),
axis.title=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank())
}
gg1 <- gg.gauge(2,breaks=c(0,10,25,100))
gg2 <- gg.gauge(5,breaks=c(0,10,25,100))
gg3 <- gg.gauge(7,breaks=c(0,10,25,100))
```
```{r, fig.width=9.5, fig.height=7}
for (i in 1:5){
title1=textGrob("Test title TESTE", gp=gpar(fontface="bold", fontsize = 15))
lay <- rbind(c(3,3,4,4,5,5),
c(1,1,1,1,1,1),
c(1,1,1,1,1,1),
c(2,2,2,2,2,2),
c(2,2,2,2,2,2))
grid.arrange(graf, tab, gg1, gg2, gg3, top=title1,
layout_matrix= lay)
grid.rect(width = 1, height = 1, gp = gpar(lwd = 2, col = "black", fill = NA))
cat("\n")
}
```
---
title: "BRADESCO"
output:
flexdashboard::flex_dashboard:
orientation: rows
---
```{r setup, include=FALSE}
library(ggplot2);library(knitr);library(kableExtra)
library(flexdashboard);
library(gridExtra);library(grid)
```
Geral {data-icon="fa-signal"}
=====================================
### Chat 1
```{r}
p1 <- qplot(mpg, wt, data = mtcars, colour = cyl)
p2 <- qplot(mpg, data = mtcars)
p3 <- qplot(mpg, data = mtcars, geom = "dotplot")
lay <- rbind(c(1,1,1,2,2,2),
c(3,3,3,3,3,3))
grid.arrange(p2, p3, p1, nrow = 2, layout_matrix= lay)
```
### Table 1
```{r}
kable(mtcars[1:10, c(1:6,1:4)], caption = "Group Rows") %>%
kable_styling("striped", full_width = F) %>%
group_rows("Group 1", 4, 7) %>%
group_rows("Group 2", 8, 10)
```
Por segmento {data-icon="fa-signal"}
=====================================
<style>
.colored {
background-color: #002080;}
</style>
Row{data-height=200}
-------------------------------------
### Chart 1{.colored}
```{r, fig.width=55}
dat = data.frame(count=rep(c(10, 60, 30),10), category=rep(c("A", "B", "C"),10), fator=c(1,2,3,4,5))
# Add addition columns, needed for drawing with geom_rect.
dat$fraction = dat$count / sum(dat$count)
dat = dat[order(dat$fraction), ]
dat$ymax = cumsum(dat$fraction)
dat$ymin = c(0, head(dat$ymax, n=-1))
p <- ggplot(dat, aes(x=2, y=fraction, fill=category))+
geom_bar(stat="identity", colour = "white", size = 2) +
xlim(0, 2.5) +
scale_fill_manual(values=c("#002080", "#002080", "white")) +
coord_polar(theta = "y")+
labs(x=NULL, y=NULL)+ guides(fill=FALSE) +
ylab("fsfagafs") + facet_wrap(~ fator,nrow = 1) +
annotate("text", x = 0, y = 0, label = "WW", size = 20, colour = "white") +
theme(
plot.margin = margin(-1.1, 3.6, -1.1, 3.6, "cm"),
panel.spacing = unit(30, "lines"),
axis.ticks=element_blank(),
axis.text=element_blank(),
axis.title=element_blank(),
panel.grid=element_blank(),
plot.background = element_rect(fill = "#002080", colour="#002080"),
panel.background = element_rect(fill = "#002080", colour="#002080"),
strip.background = element_blank(),
strip.text.x = element_blank())
p
```
Row
-------------------------------------
### Chart 2 {data-wight=900}
```{r, include=FALSE}
tt1 <- ttheme_default()
tt2 <- ttheme_minimal()
tt3 <- ttheme_minimal(
core=list(bg_params = list(fill = blues9[1:4], col=NA),
fg_params=list(fontface=3)),
colhead=list(fg_params=list(col="navyblue", fontface=4L)),
rowhead=list(fg_params=list(col="orange", fontface=3L)))
tab <- grid.arrange(tableGrob(iris[c(1:4,1:2), c(1:3,1:2)], theme=tt3), nrow=1)
graf <- ggplot(data=mtcars, aes(x=drat, y=disp, group=vs)) +
geom_line() + ylab("") +
geom_point()
gg.gauge <- function(pos,breaks=c(0,10,25,100)) {
get.poly <- function(a,b,r1=0.5,r2=1.0) {
th.start <- pi*(1-a/100)
th.end <- pi*(1-b/100)
th <- seq(th.start,th.end,length=1000)
x <- c(r1*cos(th),rev(r2*cos(th)))
y <- c(r1*sin(th),rev(r2*sin(th)))
return(data.frame(x,y))
}
ggplot()+
geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="forestgreen", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="red", colour = "white", size = 1.2, alpha = 0.7) +
geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y), colour = "white")+
annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+
coord_fixed()+
theme_bw()+
theme(axis.text=element_blank(),
axis.title=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank())
}
gg1 <- gg.gauge(2,breaks=c(0,10,25,100))
gg2 <- gg.gauge(5,breaks=c(0,10,25,100))
gg3 <- gg.gauge(7,breaks=c(0,10,25,100))
```
```{r, fig.width=7.2, fig.height=7}
for (i in 1:5){
title1=textGrob("Test title TESTE", gp=gpar(fontface="bold", fontsize = 15))
lay <- rbind(c(3,3,4,4,5,5),
c(1,1,1,1,1,1),
c(1,1,1,1,1,1),
c(2,2,2,2,2,2),
c(2,2,2,2,2,2))
grid.arrange(graf, tab, gg1, gg2, gg3, top=title1,
layout_matrix= lay)
grid.rect(width = 1, height = 1, gp = gpar(lwd = 2, col = "black", fill = NA))
cat("\n")
}
```
### Chart 2
```{r}
mydata = data.frame(x1 = c(1,2,3),
x2 = c(9,8,7),
label = c("description a",
"description b",
"description c"))
ht = 5
wd1 = 5
wd2 = 12
gap = 0.1
nc = ncol(mydata)
nr = nrow(mydata)
x = rep(c(seq(0,(nc-2)*(wd1+gap), wd1+gap), (nc-2)*(wd1+gap) + gap + 0.5*(wd2+wd1)), nr)
y = rep(seq(0,(nr-1)*(ht+gap), ht+gap), nc) %>% sort()
h = rep(ht, nr * nc)
w = rep(c(rep(wd1, nc-1), wd2), nr)
info = as.vector(t(as.matrix(mydata[nr:1,])))
df = data.frame(x = x, y = y, h = h, w = w, info = info)
ggplot(df, aes(x, y, height = h, width = w, label = info)) +
geom_tile() +
geom_text(color = "white", fontface = "bold") +
coord_fixed() +
scale_fill_brewer(type = "qual",palette = "Dark2") +
theme_void() +
guides(fill = F)
```
teste

Resources