How do I write the code for the variable BUY that I have in strategy.entry I will use this code to write the Variable BUY code - linear-regression

I have these variables that I want to be able to choose from in a drop down input under option for Line1 and Line2. These should be selectable using yet another drop down input with options = ['none', '==', '<', '>', '<=', '>=', '!=' , 'crossover', 'crossunder']) named Operator1.
sm1res = input.timeframe(title='Time for open', defval='30')
sm1 = request.security(syminfo.tickerid, sm1res, open, lookahead=barmerge.lookahead_on)
sm2res = input.timeframe(title='Time for open', defval='60')
sm2 = request.security(syminfo.tickerid, sm2res, open, lookahead=barmerge.lookahead_on)
sm3res = input.timeframe(title='Time for open', defval='240')
sm3 = request.security(syminfo.tickerid, sm3res, open, lookahead=barmerge.lookahead_on)
to1res = input.timeframe(title='Time for previous open 1', defval='30')
to1 = request.security(syminfo.tickerid, to1res, open[1], lookahead=barmerge.lookahead_on)
to2res = input.timeframe(title='Time for previous open 2', defval='60')
to2 = request.security(syminfo.tickerid, to2res, open[1], lookahead=barmerge.lookahead_on)
to3res = input.timeframe(title='Time for previous open 3', defval='240')
to3 = request.security(syminfo.tickerid, to3res, open[1], lookahead=barmerge.lookahead_on)
th1res = input.timeframe(title='Time for previous high 1', defval='30')
th1 = request.security(syminfo.tickerid, th1res, high[1], lookahead=barmerge.lookahead_on)
th2res = input.timeframe(title='Time for previous high 2', defval='60')
th2 = request.security(syminfo.tickerid, th2res, high[1], lookahead=barmerge.lookahead_on)
th3res = input.timeframe(title='Time for previous high 3', defval='240')
th3 = request.security(syminfo.tickerid, th3res, high[1], lookahead=barmerge.lookahead_on)
tl1res = input.timeframe(title='Time for previous low 1', defval='30')
tl1 = request.security(syminfo.tickerid, tl1res, low[1], lookahead=barmerge.lookahead_on)
tl2res = input.timeframe(title='Time for previous low 2', defval='60')
tl2 = request.security(syminfo.tickerid, tl2res, low[1], lookahead=barmerge.lookahead_on)
tl3res = input.timeframe(title='Time for previous low 3', defval='240')
tl3 = request.security(syminfo.tickerid, tl3res, low[1], lookahead=barmerge.lookahead_on)
Line1 = input.string(defval = "sm1", title = 'Line1', inline = 'Operator1', group = 'Strategy1', options=["sm1", "sm2", "sm3", "to1", "to2", "to3", "th1", "th2", "th3", "tl1", "tl2", "tl3"])
Operator1 = input.string(defval = 'none', title = 'Operator1', inline = 'Operator1', group = 'Strategy1', options = ['none', '==', '<', '>', '<=', '>=', '!=', 'crossover', 'crossunder'])
Line2 = input.string(defval = none, title = 'Line2', inline = 'Operator1', group = 'Strategy1', options=["sm1", "sm2", "sm3", "to1", "to2", "to3", "th1", "th2", "th3", "tl1", "tl2", "tl3"])
Then I have a buy variable but can't get it to work with different attempts of code, sometimes it says it should be series string, bool, const string, Syntax error at input ':' and a lot of other errors.
BUY = line1 : Operator1 : line2 ? : na
Then comes my order placement:
if BUY
if Type == _S_
strategy.close('S')
else
strategy.entry('K', strategy.long)
if SELL
if Type == _L_
strategy.close('K')
else
strategy.entry('S', strategy.short)
Grateful for help so that parts of the errors are with correct code instead and suggestions for improvements welcome. I'm not very good at programming, so please explain in a simple way if you have time.
I've tried reading the manual and looking for different allowed types that go together. I have also tried Pinecoders and the chat. I'm afraid request.security doesn't allow options.

Please edit your question so it contains only one question at a time.
Regarding your first question, you can use a switch:
Line1_input = input.string(defval = "sm1", title = 'Line1', inline = 'Operator1', group = 'Strategy1', options=["sm1", "sm2", "sm3", "to1", "to2", "to3", "th1", "th2", "th3", "tl1", "tl2", "tl3"])
Line2_input = input.string(defval = "sm1", title = 'Line2', inline = 'Operator1', group = 'Strategy1', options=["sm1", "sm2", "sm3", "to1", "to2", "to3", "th1", "th2", "th3", "tl1", "tl2", "tl3"])
Operator1 = input.string(defval = 'none', title = 'Operator1', inline = 'Operator1', group = 'Strategy1', options = ['none', '==', '<', '>', '<=', '>=', '!=', 'crossover', 'crossunder'])
line1 = switch Line1_input
"sm1" => ta.sma(close, 10)
"sm2" => ta.ema(close, 10)
=> ta.hma(close, 10)
line2 = switch Line2_input
"sm1" => ta.sma(close, 20)
"sm2" => ta.ema(close, 20)
=> ta.hma(close, 20)
BUY = switch Operator1
'==' => line1 == line2
'<' => line1 < line2
'>' => line1 > line2
'<=' => line1 <= line2
'>=' => line1 >= line2
'!=' => line1 != line2
'crossover' => ta.crossover(line1, line2)
'crossunder' => ta.crossunder(line1, line2)

Related

Cannot get my chart ‘stacked’ using a Calc macro

Somehow I cannot get my chart to ‘stack’. For reasons explained below I first prepare a standard chart in a macro called ‘ChartsGeneral’. Based on some settings on my ‘Charts’ worksheet, it then calls a specific second macro, e.g. ‘ChartBuildStatus’. In this second macro I generate the category and data-series, and adjust the settings of the standard chart as necessary.
When I try to get a stacked chart via ‘createInstance(“com.sun.star.chart.StackableDiagram”)’ nothing changes. I have studied the documentation and several forums, but I have no clue what I am missing. Code below.
Configuration details
Version: 7.4.3.2 (x64) / LibreOffice Community
CPU threads: 12; OS: Windows 10.0 Build 19045; Locale: nl-NL (nl_NL); UI: en-US
OK, here it goes… Please have some mercy on a poor old non-programmer nerd.
Background
Over the years I collected a rather large set of Excel spreadsheets with VBA macros for my personal finances. This year I decided to migrate them all to LibreOffice, as part of my wider migration from Windows to Linux. I am not a programmer, so I decided to use BASIC as it would be closest to VBA.
One of my spreadsheets tracks progress on our home mortgage. I keep track of all payments on interest and principal. As we are paying down extra with a fixed monthly payment and a ‘snowball’ (all savings go back as payments to the principal) the spreadsheet also calculates the expected next snowball payment, as well as a prognosis for the remainder of the mortgage. That all works fine.
The key worksheets in my Mortgage spreadsheet are ‘Months’, where I store all the data of past payments, and ‘Prognosis’, which holds a copy of ‘Months’ but also a prognosis for every month in the future.
I am now down to the last block of functionality: reporting. This is mainly a collection of charts that show the history, current status and prognosis for my mortgage based on the data in Months and Prognosis. For this I use a dedicated worksheet called ‘Charts’ in my spreadsheet. Here I can select a Chart Type from a dropdown-list, as well as some date or period related settings (I use named fields for this). See a partial screenshot below.
Partial Screenshot of Charts worksheet
When I press the ‘Update Chart’ button on my Charts worksheet, a macro called ‘ChartsGeneral’ is triggered. In this macro:
I use the date or period related settings to calculate the starting row and ending row for the data series
I then generate an empty standard linechart called ‘AdminChart’ on the Charts worksheet, with settings for the axes, the formatting, and everything
I call a second macro based on the ChartType value on Charts. In the above example the chart is called ‘Opbouw Stand van Zaken’, so I call a second macro called ChartBuildStatus.
The code for ChartsGeneral can be found below
Sub ChartsGeneral()
'Manages the Charts worksheet
'Set Worksheets
wshC = ThisComponent.Sheets.getByName("Charts")
wshM = ThisComponent.Sheets.getByName("Months")
wshP = ThisComponent.Sheets.getByName("Prognosis")
wshS = ThisComponent.Sheets.getByName("Settings")
'Define Colours
cBlack = RGB(0, 0, 0)
cGray01 = RGB(50, 50, 50)
cGray02 = RGB(191, 191, 191)
cWhite = RGB(255, 255, 255)
cDarkRed = RGB(192, 0, 0)
cPinkiDEAL = RGB(204, 0, 102) 'iDeal
cGreenCash = RGB(112, 173, 71) 'Cash Green
cBluePin = RGB(41, 65, 113) 'PIN Blue
cBlueContactless = RGB(58, 125, 193) 'Contactloos Light Blue
cOrangeVisa = RGB(246, 155, 14) 'Visa Orange
'Set Parameters
'Prognosis
ColumnOriginal = 18 'Original Rest Mortgage
ColumnRest = 17 'Actual Rest Mortgae
ColumnPaid = 16 'Reeds afgelost
ColumnPrognosis = 21 'Prognosis Rest Mortgage
ColumnInterestSavedPrognosis = 23 'Bespaarde rente prognose
ColumnInterestSaved = 26 'Bespaarde rente
ColumnExtraTotal = 14 'Column total extra cumulative
ColumnPercent = 24
ColumnPercentPrognosis = 25
'Months
XASColumn = 2
ColumnExtra = 13 'Extra repayment column
ColumnRegular = 12 'Regular repayment column
ColumnInterest = 11 'Interest payment column
ColumnMonthInterest = 3 'Interest payment column
ColumnMonthRegular = 4 'Regular repayment column
ColumnMonthTotal = 9 'Total Monthly repayment column
ColumnSnowball = 7 'Snowball per month column
ColumnWOZ = 17 'WOZ column
ColumnMortgage = 16 'Rest of mortgage column
ColumnVasteLasten = 5 'Regular Interest and Depreciation
ColumnLTV = 21 'LTV Ratio
ColumnPercentageRest = 24 'Percentage Rest Mortgage Paid This Month
ColumnWOZpercentage = 22 'WOZ percentage column
ColumnMortgagePercentage = 26 'Rest of mortgage percentage column
'X-As Values
LastMonthRow = getLastContentIndex("Months", 3)
If wshM.getCellByPosition(1, LastMonthRow).Value = (ThisComponent.NamedRanges.getByName("ChartMonth").getReferredCells.Value + 1) Then
LastMonthRow = LastMonthRow - 1
End If
LastMonth = wshM.getCellByPosition(1, LastMonthRow).Value
LastYear = wshM.getCellByPosition(0, LastMonthRow).Value
xStartRow = 3
xEndRow = LastMonthRow
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "1Y" Then
StartYear = LastYear - 1
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "2Y" Then
StartYear = LastYear - 2
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "3Y" Then
StartYear = LastYear - 3
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "5Y" Then
StartYear = LastYear - 5
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "10Y" Then
StartYear = LastYear - 10
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "15Y" Then
StartYear = LastYear - 15
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
If ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String = "20Y" Then
StartYear = LastYear - 20
StartMonth = LastMonth + 1
If StartMonth = 13 Then
StartYear = StartYear + 1
StartMonth = 1
End If
For i = xStartRow To LastMonthRow
If wshM.getCellByPosition(0, i).Value = StartYear And wshM.getCellByPosition(1, i).Value = StartMonth Then
xStartRow = i
Exit For
End If
Next i
End If
'Global Variable for BlogMarkers
ChartStartRow = StartRow
'Generate New Chart
oCharts = wshC.Charts
If oCharts.Count <> 0 then
For i = 0 to oCharts.Count-1
oChart = oCharts.getByIndex(i)
If oChart.name = "AdminChart" then
oCharts.removeByName("AdminChart")
End If
Next i
End If
Dim oRange as Object
Dim oRangeAddress(1) As New com.sun.star.table.CellRangeAddress
Dim oRect As New com.sun.star.awt.Rectangle
Dim cTitle as String
'Define Point and Size in order to change Position and Size of Chart Objects
Dim Pos_Chart As New com.sun.star.awt.Point
Dim Pos_Title As New com.sun.star.awt.Point
Dim Pos_SubTitle As New com.sun.star.awt.Point
Dim Pos_xTitle As New com.sun.star.awt.Point
Dim Pos_yTitle As New com.sun.star.awt.Point
Dim Pos_Legend As New com.sun.star.awt.Point
Dim Size_Chart As New com.sun.star.awt.Size
Dim Size_Title As New com.sun.star.awt.Size
Dim Size_SubTitle As New com.sun.star.awt.Size
Dim Size_xTitle As New com.sun.star.awt.Size
Dim Size_yTitle As New com.sun.star.awt.Size
Dim Size_Legend As New com.sun.star.awt.Size
oRange = thisComponent.getCurrentSelection.getRangeAddress
oRect.Width = 34000
oRect.Height = 19500
oRect.X = 8650
oRect.Y = 20
cTitle = "AdminChart"
oCharts.addNewByName(cTitle,oRect,oRangeAddress(), TRUE, TRUE)
oChart = oCharts.getByName(cTitle).embeddedObject
oChart.Diagram = oChart.createInstance("com.sun.star.chart.LineDiagram") 'LineDiagram
oDiagram = oChart.Diagram
'Change position and size of chart area in rectangle
oChart.RefreshAddInAllowed = True
Pos_Chart.X = 700
Pos_Chart.Y = 1600
Size_Chart.Width = oRect.Width - 1500
Size_Chart.Height = oRect.Height - 2500
oDiagram.setPosition( Pos_Chart )
oDiagram.setSize( Size_Chart )
'Title and Subtitle of Chart
'oChart.SplineType = 0
oChart.HasMainTitle = True
oChart.Title.String = cTitle
oChart.Title.CharColor = cBlack
oChart.Title.CharFontName = "Liberation Sans"
oChart.Title.CharHeight = 16 ' Font Size
oChart.Title.CharWeight = 0 ' Bold in %
oChart.Title.CharPosture = 0 ' Italics = 1
oChart.HasSubTitle = False
'oChart.SubTitle.String = "Testing the waters"
'oChart.SubTitle.CharColor = cBlue
'oChart.SubTitle.CharFontName = "Liberation Sans"
'oChart.SubTitle.CharHeight = 12 ' Font Size
'oChart.SubTitle.CharWeight = 100 ' Bold in %
'oChart.SubTitle.CharPosture = 0 ' Italics
'Chart Area colours
oDiagram.Wall.FillStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.Wall.FillColor = cWhite 'Chart Area Colour
oDiagram.Wall.LineStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.Wall.LineColor = cBlack 'Chart Area Border Colour
oDiagram.Wall.LineWidth = 20
oChart.Area.FillStyle = com.sun.star.drawing.FillStyle.SOLID
oChart.Area.FillColor = cWhite 'Full Area Colour
'Horizontal Major Grid Lines
oDiagram.HasYAxisGrid = True
oDiagram.YMainGrid.LineStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.YMainGrid.LineColor = cGray02
oDiagram.YMainGrid.LineWidth = 20
'Vertical Major Grid Lines
oDiagram.HasXAxisGrid = False
oDiagram.XMainGrid.LineStyle = com.sun.star.drawing.FillStyle.SOLID
oDiagram.XMainGrid.LineColor = cGray02
oDiagram.XMainGrid.LineWidth = 20
'X-Axis
oDiagram.HasXAxis = True
oDiagram.HasXAxisDescription = True
oDiagram.HasXAxisTitle = True
oXaxis = oDiagram.getXAxis()
oXaxis.AxisTitle.String = "X-Values"
oXaxis.AxisTitle.CharFontName = "Liberation Sans"
oXaxis.AxisTitle.CharColor = cBlack
oXaxis.AxisTitle.CharHeight = 11 ' Font Size
oXaxis.AxisTitle.CharWeight = 0 ' Bold in %
oXaxis.AxisTitle.CharPosture = 0 ' Italics = 1
oXaxis.AutoMin = True
oXaxis.AutoMax = True
'oXaxis.Min = 1
'oXaxis.Max = 5
oXaxis.CharColor = cBlack
oXaxis.CharFontName = "Liberation Sans"
oXaxis.CharHeight = 10 ' Font Size
oXaxis.CharWeight = 100 ' Bold in %
oXaxis.CharPosture = 0 ' Italics
oXaxis.LineColor = cBlack
oXaxis.LineWidth = 20
'Primary Y-Axis
oDiagram.HasYAxis = True
oDiagram.HasYAxisDescription = True
oDiagram.HasYAxisTitle = False
oDiagram.HasYAxis = True
oYaxis = oDiagram.getYAxis()
oYaxis.AxisTitle.String = "Y-Values"
oYaxis.AxisTitle.CharFontName = "Liberation Sans"
oYaxis.AxisTitle.CharColor = cBlack
oYaxis.AxisTitle.CharHeight = 11 ' Font Size
oYaxis.AxisTitle.CharWeight = 0 ' Bold in %
oYaxis.AxisTitle.CharPosture = 0 ' Italics = 1
oYaxis.AutoMin = False
oYaxis.AutoMax = False
oYaxis.Min = 0
oYaxis.Max = 2000
oYaxis.StepMain = 250
oYaxis.CharColor = cBlack
oYaxis.CharFontName = "Liberation Sans"
oYaxis.CharHeight = 10 ' Font Size
oYaxis.CharWeight = 0 ' Bold in %
oYaxis.CharPosture = 0 ' Italics
oYaxis.LineColor = cBlack
oYaxis.LineWidth = 20
oYaxis.LinkNumberFormatToSource = False
oYaxis.NumberFormat = "114"
oChart.HasLegend = 1
oLegend = oChart.getLegend()
oLegend.AutomaticPosition = True
oLegend.Alignment = com.sun.star.chart.ChartLegendPosition.BOTTOM
oLegend.CharHeight = 10 ' Font Size
oLegend.CharWeight = 0 ' Bold in %
oLegend.CharFontName = "Liberation Sans"
oLegend.FillColor = cWhite
oLegend.LineColor = cWhite
oLegend.CharColor = cBlack
oLegend.CharPosture = 0 'Italics
oDiagram.Lines = True
oDiagram.LineColor = cDarkRed
oDiagram.LineWidth = 20
'oChart.DataSourceLabelsInFirstColumn = True
'oChart.DataSourceLabelsInFirstRow = False
'Call Chart Procedure
If ThisComponent.NamedRanges.getByName("ChartType").getReferredCells.String = "Opbouw Stand van Zaken" Then
cTitle = "Opbouw Eigen Woning " & ThisComponent.NamedRanges.getByName("ChartPeriod").getReferredCells.String
Call ChartBuildStatus(xStartRow, xEndRow, cTitle)
End If
End Sub
Once the macro ChartBuildStatus is called, that macro contains the following actions:
I change the chart type of AdminChart to AreaDiagram. That shows up correctly on my screen.
I then try to make it a stacked diagram. But it won’t…
After that, I change some formatting characteristics of the chart, like axis titles and number formats
And I generate the category and data series calling on two other macro’s, CreateDataSequence() and CreateDataSeries_Chart(). I don’think they are the problem, they work correctly with other non-stacked line charts and the series
I have tried a number of things, including moving the stacking code to the end of the macro. But I cannot get it to work correctly. I must be overlooking something or doing something very stupid. So after literally days of trying I am pinning my hopes on the community. Anybody who can shed some light on this?
Sub ChartBuildStatus(xStartRow As Long, xEndRow As Long, cTitle As String)
'Define Colours
cBlack = RGB(0, 0, 0)
cGray01 = RGB(50, 50, 50)
cGray02 = RGB(191, 191, 191)
cWhite = RGB(255, 255, 255)
wshC = ThisComponent.Sheets.getByName("Charts")
wshM = ThisComponent.Sheets.getByName("Months")
oCharts = wshC.Charts
oChart = oCharts.getByName("AdminChart").embeddedObject
oChart.Diagram = oChart.createInstance("com.sun.star.chart.AreaDiagram")
'Stackable Diagram
oChart.Diagram = oChart.createInstance("com.sun.star.chart.StackableDiagram")
oDiagram = oChart.getDiagram()
oChart.setDiagram(oDiagram)
oDiagram = oChart.getDiagram()
With oDiagram
.Stacked = True
.Percent = False
.Vertical = False
End With
ChartUnit = 50000
'Specific Chart Adjustments
oXaxis = oDiagram.getXAxis()
oYaxis = oDiagram.getYAxis()
'Ymax And Ymin
oYaxis.AutoMax = True
oYaxis.Min = 0
'Chart details
oChart.Title.String = cTitle
oDiagram.HasXAxisTitle = False
oYaxis.AxisTitle.String = "EUR"
oYaxis.StepMain = ChartUnit
oYaxis.NumberFormat = "115" ' #,##0
'Data Series Generator
oDataProvider = oChart.getDataProvider()
oDiagram = oChart.getFirstDiagram()
oCooSys = oDiagram.getCoordinateSystems()
oCoods = oCooSys(0) ' this chart has only a coordinate system
oChartTypes = oCoods.getChartTypes() ' chart type one by one
oChartType = oChartTypes(0)
'Data Ranges
xEndRow = getLastContentIndex ("Months", 3 )
Xrange = "Months.C" & (xStartRow + 1) & ":C" & (xEndRow + 1) 'yyyymm
Y1range = "Months.S" & (xStartRow + 1) & ":S" & (xEndRow + 1) 'Overwaarde
Y2range = "Months.T" & (xStartRow + 1) & ":T" & (xEndRow + 1) 'Eigen Geld
Y3range = "Months.M" & (xStartRow + 1) & ":M" & (xEndRow + 1) 'Reguliere Aflossing
Y4range = "Months.N" & (xStartRow + 1) & ":N" & (xEndRow + 1) 'Extra Aflossing
Y5range = "Months.Q" & (xStartRow + 1) & ":Q" & (xEndRow + 1) 'Restant Hypotheek
'Prepare for Data Series
oDataProvider = oChart.getDataProvider()
oDiagram = oChart.getFirstDiagram()
oCooSys = oDiagram.getCoordinateSystems()
oCoods = oCooSys(0) ' this chart has only a coordinate system
oChartTypes = oCoods.getChartTypes() ' chart type one by one
oChartType = oChartTypes(0)
'X-Axis Data series
dim categorySequence as object, categoryRange as string
dim coordinateSystem as object, axis as object
dim scaleData as new com.sun.star.chart2.ScaleData
categorySequence = CreateUnoService("com.sun.star.chart2.data.LabeledDataSequence")
categorySequence.setValues(CreateDataSequence(oDataProvider, Xrange, "categories"))
coordinateSystem = oDiagram.getCoordinateSystems()(0)
axis = coordinateSystem.getAxisByDimension(0, 0)
scaleData = axis.getScaleData()
scaleData.Categories = categorySequence
axis.setScaleData(scaleData)
'Y-Axis Data series
oDataSeriesList = oChartType.getDataSeries()
Dim oNewDataSeriesList(4) As Object ' new data series
oSeries1 = CreateDataSeries_Chart(oDataProvider, Xrange, Y1range, "Overwaarde")
oSeries1.Color = RGB(197, 224, 180)
oSeries1.LineWidth = 60
oNewDataSeriesList(0) = oSeries1
oSeries2 = CreateDataSeries_Chart(oDataProvider, Xrange, Y2range, "EigenGeld")
oSeries2.Color = RGB(0, 176, 80)
oSeries2.LineWidth = 60
oNewDataSeriesList(1) = oSeries2
oSeries3 = CreateDataSeries_Chart(oDataProvider, Xrange, Y3range, "Aflossing")
oSeries3.Color = RGB(146, 208, 80)
oSeries3.LineWidth = 60
oNewDataSeriesList(2) = oSeries3
oSeries4 = CreateDataSeries_Chart(oDataProvider, Xrange, Y4range, "AflossingExtra")
oSeries4.Color = RGB(255, 215, 0)
oSeries4.LineWidth = 60
oNewDataSeriesList(3) = oSeries4
oSeries5 = CreateDataSeries_Chart(oDataProvider, Xrange, Y5range, "RestHypotheek")
oSeries5.Color = RGB(192, 0, 0)
oSeries5.LineWidth = 60
oNewDataSeriesList(4) = oSeries5
'Update chart (only the charttype is updated)
oChartType.setDataSeries(oNewDataSeriesList)
End Sub
On the left the chart as it looks now in my LibreOffice Calc spreadsheet, on the right the chart as I want it to look based on my current Excel sheet.
Left: LibreOffice / Right: Excel (how I want it)
For the sake of completeness, please find the additional macro’s CreateDataSequence() and CreateDataSeries_Chart() below.
CreateDataSequence()
Function CreateDataSequence( oDataProvider As Object, sRangeRepresentation As String, sRole As String ) As Object
Dim oDataSequence As Object
On Error GoTo Handler
' create .chart2.data.DataSequence from range representation
oDataSequence = oDataProvider.createDataSequenceByRangeRepresentation(sRangeRepresentation)
If NOT IsNull(oDataSequence) Then
oDataSequence.Role = sRole
End If
Handler:
CreateDataSequence = oDataSequence
End Function
CreateDataSeries_Chart()
Function CreateDataSeries_Chart( oDataProvider As Object, sXRangeRepresentation As String, sYRangeRepresentation As String, sLabelRangeRepresentation As String ) As Object
Dim oNewDataSeries As Object
oNewDataSeries = CreateUnoService("com.sun.star.chart2.DataSeries")
Dim oData(1) As Object ' x and y: .chart2.data.XLabeledDataSequence
' Y
oDataY = CreateUnoService("com.sun.star.chart2.data.LabeledDataSequence")
oSequenceY = CreateDataSequence(oDataProvider, sYRangeRepresentation, "values-y")
If NOT IsNull(oSequenceY) Then
oDataY.setValues(oSequenceY)
If NOT ((IsMissing(sLabelRangeRepresentation)) AND (sLabelRangeRepresentation <> "")) Then
oSequenceLabel = CreateDataSequence(oDataProvider, sLabelRangeRepresentation, "label") ' ""
oDataY.setLabel(oSequenceLabel) ' oSequenceLabel label is used as name
End If
End If
' X
oDataX = CreateUnoService("com.sun.star.chart2.data.LabeledDataSequence")
oSequenceX = CreateDataSequence(oDataProvider, sXRangeRepresentation, "values-x")
If NOT IsNull(oSequenceX) Then
oDataX.setValues(oSequenceX)
End If
' set x and y data to series
aData = Array(oDataY, oDataX)
oNewDataSeries.setData(aData)
CreateDataSeries_Chart = oNewDataSeries
End Function

LateInitializationError: Local 'res' has not been initialized

I am making a program for encrypting text relative to a keyword. Initially, the algorithm was written in Python, everything worked correctly. I decided to translate it into a mobile application in Flutter, so I had to rewrite it in Dart.
List symbols = ['a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',', ';', ':', '-',
'_', ' ', '!', '#', '#', '\$', '%', '^', '&', '*', '(', ')', '+', '=', '\"', '№', '~', '?',
'\\', '/', '|', '[', ']', '{', '}', '`', '\'', '<', '>'];
late dynamic keyWord = ' ';
late dynamic text = ' ';
late dynamic res;
late dynamic a4;
late dynamic m;
late dynamic n;
late dynamic f;
var d = 0;
var k = 0;
var z = 0;
var operation = 0;
var m1 = 0;
var c = 0;
encode(keyWord, text){
late dynamic res;
var l = (text.length) as int;
for( var i = l ; i >= 1; i-- ){
if(symbols.contains(text[d])) {
var f = symbols.indexOf(text[d]);
a4 = '';
if(f == 0){
a4 = '0';
while(f > 0){
a4 = (f % 4).toString() + a4.toString();
f = f ~/ 4;
}
a4 = '$a4';
}
}
else{
a4 += '1123';
}
while(a4.length != 4) {
a4 = '0' + a4;
}
for( var j = 4 ; j >= 1; j-- ){
res += (keyWord[(a4[z]) as int]);
res.whenComplete((){
setState(() {});
});
z += 1;
}
z = 0;
d += 1;
}
return(res);
}
The encode function does not work due to LateInitializationError: Local 'res' has not been initialized.
The rest of the code works correctly, the res
variable was not called anywhere except for this function. Maybe someone faced the same problem or knows how to solve it? I would be grateful for your help.
Exception is pretty self-explanatory. You access res in res += (keyWord[(a4[z]) as int]);, when it's not yet initialized. You should remove late and do dynamic res = '' for example.
P.S. 'res += value' is basically 'res = res + value'. That's why you get the error
P.S.S Why not to use some typing? Your code's res.whenComplete will fail, because it's not a Future. Seems, that you don't use any code completion at all.

Tradingview Pinescript alert not working as expected

I am using below pinescript and i am not getting alerts as expected. I am aware that it is a repainting script. It is working fine with the back testing.
Long alert is set to "Once per bar close" and short alert is set to "once per bar".
The unexpected behavior is
1) Few times, i am getting short alert though there is no corresponding long alert (though i have taken care in my script, short alert will be sent only when there is a long).
2) Multiple consecutive Short alerts per bar. I am aware that in the realtime bar, the short condition may be true multiple number of times. But since i have set alert to "once per bar", the alert should come only for the first time short condition becomes true.
Please can you let me know if i am doing anything wrong ?
Thanks in advance.
//#version=4
study("My Script",overlay = true)
ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2020, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E
firstrun = true
bought = false
longcondition = false
shortcondition = false
//Just to track first run
firstrun := firstrun[1]
if (firstrun == false)
bought := bought[1]
//once condition is met, send a buy alert and make "bought" equal to true //to enable selling
if (close <= 8600 and bought==false and T)
bought := true
longcondition :=true
alertcondition(longcondition, "Long", "Long")
plotshape(longcondition, title = "Buy", text = 'Buy', style = shape.labelup, location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
if (longcondition)
longcondition :=false
//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
shortcondition := true
bought := false
alertcondition(shortcondition, "short", "short")
plotshape(shortcondition, title = "Sell", text = 'Sell', style = shape.labelup, location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
if (shortcondition)
shortcondition :=false
plotchar(bought, "bought", "", location = location.top)
firstrun := false
You bought variable now automatically saves its value bar to bar and I have removed the late reinitializations of vars in your script. Seems to be working fine here:
//#version=4
study("My Script",overlay = true)
ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2000, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E
var bought = false
longcondition = false
shortcondition = false
//once condition is met, send a buy alert and make "bought" equal to true //to enable selling
if (close <= 8600 and bought==false and T)
bought := true
longcondition :=true
//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
shortcondition := true
bought := false
alertcondition(longcondition, "Long", "Long")
alertcondition(shortcondition, "short", "short")
plotshape(longcondition, title = "Buy", text = 'Buy', style = shape.labelup, location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
plotshape(shortcondition, title = "Sell", text = 'Sell', style = shape.labelup, location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
// For debugging.
plotchar(bought, "bought", "•", location = location.top)
if buy signal is generated continuously for two sessions, then it will not appear till sell signal is generated.

Sort lines by date (DD.MM.YYYY)

Is there a possibility to sort lines within a textfile by date and save the results to another output file? Each line begins with a date (DD.MM.YYYY). Delimiter between date and text is Tab (no space). I prefer a solution in VBS.
Source
25.11.1968 Death of Upton Sinclair
14.06.1946 Birthday Donald Trump
25.11.2016 Death of Fidel Castro
14.06.1969 Birthday Steffi Graf
01.01.2017 New Year
to the new order (target)
01.01.2017 New Year
14.06.1946 Birthday Donald Trump
14.06.1969 Birthday Steffi Graf
25.11.1968 Death of Upton Sinclair
25.11.2016 Death of Fidel Castro
Order to change and compare: Month-Day-Year
Here, it's not pretty and it doesn't sort in reverse order as you wanted, but hopefully this will teach you something if you learn like I do...
Option Explicit
Const fsoForReading = 1
Const fsoForWriting = 2
inputFile = "input.txt"
outputFile = "output.txt"
dim inputFile, outputFile, lineCount, file, fline, lDate, lYear, lMonth, lDay, iDate,output
dim a, d, i
dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
set a = CreateObject("System.Collections.ArrayList")
set d = CreateObject("Scripting.Dictionary")
'open up the file for reading
Set objFile = objFSO.GetFile(inputFile)
Set file = objFile.OpenAsTextStream(fsoForReading,-2)
Do Until file.AtEndOfStream
fline = file.ReadLine 'get the line
lDate = left(fline,10) 'get the date portion at the beginning (the first 10 characters)
lYear = split(lDate,".")(2) 'parse the year from the date
lMonth = split(lDate,".")(1) 'parse the month
lDay= split(lDate,".")(0) 'parse the day
iDate = lYear + lMonth + lDay 'put together the "index date". The date needs to be formatted as yyyymmdd so it is sortable
a.add iDate 'add the index date to an array for easier sorting
d.add iDate, fline 'add the index date and line contents to a dictionary object
Loop 'go to the next line in the file
a.Sort() 'sort the array of dates
for each i in a 'loop through the array of dates
output = output + d(i) + vbCrlf 'add the appropriate dictionary object to the output
Next
call writeFile(output) 'write the file
file.Close
WScript.Quit 0
sub writeFile(fc)
dim fso
'fn = fn + ".hl7"
Set fso = CreateObject("Scripting.FileSystemObject")
if (fso.FileExists(outputFile)) then
Set objFile = fso.OpenTextFile(outputFile,8,True)
objFile.writeline fc
objFile.Close
else
Set objFile = fso.CreateTextFile(outputFile,True)
objFile.writeline fc
objFile.Close
end if
end sub

excel 2010: based on a radio button selection save user from date to ain a different worksheet

I have a excel form which works and saves data to just one worksheet. I like to be able to put a radio button and based on that selection i like to save to a diffent work sheet.
example:
if radio button 1 is selected save to sheet1
if radio button 2 is selected save to sheet2
if radio button 3 is selected save to sheet3
same form used to save on different worksheet.
the code im working with.
Private Sub btn_append_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Assessment")
'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'check for a part number
If Trim(Me.txt_roomNumber.Value) = "" Then
Me.txt_roomNumber.SetFocus
MsgBox "Please enter a Room Number"
Exit Sub
End If
'copy the data to the database
'use protect and unprotect lines,
' with your password
' if worksheet is protected
With ws
' .Unprotect Password:="password"
.Cells(iRow, 1).Value = Me.txt_roomNumber.Value
.Cells(iRow, 2).Value = Me.txt_roomName.Value
.Cells(iRow, 3).Value = Me.txt_department.Value
.Cells(iRow, 4).Value = Me.txt_contact.Value
.Cells(iRow, 5).Value = Me.txt_altContact.Value
.Cells(iRow, 6).Value = Me.cbx_devices.Value
.Cells(iRow, 7).Value = Me.cbx_wallWow.Value
.Cells(iRow, 8).Value = Me.txt_existingHostName.Value
.Cells(iRow, 10).Value = Me.cbx_relocate.Value
If Me.ckb_powerbar.Value = True Then Cells(iRow, 11).Value = "Y"
If Me.ckb_dataJackPull.Value = True Then Cells(iRow, 12).Value = "P"
.Cells(iRow, 13).Value = Me.txt_existingDataJack.Value
If Me.ckb_hydroPull.Value = True Then Cells(iRow, 14).Value = "P" Else Cells(iRow, 14).Value = "A"
.Cells(iRow, 19).Value = Me.txt_cablePullDesc.Value
.Cells(iRow, 20).Value = Me.txt_hydroPullDesc.Value
.Cells(iRow, 21).Value = Me.Txt_otherDesc.Value
' .Protect Password:="password"
End With
'clear the data
'Me.txt_roomNumber.Value = ""
'Me.txt_roomName.Value = ""
'Me.txt_department.Value = ""
'Me.txt_contact.Value = ""
'Me.txt_altContact.Value = ""
Me.cbx_relocate.Value = ""
Me.txt_existingHostName = ""
Me.txt_altContact.SetFocus
End Sub
Private Sub btn_close_Click()
Unload Me
End Sub
Private Sub ComboBox1_Change()
End Sub
Private Sub UserForm_Click()
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
MsgBox "Please use the Close Form button!"
End If
End Sub
The first thing to do is to add the radio-buttons (actually OptionButton) to the form and name them.
Then to check if one of them is selected use code such as:
If optSheet1 Then
'it is checked
ElseIf optSheet2 Then
'the second one is checked
'etc
End If