Skip to content

Instantly share code, notes, and snippets.

@ajinasokan
Last active October 7, 2022 09:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save ajinasokan/267d68c9f61e3e4ea11681c0ec4e707d to your computer and use it in GitHub Desktop.
Save ajinasokan/267d68c9f61e3e4ea11681c0ec4e707d to your computer and use it in GitHub Desktop.
KiteConnect postback example
'''
Hi traders,
Here is a simple generic example for implementing a postback mechanism. You can host this in a remote server or in your local server itself.
Run Locally
===========
1. Install ngrok from https://ngrok.com/
This is a simple free tool to tunnel your local server and a public domain given by ngrok. Follow the simple tutorial in their website to set it up.
2. Run python app and ngrok tunnel
Save the following code to "app.py"
Run the script by "sudo python app.py"
Run ngrok tunnel by "ngrok http 80"
3. Update postback url in Kite Connect dashboard
In the ngrok command line interface you can see a url in the format "https://<randomstring>.ngrok.io". Copy that url.
Go to your app's setup page and paste the url in "Postback URL" field as "https://<randomstring>.ngrok.io/post"
Click on save
You will have to do this every time you restart ngrok. Because in their free plan the url is not exclusive.
4. Test
Try some trades from your app. You can see logs in your ngrok interface.
Goto "https://<randomstring>.ngrok.io" in your browser. You can see entire log of the day
Run in Server
===========
1. Setup
Save the following code to "app.py"
Save your ssl certificates as "cert.pem" and "key.pem"
Modify port number to 443 and add ssl_context param to enable https
Run the script as "sudo python app.py"
2. Update postback url in Kite Connect dashboard
Go to your app's setup page and paste the url in "Postback URL" field as "https://<yourdomain>/post"
Click on save
3. Test
Try some trades from your app.
Goto "https://<yourdomain>/" in your browser. You can see entire log of the day
'''
from flask import Flask, request
import os
import datetime
app = Flask(__name__)
def log_name():
# logs will be saved in files with current date
return datetime.datetime.now().strftime("%Y-%m-%d") + '.txt'
@app.route('/post', methods=['POST'])
def post():
# post back json data will be inside request.get_data()
# as an example here it is being stored to a file
f = open(log_name(),'a+')
f.write(str(request.get_data())+'\n')
f.close()
return 'done'
@app.route('/')
def index():
# show the contents of todays log file
if not os.path.exists(log_name()):
open(log_name(), 'a+').close()
return open(log_name()).read()
app.run(debug=True, host='0.0.0.0', port=80)
# if you have your own ssl certificates place them in this directory
# use this statement to enable https for postbacks
# app.run(debug=True, '0.0.0.0', port=443, ssl_context=('cert.pem', 'key.pem'))
@urrakesh2053
Copy link

Hi @ajinasokan,

This app.py is showing all GET/POST line entries but nowhere order details are fetched so that it can be used in python scripts for Algorithm trading.
Log file is totally empty...

I can seen json details on a link mentioned in ngrok documentation to see details of order execution. but need to capture it into my main python script. Please help me in this.

screenshot from 2017-12-26 23 34 15

@ajinasokan
Copy link
Author

@viks555
Copy link

viks555 commented Jul 28, 2021

HI @ajinasoka.. i am curious to know where is log saved on system

def log_name():
# logs will be saved in files with current date
return datetime.datetime.now().strftime("%Y-%m-%d") + '.txt'

As per the above code what is the location of the saved file

@ajinasokan
Copy link
Author

@viks555 It will be in the directory from which the python script was executed.

@gmdraj2000
Copy link

Hi,
please help..

When i try running the script it gives below error

C:\Users\Administrator.spyder-py3>python app.py

  • Serving Flask app "app" (lazy loading)
  • Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: on
    Traceback (most recent call last):
    File "app.py", line 75, in
    app.run(debug=True, host='0.0.0.0', port=80)
    File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 990, in run
    run_simple(host, port, self, **options)
    File "C:\ProgramData\Anaconda3\lib\site-packages\werkzeug\serving.py", line 1030, in run_simple
    s.bind(server_address)
    OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

@priyankt
Copy link

priyankt commented Feb 2, 2022

You can use https://telebit.cloud/ to create tunnel. It provides fixed url for tunneling. No need to change postback url every time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment