Open and close of the first 1 min bar - thinkscript

I know it's a long shot to ask here, but I am looking for a way to determine if the first 1 minute candle is red, meaning that the bar closes below the open.
To do this I simply need the open value and close value of the first one minute bar, but I haven't found a way to get the close.
Getting the open is fairly straight forward:
def openValue = open(period = AggregationPeriod.DAY);
Getting the Range of the first bar is fairly straightforward as well since we define a range (1 min) and return the high/low of that range.
If anybody can help, I would really appreciate it.
Thanks!

Ok, someone helped me figure it out.
def x = barNumber(); //bar
def RTH = getTime() >= RegularTradingStart(getYYYYMMDD()) and
getTime() <= RegularTradingEnd(getYYYYMMDD());
def TodaysOpen = if RTH and !RTH[1]
then open
else TodaysOpen[1];
def OpenX = if RTH and !RTH[1]
then x
else double.nan;
def YesterdaysClose = if !RTH and RTH[1]
then close[1]
else YesterdaysClose[1];
def CloseX = if !RTH and RTH[1]
then x
else double.nan;
def HighToday = if RTH and !RTH[1]
then high
else if RTH and high > HighToday[1]
then high
else HighToday[1];
def HighX = if high == HighToday
then x
else double.nan;
def LowToday = if RTH and !RTH[1]
then low
else if RTH and low < LowToday[1]
then low
else LowToday[1];
def LowX = if low == LowToday
then x
else double.nan;
plot OpenToday = if barNumber() >= HighestAll(OpenX)
then HighestAll(if isNaN(close[-1])
then TodaysOpen
else double.nan)
else double.nan;
OpenToday.SetStyle(Curve.Long_Dash);
def firstbarclose = if RTH and !RTH[1]
then close
else firstbarclose[1];
plot CloseBar = if barNumber() >= HighestAll(OpenX)
then HighestAll(if isNaN(close[-1])
then firstbarclose
else double.nan)
else double.nan;
closebar.SetStyle(Curve.Long_Dash);

Related

cv2.VideoCapture freeze framing when using a countdown timer with pressed key 's' for rock paper scissors project

I have defined two different functions, one for getting the prediction of the user using the Teachable Machine from Google and then a countdown function which is initiated by the 'S' key within the loop.
My issue is that when I click the 'S' key my Video Capture freeze frames and begins the countdown, when all I want it to be doing is allowing the user to ready themselves for creating one of three gestures.
The code is below:
def get_user_choice(self):
user_choice = ''
while True:
ret, frame = cap.read()
resized_frame = cv2.resize(frame, (224, 224), interpolation = cv2.INTER_AREA)
image_np = np.array(resized_frame)
normalized_image = (image_np.astype(np.float32) / 127.0) - 1 # Normalize the image
data[0] = normalized_image
prediction = model.predict(data, verbose=0)
cv2.imshow('frame', frame)
k = cv2.waitKey(1)
if k == ord('s'):
countdown()
user_index = np.argmax(prediction[0])
user_choice = user_options[user_index]
print('You chose:', user_choice)
return user_choice
def countdown():
print('Get your answer ready!')
prev = time.time() + 1
TIMER = int(4)
while TIMER >= 1:
cur = time.time()
if cur - prev >= 1:
prev = cur
TIMER = TIMER -1
print(TIMER)
It works almost perfectly apart from the countdown function which has created a freeze frame issue.
I've tried to mess around with the countdown function, and put the videocapture into the countdown function. Nothing seems to have worked for me so far, and thus is causing frustration.

Make model function to stop counting

In a django app i have a model function that counting the progress of an event between date time fields. Is it possible to stop the progress after reaching 100. For example:
models.py
start_appointment = models.DateTimeField(default=timezone.now, blank=True)
end_appointment = models.DateTimeField(default=timezone.now, blank=True)
model function
def get_progress(self):
if (self.status) == 'New' or (self.status) == 'Finished':
now = timezone.now()
progress = ((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100
if progress > 100.0:
...
return progress
Thank you
Simply use the Python min() function. That will return your progress calculation or 100 if the progress calculation is larger.
def get_progress(self):
if (self.status) == 'New' or (self.status) == 'Finished':
now = timezone.now()
progress = min(((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100, 100)
return progress
def get_progress(self):
return ((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100
def other_process():
while self.get_progress() < 100:
Do stuff here...
return progress
This will return the progress once it the appointment is over. Maybe you will want to return True or something instead to assert the appointment is complete

How do I change class value Python 3?

I'm trying to use OOP to make tic tac toe, but whenever I win/draw a game is just keeps running and won't cancel out the game?
The error seems to be something to do with my while loop not wanted to break out.
Maybe this is a really stupid and obvious error in my code, but I've only been learning Python for 3 months so unfortunately I'm not the best right now.
# The
In the p_v_p() function it checks while both players have won, could this be causing the problem?
The problem isn't that the class variable isn't changed, it's that you're not checking it frequently enough. FYI, you called it a class variable in your question, but has_won is actually an instance variable. There are two problems that need to be corrected.
Your diagonal win conditions are incorrect:
diagnol_win = [[1,4,9],[3,4,7]]
This should be diagnol_win = [[1,5,9],[3,5,7]]
As #rob-py mentioned, you need to check has_won after each move. The following should fix the issue.
def p_v_p():
print("\nWelcome to Player vs Player Game Mode\
Player 1 you are 'X' , Player 2 you are 'O'!")
while True:
print("\nPlayer Ones Turn!")
player1.move()
if player1.has_won:
return
print("\nPlayer Twos Turn!")
player2.move()
if player2.has_won:
return
Since you're new to python, I thought I could offer some suggestions. I think you're off to a good start, but I would suggest defining three main classes: Player, Board, and Game. Here's a (at least mostly) working example. Keep in mind that this was a quick edit, so there's still plenty of room for more improvement.
class Board():
class PositionError(RuntimeError):
pass
class UpdateError(RuntimeError):
pass
def __init__(self):
self.markers = [' '] * 9
def print(self):
print()
print(self.markers[:3])
print(self.markers[3:6])
print(self.markers[6:])
def update(self, position, marker):
if position < 1 or position > 9:
raise self.PositionError()
if self.markers[position - 1] != ' ':
raise self.UpdateError()
self.markers[position - 1] = marker
def __getitem__(self, index):
return self.markers[index]
def __setitem__(self, index, value):
self.update(index + 1, value)
class Player:
def __init__(self, counter):
self.has_won = False
self.counter = counter
def move(self, board):
while True:
try:
player_input = int(input("Where you you like to place your counter? (1-9): "))
board.update(player_input, self.counter)
return
except ValueError:
print("\nInvalid Input not an number,Try Again.")
continue
except Board.PositionError:
print("\nPlease enter a position between 1-9")
continue
except Board.UpdateError:
print("\nPosition {} is already taken".format(player_input))
continue
class Computer(Player):
def move(self):
raise NotImplementedError()
class Game:
DRAW = 'D'
INCOMPLETE = 'I'
HORIZONTAL_WIN = [[1,2,3],[4,5,6],[7,8,9]]
VERTICAL_WIN = [[1,4,7],[2,5,8],[3,6,9]]
DIAGONAL_WIN = [[1,5,9],[3,5,7]]
def __init__(self, player_1, player_2):
self.player_1 = player_1
self.player_2 = player_2
self.board = Board()
def reset(self):
self.board = Board()
def play(self):
index = 0
players = [self.player_1, self.player_2]
while True:
players[index].move(self.board)
self.board.print()
state = self.check_state()
if state == players[index].counter:
print("\nPlayer with counter {} has won!".format(players[index].counter))
break
if state == self.DRAW:
print("\nTHIS GAME IS A DRAW! NOBODY WINS!")
break
index = (index + 1) % len(players)
self.reset()
return
def check_state(self):
if len([c for c in self.board.markers if c in ['O', 'X']]) >= 9:
return self.DRAW
for x, y, z in self.HORIZONTAL_WIN:
if self.board[x-1] == self.board[y-1] == self.board[z-1] != " ":
return self.board[x-1]
for x, y, z in self.VERTICAL_WIN:
if self.board[x-1] == self.board[y-1] == self.board[z-1] != " ":
return self.board[x-1]
for x, y, z in self.DIAGONAL_WIN:
if self.board[x-1] == self.board[y-1] == self.board[z-1] != " ":
return self.board[x-1]
return self.INCOMPLETE
def p_v_p():
print("\nWelcome to Player vs Player Game Mode")
print("Player 1 you are 'X' , Player 2 you are 'O'!")
return Game(Player('X'), Player('O'))
def p_v_c():
print("\nWelcome to Player vs Computer")
print("Human player you are Player 1 and counter 'X'. "
"The Computer is player 2 and counter 'O'")
return Game(Player('X'), Computer('0'))
def game_selection():
while True:
game_mode = input("""\nEnter what game mode you want to play:
- Player Vs Player (PvP)
- Player vs Computer (PvC)
Type your desired game mode here: """)
if game_mode.lower() == 'pvp':
return p_v_p() # Calls function for Player vs Player
if __name__ == '__main__':
while True:
game_selection().play()
if not input('Play again? [y/N]: ').lower().startswith('y'):
break

Qt wrong duration with variable bitrate

QMediaPlayer calculates wrong duration with variable bitrate mp3. Yes, I know a similar topic was already opened, but is pretty old (2012). In addition, both VLC and Clementine, using Qt, for the same mp3 files can calculate the exact duration. So, I do not think it's a Qt bug.
I take the mp3 duration in this way:
void MainWindow::playerOnMediaStatusChanged(QMediaPlayer::MediaStatus status) {
if (status == QMediaPlayer::BufferedMedia) {
qint64 duration = player->duration(); //wrong
}
}
Can you help me?
QtMultiMedia::QMediaPlayer can not recognize variable bitrate mode.
It will give you wrong duration and wrong position.
You can patch QMediaPlayer to calculate the real position/duration.
Python/PySide2 example:
# Created by BaiJiFeiLong#gmail.com at 2022/2/22 21:39
import taglib
from IceSpringPathLib import Path
from PySide2 import QtMultimedia, QtCore
class PatchedMediaPlayer(QtMultimedia.QMediaPlayer):
durationChanged: QtCore.SignalInstance = QtCore.Signal(int)
positionChanged: QtCore.SignalInstance = QtCore.Signal(int)
def __init__(self):
super().__init__()
self._realDuration = 0
self._lastFakePosition = 0
self._bugRate = 0.0
super().durationChanged.connect(self._onSuperDurationChanged)
super().positionChanged.connect(self._onSuperPositionChanged)
def _onSuperDurationChanged(self, duration: int):
self._bugRate = duration / self._realDuration
self.durationChanged.emit(self._realDuration)
def _onSuperPositionChanged(self):
self.positionChanged.emit(self.position())
def setMedia(self, media: QtMultimedia.QMediaContent, stream: QtCore.QIODevice = None, realDuration=None) -> None:
self.blockSignals(True)
super().setMedia(media, stream)
self.blockSignals(False)
self._realDuration = realDuration
self._lastFakePosition = 0
self._bugRate = 0.0
if realDuration is None:
filename = media.canonicalUrl().toLocalFile()
file = taglib.File(filename)
bitrate = file.bitrate
file.close()
self._realDuration = Path(filename).stat().st_size * 8 // bitrate
def setPosition(self, position: int) -> None:
assert self._bugRate != 0 or position == 0
fakePosition = int(position * self._bugRate)
super().setPosition(int(position * self._bugRate))
self._lastFakePosition = fakePosition
def duration(self) -> int:
return self._realDuration
def position(self) -> int:
elapsed = super().position() - self._lastFakePosition
lastPosition = 0 if self._lastFakePosition == 0 else int(self._lastFakePosition / self._bugRate)
realPosition = lastPosition + elapsed
realPosition = max(realPosition, 0)
realPosition = min(realPosition, self._realDuration)
return realPosition
Requirement: pip install pytaglib==1.4.6, or any other library to fetch the real bitrate

Union Find algorithm in Python

I am trying to implement Union Find algorithm in python and I don't understand what's wrong with my code as everything seems to be in the right place.
Please help in this regard. Below is my code
class UnionFind:
def __init__(self,v):
self.parent = [-1 for i in range(v)]
self.lis=[]
def addEdge(self,i,j):
self.lis.append([i,j])
def findParent(self,i):
if self.parent[i] == -1:
return i
else :
self.findParent(self.parent[i])
def union(self,i,j):
self.parent[i]=j
def printResult(self):
print self.lis
def isBool(self):
for lisIter in self.lis:
x=self.findParent(lisIter[0])
y=self.findParent(lisIter[1])
if(x==y):
return True
self.union(x,y)
return False
uf = UnionFind(3)
uf.addEdge(0,1)
uf.addEdge(1,2)
uf.addEdge(2,0)
if uf.isBool():
print "The graph is cyclic"
else:
print "The graph is not cyclic"
Finally I got that little logic which I missed in the my code. I need to add the return statement in the else block of findParent method or else the returned value will be discarded and a none value will get returned. Uff!
def findParent(self,i):
if self.parent[i] == -1:
return i
else :
return self.findParent(self.parent[i])