def run_bot(bot=bot): try: rpc = GrapheneAPI(config.wallet_host, config.wallet_port, "", "") rpc.unlock(config.wallet_password) # unlock the wallet. except RPCError as e: print(e) print(str(datetime.datetime.now()) + ": Starting bot...") print(str(datetime.datetime.now()) + ": Cancelling orders...") bot.cancel_all() print(str(datetime.datetime.now()) + ": Sleeping") time.sleep(12) print(str(datetime.datetime.now()) + ": Running the bot") try: bot.execute() except RPCError as e: if "amount_to_sell.amount > 0" in str(e): print( "MANUAL ACTION NEEDED: Can't place order because the amount is too small" ) print( "Getting more of the currency you are selling or buying with should fix this" ) print(e) else: print(e)
def run_bot(bot=bot): rpc = GrapheneAPI(config.wallet_host, config.wallet_port, "", "") if rpc.is_locked(): rpc.unlock(config.wallet_password) print(str(datetime.now()) + "| Starting bot...") bot.init(config) time.sleep(6) print(str(datetime.now()) + "| Running the bot") bot.run()
def run_bot(bot=bot): try: rpc = GrapheneAPI(config.wallet_host, config.wallet_port, "", "") rpc.unlock(config.wallet_password) # unlock the wallet. except RPCError as e: print(e) print(str(datetime.datetime.now()) + ": Starting bot...") print(str(datetime.datetime.now()) + ": Cancelling orders...") bot.cancel_all() print(str(datetime.datetime.now()) + ": Sleeping") time.sleep(12) print(str(datetime.datetime.now()) + ": Running the bot") try: bot.execute() except RPCError as e: if "amount_to_sell.amount > 0" in str(e): print("MANUAL ACTION NEEDED: Can't place order because the amount is too small") print("Getting more of the currency you are selling or buying with should fix this") print(e) else: print(e)
import json import datetime from grapheneapi import GrapheneAPI import config if __name__ == '__main__': client = GrapheneAPI(config.wallet_host, config.wallet_port, config.wallet_user, config.wallet_password) proposer = client.get_account(config.proposer_account) owner = client.get_account(config.proposing_account) ops = [] """ Construct TX """ op = client.get_prototype_operation("proposal_delete_operation") op[1]["fee_paying_account"] = owner["id"] op[1]["proposal"] = config.pid ops.append(op) buildHandle = client.begin_builder_transaction() for op in ops : client.add_operation_to_builder_transaction(buildHandle, op) client.set_fees_on_builder_transaction(buildHandle, "1.3.0") params = client.get_object("2.0.0")[0] if owner["name"] == "committee-account": preview = params["parameters"]["committee_proposal_review_period"] else: preview = 0
import json from grapheneapi import GrapheneAPI from datetime import datetime import time import config if __name__ == '__main__': client = GrapheneAPI(config.wallet_host, config.wallet_port, config.wallet_user, config.wallet_password) proposer = client.get_account(config.proposer_account) owner = client.get_account(config.worker_owner) asset = client.get_asset("1.3.0") ops = [] for i in range(0,config.numWorkersPertype) : op = client.get_prototype_operation("worker_create_operation") op[1]["name"] = "burn-100k-%d" % (i+1) op[1]["owner"] = owner["id"] op[1]["work_begin_date"] = config.start_date op[1]["work_end_date"] = config.end_date op[1]["daily_pay"] = config.daily_pay op[1]["url"] = config.url op[1]["initializer"] = [ 2,{} # BURN ] ops.append(op) for i in range(0,config.numWorkersPertype) : op = client.get_prototype_operation("worker_create_operation") op[1]["name"] = "refund-100k-%d" % (i+1)
def update_price_feed() : for base in _bases + [core_symbol]: price[base] = {} volume[base] = {} for asset in _all_bts_assets + [core_symbol]: price[base][asset] = [] volume[base][asset] = [] for asset in _all_bts_assets + [core_symbol]: price_in_bts_weighted[asset] = 0.0 price_median_blockchain[asset] = 0.0 lastUpdate[asset] = datetime.utcnow() myCurrentFeed[asset] = {} ## rpc variables about bts rpc ############################################### rpc = GrapheneAPI(config.host, config.port, config.user, config.passwd) fetch_from_wallet(rpc) ## Get prices and stats ###################################################### mythreads = {} mythreads["yahoo"] = threading.Thread(target = fetch_from_yahoo) if config.enable_btcid : mythreads["btcid"] = threading.Thread(target = fetch_from_btcIndonesia) if config.enable_ccedk : mythreads["ccedk"] = threading.Thread(target = fetch_from_ccedk) if config.enable_yunbi : mythreads["yunbi"] = threading.Thread(target = fetch_from_yunbi) if config.enable_btc38 : mythreads["btc38"] = threading.Thread(target = fetch_from_btc38) if config.enable_bter : mythreads["bter"] = threading.Thread(target = fetch_from_bter) if config.enable_poloniex : mythreads["poloniex"] = threading.Thread(target = fetch_from_poloniex) if config.enable_bittrex : mythreads["bittrex"] = threading.Thread(target = fetch_from_bittrex) if config.enable_btcavg : mythreads["btcavg"] = threading.Thread(target = fetch_bitcoinaverage) print("[Starting Threads]: ", end="",flush=True) for t in mythreads : print("(%s)"%t, end="",flush=True) mythreads[t].start() for t in mythreads : mythreads[t].join() # Will wait for a thread until it finishes its task. print(".", end="",flush=True) ## Determine bts price ###################################################### derive_prices() ## Only publish given feeds ################################################## price_feeds = [] for asset in asset_list_publish : if len(price[core_symbol][asset]) > 0 : if price_in_bts_weighted[asset] > 0.0: quote_precision = assets[asset]["precision"] base_precision = assets["1.3.0"]["precision"] ## core asset core_price = price_in_bts_weighted[asset] * 10**(quote_precision-base_precision) core_price = fractions.Fraction.from_float(core_price).limit_denominator(100000) denominator = core_price.denominator numerator = core_price.numerator assert assets[asset]["symbol"] is not asset #if denominator == 0 or numerator == 0 or int(denominator * config.core_exchange_factor) : # continue price_feed = { "settlement_price": { "quote": { "asset_id": "1.3.0", "amount": denominator }, "base": { "asset_id": assets[asset]["id"], "amount": numerator } }, "maintenance_collateral_ratio": config.maintenance_collateral_ratio, "maximum_short_squeeze_ratio": config.maximum_short_squeeze_ratio, "core_exchange_rate": { "quote": { "asset_id": "1.3.0", "amount": int(denominator * config.core_exchange_factor) }, "base": { "asset_id": assets[asset]["id"], "amount": numerator } } } price_feeds.append([assets[asset]["id"], price_feed]) ## Print some stats ########################################################## print_stats() ## Check publish rules and publich feeds ##################################### publish = False if publish_rule(rpc) : if config.ask_confirmation : if rpc._confirm("Are you SURE you would like to publish this feed?") : publish = True else : publish = True if publish : print("Update required! Forcing now!") update_feed(rpc,price_feeds) else : print("no update required")
import json from grapheneapi import GrapheneAPI import math import config if __name__ == '__main__': client = GrapheneAPI(config.wallet_host, config.wallet_port, config.wallet_user, config.wallet_password) proposer = client.get_account(config.proposer_account) owner = client.get_account(config.issuer_account) ops = [] for symbol in config.claim_assets : percentage = config.claim_assets[symbol] asset = client.get_asset(symbol) """ Construct TX """ op = client.get_prototype_operation("asset_claim_fees_operation") op[1]["issuer"] = owner["id"] op[1]["amount_to_claim"]["asset_id"] = asset["id"] """ Get accumulated amount from blockchain """ asset_data = client.get_object(asset["dynamic_asset_data_id"])[0] accumulated_fees = asset_data["accumulated_fees"] op[1]["amount_to_claim"]["amount"] = math.floor(accumulated_fees * percentage / 100) ops.append(op) buildHandle = client.begin_builder_transaction() for op in ops :
import json from grapheneapi import GrapheneAPI from datetime import datetime import time import config if __name__ == '__main__': client = GrapheneAPI(config.wallet_host, config.wallet_port, config.wallet_user, config.wallet_password) proposer = client.get_account(config.proposer_account) owner = client.get_account(config.worker_owner) asset = client.get_asset("1.3.0") ops = [] for i in range(0, config.numWorkersPertype): op = client.get_prototype_operation("worker_create_operation") op[1]["name"] = "burn-100k-%d" % (i + 1) op[1]["owner"] = owner["id"] op[1]["work_begin_date"] = config.start_date op[1]["work_end_date"] = config.end_date op[1]["daily_pay"] = config.daily_pay op[1]["url"] = config.url op[1]["initializer"] = [ 2, {} # BURN ] ops.append(op) for i in range(0, config.numWorkersPertype):
import json from grapheneapi import GrapheneAPI import config if __name__ == '__main__': client = GrapheneAPI(config.wallet_host, config.wallet_port, config.wallet_user, config.wallet_password) proposer = client.get_account(config.proposer_account) from_account = client.get_account(config.transfer_from) to_account = client.get_account(config.transfer_to) ops = [] assetsavailable = client.list_account_balances("committee-account") for balance in assetsavailable: asset = client.get_asset(balance["asset_id"]) if asset["id"] == "1.3.0": continue transfer_amount = int(balance["amount"] * config.transfer_percentage / 100.0) op = client.get_prototype_operation("transfer_operation") op[1]["amount"]["amount"] = transfer_amount op[1]["amount"]["asset_id"] = asset["id"] op[1]["from"] = from_account["id"] op[1]["to"] = to_account["id"] ops.append(op) buildHandle = client.begin_builder_transaction() for op in ops: client.add_operation_to_builder_transaction(buildHandle, op) client.set_fees_on_builder_transaction(buildHandle, "1.3.0") params = client.get_object("2.0.0")[0]
import time import json from grapheneapi import GrapheneAPI blockinterval = 5 numbertxperblock = 15 if __name__ == '__main__': client = GrapheneAPI("localhost", 8092, "", "") while True: for i in range(0, numbertxperblock): print(i) res = client.transfer("fabian.schuh", "schuh", "0.00001", "CORE", "memo", True) print(json.dumps(res, indent=4)) time.sleep(blockinterval)
def update_price_feed() : global derived_prices, config state = {} for asset in _all_assets + [core_symbol]: price_median_blockchain[asset] = 0.0 lastUpdate[asset] = datetime.utcnow() myCurrentFeed[asset] = {} if configFile.blame != "latest" : blameFile = config.configPath + "/blame/" + configFile.blame + ".json" if os.path.isfile(blameFile) : # Load data from disk for (faster) debugging and verification with open(blameFile, 'r') as fp: state = json.load(fp) # Load feed sources feed = state["feed"] # Load configuration from old state configStruct = state["config"] for key in configStruct : # Skip asset config if key == "asset_config" : continue config.__dict__[key] = configStruct[key] else : sys.exit("Configuration error: Either set 'blame' to an existing " + "block number from the blame/ to verify or set it to " + "'latest' to run the script online! ") else : # Load configuration from file config = configFile # Get prices online from sources pool = futures.ThreadPoolExecutor(max_workers=8) feed = {} mythreads = {} for name in config.feedSources : print("(%s)" % name, end="", flush=True) mythreads[name] = pool.submit(config.feedSources[name].fetch) for name in config.feedSources : print(".", end="", flush=True) feed[name] = mythreads[name].result() # rpc variables about bts rpc ############################################## rpc = GrapheneAPI(config.host, config.port, config.user, config.passwd) fetch_from_wallet(rpc) # Determine bts price ###################################################### derived_prices = derive_prices(feed) # Only publish given feeds ################################################# price_feeds = {} update_required = False for asset in asset_list_publish : # Get Final Price according to price metric this_asset_config = config.asset_config[asset] if asset in config.asset_config else config.asset_config["default"] price_metric = this_asset_config["metric"] if "metric" in this_asset_config else config.asset_config["default"]["metric"] if (asset not in derived_prices or core_symbol not in derived_prices[asset] or price_metric not in derived_prices[asset][core_symbol]) : print("Warning: Asset %s has no derived price!" % asset) continue if float(derived_prices[asset][core_symbol][price_metric]) > 0.0: quote_precision_core = assets[asset]["precision"] symbol = assets[asset]["symbol"] assert symbol is not asset base_precision_cer = assets[blockchain_feed_quote[asset]]["precision"] # core asset core_price_cer = derived_prices[asset][core_symbol][price_metric] * 10 ** (quote_precision_core - base_precision_cer) core_price_cer = fractions.Fraction.from_float(core_price_cer).limit_denominator(100000) denominator_cer = core_price_cer.denominator numerator_cer = core_price_cer.numerator quote_precision_settle = assets[asset]["precision"] symbol = assets[asset]["symbol"] assert symbol is not asset base_precision_settle = assets[blockchain_feed_quote[asset]]["precision"] # core asset core_price_settle = derived_prices[asset]["short_backing_asset"][price_metric] * 10 ** (quote_precision_settle - base_precision_settle) core_price_settle = fractions.Fraction.from_float(core_price_settle).limit_denominator(100000) denominator_settle = core_price_settle.denominator numerator_settle = core_price_settle.numerator price_feed = {"settlement_price": { "quote": {"asset_id": assets[blockchain_feed_quote[asset]]["id"], "amount": denominator_settle }, "base": {"asset_id": assets[asset]["id"], "amount": numerator_settle } }, "maintenance_collateral_ratio" : config.asset_config[symbol]["maintenance_collateral_ratio"] if (symbol in config.asset_config and "maintenance_collateral_ratio" in config.asset_config[symbol]) else config.asset_config["default"]["maintenance_collateral_ratio"], "maximum_short_squeeze_ratio" : config.asset_config[symbol]["maximum_short_squeeze_ratio"] if (symbol in config.asset_config and "maximum_short_squeeze_ratio" in config.asset_config[symbol]) else config.asset_config["default"]["maximum_short_squeeze_ratio"], "core_exchange_rate": { "quote": {"asset_id": "1.3.0", "amount": int(denominator_cer * ( config.asset_config[symbol]["core_exchange_factor"] if (symbol in config.asset_config and "core_exchange_factor" in config.asset_config[symbol]) else config.asset_config["default"]["core_exchange_factor"])) }, "base": {"asset_id": assets[asset]["id"], "amount": numerator_cer }}} asset_update_required = publish_rule(rpc, asset) if asset_update_required : update_required = True price_feeds[symbol] = {"asset_id": assets[asset]["id"], "feed": price_feed, "publish": asset_update_required } else : print("Warning: Asset %s has a negative derived price of %f (%s metric)!" % (asset, float(derived_prices[asset][price_metric]), price_metric)) continue if not debug : # Print some stats ########################################################## print_stats(price_feeds) # Verify results or store them ############################################## configStruct = {} for key in dir(config) : if key[0] == "_" : continue if key == "feedSources" : continue if key == "feedsources" : continue if key == "subprocess" : continue if key == "os" : continue configStruct[key] = config.__dict__[key] # Store State state["feed"] = feed state["derived_prices"] = derived_prices state["price_feeds"] = price_feeds state["lastblock"] = get_last_block(rpc) state["config"] = configStruct blameFile = config.configPath + "/blame/" + str(state["lastblock"]) + ".json" with open(blameFile, 'w') as fp: json.dump(state, fp) print("Blamefile: " + blameFile) # Check publish rules and publich feeds ##################################### if update_required and not debug : publish = False if config.ask_confirmation : if rpc._confirm("Are you SURE you would like to publish this feed?") : publish = True else : publish = True if publish : print("Update required! Forcing now!") update_feed(rpc, price_feeds) else : print("no update required") else : # Verify results print() print("[Warning] This script is loading old data for debugging. No price can be published.\n" + " Please set 'blame' to 'latest' if you are ready to go online!") print() compare_feeds(state["derived_prices"], derived_prices)
def update_price_feed() : for base in _bases + [core_symbol]: price[base] = {} volume[base] = {} for asset in _all_bts_assets + [core_symbol]: price[base][asset] = [] volume[base][asset] = [] for asset in _all_bts_assets + [core_symbol]: price_in_bts_weighted[asset] = 0.0 price_median_blockchain[asset] = 0.0 lastUpdate[asset] = datetime.utcnow() myCurrentFeed[asset] = {} ## rpc variables about bts rpc ############################################### rpc = GrapheneAPI(config.host, config.port, config.user, config.passwd) fetch_from_wallet(rpc) ## Get prices and stats ###################################################### mythreads = {} mythreads["yahoo"] = threading.Thread(target = fetch_from_yahoo) if config.enable_btcid : mythreads["btcid"] = threading.Thread(target = fetch_from_btcIndonesia) if config.enable_ccedk : mythreads["ccedk"] = threading.Thread(target = fetch_from_ccedk) if config.enable_yunbi : mythreads["yunbi"] = threading.Thread(target = fetch_from_yunbi) if config.enable_btc38 : mythreads["btc38"] = threading.Thread(target = fetch_from_btc38) if config.enable_bter : mythreads["bter"] = threading.Thread(target = fetch_from_bter) if config.enable_poloniex : mythreads["poloniex"] = threading.Thread(target = fetch_from_poloniex) if config.enable_bittrex : mythreads["bittrex"] = threading.Thread(target = fetch_from_bittrex) if config.enable_btcavg : mythreads["btcavg"] = threading.Thread(target = fetch_bitcoinaverage) print("[Starting Threads]: ", end="",flush=True) for t in mythreads : print("(%s)"%t, end="",flush=True) mythreads[t].start() for t in mythreads : mythreads[t].join() # Will wait for a thread until it finishes its task. print(".", end="",flush=True) ## Determine bts price ###################################################### derive_prices() ## Only publish given feeds ################################################## price_feeds = [] for asset in asset_list_publish : if len(price[core_symbol][asset]) > 0 : if price_in_bts_weighted[asset] > 0.0: quote_precision = assets[asset]["precision"] base_precision = assets["1.3.0"]["precision"] ## core asset core_price = price_in_bts_weighted[asset] * 10**(quote_precision-base_precision) core_price = fractions.Fraction.from_float(core_price).limit_denominator(100000) denominator = core_price.denominator numerator = core_price.numerator assert assets[asset]["symbol"] is not asset #if denominator == 0 or numerator == 0 or int(denominator * config.core_exchange_factor) : # continue price_feed = { "settlement_price": { "quote": { "asset_id": "1.3.0", "amount": denominator }, "base": { "asset_id": assets[asset]["id"], "amount": numerator } }, "maintenance_collateral_ratio": config.maintenance_collateral_ratio, "maximum_short_squeeze_ratio": config.maximum_short_squeeze_ratio, "core_exchange_rate": { "quote": { "asset_id": "1.3.0", "amount": int(denominator * config.core_exchange_factor) }, "base": { "asset_id": assets[asset]["id"], "amount": numerator } } } price_feeds.append([assets[asset]["id"], price_feed]) ## Print some stats ########################################################## print_stats() ## Check publish rules and publich feeds ##################################### publish = False if publish_rule(rpc) : if config.ask_confirmation : if rpc._confirm("Are you SURE you would like to publish this feed?") : publish = True else : publish = True if publish : print("Update required! Forcing now!") update_feed(rpc,price_feeds) else : print("no update required")
import time import json from grapheneapi import GrapheneAPI blockinterval = 5 numbertxperblock = 15 if __name__ == '__main__': client = GrapheneAPI("localhost", 8092, "", "") while True : for i in range(0,numbertxperblock) : print(i) res = client.transfer("fabian.schuh","schuh","0.00001", "CORE", "memo", True); print(json.dumps(res,indent=4)) time.sleep(blockinterval)
"owner_key": public_key, "active_key": public_key, "memo_key": public_key, "refcode": referrer, "referrer": referrer } } request = requests.post(faucet + '/api/v1/accounts', data=json.dumps(payload), headers=headers) return (request.status_code == 201, request.text) if __name__ == '__main__': time.sleep(5) # sleep to give the cli_wallet time to start rpc = GrapheneAPI(config.wallet_host, config.wallet_port, "", "") try: rpc.set_password(config.wallet_password) # try to set password except RPCError: # if RCPError the password is already set pass rpc.unlock(config.wallet_password) # unlock the wallet. my_accounts = rpc.list_my_accounts() if len(my_accounts) == 0: brain_key = rpc.suggest_brain_key() account_registered, account_registration_response = register_account_faucet( config.account, brain_key['pub_key']) if account_registered: rpc.import_key(config.account, brain_key['wif_priv_key']) print("Account: %s successfully registered" % config.account)
for base in _bases + [core_symbol]: price[base] = {} volume[base] = {} for asset in _all_bts_assets + [core_symbol]: price[base][asset] = [] volume[base][asset] = [] for asset in _all_bts_assets + [core_symbol]: price_in_bts_weighted[asset] = 0.0 price_median_blockchain[asset] = 0.0 lastUpdate[asset] = datetime.utcnow() myCurrentFeed[asset] = {} ## rpc variables about bts rpc ############################################### rpc = GrapheneAPI(config.host, config.port, config.user, config.passwd) fetch_from_wallet(rpc) ## Get prices and stats ###################################################### mythreads = {} mythreads["yahoo"] = threading.Thread(target=fetch_from_yahoo) mythreads["yunbi"] = threading.Thread(target=fetch_from_yunbi) mythreads["btc38"] = threading.Thread(target=fetch_from_btc38) mythreads["bter"] = threading.Thread(target=fetch_from_bter) mythreads["poloniex"] = threading.Thread(target=fetch_from_poloniex) mythreads["bittrex"] = threading.Thread(target=fetch_from_bittrex) mythreads["btcavg"] = threading.Thread(target=fetch_bitcoinaverage) print("[Starting Threads]: ", end="", flush=True) for t in mythreads: print("(%s)" % t, end="", flush=True)
"owner_key": public_key, "active_key": public_key, "memo_key": public_key, "refcode": referrer, "referrer": referrer } } request = requests.post(faucet + '/api/v1/accounts', data=json.dumps(payload), headers=headers) return (request.status_code == 201, request.text) if __name__ == '__main__': time.sleep(5) # sleep to give the cli_wallet time to start # rpc connection rpc = GrapheneAPI(config.wallet_host, config.wallet_port, "", "") try: rpc.set_password(config.wallet_password) # try to set password except RPCError: # if RCPError the password is already set pass rpc.unlock(config.wallet_password) # unlock the wallet. my_accounts = rpc.list_my_accounts() if len(my_accounts) is 0: brain_key = rpc.suggest_brain_key() account_registered, account_registration_response = register_account_faucet(config.account, brain_key['pub_key']) if account_registered: rpc.import_key(config.account, brain_key['wif_priv_key']) print("Account: %s succesfully registered" % config.account)
for base in _bases + [core_symbol]: price[base] = {} volume[base] = {} for asset in _all_bts_assets + [core_symbol]: price[base][asset] = [] volume[base][asset] = [] for asset in _all_bts_assets + [core_symbol]: price_in_bts_weighted[asset] = 0.0 price_median_blockchain[asset] = 0.0 lastUpdate[asset] = datetime.utcnow() myCurrentFeed[asset] = {} ## rpc variables about bts rpc ############################################### rpc = GrapheneAPI(config.host, config.port, config.user, config.passwd) fetch_from_wallet(rpc) ## Get prices and stats ###################################################### mythreads = {} mythreads["yahoo"] = threading.Thread(target = fetch_from_yahoo) if config.enable_yunbi : mythreads["yunbi"] = threading.Thread(target = fetch_from_yunbi) if config.enable_btc38 : mythreads["btc38"] = threading.Thread(target = fetch_from_btc38) if config.enable_bter : mythreads["bter"] = threading.Thread(target = fetch_from_bter) if config.enable_poloniex : mythreads["poloniex"] = threading.Thread(target = fetch_from_poloniex) if config.enable_bittrex : mythreads["bittrex"] = threading.Thread(target = fetch_from_bittrex) if config.enable_btcavg : mythreads["btcavg"] = threading.Thread(target = fetch_bitcoinaverage) print("[Starting Threads]: ", end="",flush=True) for t in mythreads : print("(%s)"%t, end="",flush=True)