Fixing Plotting of Initial Balance Indicator in AmiBroker AFL - amibroker

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.

Related

AttributeError: module 'interactions' has no attribute 'Client'

Full disclosure I haven't written this code myself and I'm still a little new to discord intents. I'm worried that some older discord libraries on my computer may be causing this but i'm not sure why I'm getting this error. Every time I run my program "AttributeError: module 'interactions' has no attribute 'Client' ".
Here is the code I was using
#imports
import interactions
import random
import cloudscraper
#settings
SafeMines = ':white_check_mark:'
TileMines = ':x:'
SafeTowers = ':white_check_mark:'
TileTowers = ':x:'
BotToken = ''
ServerId = 0
BuyerRoleId = 0
#StartUp
bot = interactions.Client(
token=BotToken
)
#defines
def GenGrid(SafeTiles:int):
Generating = True
BoardNums = []
Board = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Grid = f''
line = 0
endrownums = [6,11,16,21]
while Generating:
if len(BoardNums) < SafeTiles:
Selection = random.randint(1, 25)
if Selection in BoardNums:
pass
else:
BoardNums.append(Selection)
else:
Generating = False
for Number in BoardNums:
Board[Number-1] = 1
for Position in Board:
line += 1
if line in endrownums:
Grid += f'\n'
if Position == 1:
Grid += f'{SafeMines}'
else:
Grid += f'{TileMines}'
else:
if Position == 1:
Grid += f'{SafeMines}'
else:
Grid += f'{TileMines}'
return Grid
def gentower(rows:int):
if rows >= 9:
return "Max Rows 8!"
else:
def pr():
rowtp1 = f"{SafeTowers}{TileTowers}{TileTowers}"
rowtp2 = f"{TileTowers}{SafeTowers}{TileTowers}"
rowtp3 = f"{TileTowers}{TileTowers}{SafeTowers}"
joe = random.randint(1,3)
if joe == 1:
return rowtp1
elif joe == 2:
return rowtp2
else:
return rowtp3
leg = True
counter = 0
finaltower = f""
while leg:
if counter == rows:
leg = False
else:
counter +=1
finaltower += f"{pr()}\n"
return finaltower
#Commands
#bot.command(
name='mines',
description="Generates A Mine Grid",
scope=ServerId,
options= [
interactions.Option(
name="game_id",
description="Put your game id here",
type=interactions.OptionType.STRING,
required=True,
),
interactions.Option(
name="clicks",
description="How many safe spots to generate",
type=interactions.OptionType.INTEGER,
required=True,
)
]
)
async def Mines(ctx, game_id: str, clicks:int):
if BuyerRoleId in ctx.author.roles or ctx.author.id == 756534114143961088:
if int(clicks) > 23:
mines = interactions.Embed(title=f"Mines", description=f"Too Many SafeClicks! Max is 23\nYou Chose {clicks}/23", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
count = 0
includes_dash = False
includes_number1 = ""
includes_number2 = ""
l = [14,15,16]
l2 = [18,19,20,21,22]
lsu = False
for v in game_id:
count += 1
if count == 9:
if v == "-":
includes_dash = True
if count in l:
if v == "4":
includes_number1 += v
if count in l:
try:
int(v)
if lsu == True:
continue
else:
includes_number2 +=v
lsu = True
except ValueError:
continue
if includes_dash == True:
if includes_number1 == "4":
try:
int(includes_number2)
mines = interactions.Embed(title=f"Mines", description=f"Generated Tiles!", color=0xFC4431)
mines.add_field(name=f"Field {clicks} Clicks", value=GenGrid(clicks),inline=True)
await ctx.send(embeds=mines, ephemeral=True)
print(f"\n\n{ctx.author} Used Towers command\nID = {ctx.author.id}\n")
except ValueError:
mines = interactions.Embed(title=f"Mines", description=f"Invalid ID!", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
mines = interactions.Embed(title=f"Mines", description=f"Invalid ID!", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
mines = interactions.Embed(title=f"Mines", description=f"Invalid ID!", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
await ctx.send(f"Not Eligable! {ctx.author.mention}")
#Bot
bot.start()
Im not sure why its giving me any error, any suggestions on this?

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?

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

StageText - How to use more than 1 StageText field?

I'm using Flash CS 6 and Air 3.6 to build an Android app.
I would like to use StageText for the input fields.
The code below is only working for the first textfield. What do I need change to make it work for both text fields?
// NO. 1
var firstfield:StageText = new StageText();
firstfield.softKeyboardType = SoftKeyboardType.DEFAULT
firstfield.stage = foobar.stage
firstfield.viewPort = new Rectangle(foobar.x, foobar.y, foobar.width, foobar.height);
// NO. 2
var secondfield:StageText = new StageText();
secondfield.softKeyboardType = SoftKeyboardType.DEFAULT
secondfield.stage = example.stage
secondfield.viewPort = new Rectangle(example.x, example.y, example.width, example.height);
Try something like this:
var firstfield:StageText = new StageText();
firstfield.softKeyboardType = SoftKeyboardType.DEFAULT
firstfield.stage = this.stage;
firstfield.viewPort = new Rectangle(0, 0, 200, 30);
firstfield.x = 0;
firstfield.y = 0;
firstfield.width = 200;
firstfield.height = 30;
addChild(firstfield);
var secondfield:StageText = new StageText();
secondfield.softKeyboardType = SoftKeyboardType.DEFAULT
secondfield.stage = this.stage;
secondfield.viewPort = new Rectangle(0, 40, 200, 30);
secondfield.x = 0;
secondfield.y = 40;
secondfield.width = 200;
secondfield.height = 30;
addChild(secondfield);

Resources