Undeclared identifier on pinescript for a backtest strategy - pine-script-v4

I can't find my error in this code. Could you help me? This is supposed to be a test code for backtesting in pinescript version 4. The Error is "undeclared identifier 'macdval' and 'macdsignalVal' ligne 38 and 38
//#version=4
// Paramètres de l'indicateur MACD
fastMA = 12
slowMA = 26
signalMA = 9
// Paramètres de l'indicateur RSI
lengthRSI = 14
overbought = 70
oversold = 30
study("My Script", overlay=true)
macdVal = macd(fastMA, slowMA, signalMA)
macdSignalVal = ema(macdVal, signalMA)
rsiVal = rsi(close, lengthRSI)
// Variables pour stocker les positions d'achat et de vente
buyPrice = 0.0
sellPrice = 0.0
// Vérifier les conditions d'entrée
if crossover(macdVal, macdSignalVal) and rsiVal < oversold
strategy.entry("Long", strategy.long)
else if crossunder(macdVal, macdSignalVal) and rsiVal > overbought
strategy.entry("Short", strategy.short)
// Vérifier les conditions de sortie
if crossover(macdVal, macdSignalVal) or rsiVal > overbought
strategy.exit("Long")
else if crossunder(macdVal, macdSignalVal) or rsiVal < oversold
strategy.exit("Short")
// Afficher les indicateurs sur le graphique
plot(macdVal, color = color.blue, linewidth = 2)
plot(macdSignalVal, color = color.red, linewidth = 2)
plot(rsiVal, color = color.yellow, linewidth = 2)
I searched through the code for the error but could not find it

Related

Autofill formulas in multiple sheets

I have a problem to address, I have a Gsheet with many sheets that have columns with many formulas, for example I have a sheet AD that in the column A, N, O, P, Q, R, S , T , U, V , W , Y and Z have formulas. I have solved it with the script that I put here but it takes too long.
The thing is that in this Gsheet I have more sheets with as many formulas as the AD sheet, I have a MAIL etc sheet that has formulas in skipped columns, how can I optimize the script so that it copies formulas in the column that has formulas and drags them to the last column with data?
`
function autoFill(){
var spreadsheet = SpreadsheetApp.getActive();
var hojaAD = spreadsheet.getSheetByName('AD');
var copiaA2 = hojaAD.getRange('A2');
var destinationRangeA = hojaAD.getRange(2,1,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaA2.copyTo(destinationRangeA);
var copiaO2 = hojaAD.getRange('O2');
var destinationRangeO = hojaAD.getRange(2,15,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaO2.copyTo(destinationRangeO);
var copiaP2 = hojaAD.getRange('P2');
var destinationRangeP = hojaAD.getRange(2,16,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaP2.copyTo(destinationRangeP);
var copiaQ2 = hojaAD.getRange('Q2');
var destinationRangeQ = hojaAD.getRange(2,17,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaQ2.copyTo(destinationRangeQ);
var copiaR2 = hojaAD.getRange('R2');
var destinationRangeR = hojaAD.getRange(2,18,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaR2.copyTo(destinationRangeR);
var copiaS2 = hojaAD.getRange('S2');
var destinationRangeS = hojaAD.getRange(2,19,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaS2.copyTo(destinationRangeS);
var copiaT2 = hojaAD.getRange('T2');
var destinationRangeT = hojaAD.getRange(2,20,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaT2.copyTo(destinationRangeT);
var copiaU2 = hojaAD.getRange('U2');
var destinationRangeU = hojaAD.getRange(2,21,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaU2.copyTo(destinationRangeU);
var copiaV2 = hojaAD.getRange('V2');
var destinationRangeV = hojaAD.getRange(2,22,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaV2.copyTo(destinationRangeV);
var copiaW2 = hojaAD.getRange('W2');
var destinationRangeW = hojaAD.getRange(2,23,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaW2.copyTo(destinationRangeW);
var copiaY2 = hojaAD.getRange('Y2');
var destinationRangeY = hojaAD.getRange(2,25,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaY2.copyTo(destinationRangeY);
var copiaZ2 = hojaAD.getRange('Z2');
var destinationRangeZ = hojaAD.getRange(2,26,hojaAD.getLastRow()-1); //el 2 es la fila y el 1 la column
copiaZ2.copyTo(destinationRangeZ);
}
`
I have tried to make a script but it is slow
Grouping columns as suggested by #GiampaoloFerradini.
Instead of 12 discrete columns, the function applies to three discrete groups:
Column A
Column O-W inclusive
Column Y-Z inclusive
Column X is omitted; just as it is not part of the discrete columns in the OP script.
function autoFill(){
var spreadsheet = SpreadsheetApp.getActive();
var hojaAD = spreadsheet.getSheetByName('AD');
// CopiaA2
var copiaA2 = hojaAD.getRange(2,1)
// Logger.log("DEBUG: copiaA2 is "+copiaA2.getA1Notation())
var copiaA2LR = hojaAD.getLastRow()
// Logger.log("DEBUG: last row = "+copiaA2LR)
var destinationRangeA = hojaAD.getRange(2,1,(copiaA2LR-1),1)
// Logger.log("DEBUG: destination rangeA = "+destinationRangeA.getA1Notation())
copiaA2.copyTo(destinationRangeA)
// CopiaO2-W2
var copiaOW2 = hojaAD.getRange(2,15,1,9)
// Logger.log("DEBUG: copiaOW2 is "+copiaOW2.getA1Notation())
var destinationRangeOW = hojaAD.getRange(2,15,(copiaA2LR-1),9)
// Logger.log("DEBUG: destination rangeOW = "+destinationRangeOW.getA1Notation())
copiaOW2.copyTo(destinationRangeOW)
// CopiaY2-Z2
var copiaYZ2 = hojaAD.getRange(2,25,1,2)
// Logger.log("DEBUG: copiaYZ2 is "+copiaYZ2.getA1Notation())
var destinationRangeYZ = hojaAD.getRange(2,25,(copiaA2LR-1),2)
// Logger.log("DEBUG: destination rangeYZ = "+destinationRangeYZ.getA1Notation())
copiaYZ2.copyTo(destinationRangeYZ)
}

error about negative ou NA values in a array when using absolute values

a = 2;
epsilon = 1e-10;
t0 = 1;
N = 20;
function t = metodoDeNewton(a, t0, N, epsilon)
t = zeros(1, N+1);
t(1) = t0;
for i = 1:N
t(i+1) = t(i) - (t(i)^2 - (a - sin(t(i)))) / (2 * t(i) - cos(t(i)));
if (abs(t(i+1) - t(i)) < epsilon)
break;
endif
endfor
endfunction
t = metodoDeNewton(a, t0, N, epsilon);
% Mostra a última iteração, que é a aproximação da raiz da equação
disp(t(end));
% Estima a ordem de convergência e o coeficiente assintótico de convergência
% Para isso, calcula a razão entre duas iterações consecutivas e a razão entre
% o erro absoluto dessas iterações e o erro absoluto das iterações anteriores
r = zeros(1, length(t) - 1);
k = zeros(1, length(t) - 1);
for i = 2:length(t)
r(i-1) = t(i) / t(i-1);
k(i-1) = (abs(t(i) - t(i-1))) / (abs(t(i-1) - t(i-2)));
endfor
% Mostra a razão e o coeficiente assintótico de convergência
x = disp(r(end));
y = disp(k(end));
This code gives me the error error: t(0): subscripts must be either integers 1 to (2^63)-1 or logicals I understand this is because my k variable calculates a negative integer maybe, and I don't really understand why, since my values will allways be positive. I thought that maybe it's because the for loop might be trying to calculate NA values, but even so, how do I fix that?

How do i use the second function i've created?

It's giving me an error ( value on right hand side of assignment is undefined) when i want to call the second function that i've created on line 12
function cosaprox
clc, clear
%d es el incremento y c sera la aproximacion del coseno
d = pi/100;
c = 0;
tol = 0.2;
i = 0;
flag = true;
%Aproximacion del cos
while flag
%Iteracion de la sumatoria
x=facto (2*i)
i+=1
if abs(c - cos(2*pi))>= tol
flag = false
else
endif
endwhile
disp (c)
end
function facto (x)
if x==0;
x=1;
endif
for h = 1:x-1
x = x*h;
endfor
end

how to format mysql float into sytem local values or decimal comma for a reportlab billing system

I have a Reportlab form for a billing system and it works good. But what I want to get are the values in sytem local values, with decimal comma, or separator; something as next instead as shown in the picture:
1,350,000.00
I'd like something like FORMAT in MySQL, but the problem with this one is that it does'nt let me to sum the values to get the total because it returns the values as string.
SELECT FORMAT (columna, 'es_CO') FROM tabla;
How my form looks like
And my Python code:
Just retefuente, ivajuridico, rteiva and i_vlrenta are float in mysql
#!/usr/bin/python
#-*- coding:utf-8 -*-
from Tkinter import*
from tkMessageBox import*
import MySQLdb
from controller import *
import analisis_arrendatarios
import os
import datetime
import time
import locale
locale.setlocale(locale.LC_ALL, "")
#LIBRERÍA PLATYPUS DE REPORTLAB PARA CREAR TABLAS
from reportlab.platypus import (SimpleDocTemplate, PageBreak, Image, Spacer,
Paragraph, Table, TableStyle)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']
class Proceso_Fact_Auto_Arre(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
global opt
#VARIABLES
opt = IntVar()
#WIDGETS
header = Label(self, text="TENANTS AUTO BILLING PROCESS", font="bold")
header.pack(pady=20, side=TOP)
wrapper = Frame (self)
wrapper.pack()
r1 = Radiobutton(wrapper, text="Generate Analysis", variable=opt, value=0).pack(pady=5, anchor=W)
r2 = Radiobutton(wrapper, text="Generate Billings", variable=opt, value=1).pack(pady=5, anchor=W)
Button(wrapper, text="Iniciar Proceso", bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=operacion).pack(pady=5, anchor=W)
def operacion():
if opt.get()==0:
showinfo('Operation', "Generate Analysis")
try:
connect.commit()
#Consulta de códigos y valores de la tabla 'configuracion'
cursor.execute("SELECT cod_canon, cod_subtotalarrend, cod_ivaarrend,
retefuente, ivajuridico, rteiva, resolucion
FROM configuracion;")
dato1 = cursor.fetchall()
#Consulta de datos generales del propietario y el arrendatario para la factura
cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, i_vlrenta, i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
FROM contratos
INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
#cursor.execute("SELECT p_cc, dueño, r_carpeta, relacionip.i_cod, i_dir, FORMAT(SUM(i_vlrenta), 2,'es'), i_tel, contratos.a_cc, inquilino, a_tpersona, a_contribuyente
#FROM contratos
#INNER JOIN relacionip ON contratos.r_id = relacionip.r_id
#INNER JOIN inmuebles ON relacionip.i_cod = inmuebles.i_cod
#INNER JOIN arrendatarios ON contratos.a_cc = arrendatarios.a_cc;")
dato2 = cursor.fetchall()
except:
pass
for c in dato1:
canon = c[0]
subtotal = c[1]
iva = c[2]
retef = c[3]
ivajuridi = c[4]
retei = c[5]
resolucion = c[6]
doc = SimpleDocTemplate("facturas/factura_auto_inquilino.pdf", pagesize = (595.27,400.00), rightMargin=5, leftMargin=5, topMargin=10, bottomMargin=0)
story=[]
for i in dato2:
nit = i[0]
prop = i[1]
folder = i[2]
inm = i[3]
loc = i[4]
renta = i[5]
tel = i[6]
cc = i[7]
arrend = i[8]
tipo = i[9]
contri = i[10]
#SI ARREND ES NATURAL(1)
if tipo == 1:
tipo = 0
#SI ARREND ES JURÍDICO(2)
if tipo == 2:
tipo = renta*ivajuridi/100
total = renta+tipo
tiempo = datetime.date.today()
anio = time.strftime("%Y")
mes = time.strftime("%B")
#-------------------------------------------- CABECERA DEL DOCUMENTO
#VARIABLES
logo = Image("img/logo.gif", width=150, height=45) #LOGO
logo.hAlign ='LEFT' #Posicion de la img en la hoja
info = Paragraph('''<para align=center leading=8><font size=6>CALLE 11A N°42-68 LOC,195 ED. EL DORADO<br/>TELEFONO: 3110513 FAX:2664154<br/>AFILIADO A FENALCO<br/>M.A.V.U N°000078</font></para>''', styleSheet["BodyText"])
tipoDoc = Paragraph ('''<para align=right><b>FACTURA DE VENTA<br/>N°</b></para>''', styleSheet["BodyText"])
#TABLA 1
tabla1 = Table([[logo, info, tipoDoc]], colWidths=[200,150,140], rowHeights=None)
tabla1.setStyle([
('VALIGN', (1,0), (2,0), 'TOP'),
('ALIGN', (2,0), (2,0), 'RIGHT')#ALINEAR A LA DER
])
story.append(tabla1) #Construye la tabla 't' definida anteriormente
story.append(Spacer(0,-10)) #Espacio del salto de línea con el siguiente Ejemplo
#-------------------------------------------- DATOS GENERALES DEL DOCUMENTO
#VARIABLES
inquilino = Paragraph ('''<font size=6><b>Nombre Arrendatario:</b><br/></font>%s'''%arrend, styleSheet["BodyText"])
docID = Paragraph ('''<font size=6><b>CC/Nit: </b></font> %s''' %nit, styleSheet["BodyText"])
locImn = Paragraph ('''<font size=6><b>Dirección Inmueble:</b><br/></font>%s'''%loc, styleSheet["BodyText"])
telefono = Paragraph ('''<font size=6><b>Teléfono:</b><br/></font>%s'''%tel, styleSheet["BodyText"])
IDpropietario = Paragraph ('''<font size=6><b>CC/Nit:</b><br/></font>%s'''%cc, styleSheet["BodyText"])
propietario = Paragraph ('''<font size=6><b>Propietario: </b></font>%s'''%prop, styleSheet["BodyText"])
fechaFormato = Paragraph ('''<para align=center fontSize=6>Día Mes Año</para>''', styleSheet["BodyText"])
hoy = time.strftime("%d/%m/%Y")
fecha = Paragraph ('''<para align=center spaceBefore=0>%s</para>''' %hoy, styleSheet["BodyText"])
codigoImn = Paragraph ('''<font size=6><b>Código Inmueble:</b><br/></font>%s'''%inm, styleSheet["BodyText"])
#TABLA 2
datos = [[inquilino,'','','','',[fechaFormato,fecha]],
[docID,'','',propietario,'',''],
[locImn,'',telefono,IDpropietario,'',codigoImn]]
tabla2 = Table(datos,
style=[('BOX',(0,0),(2,2),0.5,colors.black),
('VALIGN', (0,0),(2,0),'TOP'),
('SPAN',(0,0),(2,0)),#Combinar 3 filas (col0,row0) hasta (col2,row0) Arrendatario #0
('SPAN',(0,1),(2,1)),#Combinar 3 filas CC/Nit #1
('SPAN',(0,2),(1,2)),#Combinar 2 filas Dirección #2
('SPAN',(3,1),(5,1)),#Combinar 3 filas Nombre Propietario #
('SPAN',(3,2),(4,2)),#Combinar 2 filas CC/Nit Propietario #
('GRID',(3,1),(4,2),0.5,colors.black),
('GRID',(5,0),(5,2),0.5,colors.black)
],colWidths=[100,90,90,90,80,70], rowHeights=None)
#Constructor y espaciado
story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
story.append(tabla2) #Construye la tabla 't' definida anteriormente
#-------------------------------------------- DETALLES DEL DOCUMENTO
#VARIABLES
desc = Paragraph('''<para align=center><b>DESCRIPCION</b></para>''', styleSheet["BodyText"])
vlr = Paragraph('''<para align=center><b>VALOR</b></para>''', styleSheet["BodyText"])
concepto = Paragraph('''Valor Arrendamiento Mes: %s/%s''' % (mes,anio), styleSheet["BodyText"])
resol = "Resolucion Dian N°110000658514 de Diciembre de 2015 Consectivo Facturacion 33001 al 36000. P"
#TABLA 3
data=[[desc, '', vlr], #0
[concepto, '', renta], #1
['', '', ''], #2
['', '', ''], #3
['', '', ''], #4
['', '', ''], #5
['', '', ''], #6
['Observaciones', 'SUBTOTAL', renta], #7
['', 'IVA', tipo], #8
[resolucion, 'TOTAL', total]] #9
#Formato de la tabla
tabla3 = Table(data,
style=[('GRID',(0,0),(2,0),0.5,colors.black),#Color regilla de DESCRIPCION & VALOR
('BOX',(2,1),(2,9),0.5,colors.black), #Color & grosor de la tabla/marco externo de los VALORES
#('BACKGROUND',(0,0),(2,0), colors.pink), #Color de fondo de DESCRIPCION & VALOR #0
('SPAN',(0,0),(1,0)), #Combinar filas DESCRIPCION #0
('BOX',(0,1),(2,6),0.5,colors.black), #Color & grosor de la tabla o marco externo de los DETALLES
('ALIGN', (2,1), (2,1), 'RIGHT'),#Centrar renta #1
('ALIGN', (2,7), (2,7), 'RIGHT'),#Centrar renta #7
('ALIGN', (2,8), (2,8), 'RIGHT'),#Centrar tipo #8
('ALIGN', (2,9), (2,9), 'RIGHT'),#Centrar total #9
#('ALIGN', (2,9), (2,9), 'CENTER'),#Centrar total #9
('SPAN',(0,1),(1,1)), #Combinar filas de Detalle #1
('SPAN',(0,2),(1,2)), #Combinar filas de Detalle #2
('SPAN',(0,3),(1,3)), #Combinar filas de Detalle #3
('SPAN',(0,4),(1,4)), #Combinar filas de Detalle #4
('SPAN',(0,5),(1,5)), #Combinar filas de Detalle #5
('SPAN',(0,6),(1,6)), #Combinar filas de Detalle #6
('GRID',(1,7),(2,9),0.5,colors.black),#Color regilla de SUBTOTAL, IVA, TOTAL
('BOX',(0,7),(0,9),0.5,colors.black), #Color & grosor de la tabla o marco externo de los OBSERVACIONES Y RESOLUCION
('FONTSIZE', (0,9),(0,9),7), #Tamaño de la Resolucion
#('BACKGROUND',(1,9),(1,9),colors.black),#Color de fondo de TOTAL
('TEXTCOLOR',(1,9),(1,9),colors.black), #Color de letra de TOTAL
#('BACKGROUND',(2,9),(2,9),colors.grey)#Color de fondo de VALOR TOTAL
],colWidths=[340,80,100], rowHeights=None)
story.append(Spacer(0,15)) #Espacio del salto de línea con el siguiente Ejemplo
story.append(tabla3) #Construye la tabla 't' definida anteriormente
#-------------------------------------------- FIN PDF
doc.build(story) #Constructor del documento
if sys.platform == 'linux2':
os.system("xdg-open ~/Project/facturas/factura_auto_inquilino.pdf")#DEBIAN
elif sys.platform == 'linux2':
os.system("/usr/bin/gnome-open facturas/factura_auto_inquilino.pdf")#UBUNTU
else:
os.startfile("Project/facturas/factura_auto_inquilino.pdf")#WINDOWS
else:
#Code to insert data into a billinf table)
SELECT FORMAT(SUM(columna), 2, 'es_CO') FROM tabla;
For example:
mysql> SELECT FORMAT(SUM(population), 3, 'es_CO') FROM canada;
+-------------------------------------+
| FORMAT(SUM(population), 3, 'es_CO') |
+-------------------------------------+
| 23584718,000 |
+-------------------------------------+
1 row in set (0.01 sec)
I suspect you wanted something like
| 23.584.718,000 |
Then I suggest you file a bug with bugs.mysql.com . It seems that the 'grouping separator' is incorrect?
Meanwhile, will 'es' (instead if 'es_CO') work correctly enough?
As some guys suggested, what I had to do was: sum the values, which was already done in my code, add a new variable appling a format with 'locale.format', and then just place that variable in the corresponding place in the reportlab form. For the total value it was not necessary to create a new variable, but just apply locate.
So, I added to my code something like this:
for i in dato2:
#...
renta = i[5]
#New var to show value with thousands separator in the form
renta1 = locale.format("%d", renta, grouping=True)
tipo = i[9]
#SI ARREND ES NATURAL(1)
if tipo == 1:
tipo = 0
#New var to show value with thousands separator in the form
tipo1 = locale.format("%d", tipo, grouping=True)
#SI ARREND ES JURÍDICO(2)
if tipo == 2:
tipo = renta*ivajuridi/100
#New var to show value with thousands separator in the form
tipo1 = locale.format("%d", tipo, grouping=True)
total = locale.format("%d", renta+tipo, grouping=True)
#REPORTLAB FORM TABLA 3
data=[[desc, '', vlr], #0
[concepto, '', renta], #1
['', '', ''], #2
['', '', ''], #3
['', '', ''], #4
['', '', ''], #5
['', '', ''], #6
['Observaciones', 'SUBTOTAL', renta], #7
['', 'IVA', tipo], #8
[resolucion, 'TOTAL', total]] #9

Order by ASC returning weird results

I have the following query :
SELECT
x.id,x.title
FROM `x`
WHERE `x`.status = 'validated'
ORDER BY `x`.title ASC
Results :
3042 Cinéastes en herbe Télé-Québec
1681 Danse contemporaine
2725 Dessins, peinture et illustrations.
2448 Les petits mots de Paolo
641 Ma tente à lire et les Mosaïques dans la rue
3215 Performance & Visites commentées
2186 Se partager l’espace : Yann Pocreau
2364 Souper communautaire
1223 100 ans
199 100% couleurs
2794 125 ans de tourisme à Laval
2306 À court de souffle!
1517 Abracadabra Sonia
2477 Atelier ouvert
335 Au bout du fil
2362 Au coeur de notre mémoire
2489 Bientôt 100 ans!
2275 Café historique
1838 Rencontre avec
Am i missing something ? Why the title is not ordered correctly ?
For info :
Collation : utf8_general_ci
Character set : utf-8
Solution : a hidden space was in the results --> used the trim function
I would check the first few rows to see if there is a hidden character at the front of the title.
SELECT
ASCII(SUBSTRING(x.title, 1, 1))
FROM
x
WHERE
x.id IN (3042, 1681)
Maybe you are not using the collation you want to. Depending on the collation of your database, strings get ordered differently.