Optimising PixelSearch - performance

I need to optimise this AHK script, currently the script runs in around 2 seconds. I would ultimately like it to run >1 second, the best case would be 0.6 seconds. The basic functionality is the script is clicking on red boxes, of which there can be between 2 - 8. I'd love some help on ways to increase the speed of this script if possible.
Thanks, code below.
1::
; Activate the target window
WinActivate, Paint
; Define the search area
SearchLeft := 1047
SearchTop := 572
SearchRight := 1222
SearchBottom := 650
SetDefaultMouseSpeed, 0
; Start the timer
StartTime := A_TickCount
; Loop through all pixels in the search area and click on them
Loop {
; Search for the next pixel
PixelSearch, Px, Py, SearchLeft, SearchTop, SearchRight, SearchBottom, 0x0000FF, RGBFast, Fastest
if (ErrorLevel = 0) {
; Click on the pixel
Click, %Px%, %Py%, 1
}
else {
; If no pixel is found, exit the loop
break
}
}
; Calculate the elapsed time
ElapsedTime := A_TickCount - StartTime
; Output the elapsed time as a message box
MsgBox, % "Script completed in " . ElapsedTime . " milliseconds."
3::ExitApp

Related

Pine script strategy open at second open candel and no when EMA crossover

whith this strategy i would like to have the open trade in exactly moment of ema crossovers, but all time I have open trade when the next candle open.
It is often a problem because at the ema crossovers I have a bullish push but at the opening of the next candle can be bearish causing the loss of the trade.
Can you help me? thanks
//#version=5
strategy(title='MARCO 18/20', overlay=true)
// STEP 1:
// Make inputs that set the take profit % (optional)
FastPeriod = input.int(title='Fast MA Period', defval=18, group='Moving Average')
SlowPeriod = input.int(title='Slow MA Period', defval=20, group='Moving Average')
TPPerc = input.float(title='Long Take Profit (%)', defval=0.11, group='TP & SL')
SLPerc = input.float(title='Long Stop Loss (%)', defval=4.4, group='TP & SL')
TP_Ratio = input.float(title='Sell Postion Size % # TP', defval=100, group='TP & SL', tooltip='Example: 100 closing 100% of the position once TP is reached') / 100
// Calculate moving averages
fastSMA = ta.sma(close, FastPeriod)
slowSMA = ta.sma(close, SlowPeriod)
// Calculate trading conditions
enterLong = ta.crossover(fastSMA, slowSMA)
// Plot moving averages
plot(series=fastSMA, color=color.new(color.green, 0), title='Fase MA')
plot(series=slowSMA, color=color.new(color.red, 0), title='Slow MA')
// STEP 2:
// Figure out take profit price
percentAsPoints(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)
percentAsPrice(pcnt) =>
strategy.position_size != 0 ? (pcnt / 100.0) * strategy.position_avg_price : float(na)
current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))
TP = strategy.position_avg_price + percentAsPoints(TPPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
SL = strategy.position_avg_price - percentAsPoints(SLPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
// Submit entry orders
if enterLong
strategy.entry(id='Long', direction=strategy.long)
// STEP 3:
// Submit exit orders based on take profit price
if strategy.position_size > 0
strategy.exit('TP', from_entry='Long', limit=TP, stop=SL)
// Plot take profit values for confirmation
plot(series=strategy.position_size > 0 ? TP : na, color=color.new(color.green, 0), style=plot.style_circles, linewidth=1, title='Take Profit')
plot(series=strategy.position_size > 0 ? SL : na, color=color.new(color.red, 0), style=plot.style_circles, linewidth=1, title='Stop Loss')
Pine script makes the calculations (runs your code) when the bar closed. After that, if your code has an entry, you can enter a trade on the next trade. Since the bar where you run the script is already closed, the trade will be made on the next trade - open price of the next bar. This is basically how real trade will work, since you can't check a trade that already happened and then decide that this trade is good for you or not. You will have to enter on the next trade.
You can override this if you wish.
try enabling in settings: recalculate strategy on each tick

Select whole words when mouse hovers over- Autohotkey

If the cursor is of the IBeam type and the F20 key is pressed and dragged, the text is selected with the shortcut Ctrl + Shift + right (or in the direction to which it is moved) .
Is there any way of doing this? https://imgur.com/a/Rqrfwjk
I have this code but it is based on the number of pixels moved and not on whether the cursor is over a word
#If WinActive("ahk_exe chrome.exe") && A_Cursor = "IBeam"
~LButton::
Click
MouseGetPos, x1
SetTimer, Check, 100
SoundBeep, 1500
KeyWait, LButton
SetTimer, Check, Off
SoundBeep, 1000
Return
#If
Check:
MouseGetPos, x2
f := Floor(Abs((x2 - x1) / 110))
Switch
{
Case x2 > x1: Send ^+{Right %f%}
Case x2 < x1: Send % "{Right}^+{Left " f + 1 "}"
}
Return

Quick selection script issue

I have this autohotkey script that points to the entire word by pointing to the first word and if the cursor scrolls 110px in one direction. The code uses Ctrl + Shift + {Right} to select the next words, but for the previous words you can't use Ctrl + Shift + {Left} because the current word is deselected.
How could I solve this problem so that it selects well in this direction?
#If WinActive("ahk_exe chrome.exe") && A_Cursor = "IBeam" ; Is in Chrome and cursor is on text field
~LButton::
Click
MouseGetPos, x1
SetTimer, Check, 100
SoundBeep, 1500
KeyWait, LButton
SetTimer, Check, Off
SoundBeep, 1000
Return
#If
Check:
MouseGetPos, x2
f := Floor(Abs((x2 - x1) / 110)) ; calculate if the pointer have travel 110px
Switch
{
Case x2 > x1: Send ^+{Right %f%}
Case x2 < x1: Send % "{Right}^+{Left " f + 1 "}" ;Does not allow selecting the previous word while keeping the current word selected
}
Return

Algorithm and pseudocode from a flowchart

I'm new to programming, and I became stuck here where I have to write an algorithm and pseudo code for this flowchart, but I'm confused on how to do the loop delay 2 seconds, or the add 2 seconds until it hits 10.
Thanks for your help!!!!
I think that psuedocode can sometimes be harder than writing real code for people who are just starting. The psuedocode for those instructions can be pretty-well exactly as in the flowchard:
How to do the loop delay 2 seconds:
while (door_sensor_read is no)
sleep for 2 seconds
and the add 2 seconds until it hits 10:
The pseudo code would be:
while (counter < 10)
{
sensor read = read the door;
while (sensor read == closed)
{
counter = 0;
sleep 2000ms;
}
counter += 2;
sleep 2000ms;
}
sound alarm;

How to best create a Timer Function in R

I'm trying to create a function in R that returns for the first x seconds after the function call 1, the next x seconds 0, the next x seconds 1 again,...the whole procedure should stop after another time interval or after n iterations. I want to do this with one function call.
I read about the package tcltk which apparently entails some possibilities to create such "timer" functions, however I did not find enough explanations to sort out my issue.
Could you advise me where to find a good manual that explains tcl in context with R? Do you have other ideas how to create such a function in an efficient way?
Thanks a lot for your help.
If I understood you correctly, you are trying to create a function that will return 1 whenever it is called in the first x secs, then return 0 whenever it's called in the next x secs, then return 1 over the next x secs, etc. And after a certain total time, it should be "done", maybe return -1?
You could do this using the following function that will "create" a function with any desired interval:
flipper <- function(interval=10, total = 60) {
t0 <- Sys.time()
function() {
seconds <- round(as.double( difftime(Sys.time(), t0, u = 'secs')))
if(seconds > total)
return(-1) else
return(trunc( 1 + (seconds / interval ) ) %% 2)
}
}
You can use this to create a function that alternates between 0 and 1 every 10 secs during the first 60 seconds, and returns -1 after 60 seconds:
> flp <- flipper(10,60)
Now calling flp() will have the behavior you are looking for, i.e. when you call flp() during the next 60 secs, it will alternate between 1 and 0 every 10 secs, then after 60 secs it will just return -1.
Sys.sleep from base could not be a solution?
E.g.: stop every 10th iteration in a loop for 10 seconds:
for (i in 1:100) {
# do something
if ((i %% 10) == 0) {
Sys.sleep(10)
}
}
May I also suggest:
Timer 1
library(data.table)
begin.time <- proc.time()
timetaken(begin.time)
Timer 2
library(matlab)
tic(gcFirst=FALSE)
toc(echo=TRUE)
Both are excellent choices for timers
The tcltk command after will call a function after a time delay. Getting it to repeatedly call can be done along the following lines (made more complicated by this desire to have different intervals between events).
afterID <- ""
someFlag <- TRUE
MS <- 5000 # milliseconds
repeatCall <- function(ms=MS, f) {
afterID <<- tcl("after", ms, function() {
if(someFlag) {
f()
afterID <<- repeatCall(MS - ms, f)
} else {
tcl("after", "cancel", afterID)
}
})
}
repeatCall(MS, function() {
print("Running. Set someFlag <- FALSE to stop.")
})
timefun <- function(interval = 10, output = c(0, 1)) {
start <- Sys.time()
# do some stuff
for (i in 1:99999) paste(i, i^2)
# how many intervals did it take
elapsed <- as.numeric(round(Sys.time() - start)) / interval
output[elapsed %% length(output) + 1]
}
I'm not clear on "the whole procedure should stop after another time interval or after n iterations", do you want to check elapsed time periodically during the function execution and stop() if it's above a certain value?

Resources