class Token(dict): """ steem-engine token dict :param str token: Name of the token """ def __init__(self, symbol, api=None): if api is None: self.api = Api() else: self.api = api if isinstance(symbol, dict): self.symbol = symbol["symbol"] super(Token, self).__init__(symbol) else: self.symbol = symbol.upper() self.refresh() def refresh(self): info = self.get_info() if info is None: raise TokenDoesNotExists("Token %s does not exists!" % self.symbol) super(Token, self).__init__(info) def quantize(self, amount): """Round down a amount using the token precision and returns a Decimal object""" amount = decimal.Decimal(amount) places = decimal.Decimal(10) ** (-self["precision"]) return amount.quantize(places, rounding=decimal.ROUND_DOWN) def get_info(self): """Returns information about the token""" token = self.api.find_one("tokens", "tokens", query={"symbol": self.symbol}) if len(token) > 0: return token[0] else: return token def get_holder(self, limit=1000, offset=0): """Returns all token holders""" holder = self.api.find("tokens", "balances", query={"symbol": self.symbol}, limit=limit, offset=offset) return holder def get_market_info(self): """Returns market information""" metrics = self.api.find_one("market", "metrics", query={"symbol": self.symbol}) if len(metrics) > 0: return metrics[0] else: return metrics def get_buy_book(self, limit=100, offset=0): """Returns the buy book""" holder = self.api.find("market", "buyBook", query={"symbol": self.symbol}, limit=limit, offset=offset) return holder def get_sell_book(self, limit=100, offset=0): """Returns the sell book""" holder = self.api.find("market", "sellBook", query={"symbol": self.symbol}, limit=limit, offset=offset) return holder
def __init__(self, api=None, steem_instance=None): if api is None: self.api = Api() else: self.api = api self.steem = steem_instance or shared_steem_instance() self.tokens = Tokens(api=self.api) self.ssc_id = "ssc-mainnet1" self.refresh()
def __init__(self, account, api=None, steem_instance=None): if api is None: self.api = Api() else: self.api = api self.ssc_id = "ssc-mainnet1" self.steem = steem_instance or shared_steem_instance() check_account = Account(account, steem_instance=self.steem) self.account = check_account["name"] self.refresh()
def __init__(self, symbol, api=None): if api is None: self.api = Api() else: self.api = api if isinstance(symbol, dict): self.symbol = symbol["symbol"] super(Token, self).__init__(symbol) else: self.symbol = symbol.upper() self.refresh()
class Tokens(list): """ Access the steem-engine tokens """ def __init__(self, api=None, **kwargs): if api is None: self.api = Api() else: self.api = api self.refresh() def refresh(self): super(Tokens, self).__init__(self.get_token_list()) def get_token_list(self): """Returns all available token as list""" tokens = self.api.find("tokens", "tokens", query={}) return tokens def get_token(self, symbol): """Returns Token from given token symbol. Is None when token does not exists. """ for t in self: if t["symbol"].lower() == symbol.lower(): return Token(t, api=self.api) return None
def test_api(self): api = Api() result = api.get_latest_block_info() self.assertTrue(len(result) > 0) result = api.get_block_info(1910) self.assertTrue(len(result) > 0) result = api.get_transaction_info( "e6c7f351b3743d1ed3d66eb9c6f2c102020aaa5d") self.assertTrue(len(result) > 0) result = api.get_contract("tokens") self.assertTrue(len(result) > 0) result = api.find("tokens", "tokens") self.assertTrue(len(result) > 0) result = api.find_one("tokens", "tokens") self.assertTrue(len(result) > 0) result = api.get_history("holger80", "NINJA") self.assertTrue(len(result) > 0)
from steemengine.market import Market import time import random import schedule import json from dhooks import Webhook import math from beem.nodelist import NodeList import json import six import requests import getpass beem_pass = "" # Password to unlock beem wallet api = Api() tokens = Tokens() token = Token("TMPS") stm = Steem() market = Market(steem_instance=stm) wallet = Wallet("tmps", steem_instance=stm) wallet2 = Wallet("market", steem_instance=stm) stm.wallet.unlock(pwd=beem_pass) blacklist = ["market", "tokens", "null", "tmps"] dragon_token = wallet.get_token("TMPS") wallet.refresh() upvote_account = "ufm.pay" adjusted_dragon = float(dragon_token["balance"]) * 0.95 balances = token.get_holder() info = token.get_info() max_post_age_days = 6
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import time from beem import Steem from beem.nodelist import NodeList from steemengine.api import Api from steemengine.wallet import Wallet if __name__ == "__main__": nodelist = NodeList() nodelist.update_nodes() stm = Steem(node=nodelist.get_nodes()) api = Api() wallet = Wallet("ufm.pay") # edit here upvote_account = "ufm.pay" upvote_token = "KITTENS" token_weight_factor = 1 # multiply token amount to get weight kitten_ratio = 20 stm = Steem() stm.wallet.unlock(pwd="") wallet = Wallet(upvote_account, steem_instance=stm) stamps = [] whitelist = [] blacklist = ["market", "tokens"] last_steem_block = 1950 # It is a good idea to store this block, otherwise all transfers will be checked again while True: main_token = wallet.get_token("CATS")
class Market(list): """ Access the steem-engine market :param Steem steem_instance: Steem instance """ def __init__(self, api=None, steem_instance=None): if api is None: self.api = Api() else: self.api = api self.steem = steem_instance or shared_steem_instance() self.tokens = Tokens(api=self.api) self.ssc_id = "ssc-mainnet1" self.refresh() def refresh(self): super(Market, self).__init__(self.get_metrics()) def set_id(self, ssc_id): """Sets the ssc id (default is ssc-mainnet1)""" self.ssc_id = ssc_id def get_metrics(self): """Returns all token within the wallet as list""" metrics = self.api.find("market", "metrics", query={}) return metrics def get_buy_book(self, symbol, account=None, limit=100, offset=0): """Returns the buy book for a given symbol. When account is set, the order book from the given account is shown. """ if self.tokens.get_token(symbol) is None: raise TokenDoesNotExists("%s does not exists" % symbol) if account is None: buy_book = self.api.find("market", "buyBook", query={"symbol": symbol.upper()}, limit=limit, offset=offset) else: buy_book = self.api.find("market", "buyBook", query={"symbol": symbol.upper(), "account": account}, limit=limit, offset=offset) return buy_book def get_sell_book(self, symbol, account=None, limit=100, offset=0): """Returns the sell book for a given symbol. When account is set, the order book from the given account is shown. """ if self.tokens.get_token(symbol) is None: raise TokenDoesNotExists("%s does not exists" % symbol) if account is None: sell_book = self.api.find("market", "sellBook", query={"symbol": symbol.upper()}, limit=limit, offset=offset) else: sell_book = self.api.find("market", "sellBook", query={"symbol": symbol.upper(), "account": account}, limit=limit, offset=offset) return sell_book def get_trades_history(self, symbol, account=None, limit=30, offset=0): """Returns the trade history for a given symbol. When account is set, the trade history from the given account is shown. """ if self.tokens.get_token(symbol) is None: raise TokenDoesNotExists("%s does not exists" % symbol) if account is None: trades_history = self.api.find("market", "tradesHistory", query={"symbol": symbol.upper()}, limit=limit, offset=offset) else: trades_history = self.api.find("market", "tradesHistory", query={"symbol": symbol.upper(), "account": account}, limit=limit, offset=offset) return trades_history def withdraw(self, account, amount): """Widthdraw STEEMP to account as STEEM. :param str account: account name :param float amount: Amount to withdraw Withdraw example: .. code-block:: python from steemengine.market import Market from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) market = Market(steem_instance=stm) market.withdraw("test", 1) """ wallet = Wallet(account, api=self.api, steem_instance=self.steem) token_in_wallet = wallet.get_token("STEEMP") if token_in_wallet is None: raise TokenNotInWallet("%s is not in wallet." % "STEEMP") if float(token_in_wallet["balance"]) < float(amount): raise InsufficientTokenAmount("Only %.3f in wallet" % float(token_in_wallet["balance"])) token = Token("STEEMP", api=self.api) quant_amount = token.quantize(amount) if quant_amount <= decimal.Decimal("0"): raise InvalidTokenAmount("Amount to transfer is below token precision of %d" % token["precision"]) contract_payload = {"quantity":str(quant_amount)} json_data = {"contractName":"steempegged","contractAction":"withdraw", "contractPayload":contract_payload} tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[account]) return tx def deposit(self, account, amount): """Deposit STEEM to market in exchange for STEEMP. :param str account: account name :param float amount: Amount to deposit Deposit example: .. code-block:: python from steemengine.market import Market from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) market = Market(steem_instance=stm) market.deposit("test", 1) """ acc = Account(account, steem_instance=self.steem) steem_balance = acc.get_balance("available", "STEEM") if float(steem_balance) < float(amount): raise InsufficientTokenAmount("Only %.3f in wallet" % float(steem_balance)) json_data = '{"id":"' + self.ssc_id + '","json":{"contractName":"steempegged","contractAction":"buy","contractPayload":{}}}' tx = acc.transfer("steem-peg", amount, "STEEM", memo=json_data) return tx def buy(self, account, amount, symbol, price): """Buy token for given price. :param str account: account name :param float amount: Amount to withdraw :param str symbol: symbol :param float price: price Buy example: .. code-block:: python from steemengine.market import Market from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) market = Market(steem_instance=stm) market.buy("test", 1, "ENG", 0.95) """ wallet = Wallet(account, api=self.api, steem_instance=self.steem) token_in_wallet = wallet.get_token("STEEMP") if token_in_wallet is None: raise TokenNotInWallet("%s is not in wallet." % "STEEMP") if float(token_in_wallet["balance"]) < float(amount) * float(price): raise InsufficientTokenAmount("Only %.3f in wallet" % float(token_in_wallet["balance"])) token = Token(symbol, api=self.api) quant_amount = token.quantize(amount) if quant_amount <= decimal.Decimal("0"): raise InvalidTokenAmount("Amount to transfer is below token precision of %d" % token["precision"]) contract_payload = {"symbol": symbol.upper(), "quantity":str(quant_amount), "price": str(price)} json_data = {"contractName":"market","contractAction":"buy", "contractPayload":contract_payload} tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[account]) return tx def sell(self, account, amount, symbol, price): """Sell token for given price. :param str account: account name :param float amount: Amount to withdraw :param str symbol: symbol :param float price: price Sell example: .. code-block:: python from steemengine.market import Market from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) market = Market(steem_instance=stm) market.sell("test", 1, "ENG", 0.95) """ wallet = Wallet(account, api=self.api, steem_instance=self.steem) token_in_wallet = wallet.get_token(symbol) if token_in_wallet is None: raise TokenNotInWallet("%s is not in wallet." % symbol) if float(token_in_wallet["balance"]) < float(amount): raise InsufficientTokenAmount("Only %.3f in wallet" % float(token_in_wallet["balance"])) token = Token(symbol, api=self.api) quant_amount = token.quantize(amount) if quant_amount <= decimal.Decimal("0"): raise InvalidTokenAmount("Amount to transfer is below token precision of %d" % token["precision"]) contract_payload = {"symbol": symbol.upper(), "quantity":str(quant_amount), "price": str(price)} json_data = {"contractName":"market","contractAction":"sell", "contractPayload":contract_payload} tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[account]) return tx def cancel(self, account, order_type, order_id): """Cancel buy/sell order. :param str account: account name :param str order_type: sell or buy :param int order_id: order id Cancel example: .. code-block:: python from steemengine.market import Market from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) market = Market(steem_instance=stm) market.sell("test", "sell", 12) """ contract_payload = {"type": order_type, "id": order_id} json_data = {"contractName":"market","contractAction":"cancel", "contractPayload":contract_payload} tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[account]) return tx
def __init__(self, api=None, **kwargs): if api is None: self.api = Api() else: self.api = api self.refresh()
class Wallet(list): """ Access the steem-engine wallet :param str account: Name of the account :param Steem steem_instance: Steem instance Wallet example: .. code-block:: python from steemengine.wallet import Wallet wallet = Wallet("test") print(wallet) """ def __init__(self, account, api=None, steem_instance=None): if api is None: self.api = Api() else: self.api = api self.ssc_id = "ssc-mainnet1" self.steem = steem_instance or shared_steem_instance() check_account = Account(account, steem_instance=self.steem) self.account = check_account["name"] self.refresh() def refresh(self): super(Wallet, self).__init__(self.get_balances()) def set_id(self, ssc_id): """Sets the ssc id (default is ssc-mainnet1)""" self.ssc_id = ssc_id def get_balances(self): """Returns all token within the wallet as list""" balances = self.api.find("tokens", "balances", query={"account": self.account}) return balances def change_account(self, account): """Changes the wallet account""" check_account = Account(account, steem_instance=self.steem) self.account = check_account["name"] self.refresh() def get_token(self, symbol): """Returns a token from the wallet. Is None when not available.""" for token in self: if token["symbol"].lower() == symbol.lower(): return token return None def transfer(self, to, amount, symbol, memo=""): """Transfer a token to another account. :param str to: Recipient :param float amount: Amount to transfer :param str symbol: Token to transfer :param str memo: (optional) Memo Transfer example: .. code-block:: python from steemengine.wallet import Wallet from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) wallet = Wallet("test", steem_instance=stm) wallet.transfer("test1", 1, "ENG", "test") """ token_in_wallet = self.get_token(symbol) if token_in_wallet is None: raise TokenNotInWallet("%s is not in wallet." % symbol) if float(token_in_wallet["balance"]) < float(amount): raise InsufficientTokenAmount("Only %.3f in wallet" % float(token_in_wallet["balance"])) token = Token(symbol, api=self.api) quant_amount = token.quantize(amount) if quant_amount <= decimal.Decimal("0"): raise InvalidTokenAmount( "Amount to transfer is below token precision of %d" % token["precision"]) check_to = Account(to, steem_instance=self.steem) contract_payload = { "symbol": symbol.upper(), "to": to, "quantity": str(quant_amount), "memo": memo } json_data = { "contractName": "tokens", "contractAction": "transfer", "contractPayload": contract_payload } tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[self.account]) return tx def stake(self, amount, symbol): """Stake a token. :param float amount: Amount to stake :param str symbol: Token to stake Stake example: .. code-block:: python from steemengine.wallet import Wallet from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) wallet = Wallet("test", steem_instance=stm) wallet.stake(1, "ENG") """ token_in_wallet = self.get_token(symbol) if token_in_wallet is None: raise TokenNotInWallet("%s is not in wallet." % symbol) if float(token_in_wallet["balance"]) < float(amount): raise InsufficientTokenAmount("Only %.3f in wallet" % float(token_in_wallet["balance"])) token = Token(symbol, api=self.api) quant_amount = token.quantize(amount) if quant_amount <= decimal.Decimal("0"): raise InvalidTokenAmount( "Amount to stake is below token precision of %d" % token["precision"]) contract_payload = { "symbol": symbol.upper(), "quantity": str(quant_amount) } json_data = { "contractName": "tokens", "contractAction": "stake", "contractPayload": contract_payload } tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[self.account]) return tx def unstake(self, amount, symbol): """Unstake a token. :param float amount: Amount to unstake :param str symbol: Token to unstake Unstake example: .. code-block:: python from steemengine.wallet import Wallet from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) wallet = Wallet("test", steem_instance=stm) wallet.unstake(1, "ENG") """ token_in_wallet = self.get_token(symbol) if token_in_wallet is None: raise TokenNotInWallet("%s is not in wallet." % symbol) if "stake" not in token_in_wallet: raise InsufficientTokenAmount("Token cannot be unstaked") if float(token_in_wallet["stake"]) < float(amount): raise InsufficientTokenAmount( "Only %.3f are staked in the wallet" % float(token_in_wallet["stake"])) token = Token(symbol, api=self.api) quant_amount = token.quantize(amount) if quant_amount <= decimal.Decimal("0"): raise InvalidTokenAmount( "Amount to stake is below token precision of %d" % token["precision"]) contract_payload = { "symbol": symbol.upper(), "quantity": str(quant_amount) } json_data = { "contractName": "tokens", "contractAction": "unstake", "contractPayload": contract_payload } tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[self.account]) return tx def cancel_unstake(self, trx_id): """Cancel unstaking a token. :param str trx_id: transaction id in which the tokan was unstaked Cancel unstake example: .. code-block:: python from steemengine.wallet import Wallet from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) wallet = Wallet("test", steem_instance=stm) wallet.stake("cf39ecb8b846f1efffb8db526fada21a5fcf41c3") """ contract_payload = {"txID": trx_id} json_data = { "contractName": "tokens", "contractAction": "cancelUnstake", "contractPayload": contract_payload } tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[self.account]) return tx def issue(self, to, amount, symbol): """Issues a specific token amount. :param str to: Recipient :param float amount: Amount to issue :param str symbol: Token to issue Issue example: .. code-block:: python from steemengine.wallet import Wallet from beem import Steem active_wif = "5xxxx" stm = Steem(keys=[active_wif]) wallet = Wallet("test", steem_instance=stm) wallet.issue(1, "my_token") """ token = Token(symbol, api=self.api) if token["issuer"] != self.account: raise TokenIssueNotPermitted("%s is not the issuer of token %s" % (self.account, symbol)) if token["maxSupply"] == token["supply"]: raise MaxSupplyReached("%s has reached is maximum supply of %d" % (symbol, token["maxSupply"])) quant_amount = token.quantize(amount) if quant_amount <= decimal.Decimal("0"): raise InvalidTokenAmount( "Amount to issue is below token precision of %d" % token["precision"]) check_to = Account(to, steem_instance=self.steem) contract_payload = { "symbol": symbol.upper(), "to": to, "quantity": str(quant_amount) } json_data = { "contractName": "tokens", "contractAction": "issue", "contractPayload": contract_payload } tx = self.steem.custom_json(self.ssc_id, json_data, required_auths=[self.account]) return tx def get_history(self, symbol, limit=1000, offset=0): """Returns the transfer history of a token""" return self.api.get_history(self.account, symbol, limit, offset) def get_buy_book(self, symbol=None, limit=100, offset=0): """Returns the buy book for the wallet account. When symbol is set, the order book from the given token is shown. """ if symbol is None: buy_book = self.api.find("market", "buyBook", query={"account": self.account}, limit=limit, offset=offset) else: buy_book = self.api.find("market", "buyBook", query={ "symbol": symbol, "account": self.account }, limit=limit, offset=offset) return buy_book def get_sell_book(self, symbol=None, limit=100, offset=0): """Returns the sell book for the wallet account. When symbol is set, the order book from the given token is shown. """ if symbol is None: sell_book = self.api.find("market", "sellBook", query={"account": self.account}, limit=limit, offset=offset) else: sell_book = self.api.find("market", "sellBook", query={ "symbol": symbol, "account": self.account }, limit=limit, offset=offset) return sell_book
def info(objects): """ Show basic blockchain info General information about steem-engine, a block, an account, a token, and a transaction id """ stm = None api = Api() if not objects: latest_block = api.get_latest_block_info() tokens = Tokens() t = PrettyTable(["Key", "Value"]) t.align = "l" t.add_row(["latest block number", latest_block["blockNumber"]]) t.add_row(["latest steem block", latest_block["refSteemBlockNumber"]]) t.add_row(["latest timestamp", latest_block["timestamp"]]) t.add_row(["Number of created tokens", len(tokens)]) print(t.get_string()) for obj in objects: if re.match("^[0-9-]*$", obj): block_info = api.get_block_info(int(obj)) print("Block info: %d" % (int(obj))) trx_nr = 0 for trx in block_info["transactions"]: trx_nr += 1 t = PrettyTable(["Key", "Value"]) t.align = "l" t.add_row(["trx_nr", str(trx_nr)]) t.add_row(["action", trx["action"]]) t.add_row(["contract", trx["contract"]]) t.add_row( ["logs", json.dumps(json.loads(trx["logs"]), indent=4)]) t.add_row([ "payload", json.dumps(json.loads(trx["payload"]), indent=4) ]) t.add_row(["refSteemBlockNumber", trx["refSteemBlockNumber"]]) t.add_row(["timestamp", block_info["timestamp"]]) t.add_row(["sender", trx["sender"]]) t.add_row(["transactionId", trx["transactionId"]]) print(t.get_string()) elif re.match("^[A-Z0-9\-\._]{1,16}$", obj): print("Token: %s" % obj) tokens = Tokens() token = tokens.get_token(obj) if token is None: print("Could not found token %s" % obj) return t = PrettyTable(["Key", "Value"]) t.align = "l" metadata = json.loads(token["metadata"]) for key in token: if key == "metadata": if "url" in metadata: t.add_row(["metadata_url", metadata["url"]]) if "icon" in metadata: t.add_row(["metadata_icon", metadata["icon"]]) if "desc" in metadata: t.add_row(["metadata_desc", metadata["desc"]]) else: t.add_row([key, token[key]]) market_info = token.get_market_info() if market_info is not None: for key in market_info: if key in ["$loki", "symbol"]: continue t.add_row([key, market_info[key]]) print(t.get_string()) elif re.match("^[a-zA-Z0-9\-\._]{2,16}$", obj): print("Token Wallet: %s" % obj) if stm is None: nodelist = NodeList() nodelist.update_nodes() stm = Steem(node=nodelist.get_nodes()) wallet = Wallet(obj, steem_instance=stm) t = PrettyTable( ["id", "symbol", "balance", "stake", "pendingUnstake"]) t.align = "l" for token in wallet: if "stake" in token: stake = token["stake"] else: stake = "-" if "pendingUnstake" in token: pendingUnstake = token["pendingUnstake"] else: pendingUnstake = "-" t.add_row([ token["$loki"], token["symbol"], token["balance"], stake, pendingUnstake ]) print(t.get_string(sortby="id")) elif len(obj) == 40: print("Transaction Id: %s" % obj) trx = api.get_transaction_info(obj) if trx is None: print("trx_id: %s is not a valid steem-engine trx_id!" % obj) return payload = json.loads(trx["payload"]) logs = json.loads(trx["logs"]) t = PrettyTable(["Key", "Value"]) t.align = "l" t.add_row(["blockNumber", str(trx["blockNumber"])]) t.add_row(["action", trx["action"]]) t.add_row(["contract", trx["contract"]]) t.add_row(["logs", json.dumps(logs, indent=4)]) t.add_row(["payload", json.dumps(payload, indent=4)]) t.add_row(["refSteemBlockNumber", trx["refSteemBlockNumber"]]) t.add_row(["sender", trx["sender"]]) t.add_row(["transactionId", trx["transactionId"]]) print(t.get_string())
import time import logging import json from steemengine.api import Api from beem.block import Block log = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) if __name__ == "__main__": api = Api() latest_block = api.get_latest_block_info() scan_token = ['BTC'] print("Scanning all blocks from 0 to %d..." % latest_block['blockNumber']) steemp_payments = [] for block_num in range(14500, latest_block['blockNumber']): block = api.get_block_info(block_num) if block_num % 1000 == 0: print("%.2f %%" % (block["blockNumber"] / latest_block['blockNumber'] * 100)) for trx in block["transactions"]: if trx["contract"] not in ['market']: continue if trx["action"] not in ['buy', 'sell']: continue logs = json.loads(trx["logs"]) sender = trx["sender"]