When the RSI is Divergence, I want the position not to open until the certain candle time expires - pine-script-v5

In a Pine script,
I am running dca strategy within 1 minute time frame. When the RSI Deviation occurs in a different time frame (for example, 1 hour), I want the position not to be opened until the certain candle period ends (for example, 40 minutes). How can I do that
Thank you

You can do a manual check the time of the current candle in the different time frame and only open a position if the candle has completed.
timeFrame = 40m
timeRSIDeviation = 60m
timeFrame = time(timeFrame)
timeRSIDeviation = time(timeRSIDeviation)
currentTime = timestamp()
rsiDeviationOccurred = (currentTime > timeRSIDeviation)
if (rsiDeviationOccurred and currentTime == timeFrame)
strategy.entry("DCA", strategy.long)

Related

Fixing the Plot Shape signals on a highly profitable Pinescript strategy

I want to fix the attached pine script code in version 5 of Tradingview for a strategy I formed which is highly profitable but the signals for Buy, Sell, Exit Buy and Exit Sell are not occurring on the chart at the right points.
If someone can help me fix the attached code it would be great for even them as the strategy is highly profitable in trending markets and can be easily used to implement on a Trading Bot.
The strategy is as follows
I have 2 Exponential Moving Averages plotted on the chart, mainly EMA of 144 and EMA of 169. Once you plot these EMA's on the chart, they appear like a tunnel.
Buy Condition is - If the candle closes above both the EMA's, then a Buy Plot shape should occur on that candle.
Exit Buy Condition is - if the candle breaks the low of both the EMA's, even if not on a closing basis (even if the low of the candle is below both the EMA's), then a Exit Buy Plot shape should occur on that candle.
Sell Condition is - If the candle closes below both the EMA's, then a Sell Plot shape should occur on that candle.
Exit Sell Condition is - if the candle breaks the high of both the EMA's, even if not on a closing basis (even if the high of the candle is above both the EMA's), then a Exit Buy Plot shape should occur on that candle.
Also the most important aspect is that these shapes should not occur repeatedly. They should only occur on the specific candle when the condition is met.
I have attached the current pinescript code that I drafted but it isint working properly.
//#version=5
indicator("WavyCrorepati v2.0", overlay=true)
tunnel1 = ta.ema(close, 144)
tunnel2 = ta.ema(close, 169)
plot(tunnel1, color=color.white, linewidth=2)
plot(tunnel2, color=color.white, linewidth=2)
intradelong = 0
intradeshort = 0
// BUY
long = close > tunnel1 and close > tunnel2 or (ta.crossover(close,tunnel1) and ta.crossover(close,tunnel2))
if long
intradelong := 10
exitlong = low < tunnel2 and low < tunnel1
if exitlong
intradelong := 5
// SHORT
short = close < tunnel1 and close < tunnel2 or (ta.crossunder(close, tunnel1) and ta.crossunder(close, tunnel2))
if short
intradeshort := -10
exitshort = high > tunnel1 and high > tunnel2
if exitshort
intradeshort := -5
// PLOT SHAPES
plotshape(long and intradelong[1] == 5 , style=shape.labelup, color=color.green, location=location.belowbar, size=size.small,text="B",textcolor=color.white)
plotshape(exitlong and long[1], style=shape.diamond,color=color.white,location=location.belowbar,size=size.tiny)
plotshape(short and intradeshort[1] == -5 , style=shape.labeldown, color=color.red, location=location.abovebar, size=size.small,text="S",textcolor=color.yellow)
plotshape(exitshort and short[1], style=shape.diamond,color=color.yellow, location=location.abovebar,size=size.tiny)
plot(intradelong, color = color.green, display = display.status_line)
plot(intradeshort, color = color.red, display = display.status_line)

offset in atr in tradingview - pine script

Need to have offset in ATR function in pine script
Background: The indicator script below is based on the hypothesis that this period's range will be mostly within [last period high + atr(14)] and [last period low - atr(14)]. I want to sell the high call option and low put option and enjoy the premium at the end of the period (week, month).
I have created a pine script that will calculate this period range based on [last period high + atr(14)] and [last period low - atr(14)].
However, because atr(14) applies to current period as well, it plots the dots that change with the current price.
I need to have an atr(14) days till the last period and not considering this current period. Could you please advise how to achieve that.
//#version=3
study(title="High and Low Levels", shorttitle="HL Levels", overlay = true)
Width = input(2, minval=1)
SelectPeriod = input("W", defval="W", type=string)
LookBack = input(1, minval=1)
xHigh = high[LookBack]
xHigh := xHigh + (atr(14))
xLow = low[LookBack] - atr(14)
vS1 = xHigh
vR1 = xLow
plot(vS1, color=#ff0000, title="S1", style = circles, linewidth = Width)
plot(vR1, color=#009600, title="R1", style = circles, linewidth = Width)
Expected: the dots plotted should be plotted based on last period high + last period atr(14) and last period low - last period atr(14)
Actual: the dots plotted based on last week high + atr(14) till the current period and last week low - atr(14) till the current period. This is changing the dots based on the current price movement.
Maybe, I got it wrong, but I think what you want is to take the previous value of atr(14). So it looks like that:
xLow = low[LookBack] - atr(14)[1]
I think, you've got my idea.
This should help....
plot(vS1[1], color=#ff0000, title="S1", style = circles, linewidth = Width)
plot(vR1[1], color=#009600, title="R1", style = circles, linewidth = Width)

STM32 HAL Nucleo F446RE Quadrature Encoder

I have a problem with the quadrature encoder mode on timer TIM3 of my
STM32F446RE /
NUCLEO-F446RE:
TIM3 counts on every rising edge on the first signal.
The CNT register counts up and I read the value with 1 Hz and then
I set the register to 0.
When I look on the
oscilloscope
the frequency is half as high as the value from the
CNT register output (1hz).
Why?
TIM3 counts on both edges on the first signal.
The
CNT register output (1 Hz)
is completely wrong.
My configuration is:
GPIO_InitTypeDef sInitEncoderPin1;
sInitEncoderPin1.Pin = pin1Encoder.pin; // A GPIO_PIN_6
sInitEncoderPin1.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin1.Pull = GPIO_PULLUP;
sInitEncoderPin1.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin1.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
GPIO_InitTypeDef sInitEncoderPin2;
sInitEncoderPin2.Pin = pin2Encoder.pin; // A GPIO_PIN_7
sInitEncoderPin2.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin2.Pull = GPIO_PULLUP;
sInitEncoderPin2.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin2.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
HAL_GPIO_Init(GPIOA, &sInitEncoderPin1);
HAL_GPIO_Init(GPIOA, &sInitEncoderPin2);
encoderTimer.Init.Period = 0xffff;
encoderTimer.Init.Prescaler = 0;
encoderTimer.Init.CounterMode = TIM_COUNTERMODE_UP;
encoderTimer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
encoderTimer.Init.RepetitionCounter = 0;
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 1);
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
encoder.IC1Filter = 0x0f;
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; // TIM_INPUTCHANNELPOLARITY_BOTHEDGE
encoder.IC1Prescaler = TIM_ICPSC_DIV1;
encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
encoder.IC2Filter = 0x0f;
encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
encoder.IC2Prescaler = TIM_ICPSC_DIV1;
encoder.IC2Selection = TIM_ICSELECTION_DIRECTTI;
HAL_TIM_Encoder_Init(&encoderTimer, &encoder);
HAL_TIM_Encoder_Start_IT(&encoderTimer, TIM_CHANNEL_ALL);
The
oscilloscope screenshot
shows a frequency of about 416 Hz.
The values shown in the
first shell output
are (very roughly!) twice as high (as the question points out already).
This appears (nearly...) correct to me since the shown configuration
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
selects the "X2 resolution encoder mode", which counts 2 CNT increments per signal period.
In an application note on
timer overview,
(Sec. 4.3.4 / Fig. 7) there is an illustrative diagram how the encoder mode works in detail.
The
second screenshot
results from an incorrect TIM3 configuration:
The encoder mode (TIM_ENCODERMODE_TI1) assumes that both channels trigger only upon directed flanks in an alternating way (see the AN link above).
If one of the two channels triggers twice as many events due to
configuration
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE,
the counter will only count up one position and then "recognize" a "reversal" event (= change of direction).
Keeping in mind that
65535u = 0xFFFF = -1
the second screenshot only shows values -1, 0, +1 - which fits perfectly with this explanation.
The question remains why the first screenshot shows (reproducible) measurements between 800 and 822.
I assume that
the physical source of the encoder signal runs at a constant pace
the 1 Hz timer that triggered shell output is independent from TIM3, and
it has been started before the encoder timer
(i.e., above the shown code sample).
This may explain why the first two values look like nonsense (0: TIM3 has not been started yet. 545: TIM3 has been started during the shell output timer period).
Discarding the first two measurement samples, the average and standard deviation, resp., of the measured signal frequency are
808,9091 +/- 0,5950 [X2 increments per second]
404,4545 +/- 0,2975 [Hz]
which corresponds to a period of
2,4331 +/- 0,003 [ms].
Hence, the measured frequency is too low by about 11 Hz, i.e., measured period too high by nearly 30 µs, and this error is clearly beyond the statistical noise.
The question gives a hint where this error might come from:
The CNT register counts up and I read the value with 1 Hz and then I set the register to 0.
Whenever the 1 Hz "polling timer" expires, it triggers an interrupt
(or a logical event in polling software).
Processing of this interrupt/event may be delayed a little,
depending on other software (IRQ: deactivation times elsewhere in the software,
Polling: loop duration until event is polled).
Software reads CNT value.
Software resets CNT value to zero,
discarding further increments since the CNT value has been read.
TIM3 continues counting (from zero).
This hints that software needs 30 µs between (3.) and (4.), which would be quite a lot of time on an STM32F4.
Edit: I just re-checked the oscilloscope screenshot. The error is visible, but I believe it is smaller than I originally assumed (from counting flanks in the picture).

Flicker frequencies in PTB

I'm trying to present a 4Hz flickering stimuli in PsychToolbox for 5 seconds followed by a 500Hz tone. Does anyone have an idea of how to do this? I've been using the vbl or screen refresh rate to calculate the flicker frequency but I'm not sure if I'm on the right track at all. I also have no idea how to present an auditory stimuli in PTB (I tried the sound function already). Any help is greatly appreciated!
I'm not sure about sound presentation in PTB (I've never done it), but you seem to be on the right track for the flicker frequency.
The way I do it is to determine the screen refresh rate, divide the total length of time you want the stimulus presented by this refresh rate (this will give you the number of frames that will be drawn during this time), and then have a frame counter that increases by 1 after every flip. You can then use this frame counter to switch commands on or off.
A minimal example (randomly changes the background colour at 4Hz for 5 seconds):
[w, wRect]=Screen('OpenWindow', 0);
MaxTime = 5; %Set maximum time for all stimuli to be presented in seconds
Hz = 4; %Set Hz for stimulus flicker
Screen('Flip',w);
Frametime=Screen('GetFlipInterval',w); %Find refresh rate in seconds
FramesPerFull = round(5/Frametime); % Number of frames for all stimuli
FramesPerStim = round((1/Hz)/Frametime); %Number of frames for each stimulus
StartT = GetSecs; %Measure start time of session
Framecounter = 0; %Frame counter begins at 0
while 1
if Framecounter==FramesPerFull
break; %End session
end
if ~mod(Framecounter,FramesPerStim)
randomcolour = rand(1, 3)*255; %Change background stimulus colour
end
Screen('FillRect', w, randomcolour, wRect);
Screen('Flip',w);
Framecounter = Framecounter + 1; %Increase frame counter
end
EndT = GetSecs; %Measure end time of session
Screen('CloseAll');
EndT - StartT %Shows full length of time all stimuli were presented
The timing precision will depend on your particular refresh rate.
Hope this helps!

Calculate Pace To String

I am trying to calculate pace (min/mi) and format it as mmmm:ss.
So far I calculate my pace into a float by taking 60 and dividing it by my average speed. At an average speed of 76mph, my average pace is displayed as 0.79. I want to format it so that it converts my 0.79 minutes to mmmm:ss (thus showing my average pace as 0000:47). How can I do this?
double milesPerHour = 76.0;
int secondsPerMile = (int)round(3600.0 / milesPerHour);
NSString *paceString = [NSString stringWithFormat:#"%04d:%02d", secondsPerMile / 60, secondsPerMile % 60];
Not sure if I get your question right, but this is pretty much just math.
You can get the minutes by rounding your value (0.79 in this case) down and you can get seconds by taking your value, subtracting the minutes from it and multiplying that by 60.
So if you'd need 2.35 minutes for a mile, you'd have 2 minutes and 0.35*60 = 21 seconds.