Programming Your First Cryptobot (Part 2)
In part one of the series, we wrote a simple Python based wrapper around some of the basic Bittrex API features. In part two we will expand on this wrapper so that you can add further functionality to your trading bot.
For convenience, I have uploaded the source from part one to github.com/tmstieff/BittrexBot. If you spot an errors, please feel free to open an issue or pull request!
We can open buy and sell orders already, but at the moment we are relying Bittrex to tell us if the order went through. For various reasons the order might fail, but the most common reason for our current implementation will involve insufficient funds. To fix this, let's first check our account balances and determine if we actually have enough of a specific coin or token to sell.
Create two new functions, and add them anywhere to the body of our Python file. These will query for the balance of a specific market using our API key. Because of how the Bittrex API works, we will need to query for the market first and then using that information we can query for the balance of the market currency.
def get_balance_from_market(market_type):
markets_res = simple_request('https://bittrex.com/api/v1.1/public/getmarkets')
markets = markets_res['result']
for market in markets:
if market['MarketName'] == market_type:
return get_balance(market['MarketCurrency'])
# Return a fake response of 0 if not found
return {'result': {'Available': 0}}
def get_balance(currency):
url = 'https://bittrex.com/api/v1.1/account/getbalance?apikey=' + API_KEY + '¤cy=' + currency
res = signed_request(url)
if res['result'] is not None and len(res['result']) > 0:
return res
# If there are no results, than your balance is 0
return {'result': {'Available': 0}}
Now in our tick() function, we can utilize the get_balance_from_market() function to check if we have any coins to sell before blindly placing a market sell order.
if percent_chg < -20:
# Do we have any to sell?
balance_res = get_balance_from_market(market)
current_balance = balance_res['result']['Available']
if current_balance > 5:
# Ship is sinking, get out!
print('Selling 5 units of ' + market + ' for ' + str(format_float(last)))
res = sell_limit(market, 5, last)
print(res)
else:
print('Not enough ' + market + ' to open a sell order')
This new block of code will query for the current balance of the market in question. If we have enough to sell, a market sell order will be opened.
There's another obvious issue with our crypto bot. It will keep placing buy and sell orders no matter how many existing orders we have open! Let's use the 'getopenorders' endpoint to determine if we have any open orders for a specific market. We can use this information to limit how many orders our trader creates.
In the script add two more functions. One will make the API call, and another will parse the open orders list to determine if we have any open orders for a specific market and order type. The two order types listed on the API docs are 'LIMIT_BUY' and 'LIMIT_SELL'.
def get_open_orders(market):
url = 'https://bittrex.com/api/v1.1/market/getopenorders?apikey=' + API_KEY + '&market=' + market
return signed_request(url)
def has_open_order(market, order_type):
orders_res = get_open_orders(market)
orders = orders_res['result']
if orders is None or len(orders) == 0:
return False
# Check all orders for a LIMIT_BUY
for order in orders:
if order['OrderType'] == order_type:
return True
return False
Now let's modify our tick() function again to check for any open orders before we execute a trade.
if 40 < percent_chg < 60:
# Fomo strikes! Let's buy some
if has_open_order(market, 'LIMIT_BUY'):
print('Order already opened to buy 5 ' + market)
else:
print('Purchasing 5 units of ' + market + ' for ' + str(format_float(last)))
res = buy_limit(market, 5, last)
print(res)
if percent_chg < -20:
# Do we have any to sell?
balance_res = get_balance(market)
current_balance = balance_res['result']['Available']
if current_balance > 5:
# Ship is sinking, get out!
if has_open_order(market, 'LIMIT_SELL'):
print('Order already opened to sell 5 ' + market)
else:
print('Selling 5 units of ' + market + ' for ' + str(format_float(last)))
res = sell_limit(market, 5, last)
print(res)
else:
print('Not enough ' + market + ' to open a sell order')
The changes should be pretty straightforward. If an existing order is still open for a given market, the bot will skip it and continue ticking.
Hopefully all of this doesn't seem too daunting, and you are able to expand on your crypto bot from part one. I h ave uploaded the complete code for this part to github.com/tmstieff/BittrexBot so that everyone can have a complete working copy. If you have any questions please comment below!
Really enjoyed this post and will try your bot with my own settings :-)
Thanks for this great post. Keep up the good work!
Upvoted and Resteemed ;)
Cheers,
alex
Thank you very much for follow up, great article. I hope one day i will clean the dust form my python programming knowledge and i will sit to this. Anyway - I'm bookmarking your article, thanks man!
it's great post python is very useful this idea it's really great thank's to share it with us , I have followed you !
This one is very helpful thank you
great achievement thanks
did u hear btc is temporally banned in china soon??
now is the chance to earn btc...
i found a great miner i earn 5000doge a day with just 50$
anyway here is the link, im happy to help :)
https://victorymine.com/?ref=stiffywalsh
Congratulations @tstieff!
Your post was mentioned in the hit parade in the following category:
Congratulations @tstieff! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes received
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Hello,
Hope i'm not a little to late.
Could be please take us through on how to call each of the functions and print the output for each of the 'def functions'. E.g the Get Balance function ?
Many thanks
Interesante pero realmente no estas conectado a la api, hace meses hice algunas funciones parecidas, lo unico que me faltaba era eliminar las ordenes que no se hacian en un determinado tiempo, voy a revisar y hare mi bot que habia pensado hace meses, ya que veo que no importa que tan funcional sea a la primera :D... por ejemplo comprar 5, deberias comprar la cantidad cercana a lo que tienes en BTC