'variable name' is already defined - pine-script-v5

When I save the following code I get a compile error on the last line. The error is "trend' is already declared.
// Data row AUDCAD
tclose = request.security("AUDCAD", "60", close)
thigh = request.security("AUDCAD", "60", high)
tlow = request.security("AUDCAD", "60", low)
[trend,barcount] = request.security("AUDCAD", timeframe.period,calc_trend(tclose,thigh,tlow))
<< Do some stuff here >>
tclose = request.security("AUDCHF", "60", close)
thigh = request.security("AUDCHF", "60", high)
tlow = request.security("AUDCHF", "60", low)
[trend,barcount] = request.security("AUDCHF", timeframe.period,calc_trend(tclose,thigh,tlow))
When I changed the '=' to ':='I get the message "'trend' is already defined" on the last row. Are these declaration errors able to be resolved? If so, could someone please point me in the right direction.
// Data row AUDCAD
tclose = request.security("AUDCAD", "60", close)
thigh = request.security("AUDCAD", "60", high)
tlow = request.security("AUDCAD", "60", low)
[trend,barcount] = request.security("AUDCAD", timeframe.period,calc_trend(tclose,thigh,tlow))
<< Do some stuff here >>
tclose = request.security("AUDCHF", "60", close)
thigh = request.security("AUDCHF", "60", high)
tlow = request.security("AUDCHF", "60", low)
[trend,barcount] := request.security("AUDCHF", timeframe.period,calc_trend(tclose,thigh,tlow))

Related

Compilation error. Line 10: Extraneous input ':' expecting 'end of line without line continuation'

I keep getting compilation errors, I am new to pinescript and cant figure out where I am going wrong.
//#version=5
// Define the RSI period
period = 14
// Calculate the RSI
rsi = rsi(close, period)
// Check for bullish divergence
if (rsi < 30) and (rsi < rsi[1]) and (close > close[1]):
# Bullish divergence detected, go long
strategy.entry("Long", long=true)
strategy.exit("Exit long", "Long", profit=50, stop=-50)
// Check for bearish divergence
if (rsi > 70) and (rsi > rsi[1]) and (close < close[1]):
# Bearish divergence detected, go short
strategy.entry("Short", short=true)
strategy.exit("Exit short", "Short", profit=50, stop=-50)
You error comes from the indentation of your 'if' block.
Change you indentation and your code to :
//#version=5
// Define the RSI period
period = 14
rsi = ta.rsi(close, period)
// Check for bullish divergence
if (rsi < 30) and (rsi < rsi[1]) and (close > close[1])
// Bullish divergence detected, go long
strategy.entry("Long", strategy.long)
strategy.exit("Exit long", "Long", profit=50, stop=-50)
// Check for bearish divergence
if (rsi > 70) and (rsi > rsi[1]) and (close < close[1])
// Bearish divergence detected, go short
strategy.entry("Short", strategy.short)
strategy.exit("Exit short", "Short", profit=50, stop=-50)

Setting A Multiple Ticker Alert On Barstate.islast in Pine Script

Good Day! I am trying to emulate a script I created that provides alerts on multiple tickers for the various conditions I have set up. This works as it should and have been happy with it. Although it is not pretty, it is the first section of code posted below. The end of the code is where I input the action_alerts for the multiple tickers.
The new code I am trying to create deals with a label that shows if the relative strength reach a new high over a 28 day span. I am looking to create an alert of that new high on the same tickers as the first code to tell me once that new high is reached. That is the second code below. I also added a picture showing that label.new is a tiny green circle every time the new high is reached.
Any help with this will be greatly appreciated!
First Code (working)
indicator('Daily Screener #1', overlay=true)
//Backtest start date with inputs
startDate = input.int(title='Start Date', defval=1, minval=1, maxval=31)
startMonth = input.int(title='Start Month', defval=5, minval=1, maxval=12)
startYear = input.int(title='Start Year', defval=2021, minval=2000, maxval=2100)
//See if the bar's time happened on/after start date
afterStartDate = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)
//Inputs
ts_bars = input.int(10, minval=1, title='Tenkan-Sen Bars')
ks_bars = input.int(20, minval=1, title='Kijun-Sen Bars')
ssb_bars = input.int(50, minval=1, title='Senkou-Span B Bars')
sma_bars = input.int(50, minval=1, title='SMA Bars')
sec_sma_bars = input.int(5, minval=1, title='Second SMA Bars')
cs_offset = input.int(20, minval=1, title='Chikou-Span Offset')
ss_offset = input.int(20, minval=1, title='Senkou-Span Offset')
long_entry = input(true, title='Long Entry')
short_entry = input(true, title='Short Entry')
wait_for_cloud = input(true, title='Wait for Cloud Confirmation')
//values
avgvalue = input(defval=20, title='Avg Vol Period')
avgvolfac = input(defval=2, title='Rvol Factor')
maxvol = input(defval=5, title='Max Vol')
minvol = input(defval=10000, title='Required Min Vol')
color bo = color.white
color suy = color.black
avgvola = ta.sma(volume, avgvalue)
volcheck = volume > avgvola * avgvolfac and volume > minvol and volume > volume[1] * .75
maxvolcheck = volume > avgvola * maxvol and volume > minvol and volume > volume[1] * .75
// RSI Inputs
use_rsi_tp = input(false, title='Use RSI for Take Profit')
use_rsi_entry = input(false, title='Use RSI for Entry')
seq_rsi = input(defval=1, title='Alert TP after X Sequential bars past RSI')
rsi_period = input(defval=7, title='RSI Period')
overbought_rsi = input(defval=80, title='RSI Overbought Level')
oversold_rsi = input(defval=20, title='RSI Oversold Level')
middle(len) =>
ta.sma(close, len)
//Stoch RSI Inputs
smoothK = input.int(3, 'K', minval=1)
smoothD = input.int(3, 'D', minval=1)
lengthRSI = input.int(14, 'RSI Length', minval=1)
lengthStoch = input.int(14, 'Stochastic Length', minval=1)
src = input(close, title='RSI Source')
//Stoch RSI Components
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
//MACD Inputs
fast_length = input(title='Fast Length', defval=12)
slow_length = input(title='Slow Length', defval=26)
src2 = input(title='Source', defval=close)
signal_length = input.int(title='Signal Smoothing', minval=1, maxval=50, defval=9)
sma_source = input(title='Simple MA (Oscillator)', defval=false)
sma_signal = input(title='Simple MA (Signal Line)', defval=false)
//MACD Components
fast_ma = sma_source ? ta.sma(src2, fast_length) : ta.ema(src2, fast_length)
slow_ma = sma_source ? ta.sma(src2, slow_length) : ta.ema(src2, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
// Ichimoku Components
tenkan = middle(ts_bars)
kijun = middle(ks_bars)
mid_sma = middle(sma_bars)
sec_sma = middle(sec_sma_bars)
senkouA = math.avg(tenkan, kijun)
senkouB = middle(ssb_bars)
// Plot Ichimoku Kinko Hyo
plot(tenkan, color=color.new(#0496ff, 0), title='Tenkan-Sen')
plot(kijun, color=color.new(#991515, 0), title='Kijun-Sen')
plot(mid_sma, color=color.new(color.white, 0), title='50 SMA')
plot(sec_sma, color=color.new(color.orange, 0), title='5 SMA')
plot(close, offset=-cs_offset + 1, color=color.new(color.gray, 0), title='Chikou-Span')
sa = plot(senkouA, offset=ss_offset - 1, color=color.new(color.green, 0), title='Senkou-Span A')
sb = plot(senkouB, offset=ss_offset - 1, color=color.new(color.red, 0), title='Senkou-Span B')
fill(sa, sb, color=senkouA > senkouB ? color.green : color.red, title='Cloud color', transp=90)
ss_high = math.max(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
// Entry/Exit Signals
tk_cross_bull = tenkan > kijun
tk_cross_bear = tenkan < kijun
cs_cross_bull = ta.mom(close, cs_offset - 1) > 0
cs_cross_bear = ta.mom(close, cs_offset - 1) < 0
price_above_kumo = close > ss_high
price_below_kumo = close < ss_low
price_between_kumo = close < ss_high and close > ss_low
senkou_green = senkouA > senkouB ? true : false
rsi_value = ta.rsi(close, rsi_period)
trend_midentry_T = close < tenkan or open < tenkan
trend_midentry_K = close > kijun or open > kijun
pp_t = close > tenkan or open > tenkan
pp_k = close < kijun or open < kijun
open_trend_reentry_T = open < tenkan
open_trend_reentry_K = open > kijun
close_trend_reentry_T = close < tenkan
close_trend_reentry_K = close > kijun
kumo_open_trend_reentry_T = open > tenkan
kumo_open_trend_reentry_K = open < kijun
kumo_close_trend_reentry_T = close > tenkan
kumo_close_trend_reentry_K = close < kijun
rsi_positive = k > d
rsi_negative = d > k
rsi_cross = ta.crossover(k, d)
macd_positive = macd > signal and macd > 0
macd_exit = ta.crossover(signal, macd)
macd_entry = ta.crossover(macd, signal)
hist_positive = hist >= 0
higherOrSameClose = close >= close[1]
two_day_higherOrSameClose = close >= close[1] and close[1] >= close[2]
five_day_lowerOrSameClose = close < close[7]
macd_greater_zero = fast_ma > 0
first_exit = ta.crossover(tenkan, close)
avgVol = ta.ema(volume, 50)
support = ta.lowest(close, 25)
five_ten_cross = ta.crossunder(sec_sma, tenkan)
bullish = tk_cross_bull and cs_cross_bull and price_above_kumo
bearish = tk_cross_bear and cs_cross_bear and price_below_kumo
if wait_for_cloud
bullish := bullish and senkou_green
bearish := bearish and not senkou_green
bearish
if use_rsi_entry
bullish := bullish and rsi_value < overbought_rsi
bearish := bearish and rsi_value > oversold_rsi
bearish
in_long = false
in_long := in_long[1]
open_long = bullish and long_entry and not in_long
open_short = bearish and short_entry and in_long
ish_long_entry = tk_cross_bull and cs_cross_bull and price_below_kumo
ish_2nd_long_entry = price_above_kumo and trend_midentry_T and trend_midentry_K
ish_sell_in_trend = price_above_kumo and ta.crossunder(tenkan, kijun)
ish_buy_in_trend = price_above_kumo and ta.crossover(tenkan, kijun) and higherOrSameClose
early_exit_bear = price_below_kumo and ta.crossunder(tenkan, kijun) or first_exit and price_below_kumo
best_entry = rsi_positive and macd_positive and ish_long_entry or ish_buy_in_trend and rsi_positive and macd_positive
best_exit = macd_exit and rsi_negative and ish_2nd_long_entry or first_exit and price_above_kumo
trend_reentry = price_above_kumo and (open_trend_reentry_T or close_trend_reentry_T) and (open_trend_reentry_K or close_trend_reentry_K) and rsi_positive and higherOrSameClose and macd_entry
in_kumo_trend_reentry = price_between_kumo and (kumo_open_trend_reentry_T or kumo_close_trend_reentry_T) and (kumo_open_trend_reentry_K or kumo_close_trend_reentry_K) and rsi_positive and higherOrSameClose and macd_entry
better_entry = price_above_kumo and rsi_cross and macd_greater_zero and higherOrSameClose
in_kumo_trend_reentry1 = price_between_kumo and kumo_open_trend_reentry_T and kumo_open_trend_reentry_K and rsi_positive and higherOrSameClose and macd_entry
in_kumo_trend_reentry2 = price_between_kumo and kumo_close_trend_reentry_T and kumo_close_trend_reentry_K and rsi_positive and higherOrSameClose and macd_entry
better_entry_pos = price_above_kumo and rsi_cross and macd_positive and higherOrSameClose
pre_party = price_below_kumo and (trend_midentry_T and trend_midentry_K or pp_t and pp_k) and two_day_higherOrSameClose and not five_day_lowerOrSameClose and cs_cross_bull
test = cs_cross_bull and price_below_kumo and two_day_higherOrSameClose
trend_breakout_close = not price_below_kumo and ta.crossover(close, tenkan) and rsi_positive and close > open[3]
quick_test = not price_above_kumo and close > tenkan and rsi_positive and higherOrSameClose and close[1] > close[2] and close > close[1] * 1.05
//reversal = price_below_kumo and close > close[1] and close[1] > close[2] and close > support and macd_entry
sell_off = open_short or ish_sell_in_trend
buy_up = open_long or (trend_breakout_close and ish_buy_in_trend) or (better_entry_pos and trend_breakout_close) or (trend_reentry and trend_breakout_close) or (trend_reentry and better_entry_pos) or (in_kumo_trend_reentry and trend_breakout_close) or (pre_party and test) or (quick_test and test)
sell_all = sell_off and volcheck
buy_all = buy_up and volcheck
voliskey = higherOrSameClose and maxvolcheck
all_volcheck = higherOrSameClose and volcheck and open>mid_sma
fifty_bo = trend_breakout_close and volcheck and ta.crossover(close,mid_sma)
show_me = ((ta.crossover(close,tenkan) and ta.crossover(close,kijun)) or (ta.crossover(close,sec_sma) and ta.crossover(close,tenkan))) and close<mid_sma and sec_sma>=tenkan*.99 and (volume > avgvola*.5)
bull_trend = price_above_kumo and close > sec_sma and tenkan>sec_sma and sec_sma>kijun and close>close[1] and close[1] >close[2]
chikcross = ta.crossover(close,mid_sma[20]) and open>mid_sma
ten_chikcross = ta.crossover(close,tenkan[20]) and volume > (avgvola * .75)
upside = low<low[1] and close>close[1] and ((close-low)/(high-low))>.55 and volume>avgvola*1.33 and sec_sma>tenkan
grab_it = voliskey
dump_it = sell_all
ybbo = (trend_breakout_close and better_entry_pos)
olretrace = (open_long and ish_buy_in_trend)
hvretrace = (volcheck and ish_buy_in_trend)
earbuy = quick_test
below_earbuy = (quick_test and test)
sbreak= fifty_bo
ebreak = (trend_breakout_close and quick_test)
olyb = better_entry_pos
if open_long
in_long := true
in_long
if open_short
in_long := false
in_long
rsi_count = 0
arm_tp = false
if use_rsi_tp
rsi_count := rsi_count[1]
if in_long and rsi_value > overbought_rsi or not in_long and rsi_value < oversold_rsi
rsi_count += 1
rsi_count
else
rsi_count := 0
rsi_count
if rsi_count >= seq_rsi
arm_tp := true
arm_tp
//Function Definition
action_alert(_ticker) =>
agrab_it = voliskey
adump_it = sell_all
aybbo = better_entry_pos
aearbuy = quick_test
asbreak= fifty_bo
awatch = show_me
[_grab_it, _ybbo, _earbuy, _sbreak, good_vol, _watch, _bull_trend,_ten_chikcross, _upside] = request.security(_ticker, timeframe.period, [ agrab_it, aybbo, aearbuy, asbreak, all_volcheck, awatch, bull_trend,ten_chikcross, upside])
_msg = _ticker + ',' + timeframe.period + ': '
if _grab_it
_msg += 'Big Volume Buy'
alert(_msg, alert.freq_once_per_bar)
if _ybbo
_msg += 'Yellow Buy'
alert(_msg, alert.freq_once_per_bar_close)
if _earbuy
_msg += 'Early Buy'
alert(_msg, alert.freq_once_per_bar_close)
if _sbreak
_msg += 'Super Breakout'
alert(_msg, alert.freq_once_per_bar_close)
if _bull_trend
_msg += 'Trend'
alert(_msg, alert.freq_once_per_bar_close)
if good_vol
_msg += 'Good Vol'
alert(_msg, alert.freq_once_per_bar_close)
if chikcross
_msg += 'Chikou Cross'
alert(_msg, alert.freq_once_per_bar_close)
if _ten_chikcross
_msg += '10 Chikou Cross'
alert(_msg, alert.freq_once_per_bar_close)
if _upside
_msg += 'Upside Reversal'
alert(_msg, alert.freq_once_per_bar_close)
barcolor(sell_all ? bo : na, editable=false)
barcolor(buy_all ? suy : na, editable=false)
barcolor(voliskey ? color.yellow : na, editable=false)
barcolor(all_volcheck ? suy : na, editable=false)
//Alert Plots
plotshape(open_short, text='Open Short', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.red, 0))
plotshape(better_entry_pos, text='Buy', style=shape.arrowup, location=location.belowbar, color=color.new(#FFC803, 0), textcolor=color.new(#FFC803, 0))
plotshape(bull_trend, text='Trend', style=shape.arrowup, location=location.belowbar, color=color.new(#00BFFF, 0), textcolor=color.new(#00BFFF, 0))
plotshape(quick_test, text='Early Buy', style=shape.arrowup, location=location.belowbar, color=color.new(color.orange, 0), textcolor=color.new(color.orange, 0))
plotshape(chikcross, text='Chikou Cross', style=shape.arrowup, location=location.belowbar, color=color.new(#00FFFF, 0), textcolor=color.new(#00FFFF, 0))
plotshape(voliskey, text= "Big Vol", style=shape.arrowup, location=location.belowbar, color=color.new(color.yellow, 0), textcolor=color.new(color.yellow, 0))
plotshape(fifty_bo, text= "Super Breakot", style=shape.arrowup, location=location.belowbar, color=color.new(color.white, 0), textcolor=color.new(color.white, 0))
plotshape(ybbo, text='Good Buy Breakout', style=shape.arrowup, location=location.belowbar, color=color.new(#66FF00, 0), textcolor=color.new(#66FF00, 0))
plotshape(all_volcheck, text='Good Volume', style=shape.arrowup, location=location.belowbar, color=color.new(color.lime, 0), textcolor=color.new(color.lime, 0))
plotshape(hvretrace, text="Retrace", style=shape.arrowup, location=location.belowbar, color=color.new(color.aqua, 0), textcolor=color.new(color.aqua, 0))
plotshape(ten_chikcross, text='10 Chikou Cross', style=shape.arrowup, location=location.belowbar, color=color.new(#00BFFF, 0), textcolor=color.new(#00BFFF, 0))
plotshape(upside, text='Upside Reversal', style=shape.arrowup, location=location.belowbar, color=color.new(#C3CDE6, 0), textcolor=color.new(#C3CDE6, 0))
//Position Alert
action_alert("AMEX:DRIP")
action_alert("AMEX:DUG")
action_alert("AMEX:EQX")
action_alert("AMEX:ERY")
action_alert("AMEX:NGD")
action_alert("AMEX:TZA")
Second Code (not working)
//#version=5
indicator("Ish's Relative Strength")
length = 20
five_sma=ta.sma(close,5)
var prevRatio = 0.0
//Save each ratio so we can look for RS line new high
var array=array.new_float(0)
// RS - IBD
ThreeMonthRS = 0.4 * (close / close[13])
SixMonthRS = 0.2 * (close / (close[26] * 2))
NineMonthRS = 0.2 * (close / (close[39] * 3))
TwelveMonthRS = 0.2 * (close / (close[52] * 4))
RatingRS = (ThreeMonthRS + SixMonthRS + NineMonthRS + TwelveMonthRS) * 100
rsText = "RS Rating \n" + str.tostring(RatingRS, "0.00")
//Gather Compared Index/Stock
comparedSymbol = input.symbol(title="Benchmark RS Line", defval="QQQ", group="Relative Strength")
comparedClose = request.security(comparedSymbol, timeframe.period, close)
cThreeMonthRS = 0.4 * (comparedClose / comparedClose[13])
cSixMonthRS = 0.2 * (comparedClose / (comparedClose[26] * 2))
cNineMonthRS = 0.2 * (comparedClose / (comparedClose[39] * 3))
cTwelveMonthRS = 0.2 * (comparedClose / (comparedClose[52] * 4))
cRatingRS = (cThreeMonthRS + cSixMonthRS + cNineMonthRS + cTwelveMonthRS) * 100
crsText = "Comp RS \n" + str.tostring(cRatingRS, "0.00")
compratio = "RS Ratio \n" + str.tostring(RatingRS/cRatingRS, "0.00")
compratioNUM = RatingRS/cRatingRS
posslope= (compratioNUM-compratioNUM[2])/2
posfive=five_sma-five_sma[1]
slope=ta.sma(compratioNUM,5)
getin=ta.crossover(compratioNUM,slope) and posslope>0 and posfive>0
//Color of line to show up or down
ColorUp = color.new(color.green,0)
ColorDown = color.new(color.red,0)
linecolor = (posslope>.02 and posfive>.02)? ColorUp: ColorDown
//plot(RatingRS, color=color.new(color.white, 0), title='50 SMA')
//plot(cRatingRS, color=color.new(color.white, 0), title='Test')
plot(compratioNUM, color=linecolor, linewidth=2, title="Got It")
//plot(slope, color=color.new(color.lime,0),title="Please Work")
//plotshape(getin, title="Get In", style=shape.arrowup, location=location.belowbar, color=color.new(#C3CDE6,0), textcolor=color.new(#C3CDE6,0))
//Show high dot based on time
if (barstate.islast)
newHigh=true
for i=0 to 27
if(array.get(array, i)>compratioNUM)
newHigh:=false
break
if (newHigh)
label.new(bar_index, compratioNUM, color=color.new(color.green,40), style=label.style_circle, size=size.tiny)
if (barstate.islast)
newLow=true
for i=0 to 27
if(array.get(array, i)<compratioNUM)
newLow:=false
break
if (newLow)
label.new(bar_index, compratioNUM, color=color.new(color.red, 40), style=label.style_circle, size=size.tiny)
prevRatio:=compratioNUM
array.unshift(array, compratioNUM)
action_alert(_ticker) =>
test= newHigh
[_test] = request.security(_ticker, timeframe.period, [newHigh])
_msg = _ticker + ',' + timeframe.period + ': '
if _test
_msg += 'New High'
alert(_msg, alert.freq_once_per_bar)
//Position Alert
action_alert("AMEX:DRIP")
action_alert("AMEX:DUG")
action_alert("AMEX:EQX")
action_alert("AMEX:ERY")
action_alert("AMEX:NGD")
action_alert("AMEX:TZA")
Green dot showing new high value of relative strength reached over the last 28 days

Pine Script V5, How can i DELAY 5 seconds for my LONG & SHORT Entry?

I want to delay 5 seconds for my LONG & SHORT entries.
for example,
if the "longCondition" is true at 12:00:00, I want to execute LONG entry at 12:00:05
the same for Short entry: if the "shortCondition" is true at 12:00:00, I want to execute SHORT entry at 12:00:05
Can anyone help me, please?
//#version=5
strategy('My Strategy', overlay=true)
// Indicators
shortSMA = ta.sma(close, 10)
longSMA = ta.sma(close, 30)
rsi = ta.rsi(close, 14)
// Conditions
longCondition = ta.crossover(shortSMA, longSMA) and (rsi > 50)
shortCondition = ta.crossunder(shortSMA, longSMA) and (rsi < 50)
/// LONG
strategy.entry("long", strategy.long, when=longCondition, comment="Entry Long") //## How can i delay 5 seconds for this entry ???
strategy.close("long", when=shortCondition, comment = "Exit Long")
/// SHORT
strategy.entry("short", strategy.short, when = shortCondition, comment="Entry Short") //## How can i delay 5 seconds for this entry ???
strategy.close("short", when=longCondition, comment="Exit Short")

Raspberry pi pico rfid rc522 (Micropython)

I want to read data from mfrc522 (Iduino RFID-rc522) card reader using my RPi Pico but I don't know how to. I was trying to use mfrc522.py MicroPython library made for this purpose. Reader is communicating with Pi over SPI and I connected it to SPI0.
Code on pi:
import time
from machine import I2C, Pin, SPI
from mfrc522 import MFRC522
sck = Pin(6, Pin.OUT)
mosi = Pin(7, Pin.OUT)
miso = Pin(4, Pin.OUT)
spi = SPI(0, baudrate=100000, polarity=0, phase=0, sck=sck, mosi=mosi, miso=miso)
sda = Pin(5, Pin.OUT)
rst = Pin(22, Pin.OUT)
while True:
rdr = MFRC522(spi, sda, rst)
uid = ""
(stat, tag_type) = rdr.request(rdr.REQIDL)
if stat == rdr.OK:
(stat, raw_uid) = rdr.anticoll()
if stat == rdr.OK:
uid = ("0x%02x%02x%02x%02x" % (raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3]))
print(uid)
And Library:
from machine import Pin, SPI
from os import uname
class MFRC522:
OK = 0
NOTAGERR = 1
ERR = 2
REQIDL = 0x26
REQALL = 0x52
AUTHENT1A = 0x60
AUTHENT1B = 0x61
def __init__(self, spi, cs, rst):
self.spi = spi
self.cs = cs
self.rst = rst
self.rst.value(0)
self.cs.value(1)
self.spi.init()
self.rst.value(1)
self.init()
def _wreg(self, reg, val):
self.cs.value(0)
self.spi.write(b'%c' % int(0xff & ((reg << 1) & 0x7e)))
self.spi.write(b'%c' % int(0xff & val))
self.cs.value(1)
def _rreg(self, reg):
self.cs.value(0)
self.spi.write(b'%c' % int(0xff & (((reg << 1) & 0x7e) | 0x80)))
val = self.spi.read(1)
self.cs.value(1)
return val[0]
def _sflags(self, reg, mask):
self._wreg(reg, self._rreg(reg) | mask)
def _cflags(self, reg, mask):
self._wreg(reg, self._rreg(reg) & (~mask))
def _tocard(self, cmd, send):
recv = []
bits = irq_en = wait_irq = n = 0
stat = self.ERR
if cmd == 0x0E:
irq_en = 0x12
wait_irq = 0x10
elif cmd == 0x0C:
irq_en = 0x77
wait_irq = 0x30
self._wreg(0x02, irq_en | 0x80)
self._cflags(0x04, 0x80)
self._sflags(0x0A, 0x80)
self._wreg(0x01, 0x00)
for c in send:
self._wreg(0x09, c)
self._wreg(0x01, cmd)
if cmd == 0x0C:
self._sflags(0x0D, 0x80)
i = 2000
while True:
n = self._rreg(0x04)
i -= 1
if ~((i != 0) and ~(n & 0x01) and ~(n & wait_irq)):
break
self._cflags(0x0D, 0x80)
if i:
if (self._rreg(0x06) & 0x1B) == 0x00:
stat = self.OK
if n & irq_en & 0x01:
stat = self.NOTAGERR
elif cmd == 0x0C:
n = self._rreg(0x0A)
lbits = self._rreg(0x0C) & 0x07
if lbits != 0:
bits = (n - 1) * 8 + lbits
else:
bits = n * 8
if n == 0:
n = 1
elif n > 16:
n = 16
for _ in range(n):
recv.append(self._rreg(0x09))
else:
stat = self.ERR
return stat, recv, bits
def _crc(self, data):
self._cflags(0x05, 0x04)
self._sflags(0x0A, 0x80)
for c in data:
self._wreg(0x09, c)
self._wreg(0x01, 0x03)
i = 0xFF
while True:
n = self._rreg(0x05)
i -= 1
if not ((i != 0) and not (n & 0x04)):
break
return [self._rreg(0x22), self._rreg(0x21)]
def init(self):
self.reset()
self._wreg(0x2A, 0x8D)
self._wreg(0x2B, 0x3E)
self._wreg(0x2D, 30)
self._wreg(0x2C, 0)
self._wreg(0x15, 0x40)
self._wreg(0x11, 0x3D)
self.antenna_on()
def reset(self):
self._wreg(0x01, 0x0F)
def antenna_on(self, on=True):
if on and ~(self._rreg(0x14) & 0x03):
self._sflags(0x14, 0x03)
else:
self._cflags(0x14, 0x03)
def request(self, mode):
self._wreg(0x0D, 0x07)
(stat, recv, bits) = self._tocard(0x0C, [mode])
if (stat != self.OK) | (bits != 0x10):
stat = self.ERR
return stat, bits
def anticoll(self):
ser_chk = 0
ser = [0x93, 0x20]
self._wreg(0x0D, 0x00)
(stat, recv, bits) = self._tocard(0x0C, ser)
if stat == self.OK:
if len(recv) == 5:
for i in range(4):
ser_chk = ser_chk ^ recv[i]
if ser_chk != recv[4]:
stat = self.ERR
else:
stat = self.ERR
return stat, recv
def select_tag(self, ser):
buf = [0x93, 0x70] + ser[:5]
buf += self._crc(buf)
(stat, recv, bits) = self._tocard(0x0C, buf)
return self.OK if (stat == self.OK) and (bits == 0x18) else self.ERR
def auth(self, mode, addr, sect, ser):
return self._tocard(0x0E, [mode, addr] + sect + ser[:4])[0]
def stop_crypto1(self):
self._cflags(0x08, 0x08)
def read(self, addr):
data = [0x30, addr]
data += self._crc(data)
(stat, recv, _) = self._tocard(0x0C, data)
return recv if stat == self.OK else None
def write(self, addr, data):
buf = [0xA0, addr]
buf += self._crc(buf)
(stat, recv, bits) = self._tocard(0x0C, buf)
if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
stat = self.ERR
else:
buf = []
for i in range(16):
buf.append(data[i])
buf += self._crc(buf)
(stat, recv, bits) = self._tocard(0x0C, buf)
if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
stat = self.ERR
return stat
My output is absolutely clear and I am not getting any print. Where's my problem?
After straggling with this problem too and posting an unuseful answer which was deleted, i finally managed to get it work. Take a look at this thread at raspberry.org, especially at the GitHub repo from danjperron mentioned there.
I copied the code to my Pico and changed the pin numbers in examples/Pico_read.py, line 11 to reader = MFRC522(spi_id=0,sck=6,miso=4,mosi=7,cs=5,rst=22) to match your used pins. It will print out something like Card detected 0C9B5023 if it works.
The miso is an input to the pico. Try changing the miso pin assignment to miso = Pin(4, Pin.IN, Pin.PULL_DOWN)

Tradingview Pinescript alert not working as expected

I am using below pinescript and i am not getting alerts as expected. I am aware that it is a repainting script. It is working fine with the back testing.
Long alert is set to "Once per bar close" and short alert is set to "once per bar".
The unexpected behavior is
1) Few times, i am getting short alert though there is no corresponding long alert (though i have taken care in my script, short alert will be sent only when there is a long).
2) Multiple consecutive Short alerts per bar. I am aware that in the realtime bar, the short condition may be true multiple number of times. But since i have set alert to "once per bar", the alert should come only for the first time short condition becomes true.
Please can you let me know if i am doing anything wrong ?
Thanks in advance.
//#version=4
study("My Script",overlay = true)
ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2020, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E
firstrun = true
bought = false
longcondition = false
shortcondition = false
//Just to track first run
firstrun := firstrun[1]
if (firstrun == false)
bought := bought[1]
//once condition is met, send a buy alert and make "bought" equal to true //to enable selling
if (close <= 8600 and bought==false and T)
bought := true
longcondition :=true
alertcondition(longcondition, "Long", "Long")
plotshape(longcondition, title = "Buy", text = 'Buy', style = shape.labelup, location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
if (longcondition)
longcondition :=false
//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
shortcondition := true
bought := false
alertcondition(shortcondition, "short", "short")
plotshape(shortcondition, title = "Sell", text = 'Sell', style = shape.labelup, location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
if (shortcondition)
shortcondition :=false
plotchar(bought, "bought", "", location = location.top)
firstrun := false
You bought variable now automatically saves its value bar to bar and I have removed the late reinitializations of vars in your script. Seems to be working fine here:
//#version=4
study("My Script",overlay = true)
ST = input(true, title = "Activate Strategy Tester")
T_SY = input(2000, title = "Strategy Start Year")
T_SM = input(5, title = "Start Month")
T_SD = input(1, title = "Strategy Start Day")
T_EY = input(2025, title = "Strategy End Year")
T_EM = input(1, title = "End Month")
T_ED = input(1, title = "Strategy End Day")
T_S = timestamp(T_SY, T_SM, T_SD,00,00)
T_E = timestamp(T_EY, T_EM, T_ED,00,00)
T= ST and time >= T_S and time <= T_E
var bought = false
longcondition = false
shortcondition = false
//once condition is met, send a buy alert and make "bought" equal to true //to enable selling
if (close <= 8600 and bought==false and T)
bought := true
longcondition :=true
//once condition is met, sent a sell alert.
if (bought and close>=9000 and T)
shortcondition := true
bought := false
alertcondition(longcondition, "Long", "Long")
alertcondition(shortcondition, "short", "short")
plotshape(longcondition, title = "Buy", text = 'Buy', style = shape.labelup, location = location.abovebar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny)
plotshape(shortcondition, title = "Sell", text = 'Sell', style = shape.labelup, location = location.belowbar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny)
// For debugging.
plotchar(bought, "bought", "•", location = location.top)
if buy signal is generated continuously for two sessions, then it will not appear till sell signal is generated.