Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - litepresence

Pages: 1 ... 3 4 5 6 7 8 9 [10]
136
that just went over my head

rewind pls


what is Bitshares() vs Notify() and which did I use?

137
Code: [Select]
    if command == 'account_value':

        # returns estimated account value in BTS, BTC, USD
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        btc_value = 0
        for asset, amount in balances.items():
            market_pair = 'BTC:' + asset
            market = Market(market_pair)
            price = float(market.ticker()['latest'])
            value = amount/price
            if asset != 'USD':
                price = 1/price
            print (('%.4f' % value), 'BTC', ('%.2f' % amount),
                    asset, '@', ('%.8f' % price))
            btc_value+=value

        market_pair = 'BTC:USD'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        usd_value = btc_value*price
        market_pair = 'BTC:BTS'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        bts_value = btc_value*price
       
        print(  ('%.2f' % bts_value), 'BTS',
                ('%.4f' % btc_value), 'BTC',
                ('%.2f' % usd_value), 'USD')
        return bts_value, btc_value, usd_value

138
v1 : https://pastebin.com/9zAbqx2A

updated Mar6/2018

v2 https://pastebin.com/pBzi8a4N

 - improved cancel all
 - block number / latency
 - account value in BTS, BTC, USD terms



license: WFTPLv2 http://www.wtfpl.net/about/
Code: [Select]
# python3.4
 
' Wrapper for Common PyBitshares DEX Algo Trading API Calls '
 
# data is in easy to quant float / list of floats / dict of floats format
 
    # buy / sell / cancel
    # outstanding orders
    # account balance for pair
    # complete account balance
    # orderbook
    # last_price
    # account value
    # latency
 
# if no price / amount specified executes market order buy/sell
# if no expiration specified default is 3.2 years
# cancels all outstanding orders in market
 
' BTS: litepresence1 '
 
# http://docs.pybitshares.com
from bitshares.market import Market
from bitshares.account import Account
from bitshares import BitShares
from bitshares.blockchain import Blockchain
import time
 
 
ACCOUNT = Account("")
PASS_PHRASE = ""
 
BitCURRENCY = 'OPEN.BTC'
BitASSET = 'BTS'
BitPAIR = BitASSET + ":" + BitCURRENCY
MARKET = Market(BitPAIR, bitshares_instance=BitShares(nodes()))
CHAIN = Blockchain(bitshares_instance=BitShares(
    nodes()), mode='head')
 
SATOSHI = 0.00000001
ANTISAT = 1 / SATOSHI
 
def nodes():  # Public Nodes List
 
    nodes = [
        'wss://b.mrx.im/ws',
        'wss://bitshares.openledger.info/ws',
        'wss://bitshares.dacplay.org:8089/ws',
        'wss://dele-puppy.com/ws',
        'wss://eu.openledger.info/ws',
        'wss://bit.btsabc.org/ws',
        'wss://eu.openledger.info/ws',
        'wss://dexnode.net/ws',
        'wss://ws.gdex.top',
        'wss://kc-us-dex.xeldal.com/ws',
        'wss://bts.ai.la/ws',
        'wss://btsza.co.za:8091/ws',
        'wss://japan.bitshares.apasia.tech/ws',
        'wss://api.bts.blckchnd.com',
        'wss://bitshares-api.wancloud.io/ws',
        'wss://eu.nodes.bitshares.ws',
        'wss://bitshares.crypto.fans/ws',
        'wss://dex.rnglab.org',
        'wss://bitshares.openledger.info/ws',
        'wss://ws.winex.pro',
        'wss://sg.nodes.bitshares.ws',
        'wss://us.nodes.bitshares.ws',
        'wss://bitshares.apasia.tech/ws',
        'wss://openledger.hk/ws',
        'wss://bitshares.dacplay.org/ws',
    ]
    return nodes
 
def dex(  # Public AND Private API Bitshares
        command, amount=ANTISAT, price=None,
        depth=1, expiration=ANTISAT):
 
    MARKET.bitshares.wallet.unlock(PASS_PHRASE)
    ACCOUNT.refresh()
 
    if command == 'buy':
 
        # buy relentlessly until satisfied or currency exhausted
        print(('Bitshares API', command))
        if price is None:
            price = ANTISAT
        print(('buying', amount, 'at', price))
        attempt = 1
        currency = float(ACCOUNT.balance(BitCURRENCY))
        if amount > 0.998 * currency * price:
            amount = 0.998 * currency * price
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.buy(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("buy attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('buy aborted')
                        return
                    pass
        else:
            print('no currency to buy')
 
    if command == 'sell':
 
        # sell relentlessly until satisfied or assets exhausted
        expiration = 86400 * 7
        print(('Bitshares API', command))
        if price is None:
            price = SATOSHI
        print(('selling', amount, 'at', price))
        attempt = 1
        assets = float(ACCOUNT.balance(BitASSET))
        if amount > 0.998 * assets:
            amount = 0.998 * assets
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.sell(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("sell attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('sell aborted')
                        return
                    pass
        else:
            print('no assets to sell')
 
    if command == 'cancel':
 
        # cancel all orders in this MARKET relentlessly until satisfied
        print(('Bitshares API', command)) 
        orders = MARKET.accountopenorders()
        print((len(orders), 'open orders to cancel'))
        if len(orders):
            attempt = 1 
            order_list = []     
            for order in orders:
                order_list.append(order['id'])
            while attempt:
                try:
                    details = MARKET.cancel(order_list)
                    print (details)
                    attempt = 0
                except:
                    print((attempt, 'cancel failed', order_list))
                    attempt += 1
                    if attempt > 10:
                        print ('cancel aborted')
                        return
                    pass   
 
    if command == 'orders':
 
        # dictionary of open orders in traditional format:
        # orderNumber, orderType, market, amount, price
        print(('Bitshares API', command))
        orders = []
        for order in MARKET.accountopenorders():
            orderNumber = order['id']
            asset = order['base']['symbol']
            currency = order['quote']['symbol']
            amount = float(order['base'])
            price = float(order['price'])
            orderType = 'buy'
            if asset == BitASSET:
                orderType = 'sell'
                price = 1 / price
            orders.append({'orderNumber': orderNumber,
                           'orderType': orderType,
                           'market': BitPAIR, 'amount': amount,
                           'price': price})
        for o in orders:
            print (o)
        if len(orders) == 0:
            print ('no open orders')
        return orders
 
    if command == 'market_balances':
 
        # dictionary of currency and assets in this MARKET
        print(('Bitshares API', command))
        currency = float(ACCOUNT.balance(BitCURRENCY))
        assets = float(ACCOUNT.balance(BitASSET))
        balances = {'currency': currency, 'assets': assets}
        print (balances)
        return balances
 
    if command == 'complete_balances':
 
        # dictionary of ALL account balances
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        print (balances)
        return balances
 
    if command == 'book':
 
        # dictionary of 4 lists containing bid/ask volume/price
        print(('Bitshares API', command))
        raw = MARKET.orderbook(limit=depth)
        bids = raw['bids']
        asks = raw['asks']
        bidp = [float(bids[i]['price']) for i in range(len(bids))]
        bidv = [float(bids[i]['quote']) for i in range(len(bids))]
        askp = [float(asks[i]['price']) for i in range(len(asks))]
        askv = [float(asks[i]['quote']) for i in range(len(asks))]
        book = {'bidp': bidp, 'bidv': bidv, 'askp': askp, 'askv': askv}
        # print(book)
        print(('ask', ('%.8f' % book['askp'][0])))  # lowest ask price
        print(('bid', ('%.8f' % book['bidp'][0])))  # highest bid price
        # print(book['bidv'][0]) #highest bid volume
        # print(book['askv'][0]) #lowest ask volume
        return book
 
    if command == 'last':
 
        # the most recent transation in this MARKET
        print(('Bitshares API', command))
        raw = MARKET.ticker()['latest']
        price = float(raw)
        # print (price)
        return price
 
    if command == 'account_value':
 
        # dictionary account value in BTS BTC and USD
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        btc_value = 0
        for asset, amount in list(balances.items()):
            market_pair = 'OPEN.BTC:' + asset
            market = Market(market_pair)
            price = float(market.ticker()['latest'])
            try:
                value = amount / price
            except:
                value = 0
            if value < 0.0001:
                value = 0
            else:
                if asset != 'USD':
                    price = 1 / (price + SATOSHI)
                print((('%.4f' % value), 'OPEN.BTC', ('%.2f' % amount),
                       asset, '@', ('%.8f' % price)))
                btc_value += value
 
        market_pair = 'OPEN.BTC:USD'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        usd_value = btc_value * price
        market_pair = 'OPEN.BTC:BTS'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        bts_value = btc_value * price
        print((('%.2f' % bts_value), 'BTS',
             ('%.4f' % btc_value), 'OPEN.BTC',
             ('%.2f' % usd_value), 'bitUSD'))
        return bts_value, btc_value, usd_value
 
    if command == 'blocktime':
 
        current_block = CHAIN.get_current_block_num()
        blocktime = CHAIN.block_time(current_block)
        blocktimestamp = CHAIN.block_timestamp(current_block) - 18000
        now = time.time()
        latency = now - blocktimestamp
        print(('block               :', current_block))
        # print(('blocktime           :', blocktime))
        # print(('stamp               :', blocktimestamp))
        # print(('ctime(stamp)        :', time.ctime(blocktimestamp)))
        # print(('now                 :', now))
        print(('dex_rate latency    :', ('%.2f' % latency)))
        return current_block, blocktimestamp, latency
 
 
 
'''
dex('buy')
dex('sell')
dex('orders')
dex('cancel')
dex('market_balances')
dex('complete_balances')
dex('last')
dex('book')
dex('account_value')
dex('blocktime')
'''

139
this should be helpful:


Code: [Select]
for order in MARKET.accountopenorders():

        #print(MARKET.cancel(order['id']))
        print ('id', order['id'])
        print ('price', 1/float(order['price']))
        print ('asset', str(order['base']).split(' ')[1])
        print ('currency', str(order['quote']).split(' ')[1])
        print ('amount', str(order['base']).split(' ')[0])

returns:
Code: [Select]
id 1.7.5565xxxx
price 0.777
asset BTS
currency USD
amount 2.00000

140
spent several hours today trying to figure this out...

came here posted question... few minutes later figured it out

:D


found a snippet that helped

Code: [Select]
    def cancelall(self):
        """ Cancel all orders of this bot
        """
        if self.orders:
            return self.bitshares.cancel(
                [o["id"] for o in self.orders],
                account=self.account

https://github.com/xeroc/stakemachine/blob/master/stakemachine/basestrategy.py


so I can do:

Code: [Select]
for order in MARKET.accountopenorders():
    print (order['id'])


works!

this should really be added to pybitshares docs


BTS litepresence1

141
from docs:

http://docs.pybitshares.com/en/latest/market.html?highlight=cancel#bitshares.market.Market.cancel
Code: [Select]
cancel(orderNumber, account=None)¶
Cancels an order you have placed in a given market.
Requires only the “orderNumber”. An order number takes the form 1.7.xxx.

Parameters: orderNumber (str) – The Order Object ide of the form 1.7.xxxx

how can I get orderNumber actively while placing an order?

how can I get orderNumber after the fact for all outstanding orders?

I attempted

Code: [Select]
print(ACCOUNT.openorders)
and

Code: [Select]
for order in MARKET.accountopenorders():
    print (order)

and this gives the order amount and price... but not orderNumber


thanks


142
Technical Support / Re: I need some help getting started with pybitshares
« on: January 30, 2018, 04:59:29 pm »
works!

:D

huge

days and days of rabbit holes

finally can see my acct balance!



...next trade functions



oh btw... perhaps u don't want to keep your PORNXXX coins held on your public xeroc bitshares account

 :o

143
Technical Support / Re: I need some help getting started with pybitshares
« on: January 30, 2018, 01:22:24 pm »
How is your system setup?

Is this all installed?
http://docs.pybitshares.com/en/latest/installation.html

I have both python 2 and python 3 installed.

[email protected] ~ $ python --version
Python 2.7.6
[email protected] ~ $ python3 --version
Python 3.4.3

[email protected] ~ $ cat /etc/linuxmint/info
RELEASE=17.3
CODENAME=rosa
EDITION="Cinnamon 64-bit"
DESCRIPTION="Linux Mint 17.3 Rosa"
DESKTOP=Gnome
TOOLKIT=GTK


I did everything mentioned in the installation page of the docs for pybitshares.


144
Technical Support / Re: I need some help getting started with pybitshares
« on: January 30, 2018, 01:18:33 pm »
To me, this looks like the wrong or an outdated `websocket` library is installed.
The correct package is called `websocket-client` in pip3


Code: [Select]
[email protected] ~ $ pip install websocket-client

Requirement already satisfied (use --upgrade to upgrade): websocket-client in ./.local/lib/python2.7/site-packages
Cleaning up...

[email protected] ~ $ pip install websocket-client --upgrade

Requirement already up-to-date: websocket-client in ./.local/lib/python2.7/site-packages
Cleaning up...

[email protected] ~ $ pip3 install websocket-client --upgrade

Downloading/unpacking websocket-client
  Downloading websocket_client-0.46.0-py2.py3-none-any.whl (200kB): 200kB downloaded
Downloading/unpacking six from https://pypi.python.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl#md5=866ab722be6bdfed6830f3179af65468 (from websocket-client)
  Downloading six-1.11.0-py2.py3-none-any.whl
Installing collected packages: websocket-client, six
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 672, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python3/dist-packages/pip/req.py", line 902, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python3.4/os.py", line 237, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.4/dist-packages/websocket_client-0.46.0.dist-info'
Storing debug log for failure in /home/xyz/.pip/pip.log

[email protected] ~ $ sudo pip3 install websocket-client --upgrade
[sudo] password for xyz:

Downloading/unpacking websocket-client
  Downloading websocket_client-0.46.0-py2.py3-none-any.whl (200kB): 200kB downloaded
Downloading/unpacking six from https://pypi.python.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl#md5=866ab722be6bdfed6830f3179af65468 (from websocket-client)
  Downloading six-1.11.0-py2.py3-none-any.whl
Installing collected packages: websocket-client, six
  Found existing installation: six 1.5.2
    Not uninstalling six at /usr/lib/python3/dist-packages, owned by OS
Successfully installed websocket-client six
Cleaning up...


[email protected] ~ $ cd Python/EV
[email protected] ~/Python/EV $ python3 bitsharestest.py

Traceback (most recent call last):
  File "bitsharestest.py", line 11, in <module>
    account = Account("xeroc")
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/account.py", line 50, in __init__
    bitshares_instance=None
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/blockchainobject.py", line 69, in __init__
    self.bitshares = bitshares_instance or shared_bitshares_instance()
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/instance.py", line 15, in shared_bitshares_instance
    SharedInstance.instance = bts.BitShares()
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/bitshares.py", line 151, in __init__
    **kwargs)
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/bitshares.py", line 180, in connect
    self.rpc = BitSharesNodeRPC(node, rpcuser, rpcpassword, **kwargs)
  File "/home/xyz/.local/lib/python3.4/site-packages/bitsharesapi/bitsharesnoderpc.py", line 23, in __init__
    super(BitSharesNodeRPC, self).__init__(*args, **kwargs)
  File "/home/xyz/.local/lib/python3.4/site-packages/grapheneapi/graphenewsrpc.py", line 64, in __init__
    self.wsconnect()
  File "/home/xyz/.local/lib/python3.4/site-packages/grapheneapi/graphenewsrpc.py", line 79, in wsconnect
    self.ws = websocket.WebSocket(sslopt=sslopt_ca_certs)
TypeError: __init__() got an unexpected keyword argument 'sslopt'



no change

TypeError: __init__() got an unexpected keyword argument 'sslopt'

145
Technical Support / I need some help getting started with pybitshares
« on: January 29, 2018, 06:09:06 pm »
experienced python algo trader... very good w/ quant, databases, plotting, backtesting, etc...
but least favorite task is connectivity; moving from one api to another.


just getting started w/ pybitshares:

not fully understanding what I need to do; so please ELI5

thanks,

litepresence

I just need basic trading functions:

buy/sell/cancel
list open orders
ticker
balances
orderbook



first try first fail:



Code: [Select]
from bitshares.account import Account
account = Account("xeroc")
print(account)
print(account.balances)




Code: [Select]
[email protected] ~/Python/EV $ python3 bitsharestest.py

Traceback (most recent call last):
  File "bitsharestest.py", line 14, in <module>
    account = Account("xeroc")
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/account.py", line 50, in __init__
    bitshares_instance=None
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/blockchainobject.py", line 69, in __init__
    self.bitshares = bitshares_instance or shared_bitshares_instance()
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/instance.py", line 15, in shared_bitshares_instance
    SharedInstance.instance = bts.BitShares()
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/bitshares.py", line 151, in __init__
    **kwargs)
  File "/home/xyz/.local/lib/python3.4/site-packages/bitshares/bitshares.py", line 180, in connect
    self.rpc = BitSharesNodeRPC(node, rpcuser, rpcpassword, **kwargs)
  File "/home/xyz/.local/lib/python3.4/site-packages/bitsharesapi/bitsharesnoderpc.py", line 23, in __init__
    super(BitSharesNodeRPC, self).__init__(*args, **kwargs)
  File "/home/xyz/.local/lib/python3.4/site-packages/grapheneapi/graphenewsrpc.py", line 64, in __init__
    self.wsconnect()
  File "/home/xyz/.local/lib/python3.4/site-packages/grapheneapi/graphenewsrpc.py", line 79, in wsconnect
    self.ws = websocket.WebSocket(sslopt=sslopt_ca_certs)
TypeError: __init__() got an unexpected keyword argument 'sslopt'



seems like no matter what I do I get this TypeError

why?  what is sslopt?  what do I have to do to fix the problem?

???

146
Technical Support / Re: How to sell my litecoins in dex?
« on: January 29, 2018, 05:11:41 pm »
does not look like you're logged in

do you see this upper right:



if so... click on it and to unlock your acct

then in

SETTINGS >> General

you may wish to change

WALLET AUTO-LOCK TIME


Pages: 1 ... 3 4 5 6 7 8 9 [10]