示例#1
0
    def init_grid(self):
        self.log("Grid initialisation [base price : %.*f]" %
                 (self.asset_pair.asset2.decimals, float(self.base_price) /
                  10**self.asset_pair.asset2.decimals))
        self.log("Grid initialisation [base price : %.*f]" %
                 (self.asset_pair.asset2.decimals, float(self.base_price) /
                  10**(self.asset_pair.asset2.decimals +
                       (self.asset_pair.asset2.decimals -
                        self.asset_pair.asset1.decimals))))

        pw.setNode(node=self.node, chain=self.chain)
        pw.setMatcher(node=self.matcher)
        self.log("Cancelling open orders...")
        self.wallet.cancelOpenOrders(
            self.asset_pair)  # cancel all open orders on the specified pair

        self.log("Deleting order history...")
        self.wallet.deleteOrderHistory(
            self.asset_pair)  # delete order history on the specified pair

        bids = []
        for n in range(0, self.base_level):
            self.buy(n)
            bids.append(self.get_level_price(n))

        asks = []
        for n in range(self.base_level + 1, self.grid_levels):
            self.sell(n)
            asks.append(self.get_level_price(n))

        return bids, asks
    def token_price(self, bot, update):
        old_price = self.price
        price = self.__get_price()

        usd_price = format((self.btc_price * price / 100000000), '.3f')

        hashrate = 0
        for deal in self.__get_dwh_deals():
            hashrate += deal["deal"]["benchmarks"]["values"][9]

        hashrate /= 1000000  # convert to MH/s
        hashrate /= 1000  # further convert to GH/s
        hashrate = format(hashrate, '.2f')

        DICS = "Fweiconow1LnWTwCKdQzqUsbbc6xEnp1tMvFMqpm4e6F"
        myToken = pw.Asset(DICS)
        PAIR = pw.AssetPair(myToken, pw.BTC)
        NODE = "http://nodes.wavesnodes.com"
        # select the network: testnet or mainnet
        NETWORK = "mainnet"
        MATCHER = "http://matcher.wavesnodes.com"
        pw.setNode(NODE, NETWORK)
        pw.setMatcher(MATCHER)
        out = PAIR.orderbook()
        divider = 100000000

        #return int(out['bids'][0]['price'] / divider)
        DICS_price = int(out['bids'][0]['price'] / divider)

        #DICS_price = DICS_price()
        usd_DICS_price = format((self.btc_price * DICS_price / 100000000),
                                '.3f')

        msg = """\
SNM Price: {price} sats (${usd} US)\n\
Volume: {vol} BTC\n\
\n\
(Source: Binance)\n\
\n\
Deals: {deals}\n\
DICS Price: {DICS_price} sats (${DICS_usd} US)\n\
ETH-hashrate: {hashrate} GH/s""".format(price=price,
                                        usd=usd_price,
                                        vol=self.volume,
                                        deals=len(self.__get_dwh_deals()),
                                        DICS_price=DICS_price,
                                        DICS_usd=usd_DICS_price,
                                        hashrate=hashrate)

        bot.send_message(chat_id=update.message.chat_id, text=msg)
示例#3
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)

    waves_btc = pw.AssetPair(bot.amount_asset, bot.price_asset)
    while True:
        waves_balance = my_address.balance()
        bot.log("Your balance is %18d" % waves_balance)
        btc_balance = my_address.balance(bot.price_asset_id)
        bot.log("Your balance is %18d" % btc_balance)
        my_address.cancelOpenOrders(waves_btc)
        order_book = waves_btc.orderbook()
        best_bid = order_book["bids"][0]["price"]
        best_ask = order_book["asks"][0]["price"]
        spread_mean_price = ((best_bid + best_ask) // 2) * 10**(
            bot.price_asset.decimals - bot.amount_asset.decimals)
        bid_price = spread_mean_price * (1 - bot.price_step)
        ask_price = spread_mean_price * (1 + bot.price_step)
        bid_amount = int(
            (btc_balance / bid_price) * 10**pw.WAVES.decimals) - bot.order_fee

        bot.log("Best_bid: {0}, best_ask: {1}, spread mean price: {2}".format(
            best_bid, best_ask, spread_mean_price))

        if bid_amount >= bot.min_amount:
            bot.log("Post buy order with price: {0}, amount:{1}".format(
                bid_price, bid_amount))
            my_address.buy(assetPair=waves_btc,
                           amount=bid_amount,
                           price=bid_price,
                           matcherFee=bot.order_fee,
                           maxLifetime=bot.order_lifetime)

        waves_balance, btc_balance = my_address.tradableBalance(waves_btc)
        ask_amount = int(waves_balance) - bot.order_fee
        if ask_amount >= bot.min_amount:
            bot.log("Post sell order with price: {0}, ask amount: {1}".format(
                ask_price, ask_amount))
            my_address.sell(assetPair=waves_btc,
                            amount=ask_amount,
                            price=ask_price,
                            matcherFee=bot.order_fee,
                            maxLifetime=bot.order_lifetime)

        bot.log("Sleep {0} seconds...".format(bot.seconds_to_sleep))
        sleep(bot.seconds_to_sleep)
    def DICS(selfself, bot, update):
        import pywaves as pw

        DICS = "Fweiconow1LnWTwCKdQzqUsbbc6xEnp1tMvFMqpm4e6F"
        myToken = pw.Asset(DICS)
        PAIR = pw.AssetPair(myToken, pw.BTC)
        NODE = "http://nodes.wavesnodes.com"
        # select the network: testnet or mainnet
        NETWORK = "mainnet"
        MATCHER = "http://matcher.wavesnodes.com"
        pw.setNode(NODE, NETWORK)
        pw.setMatcher(MATCHER)
        out = PAIR.orderbook()
        divider = 100000000

        response = "Deal Index Coin for SONM (DICS)  https://bit.ly/2QXKCDF"
        response = response + "\n"
        response = response + "DICS price: " + str(
            int(out['bids'][0]['price'] / divider)) + " sats"
        response = response + "\n"
        response = response + "DICS/BTC exchange:  https://bit.ly/2Kg7jjZ"

        bot.send_message(chat_id=update.message.chat_id, text=response)
示例#5
0
    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
示例#6
0
import pywaves as py
import pandas as pd
import json

py.setNode('https://privatenode.blackturtle.eu', 'TN', 'L')
py.setMatcher('https://privatematcher.blackturtle.eu')
py.DEFAULT_BASE_FEE = 2000000
address = py.Address(seed='putyourseedhere')
oracle = py.Oracle(seed='putyourseedhere')

##Black liating scams
SCAM_URL = "https://raw.githubusercontent.com/BlackTurtle123/TN-community/master/scam-v2.csv"

wine_csv_url = SCAM_URL
wine_data = pd.read_csv(wine_csv_url, header=None, nrows=None)
for value in wine_data.values:
    print(value[0])
    oracle.storeData('scam_<' + value[0] + '>',
                     'boolean',
                     True,
                     minimalFee=2000000)

##Add basic data provider info

oracle.storeData('data_provider_version', 'integer', 0, minimalFee=2000000)
oracle.storeData('data_provider_name',
                 'string',
                 'Turtle Network',
                 minimalFee=2000000)
oracle.storeData('data_provider_email',
                 'string',
示例#7
0
def main():
    global my_address
    global PAIR
    global PAIR2

    #initialisation
    bot = MortyBot()

    CFG_FILE = "bot.cfg"

    if len(sys.argv) >= 2:
        CFG_FILE = sys.argv[1]

    if not os.path.isfile(CFG_FILE):
        bot.log("Missing config file")
        bot.log("Exiting.")
        exit(1)

    bot.read_config(CFG_FILE)
    pw.setMatcher(node=bot.matcher)
    pw.setDatafeed(wdf=bot.datafeed)
    
    if bot.chain == "turtlenetwork":
        pw.setNode(bot.node, bot.chain, 'L')
        PAIR = pw.AssetPair(pw.Asset(bot.amount_asset_id), pw.Asset(bot.price_asset_id))
        PAIR2 = PAIR
        if bot.price_asset_id == 'TN':
            PAIR2 = pw.AssetPair(pw.Asset(bot.amount_asset_id), pw.Asset('WAVES'))
        elif bot.amount_asset_id == 'TN':
            PAIR2 = pw.AssetPair(pw.Asset('WAVES'), pw.Asset(bot.price_asset_id))
    else:
        pw.setNode(bot.node, bot.chain)
        PAIR = pw.AssetPair(pw.Asset(bot.amount_asset_id), pw.Asset(bot.price_asset_id))
        PAIR2 = PAIR
        if bot.price_asset_id == 'WAVES':
            PAIR2 = pw.AssetPair(pw.Asset(bot.amount_asset_id), pw.WAVES)
        elif bot.amount_asset_id == 'WAVES':
            PAIR2 = pw.AssetPair(pw.WAVES, pw.Asset(bot.price_asset_id))
    
    my_address = pw.Address(privateKey=bot.private_key)

    bot.log("-" * 80)
    bot.log("          Address : {0}".format(my_address.address))
    bot.log("  Amount Asset ID : {0} ({1})".format(bot.amount_asset_id, PAIR2.asset1.name))
    bot.log("   Price Asset ID : {0} ({1})".format(bot.price_asset_id, PAIR2.asset2.name))
    bot.log("Strategy selected : {0}".format(bot.strategy.upper()))
    bot.log("-" * 80)
    bot.log("")

    # cancel all open orders on the specified pair
    bot.log(">> Cancelling open orders...")
    my_address.cancelOpenOrders(PAIR)

    #grid trading
    if bot.strategy.lower() == "grid" or bot.strategy.lower() == "moving_grid":
        go_grid(bot)
    elif bot.strategy.lower() == "scalp":
        go_scalp(bot)
    elif bot.strategy.lower() == "uptrend":
        bot.seconds_to_sleep = 1
        go_uptrend(bot)
示例#8
0
"""
import urllib2
#import urllib
import json
import pywaves as pw
import time

token_ID = 'xxxxxxx'  # nova token
presale_wallet_addr = ''
privkey = ''
assetDetail = json.load(
    urllib2.urlopen('http://wavesnode.io:6869/assets/details/' + token_ID))
token_decimal = 10**assetDetail['decimals']
# set Matcher node to use
#pw.setMatcher(node=u'https://matcher.wavesplatform.com/matcher')
pw.setMatcher(node=u'https://nodes.wavesnodes.com')
myAddress = pw.Address(privateKey=privkey)

# post a buy order, test successful
BTC = pw.Asset('8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS')
ETH = pw.Asset('474jTeYx2r2Va35794tCScAXWJG9hU2HcgxzMowaZUnu')
token_decimal = ETH.decimals
ETH_BTC = pw.AssetPair(ETH, BTC)
t0 = time.time()
UnitPrice = 0.0505
AmountAssetToBuy = 0.001
myBuyOrder = myAddress.buy(assetPair=ETH_BTC,
                           amount=AmountAssetToBuy *
                           10**ETH_BTC.asset1.decimals,
                           price=UnitPrice * 10**ETH_BTC.asset2.decimals)
t1 = time.time()
import random
import string
import time

import pywaves as py
import unittest

py.setNode('https://apitnetworktest.blackturtle.eu', 'testnetTN', 'l')
py.setMatcher('https://tntestnetmatcher.blackturtle.eu')
py.DEFAULT_CURRENCY = 'TN'

address = py.Address(seed='input a seed here')
address2 = py.Address(
    seed=
    "seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed seed"
)

ASSET = "2GRJaVYhhQPKVoWQFyJfTfx3eB5DD7CPdG7ZYx3Cs6Mk"
PAIR = py.AssetPair(py.Asset(ASSET), py.Asset("TN"))
py.THROW_EXCEPTION_ON_ERROR = True


class TNTest(unittest.TestCase):
    currentResult = None  # holds last result object passed to run method

    @classmethod
    def setResult(cls, amount, errors, failures, skipped):
        cls.amount, cls.errors, cls.failures, cls.skipped = \
            amount, errors, failures, skipped

    def tearDown(self):
示例#10
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)
示例#11
0
# coding: utf-8

# In[ ]:

import pywaves as pw

WavesWalletID = "XXX-Finamatrix_Wallet_ID-XXX"
# Set Matcher node to use
pw.setMatcher(node = 'http://127.0.0.1:6886')

# set an address with a public key
WavesAddress = pw.Address(privateKey = 'CsBpQpNE3Z1THNMS9vJPaXqYwN9Hgmhd9AsAPrM3tiuJ')

# Asset names can be found at http://dev.pywaves.org/assets/
WavesAssetsIDs = { 'BTC' : '8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS',
                   'USD' : '4Aw6NnmkAELqK6FqQVj5nYB5PPt39TSccpFhgFKNYVAQ',
                   'FIX' : 'GS5RfWDS8ytVnxqr7M2pnqeFuu7BpSwGnADTcw23FvbZ'}

def FinamatrixBlackBox():
    ########################
    #     Confidential     #
    ########################
    ######Examplar Variable Setting######
    TokenPairNames = ["BTC","USD"]
    OrderType="long"
    OrderAmount=100000000
    Exchange="Waves"
    return(TokenPairNames, OrderType, OrderAmount, Exchange)

# Non-stop while loop: Whenever trading signal is triggred, execute trades 
示例#12
0
import pywaves as pw
import waveflow_handler as wf
from time import sleep

account = pw.Address(privateKey="27uhZoT9ASj6XZAn7Fidjws5yijyxWsMRpb3hPMQhNDL"
                     )  # address for a public use :)
pw.setMatcher(pw.MATCHER)
WVS = 10**8


def wf_exchange(amount):
    """ changes <amount> WAVES or <all_available> tokenB on WaveFlow.xyz """
    amount = int(amount * WVS)

    tx = account.invokeScript("3PNtfqFrJu6Svp7rKYtb3VmZu8hseiownoo",
                              "exchanger", [{
                                  "type": "integer",
                                  "value": 0
                              }], [{
                                  "assetId": None,
                                  "amount": amount
                              } if amount > 0 else {
                                  "assetId": wf.tokenB,
                                  "amount": account.balance(wf.tokenB)
                              }])

    for x in range(150):
        sleep(0.1)
        if "error" not in pw.tx(tx["id"]):
            print(
                "WaveFlow exchange completed. Payment: {amount} {assetId}. Transaction ID: {txid}"
示例#13
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 = ''


def getprices():
示例#14
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)