예제 #1
0
파일: main.py 프로젝트: waves-loans/worker
import repo
import waves_api
from os import getenv
import pywaves as pw
import time

pw.setNode(getenv('NODE_URL'), getenv('NODE_CHAIN'), getenv('NODE_CHAIN_ID'))


def takeOne(item):
    if len(item) == 0:
        return None

    return item[0]['value']


def nodeReader():
    appSetting = repo.getAppSetting()
    wavesLastBlock = waves_api.getLatestBlockHeight() - 1

    if appSetting['lastBlock'] < wavesLastBlock:
        for height in range(appSetting['lastBlock'] + 1, wavesLastBlock + 1):
            currentBlock = waves_api.getBlockByHieght(height)
            if len(currentBlock['transactions']):
                for transaction in currentBlock['transactions']:
                    if transaction['type'] == 16 and transaction[
                            'dApp'] == getenv("DAPP_ADDRESS") and transaction[
                                'call']['function'] == 'borrow':
                        repo.addDebt(transaction['id'])

    repo.updateAppSetting({'lastBlock': wavesLastBlock})
예제 #2
0
    LOGFILE = config.get('logging', 'logfile')

    BLACKBOT = pw.Address(privateKey=PRIVATE_KEY)

    log("-" * 80)
    log("          Address : %s" % BLACKBOT.address)
    log("  Amount Asset ID : %s" % amountAssetID)
    log("   Price Asset ID : %s" % priceAssetID)
    log("-" * 80)
    log("")
except:
    log("Error reading config file")
    log("Exiting.")
    exit(1)

pw.setNode(NODE, "mainnet")
pw.setMatcher(MATCHER)
PAIR = pw.AssetPair(pw.Asset(amountAssetID), pw.Asset(priceAssetID))

# grid list with GRID_LEVELS items. item n is the ID of the order placed at the price calculated with this formula
# price = int(basePrice * (1 + INTERVAL) ** (n - GRID_LEVELS / 2))

grid = ["-"] * GRID_LEVELS

log("Cancelling open orders...")

# cancel all open orders on the specified pair
BLACKBOT.cancelOpenOrders(PAIR)
log("Deleting order history...")

# delete order history on the specified pair
예제 #3
0
import pywaves as pw


# myAddress = pw.Address(privateKey='CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S')
# otherAddress = pw.Address('3PNTcNiUzppQXDL9RZrK3BcftbujiFqrAfM')
# myAddress.sendWaves(otherAddress, 10000000)
# myToken = myAddress.issueAsset('Token1', 'My Token', 1000, 0)
# while not myToken.status():
# 	pass
# myAddress.sendAsset(otherAddress, myToken, 50)

# Point on node we're gonna work with
pw.setNode('https://testnode1.wavesnodes.com','testnet')
myAddress = pw.Address(privateKey='7XSgNdnwNF6mcQxPLggFsgxWvJCVG2pige2i8qhWxpfv')
print(pw.Address.balance(myAddress))
otherAddress = pw.Address('3MqSUG4WePmQBEVqreAMc3FrYJuR1Jm3vRZ')
print(pw.Address.balance(otherAddress))
myAddress.sendWaves(otherAddress,1)
print(pw.Address.balance(myAddress))
print(pw.Address.balance(otherAddress))
BiairdropTocken = pw.Asset('32kTPfXsUSWwjquT4NcXa52sLt9wWNngzY9SVvQbowH1')
# myToken = myAddress.issueAsset('Biairdrop2', 'Tocken created via api', 1337, 10)
# while not myToken.status():
# 	pass
# myAddress.sendAsset(otherAddress, myToken, 50)

myAddress.sendAsset(recipient=otherAddress, asset=BiairdropTocken, amount = 100000000)
예제 #4
0
def create_account():
    pw.setNode(NODE, CHAIN)
    seed = " ".join([random.choice(pw.wordList) for n in range(15)])
    account = pw.Address(seed=seed)
    return {"seed": account.seed, "address": account.address}
예제 #5
0
import pywaves as pw

# Andre
# Address: 	   3MwXvspLKJMdrkjveS3T4WKvjN3tWdgAq8U
# Public Key:  74gVmjC1eSMB4DWiczqW4XyU1wLpPKqY5KnbBg1DQiZf
# Private Key: 6wtSrJhE6NRZju6Wpzj1hwcyn72vHwTknM2RpVCyGp7W

# Joel
# Address: 	   3N1fDFhqCpSqUascfa1nAjQvpcagndBPhRG
# Public Key:  ???
# Private Key: ???

node1 = 'http://testnode1.wavesnodes.com'
chain1 = 'testnet'
pw.setNode(node=node1, chain=chain1)

andreAddress = pw.Address(
    privateKey='6wtSrJhE6NRZju6Wpzj1hwcyn72vHwTknM2RpVCyGp7W')  # Andre
joelAddress = pw.Address('3N1fDFhqCpSqUascfa1nAjQvpcagndBPhRG')  # Joel

#if __name__ == "__main__":
#	print("Test")

#socketKey = 'CtMQWJZqfc7PRzSWiMKaGmWFm4q2VN5fMcYyKDBPDx6S'
socketKey = '3N1fDFhqCpSqUascfa1nAjQvpcagndBPhRG'
socketAddress = pw.Address(socketKey)


def getBalance(address):
    if (len(address) == 35):  # Address
        address = pw.Address(address)
예제 #6
0
import pywaves as py

lock_height = 650000
script = 'height >= ' + str(lock_height)

py.setNode('https://privatenode.blackturtle.eu', 'TN', 'L')
py.setMatcher('https://privatematcher.blackturtle.eu')

address = py.Address(seed='')

output = address.setScript(script, txFee=100000000)
print(output)

# output from test needs to be : ""u'message': u'Transaction is not allowed by account-script'
test = address.sendWaves(address, 8000, txFee=2000000)
print(test)
예제 #7
0
def gateway_pywaves_address(gateway_waves_address_secret: model.KeyPair,
                            waves_node: str, waves_chain: str):
    """Creates an address instance from the pywaves library that represents the Gateway waves address."""
    pywaves.setNode(waves_node, waves_chain)
    return pywaves.Address(gateway_waves_address_secret.public,
                           privateKey=gateway_waves_address_secret.secret)
예제 #8
0
config = {
	'privateKey': '',
	'file': '',
	# timeout between requests in ms
	'timeout': 100,
	'nodes': [
		''
	]
}

startTime = time.time()
totalPayments = 0
paid = 0
counter = 0

pw.setNode(config['nodes'][0], 'mainnet')
pw.setChain('Vostok', 'V')
print(config['nodes'][0])
address = pw.Address(privateKey = config['privateKey'])

def pay(batch):
    global paid
    global address
    global counter

    node = config['nodes'][counter % len(config['nodes'])]
    counter += 1
    pw.setNode(node, 'mainnet')
    pw.setChain('Vostok', 'V')

    print('number of payouts in batch: ' + str(len(batch)))
예제 #9
0
    def synchronaze_button(self):
        date_of_synchronization = dt.now()
        if self.import_export == 'export':
            res = self.env['journal.of.export'].create({'date_of_export':date_of_synchronization})
            #-------------get general info timestemp for synchronization with waves and than search of this record in bigchaindb
            general_info_text = str(date_of_synchronization)+'_'+str(res.id)
            #------------------------------------------ create main data element with general info
            root = etree.Element("data")
            general_info = etree.SubElement(root,'general_info')
            general_info.text=general_info_text
            #----------------------- create element of model from setting wizard
            control_model_dict = {}
            if self.all_models:
                _logger.info('test all models') #to-do for all model in DB
            else:
                #-------------------- get all models from setting wizard in item
                #==============================================================================================================
                for item in self.models:
                    model = etree.SubElement(root, 'model') #----------------------------------------------create element model
                    model.set('name',str(item.model_id.model)) #-------------------------------------------add name to model
                    model.set('main','True')
                    # search records from model and put this records by field in XML
                    #________________-_________________________________________________________________________________________
                    record_of_models = self.env[str(item.model_id.model)].search([])
                    if record_of_models:
                        records_list = [] #list of records for model in model control dictionary
                        for record in record_of_models:
                            record_xml = etree.SubElement(model,'record')
                            record_xml.set('id',str(record.id)) #get id of record of model
                            #==================================================================================================
                            #-------------------- add current id to records list and write values in control model dictionary
                            records_list.append(record.id)
                            if item.model_id.model in control_model_dict.keys():
                                records_value = control_model_dict[item.model_id.model]
                                list_for_record = records_value+records_list
                                control_model_dict.update({item.model_id.model:list_for_record})
                            else:
                                control_model_dict.update({item.model_id.model:records_list})
                            #==================================================================================================   
                            model_fields = self.env['ir.model'].search([('model','=',item.model_id.model)]) #get object of model
                            for model_field in model_fields.field_id:
                                # create field element without special information
                                res_field = str(getattr(record,str(model_field.name)))
                                if res_field not in ['id','create_date','create_uid','__last_update','message_ids'] and res_field != "" and res_field[res_field.find("(")+1:res_field.find(")")] != "":
                                    field = etree.SubElement(record_xml,'field') #add field element to record
                                    field.set('name',str(model_field.name))
                                    field.set('type',str(model_field.ttype))
                                    current_field_result = getattr(record,str(model_field.name)) #get value of record
                                    if str(model_field.ttype) in ['one2many','many2many','many2one']:
                                        list_of_id = str(res_field[res_field.find("(")+1:res_field.find(")")]).split(",")
                                        list_of_one = list(res_field[res_field.find("(")+1:res_field.find(")")])
                                        if list_of_one[-1] == ',':
                                            list_of_id = list_of_id[0:-1]
                                        list_of_id = map(int,list_of_id)
                                        model_name = str(res_field.split('(')[0])
                                        field.text="{'"+model_name+"':"+str(list_of_id)+"}"
                                        # create model with record accoding to list_of_id
                                        #check if model exist in control dict
                                        if model_name in control_model_dict.keys():
                                            for list_item in control_model_dict[model_name]:
                                                if list_item in list_of_id:
                                                    list_of_id.remove(list_item)
                                        else:
                                            model_rel = etree.SubElement(root, 'model')
                                            model_rel.set('name',model_name)
                                            model_rel.set('main','False')
                                        #----- get all needed records from model
                                        records_of_current_model = self.env[model_name].search([('id','in',list_of_id)])
                                        fields_of_model = self.env['ir.model'].search([('model','=',model_name)])
                                        # create element model for relation models
                                        excepted_fields = ['password_crypt','id','create_date','create_uid','__last_update','message_ids','login_date','message_channel_ids',
                                                            'message_follower_ids','message_is_follower', 'message_last_post','message_needaction','message_needaction_counter',
                                                            'message_partner_ids','message_unread', 'message_unread_counter','logo','logo_web','image','image_medium','image_small']
                                        if records_of_current_model:
                                            for record_c in records_of_current_model:
                                                if model_name in control_model_dict.keys():
                                                    for model_by_attr in root.iter('model'):
                                                        if model_by_attr.attrib['name'] == model_name:
                                                            next_record = etree.SubElement(model_by_attr,'record')
                                                            next_record.set('id',str(record_c.id)) 
                                                else:
                                                    next_record = etree.SubElement(model_rel,'record')
                                                    next_record.set('id',str(record_c.id))
                                                for field_c in fields_of_model.field_id:
                                                    current_field_n_result = getattr(record_c,str(field_c.name))
                                                    res_field = str(current_field_n_result)
                                                    if  field_c.name not in excepted_fields:
                                                        field_n = etree.SubElement(next_record,'field') #add field element to record
                                                        field_n.set('name',str(field_c.name))
                                                        field_n.set('type',str(field_c.ttype))
                                                        if str(field_c.ttype) in ['one2many','many2many','many2one']:
                                                            if res_field is not False:
                                                                list_of_id = str(res_field[res_field.find("(")+1:res_field.find(")")]).split(",")
                                                                list_of_one = list(res_field[res_field.find("(")+1:res_field.find(")")])
                                                                if len(list_of_one) > 0:
                                                                    if list_of_one[-1] == ',' and len(list_of_one)>0:
                                                                        list_of_id = list_of_id[0:-1]
                                                                if len(list_of_one) > 0:
                                                                    list_of_id = map(int,list_of_id)
                                                                model_name_str = str(res_field.split('(')[0])
                                                                if len(list_of_one)==0:
                                                                    field_n.text="False"
                                                                else:
                                                                    field_n.text="{'"+model_name_str+"':"+str(list_of_id)+"}"
                                                            else:
                                                                field_n.text="False"
                                                        else:
                                                            field_n.text=str(current_field_n_result)
                                                    if model_name in control_model_dict.keys():
                                                        records_value = control_model_dict[model_name]
                                                        list_for_record = records_value+list_of_id
                                                        control_model_dict.update({model_name:list_for_record})
                                                    else:
                                                        control_model_dict.update({model_name:list_of_id})
                                        if model_name in control_model_dict.keys():
                                            records_value = control_model_dict[model_name]
                                            list_for_record = records_value+list_of_id
                                            control_model_dict.update({model_name:list_for_record})
                                        else:
                                            control_model_dict.update({model_name:list_of_id})
                                    else:
                                        field.text=str(current_field_result)
                               
            self.xml_for_synchronization = etree.tostring(root, pretty_print=True)
            #self.xml_for_synchronization = etree.tostring(root, pretty_print=False)
            xml_result = etree.tostring(root, pretty_print=False)
            #xml_result = xml_result.replace('"','\\"')
            #-------------------------------------------- write xml to temp file
            file_to_save_with_path = '/tmp/'+general_info_text
            temp_file = open(file_to_save_with_path,'w')
            temp_file.write(xml_result)
            temp_file.close()
            string = '/usr/bin/putbigchaindb.py --xml="'+file_to_save_with_path+'"'
            #------------------------------------- synchronaze with waves blockchain
            pw.setNode(node = self.export_node_address, chain = 'testnet')
            myAddress = pw.Address(privateKey=self.export_privat_key)
            myAddress.sendWaves(myAddress, 110000, attachment=general_info_text,txFee=100000)
            os.system(string)
            
            #call(string, shell=True)
            #self.xml_for_synchronization = dumps(xmltodict.parse(etree.tostring(root, pretty_print=True)))
        else:
            _logger.info('start import')
            url_of_access = self.import_node+'/transactions/address/'+self.import_address+'/limit/100'
            result_waves = requests.get(url_of_access)
  
            attachment = result_waves.json()[0][0]['attachment']
            attachment = base58.b58decode(attachment)
            print attachment
            conn = r.connect('172.18.0.1', 28015).repl()
            get_result = r.db('bigchain').table('assets').filter({'data':{"general_info":  attachment}}).run(conn)
            dict_for_record  = {}
            excepted_fields = ['password_crypt','id','create_date','create_uid','__last_update','message_ids','login_date','mail_followers','write_date','message_last_post','validity_date','message_is_follower']
            for item_import in get_result:
#                 print item_import
                self.import_synchronization = item_import
                test = item_import
                def get_name(json,model_name,record_id):
                    for item in json['data']['model']:
                        if item['@name'] == model_name:
                            if isinstance(item['record'],list):
                                for record in item['record']:
                                    if int(record['@id']) == record_id:
                                        for field in record['field']:
                                            if field['@name'] == 'name':
                                                result = field['#text']
                                                return result
                            else:
                                if int(item['record']['@id']) == record_id:
                                    for field_cur in item['record']['field']:
                                        if field_cur['@name'] == 'name':
                                            result = field_cur['#text']
                                            return result
#                   
                def get_dict_record(json,model_name,record_id):
                    dict_for_record_field = {}
                    result_dict = {}
                    for item in json['data']['model']:
                        if item['@name'] == model_name:
                            if isinstance(item['record'],list):
                                for record in item['record']:
                                    if int(record['@id']) == record_id:
                                        for field in record['field']:
                                            if '#text' in field.keys():
                                                if field['@type'] == 'many2one' and field['#text'] != 'False':
                                                    key = ast.literal_eval(field['#text']).keys()[0]
                                                    list_id =  ast.literal_eval(field['#text'])[key]
                                                    dict_for_record_field.update({field['@name']:list_id[0]})
                                                elif field['@type'] in ['one2many']:
                                                    if str(field['#text']) != 'False':
                                                        key = ast.literal_eval(field['#text']).keys()[0]
                                                        list_id =  ast.literal_eval(field['#text'])[key]
                                                        record_list = []
                                                        for list_record in list_id:
                                                            record_list.append((4,list_record,False))
                                                        if field['@name'] == 'procurement_ids':
                                                            pass
                                                        else:
                                                            dict_for_record_field.update({field['@name']:record_list})
                                                else:
                                                    pass
                                                    #dict_for_record_field.update({field['@name']:field['#text']})
                            else:
                                if int(item['record']['@id']) == record_id:
                                    for field_cur in item['record']['field']:
                                        if '#text' in field_cur.keys():
                                            if field_cur['@type'] == 'many2one' and field_cur['#text'] != 'False':
                                                    key = ast.literal_eval(field_cur['#text']).keys()[0]
                                                    list_id =  ast.literal_eval(field_cur['#text'])[key]
                                                    dict_for_record_field.update({field_cur['@name']:list_id[0]})
                                            elif field_cur['@type'] in ['one2many']:
                                                print field_cur['#text']
                                                if str(field_cur['#text']) != 'False':
                                                    key = ast.literal_eval(field_cur['#text']).keys()[0]
                                                    list_id =  ast.literal_eval(field_cur['#text'])[key]
                                                    record_list = []
                                                    for list_record in list_id:
                                                        record_list.append((4,list_record,False))
                                                    if field_cur['@name'] == 'procurement_ids':
                                                        pass
                                                    else:
                                                        dict_for_record_field.update({field_cur['@name']:record_list})
                                            else:
                                                pass
                                                #dict_for_record_field.update({field_cur['@name']:field_cur['#text']})
                    return dict_for_record_field
                
                for item in test['data']['model']:
                    if item['@main'] == 'True':
                        if isinstance(item['record'],list):
                            for record in item['record']:
                                for field in record['field']:
                                    if field['@type'] not in ['one2many','many2many','many2one'] and item['@name'] == 'sale.order' and field['@name'] not in excepted_fields:
                                        dict_for_record.update({field['@name']:field['#text']})
                                    if field['@type'] == 'one2many'  and field['@name'] not in excepted_fields:
                                        key = ast.literal_eval(field['#text']).keys()[0]
                                        list_id =  ast.literal_eval(field['#text'])[key]
                                        list_of_one2many = []
                                        if key not in ['mail.followers']:
                                            for test_list in list_id:
                                                result = get_name(test,key,test_list)
                                                result_dict = get_dict_record(test,key,test_list)
                                                name_field_current = self.env[key].search([('name','=',result)])
                                                if result == name_field_current.name:
                                                    list_of_one2many.append((4,name_field_current.id,False))
                                                else:
                                                    result_dict = get_dict_record(test,key,test_list)
                                                    #res = self.env[key].create(result_dict)
                                                    list_of_one2many.append((0,False,result_dict))        
                                            dict_for_record.update({field['@name']:list_of_one2many})
                                                
                                    if field['@type'] == 'many2one':
                                        print 'test many2one ++++++++++++++++++++++++++++++++'
                                        key = ast.literal_eval(field['#text']).keys()[0]
                                        list_id =  ast.literal_eval(field['#text'])[key]
                                        list_of_many2one = []
                                        for test_list in list_id:
                                            result = get_name(test,key,test_list)
                                            result_dict = get_dict_record(test,key,test_list)
                                            name_field_current = self.env[key].search([('name','=',result)])
                                            if result == name_field_current.name:
                                                list_of_many2one.append(name_field_current.id)
                                                dict_for_record.update({field['@name']:name_field_current.id})
                                            else:
                                                result_dict = get_dict_record(test,key,test_list)
                                                #res = self.env[key].create(result_dict)
                                                #dict_for_record.update({field['@name']:res.id})
                                                dict_for_record.update({field['@name']:list_id[0]})
                                    if field['@type'] == 'many2many':
                                        print field['@type']
                                        print field['#text']
                        else:
                            for field in item['record']['field']: #record of fields
                                if '#text' in field.keys():
                                    if field['@type'] not in ['one2many','many2many','many2one'] and item['@name'] == 'sale.order' and field['@name'] not in excepted_fields:
                                        dict_for_record.update({field['@name']:field['#text']})
                                    if field['@type'] == 'one2many' and field['@name'] not in excepted_fields:
                                        key = ast.literal_eval(field['#text']).keys()[0]
                                        list_id =  ast.literal_eval(field['#text'])[key]
                                        list_of_one2many = []
                                        if key not in ['mail.followers']:
                                            for test_list in list_id:
                                                result = get_name(test,key,test_list)
                                                result_dict = get_dict_record(test,key,test_list)
                                                name_field_current = self.env[key].search([('name','=',result)])
                                                if result is not None:
                                                    result_dict = get_dict_record(test,key,test_list)
                                                    print result_dict
                                                    if result == name_field_current.name:
                                                        list_of_one2many.append((4,name_field_current.id,False))
                                                    else:
                                                        result_dict = get_dict_record(test,key,test_list)
                                                        #res = self.env[key].create(result_dict)
                                                        list_of_one2many.append((0,False,result_dict))        
                                            dict_for_record.update({field['@name']:list_of_one2many})
                                    if field['@type'] == 'many2one':
                                        print 'test many2one ++++++++++++++++++++++++++++++++'
                                        key = ast.literal_eval(field['#text']).keys()[0]
                                        list_id =  ast.literal_eval(field['#text'])[key]
                                        list_of_many2one = []
                                        for test_list in list_id:
                                            result = get_name(test,key,test_list)
                                            result_dict = get_dict_record(test,key,test_list)
                                            name_field_current = self.env[key].search([('name','=',result)])
                                            if result is not None:
                                                if result == name_field_current.name:
                                                    list_of_many2one.append(name_field_current.id)
                                                    dict_for_record.update({field['@name']:list_of_many2one[0]})
                                                else:
                                                    result_dict = get_dict_record(test,key,test_list)
                                                    if 'procurement_ids' in result_dict.keys() and key == 'procurement.group':
                                                        del result_dict['procurement_ids']
                                                    res = self.env[key].create(result_dict)
                                                    dict_for_record.update({field['@name']:res.id})
                                                    
                                    if field['@type'] == 'many2many':
                                        print field['@type']
                                        print field['#text']
                                        print 'test ----------------- '
                                        print ast.literal_eval(field['#text']).keys()
                                        key = ast.literal_eval(field['#text']).keys()[0]
                                        list_id =  ast.literal_eval(field['#text'])[key]
                                        print list_id[0]
                                        print list_id
                                        for test_list in list_id:
                                            result = get_name(test,key,test_list)
                                            name_field = self.env[key].search([('name','=',result)])
                                            if name_field.name == result:
                                                print 'test of name get'
                                                print name_field
                print dict_for_record
                res_create = self.env['sale.order'].with_context(mail_create_nosubscribe=True).create(dict_for_record)
import pywaves as pw

#configuration
amountAssetID = 'WAVES'
priceAssetID = 'BTC'
traders = [
    "3Jjp6T5b7T7fWZt8RWEBz4stoGyQrXVWC1r",
    "3Jz42v5L6pZtUz8nbcVKBroBmZmPL5JnEFt"
]

pw.setNode('https://privatenode2.blackturtle.eu', 'turtlenetwork', 'L')
pw.setMatcher('ttps://privatematcher.blackturtle.eu')
pw.setDatafeed('https://bot.blackturtle.eu')
PAIR = pw.AssetPair(pw.Asset(amountAssetID), pw.Asset(priceAssetID))

#Reward1: Count number of transactions for wallets in trader[] within the last 24 hours for the configured PAIR
#Reward2: Same as Reward1 with an extra check if the amount was > 1
#Reward3: Same as 1 but over a 7 day period

#determine timestamps - 24h
from datetime import datetime
from datetime import timedelta

today = datetime.today()
yesterday = today - timedelta(days=1)
lastweek = today - timedelta(days=7)

today = int(round(datetime.timestamp(today) * 1000))
yesterday = int(round(datetime.timestamp(yesterday) * 1000))
lastweek = int(round(datetime.timestamp(lastweek) * 1000))
예제 #11
0
# LEASE WAVES TO THE WAVESGO POOL
# USES PYWAVES (WITH THANKS)
# ANY QUESTIONS: [email protected]
# www.wavesgo.com

#import libraries
import pywaves as pw
from decimal import *

#configure parameters
pw.setNode(node='http://node.wavesgo.com:6869', chain='mainnet')
minerAddress = pw.Address('3P2HNUd5VUPLMQkJmctTPEeeHumiPN2GkTb')

#ask for user private key
print(
    "=-=-= WELCOME TO THE FANTASTIC, MAGNIFICENT, WAVESGO LEASING APP! =-=-=.\n"
)
print("www.wavesgo.com\n\n")
print("In order to lease, we need your Waves account private key.\n")
print(
    "You can get this from the Waves lite client, click on the backup icon (on the top right hand corner), copy your private key and paste it here.\n"
)
print(
    "Oh, and don't worry - your private key is only used to sign the transaction locally, it won't be sent over the internet.\n\n"
)
while True:
    try:
        myKey = raw_input('Your private Key: ')
        myAddress = pw.Address(privateKey=myKey)
        if myKey:
            break
예제 #12
0
def main():
    bot = SimpleBot()
    bot.read_config("config.cfg")
    pw.setNode(node=bot.node, chain=bot.chain)
    pw.setMatcher(node=bot.matcher)
    my_address = pw.Address(privateKey=bot.private_key)

    bot.log("")
    bot.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    bot.log("+++++++++++++++++++   START NEW SESSION ++++++++++++++++++++++++")
    bot.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    bot.log("Price_asset_id        " + bot.price_asset_id)
    bot.log("Price_asset_name      " + bot.price_asset_name)
    bot.log("Price_asset.decimals  " + str(bot.price_asset.decimals))
    bot.log("Amount_asset.decimals " + str(bot.amount_asset.decimals))
    bot.log("Price_step            " + str(bot.price_step) + " " +
            bot.price_asset_name)

    waves_btc = pw.AssetPair(bot.amount_asset, bot.price_asset)

    # ---- Calculate starting values
    start_waves_balance = my_address.balance() / (10**
                                                  bot.amount_asset.decimals)
    start_btc_balance = my_address.balance(
        bot.price_asset_id) / (10**bot.price_asset.decimals)

    order_book = waves_btc.orderbook()
    start_best_bid = order_book["bids"][0]["price"] / (
        10**bot.price_asset.decimals)
    start_best_ask = order_book["asks"][0]["price"] / (
        10**bot.price_asset.decimals)

    start_value = (start_waves_balance + (start_btc_balance / start_best_bid))

    bot.log("Starting best_bid = " + str(start_best_bid))
    bot.log("Starting best_ask = " + str(start_best_ask))
    bot.log("Starting WAVES balance = " + str(start_waves_balance))
    bot.log("Starting BTC   balance = " + str(start_btc_balance))
    bot.log("Starting Value         = " + str(start_value) + " Waves")

    bot.log("---------------------------------------------------------------")

    last_best_bid = start_best_bid
    last_best_ask = start_best_ask

    while True:

        # ---- collect balances
        waves_balance, btc_balance = my_address.tradableBalance(waves_btc)

        # ---- Collect last balances
        last_waves_balance = my_address.balance() / (10**
                                                     bot.amount_asset.decimals)
        last_btc_balance = my_address.balance(
            bot.price_asset_id) / (10**bot.price_asset.decimals)

        # ---- Collect last price
        order_book = waves_btc.orderbook()
        best_bid = order_book["bids"][0]["price"] / (10**
                                                     bot.price_asset.decimals)
        best_ask = order_book["asks"][0]["price"] / (10**
                                                     bot.price_asset.decimals)
        bot.log("Best_bid  = {0}, best_ask = {1}".format(best_bid, best_ask))

        bot.log("Last WAVES balance " + str(last_waves_balance))
        bot.log("Last BTC   balance " + str(last_btc_balance))
        bot.log("Last BID   Price   " + str(best_bid))

        # ---- calculate value and gain (respect actual price)
        # ---- gain value represent the increase or decrease in Waves if the bot was not running
        value = (last_waves_balance + (last_btc_balance / best_bid))
        gain = value - start_value
        bot.log("GAIN  = " + str(gain) + " Waves")
        bot.log("VALUE = " + str(value) + " Waves")

        # ---- check if pool changed
        if ((best_bid == last_best_bid) and (best_ask == last_best_ask)):
            # Pool not changed to prevent useless traffic
            # -------------------------------------------
            bot.log("Pool NOT changed")
        else:
            # pool changed
            # ------------

            # clear pending order
            my_address.cancelOpenOrders(waves_btc)
            sleep(2)

            # calculate what is better between sell or buy
            # it will sell waves (buying btc)  if btc price lower than previous price less spread
            # it will buy  waves (selling btc) if btc price greater than previous price plus spread
            # to work better the spread must be taken small as much as possible bid and ask prices must be
            # the first in pool

            # -------------------------------------------------
            ask_price = (best_ask + bot.price_step)
            bot.log("ask_price = " + str(ask_price))

            if (best_ask < ask_price):
                # buy waves selling btc
                # ---------------------
                ask_amount = int((last_btc_balance / ask_price) *
                                 10**pw.WAVES.decimals) - (bot.order_fee * 2)
                bot.log("BUY price: {0}, ask amount:{1}".format(
                    ask_price, ask_amount))
                last_best_ask = ask_price
                if ask_amount >= bot.min_amount:
                    bot.log("Post sell order")
                    my_address.sell(assetPair=waves_btc,
                                    amount=ask_amount,
                                    price=ask_price,
                                    matcherFee=bot.order_fee,
                                    maxLifetime=bot.order_lifetime)
                    sleep(4)

                    # ---- collect balances
                    waves_balance, btc_balance = my_address.tradableBalance(
                        waves_btc)

                    # ---- Collect last balances
                    last_waves_balance = my_address.balance() / (
                        10**bot.amount_asset.decimals)
                    last_btc_balance = my_address.balance(
                        bot.price_asset_id) / (10**bot.price_asset.decimals)

            # -------------------------------------------------
            bid_price = (best_bid - bot.price_step)
            bot.log("bid_price = " + str(bid_price))

            if (best_bid > bid_price):
                # sell waves buying btc
                # ---------------------
                bid_amount = int((last_waves_balance *
                                  10**bot.amount_asset.decimals) -
                                 (bot.order_fee * 2))
                bot.log("SELL price: {0}, bid amount: {1}".format(
                    bid_price, bid_amount))
                last_best_bid = bid_price
                if bid_amount >= bot.min_amount:
                    bot.log("Post buy order")
                    my_address.buy(assetPair=waves_btc,
                                   amount=bid_amount,
                                   price=bid_price,
                                   matcherFee=bot.order_fee,
                                   maxLifetime=bot.order_lifetime)

        bot.log(
            "---------------------------------------------------------------")
        sleep(bot.seconds_to_sleep)
예제 #13
0
    amountAssetID = config.get('market', 'amount_asset')
    priceAssetID = config.get('market', 'price_asset')

    INTERVAL = config.getfloat('grid', 'interval')
    TRANCHE_SIZE = config.getint('grid', 'tranche_size')
    GRID_LEVELS = config.getint('grid', 'grid_levels')
    GRID_BASE = config.get('grid', 'base').upper()
    GRID_TYPE = config.get('grid', 'type').upper()

    LOGFILE = config.get('logging', 'logfile')
except:
    log("Error reading config file")
    log("Exiting.")
    exit(1)

pw.setNode(NODE, NETWORK)
pw.setMatcher(MATCHER)
BLACKBOT = pw.Address(privateKey=PRIVATE_KEY)
PAIR = pw.AssetPair(pw.Asset(amountAssetID), pw.Asset(priceAssetID))

log("-" * 80)
log("          Address : %s" % BLACKBOT.address)
log("  Amount Asset ID : %s" % amountAssetID)
log("   Price Asset ID : %s" % priceAssetID)
log("-" * 80)
log("")

# grid list with GRID_LEVELS items. item n is the ID of the order placed at the price calculated with this formula
# price = int(basePrice * (1 + INTERVAL) ** (n - GRID_LEVELS / 2))

grid = ["-"] * GRID_LEVELS
        "type": 4,
        "version": 2,
        "assetId": assetId,
        "senderPublicKey": publicKey,
        "recipient": recipient,
        "amount": amount,
        "fee": txFee,
        "timestamp": timestamp,
        "attachment": base58.b58encode(crypto.str2bytes(attachment)),
        "proofs": [signature]
    }

    return data


pywaves.setNode(node, 'testnet')

# Alice creates a new transaction for Bob
aliceInitialTxForBob = createTransaction(bobsAddress,
                                         alicePublicKey,
                                         alicePrivateKey,
                                         100,
                                         txFee=500000)
# add the hashed secret to the proofs on second position
aliceInitialTxForBob['proofs'].append(
    base58.b58encode(crypto.str2bytes(hashedSecret)))
# Alice secures her account by a Smart Contract implmenting the Atomic Swap protocol
setSmartContract(alicePrivateKey, alicePublicKey, bobsPublicKey, 385000)

# Bob creates a new transaction for Alice
bobsInitialTxForAlice = createAssetTransaction(aliceAddress,
예제 #15
0
    def deploy(self):
        if NETWORKS[self.contract.network.name]['is_free']:
            pw.setNode(node='https://{addr}'.format(
                addr=NETWORKS[self.contract.network.name]['host']),
                       chain=NETWORKS[self.contract.network.name]['type'])
        else:
            pw.setNode(node='https://{addr}'.format(
                addr=NETWORKS[self.contract.network.name]['host']),
                       chain=NETWORKS[self.contract.network.name]['type'])
        pw.setOnline()

        deploy_address = pw.Address(
            privateKey=NETWORKS[self.contract.network.name]['private_key'])
        pubKey, privKey, address = create_waves_privkey()
        created_address = {
            'publicKey': pubKey,
            'privateKey': privKey,
            'address': address
        }
        contract_address = pw.Address(privateKey=privKey)
        print('account created', pubKey, privKey, address, flush=True)
        sending = sign_send_waves(deploy_address, created_address['address'],
                                  110000000)
        #sending = deploy_address.sendWaves(contract_address, 110000000)
        print('sending', sending, flush=True)
        time.sleep(30)
        asset_id = ''
        if not self.reused_token:
            token_params = {
                'name': self.token_short_name,
                'description': self.token_description,
                'total_supply': self.total_supply,
                'decimals': self.decimals
            }
            token_tx = issue_asset_waves(token_params, created_address)
            print('token tx', token_tx, flush=True)
            asset_id = token_tx['assetId']

        token_address = self.asset_id if self.reused_token else asset_id
        self.compile(asset_id=token_address)

        script_trx = set_script_waves(self.ride_contract.source_code,
                                      created_address)

        # try:
        #     trx = contract_address.setScript(
        #         self.ride_contract.source_code,
        #     txFee=1000000,
        #     timestamp=0
        #     )
        # except KeyError:
        #     pw.setOffline()
        #     trx = contract_address.setScript(
        #         self.ride_contract.source_code,
        #     txFee=1000000,
        #     timestamp=0
        #     )
        #     print('setScript trx not broadcasted', token_trx, flush=True)
        #     pw.setOffline()
        print('trx', script_trx, flush=True)
        if not self.asset_id:
            self.asset_id = token_address
            self.save()
        # self.ride_contract.address = address
        self.ride_contract.tx_hash = script_trx['id']
        self.ride_contract.address = script_trx['sender']
        self.ride_contract.bytecode = script_trx['script']
        self.ride_contract.save()
        self.contract.state = 'ACTIVE'
        self.contract.save()
        take_off_blocking(self.contract.network.name)
예제 #16
0
import sys

from flask import Flask, request, jsonify, abort, render_template
from flask_qrcode import QRcode
import pywaves as pw

#from database import db_session, init_db
#from models import KycRequest

#init_db()
# testnet node
#TESTNET_WAVES_NODE='https://testnode1.wavesnodes.com'
#pw.setNode(TESTNET_WAVES_NODE, 'testnet')
# mainnet node
WAVES_NODE = 'https://nodes.wavesnodes.com'
pw.setNode(WAVES_NODE, 'mainnet')
pw.setOnline()
logger = logging.getLogger(__name__)
app = Flask(__name__)
qrcode = QRcode(app)

# testnet asset id
#ASSET_ID='CgUrFtinLXEbJwJVjwwcppk4Vpz1nMmR3H5cQaDcUcfe'
# mainnet asset id
ASSET_ID = '9R3iLi4qGLVWKc16Tg98gmRvgg1usGEYd7SgC1W5D6HB'
asset = pw.Asset(ASSET_ID)
if asset.status() != 'Issued':
    print("ERROR: could not load asset")
    sys.exit(1)
if asset.decimals == 0:
    print("ERROR: asset decimals is 0")
예제 #17
0
import pywaves as pw

pw.setNode(node='https://testnode2.wavesnodes.com', chain='testnet')
script = 'match tx { \n' + \
'  case _ => true\n' + \
'}'
myAddress = pw.Address(
    seed=
    'kind expire cream settle tribe despair act endorse boss material lonely piano advice laundry visa'
)
pw.setOnline()
data = [{'type': 'string', 'key': 'test', 'value': 'testval'}]

print(myAddress.dataTransaction(data))


def send_data_transaction(seed, data):
    adr = pw.Address(seed=seed)
    pw.setOnline()
    adr.dataTransaction()
예제 #18
0
def mixorder(type, pair, amount, price):
    bid_amount = int(amount * 10**pw.WAVES.decimals)
    bid_price = int(price * 10**pw.WAVES.decimals)
    if (type == 'buy'):
        id = my_address.buy(assetPair=pair, amount=bid_amount, price=bid_price)
    else:
        id = my_address.sell(assetPair=pair,
                             amount=bid_amount,
                             price=bid_price)
    return id.orderId


key = getPK()
market = market()
pw.setNode(node=market.node, chain=market.chain)
pw.setMatcher(node=market.matcher)
my_address = pw.Address(privateKey=market.private_key)
cryptomix_btc = pw.AssetPair(market.amount_asset, market.price_asset_btc)
cryptomix_eth = pw.AssetPair(market.amount_asset, market.price_asset_eth)
cryptomix_waves = pw.AssetPair(market.amount_asset, market.price_asset_waves)
BTCprice = 0
ETHprice = 0
WAVESprice = 0

paramError = ''
paramErrorbbBTC = ''
paramErrorbbETH = ''
paramErrorbbWAVES = ''

예제 #19
0
    exit(1)

# parse config file
try:
    log("%sReading config file '%s'" % (COLOR_RESET, CFG_FILE))
    config = configparser.RawConfigParser()
    config.read(CFG_FILE)
    DATA_API_URL = config.get('rfbnetwork', 'rfb_gateway_minimum_balance')
    DATA_API_URL = config.get('main', 'api_url')
    NODE = config.get('main', 'node')
    NETWORK = config.get('main', 'network')
    HOST_PORT = config.getint('rfbnetwork', 'rfb_node_port')
    ACCOUNT_ADDRESS = config.get('account', 'account_address')
    RFBT_ADDRESS = config.get('main', 'rfbt_address')
    LOGFILE = config.get('logging', 'logfile')
    pw.setNode(node=NODE, chain=NETWORK)
    wallet_file = Path("wallet.dat")
    if wallet_file.is_file():
        f = open("wallet.dat", "r")
        if f.mode == 'r':
            contents = f.read()
            if pw.validateAddress(contents):
                ACCOUNT_ADDRESS = contents

    if ACCOUNT_ADDRESS == "XXX":
        print("Please configure your account address")
        ACCOUNT_ADDRESS = configureAccountAddress(NODE, NETWORK)

    log("-" * 80)
    log("  Network : %s" % NETWORK)
    log("  HostPort : %s" % HOST_PORT)
import pywaves as pw
import time

pw.setNode('https://apitnetworktest.blackturtle.eu', 'Turtle Network', 'l')
block = pw.lastblock()
addr = pw.Address(seed='seeeeeeeeedddddd heeeeeerrrrreeeeeeee')
while True:
    try:
        while block['height'] == pw.lastblock()['height']:
            time.sleep(2)

        block = pw.lastblock()
        print(str(block['generator']))
        print(str(block['height']))
        print(
            str(
                addr.sendWaves(pw.Address(address=block['generator']),
                               4200,
                               attachment='Thanks for running a node',
                               txFee=2000000)))
    except:
        time.sleep(2)
        print("except")
예제 #21
0
#print('Computed Public Key:\n{}'.format(b58encode(k_pub)))
# CHECK:print('Expected result:\nHBqhfdFASRQ5eBBpu2y6c6KKi1az6bMx8v1JxX4iW1Q8')

#compute Address
ver = bytes([1])
scheme = b'\x54' # \x57 for mainnet, \x54 for testnet
k_pub_hash = SecureHash(k_pub)[:20]
checksum = SecureHash(ver + scheme + k_pub_hash)[0:4]
address = ver + scheme + k_pub_hash + checksum
#print('Computed Address:\n{}\n'.format(b58encode(address)))

unhashedAddress = chr(1) + str('T') + crypto.hashChain(k_pub)[0:20]
addressHash = crypto.hashChain(crypto.str2bytes(unhashedAddress))[0:4]
address2 = crypto.str2bytes(unhashedAddress + addressHash)

pywaves.setNode(node = 'http://52.30.47.67:6869', chain = 'testnet')

myAddress = pywaves.Address(seed=seed_str)

#print(myAddress.balance())
#myAddress.sendWaves(recipient = pywaves.Address('3NBVqYXrapgJP9atQccdBPAgJPwHDKkh6A8'), amount = 300000000)
time = int(time.time() * 1000)
#constructing Tx
comp = {    't_type' : b'\4',
            'k_pub' : k_pub,
            'amount_flag' : b'\0',
            'fee_flag' : b'\0',
            'timestamp' : time.to_bytes(8, byteorder='big'), #'timestamp' : (1479287120875).to_bytes(8, byteorder='big')
            'amount' : (100000000).to_bytes(8, byteorder='big'),
            'fee' : (100000).to_bytes(8, byteorder='big'),
            'recip_address' : b58decode('3NBVqYXrapgJP9atQccdBPAgJPwHDKkh6A8'),
예제 #22
0
import urllib2
#import urllib
import json
import pywaves as pw

token_ID = 'xxxxxxx'
presale_wallet_addr = ''
privkey = ''
assetDetail = json.load(
    urllib2.urlopen('http://5.189.182.6:6869/assets/details/' + token_ID))
token_decimal = 10**assetDetail['decimals']
pw.setNode('http://5.189.182.6:6869', 'mainnet')
myAddress = pw.Address(privateKey=privkey)
myAsset = pw.Asset(token_ID)
#tx=myAddress.sendAsset(recipient = pw.Address(addr_rec), asset = myAsset, amount=token_amount*token_decimal)
transfers = []
with open('addressList.txt', 'r') as f:
    for line in f:
        addr = line.split(' ')[0]
        amount = line.split(' ')[1].rstrip("\n")
        transfers.append({'recipient': addr, 'amount': int(amount)})

transfers = [{
    'recipient': 'xxxxx',
    'amount': 1000
}, {
    'recipient': 'xxxxx',
    'amount': 2000
}, {
    'recipient': 'xxxxx',
    'amount': 3000
예제 #23
0
def main():


    # add first time enter private key
    # and add copy paste of the code asking for it
    # remind people to keep it secret
    # add encryption to it

    #
    #
    #       Set Settings
    #
    #
    #

    version = "v0.02a"
    configFile = "config.cfg"


    bot = waveTracer()
    bot.read_config(configFile)
    pw.setNode(node=bot.node, chain=bot.chain)
    pw.setMatcher(node=bot.matcher)
    my_addressWaves = pw.Address(privateKey=bot.private_key)
    my_addressBTC = pw.Address(privateKey=bot.private_key_BTC)

    # Set Assets

    VST = pw.Asset("4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8")
    Waves = pw.Asset("")
    BTC = pw.Asset("8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS")
    BCH = pw.Asset("zMFqXuoyrn5w17PFurTqxB7GsS71fp9dfk6XFwxbPCy")
    XMR = pw.Asset("5WvPKSJXzVE2orvbkJ8wsQmmQKqTv9sGBPksV4adViw3")
    ZEC = pw.Asset("BrjUWjndUanm5VsJkbUip8VRYy6LWJePtxya3FNv4TQa")
    USD = pw.Asset("Ft8X1v1LTa1ABafufpaCWyVj8KkaxUWE6xBhW6sNFJck")

    # Set letter variables

    a = 1
    b = 2
    c = 3
    d = 4
    A = a
    B = b
    C = c
    D = d
    textO = ''
    account = ''

    # Set Pairs

    vst_waves = pw.AssetPair(VST, Waves)

    vst_btc = pw.AssetPair(VST, BTC)

    waves_btc = pw.AssetPair(Waves, BTC)

    waves_usd = pw.AssetPair(Waves, USD)

    bch_waves = pw.AssetPair(BCH, Waves)

    bch_usd = pw.AssetPair(BCH, USD)

    xmr_waves = pw.AssetPair(XMR, Waves)

    zec_waves = pw.AssetPair(ZEC, Waves)



    # Welcome aboard waveTracer

    cprint('\n'
           '\n'
        '.:( .:( .:(   Welcome to waveTracer ' + version + '   ):. ):. ):.'  , 'cyan', attrs=['blink'])

    # Read in account names from sheet

    accountsPairs = './matrices/Accounts-Pairs-d1b.csv'
    aPairs = csv.reader(open(accountsPairs))
    linesAP = list(aPairs)
    accountOne = linesAP[1][0]
    accountTwo = linesAP[2][0]
    accountThree = linesAP[3][0]
    accountFour = linesAP[4][0]

    # Set Account

    while account != 'exit' and account != 'a' and account != 'b':

        print('')
        cprint('Which Account to work with?', 'green')
        print('')
        cprint('a. ' + accountOne , 'white')
        cprint('b. ' + accountTwo, 'white')
        cprint('c. ' + accountThree , 'white')
        cprint('d. ' + accountFour , 'white')

        account = input('')

        if str(account) == 'a' or str(account) == 'A':
            my_address = my_addressWaves
            accountName = 'One'
            account = 'a'

        if str(account) == 'b' or str(account) == 'B':
            my_address = my_addressBTC
            accountName = 'Two'
            account = 'b'

        print('')


    # Set Trading Pair

    # ADD - Set trading style
    # - scalp trace (.1 to .9) -
    # - simple retrace (minus 1) -
    # - bear retrace (minus 3 - 10) -
    # - spiderNade (8 sell #'s per buy) -
    # - multicoat retrace for instance 50 sell become 55 rebuy, become 52 sell + 2 and 1 to next 2

    # cprint('\n'
    #        'the year is 1978, and command prompt is the cutting edge of computer interfacing, enjoy.' '\n')
    #

    pairA = './matrices/VST-Waves-Matrix-d2b.csv'
    pairB = './matrices/VST-BTC-Matrix-d2b.csv'
    pairC = './matrices/WAVES-BTC-Matrix-d2b.csv'
    pairD = './matrices/BCH-WAVES-Matrix-d2b.csv'
    pairE = './matrices/XMR-WAVES-Matrix-d2b.csv'
    pairF = './matrices/Waves-USD-Matrix-d2b.csv'
    pairG = './matrices/BCH-USD-Matrix-d2b.csv'
    pairH = './matrices/ZEC-WAVES-Matrix-d2b.csv'


    print('')
    cprint('Which pair do you want to work with?' '\n', 'green')
    cprint(         'a. VST / WAVES', 'grey', 'on_white')
    cprint(         'b. VST / BTC', 'grey', 'on_white')
    cprint(         'c. WAVES / BTC', 'grey', 'on_white')
    cprint(         'd. BCH / WAVES', 'grey', 'on_white')
    cprint(         'e. XMR / WAVES', 'grey', 'on_white')
    cprint(         'f. WAVES / USD ', 'grey', 'on_white')
    cprint(         'g. BCH / USD ', 'grey', 'on_white')
    cprint(         'h. ZEC / USD ', 'grey', 'on_white')
    pick = input('')
    cprint('\n', 'white')

    if str(pick) == 'a' or str(pick) == 'A':

        with open(pairA) as matrixVW:
            rVW = csv.reader(matrixVW)
            lines = list(rVW)

        pairName = 'VST / WAVES'
        pair = vst_waves
        pairCSV = pairA
        decCheck = 0

    if str(pick) == 'b' or str(pick) == 'B':
        with open(pairB) as matrixVB:
            rVB = csv.reader(matrixVB)
            lines = list(rVB)

        pairName = 'VST / BTC'
        pair = vst_btc
        pairCSV = pairB
        decCheck = 0


    if str(pick) == 'c' or str(pick) == 'C':

        with open(pairC) as matrixWB:
            rWB = csv.reader(matrixWB)
            lines = list(rWB)

        pairName = 'WAVES / BTC'
        pair = waves_btc
        pairCSV = pairC
        decCheck = 0


    if str(pick) == 'd' or str(pick) == 'D':

        with open(pairD) as matrixBW:
            rBW = csv.reader(matrixBW)
            lines = list(rBW)

        pairName = 'BCH / WAVES'
        pair = bch_waves
        pairCSV = pairD
        decCheck = 0


    if str(pick) == 'e' or str(pick) == 'E':

        with open(pairE) as matrixXW:
            rBW = csv.reader(matrixXW)
            lines = list(rBW)

        pairName = 'XMR / WAVES'
        pair = xmr_waves
        pairCSV = pairE
        decCheck = 0



    if str(pick) == 'f' or str(pick) == 'F':

        with open(pairF) as matrixXW:
            rBW = csv.reader(matrixXW)
            lines = list(rBW)

        pairName = 'WAVES / USD'
        pair = waves_usd
        pairCSV = pairF
        decCheck = 1



    if str(pick) == 'g' or str(pick) == 'G':

        with open(pairG) as matrixXW:
            rBW = csv.reader(matrixXW)
            lines = list(rBW)

        pairName = 'BCH / USD '
        pair = bch_usd
        pairCSV = pairG
        decCheck = 1


    if str(pick) == 'h' or str(pick) == 'H':

        with open(pairH) as matrixXW:
            rBW = csv.reader(matrixXW)
            lines = list(rBW)

        pairName = 'ZEC / USD '
        pair = zec_waves
        pairCSV = pairH
        decCheck = 0


    cprint('\n', 'white')


    #
    #    Order Spreadsheet Printer
    #

    # load order book

    order_book = pair.orderbook()


    # set CSV cells

    # decCSV csv value location
    decCSVRow = 0
    decCSVCol = 2

    dec = int(lines[decCSVRow][decCSVCol])

    priceDec = dec

    if decCheck == 1:
        priceDec = 100




    # retraceCSV csv value location
    retraceCsvRow = 1
    retraceCsvCol = 2
    reTrace = int(lines[retraceCsvRow][retraceCsvCol])

    # priceAsset csv value location
    priceAssetRow = 0
    priceAssetCol = 4

    # amountAsset csv value location
    amountAssetRow = 1
    amountAssetCol = 4

    # pairString csv value location
    pairStringRow = 0
    pairStringCol = 6

    # pairName csv value location
    pairNameRow = 1
    pairNameCol = 6

    # topRow csv value location
    topRowRow = 0
    topRowCol = 8
    sellStopRow = int(lines[topRowRow][topRowCol])


    # bottomRow csv value location
    bottomRowRow = 1
    bottomRowCol = 8
    buyStopRow = int(lines[bottomRowRow][bottomRowCol])


    # lowSellRow csv value location
    lowSellCsvRow = 0
    lowSellCsvCol = 10
    lowSellRow = int(lines[lowSellCsvRow][lowSellCsvCol])


    # hiBuyRow csv value location
    hiBuyCsvRow = 1
    hiBuyCsvCol = 10
    hiBuyRow = int(lines[hiBuyCsvRow][hiBuyCsvCol])

    # Price Column
    priceCol = 1

    # ID Column
    csvIdCol = 4


    text2 = 'none'
    text3 = 'none'
    previousID = 'none'
    orderNum = 'enter'
    check = 'check'

    balance = my_address.balance(assetId=pair, confirmations=0)

    pprint.pprint(balance)


    cprint('\n'
           '\n'
           '\n', 'blue')

    cprint('waveTracer ' + version , 'cyan' )
    print("Account: " + accountName + ', Pair: ' + pairName)
    print("Balance: " + str(balance) + '\n')

    #print('ask: ' + str(order_book['asks'][00]['price']) + ', bid: ' + str(order_book['bids'][00]['price']) +  '\n')
    #print('ask: ' + str(order_book['asks'][00]['price'] / dec) + ', bid: ' + str(order_book['bids'][00]['price'] / dec) +  '\n')
    cprint(            "' a. Set up initial matrix sell orders '", 'red')
    cprint(            "' b. Set up initial matrix buy orders '", 'green')
    cprint(            "' c. Start retrace engine '", 'cyan')
    cprint(            "' d. Work with orders '", 'grey', 'on_white')

    print('\n')


    text = input('')

    if text == 'a' or text == 'A':
        text = 'sells'

    if text == 'b' or text == 'B':
        text = 'buys'

    if text == 'c' or text == 'C':
        text = 'retrace'

    if text == 'd' or text == 'D':
        text = 'orders'

    textA = ''

    if text == 'orders':
        while textA != 'exit':
            text1 = ''
            textA = ''
            status = ''

            orderNum = 'enter'
            cprint('\n'
                   '\n'
                   '\n', 'blue')

            cprint('waveTracer ' + version, 'cyan')
            print("Account: " + accountName + ', Pair: ' + pairName)

            print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                  + str(order_book['bids'][00]['price'] / priceDec) +  '\n')

            cprint("' a. Check on a single order id '", 'cyan')
            cprint("' b. Check last orders '", 'blue')
            cprint("' c. See your full order history or type filled, accepted or cancelled '", 'red')
            cprint("' d. Post a single order '", 'green')
            cprint("' e. Cancel orders '", 'magenta')
            cprint("' f. Data Transaction '", 'blue', 'on_white')
            cprint("' g. Get a Matrix from Data Transaction '", 'magenta', 'on_cyan')

            print('')
            textA = input('')

            if textA == 'a' or textA == 'A':
                text1 = 'order'

            if textA == 'b' or textA == 'B':
                text1 = 'lastorders'

            if textA == 'c' or textA == 'C':
                text1 = 'orders'

            if textA == 'd' or textA == 'D':
                text1 = 'post'

            if textA == 'e' or textA == 'E':
                text1 = 'cancel'

            if textA == 'f' or textA == 'F':
                text1 = 'data'

            if textA == 'g' or textA == 'G':
                text1 = 'getData'


            if textA == 'filled' or textA == 'FILLED':
                status = 'Filled'
                status2 = 'Stop'
                text1 = 'orders'
                textA = 'less'

            if textA == 'accepted' or textA == 'ACCEPTED':
                status = 'Accepted'
                status2 = 'PartiallyFilled'
                text1 = 'orders'
                textA = 'less'

            if textA == 'cancelled'  or textA == 'CANCELLED':
                status = 'Cancelled'
                status2 = 'Stop'
                text1 = 'orders'
                textA = 'less'


            if text1 == 'order':

                while text2 != 'exit':

                    order_book = pair.orderbook()

                    cprint('waveTracer ' + version, 'cyan')
                    print("Account: " + accountName + ', Pair: ' + pairName)

                    print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                    + str(order_book['bids'][00]['price'] / priceDec) +  '\n')
                    text2 = input('Enter orderId to check on:')

                    myOrders = my_address.getOrderHistory(assetPair=pair)
                    for row in myOrders:
                        if str(row['id']) == text2:
                            pprint.pprint(row)
                            orderTime = row['timestamp']
                            dt_object = datetime.datetime.fromtimestamp(orderTime/ 1e3)
                            print("Time order was " + row['status'] + " " + str(dt_object))
                            print('')


            if text1 == 'orders':
                while orderNum != 'exit':
                    myOrders = my_address.getOrderHistory(assetPair=pair)

                    if textA == 'c' or textA == 'C':
                        pprint.pprint(myOrders)
                        print('')

                        orderNum = 'exit'

                    if textA == 'less':

                        cprint('waveTracer ' + version, 'cyan')
                        print("Account: " + accountName + ', Pair: ' + pairName)

                        print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                              + str(order_book['bids'][00]['price'] / priceDec) + '\n')

                        #print("did it work?")

                        matrix = {}
                        matrixList = []
                        rowMat = 0

                        for row in myOrders:
                            if str(row['status']) == status:

                                matrix['price'] = row['price']
                                matrix['amount'] = row['amount']
                                matrix['id'] = row['id']
                                matrix['type'] = row['type']
                                matrix['status'] = row['status']

                                matrixList.append(matrix.copy())

                                rowMat = rowMat + 1


                            elif str(row['status']) == status2:

                                matrix['price'] = row['price']
                                matrix['amount'] = row['amount']
                                matrix['id'] = row['id']
                                matrix['type'] = row['type']
                                matrix['status'] = row['status']

                                matrixList.append(matrix.copy())

                                rowMat = rowMat + 1


                        #print(matrixList)
                        sortedMatrix = sorted(matrixList, key=lambda k: k['price'], reverse=True)
                        for row in sortedMatrix:

                            print(str(row['type']) + ' @ price: ' + str(row['price']),
                                  ', amount: ' + str(row['amount']) + ' id: ' + str(row['id'])
                                  + ' status: ' + row['status'])

                        orderNum = 'exit'

            if text1 == 'lastorders':

                while text3 != 'exit':

                    cprint('waveTracer '  + version, 'cyan')
                    print("Account: " + accountName + ', Pair: ' + pairName + '\n')

                    print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                          + str(order_book['bids'][00]['price'] / priceDec) + '\n')

                    text3 = input('Enter Order index 0 - 99 or exit:')

                    myOrders = my_address.getOrderHistory(assetPair=pair)
                    if text3 != 'exit':
                        text3 = int(text3)
                        order = myOrders[text3]

                        orderTime = order['timestamp']
                        dt_object = datetime.datetime.fromtimestamp(orderTime/ 1e3)
                        print("Time order was " + order['status'] + " " + str(dt_object))
                        pprint.pprint(order)
                        print('')

            if text1 == 'data':

                while text2 != 'exit':
                    text2 = input('Ready to send your current ' + pairName + ' Matrix data Transaction? yes or no')

                    if text2 == 'yes':
                        data = []
                        count = 0

                        with open(pairCSV, newline='') as matrixData:
                            rBW = csv.reader(matrixData)
                            lines2 = list(rBW)


                        for one in lines2:
                            #b = one
                            #print(b)

                            c = str(one)[1:-1]
                            #print(c)

                            matrixDict = {'type': 'string', 'key': str(count), 'value': c}

                            #case = {'key1': entry[0], 'key2': entry[1], 'key3': entry[2]}
                            #case_list.append(case)

                            data.append(matrixDict)
                            count = count + 1

                        pprint.pprint(data)
                        pprint.pprint(data)


                    #
                    # data = [{
                    #
                    #
                    #     'type': 'string',
                    #     'key': '0',
                    #     'value': '0,1-price,2-volume,3-wavesVol,4-floatVolume,5-orderID,6-lastRow',
                    # },
                    #
                    # ]
                    #

                    dataOrder = my_address.dataTransaction(data)
                    pprint.pprint(dataOrder)

                    orderNum = 'exit'

                    #myOrders = my_address.getOrderHistory(assetPair=pair)
                    #pprint.pprint(myOrders[0])

            if text1 == 'getData':

                while text2 != 'exit':

                    cprint('waveTracer ' + version, 'cyan')
                    print("Account: " + accountName + ', Pair: ' + pairName)

                    print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                          + str(order_book['bids'][00]['price'] / priceDec) + '\n')

                    text2 = input('Enter Data Transaction ID: i.e. Ga5bWqure9tDTuG5mjvbj7rkrgqtVZGWgDa1s7uCT48N '
                                    + 'or D7d1hEiqN91TBZz82PL4hxqura5eKkWwMZPW6oKfv647'
                                  + '\n' )

                    print('')

                    if text2 != 'exit':

                        dataMatrix = requests.get('https://api.wavesplatform.com/v0/transactions/data/' + text2)
                        jsonMatrix = dataMatrix.json()

                        #print(jsonMatrix['data']['data'])
                        with open('./matrices/temp-waves-btc-d1a.csv', 'wt', newline='\n') as matrixWrite:
                            writer = csv.writer(matrixWrite, quoting=csv.QUOTE_NONE, escapechar='\\')
                            count = 0
                            while count < 81:
                                writer.writerows([[jsonMatrix['data']['data'][count]['value']]])
                                count = count + 1
                                print(count)

                        with open('./matrices/temp-waves-btc-d1a.csv') as in_file,\
                                open('./matrices/new-waves-btc-d1b.csv', 'w') as out_file:
                            for line in in_file:
                                out_file.write(line.replace('\\', ''))


                        with open('./matrices/new-waves-btc-d1b.csv') as in_file,\
                                open('./matrices/temp-waves-btc-d1a.csv', 'w') as out_file:
                            for line in in_file:
                                out_file.write(line.replace("'", ''))


                        with open('./matrices/temp-waves-btc-d1a.csv') as in_file,\
                                open('./matrices/new-waves-btc-d1b.csv', 'w') as out_file:
                            for line in in_file:
                                out_file.write(line.replace(" ", ''))

                            # for row in jsonMatrix['data']['data']:
                            #     writer.writerows(row['value'])

                                #print(row['value'])

                        print('')
                        cprint('Commit Matrix to waveTracer for pair: ' + '\n' + '\n'
                               + pairName + '\n' + str(pair) + '\n' + '\n'
                               + ' WARNING: THIS WILL OVERWRITE YOUR LOCAL MATRIX FILE')

                        input('')
                        orderNum = 'exit'



            if text1 == 'post':

                myOrders = ''

                text4 = 'enter'

                while text4 != 'exit':

                    cprint('waveTracer ' + version, 'cyan')
                    print("Account: " + accountName + ', Pair: ' + pairName)
                    print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                    + str(order_book['bids'][00]['price'] / priceDec) +  '\n')
                    print('')
                    cprint('Post a buy or sell?')
                    text4=input('')
                    type = text4


                    cprint("At what Price?",)
                    text4 = input('')
                    price = float(text4)

                    cprint("What amount?")
                    text4 = input('')
                    volume = float(text4) * 10e7
                    volume = int(volume)

                    print('')
                    cprint("Account: " + accountName + ', Pair: ' + pairName, 'cyan' )

                    cprint('Ready to ' + str(type) + ' ' + str(text4) + ' (posting as ' + str(volume) +
                           ') @ ' + str(price) + '? yes or no')
                    text4 = input('')

                    if text4 == 'yes':
                        if type == 'sell':
                            my_address.sell(assetPair=pair, amount=volume, price=price, matcherFee=bot.order_fee,
                                        maxLifetime=bot.order_lifetime)
                            myOrders = my_address.getOrderHistory(assetPair=pair)
                            pprint.pprint(myOrders[0])

                        if type == 'buy':
                            my_address.buy(assetPair=pair, amount=volume, price=price, matcherFee=bot.order_fee,
                                        maxLifetime=bot.order_lifetime)
                            myOrders = my_address.getOrderHistory(assetPair=pair)
                            pprint.pprint(myOrders[0])




            if text1 == 'cancel':

                cprint('waveTracer ' + version, 'cyan')
                print("Account: " + accountName + ', Pair: ' + pairName)

                print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                      + str(order_book['bids'][00]['price'] / priceDec) +  '\n')

                cprint('\n'"a. Cancel sells", 'red')
                cprint("b. Cancel buys", 'green')
                cprint( "c. Cancel both?", 'blue')
                cprint( "d. Cancel single order by id?" '\n', 'cyan')

                cancelType = input('')

                if cancelType == 'a' or cancelType == 'A':
                    cancelType = 'sells'
                if cancelType == 'b' or cancelType == 'B':
                    cancelType = 'buys'
                if cancelType == 'c' or cancelType == 'C':
                    cancelType = 'both'
                if cancelType == 'd' or cancelType == 'D':
                    cancelType = 'single'

                myOrders = my_address.getOrderHistory(assetPair=pair)


                if str(cancelType) == 'sells':
                    print("I'm trying to cancel buys...")


                    for order in myOrders:
                        if order['type'] == 'sell' and order['status'] == 'Accepted':
                            orderIdentity = order['id']
                            pprint.pprint(order)
                            my_address.cancelOrderByID(assetPair=pair, orderId=orderIdentity)

                            print('Cancelling order #' + str(order['id']))


                if str(cancelType) == 'buys':
                    print("I'm trying to cancel buys...")

                    for order in myOrders:
                        if order['type'] == 'buy' and order['status'] == 'Accepted':
                            orderIdentity = order['id']
                            pprint.pprint(order)
                            my_address.cancelOrderByID(assetPair=pair, orderId= orderIdentity)


                            print('Cancelling order #' + str(order['id']))

                if str(cancelType) == 'both':
                    my_address.cancelOpenOrders(pair)


                if str(cancelType) == 'single':

                    cprint('waveTracer ' + version, 'cyan')
                    print("Account: " + accountName + ', Pair: ' + pairName)

                    print('ask: ' + str(order_book['asks'][00]['price'] / priceDec) + ', bid: '
                          + str(order_book['bids'][00]['price'] / priceDec) +  '\n')
                    cancelId = ''
                    cancel = ''
                    cprint("Enter Order ID to Cancel:")
                    cancelId = input('')
                    myOrders = my_address.getOrderHistory(assetPair=pair)

                    for row in myOrders:
                        if str(row['id']) == cancelId:
                            pprint.pprint(row)
                            orderTime = row['timestamp']
                            dt_object = datetime.datetime.fromtimestamp(orderTime / 1e3)
                            print("Time order was " + row['status'] + " " + str(dt_object))
                            print('')
                    print('Is this the one to cancel? yes no')
                    cancel = input('')
                    if cancel == 'yes':
                        my_address.cancelOrderByID(assetPair=pair, orderId=cancelId)
                        myOrders = my_address.getOrderHistory(assetPair=pair)

                        for row in myOrders:
                            if str(row['id']) == cancelId:
                                pprint.pprint(row)
                                orderTime = row['timestamp']
                                dt_object = datetime.datetime.fromtimestamp(orderTime / 1e3)
                                print("Time order was " + row['status'] + " " + str(dt_object))
                                print('')


    if text == 'sells':

        row = lowSellRow
        previousId = 'none'

        print("Do you have your matrix open to double check the buy orders?")
        print("a. Yes")
        print("b. no")

        buyCheck = input('')

        if buyCheck == 'a' or buyCheck == 'A':

            while sellStopRow <= row <= lowSellRow :

                lowSellVol = float(lines[row][priceCol+1])
                volume = int(lowSellVol*dec)

                sellPrice = float(lines[row][priceCol])

                price = int(sellPrice * dec)
                price = price / dec


                if check != 'check':
                    print("Volume is " + str(volume))

                    print('Volume row is ' + str(row))
                    print('col is ' + str(priceCol + 1))

                    print('Price row is ' + str(row))
                    print('col is ' + str(priceCol))

                    cprint("price is " + str(price), 'green')
                    print("volume is " + str(volume))

                if check == 'check':
                    cprint('\n' 'This order is going to sell ' + str(volume/dec) + ' @ ' + str(price) + '\n', 'magenta')
                    cprint('Do you want to check each order before selling type: check', 'red')
                    cprint('Do you want to just auto set the rest of the orders: auto', 'green')

                    check = input('')

                if check == 'check' or check == 'auto':

                    my_address.sell(assetPair=pair, amount=volume, price=price, matcherFee=bot.order_fee,
                                                maxLifetime=bot.order_lifetime)

                    bot.log("Post Sell order with price: {0}, amount:{1}".format(price, volume))

                    myOrders = my_address.getOrderHistory(assetPair=pair)

                    pprint.pprint(myOrders[0])

                    idOrder = str(myOrders[0]['id'])

                    lines[int(row)][csvIdCol] = idOrder
                    cprint(lines[int(row)][csvIdCol], 'red')
                    print('')

                    row = row - 1

                    if previousId == idOrder:
                        idOrder = 'Error Writing this Order'
                        print("Error writing this order")
                        print("What next? retry, skip or exit?")
                        whatNext = input('')

                        if whatNext == 'retry':
                            row = row+1
                        if whatNext == 'skip':
                            row = row
                        if whatNext == 'exit':
                            row = 0

                    previousId = idOrder


                    with open(pairCSV, 'w') as outfile:
                        writer = csv.writer(outfile)
                        writer.writerows(lines)


            # add orderID check,

            #col = 2
            #
            # if myOrders[0]['price'] == price:
            #     if myOrders[0]['status'] == 'Accepted':
            #         print('Order of ' + str(price) + ' ' + myOrders[0]['status'])
            #
            #

    # Initial Buy Orders Engine

    row = hiBuyRow
    col = 1

    # csvBuyCol is being put into the lower Buy column to prevent duplicate matches in the id column search for rebuys

    if text == 'buys':

        row = hiBuyRow
        previousId = 'none'

        print("Do you have your matrix open to double check the buy orders for " + pairName + "?")
        print("a. Yes")
        print("b. no")

        buyCheck = input('')



        if buyCheck == 'a' or buyCheck == 'A':

            while buyStopRow >= row >= hiBuyRow:

                # set buy volume

                hiBuyVol = float(lines[row][priceCol+1])
                volume = int(hiBuyVol*dec)

                # set buy price

                hiBuyPrice = float(lines[row][priceCol])

                price = int(hiBuyPrice * dec)
                price = price / dec

                if check != 'check':

                    print('Volume row is ' + str(row))
                    print('col is ' + str(priceCol + 1))
                    print('Price row is ' + str(row))
                    print('col is ' + str(priceCol))
                    cprint("price is " + str(price), 'green')
                    print("volume is " + str(volume))
                    print("Lifetime is " + str(bot.order_lifetime))

                if check == 'check':
                    cprint('\n' 'This order is going to buy ' + str(volume/dec) + ' @ ' + str(price) + '\n', 'magenta' )
                    cprint('Do you want to check each order before buying type: check', 'red')
                    cprint('Do you want to just autobuy the rest of the orders: auto', 'green')

                    check = input('')

                if check == 'check' or check == 'auto':

                    my_address.buy(assetPair=pair, amount=volume, price=price, matcherFee=bot.order_fee,
                                                maxLifetime=bot.order_lifetime)

                    bot.log("Post Buy order with price: {0}, amount:{1}".format(price, volume))

                    myOrders = my_address.getOrderHistory(assetPair=pair)

                    pprint.pprint(myOrders[0])

                    idOrder = str(myOrders[0]['id'])

                    lines[row][csvIdCol] = idOrder
                    cprint(lines[row][csvIdCol], 'green')
                    print('')

                    row = row + 1

                    # throw error in idOrder Column if id isn't new (only works for first dup, need better solution)

                    if previousId == idOrder:

                        cprint("Error writing this order", 'magenta')
                        cprint("What next? retry, skip or exit?", 'magenta')
                        whatNext = input('')

                        if whatNext == 'retry':
                            row = row + 1
                        if whatNext == 'skip':
                            row = row
                        if whatNext == 'exit':
                            row = 0

                    previousId = idOrder

                    with open(pairCSV, 'w') as outfile:
                        writer = csv.writer(outfile)
                        writer.writerows(lines)


    if text == 'retrace':


        cprint('\n', 'blue')

        print("Account: " + accountName + ', Pair: ' + pairName)
        print('')
        cprint('a. Check each Retrace before placing a new order', 'red')
        cprint('b. Retrace automatically', 'green')
        switch = input('')

        if switch == 'a' or switch == 'A':
            check = 'check'
        if switch == 'b' or switch == 'B':
            check = 'auto'


        while __name__ == "__main__":

            # reload csv to lines

            with open(pairCSV) as matrixRT:
                rRT = csv.reader(matrixRT)
                lines = list(rRT)

            # set CSV cells

            # lowSellRow csv value location
            lowSellCsvRow = 0
            lowSellCsvCol = 10
            lowSellRow = int(lines[lowSellCsvRow][lowSellCsvCol])

            # hiBuyRow csv value location
            hiBuyCsvRow = 1
            hiBuyCsvCol = 10
            hiBuyRow = int(lines[hiBuyCsvRow][hiBuyCsvCol])

            # Price Column
            priceCol = 1

            # ID Column
            csvIdCol = 4

            # reload lowSellId/hiBuyId and lowSellPrice/hiBuyPrice

            lowSellId = lines[lowSellRow][csvIdCol]

            lowSellPrice = float(lines[lowSellRow][priceCol]) * dec

            hiBuyId = lines[hiBuyRow][csvIdCol]

            hiBuyPrice = float(lines[hiBuyRow][priceCol]) * dec

            # load order book

            order_book = pair.orderbook()

            # load Order History

            myOrders = my_address.getOrderHistory(assetPair=pair)
            #pprint.pprint(myOrders)

            cprint('\n' + 'waveTracer ' + version, 'cyan')
            cprint('Account: ' + accountName + ', Pair is: ' + pairName, 'white')
            print('')

            # Print current market low ask and high bid

            print('\n' + "Lowest current market ask is " + str(order_book['asks'][00]['price']/priceDec) + ' Amount: '
                                    + str(order_book['asks'][00]['amount']/dec))
            cprint("Your Last Sell Id is " + lowSellId, 'red')

            for row in myOrders:
                if str(row['id']) == lowSellId:
                    lowSellPrice = row['price']

            cprint("Selling for the very reasonable price of " + str(lowSellPrice/priceDec), 'red')

            # check the status of the lowSellId to see if it's filled

            lowSellStatus = pw.Order(orderId=lowSellId, assetPair=pair, address=my_address).status()
            cprint(lowSellStatus, 'red')
            print('')

            # check the status of the hiBuyId to see if it's filled

            hiBuyStatus = pw.Order(orderId=hiBuyId, assetPair=pair, address=my_address).status()
            print("Highest current market buy is " + str(order_book['bids'][00]['price']/priceDec) + ' Amount: '
                  + (str(order_book['bids'][00]['amount']/dec)))
            cprint("Last Buy Id is " + hiBuyId, 'green')

            for row in myOrders:
                if str(row['id']) == hiBuyId:
                    hiBuyPrice = row['price']

            cprint("Buying for the very reasonable price of " + str(hiBuyPrice/priceDec) + '\n'
                   + hiBuyStatus, 'green')
            print('')

            # Is it time to reorder:

            # toggle to test with an 'Accepted' order
            #if lowSellStatus == 'Filled' or hiBuyStatus == 'Filled' or lowSellStatus == 'Accepted':
            if lowSellStatus == 'Filled' or hiBuyStatus == 'Filled':
                print('Time to retrace')

                # load orders by row

                for row in myOrders:
                    #print(row)

                    # loop through rows to find our 'Filled' highBuyId or lowSellId

                    if str(row['id']) == str(hiBuyId) or str(row['id']) == lowSellId:

                        if row['status'] == 'Filled':
                        # open csv matrix

                            with open(pairCSV) as f:
                                csv_f = csv.reader(f)

                                # loop through csv rows

                                for row2 in csv_f:

                                    # match csv orderId to myOrders 'id'

                                    if row2[csvIdCol] == row['id']:

                                        indexVal = int(row2[0])

                                        print("Row2 order info:")

                                        print(row2)

                                        print("row #" + str(indexVal) + " and id: " + str(row2[csvIdCol]))

                                        print("Old Price is " + str(row['price']))

                                        oldPrice = int(row['price'])
                                        oldVol = int(row['amount'])

                                        # to do: add fee to calc in waves not .9969
                                        #decFee = int(bot.order_fee)
                                        # oldFee = oldPrice * decFee

                                        oldVal = oldPrice * oldVol/dec
                                        oldNet = oldVal * .9969

                                        if row['type'] == 'sell' and row['status'] == 'Filled':
                                            #newPrice = float(lines[indexVal+reTrace][priceCol])
                                            newDecPrice = float((lines[indexVal+reTrace][priceCol]))

                                            fltVol = round(oldNet / newDecPrice, 8)
                                            newVol = int(fltVol)

                                            newPrice = int(float(newDecPrice) * dec) / dec
                                            print("New Buy Price is " + str(newPrice))
                                            # newPrice = newDecPrice
                                            # newPrice = int(float(row2[1])*100)/100

                                            print("New Volume is " + str(newVol))

                                            if check == 'check':
                                                cprint('\n' 'This order is going to buy ' + str(newVol) + ' for '
                                                       + str(newPrice) + '\n', 'magenta')
                                                cprint('Do you want to check each order before buying: check',
                                                       'red')
                                                cprint('Do you want to just autobuy the rest of the orders: auto',
                                                       'green')

                                                check = input('')

                                            if check == 'check' or check == 'auto':

                                                my_address.buy(assetPair=pair, amount=newVol, price=newPrice,
                                                               matcherFee=bot.order_fee,
                                                               maxLifetime=bot.order_lifetime)

                                                bot.log("Post Buy order with price: {0}, amount:{1}".format(newPrice,
                                                                                                            newVol))

                                        if row['type'] == 'buy' and row['status'] == 'Filled':
                                            newDecPrice = lines[indexVal-reTrace][1]
                                            print("New Sell Price is " + str(newDecPrice))
                                            newPrice = int(float(newDecPrice)*dec)/dec

                                            newVol = row['amount']


                                            if check == 'check':
                                                cprint('\n' 'This order is going to sell ' + str(newVol) + ' for ' + str(
                                                    newPrice) + '\n', 'magenta')
                                                cprint('Do you want to check each order before selling: check', 'red')
                                                cprint('Do you want to just autosell the rest of the orders: auto', 'green')

                                                check = input('')

                                            if check == 'check' or check == 'auto':

                                                my_address.sell(assetPair=pair, amount=newVol, price=newPrice,
                                                               matcherFee=bot.order_fee,
                                                               maxLifetime=bot.order_lifetime)

                                                bot.log("Post Sell order with price: {0}, amount:{1}".format(newPrice, newVol))

                                        myOrders = my_address.getOrderHistory(assetPair=pair)

                                        pprint.pprint(myOrders[0])

                                        idOrder = str(myOrders[0]['id'])
                                        idType = str(myOrders[0]['type'])

                                        # set new sell order in orderId column

                                        if idType == 'sell' and row['status'] == 'Filled':

                                            # Store new sell id in orderId column

                                            newSellIdRow = indexVal - reTrace

                                            lines[newSellIdRow][csvIdCol] = idOrder
                                            print("New Lowest Sell Order:")
                                            print(lines[newSellIdRow][csvIdCol])
                                            print('')


                                            # erase old buy orderId near market id

                                            eraseOldIdRow = indexVal

                                            lines[eraseOldIdRow][csvIdCol] = "market"
                                            print("Orders Empty @")
                                            print(lines[eraseOldIdRow][csvIdCol])
                                            print('')


                                            # Store new lowSellIdRow in lowSellCsvRow, lowSellCsvCol

                                            lines[lowSellCsvRow][lowSellCsvCol] = newSellIdRow
                                            print("Current Lowest Sell Order stored in lowSellId:")
                                            print(lines[lowSellCsvRow][lowSellCsvCol])
                                            print(newSellIdRow)
                                            print('these two should match')
                                            print('')


                                            # store new hiBuyId in last

                                            newBuyIdRow = indexVal + 1

                                            lines[hiBuyCsvRow][hiBuyCsvCol] = newBuyIdRow
                                            print("Current highest Buy Order stored in hiBuyId:")
                                            print(lines[hiBuyCsvRow][hiBuyCsvCol])
                                            print(newBuyIdRow)
                                            print('these two should match')
                                            print('')

                                            # set last market sell id for lower right box of matrix file in buy col


                                        if idType == 'buy' and row['status'] == 'Filled':

                                            # Store new hiBuyOrder id in orderId column

                                            newBuyIdRow = indexVal + reTrace

                                            lines[newBuyIdRow][csvIdCol] = idOrder
                                            print("New Highest Buy Order:")
                                            print(lines[newBuyIdRow][csvIdCol])
                                            print('')

                                            # erase old sell orderId near market id

                                            eraseOldIdRow = indexVal

                                            lines[eraseOldIdRow][csvIdCol] = "market"
                                            print("Orders Empty @")
                                            print(lines[eraseOldIdRow][csvIdCol])
                                            print('')

                                            # Store new hiBuyIdRow in hiBuyCSV Cell

                                            lines[hiBuyCsvRow][hiBuyCsvCol] = newBuyIdRow
                                            print("Current Lowest Buy Order stored in lowSellId:")
                                            print(lines[hiBuyCsvRow][hiBuyCsvCol])
                                            print(newBuyIdRow)
                                            print('these two should match')
                                            print('')

                                            # store new lowSellId in lowSellIdRow Cell

                                            newSellIdRow = indexVal - 1

                                            lines[lowSellCsvRow][lowSellCsvCol] = newSellIdRow
                                            print(newSellIdRow)
                                            print(lines[lowSellCsvRow][lowSellCsvCol])
                                            print('these two should match')
                                            print('')

                                            # set last market sell id for lower right box of matrix file in buy col

                                        # f = open(pairCSV, 'w')
                                        # f.write(lines)
                                        # f.close()

                                        with open(pairCSV, 'w') as outfile:
                                            writer = csv.writer(outfile)
                                            writer.writerows(lines)

                                        print('')

            cprint("Well nothing left to do for now, guess I'll take a nap for 100 ticks starting @ %s" % time.ctime(),
                   'cyan')
            #cprint("Current Lowest Market ask for VST/Waves is " + str(order_book['asks'][00]['price']))
            #cprint("Current Highest Market bid for VST/Waves is " + str(order_book['bids'][00]['price']))

            time.sleep(2)
            cprint('zzz', 'blue')
            time.sleep(2)
            cprint('   zzz', 'blue')
            time.sleep(2)
            cprint('      zzz', 'blue')
            time.sleep(2)
            cprint('         zzz', 'blue')
            time.sleep(2)
            cprint('            zzz', 'blue')
            time.sleep(2)
            cprint('               zzz', 'blue')
            time.sleep(2)
            cprint('                  zzz', 'blue')
            time.sleep(2)
            cprint('                     zzz', 'blue')
            time.sleep(2)
            cprint('                        zzz', 'blue')
            time.sleep(2)
            cprint('                           zzz', 'blue')

            cprint("I'm up, what'd I miss? Let me check:", 'magenta')
            time.sleep(1)
예제 #24
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")

if __name__ == "__main__":
    # parse arguments
    parser = construct_parser()
    args = parser.parse_args()

    # set chain and asset id
    pw.setNode(TESTNET_NODE, "testnet", "T")
    args.assetid = TESTNET_ASSETID
    if args.mainnet:
        pw.setNode(MAINNET_NODE, "mainnet", "W")
        args.assetid = MAINNET_ASSETID
    pw.setOnline()
    print(f"Network: {pw.NODE} ({pw.CHAIN} - {pw.CHAIN_ID})")

    # initialise database
    init_db()

    # set appropriate function
    function = None
    if args.command == "create":
        function = create_run
    elif args.command == "fund":
예제 #25
0
            'plunge draw hedgehog chief jeans narrow flight abuse isolate amazing mirror advance bone crucial educate'
        ))
    wallets.append(
        py.Address(
            seed=
            'bean tool all make clap disagree food buyer forward toy find miracle sick sauce slide'
        ))
    wallets.append(
        py.Address(
            seed=
            'fresh return verb source radio response broom space appear way energy owner polar electric lock'
        ))


#initialisation
py.setNode('https://sg.katalystcoin.com')
scheduler = BlockingScheduler()

token = py.Asset('GQsFCrD43pHkhdvt5PnZ4W9Qgg8X9LjCSWAUG6mLoFMg')  #dioncoin
myAddress = py.Address(
    privateKey='6QsHMXahBHQmaYjA2PMDR3BFXRyWWHCAJfVMn7dWXPrk')
#myAddress.sendAsset(recipient = py.Address(privateKey='7VkCrrhhueZTRiwwdBZ8R4DS82M3qTFGXVb8JxXhtRCg'), asset = token, amount = 100)

initialiseWallets()

height = py.height()
value = 25 * math.pow(10, 7)


def sendTokens():
    currentHeight = py.height()
예제 #26
0
import logging
from config import CHAIN, REWARD_LIMIT, APP_WAVES_ADDRESS, APP_SECRET_KEY, NODES
import pywaves as pw

pw.setNode(NODES[CHAIN], CHAIN)
logger = logging.getLogger(__name__)


class Rewarder:
    def __init__(self):
        self.remaining_waves = REWARD_LIMIT
        self.address = pw.Address(privateKey=APP_SECRET_KEY)

    def send_reward(self, address, amount):
        if amount > self.remaining_waves:
            raise Exception('Insufficient funds')
        recipient = pw.Address(address)
        self.remaining_waves -= amount
        logger.info(f'{self.remaining_waves} WAVES left')
        self.address.sendWaves(recipient, int(amount * 10**8))


rewarder = Rewarder()