Exemplo n.º 1
0
    def log(self, duration):
        """Log initialized symbols

        :param duration: duration in seconds
        :type duration: int
        :return: None
        """
        self.__twm = ThreadedWebsocketManager()
        self.__twm.start()
        start_time = None
        logs = self.__logs
        stop = False

        def callback(data):
            nonlocal start_time, logs, stop
            if not start_time:
                start_time = data['T'] / 1000
            elif time.time() - start_time >= duration:
                stop = True
            logs[data['s']].append(data)

        for symbol in self.__symbols:
            self.__twm.start_trade_socket(symbol=symbol, callback=callback)
        while not stop:
            time.sleep(1)
        self.stop()
Exemplo n.º 2
0
def main():

    count = 0
    batch = 1

    log_start()
    size = os.stat('runlog.txt').st_size 

    if round(size / 1024) >= 100:
        with open('runlog.txt', 'w') as o:
            o.write('Log started: ' + str(now) + '\n')

    twm = ThreadedWebsocketManager(tld='us')

    twm.start()

    while count < 1001:
        count += 1

        start_time = time()
        prices = get_prices()
        pair = ''
        prices_time = time()
        print(f'Downloaded in: {prices_time - start_time:.4f}s')

        triangles = list(find_triangles(prices))
        print(f'Computed in: {time() - prices_time:.4f}s')
    
        
        if triangles:
            for triangle in sorted(triangles, key=itemgetter('profit'), reverse=True):
                describe_triangle(prices, triangle, batch, count, pair)
            break

        elif count <= 1000:
            print('No viable triangles found... Rechecking...', (str(count)+'/1000'))

        else:
            print('No viable triangles found in 1000 attempts.')
            count -= 1000
            with open('runlog.txt', 'a') as o:
                o.write(str('No viable triangles found in 1000 attempts. Batch #:' + str(batch)) + '\n')
            batch += 1

        if batch == 100:
            with open('runlog.txt', 'a') as o:
                o.write(str('Batch count exceeded. Restarting process... ' + str(now)) + '\n')
            main()
Exemplo n.º 3
0
    def con2Socket(self):

        ##
        # @fn con2Socket
        # @brief creates socket connection
        # @return socket object

        self.APILog.info("Connection to Socket in progress")
        binSocket = ThreadedWebsocketManager(api_key=None,
                                             api_secret=None,
                                             testnet=False)
        binSocket.daemon = True
        binSocket.start()

        self.APILog.info("Connected to Socket")

        return binSocket
def single_trade_test():
    twm = ThreadedWebsocketManager()
    twm.start()
    global stopped
    twm.start_trade_socket(symbol="BTCUSDT", callback=handle_socket_message)
    twm.start_trade_socket(symbol="ETHUSDT", callback=handle_socket_message)
    while not stopped:
        print(start)
        time.sleep(1)
    print("stopping...")
    twm.stop()
    while twm.is_alive():
        time.sleep(1)
    stopped = False
class LiveDataFetcherBinance(LiveDataFetcher):
    def __init__(self):
        super().__init__()
        self.twm = ThreadedWebsocketManager()
        self.twm.start()
        self.process_message = None

    def run(self, symbol: str, timeframe: str,
            process_message: Callable[[dict], None]) -> None:
        log.info(
            f'Live fetching candlesticks for {symbol}, timeframe of {timeframe}'
        )
        self.process_message = process_message
        self.twm.start_kline_socket(callback=self.map_message,
                                    symbol=symbol,
                                    interval=timeframe)

    def stop(self) -> None:
        log.info(f'Stopping live fetching')
        self.twm.stop()

    def map_message(self, message) -> None:
        tick = Tick(Time=int(int(message["E"]) / 1000),
                    Open=float(message["k"]["o"]),
                    Close=float(message["k"]["c"]),
                    High=float(message["k"]["h"]),
                    Low=float(message["k"]["l"]),
                    Volume=float(message["k"]["v"]),
                    OpenTime=int(message["k"]["t"]),
                    CloseTime=int(message["k"]["T"]))
        self.process_message(tick)

    @staticmethod
    def condition(name: str) -> bool:
        return name == 'binance'
Exemplo n.º 6
0
api_key = os.environ.get('binance_api')
api_secret = os.environ.get('binance_secret')
client = Client(api_key, api_secret)
price = {'BTCUSDT': pd.DataFrame(columns=['date', 'price']), 'error':False}


def btc_pairs_trade(msg):
	''' define how to process incoming WebSocket messages '''
	if msg['e'] != 'error':
		price['BTCUSDT'].loc[len(price['BTCUSDT'])] = [pd.Timestamp.now(), float(msg['c'])]
	else:
		price['error'] = True
	

# init and start the WebSocket
bsm = ThreadedWebsocketManager()
bsm.start()
bsm.start_symbol_ticker_socket(symbol='BTCUSDT', callback=btc_pairs_trade)


## main
while len(price['BTCUSDT']) == 0:
	# wait for WebSocket to start streaming data
	sleep(0.1)
	
sleep(300)

while True:
	# error check to make sure WebSocket is working
	if price['error']:
		# stop and restart socket
Exemplo n.º 7
0
class BinanceLog:
    """Log price information and save to file

    :param symbols: list of symbol strings ["btcusdt, "ethusdt"]
    :type symbols: list
    """
    def __init__(self, symbols):
        self.__symbols = [symbol.upper() for symbol in symbols]
        self.__logs = {}
        for symbol in self.__symbols:
            self.__logs.update({symbol: []})
        self.__twm = None

    def clear_logs(self):
        """Clears the logs in memory

        :return: None
        """
        self.__logs.clear()
        for symbol in self.__symbols:
            self.__logs.update({symbol: []})

    def log(self, duration):
        """Log initialized symbols

        :param duration: duration in seconds
        :type duration: int
        :return: None
        """
        self.__twm = ThreadedWebsocketManager()
        self.__twm.start()
        start_time = None
        logs = self.__logs
        stop = False

        def callback(data):
            nonlocal start_time, logs, stop
            if not start_time:
                start_time = data['T'] / 1000
            elif time.time() - start_time >= duration:
                stop = True
            logs[data['s']].append(data)

        for symbol in self.__symbols:
            self.__twm.start_trade_socket(symbol=symbol, callback=callback)
        while not stop:
            time.sleep(1)
        self.stop()

    def stop(self):
        """Stop all threads

        :return: None
        """
        if self.__twm:
            self.__twm.stop()
            while self.__twm.is_alive():
                time.sleep(1)
            self.__twm = None

    def dump(self, path):
        """Dump logs in memory to json file

        :param path: path to be dumped at
        :type path: string
        :return: None
        """
        for symbol in self.__logs:
            log = self.__logs[symbol]
            if log:
                start_time = log[0]['T'] / 1000
                time_str = datetime.datetime.utcfromtimestamp(
                    start_time).strftime('%Y-%m-%d_%H.%M.%S')
                file_path = os.path.join(path,
                                         symbol + '_' + time_str + ".json")
                with open(file_path, 'w') as file:
                    json.dump(log, file)
 def __init__(self):
     super().__init__()
     self.twm = ThreadedWebsocketManager()
     self.twm.start()
     self.process_message = None
def btc_trade_history(msg):
	''' define how to process incoming WebSocket messages '''
	if msg['e'] != 'error':
		print(msg['c'])
		
		btc_price['last'] = msg['c']
		btc_price['bid'] = msg['b']
		btc_price['last'] = msg['a']
		btc_price['error'] = False
	else:
		btc_price['error'] = True


# init and start the WebSocket
bsm = ThreadedWebsocketManager()
bsm.start()

# subscribe to a stream
bsm.start_symbol_ticker_socket(callback=btc_trade_history, symbol='BTCUSDT')

# put script to sleep to allow WebSocket to run for a while
# this is just for example purposes
sleep(2)

# add a second stream
bsm.start_symbol_ticker_socket(callback=btc_trade_history, symbol='ETHUSDT')

# put script to sleep to allow WebSocket to run for a while
# this is just for example purposes
sleep(2)
Exemplo n.º 10
0
def funding_alert(threshold,
                  futures_type,
                  symbol=None,
                  is_neg=False,
                  disable_notification=False,
                  is_both=False,
                  send_to_chat=True):
    # FuturesType.USD_M
    # FuturesType.COIN_M

    global is_handling
    is_handling = True

    time_str = datetime.now().strftime("%Y-%m-%d_%H%M%S")
    file_name = f'data/temp_funding_{time_str}.csv'

    if futures_type == FuturesType.COIN_M:
        str_corbak = 'COIN-M'
    elif futures_type == FuturesType.USD_M:
        str_corbak = 'USD-M'

    def handle_socket_message(msg, time_str=''):
        global is_handling
        data = msg['data']
        data = pd.DataFrame(data)
        data.to_csv(f'data/temp_funding_{time_str}.csv', index=False)
        is_handling = False
        return "123...soleil"

    handle_socket_message = partial(handle_socket_message, time_str=time_str)

    twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret)

    twm.start()
    twm.start_all_mark_price_socket(
        callback=handle_socket_message,
        futures_type=futures_type,
    )
    while is_handling:
        pass
    twm.stop()

    my_file = Path(file_name)
    if my_file.is_file():
        data = pd.read_csv(file_name)
        data = _df_funding_astype(data, futures_type=futures_type)
        data = _df_funding_filter(data,
                                  symbol=symbol,
                                  threshold=threshold,
                                  is_neg=is_neg,
                                  is_both=is_both)

        if not data.empty:
            data = _df_funding_format(data, futures_type=futures_type)
            file_name = save_formated_df_picture(data, 'funding_df')

            if send_to_chat:
                send_message(
                    file_name,
                    chat_id,
                    telegram_token,
                    caption=f'{str_corbak} funding rates   🦅',
                    disable_notification=disable_notification,
                )

            else:
                return file_name

    else:
        funding_alert(threshold, futures_type, symbol, is_neg,
                      disable_notification, is_both, send_to_chat)
Exemplo n.º 11
0
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager

user_info = utils.get_user_info()
http_proxy = "http://127.0.0.1:7890"
https_proxy = "http://127.0.0.1:7890"
ftp_proxy = "ftp://127.0.0.1:7890"

proxyDict = {"http": http_proxy, "https": https_proxy, "ftp": ftp_proxy}
client = Client(user_info['api_key'], user_info['secret_key'],
                {'proxies': proxyDict})
withdraws = client.get_withdraw_history()
print(withdraws)
# get market depth

# socket manager using threads
twm = ThreadedWebsocketManager()
twm.start()

# depth cache manager using threads
dcm = ThreadedDepthCacheManager()
dcm.start()


def handle_socket_message(msg):
    print(f"message type: {msg['e']}")
    print(msg)


def handle_dcm_message(depth_cache):
    print(f"symbol {depth_cache.symbol}")
    print("top 5 bids")
Exemplo n.º 12
0
 def __init__(self):
     self.__api_key = "XX"
     self.__api_secret = "SS"
     self.__twm = ThreadedWebsocketManager(api_key=self.__api_key,
                                           api_secret=self.__api_secret)
Exemplo n.º 13
0
    parser.add_argument("dump_path", type=str, help="directory to dump trades")
    parser.add_argument("-d",
                        "--duration",
                        type=int,
                        dest="duration",
                        help="time in seconds")
    return parser


args = return_parser().parse_args(sys.argv[1:])
SYMBOL = args.symbol.upper()
DURATION = 60  # in seconds
DUMP_PATH = args.dump_path
if args.duration:
    DURATION = args.duration
sock_manager = ThreadedWebsocketManager()
sock_manager.start()
TRADES = []
START_TIME = None
STOPPED = False


def write_data():
    time_str = datetime.datetime.utcfromtimestamp(START_TIME).strftime(
        '%Y-%m-%d_%H.%M.%S')
    path = os.path.join(DUMP_PATH, SYMBOL + '_' + time_str + ".json")
    with open(path, 'w') as file:
        json.dump(TRADES, file)


def trade_callback(data):