Skip to content

Instantly share code, notes, and snippets.

@kasper747
Created April 21, 2023 15:28
Show Gist options
  • Save kasper747/83adc8e88bd6cb8bd9b0cbf389956071 to your computer and use it in GitHub Desktop.
Save kasper747/83adc8e88bd6cb8bd9b0cbf389956071 to your computer and use it in GitHub Desktop.
'''
I understand your concerns. Here's an updated version of the requirements list to address the connection issue:
The script starts by attempting to connect to the IB Gateway.
If the connection is unsuccessful, the script will retry multiple times (e.g., every 30 seconds) for a specified duration (e.g., 3 minutes) before notifying the user via Telegram.
During the entire time the script is running, it should continuously check the connection to the IB Gateway.
If the connection is lost at any point, the script should try to reconnect multiple times (e.g., 5 times) and then notify the user if it is unable to reconnect.
Every day at 3:30 AM New York time, the script checks a Telegram channel for a specific message ("I'm here") sent between 1:00 AM and 3:30 AM.
If the message is not found, the script sends a signal to the IB Gateway to cancel all active orders.
The script notifies the user via Telegram that the orders have been canceled.
This updated list of requirements includes the continuous connection check and retry mechanism for the initial connection and reconnection attempts.
'''
import asyncio
from datetime import datetime, timedelta
from pytz import timezone
from ib_insync import IB
import time
import datetime
import pytz
import telethon.sync
# import telethon
from telethon import TelegramClient
from ib_insync import IB
import pytz
from datetime import datetime
import asyncio
DEBUG = True
# Import necessary Telegram library
ny_time = timezone('America/New_York')
ib_api = IB()
# connect to the Telegram servers and authenticate with your bot token
client_bot = TelegramClient('session_name', api_id, api_hash)
client_bot.start(bot_token=bot_token)
client_bot.send_message(channel_name, 'I love you')
# connect to the Telegram servers and authenticate with your phone number or bot token
client_human = TelegramClient('anon', api_id, api_hash)
client_human.start(phone=Phone_Number)
client_human.send_message(channel_name, 'I love you too')
async def connect_to_ib_gateway(ib_api):
'''
Connect to IB Gateway and retry if the connection is lost.
'''
for _ in range(6): # Retry connection 6 times
try:
print("Connection to IB Gateway is lost. Reconnecting...")
await ib_api.connectAsync('127.0.0.1', 4001, clientId=5)
print(f"Reconnected: {ib_api.isConnected()}")
break
except:
print("Could not connect. Error during connection.")
await asyncio.sleep(5) # Wait for 30 seconds before retrying
else:
print("Failed to connect to IB Gateway after multiple attempts.")
# Send a Telegram message to notify about the connection failure
# send_telegram_message("Failed to connect to IB Gateway after multiple attempts.")
return None
return ib_api
# ib_api = asyncio.get_event_loop().run_until_complete(connect_to_ib_gateway(ib_api))
async def check_connection(ib_api):
'''
Check if the connection to IB Gateway is still active.
And reconnect if the connection is lost.
'''
while True:
await asyncio.sleep(5) # Check the connection every 60 seconds
if not ib_api.isConnected():
print("Initiating connect_to_ib_gateway")
ib_api = await connect_to_ib_gateway(ib_api)
else:
print("Connection to IB Gateway is still active.")
async def cancel_orders_if_no_message():
"""
The function cancels the orders if no message is found in the Telegram channel.
The function runs indefinitely, checking for messages in the Telegram channel every minute. If no message is found between 3:30 AM and 4:00 AM, the function cancels all active orders and notifies the user via Telegram.
Args:
None
Returns:
None
"""
# Get the current time in New York City.
now_time = datetime.now(ny_time)
# If it is between 3:30 AM and 4:00 AM, check for a message in the Telegram channel.
if now_time.hour == 3 and now_time.minute >= 30:
# Wait until the next minute.
await asyncio.sleep(5)
# Check for a message in the Telegram channel between 1:00 AM and 3:30 AM.
if not await check_message_between("I'm here", now_time.replace(hour=1, minute=0, second=0), now_time):
# No message was found. Cancel all active orders and notify the user via Telegram.
message = "No message found. Cancelling all active orders."
message_telegram(message)
# Cancel all active orders.
# ...
# Notify the user via Telegram that the orders have been canceled.
message_telegram(message)
else:
# A message was found. Do not cancel any orders.
message = "Message found. Orders are not canceled."
message_telegram(message)
# Wait until the next minute.
await asyncio.sleep(5)
def message_telegram(message):
'''
Define a function to send a message via Telegram:
'''
if DEBUG: print(f"Telegram message: {message}")
client_bot.send_message(channel_name, message)
async def check_message_between(message_to_check, start_time, end_time):
'''
Define a function to check for the 'I'm here' message in the Telegram channel:
'''
# create a timezone object for New York
res = False
ny_time = pytz.timezone('America/New_York')
messages = await client_human.get_messages(channel_name, limit=100)
for message in messages:
# convert message time to New York time zone
message_time = message.date.replace(tzinfo=pytz.utc).astimezone(ny_time)
if message_to_check in message.text and start_time <= message_time <= end_time:
res = True
break
print(res)
if res:
message_telegram("Found the code word! The orders are not canceled.")
return res
async def main():
try:
await asyncio.gather(
check_connection(ib_api),
cancel_orders_if_no_message(),
)
except:
ib_api.disconnect()
asyncio.get_event_loop().run_until_complete(main())
# loop.run_until_complete(check_im_here())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment