What code should i write for getting data of SMA
chart = tsl.get_intraday_data(stock_name, ‘NSE’,5) | |
---|---|
chart[‘sma’] = talib.SMA(chart[‘close’], timeperiod=44) #pandas | |
print(chart) |
is it right?
but i did not return sma value
it shows nan only
What code should i write for getting data of SMA
chart = tsl.get_intraday_data(stock_name, ‘NSE’,5) | |
---|---|
chart[‘sma’] = talib.SMA(chart[‘close’], timeperiod=44) #pandas | |
print(chart) |
is it right?
but i did not return sma value
it shows nan only
Hi @Sunny_Shah ,
The code is correct . You are calculating a 44-period SMA, which means:
NaN
because there’s not enough data to compute the average yet.for stock_name in watchlist:
chart = tsl.get_intraday_data(stock_name, 'NSE',5)
chart['SMA'] = talib.SMA(chart['close'], timeperiod=44) #pandas
CL = chart['close']
OP = chart['open']
HG = chart['high']
LW = chart ['low']
SL_SMA = chart['SMA'].iloc[-2]
#print("Last High", HG.iloc[-1])
print()
print("Second Last High", HG.iloc[-2], "SMA = ", SL_SMA)
print()
print("Second Last Low", LW.iloc[-2])
print()
print("ENTRY = ", HG.iloc[-2])
target = ((HG.iloc[-2]-LW.iloc[-2])*3)+HG.iloc[-2]
print("TARGET = ", target)
print()
SL = LW.iloc[-2]
print("StopLOSS = ", SL)
print()
A = chart['SMA'].iloc[-2] > chart['SMA'].iloc[-3]
B = chart['SMA'].iloc[-2] < CL and (chart['SMA'].iloc[-2] > LW
if A and B :
print()
print("----X------BUY-----X------")
pdb.set_trace()
What to do for IF condition will satisfy…
in code i want check RISING SMA…
Error got :
Traceback (most recent call last):
File “sma.py”, line 56, in
B = (chart[‘SMA’].iloc[-2] < CL ) and (chart[‘SMA’].iloc[-2] > LW)
File “C:\Users\shahs\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\generic.py”, line 1466, in nonzero
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Hi @Sunny_Shah ,
You’re getting that error because you’re comparing a single value with an entire column.
To fix it, use .iloc[-2]
to get the specific value instead of the whole column.
Change:
CL = chart['close']
LW = chart['low']
To:
CL = chart['close'].iloc[-2]
LW = chart['low'].iloc[-2]
Then your condition will work without error.
Respected…
I tried 200 SMA. I got values in 1 min TF, but did not got in 5 Min or 15Min TF
result shown as nan…
i used code as follows
chart = tsl.get_intraday_data(stock_name, ‘NSE’, 5)
chart[‘SMA_200’] = talib.SMA(chart[‘close’], timeperiod=200 )
what i can do for getting real time result?
Also i did not recied LTP i used tsl.get_ltp(stock_name, ‘NSE’)
see 200 SMA means , it need prevoius 200 values
reason for
1 min df showing up is beacuse daily df consists of (60/1) * 6 = 360 candles
5 min df not showing up because
(60/5) * 6 = 72 candles
for 15 min
(60/15) * 6 = 24 candles
rrquired candles for SMA is 200
so in 5 min and 15 min df consists lesss tahn 200
yes… i observe that… but any solution on that?
solution for what?
calculation for 200SMA on 5 MIN or More timeframe Calculation
ur code is correct , it will add column SMA to ur dataframe
the problem for 5 and 15 min timeframes is
for intra_data 6 hrs of trading (9.15 to 3.15)
for 5 min TF df consists only 72 candles
same as for 15 min 24 candles
But u are calculating SMA for a period of 200
so for 200 SMA u need minimum 200 candles
so 5 and 15 doesnt have minum 200 candles
for 5 and 15 u will get NAN
hop u understood well
Yes i got it…and sorted in other ways…done with success…
I have prepared the code for Long Condition SMA Strategy
LONG : RISING SMA
Price crossed SMA
BUY ABOVE THE HIGH AND SL BELOW THE LOW.
COMPLETE code is as below
PLEASE check the code and please suggest any correction.
available_balance = tsl.get_balance()
leveraged_margin = available_balance*3
max_trades = 3
per_trade_margin = (leveraged_margin/max_trades)
RISK = round((available_balance / 100) * 0.5, 2)
watchlist = [‘BIOCON’, ‘OFSS’, ‘MANAPPURAM’, ‘BSOFT’, ‘CHAMBLFERT’, ‘DIXON’, ‘NATIONALUM’, ‘DLF’, ‘IDEA’, ‘ADANIPORTS’, ‘SAIL’, ‘HINDCOPPER’, ‘INDIGO’, ‘RECLTD’, ‘PNB’, ‘HINDALCO’, ‘RBLBANK’, ‘GNFC’, ‘ALKEM’, ‘CONCOR’, ‘PFC’, ‘GODREJPROP’, ‘MARUTI’, ‘ADANIENT’, ‘ONGC’, ‘CANBK’, ‘OBEROIRLTY’, ‘BANDHANBNK’, ‘SBIN’, ‘HINDPETRO’, ‘CANFINHOME’, ‘TATAMOTORS’, ‘LALPATHLAB’, ‘MCX’, ‘TATACHEM’, ‘BHARTIARTL’, ‘INDIAMART’, ‘LUPIN’, ‘INDUSTOWER’, ‘VEDL’, ‘SHRIRAMFIN’, ‘POLYCAB’, ‘WIPRO’, ‘UBL’, ‘SRF’, ‘BHARATFORG’, ‘GRASIM’, ‘IEX’, ‘BATAINDIA’, ‘AARTIIND’, ‘TATASTEEL’, ‘UPL’, ‘HDFCBANK’, ‘LTF’, ‘TVSMOTOR’, ‘GMRAIRPORT’, ‘IOC’, ‘ABCAPITAL’, ‘ACC’, ‘IDFCFIRSTB’, ‘ABFRL’, ‘ZYDUSLIFE’, ‘GLENMARK’, ‘TATAPOWER’, ‘PEL’, ‘LAURUSLABS’, ‘BANKBARODA’, ‘KOTAKBANK’, ‘CUB’, ‘GAIL’, ‘DABUR’, ‘TECHM’, ‘CHOLAFIN’, ‘BEL’, ‘SYNGENE’, ‘FEDERALBNK’, ‘NAVINFLUOR’, ‘AXISBANK’, ‘LT’, ‘ICICIGI’, ‘EXIDEIND’, ‘TATACOMM’, ‘RELIANCE’, ‘ICICIPRULI’, ‘IPCALAB’, ‘AUBANK’, ‘INDIACEM’, ‘GRANULES’, ‘HDFCAMC’, ‘COFORGE’, ‘LICHSGFIN’, ‘BAJAJFINSV’, ‘INFY’, ‘BRITANNIA’, ‘M&MFIN’, ‘BAJFINANCE’, ‘PIIND’, ‘DEEPAKNTR’, ‘SHREECEM’, ‘INDUSINDBK’, ‘DRREDDY’, ‘TCS’, ‘BPCL’, ‘PETRONET’, ‘NAUKRI’, ‘JSWSTEEL’, ‘MUTHOOTFIN’, ‘CUMMINSIND’, ‘CROMPTON’, ‘M&M’, ‘GODREJCP’, ‘IGL’, ‘BAJAJ-AUTO’, ‘HEROMOTOCO’, ‘AMBUJACEM’, ‘BIOCON’, ‘ULTRACEMCO’, ‘VOLTAS’, ‘BALRAMCHIN’, ‘SUNPHARMA’, ‘ASIANPAINT’, ‘COALINDIA’, ‘SUNTV’, ‘EICHERMOT’, ‘ESCORTS’, ‘HAL’, ‘ASTRAL’, ‘NMDC’, ‘ICICIBANK’, ‘TORNTPHARM’, ‘JUBLFOOD’, ‘METROPOLIS’, ‘RAMCOCEM’, ‘INDHOTEL’, ‘HINDUNILVR’, ‘TRENT’, ‘TITAN’, ‘JKCEMENT’, ‘ASHOKLEY’, ‘SBICARD’, ‘BERGEPAINT’, ‘JINDALSTEL’, ‘MFSL’, ‘BHEL’, ‘NESTLEIND’, ‘HDFCLIFE’, ‘COROMANDEL’, ‘DIVISLAB’, ‘ITC’, ‘TATACONSUM’, ‘APOLLOTYRE’, ‘AUROPHARMA’, ‘HCLTECH’, ‘LTTS’, ‘BALKRISIND’, ‘DALBHARAT’, ‘APOLLOHOSP’, ‘ABBOTINDIA’, ‘ATUL’, ‘UNITDSPR’, ‘PVRINOX’, ‘SIEMENS’, ‘SBILIFE’, ‘IRCTC’, ‘GUJGASLTD’, ‘BOSCHLTD’, ‘NTPC’, ‘POWERGRID’, ‘MARICO’, ‘HAVELLS’, ‘MPHASIS’, ‘COLPAL’, ‘CIPLA’, ‘MGL’, ‘ABB’, ‘PIDILITIND’, ‘MRF’, ‘LTIM’, ‘PAGEIND’, ‘PERSISTENT’]
TRADED_LIST =
while True:
live_pnl = tsl.get_live_pnl()
current_time = datetime.datetime.now().time()
if current_time < datetime.time(9, 30): # time checking
print("wait for market to start", current_time)
continue
if (current_time > datetime.time(15, 15)) or (live_pnl < max_loss):
#I_want_to_trade_no_more = tsl.kill_switch('ON') # removed Kill swtich as it may get accidenyl hit while Testing and block all future order placement
print("Market is over, Bye Bye see you tomorrow...", current_time)
break
for stock_name in watchlist:
time.sleep(0.2)
print(f"Scaning {stock_name}")
chart = tsl.get_historical_data(stock_name, 'NSE', '5')
chart['SMA_44'] = round(talib.SMA(chart['close'], timeperiod=44 ),2)
RISING_SMA = chart['SMA_44'].iloc[-1] > chart['SMA_44'].iloc[-2] > chart['SMA_44'].iloc[-3]
SMA_44_Crossed = (chart['close'].iloc[-1] > chart['SMA_44'].iloc[-1]) and (chart['open'].iloc[-1] < chart['SMA_44'].iloc[-1])
max_order_limit = len(TRADED_LIST) <= max_trades
no_repeat_order = stock_name not in TRADED_LIST
if RISING_SMA and SMA_44_Crossed and max_order_limit and no_repeat_order:
print(stock_name, "is in RISING MODE")
print("SMA 1 Bar Back = ", chart['SMA_44'].iloc[-1], " CLOSE = ", chart['close'].iloc[-1], "OPEN = ", chart['open'].iloc[-1])
print("SMA 2 Bar Back = ",chart['SMA_44'].iloc[-2], "CLOSE = ", chart['close'].iloc[-2], "OPEN = ", chart['open'].iloc[-2])
print("SMA 3 Bar Back = ",chart['SMA_44'].iloc[-3], "CLOSE = ",chart['close'].iloc[-3], "OPEN = ", chart['open'].iloc[-3])
print()
print("CROSSED = ", chart['close'].iloc[-1], "****YOU CAN BUY****")
print()
print(chart['open'].iloc[-1])
print()
ENTRY = chart['close'].iloc[-1]
SL = chart['low'].iloc[-1]
TARGET = int((((chart['close'].iloc[-1]-chart['low'].iloc[-1])*3)+(chart['close'].iloc[-1])))
print("ENTRY = ",ENTRY, "STOPLOSS = ", SL, "TARGET =", TARGET)
# ORDER PLACEMENT
print(stock_name, "is in uptrend, Buy this script")
print()
qty = int(RISK/SL)
buy_entry_orderid = tsl.order_placement(stock_name,'NSE', qty, ENTRY, 0, 'MARKET', 'BUY', 'MIS') # BUY ORDER
sl_orderid = tsl.order_placement(stock_name,'NSE', qty, 0, SL, 'STOPMARKET', 'SELL', 'MIS') # SL ORDER
TRADED_LIST.append(stock_name)
Hi @Sunny_Shah
Overall your code looks good. Good job!
I have few suggestions:
Qty calculation logic needs to be fixed
Define risk value RISK =500
Calculate SL_Points = Entry -SL
Calculate Qty = int(RISK/SL_Points)
Try to add logic for trailing stop loss
Your strategy looks much simpler and will give buy signal for most of the stocks. Because of this it will always pick initial few stocks
You can also add condition to check account balance available in your account before placing order
Try to test your code by printing message on screen before placing actual orders. Once you get confidence then enable code for order placement
THanks for your suggetion…i will surely try to improve with all ur cooperations
as i know i will defined already SL point and qty calculation