Advertisement
anjalmorang

Untitled

Jul 18th, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.54 KB | None | 0 0
  1. import os
  2. import asyncio
  3. import sys
  4. from pathlib import Path
  5. from quotexpy import Quotex
  6. from quotexpy.utils import asset_parse
  7. from quotexpy.utils.account_type import AccountType
  8. from quotexpy.utils.operation_type import OperationType
  9. from quotexpy.utils.duration_time import DurationTime
  10. from termcolor import colored
  11. from login_manager import login_accounts, generate_signals_for_account
  12.  
  13. asset_current = "AUDCAD"
  14.  
  15. class SingletonDecorator:
  16. """
  17. A decorator that turns a class into a singleton.
  18. """
  19.  
  20. def __init__(self, cls):
  21. self.cls = cls
  22. self.instance = None
  23.  
  24. def __call__(self, *args, **kwargs):
  25. if self.instance is None:
  26. self.instance = self.cls(*args, **kwargs)
  27. return self.instance
  28.  
  29. @SingletonDecorator
  30. class MyConnection:
  31. """
  32. This class represents a connection object and provides methods for connecting to a client.
  33. """
  34.  
  35. def __init__(self, client_instance):
  36. self.client = client_instance
  37.  
  38. async def connect(self, attempts=5):
  39. check, reason = await self.client.connect()
  40. if not check:
  41. attempt = 0
  42. while attempt <= attempts:
  43. if not self.client.check_connect():
  44. check, reason = await self.client.connect()
  45. if check:
  46. print("Reconnected successfully!!!")
  47. break
  48. print("Error reconnecting.")
  49. attempt += 1
  50. if Path(os.path.join(".", "session.json")).is_file():
  51. Path(os.path.join(".", "session.json")).unlink()
  52. print(f"Trying to reconnect, attempt {attempt} of {attempts}")
  53. elif not check:
  54. attempt += 1
  55. else:
  56. break
  57. await asyncio.sleep(5)
  58. return check, reason
  59. return check, reason
  60.  
  61. def close(self):
  62. """
  63. Closes the client connection.
  64. """
  65. self.client.close()
  66.  
  67.  
  68. async def check_asset(asset, client):
  69. print("Checking asset...")
  70. print("Client:", client)
  71. if client:
  72. print("Client is valid.")
  73. asset_query = asset_parse(asset)
  74. asset_open = client.check_asset_open(asset_query)
  75. if not asset_open[2]:
  76. print(colored("[WARN]: ", "yellow"), "Asset is closed.")
  77. asset = f"{asset}_otc"
  78. print(colored("[WARN]: ", "yellow"), "Try OTC Asset -> " + asset)
  79. asset_query = asset_parse(asset)
  80. asset_open = client.check_asset_open(asset_query)
  81. return asset, asset_open
  82. else:
  83. print("Client is None!")
  84. return None, None
  85.  
  86.  
  87. async def trade(option, client):
  88. prepare_connection = MyConnection(client)
  89. check_connect, message = await prepare_connection.connect()
  90. if check_connect:
  91. client.change_account(AccountType.PRACTICE)
  92. amount = 500
  93. action = OperationType.CALL_GREEN if option == "buy" else OperationType.PUT_RED
  94. global asset_current
  95. asset, asset_open = await check_asset(asset_current, client)
  96. if asset_open[2]:
  97. print(colored("[INFO]: ", "blue"), "Asset is open.")
  98. try:
  99. await client.trade(action, amount, asset, DurationTime.ONE_MINUTE)
  100. except Exception as e:
  101. print("Trade failed:", e)
  102. else:
  103. print(colored("[WARN]: ", "yellow"), "Asset is closed.")
  104. print(colored("[INFO]: ", "blue"), "Balance: ", await client.get_balance())
  105. print(colored("[INFO]: ", "blue"), "Exiting...")
  106. prepare_connection.close()
  107.  
  108. async def get_realtime_candle(client):
  109. prepare_connection = MyConnection(client)
  110. check_connect, message = await prepare_connection.connect()
  111. if check_connect:
  112. list_size = 10
  113. global asset_current
  114. asset, asset_open = await check_asset(asset_current, client)
  115. client.start_candles_stream(asset, list_size)
  116. while True:
  117. if len(client.get_realtime_candles(asset)) == list_size:
  118. break
  119. print(client.get_realtime_candles(asset))
  120. prepare_connection.close()
  121.  
  122. async def calculate_moving_averages(client):
  123. global asset_current
  124. asset, asset_open = await check_asset(asset_current, client)
  125. if asset_open[2]:
  126. candles = client.get_realtime_candles(asset)
  127. if len(candles) >= 200:
  128. # Calculate 50-period moving average
  129. ma_50 = sum(candle["close"] for candle in candles[-50:]) / 50
  130. # Calculate 200-period moving average
  131. ma_200 = sum(candle["close"] for candle in candles[-200:]) / 200
  132. return ma_50, ma_200
  133. return None, None
  134.  
  135. async def main():
  136. accounts = [
  137. {"email": "[email protected]", "password": "password1"},
  138. {"email": "[email protected]", "password": "password2"},
  139. # Add more accounts as needed
  140. ]
  141. login_results = await login_accounts(accounts)
  142.  
  143. if all(login_results):
  144. print("All accounts logged in successfully. Starting signal generation.")
  145. await asyncio.gather(*[generate_signals_for_account(account["email"], account["password"]) for account in accounts])
  146. else:
  147. print("Failed to log in to one or more accounts. Signal generation aborted.")
  148.  
  149. def run_main():
  150. try:
  151. asyncio.run(main())
  152. except KeyboardInterrupt:
  153. print("Aborted!")
  154. sys.exit(0)
  155.  
  156. if __name__ == "__main__":
  157. run_main()
  158.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement