Advertisement
johnnydappeth

Untitled

Nov 20th, 2024
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.95 KB | Cryptocurrency | 0 0
  1. #Twitter Scraper module
  2. import tweepy
  3. from tweepy import OAuthHandler
  4.  
  5. #http client for sentiment analysis API
  6. import http.client, json
  7.  
  8. #dates module
  9. from datetime import datetime, date
  10. from itertools import count
  11. import time
  12. import re
  13.  
  14. #trading terminal
  15. import MetaTrader5 as mt5
  16.  
  17.  
  18. # Store Twitter credentials from dev account
  19. consumer_key = "consumer_key"
  20. consumer_secret = "consumer_secret"
  21. access_key = "access_key"
  22. access_secret = "access_secret"
  23.  
  24. #text sentiment API key
  25. sentiment_key = "sentiment_key"
  26.  
  27. # Pass twitter credentials to tweepy via its OAuthHandler
  28. auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  29. auth.set_access_token(access_key, access_secret)
  30. api = tweepy.API(auth)
  31.  
  32.  
  33. # connect to the trade account without specifying a password and a server
  34. mt5.initialize()
  35.  
  36. # account number in the top left corner of the MT5 terminal window
  37. # the terminal database password is applied if connection data is set to be remembered
  38. account_number = 555
  39. authorized = mt5.login(account_number)
  40.  
  41. if authorized:
  42.     print(f'connected to account #{account_number}')
  43. else:
  44.     print(f'failed to connect at account #{account_number}, error code: {mt5.last_error()}')
  45.  
  46. # store the equity of your account
  47. account_info = mt5.account_info()
  48. if account_info is None:
  49.     raise RuntimeError('Could not load the account equity level.')
  50. else:
  51.     equity = float(account_info[10])
  52.  
  53. #crypto sign and keywords
  54. CRYPTO='BTCUSD'
  55. keywords =['Bitcoin', 'bitcoin', 'BITCOIN', 'btc', 'BTC']
  56.  
  57.  
  58. #Get Technoking's latest tweet
  59. def get_elons_tweet():
  60.     """Get Elon's last tweet by user ID"""
  61.     tweets = tweepy.Cursor(api.user_timeline,id="44196397", since=date.today(), tweet_mode='extended').items(1)
  62.  
  63.     #remove all invalid characters
  64.     elons_last_tweet = [re.sub('[^A-Za-z0-9]+', ' ', tweet.full_text) for tweet in tweets]
  65.  
  66.     #re-try until it returns a value - tweepy API fails to return the tweet sometimes
  67.     while not elons_last_tweet:
  68.         tweets = tweepy.Cursor(api.user_timeline,id="44196397", since=date.today(), tweet_mode='extended').items(1)
  69.         elons_last_tweet = [re.sub('[^A-Za-z0-9]+', ' ', tweet.full_text) for tweet in tweets]
  70.     return elons_last_tweet[0]
  71.  
  72. def analyze_sentence():
  73.     """Determine whether Elons Tweet is positive, negative or neutral"""
  74.     tweet = get_elons_tweet()
  75.  
  76.     #fomat the request
  77.     conn = http.client.HTTPSConnection("text-sentiment.p.rapidapi.com")
  78.     payload = "text="+tweet
  79.     headers = {
  80.         'content-type': "application/x-www-form-urlencoded",
  81.         'x-rapidapi-key': sentiment_key,
  82.         'x-rapidapi-host': "text-sentiment.p.rapidapi.com"
  83.         }
  84.  
  85.     #post the request
  86.     conn.request("POST", "/analyze", payload, headers)
  87.  
  88.     #get response
  89.     res = conn.getresponse()
  90.     raw_tweet = res.read()
  91.  
  92.     #convert response to json
  93.     json_tweet = json.loads(raw_tweet)
  94.     return json_tweet['pos']
  95.  
  96. #buy bitcoin
  97. def trade():
  98.     """Check if Musk mentioned bitcoin with positive sentiment and open a buy position if so"""
  99.     what_musk_said = get_elons_tweet()
  100.     tweet_sentiment = analyze_sentence()
  101.  
  102.     # used to check if a position has already been placed
  103.     positions = mt5.positions_get(symbol=CRYPTO)
  104.     orders = mt5.orders_get(symbol=CRYPTO)
  105.     symbol_info = mt5.symbol_info(CRYPTO)
  106.     price = mt5.symbol_info_tick(CRYPTO).bid
  107.  
  108.     # perform logic check
  109.     if any(keyword in what_musk_said for keyword in keywords) and tweet_sentiment > 0:
  110.         print(f'the madlad said it - buying some!')
  111.  
  112.         # prepare the trade request
  113.         if not mt5.initialize():
  114.             raise RuntimeError(f'MT5 initialize() failed with error code {mt5.last_error()}')
  115.  
  116.         # check that there are no open positions or orders
  117.         if len(positions) == 0 and len(orders) < 1:
  118.             if symbol_info is None:
  119.                 print(f'{CRYPTO} not found, can not call order_check()')
  120.                 mt5.shutdown()
  121.  
  122.             # if the symbol is unavailable in MarketWatch, add it
  123.             if not symbol_info.visible:
  124.                 print(f'{CRYPTO} is not visible, trying to switch on')
  125.                 if not mt5.symbol_select(CRYPTO, True):
  126.                     print('symbol_select({}}) failed, exit', CRYPTO)
  127.  
  128.             #this represents 5% Equity. Minimum order is 0.01 BTC. Increase equity share if retcode = 10014
  129.             lot = float(round(((equity / 5) / price), 2))
  130.  
  131.             # define stop loss and take profit
  132.             sl = price - (price * 5) / 100
  133.             tp = price + (price * 10) / 100
  134.             request = {
  135.                 'action': mt5.TRADE_ACTION_DEAL,
  136.                 'symbol': CRYPTO,
  137.                 'volume': lot,
  138.                 'type': mt5.ORDER_TYPE_BUY,
  139.                 'price': price,
  140.                 'sl': sl,
  141.                 'tp': tp,
  142.                 'magic': 66,
  143.                 'comment': 'python-buy',
  144.                 'type_time': mt5.ORDER_TIME_GTC,
  145.                 'type_filling': mt5.ORDER_FILLING_IOC,
  146.             }
  147.  
  148.             # send a trading request
  149.             result = mt5.order_send(request)
  150.  
  151.             # check the execution result
  152.             print(f'1. order_send(): by {CRYPTO} {lot} lots at {price}')
  153.  
  154.             if result.retcode != mt5.TRADE_RETCODE_DONE:
  155.                 print(f'2. order_send failed, retcode={result.retcode}')
  156.  
  157.             #print the order result - anything else than retcode=10009 is an error in the trading request.
  158.             print(f'2. order_send done, {result}')
  159.             print(f'   opened position with POSITION_TICKET={result.order}')
  160.  
  161.         else:
  162.             print(f'BUY signal detected, but {CRYPTO} has {len(positions)} active trade')
  163.  
  164.     else:
  165.         print(f'He did not say it, he said: {what_musk_said} - OR sentiment was not positive')
  166.  
  167. #execute code every 5 seconds
  168. if __name__ == '__main__':
  169.     print('Press Ctrl-C / Ctrl-Q to stop.')
  170.     for i in count():
  171.         trade()
  172.         print(f'Iteration {i}')
  173.         time.sleep(5)
  174.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement