Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discord Suggestment #34

Open
AlphaAlex1 opened this issue May 22, 2021 · 50 comments
Open

Discord Suggestment #34

AlphaAlex1 opened this issue May 22, 2021 · 50 comments

Comments

@AlphaAlex1
Copy link

Hey! Is there some way we could integrate this bot into discord so it automatically buys the coin for us? It would really help out! Also, is there a panic sell button on the bot?

@abayomi185
Copy link
Owner

abayomi185 commented May 22, 2021

Yes!

Work is being done on this. I use discord often but I'm leaning towards prioritising the Telegram bot before the discord scraper. It's hard to judge what the better option might be.

The panic sell button is coming very soon

@AlphaAlex1
Copy link
Author

Thank you!

@ffbboy30
Copy link

Actually the telegram tag come faster then the discord one.
I'm looking for the telegram option but to register to the channel you have to ask to the admin to put your bot listening the channel. And they ask moeny for this :-(. I suppose it is the same with discord?

@calamarcus
Copy link

Okay....im thinking if there is some other way around this.

@ffbboy30
Copy link

Actually the events comes only from Telegram or discord. No better idea

@abayomi185
Copy link
Owner

From what I have researched, the Mproto core library acts as a telegram client just like your phone would. It shouldn't require adding a bot to the group

@calamarcus
Copy link

calamarcus commented May 24, 2021

Well that would be awesome, if that is the case.

@ffbboy30
Copy link

Hi,
I've made it working with telegram

@calamarcus
Copy link

Cool. I cant wait to try it out!

@ffbboy30
Copy link

I will send a PM to Yomi tomorrow

@calamarcus
Copy link

@ffbboy30 Could you upload the code for me to try somewhere?

@abayomi185
Copy link
Owner

You could put it in this thread too

@ffbboy30
Copy link

ffbboy30 commented May 25, 2021

#xxxx the ID you get when you register in the telegram API
#yyyy your telegram API
from telethon import TelegramClient, sync, events
import pandas as pd
import time
import os
import sys
import keyboard

api_id = xxxxxxxx
api_hash = 'xxxxxxxxxxxx'
group_username = 'aaaaaaaaa'

Group name can be found in group link

(Example group link : https://t.me/c0ban_global, group name = 'c0ban_global')

client = TelegramClient('yyyyy', api_id, api_hash).start()

@client.on(events.NewMessage)
#@client.on(events.NewMessage(chats=(group_username)))
async def my_event_handler(event):
#print('{}'.format(event))
print(event.message.message)

client.start()
client.run_until_disconnected()
keyboard.wait('esc')
print('Close')
client.disconnect()

@calamarcus
Copy link

now it need to parse the message text with regex to get the coin, correct?

@calamarcus
Copy link

@ffbboy30 think i actually need to wait for the integration from @abayomi185. i will mess it up otherwise :)

@calamarcus
Copy link

Okey, so this is python? i think we are working on nodejs now

@calamarcus
Copy link

@ffbboy30 however, i got it working aswell, though

@calamarcus
Copy link

txt = event.message.message
clean = re.search(r"\b\w+/", txt)
clean = clean.group()[:-1]
print(clean)

@calamarcus
Copy link

works with eg.

The coin we picked is BTM/BTC

ELA/USDT

Coin is: YOP/USDT

but not coins without the /

@calamarcus
Copy link

so this is nothing fancy

@ffbboy30
Copy link

Here is some previous pump with channels
#WallStreetBets Crypto Pumps - Investing!
#kucoin
#https://t.me/wallstbetspumps
#Coin is: YOP/USDT
#Coin is: DYP/USDT
#Coin is: LON/USDT

#Binance Royal Pump
#kucoin
#VIP
#https://t.me/binancepumproys
#COIN IS : WPR
#COIN IS : DLT
#COIN IS : IDEX
#COIN IS : RDN

#Crypto Pump Squad
#kucoin
#No preprump
#https://t.me/cryptoflashsignals
#Coin is: MXC
#Coin is: ORBS
#Coin is: LON

#WallStreetBets | Market Makers
#kucoin
#no VIP
#https://t.me/wsb_crpyto
#ELA/USDT
#VSYS/USDT
#SDT/USDT

#Binance Pump Signals
#binance
#no VIP
#https://t.me/Big_Pumps_Signals
#COIN IS : DLT
#COIN IS : WPR
#COIN IS :IDEX

@ffbboy30
Copy link

Now the most important is to share channels with no VIP pumps to have chance to make money.

@abayomi185
Copy link
Owner

Thanks! I should have some time to work on this later today. I'm currently looking at having both manual and telegram entry work simultaneously, particularly while it's still untested how performant it would be.

@ffbboy30
Copy link

I'm looking if there is a solution equivalent with discord , to have the both in parallel and take the first message received

@abayomi185
Copy link
Owner

It's possible. I've made the UI in the last Node commit to choose multiple pump-groups at launch.

@calamarcus
Copy link

@ffbboy30 did you manage to add it to send the coin to the prompt in the bot-kucoin.py? if so, then do you have the code?

@ffbboy30
Copy link

I suck on the Regex formula, here is the different sentence I've found
'Coin is: YOP/USDT'
'Coin is: YOP'
'YOP/USDT'
'YOP'

I thoughtabout a loop waiting while the sentence size is not null, and I put the Coin detected in the Event like this the loop break and you can make the order instantly.
What do you think of that.
I'm not Python expert :-)

@abayomi185
Copy link
Owner

abayomi185 commented May 25, 2021

Nice. It's similar to how I want to implement it in Node. I haven't used Regex extensively so I would have to learn it.

@ffbboy30
Copy link

The @calamarcus regex works for
Coin is: YOP/USDT
YOP/USDT
but not works for
Coin is: YOP
YOP

@calamarcus
Copy link

I can check more regex tomorrow!

@calamarcus
Copy link

calamarcus commented May 26, 2021

this works with all. although feel free to change anything.

clean = event.message.message.replace("COIN IS", "coin is")	
clean = re.search(r"(\b\w[A-Z]+)", clean)	
clean = clean.group()

@calamarcus
Copy link

i hope this works with the nodejs also....please try that @abayomi185 when you have time.

@calamarcus
Copy link

@ffbboy30 Could you integrate the telegram function into the pythoncode?

@ffbboy30
Copy link

I will look at it tonight
What is nodejs , I don't see java code on this repo ?

@calamarcus
Copy link

.js files in the node_wip folder. but @abayomi185 will look at that as the python version is no priority for him. but i think you can try to integrate the telegram function into the python bot. i know most of everything except programming well :-)

@ffbboy30
Copy link

ffbboy30 commented May 26, 2021

Ok,
I've seen it
Thanks

The final regex is like this 👍
clean = event.message.message.upper()
if ':' in clean:
clean = clean.split(":") # remove before ':' if present in string
clean = clean[1]
clean = re.search(r"(\b\w[A-Z]+)", clean)
clean = clean.group()
print(clean)

I've problem to make the event message non blocking

@ffbboy30
Copy link

ffbboy30 commented May 26, 2021

#Here is the baby

from future import print_function, unicode_literals
from time import sleep, time
import PyInquirer as Inquirer
from pprint import pprint
from pyfiglet import Figlet
from colorama import Fore, Back, Style
from timeit import default_timer as timer
import threading
import concurrent.futures
import asyncio
import os
import json
import yaml
import math
import uuid
import time

from telethon import TelegramClient, sync, events
import pandas as pd
import time
import os
import sys
import keyboard
import re

Kucoin API Helper - https://github.com/Kucoin/kucoin-python-sdk.git

from kucoin.client import Market
from kucoin.client import Trade
from kucoin.client import User

SQLite3 to save local records of trades

import sqlite3

Connect to records.db database

conn = sqlite3.connect('records.db')
c = conn.cursor()

Import user config and instantiate variables

conf_Telegram = "./conf-Telegram.yaml"
conf_import = "./conf-kucoin.yaml"
secrets = "./secrets-kucoin.yaml"
coin = None
config = None

Switched to .yaml as it offers commenting and other features

#It shouldn't be an issue for speed as dict is loaded into memory
with open(conf_import, "r") as conf_file:
config = yaml.safe_load(conf_file)

with open(conf_Telegram, "r") as conf_file:
Telegramconfig = yaml.safe_load(conf_file)

Open secret.json, retrieve keys and place in config dictionary

with open(secrets, "r") as secrets_file:
api_keys = yaml.safe_load(secrets_file)

config['api_key'] = api_keys['api_key']
config['api_secret'] = api_keys['api_secret']
config['api_passphrase'] = api_keys['api_passphrase']

Command Line interface prompts for PyInquirer

question1 = [
{
'type': 'list',
'name': 'trade_conf',
'message': 'Please select trade configuration?',
'choices': list(config["trade_configs"].keys()),
}
]
question2 = [
{
'type': 'input',
'name': 'coin',
'message': 'Please enter coin for Pump?',
}
]
question3 = [
{
'type': 'confirm',
'name': 'continue',
'message': 'Do you wish to proceed?',
'default': True,
}
]

Show crypto-bot banner

def show_header():
fig = Figlet(font='slant')
print(fig.renderText('crypto-bot'))

Binance API Helper Debug mode

def debug_mode(client):
# client.ping()
time_res = client.get_server_timestamp()
print(f"Server Time: {time_res}")

# There is an error for this function in the kucoin library
status = client.get_server_status()
print(f"Server Status: {status['status']}")

Get account balance for "pairing" in config before trade

def acct_balance():

acct_balance = user_client.get_account_list(config['trade_configs'][selected_config]['pairing'], 'trade')

print('\nYour {} balance is {}\n'.format(config['trade_configs'][selected_config]['pairing'], acct_balance[0]['available']))
print(Fore.YELLOW + 'Please ensure Config is correct before proceeding\n' + Fore.RESET)

if float(acct_balance[0]['available']) < 0.001:
    print(Fore.RED + 'A minimum balance may be required for trade on Kucoin\n' + Fore.RESET)

return acct_balance

Get account balance for "pairing" in config after trade

def acct_balance2():

acct_balance = user_client.get_account_list(config['trade_configs'][selected_config]['pairing'], 'trade')
    
print('\nYour {} balance after trading is {}\n'.format(config['trade_configs'][selected_config]['pairing'], acct_balance[0]['available']))

float_acct_balance = float(acct_balance[0]['available'])
float_balance = float(balance[0]['available'])

difference = float_acct_balance - float_balance
percentage = (difference/float_balance) * 100

if float_acct_balance < float_balance:
    
    print(Fore.YELLOW + 'A {:.2f}% loss\n'.format(percentage) + Fore.RESET)

if float_acct_balance > float_balance:
    
    print(Fore.GREEN + 'A {:.2f}% gain\n'.format(percentage) + Fore.RESET)

return acct_balance

def pump_duration(start_time, end_time):
time_delta = end_time - start_time
time_delta = round(time_delta, 2)
print(f"Time elapsed for pump is {time_delta}s\n")

Get available trading amount with user config

def trading_amount():
avail_trading_amount = float(balance[0]['available']) * config['trade_configs'][selected_config]['buy_qty_from_wallet']
return avail_trading_amount

Execute market order - buy and/or sell

def market_order(selected_coin_pair, order_type):

if order_type == 'buy':
    avail_trading_amount = trading_amount()
    current_price = client.get_ticker(symbol=selected_coin_pair)
    buy_qty = math.floor(avail_trading_amount / float(current_price['price']))
    # order = client.order_market_buy(symbol=selected_coin_pair, quantity=buy_qty)
    # print(f"buy_qty: {str(buy_qty)}")
    order_id = trade.create_market_order(selected_coin_pair, 'buy', clientOid=str(uuid.uuid4()), size=str(buy_qty))
    return order_id

elif order_type == 'sell':
    # coin_balance = user_client.get_withdrawal_quota(selected_coin.upper())
    coin_balance = user_client.get_account_list(selected_coin.upper(), 'trade')
    # current_price = client.get_symbol_ticker(symbol=selected_coin_pair)
    # sell_qty = math.floor(coin_balance * float(current_price['price']))
    sell_qty = math.floor(float(coin_balance[0]['available']) * config['trade_configs'][selected_config]['sell_qty_from_wallet'])
    # order = client.order_market_sell(symbol=selected_coin_pair, quantity=sell_qty)
    order_id = trade.create_market_order(selected_coin_pair, 'sell', str(uuid.uuid4()), size=str(sell_qty))
    return order_id

Displays order details asynchronously - see 'main' block

def display_order_details(order):
return json.dumps(order, sort_keys=True, indent=4)

Check user configs margin in to sell order

async def check_margin():

global pending_sell_order_id
# pending_sell_order_id = None
margin = config['trade_configs'][selected_config]['profit_margin']

fallback_task = asyncio.create_task(fallback_action())
# count = 0

while True:
    # avg_price = client.get_avg_price(symbol=selected_coin_pair)
    current_price = client.get_ticker(symbol=selected_coin_pair)
    # print(float(buy_order_data['dealFunds'])/float(buy_order_data['dealSize']))
    # count+=1
    try:
        if float(current_price['price']) >= ((float(buy_order_data['dealFunds'])/float(buy_order_data['dealSize'])) * (1.0 + margin)):
            if pending_sell_order_id == None:
                pending_sell_order_id = market_order(selected_coin_pair, 'sell')
                break
        else:
            # sleep((config['trade_configs'][selected_config]['refresh_interval']/1000))
            await asyncio.sleep(config['trade_configs'][selected_config]['refresh_interval']/1000)
    except:
        pass

    if pending_sell_order_id:
        break

# print(count)
return pending_sell_order_id

async def fallback_action():

global pending_sell_order_id
# sleep((config['trade_configs'][selected_config]['sell_fallback_timeout_ms']/1000))
await asyncio.sleep((config['trade_configs'][selected_config]['sell_fallback_timeout_ms']/1000))
    
if pending_sell_order_id == None:
    pending_sell_order_id = market_order(selected_coin_pair, 'sell')

Save orders to local db asynchronously

def insert_into_db(order, order_id):

# trade.get_order_details(order_id)

symbol = order['symbol']
symbol = symbol.split("-", 1)[0]

price = float(order['dealFunds']) / float(order['dealSize'])

c.execute("INSERT INTO Orders VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 
        ("Kucoin", order['clientOid'], order_id, order['id'],
            order['symbol'], order['type'], order['side'], order['timeInForce'],
            order['createdAt'], symbol, 
            price, order['fee'],
            order['size'], order['dealFunds']))

conn.commit()

async def main():

global buy_order_data

# coin_pair_info = client.get_symbol_info(selected_coin_pair)
# coin_pair_info = client.get_ticker(selected_coin_pair)

start_time = time.time()

buy_order = market_order(selected_coin_pair, 'buy')
# print(f"buy_order: {buy_order}")
buy_order_data = trade.get_order_details(buy_order['orderId'])

# Execution using threading
with concurrent.futures.ThreadPoolExecutor() as executor:
    
    #Print buy order details
    buy_order_details = executor.submit(display_order_details, buy_order_data)
    print('\n' + buy_order_details.result() + '\n')

    sell_order = await check_margin()

end_time = time.time()
sell_order_data = trade.get_order_details(sell_order['orderId'])
sell_order_details = display_order_details(sell_order_data)
print('\n' + sell_order_details + '\n')

insert_into_db(order=buy_order_data, order_id=buy_order['orderId'])
insert_into_db(order=sell_order_data, order_id=sell_order['orderId'])

conn.close()

balance2 = acct_balance2()
pump_duration(start_time, end_time)

if name == 'main':

show_header()

client = Market(url='https://api.kucoin.com')
trade = Trade(key=config['api_key'], secret=config['api_secret'],
                passphrase=config['api_passphrase'], is_sandbox=False, url='')
user_client = User(config['api_key'], config['api_secret'], config['api_passphrase'])

if config['debug_mode']:
    debug_mode(client=client)
    print('\n')

print(Fore.GREEN + '-- Kucoin Edition --\n' + Fore.RESET)


#Start Telegram API
client = TelegramClient(Telegramconfig['UserName'], Telegramconfig['api_id'], Telegramconfig['api_hash']).start()
selected_coin = ''

#Telegram Event
#@client.on(events.NewMessage)
@client.on(events.NewMessage(chats=(Telegramconfig['group_username'])))
async def my_event_handler(event):
    clean = event.message.message.upper()
    if ':' in clean:
        clean = clean.split(":") # remove before ':' if present in string
        clean = clean[1]
    clean = re.search(r"(\b\w[A-Z]+)", clean)	
    clean = clean.group()
    global selected_coin
    selected_coin = clean


client.start()
#client.run_until_disconnected()

#Question1
answer1 = Inquirer.prompt(question1)
selected_config = answer1['trade_conf']

#Retrieve current coin balance here
balance = acct_balance()

#Question2
#answer2 = Inquirer.prompt(question2)
#selected_coin = answer2['coin']
print('Wait for Telegram message')
async def main():
    while (selected_coin == ''):
        #print('Wait Telegram')
        await asyncio.sleep(0.01)
client.loop.run_until_complete(main())

#Coin Pair
selected_coin_pair = selected_coin.upper() + "-" +\
                        config['trade_configs'][selected_config]['pairing']

buy_order_data = None
pending_sell_order_id = None


print('Receive : ' + selected_coin_pair)

asyncio.run(main())

@ffbboy30
Copy link

#The binance one
from future import print_function, unicode_literals
from time import sleep, time
import PyInquirer as Inquirer
from pprint import pprint
from pyfiglet import Figlet
from colorama import Fore, Back, Style
from timeit import default_timer as timer
import threading
import concurrent.futures
import asyncio
import os
import json
import yaml
import math
import time

from telethon import TelegramClient, sync, events
import pandas as pd
import time
import os
import sys
import keyboard
import re

Binance API Helper - https://github.com/sammchardy/python-binance.git

from binance.client import Client

SQLite3 to save local records of trades

import sqlite3

Connect to records.db database

conn = sqlite3.connect('records.db')
c = conn.cursor()

Import user config and instantiate variables

conf_Telegram = "./conf-Telegram.yaml"
conf_import = "./conf-binance.yaml"
secrets = "./secrets-binance.yaml"
coin = None
config = None

Switched to .yaml as it offers commenting and other features

#It shouldn't be an issue for speed as dict is loaded into memory
with open(conf_import, "r") as conf_file:
config = yaml.safe_load(conf_file)

with open(conf_Telegram, "r") as conf_file:
Telegramconfig = yaml.safe_load(conf_file)

Open secret.json, retrieve keys and place in config dictionary

with open(secrets, "r") as secrets_file:
api_keys = yaml.safe_load(secrets_file)

config['api_key'] = api_keys['api_key']
config['api_secret'] = api_keys['api_secret']

#print(config)

Command Line interface prompts for PyInquirer

question1 = [
{
'type': 'list',
'name': 'trade_conf',
'message': 'Please select trade configuration?',
'choices': list(config["trade_configs"].keys()),
}
]
question2 = [
{
'type': 'input',
'name': 'coin',
'message': 'Please enter coin for Pump?',
}
]
question3 = [
{
'type': 'confirm',
'name': 'continue',
'message': 'Do you wish to proceed?',
'default': True,
}
]

Show crypto-bot banner

def show_header():
fig = Figlet(font='slant')
print(fig.renderText('crypto-bot'))

Binance API Helper Debug mode

def debug_mode(client):
# client.ping()
time_res = client.get_server_time()
print("Server Time: {}".format(time_res["serverTime"]))

status = client.get_system_status()
print("System Status: {}".format(status["msg"]))

Get account balance for "pairing" in config before trade

def acct_balance(send_output=False):
acct_balance = client.get_asset_balance(asset=config['trade_configs']
[selected_config]['pairing'])

print('\nYour {} balance is {}\n'.format(config['trade_configs'][selected_config]['pairing'], acct_balance['free']))
print(Fore.YELLOW + 'Please ensure Config is correct before proceeding\n' + Fore.RESET)

if config['trade_configs'][selected_config]['pairing'] == 'BTC':
    if float(acct_balance['free']) < 0.001:
        print(Fore.RED + 'Binance requires min balance of 0.001 BTC for trade\n' + Fore.RESET)
else:
    print(Fore.RED + 'A min balance is often required for trade on Binance\n' + Fore.RESET)

return acct_balance

Get account balance for "pairing" in config after trade

def acct_balance2(send_output=False):
acct_balance = client.get_asset_balance(asset=config['trade_configs']
[selected_config]['pairing'])

print('\nYour {} balance after trading is {}\n'.format(config['trade_configs'][selected_config]['pairing'], acct_balance['free']))

difference = acct_balance['free'] - balance['free']
percentage = (difference/balance) * 100

if float(acct_balance['free']) < balance:
    
    print(Fore.YELLOW + 'A {:.2f}% loss\n'.format(percentage) + Fore.RESET)

if float(acct_balance['free']) > balance:
    
    print(Fore.GREEN + 'A {:.2f}% gain\n'.format(percentage) + Fore.RESET)

return acct_balance

def pump_duration(start_time, end_time):
time_delta = end_time - start_time
time_delta = round(time_delta, 2)
print(f"Time elapsed for pump is {time_delta}s\n")

Get available trading amount with user config

def trading_amount():
avail_trading_amount = float(balance['free']) * config['trade_configs'][selected_config]['buy_qty_from_wallet']
return avail_trading_amount

Execute market order - buy and/or sell

def market_order(client, selected_coin_pair, order_type, coin_pair_info, balance):

if order_type == 'buy':
    avail_trading_amount = trading_amount()
    current_price = client.get_symbol_ticker(symbol=selected_coin_pair)
    buy_qty = math.floor(avail_trading_amount / float(current_price['price']))
    order = client.order_market_buy(symbol=selected_coin_pair, quantity=buy_qty)
    return order

elif order_type == 'sell':
    #This here is a potential bottle neck and may introduce delays
    coin_balance = client.get_asset_balance(asset=selected_coin.upper())
    # print(coin_balance)
    # current_price = client.get_symbol_ticker(symbol=selected_coin_pair)
    # print(current_price)
    # sell_qty = math.floor(coin_balance * float(current_price['price']))
    sell_qty = math.floor(float(coin_balance['free']) * config['trade_configs'][selected_config]['sell_qty_from_wallet'])
    order = client.order_market_sell(symbol=selected_coin_pair, quantity=sell_qty)
    return order

Displays order details asynchronously - see 'main' block

def display_order_details(order):
return json.dumps(order, sort_keys=True, indent=4)

Check user configs margin in to sell order

async def check_margin():

global pending_sell_order
margin = config['trade_configs'][selected_config]['profit_margin']

fallback_task = asyncio.create_task(fallback_action())

while True:
    # avg_price = client.get_avg_price(symbol=selected_coin_pair)
    current_price = client.get_symbol_ticker(symbol=selected_coin_pair)
    # print(current_price)
    # print(current_price['price'])
    try:
        if float(current_price['price']) >= (buy_order['fills'][0]['price'] * (1.0 + margin)):
            if pending_sell_order == None:
                pending_sell_order = market_order(client, selected_coin_pair, 'sell', coin_pair_info, balance)
                break
        else:
            await asyncio.sleep((config['trade_configs'][selected_config]['refresh_interval']/1000))
    except:
        pass

    if pending_sell_order:
        break

return pending_sell_order

async def fallback_action():

global pending_sell_order

await asyncio.sleep((config['trade_configs'][selected_config]['sell_fallback_timeout_ms']/1000))

if pending_sell_order == None:
    pending_sell_order = market_order(client, selected_coin_pair, 'sell', coin_pair_info, balance)

Save orders to local db asynchronously

def insert_into_db(order):

c.execute("INSERT INTO Orders VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 
        ("Binance", order['clientOrderId'], order['orderId'], order['fills'][0]['tradeId'], 
            order['symbol'], order['type'], order['side'], order['timeInForce'],
            order['transactTime'], order['fills'][0]['commissionAsset'],
            order['fills'][0]['price'], order['fills'][0]['commission'],
            order['fills'][0]['qty'], order['cummulativeQuoteQty']))

conn.commit()

async def main():

coin_pair_info = client.get_symbol_info(selected_coin_pair)

start_time = time.time()

buy_order = market_order(client, selected_coin_pair, 'buy', coin_pair_info, balance)

# Execution using threading
with concurrent.futures.ThreadPoolExecutor() as executor:
    
    #Print buy order details
    buy_order_details = executor.submit(display_order_details, buy_order)
    print('\n' + buy_order_details.result() + '\n')

    sell_order = await check_margin()

end_time = time.time()
sell_order_details = display_order_details(sell_order)
print('\n' + sell_order_details + '\n')

insert_into_db(order=buy_order)
insert_into_db(order=sell_order)

conn.close()

balance2 = acct_balance2()
pump_duration(start_time, end_time)

if name == 'main':

show_header()
client = Client(config["api_key"], config["api_secret"])
if config['debug_mode']:
    debug_mode(client=client)
    print('\n')

print(Fore.YELLOW + '-- Binance Edition --\n' + Fore.RESET)

#Start Telegram API
Tlgclient = TelegramClient(Telegramconfig['UserName'], Telegramconfig['api_id'], Telegramconfig['api_hash']).start()
selected_coin = ''

#Telegram Event
#@Tlgclient.on(events.NewMessage)
@Tlgclient.on(events.NewMessage(chats=(Telegramconfig['group_username'])))
async def my_event_handler(event):
    clean = event.message.message.upper()
    if ':' in clean:
        clean = clean.split(":") # remove before ':' if present in string
        clean = clean[1]
    clean = re.search(r"(\b\w[A-Z]+)", clean)	
    clean = clean.group()
    global selected_coin
    selected_coin = clean


Tlgclient.start()
#Tlgclient.run_until_disconnected()

#Question1
answer1 = Inquirer.prompt(question1)
selected_config = answer1['trade_conf']

#Retrieve current coin balance here
balance = acct_balance()

#Question2
#answer2 = Inquirer.prompt(question2)
#selected_coin = answer2['coin']
print('Wait for Telegram message')
async def main():
    while (selected_coin == ''):
        #print('Wait Telegram')
        await asyncio.sleep(0.01)
Tlgclient.loop.run_until_complete(main())    

#Coin Pair
selected_coin_pair = selected_coin.upper() + \
                        config['trade_configs'][selected_config]['pairing']

buy_order = None
coin_pair_info = None
pending_sell_order = None
print('Receive : ' + selected_coin_pair)

asyncio.run(main())

@calamarcus
Copy link

i tried telegram with binance just now. i think it took 5 seconds for the telegram message to reach the function. That will not work unless there is something to do to fix it..

@calamarcus
Copy link

And i am getting the message fast in my telegram windows app, and 4-5 seconds later in the python function.

@ffbboy30
Copy link

I test the code with a chat channel it works without delay.
I've seen that some channel are able to detect Bot and add 5 to 12 sec delay.
Maybe you can test on chat channel maybe the problem is on your side ?
Which channel do you test ?

@calamarcus
Copy link

@abayomi185
Copy link
Owner

abayomi185 commented May 26, 2021

Hey @calamarcus and @ffbboy30 how do I go about getting the group channel id?

@calamarcus
Copy link

If you click on the name of the channel, in the telegram window you should see the channel properties.

Possibly even right click on the channelname in the list of channels on the left side in telegram, to get a dropdown option list.

@abayomi185
Copy link
Owner

What platform and client should I do this on? I have yet to see it on the web client and iOS app

@calamarcus
Copy link

calamarcus commented May 26, 2021 via email

@ffbboy30
Copy link

I've just start a Discord server to list all the usefull pump channel without VIP or pre pump.
If you have some informations informations I will add them .
I don't know how it works but the channel ID is : 847330841586696193 and the name of the server is pumpchannellist's server
and the link https://discord.gg/CWvNtX4T

@abayomi185
Copy link
Owner

Just an update, I have done some testing and I'm able to get messages from telegram groups with no perceivable delay. I have yet to parse the messages and feed them into the exchange bot.

I am able to commit time into this after next week. If you have more suggestions. I'm happy to hear and implement them.

@ffbboy30
Copy link

ffbboy30 commented Jun 4, 2021 via email

@abayomi185
Copy link
Owner

abayomi185 commented Jun 8, 2021

I am doing some testing @ffbboy30 Your regex was helpful. I've refined it to allow for different text formats.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants