Esempio n. 1
0
 def Balance(self):
     qString = "nonce=" + str(self.nonce)
     sign = self.ComputeHash(qString)
     url = self.Url + "Account/Balance"
     response = self.Query(qString, url, sign)
     _json = json.loads(response.decode("utf-8"))
     return Balance(_json['BalanceNIS'], _json['BalanceLTC'], _json['BalanceBTC'])
Esempio n. 2
0
def get_balances():

    #### Fetch free balances from exchanges and enter them into Balance objects. Should only run once during setup to prevent duplicate entries. Does not include balances currently allocated by exchanges for pending transactions.

    balancelist = []

    for id in [*Exchanges]:

        balances = Exchanges[id].fetch_balance()
        for b in [*balances['free']]:
            amount = balances['free'][b]
            exchange = Exchanges[id]
            currency = Currencies[b]
            balancelist.append(Balance.Balance(amount, exchange, currency))

    return balancelist
Esempio n. 3
0
 def __init__(self, initScript=None):
     """
     create the ports and init the balance
     """
     UnitOperations.UnitOperation.__init__(self, initScript)
     self.portOut0 = self.CreatePort(OUT | MAT, OUT_PORT + str(0))
     self.portOut1 = self.CreatePort(OUT | MAT, OUT_PORT + str(1))
     self.portIn = self.CreatePort(IN | MAT, IN_PORT)
     self._balance = Balance.Balance(Balance.MOLE_BALANCE
                                     | Balance.ENERGY_BALANCE)
     self._balance.AddInput(self.portIn)
     self._balance.AddOutput(self.portOut0)
     self._balance.AddOutput(self.portOut1)
     self.splits = SplitList(
         self)  # list to hold split fraction signal ports
     self.borrowedSplits = None  # used by containing op to be notified of split list changes
Esempio n. 4
0
    def __init__(self, initScript = None):
        """
        create the ports and init the balance
        """
        super(Valve, self).__init__(initScript)
        
        self.outPort = self.CreatePort(OUT|MAT, OUT_PORT)
        self.outPort.SetLocked(True)
        
        self.inPort = self.CreatePort(IN|MAT, IN_PORT)
        self.inPort.SetLocked(True)

        self.dpPort = self.CreatePort(SIG, DELTAP_PORT)
        self.dpPort.SetSignalType(DELTAP_VAR)
        self.dpPort.SetLocked(True)
        
        self._balance = Balance.Balance(Balance.MOLE_BALANCE|Balance.ENERGY_BALANCE)
        self._balance.AddInput(self.inPort)
        self._balance.AddOutput(self.outPort)
Esempio n. 5
0
    def UpdatePortsOut(self):
        """Update the amount and names of the ports out"""
        portNames = self.GetPortNames(MAT | OUT)
        nuLPorts = self.nuLPorts
        nuSPorts = self.nuSPorts

        #Get how many phases of each we actually have
        nuLPh = self.NumberLiqPhases()
        nuSPh = self.NumberSolidPhases()

        #Create or delete the liquid ports
        for i in range(nuLPorts, nuLPh, -1):
            p = self.GetPort(L_PORT + str(i - 1))
            p.SetLocked(False)
            self.DeletePort(p)
        for i in range(nuLPorts, nuLPh):
            p = self.CreatePort(MAT | OUT, L_PORT + str(i))
            p.SetLocked(True)

        #Create or delete the solid ports
        for i in range(nuSPorts, nuSPh, -1):
            p = self.GetPort(S_PORT + str(i - 1))
            p.SetLocked(False)
            self.DeletePort(p)
        for i in range(nuSPorts, nuSPh):
            p = self.CreatePort(MAT | OUT, S_PORT + str(i))
            p.SetLocked(True)

        #Update the port counts
        self.nuLPorts = nuLPh
        self.nuSPorts = nuSPh

        #Update the balance
        self.balance = Balance.Balance(Balance.MOLE_BALANCE
                                       | Balance.ENERGY_BALANCE)
        self.balance.AddInput(self.ports_mat_IN[IN_PORT])
        for port in self.GetPorts(MAT | OUT):
            self.balance.AddOutput(port)
Esempio n. 6
0
    def __init__(self, initScript=None):
        """
        Just do balance and conserve entropy
        isCompressor determines energy flow direction
        """
        super(IdealPump, self).__init__(initScript)

        self.balance = Balance.Balance(Balance.MOLE_BALANCE
                                       | Balance.ENERGY_BALANCE)
        self.lastPIn = None
        self.lastPOut = None

        inPort = self.CreatePort(MAT | IN, IN_PORT)
        outPort = self.CreatePort(MAT | OUT, OUT_PORT)

        dpPort = self.CreatePort(SIG, DELTAP_PORT)
        dpPort.SetSignalType(DELTAP_VAR)

        qPort = self.CreatePort(ENE | IN, IN_PORT + 'Q')
        self.balance.AddInput((inPort, qPort))
        self.balance.AddOutput(outPort)

        self.SetParameterValue(ISENTROPIC_PAR, 1)
Esempio n. 7
0
File: arb2.py Progetto: mikem5/arb2
    def __init__(self, m, numCur):

        # numCur is the amount of currencies we are
        # going to be tracking across all the exchanges
        # eg, ltc/btc, ftc/btc would be 2 etc.

        # keep track of running time
        self.__started = time.time()

        # an array of market objects
        self.markets = m

        # this is the default order for currency
        self.currencies = ["ltc", "usd", "lsd"]

        # Use the pair object to creat an array of the
        # best currency markets
        # we may need to put the market name/index number
        # in the Pair object so that we can later match

        # The form that the pair objects in ask/bid will take
        # inside this arbitrage object is as follows, and
        # note: IS DIFFERENT FROM DEFAULT PAIR.

        # [price, quantity, index, marketbalance, marketidx]
        self.pairs = []
        self.trades = []
        for x in range(0, numCur):
            self.pairs.append(Pair('arb', x, 50, [dq, dq, dq], 0))
            self.trades.append(Trades('arb', x, 50, 0))

        # Variables to keep track of overall profit / trade
        # volume....This will need to be corrected for multiple
        # currency pairs as the price/volume is drasticlly different
        self.tprofit = D('0')
        self.ttrades = []

        for x in range(0, numCur):
            self.ttrades.append(D('0'))

        # Strings for the logger
        self.last_arb = ""
        self.last_best = ""
        self.last_string = ""

        # This is for our draw screen function
        self.screen_update = time.time()

        # This sets up the balance sheets for all our currencies
        # we use this to tell if we are way off the mark and need
        # to buy/sell a currency to bring us back to a flat line
        self.market_balances = Balance()

        for m in self.markets:
            for k, v in m.balances.funds.items():
                self.market_balances.funds[k] += v

        self.__initial_market_balances = copy.deepcopy(self.market_balances)

        # Write out our initial balances to our log file
        self.logger(self.stringFormat(0, 0, 0, 2))

        # This lets our main loop know if we entered an arb state
        # so that we can run checkbooks/etc
        self.entered_arb = 0

        # This is a counter, to check our books a couple times
        # then stop so we don't just check all the time as
        # really, unless there is a change in 3-5 minutes
        # there shouldnt be any further change
        self.arb_counter = 0

        #
        # This is the discrepancy from the base balance we
        # are off in each market - should use to adjust order
        # trades in the future
        #
        # This is either + or - from the base
        # + means we should sell more (or buy less)
        # - means we should buy more (or sell less)
        #
        self.discrep = {'usd': D('0'), 'ltc': D('0'), 'btc': D('0')}
Esempio n. 8
0
    def __init__(self,
                 cur,
                 url,
                 rang=50,
                 f=1.002,
                 thrp=.02,
                 thrm=0,
                 mtq=[0, 0]):

        # An array of currency names
        self.curPairs = cur

        # The url is an ARRAY [] where 0 is the first bit
        # then we stop and continue after the curPair would be
        # added so that we have [0] + curPair + [1] for the
        # complete url. but our defURL will only have [0] and [1]
        self.defURL = url

        # The range or orderbook depth default 50
        self.range = rang

        # Default fee is .2%
        # we write as 1.002
        # This is a decimal from this point on
        self.fee = D(str(f))

        # throttles should be deleted

        # Default throttle is 0
        # this is time between calls
        self.throttle = thrm

        # we set this so that we can keep track
        self.throttle_updated = time.time()

        # Main orderbook pairs initialization process
        self.pairs = []
        for i, x in enumerate(self.curPairs):
            if x != 0:
                # set the inverted bit
                if self.pairKey(x) == 'usd':
                    self.pairs.append(
                        Pair(self.mname, x, self.range, mtq[i], thrp, inv=1)
                    )  # we make the currency pairs, thrp is the default pair throttle
                # non inverted, "normal"
                else:
                    self.pairs.append(
                        Pair(self.mname, x, self.range, mtq[i], thrp, inv=0)
                    )  # we make the currency pairs, thrp is the default pair throttle
            else:
                self.pairs.append(x)

        # same process for trades history
        self.trades = []
        for x in self.curPairs:
            if x != 0:
                self.trades.append(
                    Trades(self.mname, x, self.range, thrp)
                )  # we make the currency pairs, thrp is the default pair throttle

                # now we open the trade file and get the last trade
                try:
                    line = subprocess.check_output(
                        ['tail', '-1', 'logs/trades/' + self.mname + '/' + x])
                    # now parse the trade
                    y = line.split(',')
                    self.trades[-1].last_trade = [
                        D(str(y[0])),
                        D(str(y[1])),
                        int(str(y[2])),
                        int(str(y[3])), 'bid',
                        str(time.time())
                    ]
                except:
                    pass

            else:
                self.trades.append(x)

        # This is the balance sheet object
        self.balances = Balance()

        # this is the order array for an open "market maker" order
        self.open_order_mm = OrderList()

        # This indicates if the market is in some type of error
        # so we halt trading on it
        self.hold_trade = 0

        # This variable indicates that we interacted in a trade
        # so we should call the cancelorders/setBalance
        # to update our book.
        self.need_update = 0

        # Market was last alive at this point
        self.last_alive = time.time()

        # A way to count number of trades executed on this market
        self.totaltrades = 0

        # Last quantity is a way for threading execution to get
        # the last traded amount since python threads cant
        # return the value that well.
        self.last_quantity_traded = D('-1')

        # The initial nonce is loaded from a saved file. This SHOULD
        # be quite close to the last one, but just in case we
        # will increment by 100 at the start to make sure we are not off
        # this could change later.
        # nonces are stored in nonce/

        filename = "nonce/" + self.mname
        f = open(filename, 'r')

        self.initial_nonce = int(f.readline()) + 100
        self.current_nonce = 0

        f.close()

        self.writeNonce()

        # Function which gets initial balances for this market
        self.setBalance(initial=1)

        # skew for order placement, and order cancel
        self.skew_order = 10
        self.skew_cancel = 10

        # for competing on market making orders
        self.compete_price = []
        for x in self.curPairs:
            self.compete_price.append(D('0'))