How can I enter and exit a trade at a given time? - pine-script-v5

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)

Related

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!

How to code dynamic stop loss orders under each swing low/high in a pine strategy script?

I am trying to program a strategy with stop loss orders that would automatically be placed under each swing low or high, because I believe that static stop loss orders with percentages or ticks are more likely to fail in the market.
After searching online for a long time I could not find any script that worked with dynamic stop loss, but most of them rather worked with fixed stop loss orders. Then, I came across the
ta.lowest(low,14) / ta.highest(high,14) function
and thought that it could be used to identify the value of the lowest candle in a certain range which could then be used as the initial point on which to add a percentage, and voila, that would be a dynamic stop loss based on swing low/high. Now the problem is it did not work out as I imagined and I have no clue why, which is why I am posting this question and hope that someone can point out my mistake.
Here the proof that it is not working:
The trade should be stopped out after reaching the price of the lowest candle (-0.1%) within the range of the last 5 candles
This is the part of the script that does not work:
// *************Entry orders*************
if longCondition
strategy.entry("Long", strategy.long)
if shortCondition
strategy.entry("Short", strategy.short)
//*************Stop Loss Orders*************
long_pos = strategy.position_size > 0
short_pos = strategy.position_size < 0
sl_perc = input.float(0.1, "Stop Loss Percentage under swing low/high")
sl_long = ta.lowest(low, 5) - ta.lowest(low, 14)/100*sl_perc
sl_short = ta.highest(high,5) + ta.lowest(low, 14)/100*sl_perc
strategy.exit("LongExit", "SL Long", stop = sl_long )
strategy.exit("ShortExit", "SL Short",stop = sl_short )
Thanks for any suggestions and help!
I think I found the answer myself:
I chose the wrong ID for the Exits. Really stupid mistake :(
(Hope that can be useful for anyone looking to try to do the same)
//*************STOP LOSS*************
long_pos = strategy.position_size > 0
short_pos = strategy.position_size < 0
sl_perc = input.float(1, "Stop Loss Percentage under swing low/high")
sl_long = ta.lowest(low, 5) - ta.lowest(low, 14)/100*sl_perc
sl_short = ta.highest(high, 5) + ta.lowest(low, 14)/100*sl_perc
strategy.exit("SL Long", "Long", stop=sl_long)
strategy.exit("SL Short", "Short", stop=sl_short)

Add a constraint of renewable ressource

I am new to these optimisation problems, I just found the or-tools library and saw that cp_model can fix problems that are close to mine.
I have printers and some tasks, that I want to schedule in order to finish the production the earliest. The tasks uses time on machine and raw material, that I must refill at the end of coil. For the moment, I don't consider changing a plastic coil before using all the material.
Here is some information about my situation:
1- The printers are all same, they can do every task, with the same efficiency.
2- A printer can only print one task at a time.
3- A printer cannot start without human around, so tasks can start only at certain hours (in the code below, from 0AM to 10 AM).
4- A task can finish at any time.
5- If a printer has no more material, it needs to be change, this can happen only on opening hours.
6- If a printer has no more material, the task is paused until new material is put.
7- I consider having unlimited quantity of material coil.
Thanks to examples and some search in the documentation, I have been able to fix all the issues that are not related to material. I have been able to set a maximum quantity per machine, but it is not my issue.
I don't understand how I can pause/resume my intervals (for the moment I set the duration to a fixed one).
from ortools.sat.python import cp_model
from ortools.util.python import sorted_interval_list
import random
Domain = sorted_interval_list.Domain
def main():
random.seed(0)
nb_jobs = 10
nb_machine = 2
horizon = 30000000
job_list = [] #Job : (id,time,quantity)
listOfEnds = []
quantityPerMachine = []
maxQuantity = 5
#create the jobs
for i in range(nb_jobs):
time = random.randrange(1,24)
quantity = random.randrange(1,4)
job_list.append([i,time,quantity])
print([job[1] for job in job_list])
print("total time to print = ",horizon)
print("quantity")
print([job[2] for job in job_list])
print("total quantity = ",sum([job[2] for job in job_list]))
model = cp_model.CpModel()
makespan = model.NewIntVar(0, horizon, 'makespan')
machineForJob = {}
#boolean variable for each combination of machine and job. if True then machine works on this job
for machine in range(nb_machine):
for job in job_list:
j = job[0]
machineForJob[(machine,j)]=(model.NewBoolVar(f'x[{machine},{j}]'))
#for each job, apply sum()==1 to ensure one machine works on each job only
for j in range(nb_jobs):
model.Add(sum([machineForJob[(machine,j)] for machine in range(nb_machine)])==1)
#set the affectation of the jobs
time_intervals={}
starts = {}
ends = {}
#Time domain represents working hours when someone can start the taks
timeDomain = []#[[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[24],[25],[26]]
for i in range(20):
for j in range(10):
t= [j +i*24]
timeDomain.append(t)
for machine in range(nb_machine):
time_intervals[machine] = []
for job in job_list:
j = job[0]
duration = job[1]
starts[(machine,j)] = model.NewIntVarFromDomain(Domain.FromIntervals(timeDomain),f'start {machine},{j}')
ends[(machine,j)] = (model.NewIntVar(0, horizon, f'end {machine},{j}'))
time_intervals[machine].append(model.NewOptionalIntervalVar(starts[(machine,j)], duration, ends[(machine,j)],
machineForJob[(machine,j)],f'interval {machine},{j} '))
#time should not overlap, quantity of raw material is limited,
for machine in range(nb_machine):
#model.Add(quantityPerMachine[machine] <= maxQuantity) Not working as expected as the raw material cannot be refilled
model.AddNoOverlap(time_intervals[machine])
#calculate time per machine
time_per_machine = []
for machine in range(nb_machine):
q = 0
s = 0
for job in job_list:
s+= job[1]*machineForJob[(machine,job[0])]
listOfEnds.append(ends[(machine,job[0])])
q+= job[2]*machineForJob[(machine,job[0])]
time_per_machine.append(s)
quantityPerMachine.append(q)
#Goal is to finish all taks earliest
model.AddMaxEquality(makespan,listOfEnds)
model.Minimize(makespan)
solver = cp_model.CpSolver()
# Sets a time limit of 10 seconds.
solver.parameters.max_time_in_seconds = 600.0
#Solve and prints
status = solver.Solve(model)
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
print("optimal =",status == cp_model.OPTIMAL )
print(f'Total cost = {solver.ObjectiveValue()}')
for i in range(nb_machine):
for j in range(nb_jobs):
if solver.BooleanValue(machineForJob[(i,j)]):
print(
f'Machine {i} assigned to Job {j} Time = {job_list[j][1]},Quantity = {job_list[j][2]}')
print(f"[{solver.Value(starts[(i,j)])} ,{solver.Value(ends[(i,j)])}]")
else:
print('No solution found.')
# Statistics.
print('\nStatistics')
print(' - conflicts: %i' % solver.NumConflicts())
print(' - branches : %i' % solver.NumBranches())
print(' - wall time: %f s' % solver.WallTime())

haproxy stats: qtime,ctime,rtime,ttime?

Running a web app behind HAProxy 1.6.3-1ubuntu0.1, I'm getting haproxy stats qtime,ctime,rtime,ttime values of 0,0,0,2704.
From the docs (https://www.haproxy.org/download/1.6/doc/management.txt):
58. qtime [..BS]: the average queue time in ms over the 1024 last requests
59. ctime [..BS]: the average connect time in ms over the 1024 last requests
60. rtime [..BS]: the average response time in ms over the 1024 last requests
(0 for TCP)
61. ttime [..BS]: the average total session time in ms over the 1024 last requests
I'm expecting response times in the 0-10ms range. ttime of 2704 milliseconds seems unrealistically high. Is it possible the units are off and this is 2704 microseconds rather than 2704 millseconds?
Secondly, it seems suspicious that ttime isn't even close to qtime+ctime+rtime. Is total response time not the sum of the time to queue, connect, and respond? What is the other time, that is included in total but not queue/connect/response? Why can my response times be <1ms, but my total response times be ~2704 ms?
Here is my full csv stats:
$ curl "http://localhost:9000/haproxy_stats;csv"
# pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt,comp_in,comp_out,comp_byp,comp_rsp,lastsess,last_chk,last_agt,qtime,ctime,rtime,ttime,
http-in,FRONTEND,,,4707,18646,50000,5284057,209236612829,42137321877,0,0,997514,,,,,OPEN,,,,,,,,,1,2,0,,,,0,4,0,2068,,,,0,578425742,0,997712,22764,1858,,1561,3922,579448076,,,0,0,0,0,,,,,,,,
servers,server1,0,0,0,4337,20000,578546476,209231794363,41950395095,,0,,22861,1754,95914,0,no check,1,1,0,,,,,,1,3,1,,578450562,,2,1561,,6773,,,,0,578425742,0,198,0,0,0,,,,29,1751,,,,,0,,,0,0,0,2704,
servers,BACKEND,0,0,0,5919,5000,578450562,209231794363,41950395095,0,0,,22861,1754,95914,0,UP,1,1,0,,0,320458,0,,1,3,0,,578450562,,1,1561,,3922,,,,0,578425742,0,198,22764,1858,,,,,29,1751,0,0,0,0,0,,,0,0,0,2704,
stats,FRONTEND,,,2,5,2000,5588,639269,8045341,0,0,29,,,,,OPEN,,,,,,,,,1,4,0,,,,0,1,0,5,,,,0,5374,0,29,196,0,,1,5,5600,,,0,0,0,0,,,,,,,,
stats,BACKEND,0,0,0,1,200,196,639269,8045341,0,0,,196,0,0,0,UP,0,0,0,,0,320458,0,,1,4,0,,0,,1,0,,5,,,,0,0,0,0,196,0,,,,,0,0,0,0,0,0,0,,,0,0,0,0,
In haproxy >2 you now get two values n / n which is the max within a sliding window and the average for that window. The max value remains the max across all sample windows until a higher value is found. On 1.8 you only get the average.
Example of haproxy 2 v 1.8. Note these proxies are used very differently and with dramatically different loads.
So looks like the average response times at least since last reboot are 66m and 275ms.
The average is computed as:
data time + cumulative http connections - 1 / cumulative http connections
This might not be a perfect analysis so if anyone has improvements it'd be appreciated. This is meant to show how I came to the answer above so you can use it to gather more insight into the other counters you asked about. Most of this information was gathered from reading stats.c. The counters you asked about are defined here.
unsigned int q_time, c_time, d_time, t_time; /* sums of conn_time, queue_time, data_time, total_time */
unsigned int qtime_max, ctime_max, dtime_max, ttime_max; /* maximum of conn_time, queue_time, data_time, total_time observed */```
The stats page values are built from this code:
if (strcmp(field_str(stats, ST_F_MODE), "http") == 0)
chunk_appendf(out, "<tr><th>- Responses time:</th><td>%s / %s</td><td>ms</td></tr>",
U2H(stats[ST_F_RT_MAX].u.u32), U2H(stats[ST_F_RTIME].u.u32));
chunk_appendf(out, "<tr><th>- Total time:</th><td>%s / %s</td><td>ms</td></tr>",
U2H(stats[ST_F_TT_MAX].u.u32), U2H(stats[ST_F_TTIME].u.u32));
You asked about all the counter but I'll focus on one. As can be seen in the snippit above for "Response time:" ST_F_RT_MAX and ST_F_RTIME are the values displayed on the stats page as n (rtime_max) / n (rtime) respectively. These are defined as follows:
[ST_F_RT_MAX] = { .name = "rtime_max", .desc = "Maximum observed time spent waiting for a server response, in milliseconds (backend/server)" },
[ST_F_RTIME] = { .name = "rtime", .desc = "Time spent waiting for a server response, in milliseconds, averaged over the 1024 last requests (backend/server)" },
These set a "metric" value (among other things) in a case statement further down in the code:
case ST_F_RT_MAX:
metric = mkf_u32(FN_MAX, sv->counters.dtime_max);
break;
case ST_F_RTIME:
metric = mkf_u32(FN_AVG, swrate_avg(sv->counters.d_time, srv_samples_window));
break;
These metric values give us a good look at what the stats page is telling us. The first value in the "Responses time: 0 / 0" ST_F_RT_MAX, is some max value time spent waiting. The second value in "Responses time: 0 / 0" ST_F_RTIME is an average time taken for each connection. These are the max and average taken within a window of time, i.e. however long it takes for you to get 1024 connections.
For example "Responses time: 10000 / 20":
max time spent waiting (max value ever reached including http keepalive time) over the last 1024 connections 10 seconds
average time over the last 1024 connections 20ms
So for all intents and purposes
rtime_max = dtime_max
rtime = swrate_avg(d_time, srv_samples_window)
Which begs the question what is dtime_max d_time and srv_sample_window? These are the data time windows, I couldn't actually figure how these time values are being set, but at face value it's "some time" for the last 1024 connections. As pointed out here keepalive times are included in max totals which is why the numbers are high.
Now that we know ST_F_RT_MAX is a max value and ST_F_RTIME is an average, an average of what?
/* compue time values for later use */
if (selected_field == NULL || *selected_field == ST_F_QTIME ||
*selected_field == ST_F_CTIME || *selected_field == ST_F_RTIME ||
*selected_field == ST_F_TTIME) {
srv_samples_counter = (px->mode == PR_MODE_HTTP) ? sv->counters.p.http.cum_req : sv->counters.cum_lbconn;
if (srv_samples_counter < TIME_STATS_SAMPLES && srv_samples_counter > 0)
srv_samples_window = srv_samples_counter;
}
TIME_STATS_SAMPLES value is defined as
#define TIME_STATS_SAMPLES 512
unsigned int srv_samples_window = TIME_STATS_SAMPLES;
In mode http srv_sample_counter is sv->counters.p.http.cum_req. http.cum_req is defined as ST_F_REQ_TOT.
[ST_F_REQ_TOT] = { .name = "req_tot", .desc = "Total number of HTTP requests processed by this object since the worker process started" },
For example if the value of http.cum_req is 10, then srv_sample_counter will be 10. The sample appears to be the number of successful requests for a given sample window for a given backends server. d_time (data time) is passed as "sum" and is computed as some non-negative value or it's counted as an error. I thought I found the code for how d_time is created but I wasn't sure so I haven't included it.
/* Returns the average sample value for the sum <sum> over a sliding window of
* <n> samples. Better if <n> is a power of two. It must be the same <n> as the
* one used above in all additions.
*/
static inline unsigned int swrate_avg(unsigned int sum, unsigned int n)
{
return (sum + n - 1) / n;
}

VBScript in IBM Personal Communications, Register current date and time

This is a bit complicated to explain but I sure will do my best!
I want to register the current time and date "Year,Week,day + Time", in my program IBM Personal Communications (Session A). I have to use a .MAC extension for the final file in order for the program to read it.
This is the code that I have at the moment:
[PCOMM SCRIPT HEADER]
LANGUAGE=VBSCRIPT
DESCRIPTION=
[PCOMM SCRIPT SOURCE]
OPTION EXPLICIT
autECLSession.SetConnectionByName(ThisSessionName)
REM This line calls the macro subroutine
subSub1_
sub subSub1_()
autECLSession.autECLOIA.WaitForAppAvailable
autECLSession.autECLOIA.WaitForInputReady
autECLSession.autECLPS.SendKeys "151441652 " **<--This is where the date has to appear**
autECLSession.autECLOIA.WaitForInputReady
autECLSession.autECLPS.SendKeys "[enter]"
autECLSession.autECLPS.WaitForAttrib 12,1,"00","3c",3,10000
autECLSession.autECLPS.Wait 3401
autECLSession.autECLOIA.WaitForAppAvailable
autECLSession.autECLOIA.WaitForInputReady
autECLSession.autECLPS.SendKeys "[pf12]"
end sub
autECLSession.autECLPS.SendKeys "151441652 " <--- The final values must appear here in the same order. The numbers have been entered manually by me. So what I essentially need the final program to do is to recognize the date and enter them manually.
This is what the numbers stand for:
15 = The year 2015
14 = The current week, the date right now is 02-04-2015 which is Week 14
4 = Day 4 of the week. thursday
1652 = Current time, I need the time to be a 24hour clock.
DatePart() can do all of this.
autECLSession.autECLPS.SendKeys _
Right(DatePart("yyyy", Now()), 2) & _
Right("0" & DatePart("ww", Now()), 2) & _
DatePart("w", Now()) & _
Right("0" & DatePart("h", Now()), 2) & _
Right("0" & DatePart("n", Now()), 2)
Take note of the optional FirstDayOfWeek and FirstWeekOfYear parameters, test your edge cases and set those parameters accordingly for the relevant calls.