Skip to content
This repository has been archived by the owner on May 13, 2024. It is now read-only.

Commit

Permalink
Merge branch 'release/0.5.2'
Browse files Browse the repository at this point in the history
  • Loading branch information
beeb committed Aug 31, 2021
2 parents 0bb616e + d0fda39 commit 96b2a0e
Show file tree
Hide file tree
Showing 12 changed files with 55 additions and 41 deletions.
5 changes: 3 additions & 2 deletions pancaketrade/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ def get_token_status(self, token: TokenWatcher) -> Tuple[str, Decimal]:
token_lp = self.net.find_lp_address(token_address=token.address, v2=lp_v2)
if token_lp:
chart_links.append(f'<a href="https://www.dextools.io/app/pancakeswap/pair-explorer/{token_lp}">Dext</a>')
chart_links.append(f'<a href="https://bscscan.com/token/{token.address}?a={self.net.wallet}">BscScan</a>')
token_price_usd = self.net.get_token_price_usd(
token_address=token.address, token_decimals=token.decimals, sell=True, token_price=token_price
)
Expand All @@ -353,7 +354,7 @@ def get_token_status(self, token: TokenWatcher) -> Tuple[str, Decimal]:
orders = [str(order) for order in orders_sorted]
message = (
f'<b>{token.name}</b>: {format_token_amount(token_balance)}\n'
+ f'<b>Charts</b>: {" ".join(chart_links)}\n'
+ f'<b>Links</b>: {" ".join(chart_links)}\n'
+ f'<b>Value</b>: <code>{token_balance_bnb:.3g}</code> BNB (${token_balance_usd:.2f})\n'
+ f'<b>Price</b>: <code>{token_price:.3g}</code> BNB/token (${token_price_usd:.3g})\n'
+ effective_buy_price
Expand All @@ -371,7 +372,7 @@ def get_summary_message(self, token_balances: List[Decimal]) -> Tuple[str, List[
f'<b>BNB balance</b>: <code>{balance_bnb:.4f}</code> BNB (${balance_bnb * price_bnb:.2f})\n'
+ f'<b>Tokens balance</b>: <code>{total_positions:.4f}</code> BNB (${total_positions * price_bnb:.2f})\n'
+ f'<b>Total</b>: <code>{grand_total:.4f}</code> BNB (${grand_total * price_bnb:.2f}) '
+ f'<a href="https://bscscan.com/address/{self.net.wallet}">BSCScan</a>\n'
+ f'<a href="https://bscscan.com/address/{self.net.wallet}">BscScan</a>\n'
+ f'<b>BNB price</b>: ${price_bnb:.2f}\n'
+ 'Which action do you want to perform next?'
)
Expand Down
17 changes: 10 additions & 7 deletions pancaketrade/conversations/addorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,13 +327,13 @@ def command_addorder_amount(self, update: Update, context: CallbackContext):
InlineKeyboardButton(
f'{token.default_slippage}% (default)', callback_data=str(token.default_slippage)
),
InlineKeyboardButton('0.5%', callback_data='0.5'),
InlineKeyboardButton('1%', callback_data='1'),
InlineKeyboardButton('2%', callback_data='2'),
InlineKeyboardButton('5%', callback_data='5'),
],
[
InlineKeyboardButton('5%', callback_data='5'),
InlineKeyboardButton('10%', callback_data='10'),
InlineKeyboardButton('12%', callback_data='12'),
InlineKeyboardButton('15%', callback_data='15'),
InlineKeyboardButton('20%', callback_data='20'),
],
Expand Down Expand Up @@ -367,18 +367,21 @@ def command_addorder_slippage(self, update: Update, context: CallbackContext):
self.cancel_command(update, context)
return ConversationHandler.END
try:
slippage_percent = int(query.data)
except ValueError:
slippage_percent = Decimal(query.data)
except Exception:
self.command_error(update, context, text='The slippage is not recognized.')
return ConversationHandler.END
else:
assert update.message and update.message.text
try:
slippage_percent = int(update.message.text.strip())
except ValueError:
slippage_percent = Decimal(update.message.text.strip())
except Exception:
chat_message(update, context, text='⚠️ The slippage is not recognized, try again:', edit=False)
return self.next.SLIPPAGE
order['slippage'] = slippage_percent
if slippage_percent < Decimal("0.01") or slippage_percent > 100:
chat_message(update, context, text='⚠️ The slippage must be between 0.01 and 100, try again:', edit=False)
return self.next.SLIPPAGE
order['slippage'] = f'{slippage_percent:.2f}'
network_gas_price = Decimal(self.net.w3.eth.gas_price) / Decimal(10 ** 9)
chat_message(
update,
Expand Down
15 changes: 8 additions & 7 deletions pancaketrade/conversations/addtoken.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import NamedTuple
from decimal import Decimal

from pancaketrade.network import Network
from pancaketrade.persistence import Token, db
Expand Down Expand Up @@ -130,26 +131,26 @@ def command_addtoken_noemoji(self, update: Update, context: CallbackContext):
def command_addtoken_slippage(self, update: Update, context: CallbackContext):
assert update.message and update.message.text and context.user_data is not None
try:
slippage = int(update.message.text.strip())
except ValueError:
slippage = Decimal(update.message.text.strip())
except Exception:
chat_message(
update,
context,
text='⚠️ This is not a valid slippage value. Please enter an integer number for percentage. Try again:',
text='⚠️ This is not a valid slippage value. Please enter a decimal number for percentage. Try again:',
edit=False,
)
return self.next.SLIPPAGE
if slippage < 1:
if slippage < Decimal("0.01") or slippage > 100:
chat_message(
update,
context,
text='⚠️ This is not a valid slippage value. Please enter a positive integer number for percentage. '
+ 'Try again:',
text='⚠️ This is not a valid slippage value. Please enter a number between 0.01 and 100 for '
+ 'percentage. Try again:',
edit=False,
)
return self.next.SLIPPAGE
add = context.user_data['addtoken']
add['default_slippage'] = slippage
add['default_slippage'] = f'{slippage:.2f}'
emoji = add['icon'] + ' ' if add['icon'] else ''

chat_message(
Expand Down
2 changes: 1 addition & 1 deletion pancaketrade/conversations/buysell.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ def command_buysell_summary(self, update: Update, context: CallbackContext):
add['limit_price'] = '' # we provide empty string meaning we use market price (trigger now)
add['above'] = True if add['type'] == 'sell' else False
token: TokenWatcher = self.parent.watchers[add['token_address']]
add['slippage'] = token.default_slippage
add['slippage'] = f'{token.default_slippage:.2f}'
add['gas_price'] = '+10.1'
del add['token_address'] # not needed in order record creation
try:
Expand Down
24 changes: 12 additions & 12 deletions pancaketrade/conversations/edittoken.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def command_edittoken_action(self, update: Update, context: CallbackContext):
return self.next.EMOJI
elif query.data == 'slippage':
buttons = [
InlineKeyboardButton(f'Keep {token.default_slippage}%', callback_data=token.default_slippage),
InlineKeyboardButton(f'Keep {token.default_slippage}%', callback_data=str(token.default_slippage)),
InlineKeyboardButton('❌ Cancel', callback_data='cancel'),
]
reply_markup = InlineKeyboardMarkup([buttons])
Expand Down Expand Up @@ -200,13 +200,13 @@ def command_edittoken_slippage(self, update: Update, context: CallbackContext):
if update.message is not None:
assert update.message.text
try:
slippage = int(update.message.text.strip())
except ValueError:
slippage = Decimal(update.message.text.strip())
except Exception:
chat_message(
update,
context,
text='⚠️ This is not a valid slippage value. Please enter an integer number for percentage '
+ '(without percent sign). Try again:',
text='⚠️ This is not a valid slippage value. Please enter a number between 0.01 and 100 for '
+ 'percentage (without percent sign). Try again:',
edit=False,
)
return self.next.SLIPPAGE
Expand All @@ -217,20 +217,20 @@ def command_edittoken_slippage(self, update: Update, context: CallbackContext):
if query.data == 'cancel':
return self.command_canceltoken(update, context)
try:
slippage = int(query.data)
except ValueError:
slippage = Decimal(query.data)
except Exception:
self.command_error(update, context, text='Invalid default slippage.')
return ConversationHandler.END
if slippage < 1:
if slippage < Decimal("0.01") or slippage > 100:
chat_message(
update,
context,
text='⚠️ This is not a valid slippage value. Please enter a positive integer number for percentage. '
+ 'Try again:',
text='⚠️ This is not a valid slippage value. Please enter a number between 0.01 and 100 for '
+ 'percentage. Try again:',
edit=False,
)
return self.next.SLIPPAGE
edit['default_slippage'] = slippage
edit['default_slippage'] = f'{slippage:.2f}'

token_record = token.token_record
try:
Expand All @@ -244,7 +244,7 @@ def command_edittoken_slippage(self, update: Update, context: CallbackContext):
finally:
del context.user_data['edittoken']
db.close()
token.default_slippage = token_record.default_slippage
token.default_slippage = Decimal(token_record.default_slippage)
chat_message(
update,
context,
Expand Down
3 changes: 2 additions & 1 deletion pancaketrade/conversations/sellall.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,11 @@ def command_sellall_confirm(self, update: Update, context: CallbackContext):
)
return ConversationHandler.END
logger.success(f'Sell transaction succeeded. Received {bnb_out:.3g} BNB')
usd_out = self.net.get_bnb_price() * bnb_out
chat_message(
update,
context,
text=f'✅ Got {bnb_out:.3g} BNB at '
text=f'✅ Got {bnb_out:.3g} BNB (${usd_out:.2f}) at '
+ f'tx <a href="https://bscscan.com/tx/{txhash_or_error}">{txhash_or_error[:8]}...</a>',
edit=self.config.update_messages,
)
Expand Down
8 changes: 4 additions & 4 deletions pancaketrade/network/bsc.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,15 +319,15 @@ def buy_tokens(
self,
token_address: ChecksumAddress,
amount_bnb: Wei,
slippage_percent: int,
slippage_percent: Decimal,
gas_price: Optional[str],
v2: bool = True,
) -> Tuple[bool, Decimal, str]:
balance_bnb = self.w3.eth.get_balance(self.wallet)
if amount_bnb > balance_bnb - Wei(2000000000000000): # leave 0.002 BNB for future gas fees
logger.error('Not enough BNB balance')
return False, Decimal(0), 'Not enough BNB balance'
slippage_ratio = (Decimal(100) - Decimal(slippage_percent)) / Decimal(100)
slippage_ratio = (Decimal(100) - slippage_percent) / Decimal(100)
final_gas_price = self.w3.eth.gas_price
if gas_price is not None and gas_price.startswith('+'):
offset = Web3.toWei(Decimal(gas_price) * Decimal(10 ** 9), unit='wei')
Expand Down Expand Up @@ -394,13 +394,13 @@ def sell_tokens(
self,
token_address: ChecksumAddress,
amount_tokens: Wei,
slippage_percent: int,
slippage_percent: Decimal,
gas_price: Optional[str],
v2: bool = True,
) -> Tuple[bool, Decimal, str]:
balance_tokens = self.get_token_balance_wei(token_address=token_address)
amount_tokens = min(amount_tokens, balance_tokens) # partially fill order if possible
slippage_ratio = (Decimal(100) - Decimal(slippage_percent)) / Decimal(100)
slippage_ratio = (Decimal(100) - slippage_percent) / Decimal(100)
final_gas_price = self.w3.eth.gas_price
if gas_price is not None and gas_price.startswith('+'):
offset = Web3.toWei(Decimal(gas_price) * Decimal(10 ** 9), unit='wei')
Expand Down
4 changes: 2 additions & 2 deletions pancaketrade/persistence/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Token(Model):
symbol = CharField()
icon = CharField(null=True) # emoji
decimals = SmallIntegerField()
default_slippage = SmallIntegerField()
default_slippage = FixedCharField(max_length=7)
effective_buy_price = CharField(null=True)

class Meta:
Expand All @@ -31,7 +31,7 @@ class Order(Model):
above = BooleanField() # Above = True, below = False
trailing_stop = SmallIntegerField(null=True) # in percent
amount = CharField() # in wei, either BNB or token depending on "type"
slippage = SmallIntegerField()
slippage = FixedCharField(max_length=7)
# gas price in wei, if null then use network gas price.
# If starts with "+", then we add this amount of gwei to default network price
gas_price = CharField(null=True)
Expand Down
9 changes: 8 additions & 1 deletion pancaketrade/utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pancaketrade.persistence import Order, Token, db
from pancaketrade.utils.config import Config
from pancaketrade.watchers.token import TokenWatcher
from peewee import fn
from peewee import fn, FixedCharField
from playhouse.migrate import SqliteMigrator, migrate
from telegram.ext import Dispatcher
from web3.types import ChecksumAddress
Expand All @@ -16,10 +16,17 @@ def init_db() -> None:
db.create_tables([Token, Order])
columns = db.get_columns('token')
column_names = [c.name for c in columns]
default_slippage_column = [c for c in columns if c.name == 'default_slippage'][0]
order_columns = db.get_columns('order')
order_slippage_column = [c for c in order_columns if c.name == 'slippage'][0]
migrator = SqliteMigrator(db)
with db.atomic():
if 'effective_buy_price' not in column_names:
migrate(migrator.add_column('token', 'effective_buy_price', Token.effective_buy_price))
if default_slippage_column.data_type == 'INTEGER':
migrate(migrator.alter_column_type('token', 'default_slippage', FixedCharField(max_length=7)))
if order_slippage_column.data_type == 'INTEGER':
migrate(migrator.alter_column_type('order', 'slippage', FixedCharField(max_length=7)))


def token_exists(address: ChecksumAddress) -> bool:
Expand Down
5 changes: 3 additions & 2 deletions pancaketrade/watchers/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def __init__(self, order_record: Order, net: Network, dispatcher: Dispatcher, ch
self.above = order_record.above # Above = True, below = False
self.trailing_stop: Optional[int] = order_record.trailing_stop # in percent
self.amount = Wei(int(order_record.amount)) # in wei, either BNB (buy) or token (sell) depending on "type"
self.slippage = order_record.slippage # in percent
self.slippage = Decimal(order_record.slippage) # in percent
# gas price in wei or offset from default in gwei (starts with +), if null then use network gas price
self.gas_price: Optional[str] = order_record.gas_price
self.created = order_record.created
Expand Down Expand Up @@ -273,9 +273,10 @@ def sell(self, v2: bool):
self.dispatcher.bot.send_message(
chat_id=self.chat_id, text='<u>Closing the following order:</u>\n' + self.long_str()
)
usd_out = self.net.get_bnb_price() * bnb_out
self.dispatcher.bot.send_message(
chat_id=self.chat_id,
text=f'✅ Got {bnb_out:.3g} BNB at '
text=f'✅ Got {bnb_out:.3g} BNB (${usd_out:.2f}) at '
+ f'tx <a href="https://bscscan.com/tx/{txhash_or_error}">{txhash_or_error[:8]}...</a>\n'
+ f'Effective price (after tax) {effective_price:.4g} BNB/token.\n'
+ f'This order sold {sold_proportion:.1%} of the token\'s balance.',
Expand Down
2 changes: 1 addition & 1 deletion pancaketrade/watchers/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(
self.symbol = str(token_record.symbol)
self.emoji = token_record.icon + ' ' if token_record.icon else ''
self.name = self.emoji + self.symbol
self.default_slippage = token_record.default_slippage
self.default_slippage = Decimal(token_record.default_slippage)
self.effective_buy_price: Optional[Decimal] = (
Decimal(token_record.effective_buy_price) if token_record.effective_buy_price else None
)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "pancaketrade"
version = "0.5.1"
version = "0.5.2"
description = "Trading bot for PancakeSwap"
authors = ["Valentin Bersier <[email protected]>"]

Expand Down

0 comments on commit 96b2a0e

Please sign in to comment.