Compilation error in this code - Syntax error - syntax-error

Console messages :
Line 16: Syntax error at input ','
Line 25: Mismatched input 'isShort' expecting 'end of line without line continuation'
Code:
This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0SI J/
JimmyKartel
- //#version=5
study("RSI JimmyKartel")
Definition of RSI indicator parameters
length = input(14, minval=1)
overbought = input(30)
oversold = input(70)
Calculate the RSI indicator
rsi = rsi(close, length)
Calculate the MACD indicator
**macdLine, macdSignal, macdHistogram := macd(close, 12, 26, 9)**
Define variables to track trading state
isLong = false
isShort = false
Trading strategy:
If RSI is above overbought level, take a short position
If RSI is below oversold level, take a long position
**if rsi > overbought**
isShort := true
isLong := false
else if rsi < oversold
isShort := false
isLong := true
Display indicators on chart
rsiLine = line.new(rsi, title="RSI", color=color.orange, linewidth=2)
overboughtLine = line.new(overbought, title="Overbought", color=color.red, linewidth=1, style=plot.style_circles)
oversoldLine = line.new(oversold, title="Oversold", color=color.red, linewidth=1, style=plot.style_circles)
line.set_data(rsiLine, rsi)
line.set_data(overboughtLine, overbought)
line.set_data(oversoldLine, oversold)
Add plots to the chart
plot(rsi, title="RSI Plot", color=color.green, linewidth=2)
plot(macdLine, title="MACD Line", color=color.blue, linewidth=2)
plot(macdSignal, title="MACD Signal", color=color.purple, linewidth=2)
plot(macdHistogram, title="MACD Histogram", color=color.red, linewidth=2)
The syntax is correct for version 5 of the PineScript language, but I have these errors in the console of Tradinview when I want to apply to the graph.
I'm an amateur and learn on my own.

Related

Pigs counting when crossing a line using OpenCV

I'm trying to count the number of piglets that enter and leave a zone. This is important because, in my project, there is a balance underneath the zone that computes the weight of the animals. My goal is to find the pig's weight, so, to achieve that, I will count the number of piglets that enter the zone, and if this number is zero, I have the pig's weight, and according to the number of piglets that get in I will calculate the weight of each as well.
But the weight history is for the future. Currently, I need help in the counting process.
The video can be seen here. The entrance occurs from the minute 00:40 until 02:00 and the exit starts on the minute 03:54 and goes all the way through the video because the piglets start, at this point, to enter and exit the zone.
I've successfully counted the entrance with the code below. I defined a region of interest, very small, and filter the pigs according to their colors. It works fine until the piglets start to move around and get very active, leaving and entering the zone all the time.
I'm out of ideas to proceed with this challenge. If you have any suggestions, please, tell me!
Thanks!!
import cv2
FULL_VIDEO_PATH = "PATH TO THE FULL VIDEO"
MAX_COLOR = (225, 215, 219)
MIN_COLOR = (158, 141, 148)
def get_centroid(x, y, w, h):
x1 = int(w / 2)
y1 = int(h / 2)
cx = x + x1
cy = y + y1
return cx, cy
def filter_mask(frame):
# create a copy from the ROI to be filtered
ROI = (frame[80:310, 615:620]).copy()
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
# create a green rectangle on the structure that creates noise
thicker_line_filtered = cv2.rectangle(ROI, (400, 135), (0, 165), (20, 200, 20), -1)
closing = cv2.morphologyEx(thicker_line_filtered, cv2.MORPH_CLOSE, kernel)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)
dilation = cv2.dilate(opening, kernel, iterations=2)
# Filter the image according to the colors
segmented_line = cv2.inRange(dilation, MIN_COLOR, MAX_COLOR)
# Resize segmented line only for plot
copy = cv2.resize(segmented_line, (200, 400))
cv2.imshow('ROI', copy)
return segmented_line
def count_pigs():
cap = cv2.VideoCapture(FULL_VIDEO_PATH)
ret, frame = cap.read()
total_pigs = 0
frames_not_seen = 0
last_center = 0
is_position_ok = False
is_size_ok = False
total_size = 0
already_counted = False
while ret:
# Window interval used for counting
count_window_interval = (615, 0, 620, 400)
# Filter frame
fg_mask = filter_mask(frame)
# Draw a line on the frame, which represents when the pigs will be counted
frame_with_line = cv2.line(frame, count_window_interval[0:2], count_window_interval[2:4],(0,0,255), 1)
contours, _ = cv2.findContours(fg_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# If no contour is found, increments the variable
if len(contours) == 0:
frames_not_seen += 1
# If no contours are found within 5 frames, set last_center to 0 to generate the position difference when
# a new counter is found.
if frames_not_seen > 5:
last_center = 0
for c in contours:
frames_not_seen = 0
# Find the contour coordinates
(x, y, w, h) = cv2.boundingRect(c)
# Calculate the rectangle's center
centroid = get_centroid(x, y, w, h)
# Get the moments from the contour to calculate its size
moments = cv2.moments(c)
# Get contour's size
size = moments['m00']
# Sum the size until count the current pig
if not already_counted:
total_size += size
# If the difference between the last center and the current one is bigger than 80 - which means a new pig
# enter the counting zone - set the position ok and set the already_counted to False to mitigate noises
# with significant differences to be counted
if abs(last_center - centroid[1]) > 80:
is_position_ok = True
already_counted = False
# Imposes limits to the size to evaluate if the contour is consistent
# Min and Max value determined experimentally
if 1300 < total_size < 5500:
is_size_ok = True
# If all conditions are True, count the pig and reset all of them.
if is_position_ok and is_size_ok and not already_counted:
is_position_ok = False
is_size_ok = False
already_counted = True
total_size = 0
total_pigs += 1
last_center = centroid[1]
frame_with_line = cv2.putText(frame_with_line, f'Pigs: {total_pigs}', (100, 370) , cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2)
cv2.imshow('Frame', frame_with_line)
cv2.moveWindow('ROI', 1130, 0)
cv2.moveWindow('Frame', 0, 0)
k = cv2.waitKey(15) & 0xff
if k == 27:
break
elif k == 32:
cv2.waitKey() & 0xff
ret, frame = cap.read()
cv2.destroyAllWindows()
cap.release()
if __name__ == '__main__':
count_pigs()

How to create textbox on figure using first row in geodataframe?

I am looking to plot a textbox on a figure displaying the 5-Day NHC forecast cone for a tropical cyclone, in this case Hurricane Dorian. I have the four shapefiles (track line, cone, points, and watches/warnings). On the figure I want to display the following from the first row of points_gdf (yellow circles in the image; the two commented out lines near the bottom of the code is what I tried initially):
Latest Tracking Information: (regular string; below are variables from points_gdf)
LAT LON
MAXWIND
GUST
MSLP
TCSPD
track_line_gdf = geopandas.read_file('nhc/al052019_5day_037/al052019-037_5day_lin.shp')
cone_gdf = geopandas.read_file('nhc/al052019_5day_037/al052019-037_5day_pgn.shp')
points_gdf = geopandas.read_file('nhc/al052019_5day_037/al052019-037_5day_pts.shp')
ww_gdf = geopandas.read_file('nhc/al052019_5day_037/al052019-037_ww_wwlin.shp')
fig = plt.figure(figsize=(14,12))
fig.set_facecolor('white')
ax = plt.subplot(1,1,1, projection=map_crs)
ax.set_extent([-88,-70,25,50])
ax.add_geometries(cone_gdf['geometry'], crs=data_crs, facecolor='white',
edgecolor='black', linewidth=0.25, alpha=0.4)
ax.add_geometries(track_line_gdf['geometry'], crs=data_crs, facecolor='none',
edgecolor='black', linewidth=2)
sc = ax.scatter(points_gdf['LON'], points_gdf['LAT'], transform=data_crs,
zorder=10, c=points_gdf['MAXWIND'], cmap='jet')
ww_colors = {'Tropical Storm Watch': 'gold',
'Hurricane Watch': 'pink',
'Tropical Storm Warning': 'tab:blue',
'Hurricane Warning': 'tab:red'}
for ww_type in ww_colors.keys():
ww_subset = ww_gdf[ww_gdf['TCWW']==ww_type]
ax.add_geometries(ww_subset['geometry'], facecolor='none',
edgecolor=ww_colors[ww_type], crs=data_crs,
linewidth=5)
markers = [plt.Line2D([0,0],[0,0],color=color, marker='o', linestyle='') for color in ww_colors.values()]
Name = ww_gdf['STORMNAME'][0]
Storm = ww_gdf['STORMTYPE'][0]
AdvDate = ww_gdf['ADVDATE'][0]
AdvNum = ww_gdf['ADVISNUM'][0]
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
plt.colorbar(sc, label='Wind Speed (mph)')
plt.title(Storm + ' ' + Name + ' - ' + AdvDate + ' Advisory', fontsize=14, fontweight='bold')
plt.legend(markers, ww_colors.keys())
plt.text(0.05, 0.95, 'Testing', transform=ax.transAxes, va='top', bbox=props)
It would help to know either what error you're running into, or what exactly isn't behaving how you want. I can slightly tweak your code to make this:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(14,12))
fig.set_facecolor('white')
ax = plt.subplot(1,1,1, projection=ccrs.LambertConformal())
plt.title('Storm Advisory', fontsize=14, fontweight='bold')
points_gds = pd.DataFrame(dict(GUST=[165.0], LAT=[26.8],
LON=[-78.3], MSLP=[930.2]))
storminfo = f'''Max Wind Gusts: {points_gds.iloc[0]['GUST']:.0f} mph
Current Latitude: {points_gds.iloc[0]['LAT']:.1f}
Current Longitude: {points_gds.iloc[0]['LON']:.1f}
Central Pressure: {points_gds.iloc[0]['MSLP']:.2f} mb'''
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
plt.text(0.05, 0.95, 'Testing', transform=ax.transAxes, va='top', bbox=props)
ax.coastlines()
ax.set_extent([-88,-70,25,50])
which produces this image:
To make that work I needed to change round (which is a Python built-in function) to the string 'round'. The text is formatted using f-strings ("formatted string literals"), and enclosed as a triple-quoted string to avoid needing to manually put in the newline ('\n') characters. Python's docs can tell you more about how to control the formatting of individual items.

After alert condition when condition changes from true/false. Currently alerts if either condition is true. Not when it changes

This is part of a pine script for tradingview. On the script after '//Condition', I want an alert to generate only when the condition changes from long to short or short to long. Not the end of each candle as it does now, as one condition is always true.
This has been changed to a study.
threshold = input(title="Threshold", type=float, defval=0.0014, step=0.0001)
buying = l3_0 > threshold ? true : l3_0 < -threshold ? false : buying[1]
///// T edit
selling = l3_0 > -threshold ? true : l3_0 < threshold ? false :
selling[1] //// T edit END
hline(0, title="base line")
bgcolor(l3_0 > 0.0014 ? green : l3_0 < -0.0014 ? red : gray, transp=20)
bgcolor(buying ? green : red, transp=20)
plot(l3_0, color=silver, style=area, transp=75)
plot(l3_0, color=aqua, title="prediction")
///// Stragegy
/////////////////////////////////////////////////////
//longCondition = buying
//if (longCondition)
//strategy.entry("Long", strategy.long)
//shortCondition = buying != true
//if (shortCondition)
//strategy.entry("Short", strategy.short)
///// Alerts ///////////////////////////////////////////////////////alertcondition(condition, title, message)
//Condition
long = l3_0 > 0.0014
short = l3_0 < -0.0014
alertcondition(long, title = "ANN Long", message= "ANN Long")
alertcondition(short, title = "ANN Short", message= "ANN Short")
Let's look at a smaller example using MACD. We want to go long whenever delta is >= 0 and go short whenever delta is <0. Also, we would like to stay in our position unless the opposite signal is triggered (enter once and wait for the opposite signal).
Your code looks like below:
//#version=3
study("My Script", overlay=true)
// Get the inputs
MACDLengthMACD = input(title="MACD Length", defval=9, minval=1, maxval=100)
fastLengthMACD = input(title="MACD Fast Length", defval=12, minval=1, maxval=100)
slowlengthMACD = input(title="MACD Slow Length", defval=26, minval=1, maxval=100)
// Standard MACD calculations
MACD = ema(close, fastLengthMACD) - ema(close, slowlengthMACD)
aMACD = ema(MACD, MACDLengthMACD)
deltaMACD = MACD - aMACD
buySignal = (deltaMACD >= 0)
sellSignal= (deltaMACD < 0)
plotshape(series=buySignal, text="BUY", style=shape.triangleup, location=location.belowbar, color=green, size=size.small)
plotshape(series=sellSignal, text="SELL", style=shape.triangledown, location=location.abovebar, color=red, size=size.small)
In this case, you will get multiple BUY or SELL signals because buySignal and sellSignal will be true as long as their conditions are true.
However, those signals should be true for one bar only in order to trigger only one BUY or SELL signal. To accomplish that, you can use another variable (isLong, isShort in below code) and use history reference operator [] to determine if you were previously LONG or SHORT.
Then, only trigger your BUY signal if you are not already LONG and only trigger your SELL signal if you are not already SHORT. This way you will get only one BUY or SELL signal.
//#version=3
study("My Script", overlay=true)
// Get the inputs
MACDLengthMACD = input(title="MACD Length", defval=9, minval=1, maxval=100)
fastLengthMACD = input(title="MACD Fast Length", defval=12, minval=1, maxval=100)
slowlengthMACD = input(title="MACD Slow Length", defval=26, minval=1, maxval=100)
// Standard MACD calculations
MACD = ema(close, fastLengthMACD) - ema(close, slowlengthMACD)
aMACD = ema(MACD, MACDLengthMACD)
deltaMACD = MACD - aMACD
// Deternine if we are currently LONG
isLong = false
isLong := nz(isLong[1], false)
// Determine if we are currently SHORT
isShort = false
isShort := nz(isShort[1], false)
// Buy only if the buy signal is triggered and we are not already long
buySignal = not isLong and (deltaMACD >= 0)
// Sell only if the sell signal is triggered and we are not already short
sellSignal= not isShort and (deltaMACD < 0)
if (buySignal)
isLong := true
isShort := false
if (sellSignal)
isLong := false
isShort := true
plotshape(series=buySignal, text="BUY", style=shape.triangleup, location=location.belowbar, color=green, size=size.small)
plotshape(series=sellSignal, text="SELL", style=shape.triangledown, location=location.abovebar, color=red, size=size.small)
This will result in:

how to draw lines in Pine script (Tradingview)?

Pine editor still does not have built-in functions to plot lines (such as support lines, trend lines).
I could not find any direct or indirect method to draw lines.
I want to build function that look like below (for example only)
draw_line(price1, time1,price2, time2)
any Ideas or suggestions ?
Unfortunately I don't think this is something they want to provide. Noticing several promising posts from 4 years ago that never came through. The only other way, seem to involve some calculations, by approximating your line with some line plots, where you hide the non-relevant parts.
For example:
...
c = close >= open ? lime : red
plot(close, color = c)
would produce something like this:
Then, you could try to replace red with na to get only the green parts.
Example 2
I've done some more experiments. Apparently Pine is so crippled you can't even put a plot in function, so the only way seem to be to use the point slope formula for a line, like this:
//#version=3
study(title="Simple Line", shorttitle='AB', overlay=true)
P1x = input(5744)
P1y = input(1.2727)
P2x = input(5774)
P2y = input(1.2628)
plot(n, color=na, style=line) // hidden plot to show the bar number in indicator
// point slope
m = - (P2y - P1y) / (P2x - P1x)
// plot range
AB = n < P1x or n > P2x ? na : P1y - m*(n - P1x)
LA = (n == P1x) ? P1y : na
LB = (n == P2x) ? P2y : na
plot(AB, title="AB", color=#ff00ff, linewidth=1, style=line, transp=0)
plotshape(LA, title='A', location=location.absolute, color=silver, transp=0, text='A', textcolor=black, style=shape.labeldown)
plotshape(LB, title='B', location=location.absolute, color=silver, transp=0, text='B', textcolor=black, style=shape.labelup )
The result is quite nice, but too inconvenient to use.
UPDATE: 2019-10-01
Apparently they have added some new line functionality to Pinescript 4.0+.
Here is an example of using the new vline() function:
//#version=4
study("vline() Function for Pine Script v4.0+", overlay=true)
vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line, 54 lines maximum allowable per indicator
return = line.new(BarIndex, -1000, BarIndex, 1000, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)
if(bar_index%10==0.0)
vline(bar_index, #FF8000ff, line.style_solid, 1) // Variable assignment not required
As for the other "new" line function, I have not tested it yet.
This is now possible in Pine Script v4:
//#version=4
study("Line", overlay=true)
l = line.new(bar_index, high, bar_index[10], low[10], width = 4)
line.delete(l[1])
Here is a vertical line function by midtownsk8rguy on TradingView:
vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line Function, ≈50-54 lines maximum allowable per indicator
// return = line.new(BarIndex, 0.0, BarIndex, 100.0, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=false) and RSI, Stochastic, etc...
// return = line.new(BarIndex, -1.0, BarIndex, 1.0, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=false) and +/-1.0 oscillators
return = line.new(BarIndex, low - tr, BarIndex, high + tr, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=true)
if(bar_index%10==0.0) // Generically plots a line every 10 bars
vline(bar_index, #FF8000ff, line.style_solid, 1) // Variable assignment not required
You can also use if barstate.islast if you only draw your lines once instead of on each candle, this way you don't need to delete the previous lines.
More compact code for draw lines:
//#version=3
study("Draw line", overlay=true)
plot(n, color=na, style=line)
AB(x1,x2,y1,y2) => n < x1 or n > x2 ? na : y1 + (y2 - y1) / (x2 - x1) * (n - x1)
plot(AB(10065,10136,3819,3893), color=#ff00ff, linewidth=1, style=line,
transp=0)
plot(AB(10091,10136,3966.5,3931), color=#ff00ff, linewidth=1, style=line,
transp=0)
Here is an example that might answer the original question:
//#version=4
study(title="trendline example aapl", overlay=true)
//#AAPL
line12= line.new(x1=int(1656322200000),
y1=float(143.49),
x2=int(1659519000000),
y2=float(166.59),
extend=extend.right,
xloc=xloc.bar_time)
(to calculate the time it needs to be calculated as the *bar open time in unix milliseconds see: https://currentmillis.com/ ; can be calculated in excel with this formula =
= (([date eg mm/dd/yyyy]+[bar open time eg 9.30am])- 0/24 - DATE(1970,1,1)) * 86400000
= ((6/27/2022+9:30:00 AM)- 0/24 - DATE(1970,1,1)) * 86400000
= ((44739+0.395833333333333)- 0/24 - DATE(1970,1,1)) * 86400000
= 1656322200000
)
adjust the zero/24 to offset the time zone if needed eg 1/24

Learning Python 3.3 - TypeError: 'int' object is not callable

I was trying to solve Challenge 2 at the end of the classes chapter (Chapter 8) in "Python Programming for the Absolute Beginner" which is stated as:
Write a program that simulates a television by creating it as an object. The user should be able to enter a channel number and raise or lower the volume. Make sure that the channel number and the volume level stay within valid ranges.
I keep getting: TypeError: 'int' object is not callable, which at this stage just isn't very helpful.
I'm a beginner but I've seen something really similar working (see at the bottom right below my code) and nearly went as far as nearly copying that code. Could somebody maybe explain what's wrong with this and how I can get it to work?
Here's the complete error:
Traceback (most recent call last):
File "Untitled 3.py", line 59, in <module>
main()
File "Untitled 3.py", line 50, in main
tv.channel(newchannel = int(input("What channel would you like to set the TV to?")))
TypeError: 'int' object is not callable
My code is below,
Thanks
class Television(object):
"""a TV"""
def __init__(self, channel = 0, volume = 0):
self.channel = channel
self.volume = volume
def channel(self, newchannel = 0):
if newchannel <= 0 or newchannel >9:
print("No negative numbers or numbers higher than 9. Start again from the menu")
else:
self.channel = newchannel
print("You set the TV on channel", self.channel)
def volume(self, newvolume = 0):
if newvolume <= 0 or newvolume >9:
print("No negative numbers or numbers higher than 9. Start again from the menu")
else:
self.volume = newvolume
print("You set the TV on volume", self.volume)
def watch(self):
print("You are watching channel", self.channel, "at volume", self.volume)
def main():
tv = Television()
choice = None
while choice != "0":
print \
("""
TV
0 - Quit
1 - Watch the TV
2 - Change channel
3 - Set the volume
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
elif choice == "1":
tv.watching()
elif choice == "2":
tv.channel(newchannel = int(input("What channel would you like to set the TV to?")))
elif choice == "3":
tv.volume(newvolume = int(input("What channel would you like to set the TV to?")))
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
("\n\nPress the enter key to exit.")
Why does the following work instead? To me, it looks pretty similar to what I've done.
class Critter(object):
"""A virtual pet"""
def __init__(self, hunger = 0, boredom = 0):
self.hunger = hunger
self.boredom = boredom
def eat(self, food = 4):
print("Brruppp. Thank you.")
self.hunger += food
if self.hunger < 0:
self.hunger = 0
crit = Critter()
print(crit.hunger)
crit.eat(food = int(input("how much do you want to feed him?")))
print(crit.hunger)
The problem is you are defining a method with the same name as a property. That is, you're saying Television.channel is an int, but later you are binding a method to that name.