Zerodha trade copier compleate code (31JUL2023)

import time
import pandas as pd
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from kiteconnect import KiteConnect
from selenium import webdriver
from selenium.webdriver.common.by import By
import pyotp
from Algofox import *
from flask import Flask, render_template
from urllib.parse import urlparse, parse_qs
# Create the Flask application
app = Flask(__name__)


print("Hello Traders Please Provide Us following Information So that We can start your Zerodha Trade Copier:")
print("Algofox Credential...")
url = input("Enter your Algofox URL = https//")
username= input("Please Provide Algofox UserName : ")
password= input("Please Provide Algofox Password : ")
role= input("Please Provide Algofox role (Accepted values USER/ADMIN) : ")
createurl(url)

loginresult=login_algpfox(username=username, password=password, role=role)


if loginresult!=200:
print("Algofoz credential wrong, shutdown down Trde Copier, please provide correct details and run again otherwise program will not work correctly ...")
time.sleep(10000)




print("Getting Zerodha Credential from ZerodhaCredentials file ...")
# api_key= input("Please Provide Your Zerodha Api Key: ")
# api_secret= input("Please Provide Your Zerodha Api Secret: ")
# USERID= input("Please Provide Your Zerodha User Id: ")
# Password= input("Please Provide Your Zerodha User Password: ")
# FAKEY= input("Please Provide Your Zerodha User 2fakey: ")






def get_zerodha_credentials():
credentials = {}

try:
df = pd.read_csv('ZerodhaCredentials.csv')
for index, row in df.iterrows():
title = row['Title']
value = row['Value']
credentials[title] = value
except pd.errors.EmptyDataError:
print("The CSV file is empty or has no data.")
except FileNotFoundError:
print("The CSV file was not found.")
except Exception as e:
print("An error occurred while reading the CSV file:", str(e))

return credentials

# Call the function to get the credentials as a dictionary
credentials_dict = get_zerodha_credentials()

# Assign the values to the global variables
api_key = credentials_dict.get('ZerodhaApiKey')
api_secret = credentials_dict.get('ZerodhaApiSecret')
USERID = credentials_dict.get('ZerodhaUserId')
Password = credentials_dict.get('ZerodhaPassword')
FAKEY = credentials_dict.get('Zerodha2fa')


print(api_key)
print(api_secret)
print(USERID)
print(Password)
print(FAKEY)
print("Processing...")






#
# api_key = "siwn2k7qp7q0wjg2"
# api_secret = "30gnuktshbgss8sxscz755iyhrejhuya"
# USERID = "PXZ279"
# Password = "kkk111222"
# FAKEY = "QYWCVXD7IGJP2KNAID7VRVQM3J445KJ2"

kite = None
processed_order_ids = set()

def delete_file_contents(file_path):
try:
with open(file_path, 'w') as file:
file.truncate(0)
print(f"Successfully deleted all contents of {file_path}.")
except IOError:
print(f"Error: Failed to delete contents of {file_path}.")

def autologin():
try:
print("Autologin Initiated")
global kite
token_path = "api_key.txt"
key_secret = api_secret # Function to retrieve API key and secret

kite = KiteConnect(api_key=api_key)

service = Service('./chromedriver')
service.start()

options = Options()
options.add_argument('--headless')

driver = webdriver.Remote(service.service_url, options=options)
driver.get(kite.login_url())
driver.implicitly_wait(10)

# Find and enter username
username = driver.find_element(By.XPATH, '//*[@id="userid"]')
username.send_keys(USERID)

# Find and enter password
password = driver.find_element(By.XPATH, '//*[@id="password"]')
password.send_keys(Password)

# Click on login button
login_button = driver.find_element(By.XPATH, '//*[@id="container"]/div/div/div[2]/form/div[4]/button')
login_button.click()

# Wait for page to load and handle PIN or two-factor authentication
time.sleep(6)
pin = driver.find_element(By.XPATH, '//*[@id="container"]/div[2]/div/div[2]/form/div[1]/input')
totp = pyotp.TOTP(FAKEY)
token = totp.now()
pin.send_keys(token)

time.sleep(6)

url = driver.current_url
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
request_token = query_params.get('request_token', [None])[0]



print(request_token)
with open('request_token.txt', 'w') as file:
file.write(request_token)

driver.quit()

# Read request token and generate access token
# request_token = open("request_token.txt", 'r').read()

kite = KiteConnect(api_key=api_key)
data = kite.generate_session(request_token, api_secret)
access_token = data["access_token"]
kite.positions()


# Save the access token
with open('access_token.txt', 'w') as file:
file.write(access_token)

print("Auto Login Completed...")
delete_file_contents("OrderLogs.txt")

except Exception as e:
print("Auto Login Failed:", e)
print("Please close application and run again")


def check_orders():
global kite, processed_order_ids
orders = kite.orders()

with open('OrderLogs.txt', 'a') as file:
for order in orders:
order_id = order['order_id']
if order_id not in processed_order_ids:
processed_order_ids.add(order_id) # Add the order ID to the set

timestamp = order['order_timestamp']
transaction_type = order['transaction_type']
tradingsymbol = order['tradingsymbol']
product = order['product']
quantity = order['quantity']
status = order['status']
log_message = f"{timestamp} Order for {transaction_type} {tradingsymbol} {product} for {quantity} Quantity is {status}, Exchange order Id {order_id}\n"
file.write(log_message)

process_orders(orders)


order_ids = set()
def process_orders(orders):
# To store unique order IDs
symbols = read_symbols_from_csv() # Read symbols from TradeSettings.csv
order_executed = False
# print(f'After Calculation net pos = {order_executed}')

for order in orders:
order_id = order['order_id']
tradingsymbol = order['tradingsymbol']
timestamp = order['order_timestamp']
current_time = datetime.now()
status = order['status']

# Check if the order is complete, if the order placement time matches the current time (hour and minute),
# and if the tradingsymbol is present in TradeSettings.csv
if (
status == 'COMPLETE'
and timestamp.hour == current_time.hour
and timestamp.minute == current_time.minute
and tradingsymbol in symbols
):
# Check if the order ID is already processed to avoid duplication
if order_id not in order_ids:
order_ids.add(order_id) # Add the order ID to the set

transaction_type = order['transaction_type']
product = order['product']
quantity = order['quantity']
order_type = order['order_type']
order_price = order['price']

log_message = f"Order ID: {order_id}\n"
log_message += f"Timestamp: {timestamp}\n"
log_message += f"Order Details: Order for {transaction_type} {tradingsymbol} {product} for {quantity} Quantity is {status}, Exchange order Id {order_id}\n"
print(log_message)
ssymbols = get_all_detail_csv()
netpositionresponce = kite.positions()
# print(netpositionresponce)
for symbol in ssymbols:
if symbol['Symbol'] == tradingsymbol:
ExchangeSymbol = symbol['ExchangeSymbol']
StrategyTag = symbol['StrategyTag']
Segment = symbol['Segment']
product = symbol['ProductType']
strike = symbol['STRIKE']
contract = symbol['CONTRAC TYPE']
expiery = symbol['EXPIERY']

# print(f'After Calculation net pos = {order_executed},transaction_type{transaction_type}')

if Segment == "EQ":
for item in netpositionresponce['net']:
if item['tradingsymbol'] == tradingsymbol:
symbol_net_pos = item['quantity']

if transaction_type == "BUY":
old_net_pos = int(symbol_net_pos) - int(quantity)
if transaction_type == "SELL":
old_net_pos = int(symbol_net_pos) + int(quantity)


if Segment == "OPTIDX":
for item in netpositionresponce['net']:
if item['tradingsymbol'] == tradingsymbol:
symbol_net_pos = item['quantity']

if transaction_type == "BUY":
old_net_pos = int(symbol_net_pos) - int(quantity)
if transaction_type == "SELL":
old_net_pos = int(symbol_net_pos) + int(quantity)

if Segment == "FUTIDX":
for item in netpositionresponce['net']:
if item['tradingsymbol'] == tradingsymbol:
symbol_net_pos = item['quantity']

if transaction_type == "BUY":
old_net_pos = int(symbol_net_pos) - int(quantity)
if transaction_type == "SELL":
old_net_pos = int(symbol_net_pos) + int(quantity)

if Segment == "FUTSTK":
for item in netpositionresponce['net']:
if item['tradingsymbol'] == tradingsymbol:
symbol_net_pos = item['quantity']

if transaction_type == "BUY":
old_net_pos = int(symbol_net_pos) - int(quantity)
if transaction_type == "SELL":
old_net_pos = int(symbol_net_pos) + int(quantity)

if Segment == "OPTSTK":
for item in netpositionresponce['net']:
if item['tradingsymbol'] == tradingsymbol:
symbol_net_pos = item['quantity']

if transaction_type == "BUY":
old_net_pos = int(symbol_net_pos) - int(quantity)
if transaction_type == "SELL":
old_net_pos = int(symbol_net_pos) + int(quantity)

# print(f'After Calculation net pos = {order_executed},transaction_type{transaction_type},old_net_pos= {old_net_pos}, newnet pos ={symbol_net_pos}')
if not order_executed and transaction_type == "BUY" and int(old_net_pos) >= 0:
print(f"Sending Buy Order @ {tradingsymbol}")
order_executed = True
if Segment == "EQ":
Buy_order_algofox(symbol=ExchangeSymbol, quantity=quantity, instrumentType=Segment,
direction=transaction_type, price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "OPTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Buy_order_algofox(symbol=sname, quantity=quantity, instrumentType=Segment,
direction=transaction_type, price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "FUTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Buy_order_algofox(symbol=sname, quantity=quantity, instrumentType=Segment,
direction=transaction_type, price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break
if Segment == "FUTSTK":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Buy_order_algofox(symbol=sname, quantity=quantity, instrumentType=Segment,
direction=transaction_type, price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "OPTSTK":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Buy_order_algofox(symbol=sname, quantity=quantity, instrumentType=Segment,
direction=transaction_type, price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if not order_executed and transaction_type == "SELL" and int(old_net_pos) <= 0:
print(f"Sending Short Order @ {tradingsymbol}")
order_executed = True
if Segment == "EQ":
Short_order_algofox(symbol=ExchangeSymbol, quantity=quantity,
instrumentType=Segment, direction="SHORT",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break
if Segment == "OPTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Short_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SHORT",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "FUTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Short_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SHORT",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "FUTSTK":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Short_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SHORT",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "OPTSTK":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Short_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SHORT",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if not order_executed and transaction_type == "BUY" and int(old_net_pos)< 0:
print(f"Sending Cover Order @ {tradingsymbol}")
order_executed = True
if Segment == "EQ":
Cover_order_algofox(symbol=ExchangeSymbol, quantity=quantity,
instrumentType=Segment, direction="COVER",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "OPTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Cover_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="COVER",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "FUTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Cover_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="COVER",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "FUTSTK":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Cover_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="COVER",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "OPTSTK":
sname=f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Cover_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="COVER",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if not order_executed and transaction_type == "SELL" and int(old_net_pos) > 0:
print(f"Sending Sell Order @ {tradingsymbol}")
order_executed = True
if Segment == "EQ":
Sell_order_algofox(symbol=ExchangeSymbol, quantity=quantity,
instrumentType=Segment, direction="SELL",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "OPTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Sell_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SELL",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "FUTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Sell_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SELL",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "FUTSTK":
sname = f"{ExchangeSymbol}|{str(expiery)}"
Sell_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SELL",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break

if Segment == "OPTSTK":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Sell_order_algofox(symbol=sname, quantity=quantity,
instrumentType=Segment, direction="SELL",price=order_price, product=product,
order_typ=order_type, strategy=StrategyTag,username=username,password=password,role=role)
break


# Print the order details on the Python console




def get_all_detail_csv():
symbols = []

try:
df = pd.read_csv('TradeSettings.csv')
symbols = df.to_dict(orient='records')
except pd.errors.EmptyDataError:
print("The CSV file is empty or has no data.")
except FileNotFoundError:
print("The CSV file was not found.")
except Exception as e:
print("An error occurred while reading the CSV file:", str(e))

return symbols


def read_symbols_from_csv():
symbols = []

try:
df = pd.read_csv('TradeSettings.csv', usecols=['Symbol'])
symbols = df['Symbol'].tolist()
except pd.errors.EmptyDataError:
print("The CSV file is empty or has no data.")
except FileNotFoundError:
print("The CSV file was not found.")
except Exception as e:
print("An error occurred while reading the CSV file:", str(e))

return symbols


@app.route('/')
def index():
with open('OrderLogs.txt', 'r') as file:
order_logs = file.read()
return render_template('index.html', order_logs=order_logs)


if __name__ == '__main__':
autologin()

# Create a scheduler and add the job
scheduler = BackgroundScheduler()
scheduler.add_job(check_orders, 'interval', seconds=1)
scheduler.start()

# Start the Flask app
app.run()

Comments

Popular posts from this blog

MQL5 : Add time to current time in mins

MQL5: Closed order detail