def read_config(self, cfg_file): if not os.path.isfile(cfg_file): self.log("Missing config file") self.log("Exiting.") exit(1) try: # Config File Stuff self.log("Reading config file '{0}'".format(cfg_file)) config = configparser.RawConfigParser() config.read(cfg_file) # Get Matcher and Node self.node = config.get('main', 'node') self.chain = config.get('main', 'network') self.matcher = config.get('main', 'matcher') self.order_fee = config.getint('main', 'order_fee') self.order_lifetime = config.getint('main', 'order_lifetime') self.private_key = config.get('account', 'private_key') self.private_key_BTC = config.get('account', 'private_key_BTC') self.amount_asset_id = config.get('market', 'amount_asset') # Get Asset Pair self.amount_asset = pw.Asset(self.amount_asset_id) self.price_asset_id = config.get('market', 'price_asset') self.price_asset = pw.Asset(self.price_asset_id) except OSError: self.log("Error reading config file") self.log("Exiting.") exit(1)
def __init__(self): # main self.node = config.NODE self.chain = config.NETWORK self.matcher = config.MATCHER self.order_fee = config.ORDER_FEE self.order_lifetime = config.ORDER_LIFETIME # account self.private_key = config.PRIVATE_KEY self.wallet = pw.Address(privateKey=self.private_key) # assets self.amount_asset_id = config.AMOUNT_ASSET self.price_asset_id = config.PRICE_ASSET self.asset_pair = pw.AssetPair(pw.Asset(self.amount_asset_id), pw.Asset(self.price_asset_id)) # grid self.base_price = 0 self.interval = 0.01 self.grid_levels = 20 self.base_level = 10 self.last_level = 10 self.grid = ["-"] * self.grid_levels self.tranche_size = 150000000 # 1.5 WAVES
def read_config(self, cfg_file): if not os.path.isfile(cfg_file): self.log("Missing config file") self.log("Exiting.") exit(1) try: self.log("Reading config file '{0}'".format(cfg_file)) config = configparser.RawConfigParser() config.read(cfg_file) self.node = config.get('main', 'node') self.chain = config.get('main', 'network') self.matcher = config.get('main', 'matcher') self.order_fee = config.getint('main', 'order_fee') self.order_lifetime = config.getint('main', 'order_lifetime') self.private_key = config.get('account', 'private_key') amount_asset_id = config.get('market', 'amount_asset') if amount_asset_id == "WAVES": amount_asset_id = pw.WAVES self.amount_asset = amount_asset_id self.price_asset_id = config.get('market', 'price_asset') if self.price_asset_id == "WAVES": self.price_asset_id = pw.Asset(pw.WAVES) self.price_asset = pw.Asset(self.price_asset_id) except OSError: self.log("Error reading config file") self.log("Exiting.") exit(1)
def sell_order(): pw.setNode('https://testnode1.wavesnodes.com', 'testnet') try: alice = pw.Address(privateKey=g.account_priv_key) WAVES = pw.Asset('WAVES') STO = pw.Asset('Ezmc5iyssHRF9qgCoa6h8ejPG4JFD17qEGZdPUBU1MqL') WAVES_STO = pw.AssetPair(WAVES, STO) myOrder = alice.sell(assetPair=WAVES_STO, amount=1e8, price=1) print '--> myOrder', myOrder except Exception, error: print 'ERROR: ', error return bad_request(error)
def __init__(self): self.log_file = "bot.log" self.node = "https://nodes.wavesnodes.com" self.chain = "mainnet" self.matcher = "https://nodes.wavesnodes.com" self.order_fee = int(0.003 * 10**8) self.order_lifetime = 29 * 86400 # 29 days self.private_key = "" self.amount_asset_id = pw.WAVES self.amount_asset = pw.Asset(pw.WAVES) self.price_asset_id = "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS" # BTC self.price_asset = pw.Asset(self.price_asset_id) self.price_step = 0.005 self.min_amount = 10000 self.seconds_to_sleep = 15
def __init__(self): self.log_file = "bot.log" self.node = "https://nodes.wavesnodes.com" self.chain = "mainnet" self.matcher = "https://nodes.wavesnodes.com" self.order_fee = 0.003 * 10**8 self.order_lifetime = 29 * 86400 # 29 days self.private_key = key self.amount_asset_id = "CFD3qQq9XJ3WXZ3WNDC3we3CGLwPZ5EuNhphRvDH55DF" self.price_asset_id_btc = "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS" self.price_asset_id_eth = "474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu" self.price_asset_id_waves = '' self.amount_asset = pw.Asset(self.amount_asset_id) self.price_asset_btc = pw.Asset(self.price_asset_id_btc) self.price_asset_eth = pw.Asset(self.price_asset_id_eth) self.price_asset_waves = pw.Asset(self.price_asset_id_waves)
def optionCheck(option): if option == '1': print( "Here's is your account information (WRITE THESE INFORMATION DOWN!!!): \n" ) print(generateWallet()) if option == '2': seed = input("Please enter your seed (space between words): ") recipient = input("\n Enter the recepient address: ") amount = int(input("\n Enther the amount: ")) attachment = input("\n Enter the attachment: ") pw.Address(seed=seed).sendWaves(recipient, amount, attachment=attachment, timestamp=0) if option == '3': seed = input("Please enter your seed (space between words): ") recipient = input("\n Enter the recepient address: ") asset = pw.Asset(input("\n Enter the asset ID: ")) amount = int(input("\n Enther the amount: ")) attachment = input("\n Enter the attachment: ") pw.Address(seed=seed).sendAsset(recipient, asset, amount, attachment=attachment, timestamp=0) if option == '4': seed = input("\nPlease enter your seed (space between words): ") print("\nSend waves or other tokens to the address below: \n") print(pw.Address(seed=seed).address) if option == '5': sys.exit(0)
def send_cdm(message): pw.setNode(node=config['blockchain']['host'], chain=config['blockchain']['network']) sponsor = pw.Address(seed=config['blockchain']['sponsor_seed']) asset = pw.Asset(config['blockchain']['asset_id']) feeAsset = pw.Asset(config['blockchain']['asset_id']) attachment = create_ipfs_file(message) tx = sponsor.sendAsset(recipient=sponsor, asset=asset, feeAsset=feeAsset, amount=1, attachment=attachment['Hash']) return tx
def reissueAsset(self, Asset, quantity, reissuable=False, txFee=pywaves.DEFAULT_ASSET_FEE): timestamp = int(time.time() * 1000) sData = b'\5' + \ base58.b58decode(self.publicKey) + \ base58.b58decode(Asset.assetId) + \ struct.pack(">Q", quantity) + \ (b'\1' if reissuable else b'\0') + \ struct.pack(">Q",txFee) + \ struct.pack(">Q", timestamp) signature = crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "assetId": Asset.assetId, "quantity": quantity, "timestamp": timestamp, "reissuable": reissuable, "fee": txFee, "signature": signature }) return pywaves.Asset( pywaves.wrapper('/assets/broadcast/reissue', data)['assetId'])
def _create_transaction(recipient, amount, attachment): # get fee path = f"assets/details/{cfg.asset_id}" response = requests.get(cfg.node_http_base_url + path) if response.ok: asset_fee = response.json()["minSponsoredAssetFee"] else: short_msg = "failed to get asset info" logger.error(f"{short_msg}: ({response.status_code}, {response.request.method} {response.url}):\n\t{response.text}") err = OtherError(short_msg, ERR_FAILED_TO_GET_ASSET_INFO) err.data = response.text raise err if not recipient: short_msg = "recipient is null or an empty string" logger.error(short_msg) err = OtherError(short_msg, ERR_EMPTY_ADDRESS) raise err if not utils.is_address(recipient): short_msg = "recipient is not a valid address" logger.error(short_msg) err = OtherError(short_msg, ERR_EMPTY_ADDRESS) raise err recipient = pywaves.Address(recipient) asset = pywaves.Asset(cfg.asset_id) address_data = pw_address.sendAsset(recipient, asset, amount, attachment, feeAsset=asset, txFee=asset_fee) signed_tx = json.loads(address_data["api-data"]) # calc txid properly txid = transfer_asset_txid(signed_tx) # store tx in db dbtx = CreatedTransaction(txid, CTX_CREATED, signed_tx["amount"], address_data["api-data"]) return dbtx
def _create_transaction_waves(recipient, amount, attachment): # get fee path = f"/assets/details/{ASSET_ID}" response = requests.get(NODE_BASE_URL + path) if response.ok: asset_fee = response.json()["minSponsoredAssetFee"] else: short_msg = "failed to get asset info" logger.error("%s: (%d, %s, %s):\n\t%s", short_msg, response.status_code, response.request.method, response.url, response.text) err = OtherError(short_msg, tx_utils.ERR_FAILED_TO_GET_ASSET_INFO) err.data = response.text raise err if not recipient: short_msg = "recipient is null or an empty string" logger.error(short_msg) err = OtherError(short_msg, tx_utils.ERR_EMPTY_ADDRESS) raise err if not utils.is_address(recipient): short_msg = "recipient is not a valid address" logger.error(short_msg) err = OtherError(short_msg, tx_utils.ERR_EMPTY_ADDRESS) raise err recipient = pywaves.Address(recipient) asset = pywaves.Asset(ASSET_ID) address_data = PW_ADDRESS.sendAsset(recipient, asset, amount, attachment, feeAsset=asset, txFee=asset_fee) signed_tx = json.loads(address_data["api-data"]) signed_tx["type"] = 4 # sendAsset does not include "type" - https://github.com/PyWaves/PyWaves/issues/131 # calc txid properly txid = tx_utils.tx_to_txid(signed_tx) # store tx in db dbtx = WavesTx(txid, "transfer", tx_utils.CTX_CREATED, signed_tx["amount"], True, json.dumps(signed_tx)) return dbtx
def issueAsset(self, name, description, quantity, decimals=0, reissuable=False, txFee=pywaves.DEFAULT_ASSET_FEE): if not self.privateKey: logging.error('Private key required') elif len(name) < 4 or len(name) > 16: logging.error('Asset name must be between 4 and 16 characters long') else: timestamp = int(time.time() * 1000) sData = b'\3' + \ base58.b58decode(self.publicKey) + \ struct.pack(">H", len(name)) + \ crypto.str2bytes(name) + \ struct.pack(">H", len(description)) + \ crypto.str2bytes(description) + \ struct.pack(">Q", quantity) + \ struct.pack(">B", decimals) + \ (b'\1' if reissuable else b'\0') + \ struct.pack(">Q", txFee) + \ struct.pack(">Q", timestamp) signature=crypto.sign(self.privateKey, sData) data = json.dumps({ "senderPublicKey": self.publicKey, "name": name, "quantity": quantity, "timestamp": timestamp, "description": description, "decimals": decimals, "reissuable": reissuable, "fee": txFee, "signature": signature }) req = pywaves.wrapper('/assets/broadcast/issue', data) if pywaves.OFFLINE: return req else: return pywaves.Asset(req['assetId'])
def __init__(self): self.log_file = "bot.log" self.node = "https://privatenode2.blackturtle.eu" self.chain = "turtlenetwork" self.matcher = "https://privatematcher.blackturtle.eu" self.datafeed = "https://bot.blackturtle.eu" self.order_fee = int(0.04 * 10 ** 8) self.order_lifetime = 1 * 86400 # 1 days self.private_key = "" self.amount_asset_id = "" self.amount_asset = pw.WAVES self.price_asset_id = "4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8" # BTC self.price_asset = pw.Asset(self.price_asset_id) self.price_step = 0.05 self.min_amount = 10000 self.seconds_to_sleep = 5 self.strategy = "grid" self.grid = ["-"] self.grid_levels = 20 self.grid_tranche = 10000000000 self.grid_base = "LAST" self.grid_flexibility = 20 self.grid_type = "SYMMETRIC" self.grid_basePrice = 0 self.can_buy = "" self.can_sell = "" self.uptr_profitmargin = 0.05 self.uptr_stoploss = 0.01 self.uptr_stoploss_current = 0 self.buy_orderid = "" self.sell_orderid = "" self.filled_type = "" self.filled_price = ""
def sweep_run(args): pw.setOnline() # check recipient is a valid address if not pw.validateAddress(args.recipient): print(f"ERROR: {args.recipient} is not a valid address") sys.exit(EXIT_INVALID_RECIPIENT) recipient = pw.Address(args.recipient) # sweep expired foils asset = pw.Asset(args.assetid) asset_fee = get_asset_fee(args.assetid) date = time.time() foils = Foil.get_batches_between(db_session, args.batch_start, args.batch_end) for foil in foils: if args.ignore_expiry or foil.expiry and date >= foil.expiry: addr = pw.Address(seed=foil.seed) balance = addr.balance(assetId=args.assetid) if balance == 0: print(f"Skipping {foil.batch} {addr.address}, balance is 0") continue result = addr.sendAsset(recipient, asset, balance - asset_fee, \ feeAsset=asset, txFee=asset_fee) print(result) print(f"Swept {foil.batch} {addr.address}, txid {result['id']}") else: print(f"Skipping {foil.batch} {addr.address}, not yet expired")
def burn_asset(asset): py_asset = py.Asset(assetId=asset) data = json.loads(request.data.decode()) amount = float(data['amount']) * (10**py_asset.decimals) fee = float(data['fee']) * (10**8) burn = current_user.wallet.burnAsset(py_asset, int(amount), txFee=int(fee)) return jsonify(burn)
def VerifyWallet(self, WavesAddress): con = lite.connect('test.db') with con: cur = con.cursor() # cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)") cur.execute( """SELECT WavesAddress , serializedWallet , BTCaddress FROM addresses WHERE WavesAddress=:adr""", {"adr": WavesAddress}) con.commit() row = cur.fetchone() if row: _wallet = get_wallet_addresses(wallet_name=WavesAddress, api_key=self.APIKEY) details = get_address_details(_wallet['addresses'][0]) # print(details) txrefs = details['txrefs'] # print(len(txrefs)) if len(txrefs) == 0: return {"result": "not exist any transaction"} else: tx_hash = txrefs[0][ 'tx_hash'] #TODO should be check transaction time transaction_details = get_transaction_details(tx_hash) receive_count = transaction_details['receive_count'] # print(tx_hash) recipient = pywaves.Address(address=WavesAddress) BTC = pywaves.Asset( '8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS') res = self.WAVES.sendAsset(recipient, BTC, receive_count) return res return None
def test_create_nft_buy_sell_and_burn(self): with self.assertRaises(Exception): nft_create = address.issueAsset("nft " + self.gen_random_str(12), "nft " + self.gen_random_str(12), 1, 0, reissuable=False, txFee=9999999) nft_create = address.issueAsset("nft " + self.gen_random_str(12), "nft " + self.gen_random_str(12), 1, 0, reissuable=False, txFee=10000000) self.assertNotIn("error", str(nft_create)) asset_id = nft_create.assetId time.sleep(60) PAIR = py.AssetPair(py.Asset(asset_id), py.Asset("TN")) address.cancelOpenOrders(PAIR) output = address.sell(PAIR, 1, 100, maxLifetime=60000, matcherFee=4000000) address.cancelOpenOrders(PAIR) self.assertNotIn("error", str(output)) output = address.buy(PAIR, 1, 100, maxLifetime=60000, matcherFee=4000000) address.cancelOpenOrders(PAIR) self.assertNotIn("error", str(output)) nft_burn = address.burnAsset(py.Asset(asset_id), 1, txFee=1999999) self.assertIn("ERROR", str(nft_burn)) nft_burn = address.burnAsset(py.Asset(asset_id), 1, txFee=2000000) self.assertNotIn("ERROR", str(nft_burn))
def VerifyWallet(self,WavesAddress): # con = lite.connect('test.db') # with con: # cur = con.cursor() # # cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)") # cur.execute("""SELECT WavesAddress , serializedWallet , BTCaddress # FROM addresses WHERE WavesAddress=:adr""", {"adr": WavesAddress}) # con.commit() con = lite.connect('test.db') with con: cur = con.cursor() cur.execute("""SELECT id FROM addressid WHERE WavesAddress=:adr""", {"adr": WavesAddress}) con.commit() row = cur.fetchone() if row : print('row[0] : ',row[0]) _wallet = get_wallet_addresses(wallet_name='Noay'+ str(row[0]), api_key=self.APIKEY , coin_symbol=self.coin_symbol) print('_wallet',_wallet) txrefs = [] details = get_address_details(_wallet['addresses'][0], coin_symbol=self.coin_symbol) print(details) txrefs = details['txrefs'] print(len(txrefs)) if len(txrefs) == 0 : return {"result" : "not exist any transaction"} else : tx_hash = txrefs[0]['tx_hash'] #TODO should be check transaction time transaction_details = get_transaction_details(tx_hash , coin_symbol=self.coin_symbol) print('transaction_details' , transaction_details) receive_count = transaction_details['outputs'][-1]['value'] * (10** ((-1) * 8)) # print(tx_hash) pywaves.setNode(node = self.TESTNET_NODE , chain = self.CHAIN) print("getNode(): ",pywaves.getNode()) recipient = pywaves.Address(address=WavesAddress) BTC = pywaves.Asset('DWgwcZTMhSvnyYCoWLRUXXSH1RSkzThXLJhww9gwkqdn') #todo i dnk? WAVES = pywaves.Address(address=self.WAVES_address , privateKey=self.WAVES_privateKey) res = WAVES.sendAsset(recipient,BTC,receive_count) #todo what response #todo dont read serialized? :// con = lite.connect('test.db') with con: cur = con.cursor() # cur.execute("CREATE TABLE IF NOT EXISTS btcRemind(BTCaddress TEXT , Inventory REAL ") # cur.execute("""INSERT INTO btcRemind VALUES(?,?)""", (BTCWallet['addresses'][0], receive_count)) cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """, ( receive_count , WavesAddress )) con.commit() return res return None
def read_config(self, cfg_file): if not os.path.isfile(cfg_file): self.log("Missing config file") self.log("Exiting.") exit(1) try: self.log("Reading config file '{0}'".format(cfg_file)) config = configparser.RawConfigParser() config.read(cfg_file) self.node = config.get('network', 'node') self.chain = config.get('network', 'network') self.matcher = config.get('network', 'matcher') self.datafeed = config.get('network', 'datafeed') self.order_fee = config.getint('network', 'order_fee') self.order_lifetime = config.getint('main', 'order_lifetime') self.strategy = config.get('main', 'strategy').lower() self.seconds_to_sleep = config.getint('main', 'sleeptimer') self.private_key = config.get('account', 'private_key') self.amount_asset_id = config.get('market', 'amount_asset') self.amount_asset = pw.Asset(self.amount_asset_id) self.price_asset_id = config.get('market', 'price_asset') self.price_asset = pw.Asset(self.price_asset_id) self.price_step = config.getfloat('grid', 'interval') self.grid_tranche = config.getint('grid', 'tranche_size') self.grid_flexibility = config.getint('grid', 'flexibility') self.grid_levels = config.getint('grid', 'grid_levels') self.grid_base = config.get('grid', 'base').upper() self.grid_type = config.get('grid', 'type').upper() self.uptr_profitmargin = config.getfloat('uptrend', 'profitmargin') self.uptr_stoploss = config.getfloat('uptrend', 'stoploss') self.log_file = config.get('logging', 'logfile') except OSError: self.log("Error reading config file") self.log("Exiting.") exit(1)
def send_doge_back(handler): key = urllib.unquote(handler.path[13:]) Account1 = pw.Address(privateKey=key) amounttosend = Account1.balance( 'DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT') myToken = pw.Asset('DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT') Account1.sendAsset( recipient=pw.Address('WavesWalletAddressUsedForExchange'), asset=myToken, amount=amounttosend) return amounttosend
def details_asset(assetid): asset_details = py.Asset(assetId=assetid) if asset_details.decimals == 0: asset_balance = current_user.wallet.balance(assetId=assetid) else: asset_balance = current_user.wallet.balance( assetId=assetid) / (10**asset_details.decimals) asset_smart = asset_details.isSmart() return render_template('details.html', asset_details=asset_details, asset_balance=asset_balance, asset_smart=asset_smart, extra_fees=current_user.extra_fees)
def token_price(self, bot, update): old_price = self.price price = self.__get_price() usd_price = format((self.btc_price * price / 100000000), '.3f') hashrate = 0 for deal in self.__get_dwh_deals(): hashrate += deal["deal"]["benchmarks"]["values"][9] hashrate /= 1000000 # convert to MH/s hashrate /= 1000 # further convert to GH/s hashrate = format(hashrate, '.2f') DICS = "Fweiconow1LnWTwCKdQzqUsbbc6xEnp1tMvFMqpm4e6F" myToken = pw.Asset(DICS) PAIR = pw.AssetPair(myToken, pw.BTC) NODE = "http://nodes.wavesnodes.com" # select the network: testnet or mainnet NETWORK = "mainnet" MATCHER = "http://matcher.wavesnodes.com" pw.setNode(NODE, NETWORK) pw.setMatcher(MATCHER) out = PAIR.orderbook() divider = 100000000 #return int(out['bids'][0]['price'] / divider) DICS_price = int(out['bids'][0]['price'] / divider) #DICS_price = DICS_price() usd_DICS_price = format((self.btc_price * DICS_price / 100000000), '.3f') msg = """\ SNM Price: {price} sats (${usd} US)\n\ Volume: {vol} BTC\n\ \n\ (Source: Binance)\n\ \n\ Deals: {deals}\n\ DICS Price: {DICS_price} sats (${DICS_usd} US)\n\ ETH-hashrate: {hashrate} GH/s""".format(price=price, usd=usd_price, vol=self.volume, deals=len(self.__get_dwh_deals()), DICS_price=DICS_price, DICS_usd=usd_DICS_price, hashrate=hashrate) bot.send_message(chat_id=update.message.chat_id, text=msg)
def __init__(self): self.log_file = "bot.log" self.node = "https://nodes.wavesnodes.com" self.chain = "mainnet" self.matcher = "https://matcher.wavesnodes.com" self.order_fee = 300000 self.order_lifetime = 30 * 86400 # 30 days self.private_key = "" self.private_key_BTC = "" self.amount_asset = "" self.price_asset_id = "" self.price_asset = pw.Asset(self.price_asset_id) self.price_step = 0.005 self.min_amount = 10000 self.seconds_to_sleep = 15
def post(request): cdm = '''<?xml version="1.0"?> \r\n<cdm> \r\n<version>{cdmv}</version> \r\n<blockchain>Waves</blockchain> \r\n<network>Testnet</network> \r\n<opcodes> \r\n<opcode> \r\n<trafficlight>123456789</trafficlight> \r\n<value>GODMODE</value> \r\n</opcode> \r\n</opcodes> \r\n</cdm> '''.format(cdmv=os.environ['CDM_VERSION']) # pw.setChain('testnet') # pw.setNode(node=os.environ['NODE_URL'], chain='testnet') pw.setNode('https://testnode1.wavesnodes.com', 'testnet') sponsor = pw.Address(seed=os.environ['SPONSOR_SEED']) attachment = create_ipfs_file(cdm) asset = pw.Asset(os.environ['ASSET_ID']) feeAsset = pw.Asset(os.environ['ASSET_ID']) print('NODE_URL', os.environ['NODE_URL']) print('sponsor', sponsor) print('asset', asset) print('attachment', attachment['Hash']) tx = sponsor.sendAsset(recipient=sponsor, asset=asset, feeAsset=feeAsset, amount=1, attachment=attachment['Hash']) print('TX: {}'.format(tx)) return json({'tx': tx})
def send_doge_user(handler): key = urllib.unquote(handler.path[13:]) Account1 = pw.Address( seed= 'Seed of your token wallet that will be funded with tokens for the bridge' ) dogeToken = pw.Asset('DvpmDF45bmo9xDb6rSte8uPPWWeh6EGzoATwxMStWQKT') jsondata = accounts[key] recipientaddress = jsondata['address'] intamounttosend = round(float(jsondata['amount']), 0) amounttosendtouser = int(intamounttosend) Account1.sendAsset(recipient=pw.Address(recipientaddress), asset=dogeToken, amount=amounttosendtouser) return amounttosendtouser
def complete_order(amount=0.001): """ completes buy/sell orders for the WAVES/BTC pair """ asset1 = pw.Asset("WAVES") asset2 = pw.Asset("8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS") pair = pw.AssetPair(asset1, asset2) if amount > 0: amount = int(amount * WVS) price = get_instant_price(pair.orderbook(), amount) tokenA_to_buy = int(account.balance(wf.tokenB) / price) order = account.buy(assetPair=pair, amount=tokenA_to_buy, price=price) print("Will buy {} WAVES for a price {} BTC".format( tokenA_to_buy / WVS, price / WVS)) else: order = create_sell_order(amount, pair) print("Order created. Here is the order ID: {}".format(order.orderId)) for x in range(150): sleep(0.1) if order.status() == "Filled": print("Order is filled!") return order print("Well, we need wait some more time till order is filled.")
def _check(batch, amount, assetid): print(f":: batch {batch} - amount {amount}") asset = pw.Asset(assetid) foils = Foil.get_batch(db_session, batch) for foil in foils: addr = pw.Address(seed=foil.seed) balance = addr.balance(assetId=assetid) if balance > 0: print(f"balance: {balance} addr: {addr.address}") if balance != amount and balance != amount - 1: print(f"ERROR - address ({addr.address}) has wrong balance") sys.exit(2) else: print(f"ERROR - address ({addr.address}) has no balance") sys.exit(1)
def gw_send_currencie(gateway): gw: Gateway = next( (x for x in gateways if x.name.lower() == gateway.lower()), None) data = request.data gateway = py.Address(address=gw.general_addr) json_data = json.loads(data.decode()) dest = json_data['addr'] amount = float(json_data['amount']) * (10**8) fee = float(json_data['fee']) * (10**8) result = current_user.wallet.sendAsset(gateway, py.Asset(gw.asset_id), int(amount), txFee=int(fee), attachment=dest) return jsonify(result)
def __init__(self): # there will be a log for each day timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d") s = format(timestamp) self.log_file = "bot_" + s + ".log" self.node = "https://nodes.wavesnodes.com" self.chain = "mainnet" self.matcher = "https://matcher.waves.exchange" self.order_fee = int(0.003 * 10**8) self.order_lifetime = 29 * 86400 # 29 days self.private_key = "" self.amount_asset = pw.WAVES self.price_asset_id = "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS" # BTC self.price_asset = pw.Asset(self.price_asset_id) self.price_step = 0.005 self.min_amount = 10000 #satoshi self.seconds_to_sleep = 40 self.price_asset_name = "BTC"
def _fund(seed, batch, amount, provided_expiry, required_funds, assetid): _check_mnemonic(seed) sender = _create_pwaddr(seed, required_funds) # set expiry date = time.time() two_months = 60 * 60 * 24 * 30 * 2 expiry = date + two_months if provided_expiry: pattern = r"(\d+)days" m = re.search(pattern, provided_expiry) if m: days = int(m.group(1)) expiry = date + days * 60 * 60 * 24 else: try: expiry = date + int(provided_expiry) except: print("ERROR: expiry not a valid number") sys.exit(EXIT_EXPIRY_INVALID) dt = datetime.datetime.fromtimestamp(expiry) nice_expiry = dt.strftime("%Y/%m/%d %H:%M:%S") print(f"Batch (#{batch}) expiry: {nice_expiry} ({expiry})") # add funds and expiry asset = pw.Asset(assetid) foils = Foil.get_batch(db_session, batch) for foil in foils: addr = pw.Address(seed=foil.seed) if foil.funding_txid: print(f"Skipping {addr.address}, funding_txid is not empty") continue balance = addr.balance(assetId=assetid) if balance > 0: print(f"Skipping {addr.address}, balance ({balance}) is not 0") continue result = sender.sendAsset(addr, asset, amount, feeAsset=asset, txFee=1) foil.expiry = expiry foil.funding_date = time.time() foil.funding_txid = result["id"] db_session.add(foil) db_session.commit() print(f"Funded {addr.address} with {amount}")