How to Cancel or Exit a Bracket Order,Cover Order and Regular Order in KiteConnect - Python


Follow this Video for Proper Instructions then Exactly follow Below for code Input:



from kiteconnect import KiteConnect
import csv
import pandas as pd

api_key='xxx'
api_secret='yyy'
kite=KiteConnect(api_key=api_key)
kite.set_access_token('zzz')
#after placing this order just comment
##OD1=kite.order_place('NSE','YESBANK','BUY',1,validity='DAY',trigger_price=293,variety='co')
ko=kite.orders()
ko=pd.DataFrame(ko)
print(ko)
OID=int(ko['order_id'][4:5])
POID=int(ko['parent_order_id'][4:5])
print(OID,POID)
print(kite.order_cancel(order_id=OID,variety='co',parent_order_id=POID))

Create your Own KiteConnect Dashboard with the help of Flask Framework.

Flask is a micro web framework written in python to achieve this type of framework you can proceed with the the help of this code and can achiveve just need to follow the exact steps in videos.


After above videos if you missed something this is the way it should be processed which you can follow from the image

For Logging the web page and getting access token look like this

import json
from flask import Flask, request
from kiteconnect import KiteConnect

# Base settings
PORT = 5010
HOST = "127.0.0.1"

# Kite Connect App settings. Go to https://developers.kite.trade/apps/
# to create an app if you don't have one.
kite_api_key = "your_api_key"
kite_api_secret = "your_access_token"

# Create a redirect url
redirect_url = "http://{host}:{port}/login".format(host=HOST, port=PORT)

# Login url
login_url = "https://api.kite.trade/connect/login?api_key={api_key}".format(
    api_key=kite_api_key)

# Kite connect console url
console_url = "https://developers.kite.trade/apps/{api_key}".format(
    api_key=kite_api_key)

# App
app = Flask(__name__)


index_template = """
    
Make sure your app with api_key - {api_key} has set redirect to {redirect_url}.
login_template = """ <h2 style="color: green;"> Success</h2> <div> Access token: <b>{access_token}</b></div> <h4> User login data</h4> <pre>{user_data}</pre> <a href="https://www.blogger.com/%7Bholdings_url%7D" target="_blank"><h4> Fetch user holdings</h4> </a> <a href="https://www.blogger.com/%7Borders_url%7D" target="_blank"><h4> Fetch user orders</h4> </a> <a href="https://kite.trade/docs/connect/v1/" target="_blank"><h4> Checks Kite Connect docs for other calls.</h4> </a>""" @app.route("/") def index(): return index_template.format(api_key=kite_api_key, redirect_url=redirect_url, console_url=console_url, login_url=login_url) @app.route("/login") def login(): request_token = request.args.get("request_token") if not request_token: return """ <span style="color: red;">Error while generating request token.</span><a href="https://www.blogger.com/"> Try again.</a><a href="https://www.blogger.com/null">""" kite = KiteConnect(api_key=kite_api_key) data = kite.request_access_token(request_token, secret=kite_api_secret) holdings_url = ("https://api.kite.trade/portfolio/holdings" "?api_key={api_key}&access_token={access_token}").format( api_key=kite_api_key, access_token=data["access_token"]) orders_url = ("https://api.kite.trade/orders" "?api_key={api_key}&access_token={access_token}").format( api_key=kite_api_key, access_token=data["access_token"]) return login_template.format(access_token=data["access_token"], user_data=json.dumps(data, indent=4, sort_keys=True), holdings_url=holdings_url, orders_url=orders_url) if __name__ == "__main__": print("Starting server: http://{host}:{port}".format(host=HOST, port=PORT)) app.run(host=HOST, port=PORT, debug=True)
View Code in GitHub Follow Below:

CSV Reading and Writing Streaming Data-Zerodha-KiteConnect-Python




import csv
r1=open('fill_18_10.csv','r').read()
with open('filew','w',newline='') as wr:
    wr1=csv.writer(wr,delimiter=',')
    wr1.writerow([r1])
with open('filew','r') as rd:
    rd1=csv.reader(rd)
    for row in rd1:
        print(row[0])

Bulk fetch OHLC + LTP quotes for up to 200 instruments-Zerodha-KiteConne...



import pandas as pd
import requests

r=requests.get('https://api.kite.trade/quote/ohlc?
api_key=xxx&access_token=yyy&i=NSE:INFY&i=BSE:SENSEX&i=NSE:NIFTY+50')
#if want in ltp format follow below:
#r=requests.get('https://api.kite.trade/quote/ltp?
api_key=xxx&access_token=yyy&i=NSE:INFY&i=BSE:SENSEX&i=NSE:NIFTY+50')

data=r.json()
data=pd.DataFrame(data['data']['BSE:SENSEX'])
print(data['ohlc']['close'])

How to Import Data Candles and Set them to Perform Algo Trading-Zerodha-...





import requests
import pandas as pd

r=requests.get('https://api.kite.trade/instruments/historical/5633/minute?
api_key=xxx&access_token=yyy&from=2017-09-08+09:00:00&to=2017-09-08+10:00:00')
data=r.json()
data=pd.DataFrame(data['data']['candles'],columns=['Date','Open','High','Low','Close','Volume'])
print(data['Open'])


Tracking Last Price,Profit and Loss fetching Everything from JSON KiteConnect Requests in Python




import requests,time,json


def main():
    r = requests.get('https://api.kite.trade/portfolio/positions/api_key=your_api_key&access_token=your_tok')
##    r = requests.get('https://api.kite.trade/instruments/MCX/GOLD17OCTFUT?api_key=xxx&access_token=yy')
    rjson=r.json()
##    print(rjson)
    r1=rjson['data']['last_price']
    r1=rjson['data']['last_time']

    
    
    print(r1)
##

while True:
    main()
    time.sleep(5)



Extract Particular Tick Stock Data from Streaming KiteConnect WebSocket

Streaming Tick Stock Data contains Voluminous data and Contains in a large set of Regular Expressions to filter out and get required price i have performed some operations by importing re.


While doing this i Exactly First Extracted those Tick Data in CSV and then read them and then First i asked for a match value while split them and read in each and every line of row for that i just looped through using 'for' loop and took an x for iteartaing every row.In the End if Reached end of the file it will throw an error.


For Further instructions please follow the Video and then go for the Code Input.




#import package module
import re

#read tick data
r1=open('quot.csv','r').read()

#loop it and perform the split operation
x=0
for r2 in r1:
    r2=re.split(r'last_price',r1)[x].split(',')[0]
    r2=re.findall(r'\d+',r2)
    x+=1
    print(r2)

--End of Code Input--

Tick Stock Data KiteConnect WebSocket Mode FULL,LTP & QUOTE-PYTHON

Tick data getting from KiteConnect is an awesome feature.Tick data offers everything as ohlc and then you can get tradedable future whethere it can be traded or not then we can watch last_price,buy quantity,sell quantity and other things which you expect from a terminal.


KiteConnect offers WebSocket from which if you assign the callbacks and connect you can have Tick data for that you need to assign api_key,public_token and user_id for login flow and authentication and then exactly the tokens you need just add with them with a seperated comma .




from kiteconnect import WebSocket

api_key='your_api_key'
public_token='your_public_token'
client_id='your_id'
#here i have added nifty 50 indices and then MCX GOLD contract
tokens=[53372167,256265]

pa=WebSocket(api_key,public_token,client_id)

After login flow and tokens define tick and tell them to print and then a flow for webscoket need to subscribe and said about mode whether you want to set in FULL ,LTP and QUOTE mode and assign them with callbacks and then say them to connect.



def on_tick(tick,wbskt):
    print(tick)
    
def on_connect(wbskt):
    wbskt.subscribe(tokens)
    wbskt.set_mode(wbskt.MODE_FULL,tokens)
    
pa.on_tick=on_tick
pa.on_connect=on_connect

pa.connect()

Note : it Supports in Python 3.0 Client best for Full Mode Code please Visit Below for Code Input:




from kiteconnect import WebSocket


api_key='your_api_key'
public_token='your_public_token'
client_id='your_id'
#here i have added nifty 50 indices and then MCX GOLD contract
tokens=[53372167,256265]

pa=WebSocket(api_key,public_token,client_id)



def on_tick(tick,wbskt):
    print(tick)
    
def on_connect(wbskt):
    wbskt.subscribe(tokens)
#set the mode as you wish for market watch
    wbskt.set_mode(wbskt.MODE_FULL,tokens)
    
pa.on_tick=on_tick
pa.on_connect=on_connect

pa.connect()

--End of Code Input--

Have any Doubt Regarding these please do comment and Plese do share us on Various Social Media Platform:


Extract Minute Data from KiteConnect and Analyse SMA from Pandas and then Plot Graph from Matplotlib.

Simple Moving Average is one of the Techncial Indicator widely used with other technical indicators which i already explained in this post SMA.

Exactly in this one i'm extracting the price of NIFTY 50 from KiteConnect then trying to Build Simple Moving Average with the help of Pandas Dataframes and then try to Plot with the help of Matplotlib.


So let's get started,all you need in this is to set access token and api key for that you need to follow this you tube video Automate Trade-KiteConnect-Python API Trading Platform-StockMarket-Part 1 after that need to define the Simple Moving Average to Compute it and then need to set instument token which you can get from by just pasting this URL  https://api.kite.trade/instruments in your browser and after that a download will start just save the file as filename.csv then find out the instrument_token which you need to extract the minute data for it's analysis then exactly set from and to date and set the interval as per your wish for minute data you ask for as minute,5minute,10minute,15minute,30minute and 60minute you can set interval day also to fetch datas of previous day and exactly need to define which date you want in particular.


From date and to date should be in the format of yyyy-mm-dd then after call the data in a dataframe and then enjoy you built an SMA with the help of KiteConnect data.


This Post i Just Created so you actually can visualize the data with the help of KiteConnect for Further Please follow the Video for Proper Instructions then Code Input.



#import the Necessary Package module
from kiteconnect import KiteConnect
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
api_key= 'your_api_key'
api_secret='your_api_secret'
kite = KiteConnect(api_key=api_key)
'''
If you need access token from idle just comment out the below 2 line then afte place the access token to the 3rd line
####KRT=kite.request_access_token('your_request_token',api_secret)
####print(KRT)
kite.set_access_token('your_access_token')


style.use('fivethirtyeight')

def MA(data,n):
    MA=pd.Series(pd.rolling_mean(data['close'],n),name='MA')
    data=data.join(MA)
    return data

data=kite.historical(instrument_token='256265',from_date='2017-08-21',to_date='2017-08-21',interval='minute')
data=pd.DataFrame(data)
n=2
SMA=MA(data,n)
MA=SMA['MA']
print(SMA)
SMA.plot()
plt.show()

--End of Code Input--

Have any Doubt regarding this please do Comment and Please do Share us On Various Social Media PLatform:

Read,Write and Extracting Live Stocks Quotes in Excel with the Help of Google Sheet API Python


Please Follow the Video for Proper Instructions then Code Input:



import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope=['https://spreadsheets.google.com/feeds']
creds=ServiceAccountCredentials.from_json_keyfile_name('AD.json',scope)
client=gspread.authorize(creds)

sheet=client.open('ALGO').sheet1

sheet.update_acell('A1','Ticker')
sheet.update_acell('B1','Price')
sheet.update_acell('C1','Open')
sheet.update_acell('D1','High')
sheet.update_acell('E1','Low')
sheet.update_acell('F1','Volume')
sheet.update_acell('G1','Close')


In Formulae Block place this For Close Price =GOOGLEFINANCE("NSE:"&A2,"closeyest")



For Open Price: =GOOGLEFINANCE("NSE:"&A2,"priceopen")



For High Price: =GOOGLEFINANCE("NSE:"&A2,"high")



For Low Price: =GOOGLEFINANCE("NSE:"&A2,"low")



For LTP Price: =GOOGLEFINANCE("NSE:"&A129,"price")



--End of Code Input--



Please Share us On Various Social Media Platform


Reading Analysed Data from Google Spread Sheet's with the help of Google Sheet's API in Python

Please Follow the Video for Proper Instruction and for Code Input Check Below :



import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope=['https://spreadsheets.google.com/feeds']
creds=ServiceAccountCredentials.from_json_keyfile_name('cs.json',scope)
client=gspread.authorize(creds)

sheet=client.open('BB').sheet1

Analysed=sheet.get_all_records()


Analysed=pd.DataFrame(Analysed)
print(Analysed)

--End of Code Input--

Have any Doubt Regarding this Please Feel Free to Comment and Please do Share us on Various Social Media Platform.

Calculate Pivot Point,Resistance and Support of a Stock Price with a Small Python Code.

Pivot Point,Support and Resistance is an Important factor to Place the Orders as Per the Levels.


Say Suppose if the Market is Bullish then you set you target as according R1,R2 and R3 and then vice versa you will follow to set the Target in Sell Orders in Which S1,S2 and S3 Plays role.


It will also Help in Placing Stop Loss and Trailing Stop-Loss say suppose you want to stay Buy and Choose the Target as R3 then Definitely you Stop-Loss should be Less or More as per your Risk Apetite in which you can for S1 as Less and S3 as More.


Pivot Point helps in set for Calculation in Placing bid whether it is Buy or Sell.


It Does Follow Opposite to at Sompe Point it is Just touch S1 and will try to reach R3 for in that Case you can follow this rule.


Please Follow the Video for Proper Instruction's and Python Code Input is Given Below Please do Try it Yourself:


#impot the important packaging module
import pandas_datareader.data as pdr
import fix_yahoo_finance
import pandas as pd
import matplotlib.pyplot as plt



#define each and everything to perform the operation
def PPSR(data):  
    PP = pd.Series((data['High'] + data['Low'] + data['Close']) / 3)  
    R1 = pd.Series(2 * PP - data['Low'])  
    S1 = pd.Series(2 * PP - data['High'])  
    R2 = pd.Series(PP + data['High'] - data['Low'])  
    S2 = pd.Series(PP - data['High'] + data['Low'])  
    R3 = pd.Series(data['High'] + 2 * (PP - data['Low']))  
    S3 = pd.Series(data['Low'] - 2 * (data['High'] - PP))  
    psr = {'PP':PP, 'R1':R1, 'S1':S1, 'R2':R2, 'S2':S2, 'R3':R3, 'S3':S3}  
    PSR = pd.DataFrame(psr)  
    data= data.join(PSR)  
    return data
#extract the stock data
data = pdr.get_data_yahoo("^NSEI", start="2017-01-01", end="2017-07-31")
#compute and print the data
LL=PPSR(data)
print(LL)
# plot the data
pd.concat([data['Close'],PD.PP,PD.R1,PD.S1,PD.R2,PD.S2,PD.R3,PD.S3],axis=1).plot(figsize=(12,9),grid=True)
plt.show()

---End of Code Input--


Have any Doubt Regarding this Plese Fell Free to Comment and Plese do Share this Post in Various other Platform:

Download New Version of Anaconda in Windows 10 for Python Programming and Data Analysis

Please Follow the Video Instructions properly For Installation and For Download Please Click here.

Calculate Pre-Determined Prices of Various Stocks with the help of Bollinger Bands in Python.

BB

Bollinger Bands is referred as Volatility Bands it is mainly used to measure the Volatility of Price Movement it was introduced by John Bollinger.

Bollinger Bands is a Trade Mark and Registered in the name of Bollinger Bands to Measure the Volatility as it Increases and Decreases.

Bollinger Bands are Calculated with the help of Moving Average and Standard Deviation in which it will be Above and Below the Moving Average Price .


Above graph or line is referred as Upper Band and Below one is referred as Lower Band in Between Moving Average price.


Moving Average Can be Calculated can be Calculate by taking Averages and then we Should Calculate the Standard Deviation which can be attained with the help of moving average

For better understanding of Standard Deviation please click here

Then the Upper Band is Calculated and Visualized by having moving average and then it is added with standard deviation multiplied with the factor of 2.


The Lower Band is Calculated and Visualized by having moving average and then it is subtracted with standard deviation multiplied with the factor of 2.

All of the Explanation can be understood with the help of figure given above.From the Figure we Can see that It forms a W-Bottoms and then suddenly a huge raise in the price of that particular stock which can be easily measured and if a M-Bottoms is formed we can understand Vice Versa and then after if the Moving Average Price Crosses Upper Band it is measured as Over Bought Levels and if it crosses the Lower Bands it Can be Measured as Over Sold Levels then if the price is squeezed in between then we can say that a Buy Level is about to form and Vice Versa.


Bollinger Bands Does Lot of Contraction and Relaxation from which we can use that thing and have better understanding and can realise the Pre-Determined Stock Price Movement for further Calculation and Visualization please Follow the Video and the Python Code Input is Available Below which you Can Try it by Yourself.


Compute Pre-Determined Prices of Various Stocks with the help of Bollinger Bands in Python Part-1

Compute Pre-Determined Prices of Various Stocks with the help of Bollinger Bands in Python Part-2


#import the required packaging and modules
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader.data as pdr
import fix_yahoo_finance

#compute the bollinger bands 
def BBANDS(data,ndays):
    MA=data.Close.rolling(n).mean()
    SD=data.Close.rolling(n).std()
    data['MA']=MA
    data['UBB']=MA+(2*SD)
    data['LBB']=MA-(2*SD)
    return data
#retrieve the stock data from yahoo finance
data=pdr.get_data_yahoo('^NSEI',start='2016-07-01',end='2017-08-01')
data=pd.DataFrame(data)

#compute the Bollinger Bands with 20 day moving average
n=20
NBB=BBANDS(data,n)
print(NBB)

#create the plot with Close,Moving Average,Upper band,Lower band
pd.concat([NBB.MA,NBB.Close,NBB.UBB,NBB.LBB],axis=1).plot(figsize=(9,5),grid=True)
plt.plot()
plt.show()
#if want to save those graph in PNG format please comment it out above line i.e plt.show()
plt.savefig('BBANDS.png')

--End of The Code Input--

For any Doubt and Queries Please do Comment and Please do Share this Post to Various Social Media Platform.

Quick Demo Installation on Python,Pip and Various Other Packaging Modules for Data Analysis,Stock Analysis and Algo Trading

Hello Everyone,Welcome to Profit Adda as i have been made a video on Quick Demo Installation on Python,Pip and Various Other Packaging Modules for Data Analysis,Stock Analysis and Algo Trading Purposes for that you Can follow the Installation Link Given Below.


For Installation of Python IDLE Please Click on the Link as follows : Download Python the latest version for Windows


For Installation of Pip Please Click on the Link as follows : PIP Installation


If your Facing Difficulites in Installing Scipy Please Follow the Link for Installation as Follows : Scipy

For other Python Packaging Module or Python Library which is Explained in the Video can be done through command prompt (CMD) by giving Command : pip install PackageName.


If you want to Look Up another Python Library whether it is in GitHub or Python Packaging Module website follow in CMD as : pip search PackageName


For Proper Instruction Please Follow the Video Which is Given Below:



Have any Doubt Regarding this Please Fell Free to Comment and if you Like this Post please share us on Twitter,Facebook and Other Various Social Media Platform


Implementation of Simple Moving Average for Buy/Sell Order placing automatically and grabing the profit at the end from KiteConnect.

Hello Everyone,As in Last Session and Video I Discussed about Automating Trading Strategy in python with the help of KiteConnect in that process i had only explained about getting API for order place.


In this Session i'm gonna discuss about Implementation of Simple Moving Average for Buy/Sell Order placing automatically and grabing the profit at the end.


To do this I Suggest Please Refer my Previous Post Included with the Video on Some Basic Simple Buy/Sell Order after this you need an Historical API offered by Zerodha Brokers which need to be Subscribed to Perform this SMA Strategy.


This Strategy Performs in Smooth Way with the Help of Access Token you need to follow the Same Procedure as Described in Previous post to Obtain an Access token and after getting that Follow this Input Code Below which is an Strategy Available in GitHub Posted by Zerodha .As i'am Doing in Windows Platform for that you need some basic Platform I Python Notebook and Python IDLE Version 3.6 for Smooth Operation.

From I Python Notebook i'm Usually extracting the Access Token which i have been explained in my previous video and after that you need to grab the Access Token and Place it in Access Token Column and Place the required API Key,Client ID of yours provided by Zerodha and fill up the other Credentials as of your's need.


As of Know just Run the Programme to Do this Please follow the Video for Proper Instructions and The Code Input to Backtest this Strategy




from kiteconnect import KiteConnect 

# Initialize all the variables we need
api_key='YOUR_API_KEY'
access_token = "YOUR_ACCESS_TOKEN_FROM_IPYTHON"
client_id = "YOUR_CLIENT-ID"

# Instrument token of RELIANCE
instrument_token = "738561" 

# Dates between which we need historical data
from_date = "2016-10-01"
to_date = "2016-10-17"

# Interval(minute, day, 3 minute, 5 minute...)
interval = "5minute"

kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)

# Gets historical data from Kite Connect
def get_historical_data():
 return kite.historical(instrument_token, from_date, to_date, interval)

"""
  Implementation of the moving average strategy.
  We go through the historical records that 
  we received form Kite Connect, calculate moving average,
  and place a BUY or SELL order.
"""
def strategy(records):
 total_closing_price = 0
 record_count = 0
 order_placed = False
 last_order_placed = None
 last_order_price = 0
 profit = 0

 for record in records:
  record_count += 1
  total_closing_price += record["close"]
  
  #Moving avearge is calculated for every 5 ticks(records)
  if record_count >= 5:
   moving_average = total_closing_price/5

   # If moving average is greater than last tick, place a buy order
   if record["close"] &amp;gt; moving_average:
    if last_order_placed == "SELL" or last_order_placed is None:
     
     # If last order was sell, exit the stock first
     if last_order_placed == "SELL":
      print ("Exit SELL")

      # Calculate profit
      profit += last_order_price - record["close"]
      last_order_price = record["close"]

     # Fresh BUY order
     print ("place new BUY order")
     last_order_placed = "BUY"

  # If moving average is lesser than last tick, and there is a position, place a sell order
   elif record["close"] &amp;lt; moving_average:
    if last_order_placed == "BUY":
     
     # As last order was a buy, first let's exit the position
     print ("Exit BUY")
     
     # Calculate profit
     profit += record["close"] - last_order_price
     last_order_price = record["close"]
     
     # Fresh SELL order
     print ("place new SELL order")
     last_order_placed = "SELL"
     

   
   total_closing_price -= records[record_count-5]["close"]
 print ("Gross Profit ", profit)
 # PLace the last order 
 place_order(last_order_placed)

# Place an order based upon transaction type(BUY/SELL)
def place_order(transaction_type):
 kite.order_place(tradingsymbol="RELIANCE", exchange="NSE", quantity=1, transaction_type=transaction_type, order_type="MARKET", product="CNC")


def start():
 records = get_historical_data()
 strategy(records)

start()

--End Of Code Input--


Have any Doubt Regarding This Please Feel Free to Comment and Please Support us by Sharing us on other Social Media Platform

CCI(Commodity Channel Index) Technical Indicators Build in Python

CCI refered as Commodity Channel Index is one of the famous Oscillator it was discovered by Donald Lambert in 1980.CCI is mainly discovered for commodity but this channel is aslo famous for it's oversold/overbought levels so that it's used in another segment such as ETF's,Currencies and Equities.

CCI is same as Bollinger Bands we mainly consider to found out the Bullish and Bearish Outlook.

We consider +100 for overbought levels and -100 for oversold levels it is to be considered that in +100 overbought levels will give the opportunity for selling and vice versa but it is not taken guaranteed that after these levels it won't get cross these levels further also.

in this we mainly consider Typical price which is of contained High,Low and Close after this we take the consideration of Mean and of it's Standard Deviation.


Mean is nothing but getting the Averages of ndays by dividing them with the same value datasets of ndays for further explanation please refer this page as of all explanation is done about mean and moving average which is as follows : SMA(Simple Moving Average) Technical Indicators Build in Python.


To find out the standard deviation we will take an example of datasets say for example 1,2 and 4 the ndays in this is 3 and after that we add those datsets i.e 7 and then after we will divide this by 3 which is ndays of datasets i.e the value will be 2.3 and here we got our mean i.e M=2.3 and n=3 and then again we considered those datsets and subtract with the mean i.e 1.3,0.3 and -1.7.


Then those datasets need to be squared i.e 1.69,0.09 and 2.89 and then it is sumed up and divide by n-1 i.e. 2.335 and then we exactly findout the variance by finding square root of it which is 1.528 that's it you achieve here CCI std values which is need to get divide by further with the mean value of typical price and in this end we need to considere a 0.015 constant an inverse factor for the index so that we can have readable numbers


Extraction is done from yahoo finance and the symbol considerd is Nifty .To achieve this Technical Indicator value in csv and visualize through charting please follow the Vide for Proper Instruction and then Proceed for code input.


from pandas_datareader import data as web
import matplotlib.pyplot as plt
import fix_yahoo_finance
import pandas as pd

# Commodity Channel Index 
def CCI(data, ndays): 
 TP = (data['High'] + data['Low'] + data['Close']) / 3 
 CCI = pd.Series((TP - pd.rolling_mean(TP, ndays)) / (0.015*pd.rolling_std(TP, ndays)),
 name = 'CCI') 
 data = data.join(CCI) 
 return data

# Retrieve the Nifty data from Yahoo finance:
data = web.get_data_yahoo("^NSEI", start="2014-01-01", end="2017-07-24") 
data = pd.DataFrame(data)

# Compute the Commodity Channel Index(CCI) for NIFTY based on the 20-day Moving average
n = 20
NI = CCI(data, n)
CCI = NI['CCI']

# Plotting the Price Series chart and the Commodity Channel index below
fig = plt.figure(figsize=(7,5))
ax = fig.add_subplot(2, 1, 1)
ax.set_xticklabels([])
plt.plot(data['Close'],lw=1)
plt.title('NSE Price Chart')
plt.ylabel('Close Price')
plt.grid(True)
bx = fig.add_subplot(2, 1, 2)
plt.plot(CCI,'k',lw=0.75,linestyle='-',label='CCI')
plt.legend(loc=2,prop={'size':9.5})
plt.ylabel('CCI values')
plt.grid(True)
plt.setp(plt.gca().get_xticklabels(), rotation=30)
plt.show()

---End of Code Input--

If you have any doubt regarding this please feel free to comment or whatsapp to the given number for further Queries.

SMA(Simple Moving Average) Technical Indicators Build in Python

In Technical Indicators Moving Average is Widely used Technical Indicators Moving Average is also known as Moving Mean(MM) or rolling mean it is basically used to analyse data sets by averages of it's required series of subsets of a full data set.It has many forms say basically Simple(SMA),Exponential(EMA) and Weighted(WMA) forms.It is Very much Responsive and Impulsive Filters which also can be used with Other Techncial Indicators

Moving Average Can be Calculated using Averages of 5day,15day,20day and 200day moving averages most of the time.

It is used to get the Smooth Signal it is mainly filter out the noise it mainly depend on the past prices and smoothly exceed out the data whenever fresh data sets are arrived.
It is Basic Building Blocks of the Other Techincal indicators
It is one of the "X" element we usually get whenever we include the days and get divided with the Exactly Choosen total no. of days in prior which we have considered to get the moving average of data sets.
Say Suppose if we take the 5-day data sets of Days in a Week it usually considered as Follows of First set of data SMA:(1+2+3+4+5)/5=3 then for the same if we consider Second set of Data SMA:(2+3+4+5+6)/5=4 so from this we get to conclusion that in a second data 1 element is removed so that 1 more element of fresh data is added to calculate it's of Averages of it's Days in a Week and Further Follows as Such.
We Can Follow as Such in Require of Finite Sequence of Numbers till we  get the Moving Average of Data's we required to Calculate fo it.
The Below Given Python Code Will Show you How you can get Simple Moving Average Technical Indicators Value and Exactly Print,Visualize through Graph and Save it in your CSV Files for Further Analysis.

Please Follow the Video Tutorial for Proper Instructions Before Code Input




#import the required libraries for SMA Technical Indicators value
import pandas as pd
import quandl
import matplotlib.pyplot as plt

#API-Key Given From The Quandl
auth_token="YOUR API-KEY"

#define the Simple Moving Average such that it consider the Close price of the Given Stocks 
#and No. of days which can be defined further for Calculation of SMA
def SMA(data,ndays):
    SMA=pd.Series(pd.rolling_mean(data['Close'],n),name='SMA')
    data=data.join(SMA)
    return data

#retrieve the data from qandl add your own simble i have just added gold symbol from MCX
data=quandl.get('MCX/GCQ2017',start='2016-08-12',end='2017-07-24')
data=pd.DataFrame(data)


#define the Number of days you need to calcuate the Moving Average
n=20
SMG=SMA(data,n)
SMA=SMG['SMA']

#call the function to print the SMA

print(SMG)
#Comment out Below if you need these Values in CSV Files.
SMG.plot()
#visualise the data 
plt.show()
#save the File into CSV
SMG.to_csv("FileName.csv")

---End Of Code Input---
Further any Doubt Please Fell Free to Comment or Whatsapp to the Given Number in Website

Place Bracket Orders and Cover Orders with the help of KiteConnect in Python API

Hello Everyone, As we Know that Zerodha from Kite Trade They are Offering API Trading Platform to Open Online Account Please Visit https://zerodha.com/open-account?c=ZC9000

After Having Account Please Download These Platform :

Anaconda offer Various Platform in Which I Python is Very Much Easy to Use Platform to Get This Please Visit : https://www.continuum.io/downloads

After Getting Platform Please Download KiteConnect to Get This Please Visit: https://github.com/rainmattertech/pykiteconnect

You can Install KiteConnect Directly from Anaconda Prompt by Typing : pip install kiteconnect

For Further Instructions in Placing Bracket Orders and Cover Orders Please Follow This Video Below :

Dow recorded a record close at 21,532.14 points on Wednesday after Yellen sounded cautious on inflation

fed

profitaddaweb.com - Wall Street futures pointed to a higher open on Thursday, suggesting the Dow was likely to hit a new record high as investors looked ahead to Federal Reserve (Fed) chair Janet Yellen’s second consecutive appearance before the U.S. Congress.

The blue-chip Dow futures advanced 13 points, or 0.06%, at 7:02AM ET (11:02GMT), the S&P 500 futures gained 3 points, or 0.13%, while the tech-heavy Nasdaq 100 futures rose 15 points, or 0.25%.

The Dow recorded a record close at 21,532.14 points on Wednesday after Yellen sounded cautious on inflation and noted the Fed would not need to raise rates "all that much further" to reach current low estimates of the neutral funds rate in her first day of congressional testimony.

Although markets appeared to read her remarks as reflecting a more dovish tone, the Fed chief still backed the idea that the U.S. central bank would need to proceed in a “gradual” fashion and that it would likely begin to unwind asset purchases “this year”.

Yellen will testify for a second day on the central bank's monetary policy, this time in front of the Senate Banking Committee at 10:00AM ET (14:00GMT) Thursday.

The testimony will be the same as the one presented to the House on Wednesday, but Yellen will face a new round of questions from senators.

Prior to her appearance on the economic front, investors will digest weekly jobless claims and the June producer price index at 8:30AM ET (12:30GMT).

On the company front, shares in Target (NYSE:TGT) jumped more than 5% as the retailer gave an upbeat view on second quarter earnings.

Delta Air Lines(NYSE:DAL),Commerce Bancshares(NASDAQ:CBSH) or Northern Technologies(NASDAQ:NTIC) were among a handful of firms scheduled to release results on Thursday one day prior to the unofficial start of earnings season.

JP Morgan (NYSE:JPM) will be the first Dow component to release earnings on Friday in what will be a big day for bank sharesas Wells Fargo(NYSE:WFC) and Citigroup (NYSE:C) also step up to the plate.

Meanwhile, oil prices were under pressure Thursday as the International Energy Agency’s monthly report showed that OPEC's compliance with production cuts fell in June to its lowest levels in six months.

According to the report, OPEC's compliance with cuts slumped to 78% last month from 95% in May.

U.S. crude futures lost 0.81% to $45.12 by 7:02AM ET (11:02GMT), while Brent oil fell 0.90% to $47.31.

Yellen is scheduled to testify on the economy before the Senate Banking Committee

fed

profitaddaweb.com – Gold turned positive Tuesday, after Federal Reserve Governor Lael Brainard sparked doubts about a rate hike later this year, warning that further rate increases could stifle inflation.

Gold futures for August delivery on the Comex division of the New York Mercantile Exchange rose by $2.45, or 0.20%, to $1,215.72 a troy ounce.

Brainard’s dovish comments dampened investor expectations of a Fed rate hike later this year, pressuring yields and the dollar, lifting demand for the precious metal.

“I will want to monitor inflation developments carefully, and to move cautiously on further increases in the federal funds rate, so as to help guide inflation back up around our symmetric target." Federal Reserve Governor Lael Brainard said Tuesday.

Brainard also suggested that the Fed would unwind its balance sheet “soon” as long as economic growth remained robust.

The U.S. dollar index fell to session lows against its rivals while the U.S. 10-year dipped to 2.362, down 0.37%.

Gold is sensitive to moves in both bond yields and the U.S. dollar – A weaker dollar makes gold cheaper for holders of foreign currency while a dip in U.S. rates, decreases the opportunity cost of holding non-yielding assets such as bullion.

The upside in gold futures, however, remained capped, as investors look ahead to

testimony from Fed chair Janet Yellen on the state of the U.S. economy and the Fed’s monetary policy outlook.

Yellen is scheduled to testify on the economy before the Senate Banking Committee at 10:00AM ET (14:00GMT) Wednesday. On Thursday, she will appear in front the House Financial Services Committee also at 10:00AM ET.

Other precious capitalised on dollar weaknesses, with silver futuresadding 0.95% to trade at $15.777 a troy ounce while

Copper traded at $2.673, up 0.96%, while natural gas, rose by 3.96% to $3.045.

Automate Trading Strategy from Kite Connect in Python API Trading Platform

Hello Everyone, As we Know that Zerodha from Kite Trade They are Offering API Trading Platform to Open Online Account Please Visit http://www.profitaddaweb.com/p/open-online-trading-acccount.html

After Having Account Please Download These Platform :

Anaconda offer Various Platform in Which I Python is Very Much Easy to Use Platform to Get This Please Visit : https://www.continuum.io/downloads

After Getting Platform Please Download KiteConnect to Get This Please Visit: https://github.com/rainmattertech/pykiteconnect

You can Install KiteConnect Directly from Anaconda Prompt by Typing : pip install kiteconnect

For Further Instructions Please Follow This Video Below :

For Code Input you Can Refer Below


from kiteconnect import KiteConnect
api_key="Your API KEY"
api_secret="Your API Secret"
kite=KiteConnect(api_key,api_secret)
kite.request_access_token('Your Access Token',api_secret)
kite.place_order(tradingsymbol='SBIN',quantity=1,exchange='NSE',order_type='MARKET',transaction_type='BUY',product='CNC')

--End of Code Input--

For API KEY and Secret Have it your own this is for Education Purpose Only For Further Guidance Contact in WhatsApp @ +91-7795780804

OPEC and other producers to cut output in a move to prop up the market.

oil

profitaddaweb.com - Oil rebounded on Monday, bouncing back from the previous week's losses, but gains were limited amid signals of growing shale production in the U.S.

crude was at $45.11 at 05:00 ET, up 14 cents, or 0.31%.Brent gained 21 cents, or 0.44%, at $47.58.

Energy services company Baker Hughes said on Friday that U.S. drillers added rigs for the 22nd week in a row last week, the longest such streak on record, implying that further gains in domestic production are ahead.

The U.S. rig count rose by six to 747, extending a year-long drilling recovery to the highest level since April 2015.

The increase in U.S. drilling activity and shale production has mostly offset efforts by OPEC and other producers to cut output in a move to prop up the market.

Last month, OPEC and some non-OPEC producers extended a deal to cut 1.8 million barrels per day in supply until March 2018.

Investors looked ahead to a busy week of Federal Reserve speakers for more clues on future monetary policy moves.

gold

profitaddaweb.com - Gold prices fell to the lowest level in around four weeks in European trade on Monday, as investors looked ahead to a busy week of Federal Reserve speakers for more clues on future monetary policy moves.

Comex gold futures were at $1,253.74 a troy ounce by 3:05AM ET (0705GMT), down $2.70, or around 0.2%. Prices fell to $1,252.20 in overnight trade, a level not seen since May 24.

Gold prices lost $13.20, or roughly 1.2%,last week, the second weekly decline in a row, after the Fed raised interest rates and kept the door open for another hike in 2017.

Also on the Comex, silver futures were down 5.7 cents, or around 0.3%, to $16.60 a troy ounce, after hitting its lowest since May 19 at $16.58.

New York Fed Chief William Dudley will kick off the full week of Fedspeak on Monday, giving a talk to business and community leaders in Plattsburgh, New York at 8:00AM ET (1200GMT).

Later in the global day, Chicago Fed President Charles Evans will speak about current economic conditions and monetary policy at an event in New York City.

On Tuesday, Fed Vice Chair Stanley Fischer, Boston Fed President Eric Rosengren and Dallas Fed President Rob Kaplan are scheduled to deliver comments.

Fed Governor Jay Powell is due to speak before the Senate Banking Committee on Thursday.

Finally, Friday sees St. Louis Fed President James Bullard, Cleveland Fed President Loretta Mester and Fed Governor Powell make public remarks.

Last week, the Fed raised interest rates as widely expected and maintained plans to go ahead with another rate hike by year-end. The central bank also provided greater detail about how it plans to reduce its massive $4.5 trillion balance sheet.

Despite the Fed's relatively hawkish message, market players remained doubtful over the central bank's ability to raise rates as much as it would like before the end of the year due to a recent run of disappointing U.S. economic data.

Futures traders are pricing in less than a 15% chance of a hike at the Fed's September meeting, according to Fed Rate Monitor Tool. Odds of a December increase was seen at about 35%.

Meanwhile, market players geared up ahead of Brexit negotiations between the U.K. and the European Union and kept an eye on a deadly attack on worshipers leaving a mosque in London.

How to Setup Python API Trading Platform.

Hello Everyone,Today I'm here for connecting to TWS with the Help of Python IbPy.

As this is not much in Development so i Suggest to Download Previous version of Python i.e 3.5 to Download this Please Follow this Link : https://www.python.org/downloads/

After this Download Please Download the IbPy from This Link : https://github.com/blampe/IbPy


After this Download Please be sure that you have pip installation in your System for installation of IbPy please follow this command in CMD i.e pip install IbPy2.

After this download please do have a look in python 3.5 folder i.e lib-site packages have ib folder.

After this open a new shell and Follow the Code Properly


from ib.opt import Connection,message
from ib.ext.Contract import Contract
from ib.ext.Order import Order

def make_contract(symbol,sec_type,exch,prim_exch,curr):
    Contract.m_symbol=symbol
    Contract.m_sec_Type=sec_type
    Contract.m_exchange=exch
    Contract.m_primaryExch=prim_exch
    Contract.m_currency=curr
    return Contract

def make_order(action,quantity,price=None):
 if price is not None :
    order=Order()
    order.m_orderType='LMT'
    order.m_totalQuantity=quantity
    order.m_action=action
    order.m_lmtprice=price
    return order
 else:
    order=Order()
    order.m_orderType='MKT'
    order.m_totalQuantity=quantity
    order.m_action=action
    return order

cid=500

while __name__=="__main__":
    
 conn=Connection.create(port=7496,clientId=999)
 conn.connect()
 oid=cid
 cont=make_contract('AAPL','STK','SMART','SMART','USD')
 offer=make_order('SELL',1,200)
 conn.placeOrder(oid,cont,offer)
 conn.disconnect()    
    

---End of Code Input--

Connection Succesfull:

connected

Investor jitters over looming geopolitical risk events supported demand for safe-haven assets

gold

profitaddaweb.com - Gold prices held steady just below their strongest level in seven months in European trade on Wednesday, as investor jitters over looming geopolitical risk events supported demand for safe-haven assets.

gold futures were at $1,294.93 a troy ounce by 2:55AM ET (0655GMT), down $2.50, or around 0.2%. Meanwhile,spot gold was at $1,292.40.

Gold prices scored a third-straight session of gain Tuesday after hitting its highest level since November 9 at $1,298.80, as investors sought safe-haven assets ahead of potentially market-moving events later this week.

Also on the Comex, silver futures dipped 5.2 cents, or about 0.3%, to $17.65 a troy ounce. It rose to $17.74 in the prior session, a level not seen since April 25.

Market players will pay close attention to former FBI director James Comey's testimony before the Senate Intelligence Committee on Thursday.

Investors are fearful that the Trump administration may be further damaged by any revelations that could emerge when Comey testifies about Russia's alleged involvement in the U.S. election.

Traders were also wary ahead of Britain's general election, which is also set for Thursday.

While pollsters still expect British Prime Minister Theresa May will win the most seats in the election, a tight result could throw the country into political deadlock just days before formal Brexit talks with the European Union are due to begin on June 19.

The risk-off mood was further compounded by escalating tensions in the Middle East, where Saudi Arabia and three other Arab nations severed their ties with Qatar earlier in the week, accusing it of supporting terrorism.

Gold is often seen as an alternative currency in times of global economic uncertainty and a refuge from financial risk.

Reduced expectations for aggressive U.S. rate hikes from the Federal Reserve in the second half of this year further boosted the appeal of the yellow metal.

The dollar index, which tracks the greenback against a basket of six major rivals, was little changed at 96.52 in London morning trade. It fell to 96.46 on Tuesday, the weakest level since November 9.

Elsewhere in metals trading,

Copper futures slumped 0.9 cents to $2.538 a pound.

Gains in gold, however, were short-lived, as the yellow-metal failed to capitalize on the release of mostly downbeat U.S. economic data

gold

profitaddaweb.com-Gold pulled back from six-week highs on Monday, as safe-haven demand eased despite renewed geopolitical tensions and a flurry of risk events later during the week that could spark turmoil in markets.

Gold futures for August delivery on the Comex division of the New York Mercantile Exchange rose $3.05 or 0.24%, to $1,283.18 a troy ounce.

Gold hit a six-week high in earlier trade, on the back of fresh geopolitical tensions in the Middle East, after Saudi Arabia, the United Arab Emirates, Bahrain and Egypt severed ties with Qatar on Monday, accusing it of supporting terrorism.

Gains in gold, however, were short-lived, as the yellow-metal failed to capitalize on the release of mostly downbeat U.S. economic data, which added to concerns of a slowdown in the U.S economy.

U.S. non-manufacturing activity grew at a slower pace in May, as the Institute for Supply Management on Monday said its non-manufacturing index fell 0.6 points to 56.9 in May.

In a separate report, the Commerce Department said Monday that Factory orders dipped 0.2% in April, in line with forecasts.

Gold is expected to remain supported during the week, as market participants will contend with a raft of risk events that could rattle markets.

On Thursday, the UK heads to the polls in the general election, whose outcome has become much less certain of late, after the latest opinion poll predicted that the Conservatives may fall short of the required number of seats for a majority.

A YouGov poll on Sunday, suggested that the Conservatives will win only 305 seats in the House of Commons, above Labour's 268 but well short of the 326 seats needed for a majority.

Meanwhile in Washington on Thursday, former FBI director James Comey is due to testify before the Senate Intelligence Committee about Russia's alleged involvement in the U.S election and President Trump's alleged attempt to halt an investigation into former national security advisor Michael Flynn.

In other precious metals, silver futures rose 0.06% to $17.535 a troy ounce while

Copper lost 0.49% to $2.562, while natural gas traded at $2.986, down 0.43%.

twitterfacebook

How to Setup C# API Trading Platform

This is an Video tutorial just to Show you how you can Setup Trading Platform with the Help of C# API's


Download TWS IB : https://www.interactivebrokers.com/en/index.php?f=14099&ns=T#tws-software



Download TWS API : http://interactivebrokers.github.io/



After The Download of Software From Above Link Please Follow The Below Video For Proper Instruction's:



Oil prices fell on Tuesday as concerns about oversupply continued to weigh

oil

profitaddaweb.com.com-Wall Street futures pointed to a slightly lower open on Tuesday as investors returned from the Memorial Day weekend and the SP 500 and Nasdaq Composite hovered near record highs with market focus on economic reports later in the session.

The blue-chip Dow futures slipped 25 points, or 0.12%, at 6:55AM ET (10:55GMT), the SP 500 futures lost 4 points, or 0.16%, while the tech-heavy Nasdaq 100 futures dipped 4 points, or 0.06%.

On the data front, and with the Federal Reserve (Fed) set to announce its policy decision in about two weeks time, attention will likely focus on the core PCE price index out at 8:30AM ET (12:30GMT).

Generally considered to be the Fed's favorite inflation indicator, the annualized reading is expected to have dropped to 1.5% in April, from the prior 1.6% increase.

According to Fed Rate Monitor Tool, markets were currently pricing in the odds a June rate hike at around 76%, although some experts warned that weak inflation figures could still stay the central bank's hand.

The monthly jobs report is set for release on Friday and while the labor market is considered to be at full employment, analysts suggested to pay close attention to the annualized reading of wage inflation as the key point that the Fed will be watching before making its next move.

Also out at 8:30AM ET (12:30GMT), the Commerce Department is due to release data on personal income and expenditure, which is expected to show a pickup in spending and income.

Furthermore, the Conference Board is to report on consumer confidence for May at 10:00AM ET (14:00GMT).

The April report showed that U.S. consumer confidence declined after increasing sharply in the previous two months, but remained at strong levels, with focus remaining on when the soft data will eventually pass over to hard data readings.

Meanwhile,oil prices fell on Tuesday as concerns about oversupply continued to weigh, despite the American summer driving season getting underway.

Oil remained under pressure amid doubts over whether a decision by OPEC to extend a pledge to cut output until the end of the first quarter of 2018 will be enough to reduce a massive global supply glut.

crude oil futures fell 0.42% to $49.59 at 6:57AM ET (10:57GMT), while Brent oil traded down 0.72% to $52.25.