Pine Script I want to combine two buy conditions in one buy alert and two sell conditions in one sell alert - pine-script-v5

`
//#version=5
indicator("SSL Channel", shorttitle="SSL Channel", overlay=true, timeframe="", timeframe_gaps=false)
wicks = input(false, "Take Wicks into Account ?")
highlightState = input(true, "Highlight State ?")
ma(source, length, type) =>
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "SMMA (RMA)" ? ta.rma(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
na
show_ma1 = input(true , "MA High", inline="MA #1", group="Channel №1")
ma1_type = input.string("SMA" , "" , inline="MA #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Channel №1")
ma1_source = input(high , "" , inline="MA #1", group="Channel №1")
ma1_length = input.int(200 , "" , inline="MA #1", minval=1, group="Channel №1")
ma1_color = input(color.green, "" , inline="MA #1", group="Channel №1")
ma1 = ma(ma1_source, ma1_length, ma1_type)
show_ma2 = input(true , "MA Low", inline="MA #2", group="Channel №1")
ma2_type = input.string("SMA" , "" , inline="MA #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Channel №1")
ma2_source = input(low , "" , inline="MA #2", group="Channel №1")
ma2_length = input.int(200 , "" , inline="MA #2", minval=1, group="Channel №1")
ma2_color = input(color.red, "" , inline="MA #2", group="Channel №1")
ma2 = ma(ma2_source, ma2_length, ma2_type)
showLabels1 = input(true, "Show Buy/Sell Labels ?", group="Channel №1")
show_ma3 = input(false , "MA High", inline="MA #3", group="Channel №2")
ma3_type = input.string("SMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Channel №2")
ma3_source = input(high , "" , inline="MA #3", group="Channel №2")
ma3_length = input.int(20 , "" , inline="MA #3", minval=1, group="Channel №2")
ma3_color = input(color.orange, "" , inline="MA #3", group="Channel №2")
ma3 = ma(ma3_source, ma3_length, ma3_type)
show_ma4 = input(false , "MA Low", inline="MA #4", group="Channel №2")
ma4_type = input.string("SMA" , "" , inline="MA #4", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Channel №2")
ma4_source = input(low , "" , inline="MA #4", group="Channel №2")
ma4_length = input.int(20 , "" , inline="MA #4", minval=1, group="Channel №2")
ma4_color = input(color.blue, "" , inline="MA #4", group="Channel №2")
ma4 = ma(ma4_source, ma4_length, ma4_type)
showLabels2 = input(true, "Show Buy/Sell Labels ?", group="Channel №2")
Hlv1 = float(na)
Hlv1 := (wicks ? high : close) > ma1 ? 1 : (wicks ? low : close) < ma2 ? -1 : Hlv1[1]
sslUp1 = Hlv1 < 0 ? ma2 : ma1
sslDown1 = Hlv1 < 0 ? ma1 : ma2
Color1 = Hlv1 == 1 ? ma1_color : ma2_color
fillColor1 = highlightState ? (color.new(Color1, 90)) : na
highLine1 = plot(show_ma1 ? sslUp1 : na, title="UP", linewidth=2, color = Color1)
lowLine1 = plot(show_ma2 ? sslDown1 : na, title="DOWN", linewidth=2, color = Color1)
plotshape(show_ma1 and showLabels1 and Hlv1 == 1 and Hlv1[1] == -1, title="Buy Label", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=Color1, textcolor=color.white)
plotshape(show_ma2 and showLabels1 and Hlv1 == -1 and Hlv1[1] == 1, title="Sell Label", text="Sell", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=Color1, textcolor=color.white)
fill(highLine1, lowLine1, color = fillColor1)
Hlv2 = float(na)
Hlv2 := (wicks ? high : close) > ma3 ? 1 : (wicks ? low : close) < ma4 ? -1 : Hlv2[1]
sslUp2 = Hlv2 < 0 ? ma4 : ma3
sslDown2 = Hlv2 < 0 ? ma3 : ma4
Color2 = Hlv2 == 1 ? ma3_color : ma4_color
fillColor2 = highlightState ? (color.new(Color2, 90)) : na
highLine2 = plot(show_ma3 ? sslUp2 : na, title="UP", linewidth=2, color = Color2)
lowLine2 = plot(show_ma4 ? sslDown2 : na, title="DOWN", linewidth=2, color = Color2)
plotshape(show_ma3 and showLabels2 and Hlv2 == 1 and Hlv2[1] == -1, title="Buy Label", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=Color2, textcolor=color.white)
plotshape(show_ma4 and showLabels2 and Hlv2 == -1 and Hlv2[1] == 1, title="Sell Label", text="Sell", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=Color2, textcolor=color.white)
fill(highLine2, lowLine2, color = fillColor2)
// Alerts
alertcondition(Hlv1 == 1 and Hlv1[1] == -1, title="SSL Channel (1) Buy Alert", message = "SSL Channel (1): BUY")
alertcondition(Hlv1 == -1 and Hlv1[1] == 1, title="SSL Channel (1) Sell Alert", message = "SSL Channel (1): SELL")
alertcondition(Hlv2 == 1 and Hlv2[1] == -1, title="SSL Channel (2) Buy Alert", message = "SSL Channel (2): BUY")
alertcondition(Hlv2 == -1 and Hlv2[1] == 1, title="SSL Channel (2) Sell Alert", message = "SSL Channel (2): SELL")
`
This is SSL Channel indicator. I want to create an alert based on this indicator. I want it to alert BUY when two blue cloud happens at any time. and SELL two red cloud happens at any time. I tried to add the two buy alerts together with AND operator but it is not what Im looking for. It is not necessary to occur the buy/sell conditions at the same time. the buy or sell conditions could happen one another..
I want this: while buy1 condition is already true alert when buy2 condition occurs. and visa versa
while sell1 condition is already true alert when sell2 condition occurs. and visa versa..

Related

I want to automate tradingview with capitalise.ai

I'm a beginner, but I made a script from existing scripts.
But unfortunately it doesn't work. 😦
I want to automate tradingview with capitalise.ai.
Now I get 2 signals for each candle, but I only want to get 1 signal if it is at a SellSignal or if it is at a BuySignal.
Can this be solved?
//#version=5
strategy("My Strategy", overlay=true)
//HMA
len6 = 125
src6 = close
hma = ta.wma(2 * ta.wma(src6, len6 / 2) - ta.wma(src6, len6), math.floor(math.sqrt(len6)))
hmacolor = close > hma ? #00ccff : #ff0055
plot(hma, title='HMA Line', color=color.new(hmacolor, 25), linewidth=5)
//Condition
if (hmacolor == #00ccff and hmacolor[1] != #00ccff)
strategy.entry("Long", strategy.long)
if (hmacolor == #ff0055 and hmacolor[1] != #ff0055)
strategy.entry("Short", strategy.short)
//Alert
ttbuystring = 'Input your custom alert message here.'
ttsellstring = 'Input your custom alert message here.'
ttstopstring = 'Input your custom alert message here.'
usebuyalert = input.bool(defval=true, title='Use BUY Alert', group='Alert Messages')
buystring = input.string(title='Buy Alert Message', defval='BUY', confirm=false, group='Alert Messages', tooltip=ttbuystring)
usesellalert = input.bool(defval=true, title='Use SELL Alert', group='Alert Messages')
sellstring = input.string(title='Sell Alert Message', defval='SELL', confirm=false, group='Alert Messages', tooltip=ttsellstring)
if usebuyalert
alert(buystring, alert.freq_once_per_bar)
if usesellalert
alert(sellstring, alert.freq_once_per_bar)
Now I get 2 signals for each candle, but I only want to get 1 signal if it is at a SellSignal or if it is at a BuySignal.
Can this be solved?
//#version=5
strategy("My Strategy", overlay=true)
//HMA
len6 = 125
src6 = close
hma = ta.wma(2 * ta.wma(src6, len6 / 2) - ta.wma(src6, len6), math.floor(math.sqrt(len6)))
hmacolor = close > hma ? #00ccff : #ff0055
plot(hma, title='HMA Line', color=color.new(hmacolor, 25), linewidth=5)
//Variables for alerts
ttbuystring = 'Input your custom alert message here.'
ttsellstring = 'Input your custom alert message here.'
ttstopstring = 'Input your custom alert message here.'
usebuyalert = input.bool(defval=true, title='Use BUY Alert', group='Alert Messages')
buystring = input.string(title='Buy Alert Message', defval='BUY', confirm=false, group='Alert Messages', tooltip=ttbuystring)
usesellalert = input.bool(defval=true, title='Use SELL Alert', group='Alert Messages')
sellstring = input.string(title='Sell Alert Message', defval='SELL', confirm=false, group='Alert Messages', tooltip=ttsellstring)
//Condition
if (hmacolor == #00ccff and hmacolor[1] != #00ccff) and strategy.position_size < 0
strategy.close("Short")
if (hmacolor == #ff0055 and hmacolor[1] != #ff0055) and strategy.position_size > 0
strategy.close("Long")
if (hmacolor == #00ccff and hmacolor[1] != #00ccff) and strategy.position_size <= 0
strategy.entry("Long", strategy.long)
if usebuyalert
alert(buystring, alert.freq_once_per_bar)
if (hmacolor == #ff0055 and hmacolor[1] != #ff0055) and strategy.position_size >= 0
strategy.entry("Short", strategy.short)
if usesellalert
alert(sellstring, alert.freq_once_per_bar)

Filter Form by date from - to MS Access

I have a database which I want to filter by date, I managed to make it works with single date filter, I am trying to make the filter to be two date selections from/to, I did not get it works
here is my code
Private Sub cmbFindCustomer_AfterUpdate()
If IsNull(cmbFindCustomer) Then
hptxt = ""
rptxt = ""
contxt = ""
cptxt = ""
'by field totals
M_Hottxt = ""
M_retxt = ""
M_coltxt = ""
M_contxt = ""
Text99 = ""
Text100 = ""
Text101 = ""
Text102 = ""
Text107 = ""
Text108 = ""
Text109 = ""
Text110 = ""
Chart127.RowSource = ""
Chart128.RowSource = ""
Chart129.RowSource = ""
Chart130.RowSource = ""
List6.RowSource = ""
Else
hptxt = DCount("*", "HP_Qry", "Date = #" & cmbFindCustomer & "#")
rptxt = DCount("*", "RP_Qry", "Date = #" & cmbFindCustomer & "#")
contxt = DCount("*", "Conp_Qry", "Date = #" & cmbFindCustomer & "#")
cptxt = DCount("*", "CP_Qry", "Date = #" & cmbFindCustomer & "#")
'by field totals
M_Hottxt = CalSum("Hot", "M_P", cmbFindCustomer)
M_retxt = CalSum("EQUIPMENT", "M_P", cmbFindCustomer)
M_coltxt = CalSum("Cold", "M_P", cmbFindCustomer)
M_contxt = CalSum("Space", "M_P", cmbFindCustomer)
Text99 = CalSum("Hot", "Z_P", cmbFindCustomer)
Text100 = CalSum("EQUIPMENT", "Z_P", cmbFindCustomer)
Text101 = CalSum("Cold", "Z_P", cmbFindCustomer)
Text102 = CalSum("Space", "Z_P", cmbFindCustomer)
Text107 = CalSum("Hot", "S_P", cmbFindCustomer)
Text108 = CalSum("EQUIPMENT", "S_P", cmbFindCustomer)
Text109 = CalSum("Cold", "S_P", cmbFindCustomer)
Text110 = CalSum("Space", "S_P", cmbFindCustomer)
Chart127.RowSource = "SELECT * FROM WP WHERE Date = #" & cmbFindCustomer & "#"
Chart128.RowSource = "SELECT * FROM WP WHERE Date = #" & cmbFindCustomer & "#"
Chart129.RowSource = "SELECT * FROM WP WHERE Date = #" & cmbFindCustomer & "#"
Chart130.RowSource = "SELECT * FROM WP WHERE Date = #" & cmbFindCustomer & "#"
List6.RowSource = "SELECT Date, GP, Pf, PType, [Short Description], T_From, T_To, issuer, receiver FROM WP WHERE Date = #" & cmbFindCustomer & "#"
End If
'Debug.Print List6.RowSource
End Sub
how it is possible to make the filter within two textbox selection

stocktsats Stoch RSI values dont match with trading view values

def good_buying_condition_stoch_ema_ema(the_exchange, symbol, timeframe):
#print ("finding the good to go long/buy signal")
r = dict();
hist_data = get_historical_data(the_exchange, symbol, timeframe)
stock_data = create_stock(hist_data) #stock stats data
stock_data.KDJ_WINDOW=14
stock_data.KDJ_PARAM=(3.0 / 14.0, 3.0 / 14.0)
#stock_data._calc_kd(stock_data['close']);
stock_data.MACD_EMA_SHORT = 50
stock_data.MACD_EMA_LONG = 200
macd = stock_data._get_macd(stock_data)
gap = stock_data['kdjk'][499] - stock_data['kdjd'][499]
abs_gap = abs(gap);
r['datetime'] = stock_data['timestamp'][499]
r['symbol'] = symbol
r['timeframe'] = timeframe
r['close'] = stock_data['close'][499]
r['kdjk3'] = stock_data['kdjk_3'][499]
r['kdjd3'] = stock_data['kdjd_3'][499]
r['kdjk'] = stock_data['kdjk'][499]
r['kdjd'] = stock_data['kdjd'][499]
r['macd'] = stock_data['macd'][499]
stock_data.KDJ_WINDOW=7
stock_data._calc_kd(stock_data['close']);
r['kdjk7'] = stock_data['kdjk_7'][499]
r['kdjd7'] = stock_data['kdjd_7'][499]
stock_data.KDJ_WINDOW=14
stock_data._calc_kd(stock_data['close']);
r['kdjk14'] = stock_data['kdjk_14'][499]
r['kdjd14'] = stock_data['kdjd_14'][499]
if (gap < 1 and gap > -1): r['side'] = 'HODL'
elif (gap > 1): r['side'] = 'buy'
elif (gap < -1): r['side'] = 'sell'
else: r['side'] = 'unknown'
if (r['side'] == "buy"):
if (stock_data['kdjk'][499] < 20): r['confidence'] = "strong"
elif (stock_data['kdjk'][499] < 75): r['confidence'] = "ok"
elif (stock_data['kdjk'][499] < 80): r['confidence'] = "questionable"
elif (stock_data['kdjk'][499] < 90): r['confidence'] = "risky"
elif (stock_data['kdjk'][499] < 100): r['confidence'] = "extreme risk"
elif (r['side'] == "sell"):
if (stock_data['kdjk'][499] < 20): r['confidence'] = "extreme risk"
elif (stock_data['kdjk'][499] < 40): r['confidence'] = "risky"
elif (stock_data['kdjk'][499] < 60): r['confidence'] = "questionable"
elif (stock_data['kdjk'][499] < 80): r['confidence'] = "ok"
elif (stock_data['kdjk'][499] < 100): r['confidence'] = "strong"
else: r['confidence'] = 'unknown'
r['momentum'] = gap
if (stock_data['macd'][499] > 0 and stock_data['macd'][499] < 1):
r['trend'] = "bullish"
elif (stock_data['macd'][499] > 1 ):
r['trend'] = "uncertain"
elif (stock_data['macd'][499] < 0 ):
r['trend'] = "bearish"
#### FINTA tech indicators
#ohlc = resample(hist_data, "1m")
#ema50 = TA.EMAIndicator(close=hist_data.close, n=50)
#hist_data['ema50_tpj'] = ema50
#print ("TA.STOCH K = ", TA.STOCH(hist_data['close'], period=14)[499])
#print ("TA.STOCH D = ", TA.STOCHD(hist_data['close'], period=3, stoch_period=14)[499])
#print ("TA.EMA 9 = ", TA.EMA(hist_data)[499])
#print ("TA.EMA 50 = ", TA.EMA(hist_data, 50)[499])
#print ("TA.EMA 200 = ", TA.EMA(hist_data, 200)[499])
r['ta_ema9'] = TA.EMA(hist_data)[499]
r['ta_ema50'] = TA.EMA(hist_data, 50)[499]
r['ta_ema200'] = TA.EMA(hist_data, 200)[499]
r['ta_atr14'] = TA.ATR(hist_data, 14)[499]
r['atr14'] = stock_data['atr'][499]
r['min14'] = hist_data.close.rolling(14).min()[499];
r['max14'] = hist_data.close.rolling(14).max()[499];
print ("returning", r)
return r
def get_historical_data(exchange, coin_pair, timeframe):
"""Get Historical data (ohlcv) from a coin_pair
"""
# optional: exchange.fetch_ohlcv(coin_pair, '1h', since)
data = exchange.fetch_ohlcv(coin_pair, timeframe)
# update timestamp to human readable timestamp
data = [[exchange.iso8601(candle[0])] + candle[1:] for candle in data]
header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
df = pd.DataFrame(data, columns=header)
return df
def create_stock(historical_data):
"""Create StockData from historical data using stockstats
"""
stock = Sdf.retype(historical_data)
return stock
in a 10 second loop, the above produces the following output:
returning {'datetime': '2021-05-26T15:55:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9838, 'kdjk3': 23.00115833047544, 'kdjd3': 33.246639262609804, 'kdjk': 31.557468092520086, 'kdjd': 40.89122272232644, 'macd': -0.00016899252758151295, 'kdjk7': 29.02460416563654, 'kdjd7': 40.37714935820455, 'kdjk14': 31.502465082807905, 'kdjd14': 41.35215340927536, 'side': 'sell', 'confidence': 'risky', 'momentum': -9.333754629806354, 'trend': 'bearish', 'ta_ema9': 0.9863129810243016, 'ta_ema50': 0.9876962538671861, 'ta_ema200': 0.9980103854792317, 'ta_atr14': 0.003885714285714286, 'atr14': 0.0038138082006646855, 'min14': 0.9827, 'max14': 0.9927}
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9831, 'kdjk3': 14.450607500341013, 'kdjd3': 26.42224572620021, 'kdjk': 23.26053428390232, 'kdjd': 34.77728953914806, 'macd': -0.000447425790014111, 'kdjk7': 18.859864087371616, 'kdjd7': 32.94481190275474, 'kdjk14': 23.223865610760864, 'kdjd14': 35.07235377273352, 'side': 'sell', 'confidence': 'risky', 'momentum': -11.516755255245737, 'trend': 'bearish', 'ta_ema9': 0.9856063848194415, 'ta_ema50': 0.9875009374853446, 'ta_ema200': 0.9978533449719774, 'ta_atr14': 0.0036571428571428666, 'atr14': 0.0035699647577600697, 'min14': 0.9827, 'max14': 0.9927}
baseCurrBal: 556.21882609 percent: .4 ticker['last']: 0.984
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9838, 'kdjk3': 20.006163055896863, 'kdjd3': 28.27409757805216, 'kdjk': 25.127200950569065, 'kdjd': 35.399511761370306, 'macd': -0.00039158533417382735, 'kdjk7': 20.88884959461808, 'kdjd7': 33.62114040517023, 'kdjk14': 25.09053227742761, 'kdjd14': 35.69457599495577, 'side': 'sell', 'confidence': 'risky', 'momentum': -10.27231081080124, 'trend': 'bearish', 'ta_ema9': 0.9857463848194415, 'ta_ema50': 0.9875283884657932, 'ta_ema200': 0.9978603573934625, 'ta_atr14': 0.003707142857142861, 'atr14': 0.003619964757760064, 'min14': 0.9827, 'max14': 0.9927}
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9841, 'kdjk3': 22.387115436848994, 'kdjd3': 29.06774837170287, 'kdjk': 25.927200950568974, 'kdjd': 35.66617842803694, 'macd': -0.0003676537102420552, 'kdjk7': 21.758414812009285, 'kdjd7': 33.91099547763397, 'kdjk14': 25.890532277427518, 'kdjd14': 35.96124266162241, 'side': 'sell', 'confidence': 'risky', 'momentum': -9.73897747746797, 'trend': 'bearish', 'ta_ema9': 0.9858063848194416, 'ta_ema50': 0.9875401531716997, 'ta_ema200': 0.997863362716956, 'ta_atr14': 0.003707142857142861, 'atr14': 0.003619964757760064, 'min14': 0.9827, 'max14': 0.9927}
baseCurrBal: 556.21882609 percent: .4 ticker['last']: 0.9839
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9843, 'kdjk3': 23.974417024150412, 'kdjd3': 29.596848900803344, 'kdjk': 26.46053428390225, 'kdjd': 35.8439562058147, 'macd': -0.0003516992942875774, 'kdjk7': 22.338124956936753, 'kdjd7': 34.10423219260979, 'kdjk14': 26.423865610760792, 'kdjd14': 36.13902043940016, 'side': 'sell', 'confidence': 'risky', 'momentum': -9.38342192191245, 'trend': 'bearish', 'ta_ema9': 0.9858463848194414, 'ta_ema50': 0.9875479963089707, 'ta_ema200': 0.9978653662659518, 'ta_atr14': 0.003721428571428574, 'atr14': 0.003634250472045777, 'min14': 0.9827, 'max14': 0.9927}
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9848, 'kdjk3': 27.94267099240484, 'kdjd3': 30.91960022355482, 'kdjk': 27.79386761723572, 'kdjd': 36.28840065025919, 'macd': -0.0003118132544015495, 'kdjk7': 23.787400319255745, 'kdjd7': 34.587323980049455, 'kdjk14': 27.757198944094263, 'kdjd14': 36.583464883844655, 'side': 'sell', 'confidence': 'risky', 'momentum': -8.494533033023473, 'trend': 'bearish', 'ta_ema9': 0.9859463848194416, 'ta_ema50': 0.9875676041521483, 'ta_ema200': 0.997870375138441, 'ta_atr14': 0.0038000000000000095, 'atr14': 0.0037128219006172126, 'min14': 0.9827, 'max14': 0.9927}
baseCurrBal: 556.21882609 percent: .4 ticker['last']: 0.9842
when i compare all the kdj* values, i can not see a strong resemblance to the values over the same time period from trading view's standard stoch rsi with 3/3/14/14/close params. I have adjusted the KDJ_WINDOW and KDJ_PARAM values numerous times with just about every combination of 3, 7 and 14 that make sense to me; i've tried with calls to _calc_kd and without, i've tried adjusting KDJ_WINDODW and KDJ_PARAM in between _calc_kd calls; i've tried to only reference ['kdjk'] and ['kdjd']; i've tried use the ['kdjk_N'] columns as mentoined at https://www.programmersought.com/article/69583827158/ but i have not been able closely replicate the trading view values...
What am i missing / doing incorrectly?
(note1: that any reference to an exchange is for ccxt exchange object).
(note2: i'm using stockstats )
i ended up using the following manual calculation:
i ended up using the following manual calculation:
stock_data['rsi1'] = stock_data['rsi_14']
stock_data['rsi_L14'] = stock_data['rsi1'].rolling(window=14).min()
stock_data['rsi_H14'] = stock_data['rsi1'].rolling(window=14).max()
stock_data['stoch'] = 100*((stock_data['rsi1'] - stock_data['rsi_L14']) / (stock_data['rsi_H14'] - stock_data['rsi_L14']) )
stock_data['my_k2'] = stock_data['stoch'].rolling(window=3).mean()
stock_data['my_d2'] = stock_data['my_k2'].rolling(window=3).mean()
r['kdjk'] = stock_data['my_k2'][499]
r['kdjd'] = stock_data['my_d2'][499]
i found this pine script and used explanations at the tradingview explanation and explanation from this page to come up with the true algorithm.
i subsequently cross referenced against a live 1m chart of xrp/usdt on trading view and the values aligned almost exactly.

In Load Test - "The cast to value type 'System.Int32' failed because the materialized value is null"

when we are debugging below code with single user it is working fine. But while we tried to run Load test when user count goes more than 30 we are getting
"The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type." exception.
This is code snippet where we are getting exception.
profile.AccessRights = (
from t in entities.Opportunities
join x in entities.OpportunityWorkloadGroups on t.OpportunityId equals x.OpportunityId into oppworkloads
from ow in oppworkloads.DefaultIfEmpty()
join m in entities.OpportunityWorkloads on ow.OpportunityWorkloadGroupId equals m.OpportunityWorkloadGroupId into oppworkloadmodules
from om in oppworkloadmodules.DefaultIfEmpty()
join y in entities.OpportunityUsers on om.OpportunityWorkloadId equals y.OpportunityWorkloadId into users
from ou in users.DefaultIfEmpty()
where (((t.LookupOpportunityStatu.Name.Equals(Constants.EstimationStatusCompletedName) || t.LookupOpportunityStatu.Name.Equals(Constants.OpportunityStatusDiscardedName)
|| t.LookupOpportunityStatu.Name.Equals(OSEConstants.OpportunityStatusCompletedWithDiscards)) && !t.IsRestricted) ? true : ou.User.Alias == null ? true : ou.User.Alias == alias)
select new Microsoft.OneEstimator.DataAccess.Entities.AccessRights()
{
MasterUserId = userId,
MasterUserRole = roleName,
OpportunityId = t.OpportunityId,
IsOpportunityOwner = t.OpportunityOwner == userId ? true : false,
IsRestricted = t.IsRestricted,
StatusName = t.LookupOpportunityStatu.Name,
OpportunityWorkloadId = ow.OpportunityWorkloads.Any(m => m.OpportunityWorkloadGroupId == ow.OpportunityWorkloadGroupId) ? ow.OpportunityWorkloads.FirstOrDefault(m => m.OpportunityWorkloadGroupId == ow.OpportunityWorkloadGroupId).OpportunityWorkloadId : 0,
EstimationId = ow.OpportunityWorkloadGroupId == null ? 0 : ow.IsActive == false ? 0 : ow.OpportunityWorkloadGroupId,
RoleName = ou.Role == null ? string.Empty : ou.User.Alias == alias ? ou.Role.RoleName : string.Empty,
HasRightsForWA = ow.WorkloadGroupVersion != null ? entities.WorkloadGroupUsers.Any(y => y.WorkloadGroupId == ow.WorkloadGroupVersion.WorkloadGroup.WorkloadGroupId && y.UserId == userId && y.Role.RoleName.Equals(OSEConstants.Estimator)) : true,
WorkstreamUserRoleName = ow.WorkloadGroupVersion != null ? entities.WorkloadGroupUsers.FirstOrDefault(y => y.WorkloadGroupId == ow.WorkloadGroupVersion.WorkloadGroup.WorkloadGroupId && y.UserId == userId).Role.RoleName : string.Empty
}).ToList();
I guess I'm doing something wrong with DefaultIfNull() not sure.

How to get the document with max value for a field with map-reduce in pymongo?

How do I find the document with the maximum uid field with map-reduce in pymongo?
I have tried the following but it prints out blanks:
from pymongo import Connection
from bson.code import Code
db = Connection().map_reduce_example
db.things.insert({
"_id" : "50f5fe8916174763f6217994",
"deu" : "Wie Sie sicher aus der Presse und dem Fernsehen wissen, gab es in Sri Lanka mehrere Bombenexplosionen mit zahlreichen Toten.\n",
"uid" : 13,
"eng" : "You will be aware from the press and television that there have been a number of bomb explosions and killings in Sri Lanka."
})
db.things.insert({
"_id" : "50f5fe8916234y0w3fvhv234",
"deu" : "Ich bin schwanger foo bar.\n",
"uid" : 14,
"eng" : "I am pregnant foobar."
})
db.things.insert({
"_id" : "50f5fe8916234y0w3fvhv234",
"deu" : "barbar schwarz sheep, haben sie any foo\n",
"uid" : 14,
"eng" : "barbar black sheep, have you any foo"
})
m = Code("function () {emit(this.uid,{'uid':this.uid,'eng':this.eng})}")
r = Code("function (key, values) {var total = 0;for (var i = 0; i < values.length; i++) {total += values[i];}return total;}")
result = db.things.inline_map_reduce(m, r)
for r in result:
print
An example document that look like these:
{
"_id" : ObjectId("50f5fe8916174763f6217994"),
"deu" : "Wie Sie sicher aus der Presse und dem Fernsehen wissen, gab es mehrere Bombenexplosionen mit zahlreichen Toten.\n",
"uid" : 13,
"eng" : "You will be aware from the press and television that there have been a
number of bomb explosions and killings."
}
You can use find_one to find the doc with the maximum uid by sorting on that field descending:
db.things.find_one(sort=[("uid", -1)])
or using the defined constant:
db.things.find_one(sort=[("uid", pymongo.DESCENDING)])