Failure to exit possible repaint issue - repaint

My strategy is set to process_orders_on_close=true. Everything else default.
The strategy sends alerts on entry and exit, and they are all coming at the correct moment.
However, on the chart itself, the strategy exits don't always show at the right point.
I am using a trail stop of $0.04 which is 4 ticks, that activates when a specified price level is hit.
For example, in CL1!, I just had a short that was supposed to activate a trail stop exit if the price hit $86.35 on the 5 minute chart. The price got down to $86.32 and then in the same candle, it closed at $86.43.
The position should have exited at $86.36 since that is $0.04 above the low.
The alert came correctly at $86.36. However, the chart never indicated that the order was exited, and it didn't reflect in the list of trades. However, if I turn off the strategy, and then turn back on, then it shows correctly.
This issue has happened several times, and the strategy exit shows up several candles later with what seems to be no rhyme or reason. Nothing related to the trail stop or my stop loss either.
Below is my code for the exit:
strategy.exit(alert_profit="WIN", alert_loss="LOSS", id="Exit", from_entry="Long", qty=1, limit=ltp, stop=lsl, comment_profit = "TP-Long "+str.tostring(ltp), comment_loss = "SL-Long "+str.tostring(lsl))
strategy.exit(alert_profit="WIN", alert_loss="LOSS", id="Exit", from_entry="Short", qty=1, limit=stp, stop=ssl, comment_profit = "TP-Short "+str.tostring(stp), comment_loss = "SL-Short "+str.tostring(ssl))
Both of these lines are contained within IF statements that check to see if a trailstop is set. Otherwise, it will use a different type of exit.

Related

Issue wit checking for time on check

Hi I'm currently having an issue getting the time allocated for the user which is saved on a postgres database. What I'm trying to achieve is when the users duration expires a role is removed I'm wanting to get the time from the database when the check runs but this doesn't seem to be working,
My console is not outputting an error but the check doesn't seem to be running.
Here is what I'm working with:
#tasks.loop(seconds=5.0)
async def check_mute(self):
guild = self.bot.get_guild(750744359632121661)
restricted = discord.utils.get(member.guild.roles, name="Restricted")
members = discord.utils.get(member.guild.roles, name="Members")
for member in list(guild.members):
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
cursor.execute("SELECT time FROM blacklist WHERE username=%s", (member.id, ))
restricted_role = get(ctx.guild.roles, name="Restricted")
muted_time = cursor.fetchone()
current_time = dt.datetime.now()
mute_elapsed_time = current_time - muted_time
if member.id:
await member.add_roles(members)
await member.remove_roles(restricted, reason=f'Restricted role removed by {author.name}')
You're not getting errors because tasks don't throw any errors by default. In order to get some info out of them, you need to write a custom error handler for them.
With that said, I do see a few issues that might cause your loop to break.
First of all, the variables ctx and author are never defined anywhere in your code fragment, but you're using them. This will throw errors & interrupt the loop.
Are you starting your loop using check_mute.start()? Tasks need to be started before they run, and your code fragment doesn't have this.
the check doesn't seem to be running
I don't see you checking the time difference anywhere. You said the check didn't happen, but it just isn't there in the first place. You're defining mute_elapsed_time, but never using it to check if enough time has elapsed or not.
After fixing those, could you put some debug prints in your task to see where it gets & when it stops? If something else is wrong, that might help identify it.
PS. This is unrelated, but you're get'ing restricted_role in the loop for every member, while you can just do that once above the loop (and you already did do it above the loop, so it's really unnecessary). You're not even using it as far as I can see so consider removing it ^^. That's also the line where the ctx is (which doesn't exist) so removing it all together might be a good idea.

Random failure of selenium test on test server

I'm working on a project which uses nodejs and nighwatch for test automation. The problem here is that the tests are not reliable and give lots of false positives. I did everything to make them stable and still getting the errors. I went through some blogs like https://bocoup.com/blog/a-day-at-the-races and did some code refactoring. Did anyone have some suggestions to solve this issue. At this moment I have two options, either I rewrite the code in Java(removing nodejs and nightwatch from solution as I'm far more comfortable in Java then Javascript. Most of the time, struggle with the non blocking nature of Javascript) or taking snapshots/reviewing app logs/run one test at a time.
Test environment :-
Server -Linux
Display - Framebuffer
Total VM's -9 with selenium nodes running the tests in parallel.
Browser - Chrome
Type of errors which I get is element not found. Most of the time the tests fail as soon the page is loaded. I have already set 80 seconds for timeout so time can't be issue. The tests are running in parallel but on separate VM's so I don't know whether it can be issue or not.
Edit 1: -
Was working on this to know the root cause. I did following things to eliminate random fails: -
a. Added --suiteRetries to retry the failed cases.
b. Went through the error screenshot and DOM source. Everything seems fine.
c. Replaced the browser.pause with explicit waits
Also while debugging I observed one problem, maybe that is the issue which is causing random failures. Here's the code snippet
for (var i = 0; i < apiResponse.data.length; i++) {
var name = apiResponse.data[i];
browser.useXpath().waitForElementVisible(pageObject.getDynamicElement("#topicTextLabel", name.trim()), 5000, false);
browser.useCss().assert.containsText(
pageObject.getDynamicElement("#topicText", i + 1),
name.trim(),
util.format(issueCats.WRONG_DATA)
);
}
I added the xpath check to validate if i'm waiting enough for that text to appear. I observed that visible assertion is getting passed but in next assertion the #topicText is coming as previous value or null.This is an intermittent issue but on test server happens frequently.
There is no magic bullet to brittle UI end to end tests. In the ideal world there would be an option set avoid_random_failures=true that would quickly and easily solve the problem, but for now it's only a dream.
Simple rewriting all tests in Java will not solve the problem, but if you feel better in java, then I would definitely go in that direction.
As you already know from this article Avoiding random failures in Selenium UI tests there are 3 commonly used avoidance techniques for race conditions in UI tests:
using constant sleep
using WebDriver's "implicit wait" parameter
using explicit waits (WebDriverWait + ExpectedConditions + FluentWait)
These techniques are also briefly mentioned on WebDriver: Advanced Usage, you can also read about them here: Tips to Avoid Brittle UI Tests
Methods 1 and 2 are generally not recommended, they have drawbaks, they can work well on simple HTML pages, but they are not 100% realiable on AJAX pages, and they slow down the tests. The best one is #3 - explicit waits.
In order to use technique #3 (explicit waits) You need to familiarize yourself and be comfortable with the following WebDriver tools (I point to theirs java versions, but they have their counterparts in other languages):
WebDriverWait class
ExpectedConditions class
FluentWait - used very rarely, but very usefull in some difficult cases
ExpectedConditions has many predefinied wait states, the most used (in my experience) is ExpectedConditions#elementToBeClickable which waits until an element is visible and enabled such that you can click it.
How to use it - an example: say you open a page with a form which contains several fields to which you want to enter data. Usually it is enought to wait until the first field appears on the page and it will be editable (clickable):
By field1 = By.xpath("//div//input[.......]");
By field2 = By.id("some_id");
By field3 = By.name("some_name");
By buttonOk = By.xpath("//input[ text() = 'OK' ]");
....
....
WebDriwerWait wait = new WebDriverWait( driver, 60 ); // wait max 60 seconds
// wait max 60 seconds until element is visible and enabled such that you can click it
// if you can click it, that means it is editable
wait.until( ExpectedConditions.elementToBeClickable( field1 ) ).sendKeys("some data" );
driver.findElement( field2 ).sendKeys( "other data" );
driver.findElement( field3 ).sendKeys( "name" );
....
wait.until( ExpectedConditions.elementToBeClickable( buttonOK)).click();
The above code waits until field1 becomes editable after the page is loaded and rendered - but no longer, exactly as long as it is neccesarry. If the element will not be visible and editable after 60 seconds, then test will fail with TimeoutException.
Usually it's only necessary to wait for the first field on the page, if it becomes active, then the others also will be.

Does capybara "within" deal with ajax, why failed within the css with the error " unable to find find css "

I have a step like this:
Then(/^I can see the Eligible Bugs list "([^"]*)"$/) do |bugs|
bugs_list = bugs.split(", ")
assert page.has_css?(".eligible-bugs", :visible => true)
within(".eligible-bugs") do
bugs_list.each do |bug|
assert page.has_content?(bug)
end
end
end
But the step fail sometimes at the " within(".eligible-bugs") do" with the error 'Unable to find css ".eligible-bugs"'
I feel it is odd.
for the assertion has been passed. it means the css is visible.
why within cannot find css? How it happen.
But the step fail sometimes at the " within(".eligible-bugs") do" with the error 'Unable to find css ".eligible-bugs"'
I feel it is odd.
for the assertion has been passed. it means the css is visible.
why within cannot find css? How it happen.
BTW, I have set my max wait time to 5.
Capybara.default_max_wait_time = 5
The only way that should happen, is if the page is dynamically changing while you're running the test - sometime during your check for all bugs content on the page it is changing and the '.eligible-bugs' element is going way. The test and the browser run separately, so how/why it is happening depends on what else your page is doing in the browser, it would also depend on what steps have come before this in the test.
Also, note that it's not necessarily disappearing between the has_css? and the within statement first running. If it disappears at any point during the code inside the within running it could throw the same error as it attempts to reload the '.eligible-bugs' element.
From the title of the question I assume the list that you want to check is the result of a search or filtering action. If it is, does that action remove the existing '.eligible-bugs' element and then after some time replace it with a new one returned from an ajax request or something? If that is the case then, since you control the test data, you should be waiting for the correct results count to show, thereby ensuring any element replacements have completed, before checking for the text. How you do that would depend on the exact makeup of the page, but if each eligible bug was a child of '.eligible-bugs' and had a class of '.eligible-bug' I would write your test something like
Then(/^I can see the Eligible Bugs list "([^"]*)"$/) do |bugs|
bugs_list = bugs.split(", ")
assert_css(".eligible-bugs > .eligible_bug", count: bugs_list.size) # wait until the expected number of results have shown up
within(".eligible-bugs") do
bugs_list.each do |bug|
assert_content(bug)
end
end
end

ServiceStack RequestLogger shows past requests as "is running" long after being issued

I am running ServiceStack 3.97 and just added the RequestLogger plugin - amazing that it is built-in, just what I needed. The worrisome thing I noticed once I tried it is that it says all the previous GET requests have "is running = true".
For example, I issued a few requests in a browser tab (pressing F5 a few times, and closed tab) and can see them show up here /api/requestlogs. In the items column, the elapsed time keeps ticking each time I refresh and is running is always true.
This is very scary as it appears to be saying that the requests remain open. If so, it could be related to an unknown error I get over time whereby SS is unable to return an Open connection.
Here is a sample of the items field:
_request Duration Stopwatch
is Running true
elapsed PT8M31.5460178S
elapsed Milliseconds 511546
elapsed Ticks 1395611107
Any suggestions or ideas as to why this is happening and/or how to dig deeper? What would keep GETs open?
The RequestLogger takes a 'snapshot' which includes a dump of the Request.Items dictionary (which contains a Stopwatch) into a rolling log of DTO's, but this doesn't keep the request 'open' as you might think, so there's no need for concern.

Linux x11 XGrabKeyboard() cause keyboard to be frozen

I am writing a program which need to listen the user keyboard stroks.
I use function XGrabKeyboard() and this is my code:
XGrabKeyboard(pDisplay, DefaultRootWindow(pDisplay), True, GrabModeAsync, GrabModeAsync, CurrentTime);
XEvent event;
while (true)
{
XNextEvent(pDisplay, &event);
switch (event.type)
{
...
}
}
But it causes the keyboard and cursor to be frozen.
I looked up the man page, it only says: "The third parameter specifies a Boolean value that indicates whether the keyboard events are to be reported as usual."
I tried both true or false or the 3rd param, both GrabModeAsync and GrabModeSync for the 4th and 5th param, but it doesn't work.
After calling XGrabKeyboard(), the keyboard is frozen and mouse click doesn't response.
Any ideas?
XGrabKeyboard() (if successful - be sure to check the return value), redirects all key events to your client.
So if your "..." inside the while(true) does not properly handle those key events, or does not ever ungrab (XUngrabKeyboard) or release sync events (XAllowEvents, only applies to GrabModeSync), then the keyboard would appear to lock up.
The boolean parameter is owner_events which indicates whether to report key events always to the window provided to XGrabKeyboard, or report them to the window they normally would have gone to without the grab. Typically you want False (report to the grab window).
For typical uses of XGrabKeyboard (I don't know your use-case) the parameters you would want are:
grab window = some window in your app that relates to the reason for the grab
owner_events=False to send all events to that window
pointer_mode=Async to not screw with the pointer
keyboard_mode=Async to just redirect all key events and avoid need for AllowEvents
time=the timestamp from the event triggering the grab, ideally, or one generated by changing a property and grabbing the timestamp off the PropertyNotify
But, it depends. To give any definitive answer you'd probably need to post a compilable program, I think the bug is likely in the "..." part of your code. Try narrowing your app down to a single-file test case that can be run by others perhaps. Or explain more why you are grabbing and what you're trying to accomplish in the big picture.
I cant help with the XGrabKeyboard function - I havent used it before and dont know how it works - but I can suggest another way of getting the keyboard events.
When creating my window using XCreateWindow, the last argument is a XSetWindowAttributes object. This object has a member event_mask, which you can use to choose which events your window will receive.
I set mine like this:
XSetWindowAttributes setWindAttrs
setWindAttrs.event_mask = ExposureMask
| KeyPressMask
| KeyReleaseMask
| ButtonPressMask
| ButtonReleaseMask;
That will mean you receive events for keyboard key presses and mouse button clicks if you pass this object to XCreateWindow on window creation.
Also another note you can use XPending(pDisplay) to check if there are still events waiting to be handled - so it could replace true in your while(true) line.
Edit: Also your freezing issue could be that you dont return false anywhere in your while loop? It may be stuck in an infinite loop, unless you just removed that bit for the post. Try replacing true with xpending as I suggested above and it may fix the issue, or just returning false after handling the event, but this would only handle one event per frame rather than handling all the currently pending events like XPending would do, and I assume that is what you want to do.

Resources