Exemple #1
0
def run_buy_sell_analyze(cfg, yearspan):

    min_trades = int(cfg['analyze_min_trades'])

    holds_cfg = cfg['hold_times_list'].strip()
    budget_cfg = cfg['budget_list'].strip()

    holds_lst = holds_cfg.split(",")
    budget_lst = budget_cfg.split(",")

    low_price_cutoff = float(cfg['low_price_cutoff'])

    for budget in budget_lst:
        b = budget.strip()

        for hold in holds_lst:
            h = hold.strip()

            info_str = f"Running buy-sell with {h} days and {b} dollars..."
            logging.info(info_str)

            buy_sell_v3(int(b), 0, int(h), float(low_price_cutoff), yearspan)

            info_str = f"Running analyze with {h} days and {b} dollars..."
            logging.info(info_str)

            analyze(h, b, yearspan, min_trades)
Exemple #2
0
def run_analysis():

    input_string = input(
        'input: year-span hold_days budget_dollars min_trades =>  ')
    logging.info("Running analysis...")
    args = input_string.split()
    yearspan = args[0]
    hold_days = args[1]
    budget_dollars = args[2]
    min_trades = int(args[3])
    analyze(hold_days, budget_dollars, yearspan, min_trades)
Exemple #3
0
def main(args):
    mbr, gpt = lib.analyze(args)
    while True:
        print('\n\n')
        Help()
        cmd = input('Command: ')
        cmd = cmd.split()
        if cmd[0] == 'q':
            break
        if cmd[0] == 'pm':
            print_mbr(mbr)
        if cmd[0] == 'pg':
            #print_gpt
            pass
        if cmd[0] == 'pmps':
            print_mbr_partitions(mbr)
        if cmd[0] == 'pmp':
            print_mbr_partition(mbr, int(cmd[1]))
        if cmd[0] == 'pg':
            print_gpt(gpt)
        if cmd[0] == 'pgp':
            print_gpt_partition(gpt, int(cmd[1]))
        if cmd[0] == 'pgps':
            print_gpt_partitions(gpt)
        if cmd[0] == 'dm':
            mbr.dump_partition(int(cmd[1]) - 1)
        if cmd[0] == 'dms':
            mbr.dump_partitions()
        if cmd[0] == 'dg':
            gpt.dump_partition(int(cmd[1]) - 1)
        if cmd[0] == 'dgs':
            gpt.dump_partitions()
from lib import analyze
from functools import partial


def parse_time(line):
    last_line = float(line.split(" ")[1].split("s")[0].split("m")[1])
    return last_line, str(last_line), "seconds"


tests = [(parse_time, 'real time')]

import json
print(json.dumps(analyze(tests, 'webtorrent')))
from lib import analyze
from functools import partial


def json_response(line):
    last_line = float(
        line.split("\"throughput\"")[1].split(",")[0].split(" ")[-1])
    return 1 / last_line * 1000, str(last_line), "requests/second"


def text_response(line):
    l = float(line.split("\"throughput\"")[2].split(",")[0].split(" ")[-1])
    return 1 / l * 1000, str(l), "requests/second"


tests = [(json_response, 'response json'), (text_response, 'response text')]

import json

print(json.dumps(analyze(tests, 'restify')))
Exemple #6
0
if args.gt:
    min = float(args.gt)
    all_positive = list(filter(lambda x: x[1] > min, all_positive))

if args.list:

    print("\n".join(sorted([x[0] for x in all_positive])))
    sys.exit(0)

all_history = lib.tradeHistory()

if args.json:
    list = []
    for k,v in all_history.items():

        row = lib.analyze(v, currency=k, brief=True, sort='date')
        row['exchange'] = k
        cur = k[4:]
        if cur in cur_balances:
            row['bal'] = cur_balances[cur]

        list.append(row)

    print(json.dumps(list))
    sys.exit(0)


market_exit_list = set([ k[4:] for k in all_history.keys() ]) - set([x[0] for x in all_positive])
all_positive = [(v, 0, 0) for v in market_exit_list] + all_positive
in_order = sorted(all_positive, key=itemgetter(1))
btc_ttl = 0
def f(line, idx):
    l = []
    ll = line.split("•")
    s = ll[idx]
    z = s.split('x')
    if len(z) >= 2:
        l.append(float(''.join(s.split('x')[-1].split("ops")[0].split(','))))
    return (1 / l[0]) * 1000, str(l[0]), "operations/second"


def g(i, name):
    return (partial(f, idx=i), name)


tests = [g(2, "frame unmasked (64 B)")]
t = [
    "route_with_no_verb", "route_with_GET_verb", "route_with_POST_verb",
    "route_with_dynamic_param", "route_with_wildcard", "route_with_rege",
    "respond_with_string", "respond_with_json", "reflect_one_param",
    "reflect_all_params", "route_with_no_verb", "route_with_GET_verb",
    "route_with_POST_verb", "route_with_dynamic_param", "route_with_wildcard",
    "route_with_rege", "respond_with_string", "respond_with_json",
    "reflect_one_param", "reflect_all_params", "route_with_no_verb",
    "route_with_GET_verb", "route_with_POST_verb", "route_with_dynamic_param",
    "route_with_wildcard", "route_with_rege", "respond_with_string",
    "respond_with_json", "reflect_one_param", "reflect_all_params"
]
tests = [g(i + 1, v) for i, v in enumerate(t)]
import json
print(json.dumps(analyze(tests, 'sails')))
        positive_balances = {k: v['cur'] for k, v in cur_balances.items()}

        for k, v in all_trades.items():
            all_trades[k] = {'full': v, 'last': lib.ignorePriorExits(v)}

    all_prices = lib.returnTicker(forceUpdate=True)
    last_ticker = time.strftime("%Y-%m-%d %H:%M:%S")
    if not all_prices_last:
        all_prices_last = [all_prices] * 3
        all_prices_last_list = [all_prices]

    rows = []

    for k, valueMap in all_trades.items():
        v = valueMap['last']
        statsFull = lib.analyze(valueMap['full'], currency=k, brief=True)
        stats = lib.analyze(valueMap['last'], currency=k, brief=True)
        btc_ttl = stats['buyBtc']
        btc_ttl_sell = stats['sellBtc']

        cur_ttl = stats['buyCur']
        if k not in all_prices:
            continue

        price = float(all_prices[k]['last'])
        if k[:3] == 'ETH' or cur_ttl == 0:
            continue

        my_price = btc_ttl / cur_ttl
        my_ratio = min(price / my_price, price / statsFull['buyAvg'])
        cur = k[4:]
Exemple #9
0
os.system('clear')
while True:
    if index == 0:
        if ctr % cycles_before_data_update == 0:
            if not lib.is_fake:
                print("                                    ")
                print("   ... refreshing data source ...   ")
                print("                                    ")
            ticker = lib.returnTicker(forceUpdate = True)
            trades = lib.tradeHistory(forceUpdate = True)
            all_bal = lib.returnCompleteBalances()

            if not lib.is_fake:
                os.system('clear')
            print("\033[0;0H")
            stats = lib.analyze(lib.tradeHistory('BTC_STRAT'), brief = True)
            anal.write("{} {}\n".format(stats['avgBuy'], stats['btc']))
        ctr += 1

    currency = currency_list[index]
    index = (index + 1) % mod 

    did_act = False
    if currency in next_act:
        if lib.unixtime() > next_act[currency]:
            del(next_act[currency])
        else:
            running.please_skip(currency, margin_buy=margin_buy, margin_sell=margin_sell, extra=int(next_act[currency] - lib.unixtime()))

    if not currency in next_act:
        #try:
from lib import analyze
from functools import partial


def mw(line):
    last_line = float(line.split(" ")[23])
    return 1 / last_line, str(last_line), "request/second"


tests = [(mw, '100 middleware')]

import json
print(json.dumps(analyze(tests, 'KOA')))
from lib import analyze
from functools import partial


def mw(line, idx):
    last_line = line.split("ops/s")
    l = float(last_line[idx].split('(')[-1].split(')')[0])
    #print(last_line)
    return (1 / l) * 1000, str(l), "operations/second"


def g(idx, name):
    return (partial(mw, idx=idx), name)


#tests = [
#	g(0,'100 middleware'),
#	g(1,'coll.geti()')
#	]
s = 'load(insert),coll.get(), coll.by(),NON-INDEXED coll.find,NON-INDEXED chained find,NON INDEXED loki dynamic view first find,NONINDEXED loki dynamic view subsequent finds,BINARY INDEX coll.find(), BINARY INDEXED chained find, BINARY INDEX loki dynamic view fisrt find, BINARY INDEX loki dynamic view subsequent find, UNINDEXED load(individual), UNINDEXED load (batch),INDEXED LAZY load(individual), INDEXED LAZY load(batch), INDEXED ADAPTIVE load(individual), INDEXED ADAPTIVE load(batch), UNINDEXED coll.find, UNINDEXED interlaced inserts + coll.find, UNINDEXED removes and coll.find, UNINDEXED interlaced updates and coll.find,LAZY coll.find, LAZYinsert + find, LAZY remove + find, LAZY update + find, ADAPTIVE coll.find, ADAPTIVE insert + find, ADAPTIVE remove + find, ADAPTIVE update + find'.split(
    ',')
tests = [g(idx, val) for idx, val in enumerate(s)]
import json
print(json.dumps(analyze(tests, 'lokijs')))
from lib import analyze
from functools import partial
def mw(line):
	last_line = float(line.split(" ")[23])
	return 1/ last_line, str(last_line),  "requests/second"


tests = [(mw, '100 middleware')]
		
import json	
print(json.dumps(analyze(tests, 'EXPRESS'))) 
if len(sys.argv) > 2:
    margin = float(sys.argv[2])

if len(sys.argv) > 3:
    max_btc = float(sys.argv[3])
    if max_btc == 0:
        max_btc = False

rows, cols = [int(x) for x in os.popen('stty size', 'r').read().split()]
rows -= 11
cols -= 12
#rows = 80
#cols = 150
data = lib.tradeHistory(currency)
anal = lib.analyze(data, currency=cur)
balanceMap = lib.returnCompleteBalances()
ticker = lib.returnTicker()

buyList = anal['buyList']
sellList = anal['sellList']

last = float(ticker[currency]['last'])

buy_low = buyList[0]['rate']
buy_high = buyList[-1]['rate']

if len(sellList) > 0:
    sell_low = sellList[0]['rate']
    sell_high = sellList[-1]['rate']
else:
#!/usr/bin/python3
import lib
import sys
from pprint import pprint

all_history = lib.tradeHistory()
balanceMap = lib.returnCompleteBalances()

for k,v in all_history.items():
    print(k)

    #v = lib.analyze(v, currency=k, brief=True, sort='date')
    v = lib.analyze(v, currency=k, brief=True, sort='date')

    cur = k[4:]
    if cur in balanceMap:
        v['bal'] = balanceMap[cur]
    pprint(v)
Exemple #15
0
                                       rate).groups()
    else:
        word, oper, amount = '', '', ''
    rate = None

    if word == 'ask':
        rate = ask

    if word == 'bid':
        rate = bid

    if word == 'last':
        rate = last

    if word in ['break', 'profit', 'lowest', 'highest', 'high', 'low']:
        hist = lib.analyze(lib.tradeHistory(exchange), currency=exchange)

        if word == 'lowest' or word == 'low':
            if action == 'buy':
                rate = hist['lowestBuy']

            if action == 'sell':
                rate = bid

        elif word == 'highest' or word == 'high':
            if action == 'buy':
                rate = ask

            if action == 'sell':
                rate = hist['highestSell']
def should_act(exchange, margin_buy, margin_sell, please_skip=False, extra=""):
    currency = exchange[4:]
    pList = lib.returnTicker(forceCache=True)
    data = lib.tradeHistory(exchange, forceCache=True)
    balanceMap = lib.returnCompleteBalances(forceCache=True)

    strike = find_next(data)
    if strike:
        sell_price = strike * (1 + margin_sell)
        buy_price = strike * (1 - margin_buy)
    # if we can't find anything then we can go off our averages
    else:
        analyzed = lib.analyze(data)
        sortlist = sorted(data, key=lambda x: x['rate'])
        sell_price = analyzed['lowestBuy'] * (1 + margin_sell)
        buy_price = analyzed['lowestBuy'] * (1 - margin_buy)

    order = False

    market_low = pList[exchange]['highestBid']
    market_high = pList[exchange]['lowestAsk']
    buy_rate = pList[exchange]['highestBid'] + 0.00000001
    sell_rate = pList[exchange]['lowestAsk'] - 0.00000001

    graph = graph_make(buy_price, market_low, market_high, sell_price,
                       margin_buy, margin_sell)
    market_graphic = "{:.8f} {}{:.8f}{:.8f} {}{:.8f} {}".format(
        buy_price, ' ' if buy_price < buy_rate else '>', buy_rate, sell_rate,
        ' ' if sell_price > sell_rate else '>', sell_price, graph)

    if please_skip:
        lib.plog("{:5} {:6} {} {:4}".format(currency, '*SKIP*', market_graphic,
                                            extra))
        return False

    if buy_rate < buy_price:

        p = lib.connect()
        amount_to_trade = unit / buy_rate
        order = p.buy(exchange, buy_rate, amount_to_trade)
        rate = buy_rate
        trade_type = 'buy'

    elif sell_rate > sell_price:

        p = lib.connect()
        amount_to_trade = unit / sell_rate
        if amount_to_trade < balanceMap[currency]['available']:
            #try:
            order = p.sell(exchange, sell_rate, amount_to_trade)
            rate = sell_rate
            trade_type = 'sell'
            #except:
            #    lib.plog("{:9} Failed sell {:.8f} @ {:.8f} (bal: {:.8f})".format(exchange, amount_to_trade, buy_price, balanceMap[currency]['available']))

    else:
        lib.plog("{:5} {:6} {} {:4}".format(currency, "", market_graphic,
                                            extra))
        return False

    if order:
        lib.showTrade(order,
                      exchange,
                      source='bot',
                      trade_type=trade_type,
                      rate=rate,
                      amount=amount_to_trade,
                      doPrint=False)
        lib.plog("{:5} {:6} {}".format(currency, trade_type, market_graphic))
        return True
        l.append(float(''.join(s.split('x')[-1].split(','))))
    return (1 / l[0]) * 1000, str(l[0]), "operations/second"


def g(i, name):
    return (partial(f, idx=i - 1), name)


tests = [
    g(1, "frame unmasked (64 B)"),
    g(2, "frame masked (64 B)"),
    g(3, "frame unmasked (16 KiB)"),
    g(4, "frame masked (16 KiB)"),
    g(5, "frame unmasked (64 KiB)"),
    g(6, "frame masked (16 KiB)"),
    g(7, "frame unmasked (200 KiB)"),
    g(8, "frame masked (200 KiB)"),
    g(9, "frame unmasked (1 MiB)"),
    g(10, "frame masked (1 MiB)"),
    g(11, "ping frame (5 bytes payload)"),
    g(12, "ping frame (no payload)"),
    g(13, "close frame (no payload)"),
    g(14, "text frame (20 bytes payload)"),
    g(15, "binary frame (125 bytes payload)"),
    g(16, "binary frame (65535 bytes payload)"),
    g(17, "binary frame (200 KiB payload)"),
    g(18, "binary frame (1 MiB payload)"),
]
import json
print(json.dumps(analyze(tests, 'ws')))
from lib import analyze
def get_average(line):
	last_line = line.split("summary =")[-1].split("Avg:")[0].split("=")[1].split("/s")[0]
	return (1/float(last_line)) * 1000, last_line , "requests/second" 


tests = [(get_average, 'ACME_AIR_REQS_SECOND_AFTER_10_MINUTES')]
		
import json	
print(json.dumps(analyze(tests, 'ACME_AIR')))
Exemple #19
0
from lib import analyze
from functools import partial
def parse_time(line):
	last_line = float(line.split(" ")[1].split("s")[0].split("m")[1])
	return last_line,str(last_line) , "seconds"

tests = [(parse_time, 'real time')]
		
import json	
print(json.dumps(analyze(tests, 'three'))) 
Exemple #20
0
            last = 0

        lib.bprint(" {:4} {:.8f} {:.8f}".format(
            what, sum([float(i['total']) for i in subset]), last))
        for i in subset:
            i['rate'] = float(i['rate'])
            color = '0'
            if what == 'sell':
                if i['rate'] < anal['buyAvg']:
                    color = '91'
                elif i['rate'] < anal['break']:
                    color = '35'
                elif i['rate'] > max(anal['break'], anal['buyAvg'],
                                     anal['sellAvg']):
                    color = '32'

            lib.bprint("\x1b[{}m  {} {} {:.8f} {}\x1b[0m".format(
                color, i['orderNumber'], i['date'], i['rate'], i['total']))


plist = lib.returnOpenOrders(expiry)
history = lib.tradeHistory()

for k, v in plist.items():
    if ((currency and currency == k) or not currency) and len(v):
        print(k)
        show('buy', v)
        if k in history:
            anal = lib.analyze(history[k], k)
            show('sell', v, anal)