Pinescript - Syntax error at input 'long_entry' - if-statement

I have an issue with prinescript. I don't get how to fix this, line 23. When I use an if statementwhen, I use the ?: I don't get the error.
//#version=5
indicator("Test 1", overlay = true)
// Define the indicators
ema = ta.ema(close, 200)
atr14 = ta.atr(14)
long_entry = false
short_entry = false
// Define the conditions for consecutive open and close prices
long_condition = (close[2] < open[2] and close[1] < open[1] and close > open[1]) and (close > open)
or (close[3] < open[3] and close[2] < open[2] and close > open[2]) and (close > open)
or (close[4] < open[4] and close[3] < open[3] and close > open[3]) and (close > open)
or (close[5] < open[5] and close[4] < open[4] and close > open[4]) and (close > open)
or (close[6] < open[6] and close[5] < open[5] and close > open[5]) and (close > open)
short_condition = (close[2] > open[2] and close[1] > open[1] and close < open[1]) and (close > open)
or (close[3] > open[3] and close[2] > open[2] and close < open[2]) and (close < open)
or (close[4] > open[4] and close[3] > open[3] and close < open[3]) and (close < open)
or (close[5] > open[5] and close[4] > open[4] and close < open[4]) and (close < open)
or (close[6] > open[6] and close[5] > open[5] and close < open[5]) and (close < open)
// Define the conditions for long and short positions
if long_condition and close > ema and barstate.isconfirmed
long_entry := true
if short_condition and close < ema and barstate.isconfirmed
short_entry := true
// Define the stop loss
long_stop = close - (atr14 * 2)
short_stop = close + (atr14 * 2)
I looked around but couldn't find a solution.

If blocks must be indented by four spaces or a tab. You have five spaces in below if statements:
// Define the conditions for long and short positions
if long_condition and close > ema and barstate.isconfirmed
long_entry := true
if short_condition and close < ema and barstate.isconfirmed
short_entry := true
So, change it to:
// Define the conditions for long and short positions
if long_condition and close > ema and barstate.isconfirmed
long_entry := true
if short_condition and close < ema and barstate.isconfirmed
short_entry := true
Note: The script must have at least one output function call (e.g. plot, barcolor, etc.).

Related

Boolean input to negate if statements in pinescript

In short I have an indicator that has multiple requirements for setting background colors and bar colors. All of this was fine until I wanted to add a small wrinkle to it.
Basically I have two lines (plots), one of which I call the signal line and the other the baseline, If a value is above one or the other then the background is blue and if it is below then background is red (this also goes for barcolor if people so wish to have bar coloring on). I have two separate boolean inputs for each of these two lines so that the background color or bar color is colored depending on what the user prefers. I also have a boolean for bar colors just when the value crosses up or down one of the two lines, but we'll ignore that to keep this simpler.
One of the two lines I mentioned above is a moving average (signal line) of the values being measured by the indicator. I want to add a boolean input that if true only colors the bars or background IF the signal line is increasing and not if it is decreasing.
So, if value is above signal line or baseline AND signal line is rising then color background blue, and if not, red. The problem I've run into is that regardless of the signal line rising being true, if the indicator value is above the signal or baseline then the background or bars are always going to be colored in those areas. What I want is if the boolean input for the rising signal line is true then it ONLY colors behind those areas where it is true and no other areas. If that makes sense. Problem is it always colors for areas where the indicator value is above the signal/baseline regardless if the signal line is rising or not, even if the boolean for a rising signal line is true, which defeats the purpose of having this rising signal line requirement.
I'm going to add the pertinent code below. If someone could help that would be wonderful. I can't figure out how to make a negation of background colors and bar colors, which it seems is what I need? The only other alternative I can think of (because I'm an awful coder) is to have separate boolean inputs for 'if value is above signal line' and 'if value is above signal line and signal line is rising' and 'if value is above baseline' and 'if value is above baseline and signal line is rising', plus bar coloring and the crossing up or down vs. being simply above or below. This would make for a grand total of 16 boolean inputs, which is insane obviously.
//BAR COLOR AND BACKGROUND COLOR SIGNAL LINE INPUTS
barcolor_signal = input.bool(defval=false, title='Bar Colors', group='Signal Line')
bg_signal = input.bool(defval=false, title='Background Colored', group='Signal Line')
xover_signal = input.bool(false, 'Volatility Advance', group='Signal Line')
xunder_signal = input.bool(false, 'Volatility Decline', group='Signal Line')
//BAR COLOR AND BACKGROUND COLOR BASELINE INPUTS
barcolor_bline = input.bool(defval=true, title='Bar Colors', group='Baseline')
bg_bline = input.bool(defval=false, title='Background Colored', group='Baseline')
xover_bline = input.bool(false, 'Volatility Advance', group='Baseline')
xunder_bline = input.bool(false, 'Volatility Decline', group='Baseline')
////BOOLEAN
signal_rise = input.bool(defval=true, title='Require Signal Line Rising', tooltip='Require the signal line to be rising to highlight increasing volatility.')
For the inputs, the first group is for if the value is above/below or crossing the signal line, the second group is for if the value is above/below or crossing the baseline, and the last input is signal line rising input.
///BACKGROUND AND CANDLE COLORING
sig_rise = signal_rise and signal_line > signal_line[1]
bline_rise = avg_range > baseline
bline_fall = avg_range < baseline
avg_sig_rise = avg_range > signal_line
avg_sig_fall = avg_range < signal_line
bgcolor(bg_bline and bline_rise ? color.new(#445b84, 50) : bg_bline and bline_fall ? color.new(#844444, 100) : na, title='Baseline Background')
bgcolor(sig_rise and bg_bline and bline_rise ? color.new(#445b84, 50) : sig_rise and bg_bline and bline_fall ? color.new(#844444, 100) : na, title='Baseline Background | Signal Line Rising')
bgcolor(bg_signal and avg_sig_rise ? color.new(#445b84, 50) : bg_signal and avg_sig_fall ? color.new(#844444, 100) : na, title='Signal Line Background')
bgcolor(sig_rise and bg_signal and avg_sig_rise ? color.new(#445b84, 50) : sig_rise and bg_signal and avg_sig_fall ? color.new(#844444, 100) : na, title='Signal Line Background | Signal Line Rising')
I'm not adding the code for barcolor because whatever solution there is should work for that too I would think.
You can see in the first line for bgcolor that that is the simplest--if background is true and avg_range is above baseline then COLOR. The one below requires the signal line to be rising, and the two below are if the avg_range is above the signal line.
I need for the first and third lines to be false if the second or fourth are true, OR I need another way to write this.
Appreciate any help with this.
Basically the way you use ternary operators in your bgcolor() is correct.
If those bgs are dependent on each other I'd evaluate first in variables then apply the coloring.
baseLineRising = bg_bline and bline_rise
baseLineFalling = bg_bline and bline_fall
baseLineRisingSigRising = sig_rise and bg_bline and bline_rise
baseLineFallingSigRising = sig_rise and bg_bline and bline_fall
avgSigRising = bg_signal and avg_sig_rise
avgSigFalling = bg_signal and avg_sig_fall
sigRisingAvgRising = sig_rise and bg_signal and avg_sig_rise
sigRisingAvgFalling = sig_rise and bg_signal and avg_sig_fall
bgcolor(baseLineRising ? color.new(#445b84, 50) : baseLineFalling ? color.new(#844444, 100) : na, title='Baseline Background')
bgcolor(baseLineSigRising ? color.new(#445b84, 50) : baseLineFallingSigRising ? color.new(#844444, 100) : na, title='Baseline Background | Signal Line Rising')
bgcolor(avgSigRising ? color.new(#445b84, 50) : avgSigFalling ? color.new(#844444, 100) : na, title='Signal Line Background')
bgcolor(sigRisingAvgRising ? color.new(#445b84, 50) : sigRisingAvgFalling ? color.new(#844444, 100) : na, title='Signal Line Background | Signal Line Rising')
This way you are much more flexible combining your conditions.
Eg.
secondOrForthtrue = baseLineSigRising or baseLineFallingSigRising or sigRisingAvgRising or sigRisingAvgFalling // I assume they are true if they have a coloring at all
bgcolor(baseLineRising and not secondOrForthtrue ? color.new(#445b84, 50) : baseLineFalling and not secondOrForthtrue ? color.new(#844444, 100) : na, title='Baseline Background')
I finally figured out what I needed to do. For me, being a non-coder and not in the tech profession and only having some experience coding in pinescript (the only language I can code in) this took a significant amount of my time, but I'm happy to have figured it out (I can be quite dogged at times).
Essentially instead of trying to declare everything using ternary operators in bgcolor and barcolor (because it won't work), I created some if-else-if conditions that I hoped would allow me to negate a condition that would be true all the time even if a certain other input variable was also true. Basically, if A and B are true, then C. But if input D is also true, then not C, but E. This actually is stated like if A and B and not D are true, then C, else if A, B and D are true then E. The 'not D' part is what I was struggling with using ternary operators (and maybe it's not possible in this way).
//SIGNAL LINE RISING/FALLING
signal_rising = signal_rise and signal_line >= signal_line[1]
signal_falling = signal_rise and signal_line < signal_line[1]
//BACKGROUND CONDITIONS AND COLORING
above_bline = bg_bline and avg_range > baseline
below_bline = bg_bline and avg_range < baseline
above_signal = bg_signal and avg_range > signal_line
below_signal = bg_signal and avg_range < signal_line
AboveBaselineSignalRising = if (signal_rising and above_bline)
color.new(#445b84, 50)
else if (signal_rising and below_bline or signal_falling and below_bline)
color.new(#844444, 100)
AboveBaseline = if (not signal_rise and above_bline)
color.new(#445b84, 50)
else if (not signal_rise and below_bline)
color.new(#844444, 100)
AboveSignalLineSignalRising = if (signal_rising and above_signal)
color.new(#445b84, 50)
else if (signal_rising and below_signal or signal_falling and below_signal)
color.new(#844444, 100)
AboveSignalLine = if (not signal_rise and above_signal)
color.new(#445b84, 50)
else if (not signal_rise and below_signal)
color.new(#844444, 100)
bgcolor(AboveBaselineSignalRising, title='Background | ACBR > Baseline & Signal Rising')
bgcolor(AboveBaseline, title='Background | ACBR > Baseline')
bgcolor(AboveSignalLineSignalRising, title='Background | ACBR > Signal Line & Signal Rising')
bgcolor(AboveSignalLine, title='Background | ACBR > Signal Line')
//BAR COLOR CONDITIONS AND COLORING (ACBR CROSSING ABOVE OR BELOW BASELINE/SIGNAL LINE)
barcolor_xover_bline = xover_bline and ta.crossover(avg_range, baseline)
barcolor_xunder_bline = xunder_bline and ta.crossunder(avg_range, baseline)
barcolor_xover_signal = xover_signal and ta.crossover(avg_range, signal_line)
barcolor_xunder_signal = xunder_signal and ta.crossunder(avg_range, signal_line)
BarColorBaselineCrossSignalRising = if (signal_rising and barcolor_xover_bline)
#848044
else if (barcolor_xunder_bline)
#5a4484
BarColorBaselineCross = if (not signal_rise and barcolor_xover_bline)
#848044
else if (not signal_rise and barcolor_xunder_bline)
#5a4484
BarColorSignalLineCrossSignalRising = if (signal_rising and barcolor_xover_signal)
#848044
else if (barcolor_xunder_signal)
#5a4484
BarColorSignalLineCross = if (not signal_rise and barcolor_xover_signal)
#848044
else if (not signal_rise and barcolor_xunder_signal)
#5a4484
barcolor(BarColorBaselineCrossSignalRising, title='Bar Color | ACBR Baseline Cross & Signal Rising')
barcolor(BarColorBaselineCross, title='Bar Color | ACBR Baseline Cross ')
barcolor(BarColorSignalLineCrossSignalRising, title='Bar Color | ACBR Signal Line Cross & Signal Rising')
barcolor(BarColorSignalLineCross, title='Bar Color | ACBR Signal Line Cross')
//BAR COLOR CONDITIONS AND COLORING (ACBR ABOVE OR BELOW BASELINE/SIGNAL LINE)
barcolor_above_bline = barcolor_bline and avg_range > baseline
barcolor_below_bline = barcolor_bline and avg_range < baseline
barcolor_above_signal = barcolor_signal and avg_range > signal_line
barcolor_below_signal = barcolor_signal and avg_range < signal_line
BarColorAboveBaselineSignalRising = if (signal_rising and barcolor_above_bline)
color.new(#445b84, 0)
else if (signal_rising and barcolor_below_bline or signal_falling and barcolor_above_bline or signal_falling and barcolor_below_bline)
color.new(#844444, 0)
BarColorAboveBaseline = if (not signal_rise and barcolor_above_bline)
color.new(#445b84, 0)
else if (not signal_rise and barcolor_below_bline)
color.new(#844444, 0)
BarColorAboveSignalLineSignalRising = if (signal_rising and barcolor_above_signal)
color.new(#445b84, 0)
else if (signal_rising and barcolor_below_signal or signal_falling and barcolor_above_signal or signal_falling and barcolor_below_signal)
color.new(#844444, 0)
BarColorAboveSignalLine = if (not signal_rise and barcolor_above_signal)
color.new(#445b84, 0)
else if (not signal_rise and barcolor_below_signal)
color.new(#844444, 0)
barcolor(BarColorAboveBaselineSignalRising, title='Bar Color | ACBR > Baseline & Signal Rising')
barcolor(BarColorAboveBaseline, title='Bar Color | ACBR > Baseline')
barcolor(BarColorAboveSignalLineSignalRising, title='Bar Color | ACBR > Signal Line & Signal Rising')
barcolor(BarColorAboveSignalLine, title='Bar Color | ACBR > Signal Line')

Nested if functions in arrayformula

I have this formula (1) in Google sheets:
=IF($A2="","",IF(AND(($G2 <= EOMONTH(TODAY(),-5)),($G2 <> ""),OR($H2 > EOMONTH(TODAY(),-5),$H2 = ""),OR($E2 > EOMONTH(TODAY(),-5),$E2 = "")),1,0))
which I want to convert to an arrayformula. I tried this formula (2) but I get a "#N/A no match" error:
=ARRAYFORMULA (
IFs (
ROW(A:A) = 1, "Contract Published, " & TEXT(EDATE(TODAY(),-5),"mmm-YY"),
IF(AND((G:G <= EOMONTH(TODAY(),-5)),(G:G <> ""),OR(H:H > EOMONTH(TODAY(),-5),H:H = ""),OR(E:E > EOMONTH(TODAY(),-5),E:E = "")),1,0),)
)
I also tried this formula (3), but get a "Formula parse error"
=ARRAYFORMULA (
IF(ROW(A:A) = 1, "Contract Published, " & TEXT(EDATE(TODAY(),-5),"mmm-YY")),
IF((G:G <= EOMONTH(TODAY(),-5),G:G <> ""),
IF((H:H > EOMONTH(TODAY(),-5),H:H = ""),
IF((E:E > EOMONTH(TODAY(),-5),E:E = "")),1,0)))
Does anyone have an idea what Im doing wrong, or how I can convert formula (1) into an Arrayformula?
try in row 2:
=ARRAYFORMULA(IF(A2:A="",,
IF(((G2:G <= EOMONTH(TODAY(), -5))*
(G2:G <> "")*
((H2:H > EOMONTH(TODAY(), -5)) + (H2:H = ""))*
((E2:E > EOMONTH(TODAY(), -5)) + (E2:E = ""))), 1, 0)))

Need some help writing a strategy with different positions depending on three 3 signal variables

Hi I'm brand new in coding, and I am getting stuck every new line of code I try to write but hey its a learning process.
I'm doing a strategy based on the MACD variables.
-MACD_Line is either positive or negative.
-Signal_Line is either positive or negative.
-Histogram is either positive or negative.
Based on the historical prices there are 6 possibilities of combined signals either: ---, -++, --+, +--, ++- or +++.
What I want to do is pre-set different position sizes depending on these 6 possible output signals.
So for example: if "---" then short 50% of equity,
if "+++" then long 100% of equity,
if "-++" then short 25% of equity.
Therefore the equity position would change after one of the initial 3 variables changes.
My attempt:
strategy("HIST", overlay= false, initial_capital = 1, default_qty_type= strategy.percent_of_equity, default_qty_value= 100 )
//time inputs
startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer, defval=2014, minval=1800, maxval=2100)
endDate = input(title="End Date", type=input.integer, defval=29, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer, defval=3, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer, defval=2021, minval=1800, maxval=2100)
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
//variable
ema26= ema(close,26)
ema12= ema(close,12 )
macdl= ema12-ema26
signal= ema(macdl, 9)
hist= macdl-signal
enterLong = crossover(macdl,0)
enterShort = crossunder(macdl,0)
s000 = if (hist <= 0 and macdl <= 0 and signal <=0)
s001 = if (hist > 0 and macdl <= 0 and signal <= 0)
s011 = if (hist > 0 and macdl > 0 and signal <= 0)
s111 = if (hist > 0 and macdl > 0 and signal > 0)
s011 = if (hist <= 0 and macdl > 0 signal > 0)
s001 = if (hist <= 0 and macdl <= 0 signal > 0)
if (inDateRange and s111)
strategy.entry(id="+", long=true)
if (inDateRange and s000)
strategy.entry(id="-", long=false)
if (not inDateRange)
strategy.close_all()
This should get you started in the right direction. You'll need to finish coding all the conditions yourself. See comments in code:
//#version=4
strategy("HIST", overlay= false, initial_capital = 1, default_qty_type= strategy.percent_of_equity, default_qty_value= 100 )
//time inputs
startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer, defval=2014, minval=1800, maxval=2100)
endDate = input(title="End Date", type=input.integer, defval=29, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer, defval=3, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer, defval=2021, minval=1800, maxval=2100)
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
//variable
ema26= ema(close,26)
ema12= ema(close,12 )
macdl= ema12-ema26
signal= ema(macdl, 9)
hist= macdl-signal
enterLong = crossover(macdl,0)
enterShort = crossunder(macdl,0)
// Two last var names clashed with others, so used "X" in them.
s000 = hist <= 0 and macdl <= 0 and signal <= 0
s001 = hist > 0 and macdl <= 0 and signal <= 0
s011 = hist > 0 and macdl > 0 and signal <= 0
s111 = hist > 0 and macdl > 0 and signal > 0
s01X = hist <= 0 and macdl > 0 and signal > 0
s00X = hist <= 0 and macdl <= 0 and signal > 0
// Detect changes in conditions.
f_changeIn(_cond) => _cond and not _cond[1]
c000 = f_changeIn(s000)
c001 = f_changeIn(s001)
c011 = f_changeIn(s011)
c111 = f_changeIn(s111)
c01X = f_changeIn(s01X)
c00X = f_changeIn(s00X)
// Functions calculates position size from a % (0 - 1.0).
f_positionSize(_percentEquity) => strategy.equity * _percentEquity / close
// Generate orders on trasitions into conditions.
float positionSize = na
if inDateRange
if c000
positionSize := f_positionSize(0.5)
strategy.entry(id="+", long=false, qty = positionSize)
else if c011
positionSize := f_positionSize(1.0)
strategy.entry(id="+", long=false, qty = positionSize)
else if c111
positionSize := f_positionSize(1.0)
strategy.entry(id="+", long=true, qty = positionSize)
else
strategy.close_all()
// For debugging.
plot(positionSize, "Position size", color.orange, 2, plot.style_circles)

Nested if statement in pine script

I'm trying to build a ema script in trading view but struggling with how to finish up the code. I'm essentially trying to code this, but not sure how to nest this in an if statement:
(tl <= em1 and tc > ema2) and ((tc<ema3) or (tc<em4) or (tc<em5))
How can I put a nested if statement for this? Goal is to use the if statement to tie in the rest of the code
// EMA trap
m1=8
m2=3.1
m3=3.2
m4=3.4
tl=low
tc=close
em1 = ema(tl,m1)
em2 = ema(tc,m1)
em3 = ema(tc,m2)
em4 = ema(tc,m3)
em5 = ema(tc,m4)```
You can't use float periods for ema(), so replaced them with integers.
This plots an arrow on the chart when your condition is true:
//#version=4
study("", "", true)
// EMA trap
m1=8
m2=3
m3=4
m4=5
tl=low
tc=close
em1 = ema(tl,m1)
em2 = ema(tc,m1)
em3 = ema(tc,m2)
em4 = ema(tc,m3)
em5 = ema(tc,m4)
cond = tl <= em1 and tc > em2 and (tc < em3 or tc < em4 or tc < em5)
plotchar(cond, "cond", "▼", location.top)

SQL 2005 IF not working fine

I've created an if statement to control if a customer discount is right. I take the sales volume of its previous year, control if it is in the exact range, then if it is not I need to write the right discount to apply. My problem is that this suggested discount is not the right one. I'll show you the code.
Before I give a sample customer data.
Discount Applied is 60 %
Sales Volume 2016--->€ 13.895.90
Sales Volume 2015 ---> € 25.686.92
This is my query:
DECLARE all variables that i need......
SET #Anno1 = YEAR(GETDATE());
SET #Anno2 = YEAR(DATEADD(year,-1,GETDATE()));
SET #Anno3 = YEAR(DATEADD(year,-2,GETDATE()));
SET #datada = DATEADD(DAY, -15, GETDATE());
SET #dataa = GETDATE();
----- set discount sales volume ---
SET #40 = '€ '+ REPLACE(CONVERT(varchar, CAST('1500.0000' AS money), 105),',','.');
SET #50 = '€ '+ REPLACE(CONVERT(varchar, CAST('15000.0000' AS money), 105),',','.');
SET #60 = '€ '+ REPLACE(CONVERT(varchar, CAST('150000.0000' AS money), 105),',','.');
SET #70 = '€ '+ REPLACE(CONVERT(varchar, CAST('200000.0000' AS money), 105),',','.');
SET #80 = '€ '+ REPLACE(CONVERT(varchar, CAST('500000.0000' AS money), 105),',','.');
---create cursor---
DECLARE c CURSOR FOR
SELECT DISTINCT
CODCONTO,
DSCCONTO1
FROM .dbo.TESTEDOCUMENTI
WHERE D (.dbo.TESTEDOCUMENTI.TIPODOC = 'PCL' OR .dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' ) AND .dbo.TESTEDOCUMENTI.DATADOC BETWEEN #datada AND #dataa
----take each customer----
OPEN c
FETCH NEXT FROM c INTO #CodiceCliente,#Cliente
--IF #CodiceCliente IS NULL goto finescript;
WHILE ##FETCH_STATUS = 0
BEGIN
-------------------------------------------------------------------
----------------------set sales volumes to variables---
-------------------------------Current year -----
SET #FattAnnoCorrente =
(SELECT '€ '+ REPLACE(CONVERT(varchar, CAST(SUM(TOTIMPONIBILE) AS money), 105),',','.') FROM .dbo.TESTEDOCUMENTI
WHERE CODCLIFOR = #CodiceCliente ANDAND .dbo.TESTEDOCUMENTI.TIPODOC = 'FVC' AND .dbo.TESTEDOCUMENTI.ESERCIZIO = YEAR(GETDATE()));
-------------------------------Previous Year -----
SET #FattAnnoPrecedente =
(SELECT '€ '+ REPLACE(CONVERT(varchar, CAST(SUM(TOTIMPONIBILE) AS money), 105),',','.') FROM .dbo.TESTEDOCUMENTI
WHERE CODCLIFOR = #CodiceCliente AND .dbo.TESTEDOCUMENTI.TIPODOC = 'FVC' AND .dbo.TESTEDOCUMENTI.ESERCIZIO = YEAR(DATEADD(year,-1,GETDATE())));
------------------------------2 Previous years -----
SET #Fatt2AnniPrecedenti =
(SELECT '€ '+ REPLACE(CONVERT(varchar, CAST(SUM(TOTIMPONIBILE) AS money), 105),',','.') FROM .dbo.TESTEDOCUMENTI
WHERE CODCLIFOR = #CodiceCliente AND .dbo.TESTEDOCUMENTI.TIPODOC = 'FVC' AND .dbo.TESTEDOCUMENTI.ESERCIZIO = YEAR(DATEADD(year,-2,GETDATE())));
----------- Take the last document discount and set to variable -----
SET #Sconto =
(SELECT DISTINCT MAX(SCONTORIGA)
FROM .dbo.TESTEDOCUMENTI
WHERE SCONTORIGA IS NOT NULL AND CODCLIFOR = #CodiceCliente AND (.dbo.TESTEDOCUMENTI.TIPODOC = 'PCL' OR .dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' ) AND .dbo.TESTEDOCUMENTI.DATADOC BETWEEN #datada AND #dataa);
--------------------------verify condition---THERE IS THE TRUOBLES----
---------------------------PREVIOUS YEAR SALES VOLUME----
IF #FattAnnoCorrente IS NULL SET #FattAnnoCorrente = '0'
IF #FattAnnoPrecedente IS NULL SET #FattAnnoPrecedente = '0'
IF #Fatt2AnniPrecedenti IS NULL SET #Fatt2AnniPrecedenti = '0'
IF #FattAnnoPrecedente = '0' goto fatturatocorrente;
IF (#FattAnnoPrecedente > '0' and #FattAnnoPrecedente < #40) and #Sconto < '40' goto finescript;
IF (#FattAnnoPrecedente > #40 and #FattAnnoPrecedente < #50 ) and (#Sconto > '40' and #Sconto < '50') goto finescript;
IF (#FattAnnoPrecedente > #50 and #FattAnnoPrecedente < #60 ) and (#Sconto > '50' and #Sconto < '60') goto finescript;
IF (#FattAnnoPrecedente > #60 and #FattAnnoPrecedente < #70 ) and (#Sconto > '60' and #Sconto < '70') goto finescript;
IF (#FattAnnoPrecedente > #70 and #FattAnnoPrecedente < #80 ) and (#Sconto > '70' and #Sconto < '80') goto finescript;
IF (#FattAnnoPrecedente > #80 and #FattAnnoPrecedente < '999999999999999999' ) and #Sconto > '80' goto finescript;
------------------------------------FIND THE SUGESTED DISCOUNT ------ THIS IS WRONG
IF ((#FattAnnoPrecedente > '0' and #FattAnnoPrecedente < #40 ))
SET #ScontoPrevisto = 'inferiore al 40%';
IF ((#FattAnnoPrecedente > #40 and #FattAnnoPrecedente < #50 ) )
SET #ScontoPrevisto = 'compreso tra 40% e 50%';
IF ((#FattAnnoPrecedente > #50 and #FattAnnoPrecedente < #60 ) )
SET #ScontoPrevisto = 'compreso tra 50% e 60%';
IF ((#FattAnnoPrecedente > #60 and #FattAnnoPrecedente < #70 ) )
SET #ScontoPrevisto = 'compreso tra 60% e 70%';
IF ((#FattAnnoPrecedente > #70 and #FattAnnoPrecedente < #80 ) )
SET #ScontoPrevisto = 'compreso tra 70% e 80%';
IF ((#FattAnnoPrecedente > #80 and #FattAnnoPrecedente < '999999999999999999' ) )
SET #ScontoPrevisto = 'superiore all"80%';
SET #AnnoConsiderato = 'ANNO PRECEDENTE';
fatturatocorrente:
------------USE CURRENT YEAR IF PREVIOUS SALES VOLUME IS 0---------
IF #FattAnnoPrecedente NOT LIKE '0' goto fatturatoesistente;
IF (#FattAnnoCorrente > '0' and #FattAnnoCorrente < #40 ) and #Sconto < '40' goto finescript;
IF (#FattAnnoCorrente > #40 and #FattAnnoCorrente < #50 ) and (#Sconto > '40' and #Sconto < '50') goto finescript;
IF (#FattAnnoCorrente > #50 and #FattAnnoCorrente < #60 ) and (#Sconto > '50' and #Sconto < '60') goto finescript;
IF (#FattAnnoCorrente > #60 and #FattAnnoCorrente < #70 ) and (#Sconto > '60' and #Sconto < '70') goto finescript;
IF (#FattAnnoCorrente > #70 and #FattAnnoCorrente < #80 ) and (#Sconto > '70' and #Sconto < '80') goto finescript;
IF (#FattAnnoCorrente > #80 and #FattAnnoCorrente < '999999999999999999' ) and #Sconto > '80' goto finescript;
------------------------------------FIND SUGGESTED DISCOUNT ------
--SET #FattAnnoCorrente = '1';
IF ((#FattAnnoCorrente > '0' and #FattAnnoCorrente < #40 ))
SET #ScontoPrevisto = 'inferiore al 40%';
IF ((#FattAnnoCorrente > #40 and #FattAnnoCorrente < #50 ))
SET #ScontoPrevisto = 'compreso tra 40% e 50%';
IF ((#FattAnnoCorrente > #50 and #FattAnnoCorrente < #60 ))
SET #ScontoPrevisto = 'compreso tra 50% e 60%';
IF ((#FattAnnoCorrente > #60 and #FattAnnoCorrente < #70 ))
SET #ScontoPrevisto = 'compreso tra 60% e 70%';
IF ((#FattAnnoCorrente > #70 and #FattAnnoCorrente < #80 ))
SET #ScontoPrevisto = 'compreso tra 70% e 80%';
IF ((#FattAnnoCorrente > #80 and #FattAnnoCorrente < '999999999999999999'))
SET #ScontoPrevisto = 'superiore all"80%';
SET #AnnoConsiderato = 'ANNO CORRRENTE';
IF #Sconto LIKE '0.0%' SET #ScontoPrevisto = 'da stabilire in base alla merce ordinata'
fatturatoesistente:
-----------
--- HERE THERE WAS SOME TABLES CALLED BELOW BUT THEY WORK FINE, SO I REMOVED THEM ---
---------------------------------
---HTML EMAIL BODY SET WITH ALL VARIABLES, ALL WORKING FINE BUT THE #SCONTOPREVISTO is the wrong one----
SET #Email =
N'......HTML CODE....' + #ScontoPrevisto + '..HTML CODE...';
SET #oggettomail = 'ERRATA SCONTISTICA PER ' + #Cliente;
IF #Emailis null goto finescript;
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'email#gmail.com',
#subject = #oggettomail,
#body = #Email,
#body_format = 'HTML' ;
finescript:
--take the next customerE---
FETCH NEXT FROM c INTO #CodiceCliente,#Cliente
END
--clean---
CLOSE c
DEALLOCATE c
The result of this query for #ScontoPrevisto, suggested discount is wrong, it is between 70% and 80 % but as you see the previous year sales volume is about 25000 so the right discount must be 50-60%.
I dont' understand why. Instead for some customer, reslt is good.
Another customer has
Sales Volume 2016--->0
Sales Volume 2015 ---> 0
Discount 60%
Result is greater then 80 % instead to be smaller than 40 %.
I wait for your answer. Thank you guys!