I am having study error in trading view pine script - pine-script-v5

I am trying to create a PineScript indicator that plots a horizontal line on the chart at the 9:42 AM price of the asset being charted, during the New York trading session. It does this by first defining the 9:42 AM New York time as a series of integers using the time() function. It then creates a series of true and false values, called period, representing the time period from 9:42 AM to 9:43 AM.
Next, the code uses the ta.valuewhen() function to retrieve the 9:42 AM price. It then uses the line.new() function to draw a line at the 9:42 AM price on the chart, and the label.new() function to create a label with the 9:42 AM price at the end of the line. The appearance and style of the line and label can be customized using the input options i9Style, i9Color, and i9Label. The input option i9History determines whether the line and label will persist on the chart after the current bar (true) or be removed (false).
the issue - everything is working fine there are no error runs perfectly fine but when I add this indicator on chart it showes nothing and says : study error - can not parse resolution '09
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bee_Zee
//#version=5
indicator("ICT NEW YORK 9:42 AM OPEN", "ICT SAUCE 9:42 AM OPEN", true, max_lines_count=500)
i9Display = input.bool (true, "Display", group="New York 9:42 Open")
i9Time = input.session ('0942-0943:1234567', "Session", group="New York 9:42 Open")
i9Style = input.string ("Solid", "Line Style", options=["Solid", "Dotted", "Dashed"], group="New York 9:42 Open")
i9Color = input.color (#e43030, "Color", group="New York 9:42 Open")
i9History = input.bool (true, "History", group="New York 9:42 Open")
i9Label = input.bool (true, "Show Label", group="New York 9:42 Open")
// Define the 9:42 AM New York time as a series of integers
t942 = time("09:42:00", "New York")
_9Style = i9Style == "Solid" ? line.style_solid : i9Style == "Dotted" ? line.style_dotted : line.style_dashed
//==== Sauce 9:42 Open ====
if i9Display
// Create a series of true and false values representing the time period from 9:42 AM to 9:43 AM
period = time >= t942 and time < t942 + 60
// Retrieve the 9:42 AM price using ta.valuewhen
price942 = ta.valuewhen(period, close, 0)
var label lb3 = na
var line lne3 = na
if price942 != price942[1]
if barstate.isconfirmed
line.set_x2(lne3, t942 - 30600000)
// Draw a line at the 9:42 AM price
lne3 := line.new(t942, price942, last_bar_time + 14400000/2, price942, xloc.bar_time, extend.none, i9Color, _9Style, 1)
if i9Label
// Update the label at the end of the line with the 9:42 AM price
lb3 := label.new(last_bar_time + 14400000/2, price942, "9:42", xloc.bar_time, yloc.price, na, label.style_none, i9Color, size.normal, text.align_right)
label.delete(lb3[1])
if not i9History
line.delete(lne3[1])

Related

How can I enter and exit a trade at a given time?

I am trying to backtest a strategy in Tradingview on an hourly chart that goes short AUDJPY at 5am Japan time and exits with a market order at 7am on the same day. I am using the hour(time) function and the IANA timezone 'Asia/Tokyo'.
Below is the code. I verified that the variable hr picks up the right hour by plotting it in the chart. But when I run the Strategy Tester the result is "No Data" and no trades appear on the screen after I apply "Add to chart" to the script.
strategy("Foreign JPY", overlay=true, currency = currency.USD)
hr = hour(time, "Asia/Tokyo")
shortCondition = hr == 5
if (shortCondition)
strategy.entry("short", strategy.short, 100000)
exitCondition = hr == 7 and strategy.position_size < 0
if (exitCondition)
strategy.close("exit", 100000)
The exit condition in your example is executed only for entries with an "exit" id=. If you want to point to the existing short order, use its id= in the strategy.close() parameter:
if (exitCondition)
strategy.close("short", 100000)

i am trying to get a bokeh server to run, but when i type in the command in my terminal i get an error message

I am trying to run the code below in a bokeh server to visualize the plots. the final_imdb_dataframe is in the same directory as the python code. these are the steps i take to get the server to run:
open my terminal
type in "cd" then a space and then my directory in for the map containing my python script and the final_imdb_dataframe
press enter
type: bokeh serve --show "filename.py"
press enter
in my terminal i am getting this error message however:
bokeh : The term 'bokeh' is not recognized as the name of a cmdlet, function, script file, or operable program. (the complete error message is attached as a picture)
when i type in "pip show bokeh" in the command promt in python it gives me this:
pip show bokeh
Name: bokeh
Version: 2.4.3
Summary: Interactive plots and applications in the browser from Python
Home-page: https://github.com/bokeh/bokeh
Author: Bokeh Team
Author-email: info#bokeh.org
License: BSD-3-Clause
Location: c:\users\fazan\anaconda\lib\site-packages
Requires: Jinja2, numpy, packaging, pillow, PyYAML, tornado, typing-extensions
Required-by: hvplot, panel
Note: you may need to restart the kernel to use updated packages.
so it should work right?
i don't know what to do anymore...
code:
import pandas as pd
from bokeh.plotting import figure, show
import numpy as np
from bokeh.models import ColumnDataSource, HoverTool, Slider, RangeSlider, Div, Select
from bokeh.io import output_file, curdoc
from bokeh.layouts import column, row, layout
#EERSTE PLOT:
#line diagram of amount of movies released each year en avg rating displayed over the years
df = pd.read_csv("final_imdb_dataframe")
#"unnamed column weghalen
df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)
#creating plot 2
plot2 = figure(plot_width = 1000,
plot_height = 400,
x_axis_label= "year",
title = "watchtime and movie rating over the years")
#creating a dropdown menu
source2 = ColumnDataSource(data={'x': df["release_date"], 'y': df["watchtime"]})
plot2.circle(x="x", y="y", size = 3, source = source2, alpha = 0.2)
def update_plot(attr, old, new):
if new == 'watchtime':
source2.data = {'x' : df["release_date"], 'y' : df["watchtime"]}
else:
source2.data = {'x' : df["release_date"], 'y' : df["movie_rating"]}
select = Select(title = "keuze menu", options=["watchtime", "movie_rating"], value = 'watchtime')
#code for updating the plot when the value is changed
select.on_change('value', update_plot)
#TWEEDE PLOT:
#creating a list of all the years a movie came out
dfrelease = df.release_date.drop_duplicates().tolist()
#sorting the list with release dates to get them in chronological order
dfrelease1 = sorted(dfrelease)
#creating an empty list
total_releases_per_year = []
#adding the amount of movies that came out every year to the list
for i in range(len(dfrelease1)):
total_releases_per_year.append(len(df[df["release_date"] == dfrelease1[i]]))
#creating a columndatasource of the two lists created above to make it possible for the hovertool to be used
source1 = ColumnDataSource(data=dict(year = dfrelease1, amount_of_movies_made = total_releases_per_year))
#making a hovertool
hover2 = HoverTool(tooltips=[("year", "#year"), ("amount of movies made", "#amount_of_movies_made")])
#creating plot 3
plot3 = figure(plot_width = 1000,
plot_height = 400,
x_axis_label= "year",
y_axis_label = "amount of movies",
title = "amount of movies per year")
plot3.line("year", "amount_of_movies_made", source = source1)
plot3.add_tools(hover2)
#DERDE PLOT:
#creating the ColumnDataSource
df_sel = df[df["release_date"] == 2020]
source1 = ColumnDataSource(df_sel)
#scatter plot
p1 = figure(title = "relation 'watchtime' and 'movie rating' over the years",
x_axis_label= "watchtime",
y_axis_label= "rating (0-10)",
plot_width = 1000,
plot_height = 400)
p1.circle(x="watchtime", y="movie_rating", alpha = 0.2, source=source1)
#making the rangeslider
slider = RangeSlider(title="release date", value= (1919, 2021), start=1919, end=2020, step=1)
#making the hover tool
hover1 = HoverTool(tooltips=[("title", "#movie_name"),("gross", "#gross_collection"),("votes", "#votes"),("genre", "#genre"), ("watchtime", "#watchtime"),("rating", "#movie_rating"),("release date", "#release_date")])
#making a def callback for the rangeslider to work when moved
def callback(attr, old, new):
year = slider.value
source1.data = df[(df["release_date"] >= year[0]) & (df["release_date"] <= year[1])]
slider.on_change("value", callback)
layout = column(slider, p1) #create a layout with slider on top of plot
p1.add_tools(hover1) #adding hover tool
layout3 = column(select, plot2, plot3, slider, p1) #making the layout for the dashboard
curdoc().add_root(layout3)*
i tried what i wrote above and expected acces to the bokeh server that would show me my plots. i have done this before on my previous computer (mac) and it worked then. now on my lenovo it is not working.`

How to extend a Indicator COT Data Line

Unfortunately, the commodity trade market is closed at the weekend. The new COT data will come on Saturday. The script therefore only shows the old data until Monday when the markets open again. But I would like to analyze the markets at the weekend. So how can I see the COT data in the indicator already at the weekend? I thought that it would be possible if we extend the indicator line by one point as an extension or as a forecast which are downloading the new data into the future without priceaction.
'qticker = syminfo.root == 'GE'
comm_lg = request.security(legacy_cot + '4', 'W', close)
comm_sh = request.security(legacy_cot + '5', 'W', close)
comm_net = comm_lg - comm_sh
plot(comm_net, color=color.new(color.red, 0), title='Commercials Net', style=plot.style_line, linewidth=2)`

Saving synchronised 7T fMRI Triggers received via USB connected NNL SyncBox, on every TR and Task Response Keypress (PsychoPy)

I would like to get synchronised timings and number of triggers for each single pulse sent by the 7T MRI scanner together with each single SPACEBAR keypress as a participant’s response when particular letters (A, B, C, X, Y) are presented on the screen, also the stimulus start time with each corresponding trigger.
So far I have added a “Waiting for scanner” routine where I get the first pulse via USB connected NNL Synbox saved in the .csv data file but I want to save each single pulse (TR) and timings. Triggers are automatically emulated as letter ‘s’ sent by the NNL Synbox.
# Code component: Creat routine "Wait for Scanner"
text_wait = visual.TextStim(win=win, name='text_wait',
text='Waiting for scanner...',
font='Arial',
pos=(0, 0), height=0.8, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
#Set first MR Trigger
mr_trigger_number = [] # list for triggers
mr_trigger_time = [] # list for time of each trigger
ScannerKeyboard = keyboard.Keyboard() # set keyboard
count_mr_trigger = 0 # counts amount of MR scanner trigger, starts with zero
start_trigger = ScannerKeyboard.getKeys(keyList=['s'], waitRelease = False) # experiment starts with MR Scanner "s"
# Draw waiting Screen until "s" is sent from NNL Syncbox
while len(start_trigger) == 0: # if no trigger was sent show:
text_wait.draw() # Text "Waiting for scanner"
win.flip()
start_trigger = ScannerKeyboard.getKeys(keyList=['s'], waitRelease = False) # show text_wait until one "s" was received
# Get timing information and store trigger number
onset = core.getTime() # get Onset time of trigger
count_mr_trigger = count_mr_trigger + 1 # count MR Scanner trigger, add "1!
# Save time and number of MR Trigger
thisExp.addData('MR_trigger_time',onset) # save trigger time of onset
thisExp.addData('MR_trigger_number',count_mr_trigger)
And also I used the following code component in > Each Frame tab of 2 trials conditions to save the stimuli onset timings when a pulse 's' is received. This works fine but stimulus start time > stimulus_start_time = globalClock.getTime() - mr_trigger_time is saved based on first pulse only as I am unable to save each pulse timings.
#save stimulus onset time for two types of trial conditions
if trials.thisN == 0 and frameN == 0:
loop_start_time = globalClock.getTime() - mr_trigger_time
elif frameN == 1:
stimulus_start_time = globalClock.getTime() - mr_trigger_time
# store the data:
thisExp.addData('stimulus_start_time', stimulus_start_time)
if trials_2.thisN == 0 and frameN == 0:
loop_start_time = globalClock.getTime() - mr_trigger_time
elif frameN == 1:
stimulus_start_time = globalClock.getTime() - mr_trigger_time
# store the data:
thisExp.addData('stimulus_start_time', stimulus_start_time)
However, I want to record and save timings of each trigger pulse when a SPACEBAR response is pressed on a target letter (stimulus) by a participant, to compare the timings with accuracy and reaction times of the task with each corresponding trigger timings.
I would really appreciate your valuable suggestions on how to work around this, as I am quite new to the PsychoPy. I also posted to the PsychoPy forum but haven't got any update so far.
Thanks in advance!

Save and use eigenvectors from PCA

I performed a Principal Component Analysis (PCA) in Stata.
My dataset includes eight financial indicators that vary across 9 countries.
For example:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str7 Country double(Investment Profit Income Tax Repayment Leverage Interest Liquidity) int Year
"France" -.1916055239385184 .046331346724579184 .16438012750896466 .073106839282063 30.373216652548326 4.116650784492168 3.222219873614461 .01453109309122077 2010
"UK" -.09287803170279468 .10772082765154019 .19475363707485557 .05803923583546618 31.746409646181174 9.669982727208433 1.2958094802269167 .014273374324088752 2010
"US" -.06262935107629553 .08674901201182428 .1241593221865416 .13387194413811226 25.336612638526013 11.14330064161111 1.954785887176916 .008355601163285917 2010
"Italy" -.038025847122363045 .1523162032749684 .23885658237030563 .2057478638900476 31.02007902336988 2.9660938817562292 6.12544787693943 .011694993164234125 2010
"Germany" -.05454795914578491 .06287079763890834 .09347194572148769 .08730237262847926 35.614342337621174 12.03770488195981 1.1958205191308358 .012467084153714813 2010
"Spain " -.09133982259799572 .1520056836126315 .20905656056324853 .21054797530580743 30.133833346916546 2.0623245902645073 5.122615899157435 .013545432336873187 2010
"Sweden" -.05403262462960799 .20463787181576967 .22924827352771968 .05655833155565016 20.30540887860061 10.392313613725324 .8634381995636089 .008030624504967313 2010
"Norway " -.07560184571862992 .08383822093909514 .15469418498932822 .06569716455818478 29.568228705840234 14.383460621594622 1.5561013535825234 .012843159364225464 2010
"Algeria" -.0494187835163535 .056252436429004446 .09174672864585759 .08143181185307143 34.74103858167055 15.045254276254616 1.2074942921860699 .011578038401820303 2010
"France" -.03831442432584342 .14722819896988698 .22035417794604084 .12183886462162773 28.44763045286005 12.727100288710087 1.405629911115614 .011186908059399987 2011
"UK" -.05002189329928202 .16833493262244398 .2288402623558823 .04977050186975224 27.640103129372747 11.17376089844228 1.1764542835994092 .008386726178729322 2011
"US" -.0871005985124144 .10270482619857023 .1523559355903486 .06775742210623094 26.840586700880362 10.783899184031576 1.454011947763254 .013501919089967212 2011
"Italy" -.1069324103590126 -.5877872620957578 -.47469302172710803 .2004436360021364 23.133243742952658 5.3936761686065875 4.532771849692548 .012586313916956204 2011
"Germany" -.05851794344524515 .09960345907923154 .136805115392161 .1373407846168154 32.6182637042919 14.109738344526052 1.5077699357228835 .013200993625042274 2011
"Spain " -.10650743527105216 -.015785638597076792 .1808727613216441 .05038848927405154 28.22206251292902 10.839614113486853 1.5021425852392374 .012076771099482617 2011
"Sweden" -.09678946710644694 .11801761803893955 .18569993056826523 .1481844716617448 27.439283362903794 5.771154420635893 5.493437819181101 .013820243145673811 2011
"Norway " -.04263379351591438 .09931719473864983 .14469611775596314 .0796835513869996 26.68561168581991 14.06385602832082 1.5200488174887825 .01029136242440406 2011
"Algeria" -.04871983526465598 .2139061303228528 .2728647845448156 .056537570099712456 22.50263575072073 16.919641035094685 .7539881754626142 .009734650338902404 2011
end
I called my first component "indebtedness" and my second one "profitability", after rotation.
I have the same data for 2011, 2012, 2013, 2014 and so on. I want to use the matrix of weights Stata computed for 2010 and apply it to 2011, 2012, 2013 separately. My goal is to compare the indebtedness and the profitability between countries over time.
To do this, I use the estimate save and estimates use commands (Chapter 20 of Stata manual on estimates and the post-estimation PCA command help).
However, I can't understand what Stata is saving. Is it saving the scores computed for 2010 or the eigenvalues and eigenvectors?
This is the code I use:
tempfile pca
save `pca'
use `pca' if Year==2010
global xlist Investment Profit Income Tax Repayment Leverage Interest Liquidity
pca $xlist, components(2)
estimates save pcaest, replace
predict score
summarize score
use `pca' if Year==2011, clear
estimates use pcaest
predict score
summarize score
Does this method and code seem correct to you?
I'd also like to save the matrix of weights and create a new vector Z=b|1,1]*investment+....
Using your toy example for year 2010:
clear
input str7 Country double(Investment Profit Income Tax Repayment Leverage Interest Liquidity) int Year
"France" -.1916055239385184 .046331346724579184 .16438012750896466 .073106839282063 30.373216652548326 4.116650784492168 3.222219873614461 .01453109309122077 2010
"UK" -.09287803170279468 .10772082765154019 .19475363707485557 .05803923583546618 31.746409646181174 9.669982727208433 1.2958094802269167 .014273374324088752 2010
"US" -.06262935107629553 .08674901201182428 .1241593221865416 .13387194413811226 25.336612638526013 11.14330064161111 1.954785887176916 .008355601163285917 2010
"Italy" -.038025847122363045 .1523162032749684 .23885658237030563 .2057478638900476 31.02007902336988 2.9660938817562292 6.12544787693943 .011694993164234125 2010
"Germany" -.05454795914578491 .06287079763890834 .09347194572148769 .08730237262847926 35.614342337621174 12.03770488195981 1.1958205191308358 .012467084153714813 2010
"Spain " -.09133982259799572 .1520056836126315 .20905656056324853 .21054797530580743 30.133833346916546 2.0623245902645073 5.122615899157435 .013545432336873187 2010
"Sweden" -.05403262462960799 .20463787181576967 .22924827352771968 .05655833155565016 20.30540887860061 10.392313613725324 .8634381995636089 .008030624504967313 2010
"Norway " -.07560184571862992 .08383822093909514 .15469418498932822 .06569716455818478 29.568228705840234 14.383460621594622 1.5561013535825234 .012843159364225464 2010
"Algeria" -.0494187835163535 .056252436429004446 .09174672864585759 .08143181185307143 34.74103858167055 15.045254276254616 1.2074942921860699 .011578038401820303 2010
end
I get the following results:
local xlist Investment Profit Income Tax Repayment Leverage Interest Liquidity
pca `xlist', components(2)
Principal components/correlation Number of obs = 9
Number of comp. = 2
Trace = 8
Rotation: (unrotated = principal) Rho = 0.7468
--------------------------------------------------------------------------
Component | Eigenvalue Difference Proportion Cumulative
-------------+------------------------------------------------------------
Comp1 | 3.43566 .896796 0.4295 0.4295
Comp2 | 2.53887 1.23215 0.3174 0.7468
Comp3 | 1.30672 .750756 0.1633 0.9102
Comp4 | .555959 .472866 0.0695 0.9797
Comp5 | .0830926 .0181769 0.0104 0.9900
Comp6 | .0649157 .0526462 0.0081 0.9982
Comp7 | .0122695 .00975098 0.0015 0.9997
Comp8 | .00251849 . 0.0003 1.0000
--------------------------------------------------------------------------
Principal components (eigenvectors)
------------------------------------------------
Variable | Comp1 Comp2 | Unexplained
-------------+--------------------+-------------
Investment | 0.0004 -0.3837 | .6262
Profit | 0.3896 -0.3794 | .1131
Income | 0.4621 -0.1162 | .232
Tax | 0.4146 0.1236 | .3706
Repayment | -0.1829 0.4747 | .3131
Leverage | -0.4685 -0.2596 | .07464
Interest | 0.4580 0.2625 | .1045
Liquidity | -0.0082 0.5643 | .1913
------------------------------------------------
To see what items the pca command returns type:
ereturn list
scalars:
e(N) = 9
e(f) = 2
e(rho) = .7468162625387222
e(trace) = 8
e(lndet) = -13.76082122673546
e(cond) = 36.93476257313668
macros:
e(cmdline) : "pca Investment Profit Income Tax Repayment Leverage Interest Liquidity, components(2)"
e(cmd) : "pca"
e(title) : "Principal components"
e(marginsnotok) : "_ALL"
e(estat_cmd) : "pca_estat"
e(rotate_cmd) : "pca_rotate"
e(predict) : "pca_p"
e(Ctype) : "correlation"
e(properties) : "nob noV eigen"
matrices:
e(sds) : 1 x 8
e(means) : 1 x 8
e(C) : 8 x 8
e(Psi) : 1 x 8
e(Ev) : 1 x 8
e(L) : 8 x 2
functions:
e(sample)
One way to save the returned matrix containing the eigenvectors as variables for the next year is to create a copy of the matrix and load the 2011 data:
matrix A = e(L)
clear
input str7 Country double(Investment Profit Income Tax Repayment Leverage Interest Liquidity) int Year
"France" -.03831442432584342 .14722819896988698 .22035417794604084 .12183886462162773 28.44763045286005 12.727100288710087 1.405629911115614 .011186908059399987 2011
"UK" -.05002189329928202 .16833493262244398 .2288402623558823 .04977050186975224 27.640103129372747 11.17376089844228 1.1764542835994092 .008386726178729322 2011
"US" -.0871005985124144 .10270482619857023 .1523559355903486 .06775742210623094 26.840586700880362 10.783899184031576 1.454011947763254 .013501919089967212 2011
"Italy" -.1069324103590126 -.5877872620957578 -.47469302172710803 .2004436360021364 23.133243742952658 5.3936761686065875 4.532771849692548 .012586313916956204 2011
"Germany" -.05851794344524515 .09960345907923154 .136805115392161 .1373407846168154 32.6182637042919 14.109738344526052 1.5077699357228835 .013200993625042274 2011
"Spain " -.10650743527105216 -.015785638597076792 .1808727613216441 .05038848927405154 28.22206251292902 10.839614113486853 1.5021425852392374 .012076771099482617 2011
"Sweden" -.09678946710644694 .11801761803893955 .18569993056826523 .1481844716617448 27.439283362903794 5.771154420635893 5.493437819181101 .013820243145673811 2011
"Norway " -.04263379351591438 .09931719473864983 .14469611775596314 .0796835513869996 26.68561168581991 14.06385602832082 1.5200488174887825 .01029136242440406 2011
"Algeria" -.04871983526465598 .2139061303228528 .2728647845448156 .056537570099712456 22.50263575072073 16.919641035094685 .7539881754626142 .009734650338902404 2011
end
Then you can simply use the svmat command:
svmat A
list A* if _n < 9
+-----------------------+
| A1 A2 |
|-----------------------|
1. | .0003921 -.383703 |
2. | .3895898 -.3793983 |
3. | .4621098 -.1162487 |
4. | .4146066 .1235683 |
5. | -.1828703 .4746658 |
|-----------------------|
6. | -.4685374 -.2596268 |
7. | .457974 .2624738 |
8. | -.0081538 .5643047 |
+-----------------------+
EDIT:
Revised according to comments:
use X1, clear
local xlist Investment Profit Income Tax Repayment Leverage Interest Liquidity
forvalues i = 1 / 5 {
pca `xlist' if year == 201`i', components(2)
matrix A201`i' = e(L)
svmat A201`i'
generate B201`i'1 = (A201`i'1 * Investment) + (A201`i'1 * Profit) + ///
(A201`i'1 * Income) + (A201`i'1 * Tax) + ///
(A201`i'1 * Repayment) + (A201`i'1 * Leverage) + ///
(A201`i'1 * Interest) + (A201`i'1 * Liquidity)
generate B201`i'2 = (A201`i'2 * Investment) + (A201`i'2 * Profit) + ///
(A201`i'2 * Income) + (A201`i'2 * Tax) + ///
(A201`i'2 * Repayment) + (A201`i'2 * Leverage) + ///
(A201`i'2 * Interest) + (A201`i'2 * Liquidity)
}