Can't declare a global variable inside IF statement (Pine Script) - if-statement

I am new to Pine Script and have some problem declaring a variable inside an if and use it inside another if...
In the first if statement, I tried to get the "close price" of the long signal (LongPrice).
And in the second if, I tried to get the "close price" of the short signal (ShortPrice) and subtract it from "LongPrice".
But the value of "LongPrice" not changed outside its own if statement!
From what I understand this means that the variable is not valid outside of the if statement. Is there a way to change this?
LongPrice = 0
ShortPrice = 0
if mmeLong
LongPrice = close // Get the Long signal's close price
label.new(bar_index, na, tostring(LongPrice),
color=color.green,
textcolor=color.white,
style=label.style_labelup, yloc=yloc.belowbar)
if mmeShort
ShortPrice = close - LongPrice // Get the Short signal's close price and minus it with the last Long close price.
label.new(bar_index, na, tostring(ShortPrice),
color=color.red,
textcolor=color.white,
style=label.style_label_down, yloc=yloc.abovebar)
Thank you

Make it global with := when you what to declare it again.
var float LongPrice = na
var float ShortPrice = na
if mmeLong
LongPrice := close // Get the Long signal's close price
label.new(bar_index, na, tostring(LongPrice),
color=color.green,
textcolor=color.white,
style=label.style_labelup, yloc=yloc.belowbar)
if mmeShort
ShortPrice := close - LongPrice // Get the Short signal's close price and minus it with the last Long close price.
label.new(bar_index, na, tostring(ShortPrice),
color=color.red,
textcolor=color.white,
style=label.style_label_down, yloc=yloc.abovebar)

Related

Use rblpapi::getTicks() to obtain the Mid Price at a point in time

the question seems pretty easy, but I just did not find a solution yet.
I want to obtain mid prices for a certain timespan. Obviously I can calculate the mid price from bid and ask prices myself. But I wondered, whether it could be done via getTicks directly. I tried eventType = 'MID' and eventType = 'PX_MID', but both don't seem to be supported:
con <- Rblpapi::blpConnect()
Ticker <- 'AAPL US Equity'
Time <- as.POSIXct('2022-02-02 14:22:50 CET')
df <- Rblpapi::getTicks(security = Ticker,
eventType = 'MID',
startTime = Time - 5 * 60,
endTime = Time + 5 * 60)
Error in getTicks_Impl(con, security, eventType, startUTC, endUTC, setCondCodes = returnAs %in% :
Constant with value 'MID' does not exist.
The same code using eventType = 'BID' or eventType = 'ASK' or eventType = 'TRADE' works fine.
I was already looking for a list of all supported eventTypes, but I did not find anything in the documentation. Does such a list exist?
And is there a simple solution to this problem? Or is it possible, that Bloomberg does not support MID prices with Tick Data?
Thanks a lot!

Pinescript. Plotting conditional statement

If the variable barup is true, I want it to plot one series; if the variable bardown is true, I want it to plot another series value.
My current code yields the error: Cannot use "plot in local scope".
How do I change the following code to make the indicator show the number of days the lows have been above the 30 ema or below the 30 day ema based on the high or low of the current day.
Here is the code I have now:
indicator("LandryLight")
bardown = high < ta.ema(close,30)
barup = low > ta.ema(close,30)
if barup
plot(series=ta.barssince(barup)*-1, title="Consecutive Bars Down", color=color.red, style=plot.style_histogram, linewidth=2)
if bardown
plot(series=ta.barssince(bardown), title="Consecutive Bars Up", color=color.green, style=plot.style_histogram, linewidth=2)
hline(10,title="Threshold", color=color.white, linestyle=hline.style_dashed, linewidth=1)
First Use tag [pine-script]
Try going step by step, and then the plot
I would do it like this:
//#version=5
indicator("LandryLight")
bardown = high < ta.ema(close,30)
barup = low > ta.ema(close,30)
barupCont = ta.barssince(barup)*-1
bardownCont = ta.barssince(bardown)
barupOK = barup ? barupCont : na
bardownOK = bardown ? bardownCont : na
plot(series= barupOK, title="Consecutive Bars Down", color=color.red, style=plot.style_histogram, linewidth=2)
plot(series= bardownOK, title="Consecutive Bars Up", color=color.green, style=plot.style_histogram, linewidth=2)
hline(10,title="Threshold", color=color.white, linestyle=hline.style_dashed, linewidth=1)

Adding seconds to time variable

*data final;
set final;
duration = redate-ondate;
dudays = floor(duration/86400);
duhrs = floor((duration-(dudays*86400))/3600);
dumins = floor((duration-(dudays*86400+duhrs*3600))/60);
****************Set up new variable duration**************;
attrib dur length=$11.;
if ae_term ne 'None' and dudays ne . then
dur = left(put(dudays,z2.))||':'||left(put(duhrs,z2.))||':'||left(put(dumins,z2.));
else dur = '';
run;*
I have this code but need to calculate seconds and concatenate to dur as I have an adverse event that is less than a minute so won't display. What's the most efficient way to do this?
You can calculate the remaining seconds and then append to your time string like this:
dusec = duration-(dudays*86400+duhrs*3600+dumins*60);
if ae_term ne 'None' and dudays ne . then
dur = left(put(dudays,z2.))||':'||left(put(duhrs,z2.))||':'||left(put(dumins,z2.)||':'||left(put(dusec,z2.)));
One note - using put(dudays,z2.) assumes your duration is never more than 99 days.
Ok, this should simplify things somewhat:
dudays = FLOOR(duration/86400);
duhrs = FLOOR(MOD(duration,86400)/3600);
dumins = FLOOR(MOD(duration,3600)/60);
dusec = MOD(duration,60);
The difference between two datetime values is a number of seconds (so it is also a datetime value). You can use the DATEPART() and TIMEPART() function to divide into the number of days and seconds since midnight. The TOD11.2 format will display seconds in HH:MM:SS.mm style.
length dur $20;
if n(redate,ondate)=2 and ae_term not in (' ','None') then do;
duration = redate-ondate;
dur = catx(':',datepart(duration),put(timepart(duration),tod11.2));
end;

Pinescript - "Compare" Indicator with Percentage Change Function takes only last bar data

need help pls.
In Tradingview I use "Compare" to see the BTCUSDT vs. ETHUSDT on Binance and it's basically OK. But lines on the chart are too "up & down" and I want to see the SMA or EMA for those tickers.
I'm trying to do it step by step but I can't pass through the issue that my code takes only last calculated value in consideration and "percentage change line" starts from 0 with each new data. So it makes no sence. Meaning, my last data doesn't add upon prior value, but always starts from zero.
So, data (value) that comes out is good (same as when I put same tickers on Tradingview "Compare") but Tradingview "Compare" calculates / adds data on historical data, while my code starts from 0.
Here is the Pine script code:
//#version=4
study(title="Compare", shorttitle="Compare", overlay=false, max_bars_back=0)
perc_change = (((close[0] - open[0]) / open [0]) * 100)
sym1 = "BINANCE:BTCUSDT", res1 = "30", source1 = perc_change
plot(security(sym1, res1, source1), color=color.orange, linewidth=2)
sym2 = "BINANCE:ETHUSDT", res2 = "30", source2 = perc_change
plot(security(sym2, res2, source2), color=color.blue, linewidth=2)
Sounds like the delta between the two ROCs is what you are looking for. With this you can show only the 2 ROCs, but also columns representing the delta between the two. you can also change the ROC's period:
//#version=4
study(title="Compare", shorttitle="Compare")
rocPeriod = input(1, minval = 1)
showLines = input(true)
showDelta = input(true)
perc_change = roc(close, rocPeriod)
sym1 = "BINANCE:BTCUSDT"
sym2 = "BINANCE:ETHUSDT"
res = "30"
s1 = security(sym1, res, perc_change)
s2 = security(sym2, res, perc_change)
delta = s1 - s2
plot(showLines ? s1 : na, "s1", color.orange)
plot(showLines ? s2 : na, "s2", color.blue)
hline(0)
plot(showDelta ? delta : na, "delta", delta > 0 ? color.lime : color.red, 1, plot.style_columns)

Summarizing a variable in Stata and extracting standard deviation

I am trying to create a variable for each year in my data based on mathematical expressions of other variables (I have annual data and used "..." to avoid writing each year). I am using the summarize command in Stata to extract the standard deviation but Stata does not recognize the frac variable. I have tried to use egen but that results in an unknown function error. Using gen results in an already defined variable. I would appreciate anyone helping with the following code or pointing me to a link where this issue has been discussed.
foreach yr of numlist 1995...2012 {
local row = `yr' - 1994
local numerator = 100*(income - L1.income)
local denominator = ((abs(income) + abs(L1.income)) / 2)
local frac = (`numerator' / `denominator')
summarize frac
local sdfrac = r(sd)
matrix C[`row', 1] = `numerator'
matrix C[`row', 2] = `denominator'
matrix C[`row', 3] = `sdfrac'
}
If I am understanding your question right, maybe you don't need to use a loop until the end and then you can post the results to a postfile:
This is just a thought:
tempname memhold
tempfile filename
postfile `memhold' year sdfrac using `filename'
gen row=year-1994
gen numerator=100*(income-L1.income)
gen denominator=((abs(income)+abs(L1.income))/2)
gen frac=numerator/denominator
foreach yr of numlist 1995...2012 {
summarize frac if year=`yr'
local sdfrac=r(sd)
post `memhold' (year) (`sdfrac')
}
postclose `memhold'
clear all
use `filename'
*View Results
list
This code should get you a data set with the name of the year and the standard deviation of the frac variable as variables.
In a comment, OP added a question about code similar to this (but ignored the request to post it in a more civilised form). Note that backticks or left quotation marks in Stata clash with SO mark-up codes in comments. Presumably some
tempname memhold
definition preceded this.
postfile `memhold' year sdfrac sex race using myresults
levels of sex, local (s)
levelsof race, local (r)
foreach a of local s {
foreach b of local r {
forval yr = 1995/2012 {
summarize frac if year == `yr' & sex == `a' & race == `b'
post `memhold' (`yr') (`r(sd)') (`sex') (`race')
}
}
}
Let's focus on what the problem is. You want the standard deviations of frac for all combinations of sex, race and year in a separate file. That's one line
collapse (sd) frac, by(year sex race)
If you want to see a table alongside the data, consider
egen group = group(sex race year), label
and then
tab group, su(frac)
or
tabstat frac, by(group) stat(sd)
This code modifies that by #Pcarlitz, mostly by simplifying it. I can't check with your data, which I don't have.
It's too long to fit into a comment.
I would not use a temporary file as you want to save these results, it seems.
tempname memhold
postfile `memhold' year sdfrac using myresults
gen frac = (100*(income - L1.income))/((abs(income) + abs(L1.income))/2)
forval yr = 1995/2012 {
summarize frac if year==`yr'
post `memhold' (`yr') (`r(sd)')
}
postclose `memhold'
use myresults
list
UPDATE As in a later answer, consider collapse as a much simpler direct alternative here.