xmd79

finder16 (best vers.)

Mar 17th, 2023
848
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.45 KB | Cryptocurrency | 0 0
  1. import json
  2. import numpy as np
  3. import requests
  4. import matplotlib.pyplot as plt
  5. import math
  6. import hashlib
  7. import hmac
  8. import time
  9.  
  10. class Trader:
  11.     def __init__(self, file):
  12.         self.connect(file)
  13.         self.base_url = "https://fapi.binance.com"
  14.  
  15.     def connect(self, file):
  16.         with open(file) as f:
  17.             lines = f.read().splitlines()
  18.         self.key = lines[0]
  19.         self.secret = lines[1]
  20.  
  21.     def _generate_header(self):
  22.         timestamp = int(time.time() * 1000)
  23.         message = f'timestamp={timestamp}'
  24.         signature = hmac.new(self.secret.encode(), message.encode(), hashlib.sha256).hexdigest()
  25.         return {
  26.             'X-MBX-APIKEY': self.key,
  27.             'X-MBX-TIMESTAMP': str(timestamp),
  28.             'X-MBX-SIGNATURE': signature
  29.         }
  30.  
  31.     def get_account_balance(self):
  32.         endpoint = '/fapi/v2/account'
  33.         headers = self._generate_header()
  34.         response = requests.get(f'{self.base_url}{endpoint}', headers=headers)
  35.         data = response.json()
  36.         return float(data['totalWalletBalance'])
  37.  
  38.     def buy(self, symbol):
  39.         endpoint = '/fapi/v1/order'
  40.         headers = self._generate_header()
  41.         quantity = self.get_account_balance() / float(requests.get(f"{self.base_url}/fapi/v1/ticker/price?symbol={symbol}").json()['price'])
  42.         params = {
  43.             'symbol': symbol,
  44.             'side': 'BUY',
  45.             'type': 'MARKET',
  46.             'quantity': balance
  47.         }
  48.         response = requests.post(f'{self.base_url}{endpoint}', headers=headers, params=params)
  49.         return response.json()
  50.  
  51.     def sell(self, symbol):
  52.         endpoint = '/fapi/v1/order'
  53.         headers = self._generate_header()
  54.         quantity = self.get_account_balance()
  55.         params = {
  56.             'symbol': symbol,
  57.             'side': 'SELL',
  58.             'type': 'MARKET',
  59.             'quantity': balance
  60.         }
  61.         response = requests.post(f'{self.base_url}{endpoint}', headers=headers, params=params)
  62.         return response.json()
  63.  
  64. class TechnicalAnalyzer:
  65.     def __init__(self, api_key, api_secret):
  66.         self.api_key = api_key
  67.         self.api_secret = api_secret
  68.  
  69.     def get_historical_data(self, symbol, interval):
  70.         url = f'https://fapi.binance.com/fapi/v1/klines?symbol={symbol}&interval={interval}&limit=1000'
  71.         headers = {'X-MBX-APIKEY': self.api_key}
  72.         response = requests.get(url, headers=headers)
  73.         data = json.loads(response.text)
  74.  
  75.         close_prices = [float(entry[4]) for entry in data]
  76.         return close_prices
  77.  
  78.     def fit_line(self, data):
  79.         y = np.array(data)
  80.         x = np.arange(len(y))
  81.         z = np.polyfit(x, y, 1)
  82.         p = np.poly1d(z)
  83.         return p(x)
  84.  
  85.     def identify_dip(self, symbol, interval):
  86.         close_prices = self.get_historical_data(symbol, interval)
  87.         fit_line = self.fit_line(close_prices)
  88.  
  89.         lowest_line = np.min(fit_line)
  90.         slope = np.polyfit(np.arange(len(fit_line)), fit_line, 1)[0]
  91.  
  92.         if close_prices[-1] < lowest_line and slope < 0:
  93.             print(f'{symbol}: Dip found on {interval} timeframe')
  94.             return True
  95.  
  96.         return False
  97.  
  98.     def identify_top(self, symbol, interval):
  99.         close_prices = self.get_historical_data(symbol, interval)
  100.         fit_line = self.fit_line(close_prices)
  101.  
  102.         highest_line = np.max(fit_line)
  103.         slope = np.polyfit(np.arange(len(fit_line)), fit_line, 1)[0]
  104.  
  105.         if close_prices[-1] > highest_line and slope > 0:
  106.             print(f'{symbol}: Top found on {interval} timeframe')
  107.             return True
  108.  
  109.         return False
  110.  
  111.  
  112. def create_sinewave(min_value, max_value, length):
  113.     x = np.arange(length)
  114.     y = np.sin(x * np.pi / length) * (max_value - min_value) / 2 + (max_value + min_value) / 2
  115.     return y
  116.  
  117.  
  118. filename = 'credentials.txt'
  119. trader = Trader(filename)
  120. analyzer = TechnicalAnalyzer(trader.key, trader.secret)
  121.  
  122. print()
  123. trading_pairs = [symbol['symbol'] for symbol in json.loads(requests.get('https://fapi.binance.com/fapi/v1/exchangeInfo').text)['symbols']
  124.                  if symbol['quoteAsset'] == 'USDT' and 'PERP' not in symbol['pair'].upper()]
  125.  
  126. for pair in trading_pairs:
  127.     if analyzer.identify_dip(pair, '4h'):
  128.         if analyzer.identify_dip(pair, '1h'):
  129.             if analyzer.identify_dip(pair, '15m'):
  130.                 if analyzer.identify_dip(pair, '5m'):
  131.                     print(f'{pair}: Dip confirmed on all timeframes')
  132.                     close_prices = analyzer.get_historical_data(pair, '1m')
  133.                     if len(close_prices) >= 200:
  134.                         fit_line = analyzer.fit_line(close_prices[-200:])
  135.                         current_price = close_prices[-1]
  136.                         lowest_line = np.min(fit_line)
  137.                         highest_line = np.max(fit_line)
  138.                         sin_wave = np.sin(np.arange(0, 2*np.pi, 2*np.pi/200))
  139.                         scaled_wave = (sin_wave + 1) * (highest_line - lowest_line) / 2 + lowest_line
  140.                         if current_price <= scaled_wave[0]:
  141.                             print(f'{pair}: Buy signal on 1m timeframe')
  142.                             #trader.buy(pair)
  143.                         elif current_price >= scaled_wave[-1]:
  144.                             print(f'{pair}: Sell signal on 1m timeframe for mtf dip')
  145.     elif analyzer.identify_top(pair, '4h'):
  146.         if analyzer.identify_top(pair, '1h'):
  147.             if analyzer.identify_top(pair, '15m'):
  148.                 if analyzer.identify_top(pair, '5m'):
  149.                     print(f'{pair}: Top confirmed on all timeframes')
  150.                     close_prices = analyzer.get_historical_data(pair, '1m')
  151.                     if len(close_prices) >= 200:
  152.                         fit_line = analyzer.fit_line(close_prices[-200:])
  153.                         current_price = close_prices[-1]
  154.                         lowest_line = np.min(fit_line)
  155.                         highest_line = np.max(fit_line)
  156.                         sin_wave = np.sin(np.arange(0, 2*np.pi, 2*np.pi/200))
  157.                         scaled_wave = (sin_wave + 1) * (highest_line - lowest_line) / 2 + lowest_line
  158.                         if current_price <= scaled_wave[0]:
  159.                             print(f'{pair}: Buy signal on 1m timeframe for mtf top')
  160.                         elif current_price >= scaled_wave[-1]:
  161.                             print(f'{pair}: Sell signal on 1m timeframe')
  162.                             #trader.sell(pair)
  163. print()
  164.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment