Meta api trade copier algofox
import os
import asyncio
from metaapi_cloud_sdk import MetaApi
from metaapi_cloud_sdk.clients.metaApi.tradeException import TradeException
from datetime import datetime
import time
from Algofox import *
from datetime import datetime
import pandas as pd
# Note: for information on how to use this example code please read https://metaapi.cloud/docs/client/usingCodeExamples
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
token = os.getenv('TOKEN') or 'eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI4MWZmYmVjOTJmMjliYjdmMGZlZDQ2MTEzZTYzMTk1MiIsInBlcm1pc3Npb25zIjpbXSwidG9rZW5JZCI6IjIwMjEwMjEzIiwiaW1wZXJzb25hdGVkIjpmYWxzZSwicmVhbFVzZXJJZCI6IjgxZmZiZWM5MmYyOWJiN2YwZmVkNDYxMTNlNjMxOTUyIiwiaWF0IjoxNjkxNTY5NjYzfQ.GNFKuKwZM-P-hrEFPPFWiyZkjSCdE-1Jge4fxuw5exYsp9HU1U8TvxoTotccO5eEN4Y-FDP2ZZBBqTPSarK8zds-PjTFlMW0X_ulKafqz566zu8MokrRi-iXb2y5pqAyprPXuCakcx1HnJsaIuMfoMq1nheTP8WjMWaQFcSZhTXSLuRr4Vqn9dMy4fRxdw5VIn2BzDgEj2rje0faK_bJsqT4-QKunJoekKuPXv2b0eQSZi2FLprK8j4ZfS3LcvxV13M1o3aHgPbNqWjRsLTFin7hEQ12tIqBKJqeQjS1THfcQ8zmUd1JthuXhTww8Y8uTo7Ha6YdOMZ7zy4k0d0hfH8lZlkIM4-7DHCq-wITakgFWfS7t4-rPox-x7RC57LljAGqV4Pmbz5Z2jyZ0CyMfVZQYZzIYPrFIElUdn2C4__mFEcYRK7eaqiQ2M1kRvukc0aYfvZpC57mrYzX4SnDeAcMdY1NZpqCxlAMWAGtp9P4baoNc1QE9r3uww5a8EaOb8ig1vsnzHdmxXhnRbiRFLWzqKf4m0-Jj2lTCtaYAE_VNAaRnIrxLCrMyZ4PbHfRlWXTtD1wjvWqsNnPqIR9cXPyvLZ4jBKka_LOQ4nrVpwuch1dRY3Xnep_WfVpDxwn1uHgJpW8ZNP01jMu23JoF1n36PMxZMHP63CLpHeWatQ'
accountId = os.getenv('ACCOUNT_ID') or 'ac29b9ec-d81e-45e7-95f4-d18070158555'
account = None
connection = None
terminal_state = None
history_storage=None
api=None
runnow=False
exit_order_ids = set()
order_log = set()
processed_orders = set()
last_processed_order_id = None # Initialize with None
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)
def delete_csv_contents(file_path):
with open(file_path, 'w') as csv_file:
csv_file.truncate(0)
print("Order logs File reset...")
async def test_meta_api_synchronization():
global account, connection, terminal_state,history_storage,runnow,api
api = MetaApi(token)
try:
account = await api.metatrader_account_api.get_account(accountId)
initial_state = account.state
deployed_states = ['DEPLOYING', 'DEPLOYED']
if initial_state not in deployed_states:
print('Deploying account')
await account.deploy()
print('Waiting for API server to connect to broker (may take couple of minutes)')
await account.wait_connected()
# connect to MetaApi API
connection = account.get_streaming_connection()
await connection.connect()
# wait until terminal state synchronized to the local state
print('Waiting for SDK to synchronize to terminal state (may take some time depending on your history size)')
await connection.wait_synchronized()
# print('Testing terminal state access')
terminal_state = connection.terminal_state
await connection.wait_synchronized()
# print('connected:', terminal_state.connected)
# print('connected to broker:', terminal_state.connected_to_broker)
# print('account information:', terminal_state.account_information)
history_storage = connection.history_storage
runnow = True
delete_csv_contents("OrderLog.txt")
except Exception as err:
print(api.format_error(err))
# exit()
async def check_order():
global account, history_storage, order_log, terminal_state, connection, api,last_processed_order_id,processed_orders,exit_order_ids
order_executed = False
try:
history_storage = connection.history_storage
await connection.wait_synchronized()
terminal_state = connection.terminal_state
await connection.wait_synchronized()
present_day_orders = history_storage.get_history_orders_by_time_range(
datetime.fromtimestamp(datetime.now().timestamp() - 24 * 60 * 60), datetime.now())
with open("OrderLog.txt", "a") as log_file:
for order in present_day_orders:
order_id = order["id"]
order_time = order["time"].strftime("%Y-%m-%d %H:%M:%S")
order_state = order["state"]
order_type = order["type"]
order_symbol = order["symbol"]
order_quantity = order.get("volume", 0)
# Check if this order has already been logged
if order_id in order_log:
continue
order_log.add(order_id)
log_message = f"{order_time} Order for {order_type} {order_symbol} for {order_quantity} Quantity is {order_state}"
log_message += f", Exchange order Id {order_id}"
log_file.write(log_message + "\n")
response = terminal_state.price(symbol='EURUSD')
broker_time = datetime.strptime(response['brokerTime'], '%Y-%m-%d %H:%M:%S.%f')
formatted_broker_time = broker_time.strftime('%m-%d %H:%M')
# entry
# positions = terminal_state.positions
symbols = read_symbols_from_csv()
for position in terminal_state.positions:
position_broker_time = datetime.strptime(position['brokerTime'], '%Y-%m-%d %H:%M:%S.%f')
formatted_position_broker_time = position_broker_time.strftime('%m-%d %H:%M')
if formatted_position_broker_time == formatted_broker_time:
position_id = position["id"]
if position_id not in processed_orders: # Check if order ID has been processed already
if last_processed_order_id is None or position_id != last_processed_order_id:
processed_orders.add(position_id) # Add order ID to the processed_orders set
position_type = position["type"]
position_symbol = position["symbol"]
position_quantity = position.get("volume", 0)
position_state = position["reason"]
position_price=position["openPrice"]
print("position_price= ", position_price)
if position_symbol in read_symbols_from_csv():
# Print log message
log_message = f"{formatted_position_broker_time} Position for {position_type} {position_symbol} for {position_quantity} Quantity is {position_state}"
log_message += f", Position Id {position_id}"
print(log_message)
# Save details from get_all_detail_csv() function
all_details = get_all_detail_csv()
for detail in all_details:
if detail['Symbol'] == position_symbol:
exchange_symbol = detail['ExchangeSymbol']
strategy_tag = detail['StrategyTag']
segment = detail['Segment']
expiry = detail['EXPIERY']
contract_type = detail['CONTRAC TYPE']
strike = detail['STRIKE']
product_type = detail['ProductType']
# ... use the details as needed ...
print("position_price= ", position_price)
if not order_executed and position_type=="POSITION_TYPE_BUY":
Buy_order_algofox(symbol=exchange_symbol,quantity=position_quantity,
instrumentType=segment,direction="BUY",product=product_type,
strategy=strategy_tag,order_typ="MARKET",price=position_price,username=username,password=password,role=role)
order_executed=True
break
if not order_executed and position_type=="POSITION_TYPE_SELL":
Short_order_algofox(symbol=exchange_symbol, quantity=position_quantity,
instrumentType=segment, direction="SHORT", product=product_type,
strategy=strategy_tag, order_typ="MARKET", price=position_price,
username=username, password=password, role=role)
order_executed = True
break
last_processed_order_id = position_id
last_order_detail = history_storage.deals[-1:]
last_order_detail_time=last_order_detail[0]["brokerTime"]
last_order_detail_time = datetime.strptime(last_order_detail_time, '%Y-%m-%d %H:%M:%S.%f')
last_order_detail_time = last_order_detail_time.strftime('%m-%d %H:%M')
last_order_detail_entrytype=last_order_detail[0]["entryType"]
# print("last_order_detail_time= ",last_order_detail_time)
broker_time = datetime.strptime(response['brokerTime'], '%Y-%m-%d %H:%M:%S.%f')
formatted_broker_time = broker_time.strftime('%m-%d %H:%M')
# exit
if formatted_broker_time == last_order_detail_time and last_order_detail_entrytype=="DEAL_ENTRY_OUT":
last_order_type = last_order_detail[0]["type"]
last_order_id = last_order_detail[0]["id"]
exit_position_symbol = last_order_detail[0]["symbol"]
exit_position_quantity = last_order_detail[0].get("volume", 0)
exit_position_state = last_order_detail[0]["reason"]
if exit_position_symbol in read_symbols_from_csv():
all_details = get_all_detail_csv()
for detail in all_details:
if detail['Symbol'] == exit_position_symbol:
exchange_symbol = detail['ExchangeSymbol']
strategy_tag = detail['StrategyTag']
segment = detail['Segment']
expiry = detail['EXPIERY']
contract_type = detail['CONTRAC TYPE']
strike = detail['STRIKE']
product_type = detail['ProductType']
if last_order_type == 'DEAL_TYPE_SELL' and last_order_id not in exit_order_ids:
exit_order_ids.add(last_order_id)
exit_position_symbol = last_order_detail[0]["symbol"]
exit_position_quantity = last_order_detail[0].get("volume", 0)
exit_position_state = last_order_detail[0]["reason"]
exit_position_price=last_order_detail[0]["price"]
print("exit_position_price= ", exit_position_price)
exit_log_message = f"{last_order_detail_time} Exit SELL for {exit_position_symbol} for {exit_position_quantity} Quantity is {exit_position_state}"
exit_log_message += f", Position Id {last_order_id}"
Sell_order_algofox(symbol=exchange_symbol, quantity=exit_position_quantity, instrumentType=segment,
direction="SELL", product=product_type, strategy=strategy_tag, order_typ="MARKET",
price=exit_position_price, username=username, password=password, role=role)
print(exit_log_message)
if last_order_type == 'DEAL_TYPE_BUY' and last_order_id not in exit_order_ids:
exit_order_ids.add(last_order_id)
exit_position_symbol = last_order_detail[0]["symbol"]
exit_position_quantity = last_order_detail[0].get("volume", 0)
exit_position_state = last_order_detail[0]["reason"]
exit_position_price = last_order_detail[0]["price"]
print("exit_position_price= ",exit_position_price)
exit_log_message = f"{last_order_detail_time} Exit BUY for {exit_position_symbol} for {exit_position_quantity} Quantity is {exit_position_state}"
exit_log_message += f", Position Id {last_order_id}"
Cover_order_algofox(symbol=exchange_symbol, quantity=exit_position_quantity, instrumentType=segment,
direction="COVER", product=product_type, strategy=strategy_tag,
order_typ="MARKET",
price=exit_position_price, username=username, password=password, role=role)
print(exit_log_message)
except Exception as err:
print("Error in check_order:", err)
async def main():
while runnow:
await check_order()
await asyncio.sleep(1)
async def main_entry():
await test_meta_api_synchronization()
await main()
loop = asyncio.get_event_loop()
loop.run_until_complete(main_entry())
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
Comments
Post a Comment