xts trade copier 10thjuly version , this version can send eqity order to algofox

 from flask import Flask, render_template

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 *
id = "11013144"
API_KEY = "082144eb6500c64b37aa90"
API_SECRET = "Vnsv775#57"
source = "WEBAPI"
XTS_API_BASE_URL = "https://xts-api.trading"

xt = XTSConnect(API_KEY, API_SECRET, source)
app = Flask(__name__)
order_logs = [] # Variable to store the order logs
response = xt.interactive_login()

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

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():

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()
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']
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(ExchangeSymbol)
# print(strike)
# print(expiery)
# print(contract)
# print(Segment)

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


app = Flask(__name__)

@app.route('/')
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.add_job(check_api_response, IntervalTrigger(seconds=1))
scheduler.start()
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