xts trade copier with authentication page and optidx , eq integrated (exception haneling is also done )

 from flask import Flask, render_template, redirect, url_for, flash, session

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
import atexit
from Connect import XTSConnect
import pandas as pd
from datetime import datetime
from Algofox import *
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SelectField, SubmitField
from wtforms.validators import DataRequired
import secrets
from threading import Thread

from Exception import XTSInputException

class AuthenticationForm(FlaskForm):
# XTS Detail
userId = StringField('UserId', validators=[DataRequired()])
apiKey = StringField('API KEY', validators=[DataRequired()])
apiSecret = StringField('API SECRET', validators=[DataRequired()])

# Algofox details
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
role = SelectField('Role', choices=[('admin', 'Admin'), ('user', 'User')], validators=[DataRequired()])


authenticated=False
id = "11013144"
# API_KEY = "082144eb6500c64b37aa90"
# API_SECRET = "Vnsv775#57"
source = "WEBAPI"
XTS_API_BASE_URL = "https://xts-api.trading"


app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_hex(16)
order_logs = [] # Variable to store the order logs


processed_logs = set() # Set to keep track of processed logs
processed_orders = set() # Set to keep track of processed orders

userId=None
apiKey=None
apiSecret=None
username=None
password=None
role=None
xt=None
# xt = XTSConnect(API_KEY, API_SECRET, source)
# response = xt.interactive_login()

@app.route('/', methods=['GET', 'POST'])
def authentication():
global authenticated,xt
form = AuthenticationForm()

if form.validate_on_submit():
# Access form data
userId = form.userId.data
apiKey = form.apiKey.data
apiSecret = form.apiSecret.data
username = form.username.data
password = form.password.data
role = form.role.data

try:
# Create XTSConnect instance
xt = XTSConnect(apiKey, apiSecret, source)

# Perform authentication
response = xt.interactive_login()

if response['type'] == 'success':
# Authentication successful
authenticated=True
print("Authentication successful")

# Store the form data in session
session['form_data'] = {
'userId': userId,
'apiKey': apiKey,
'apiSecret': apiSecret,
'username': username,
'password': password,
'role': role
}

# Redirect to index.html
return redirect(url_for('index'))
else:
# Authentication failed
print("Authentication failed")
flash("Authentication failed. Please check your XTS details.")

except XTSInputException as e:
# XTS input exception raised
print("XTS input exception:", str("Wrong Credential XTS"))
flash("XTS details are incorrect. Please check your XTS details.")

except Exception as e:
# Other exception occurred
print("An error occurred:", str("Wrong Credential XTS"))
flash("An error occurred during authentication.")

return render_template('authentication.html', form=form)


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

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



printed_orders = []

def check_api_response():
global authenticated,xt
if authenticated:
with open('OrderLogs.txt', 'r') as f:
existing_logs = set(f.read().splitlines())

orderbook = xt.get_order_book()

try:
results = orderbook.get('result', [])



with open('OrderLogs.txt', 'a+') as f:
for order in results:
AppOrderID = order.get('AppOrderID')
if AppOrderID not in processed_orders and AppOrderID not in processed_logs:
OrderGeneratedDateTime = order.get('OrderGeneratedDateTime')
TradingSymbol = order.get('TradingSymbol')
OrderQuantity = order.get('OrderQuantity')
OrderStatus = order.get('OrderStatus')
OrderSide = order.get('OrderSide')
ProductType = order.get('ProductType')

output = f"{OrderGeneratedDateTime} Order for {OrderSide} {TradingSymbol} {ProductType} for {OrderQuantity} Quantity is {OrderStatus}, Exchange order Id {AppOrderID}"
if output not in existing_logs:
f.write(output + '\n') # Append the output to the OrderLogs.txt file
processed_orders.add(AppOrderID) # Add the AppOrderID to the set of processed orders
processed_logs.add(AppOrderID) # Add the AppOrderID to the set of processed logs

current_time = datetime.now().strftime("%H:%M")
symbols = read_symbols_from_csv() # Read symbols from the CSV file
for order in results:
OrderStatus = order.get('OrderStatus')
OrderGeneratedDateTime = order.get('OrderGeneratedDateTime')
TradingSymbol = order.get('TradingSymbol')
OrderQuantity = order.get('OrderQuantity')
AppOrderID = order.get('AppOrderID')
OrderSide = order.get('OrderSide')
ProductType = order.get('ProductType')
OrderType=order.get('OrderType')
OrderPrice=order.get('OrderPrice')

order_time = datetime.strptime(OrderGeneratedDateTime, "%d-%m-%Y %H:%M:%S").strftime("%H:%M")
ssymbols=get_all_detail_csv()
if OrderStatus == 'Filled' and order_time == current_time and AppOrderID not in printed_orders:
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']


if TradingSymbol in symbols: # Check if the trading symbol is in the symbol list
output = f"{OrderGeneratedDateTime} Order for {OrderSide} {TradingSymbol} {ProductType} for {OrderQuantity} Quantity is {OrderStatus}, Exchange order Id {AppOrderID}"
print(output)
printed_orders.append(AppOrderID) # Add the AppOrderID to the printed orders list
netpositionresponce = xt.get_position_netwise()

if Segment == "EQ":
for position in netpositionresponce['result']['positionList']:
if position['TradingSymbol'] == TradingSymbol:
for child_position in position['childPositions']:
if child_position['TradingSymbol'] == TradingSymbol:
symbol_net_pos = child_position['Quantity']
print(symbol_net_pos)
if OrderSide == "BUY":
old_net_pos = int(symbol_net_pos) - int(OrderQuantity)
if OrderSide == "SELL":
old_net_pos = int(symbol_net_pos) + int(OrderQuantity)
print(old_net_pos)

if Segment == "OPTIDX":
for position in netpositionresponce['result']['positionList']:
if position['TradingSymbol'] == TradingSymbol:
symbol_net_pos = position['Quantity']
print(symbol_net_pos)
if OrderSide == "BUY":
old_net_pos = int(symbol_net_pos) - int(OrderQuantity)
if OrderSide == "SELL":
old_net_pos = int(symbol_net_pos) + int(OrderQuantity)

print(old_net_pos)
output = f"{OrderGeneratedDateTime} Order for {OrderSide} {TradingSymbol} {ProductType} for {OrderQuantity} Quantity is {OrderStatus}, Exchange order Id {AppOrderID}"
print(output)
printed_orders.append(AppOrderID) # Add the AppOrderID to the printed orders list
break


order_executed = False
if not order_executed and OrderSide == "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=OrderQuantity,instrumentType=Segment,direction=OrderSide,price=OrderPrice,product=product,order_typ=OrderType,strategy=StrategyTag)
if Segment == "OPTIDX":
sname=f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Buy_order_algofox(symbol=sname,quantity=OrderQuantity,instrumentType=Segment,direction=OrderSide,price=OrderPrice,product=product,order_typ=OrderType,strategy=StrategyTag)
if not order_executed and OrderSide == "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=OrderQuantity,
instrumentType=Segment, direction="SHORT",price=OrderPrice, product=product,
order_typ=OrderType, strategy=StrategyTag)
if Segment == "OPTIDX":
sname=f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Short_order_algofox(symbol=sname, quantity=OrderQuantity,
instrumentType=Segment, direction="SHORT",
price=OrderPrice, product=product,
order_typ=OrderType, strategy=StrategyTag)

if not order_executed and OrderSide == "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=OrderQuantity,
instrumentType=Segment, direction="COVER",price=OrderPrice, product=product,
order_typ=OrderType, strategy=StrategyTag)
if Segment == "OPTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Cover_order_algofox(symbol=sname, quantity=OrderQuantity,
instrumentType=Segment, direction="COVER",
price=OrderPrice, product=product,
order_typ=OrderType, strategy=StrategyTag)
if not order_executed and OrderSide == "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=OrderQuantity,
instrumentType=Segment, direction="SELL",price=OrderPrice, product=product,
order_typ=OrderType, strategy=StrategyTag)
if Segment == "OPTIDX":
sname = f"{ExchangeSymbol}|{str(expiery)}|{str(strike)}|{contract}"
Sell_order_algofox(symbol=sname, quantity=OrderQuantity,
instrumentType=Segment, direction="SELL",
price=OrderPrice, product=product,
order_typ=OrderType, strategy=StrategyTag)


except KeyError:
pass
except Exception as e:
print("An error occurred while processing the order book:")
print(str(e))
print(orderbook) # Print the orderbook response for inspection


def run_check_api_response():
xt = XTSConnect(apiKey, apiSecret, source)
response = xt.interactive_login()

scheduler = BackgroundScheduler()
scheduler.add_job(check_api_response, args=(xt,), trigger=IntervalTrigger(seconds=1))
scheduler.start()
atexit.register(lambda: scheduler.shutdown())


@app.route('/index')
def index():
logs = read_order_logs()
return render_template('index.html', logs=logs)


def read_order_logs():
with open('OrderLogs.txt', 'r') as f:
logs = f.read().splitlines()
return logs


if __name__ == '__main__':
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(
func=check_api_response,
trigger=IntervalTrigger(seconds=1),
id='check_api_response_job',
name='Check API Response',
replace_existing=True
)
atexit.register(lambda: scheduler.shutdown())

app.run(debug=True)

Comments

Popular posts from this blog

MQL5 : Add time to current time in mins

MQL5: Closed order detail