Commit f949db96 authored by hockeymikey's avatar hockeymikey

Initial

parents
**/keys.py
**/__pycache__/
**/.idea/workspace.xml
**/.idea/tasks.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.6.2 (C:\Python36\python36.exe)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">
<option name="projectConfiguration" value="Nosetests" />
<option name="PROJECT_TEST_RUNNER" value="Nosetests" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="useProjectProfile" value="false" />
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6.2 (C:\Python36\python36.exe)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/BenBotVC.iml" filepath="$PROJECT_DIR$/.idea/BenBotVC.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
This diff is collapsed.
Getting started:
1) Go into python-bittrex from command line and run "python setup.py install"
2) Install other modules that are required using pip install "module"
Requests, pause
3) Make copy of key_template.py as keys.py. Put your API keys inside
4) Run t_b.py
\ No newline at end of file
class dragon_kernel(object):
'''
Uses an exponential average of ask prices divided by the mean.
Doesn't work at all. Not updated really.
Use laker as a template not this one
'''
def __init__(self, name):
# super(market_item, self).__init__(target=target, name=name)
self.name = name
self.main_value = 'Ask'
self.p_cache_size = 32
def buy_new(self, c_t, best_n):
return c_t['Avg'] * 2.0 < best_n.health['dragon']['Avg'],1.0
def treshold_check(self, best_n):
return best_n.health[self.name]['Avg'] > 0.02 ,1.0
def should_sell(self, t_health, current_trading):
c_t = t_health[current_trading.name]
print('Curr: ' + current_trading.name + ', ' + str(c_t['Avg']))
# Second variable is the weight for decision
return c_t['Avg'] <= 0.006, 1.0
def best_health(self, t_health, threads):
best = None
best_n = None
for k, v in t_health.items():
# x[1][0] = orderB/OrderS
# x[1][1] = percentChange
# tmp = v[0] * v[1]
# Change,Orders,ASk
try:
tmp = v['Avg'] # v['Change']*v['Orders']
except TypeError:
tmp = None
if tmp is not None and (best is None or best < tmp): # and tmp > 5.0:
best = tmp
best_n = k
# return (best_n,best)
if best_n is not None:
return threads[best_n]
else:
return None
def i_health_check(self, data, c_name):
l = data.__len__()
if l >= 8:
orders = 0
try:
orders = data[0]['OpenBuyOrders'] / float(data[0]['OpenSellOrders'])
except ZeroDivisionError:
order = data[0]['OpenBuyOrders']
low = None
# avg = self.data[0]['Ask']
exp = 0.0
avg = 0.0
for x in range(l):
avg += data[x]['Ask']
exp += data[x]['Ask'] / (2.0 ** (x + 1.0))
# avg += self.data[x]['Ask']
if low == None or data[x]['Ask'] < low[1]:
low = (data[x]['TimeStamp'], data[x]['Ask'], x)
try:
dif = low[1] / (data[0]['Ask'] - low[1])
except ZeroDivisionError as ex:
dif = 0
avg /= l
exp /= l
try:
avg = (avg-low[1]) / exp#(low[1]/(2.0 ** (low[2] + 1.0)))
except ZeroDivisionError as ex:
print(c_name + ' divide by zero, avg.')
print(ex)
avg = 0.0
return {'Orders': orders, 'Change': dif, 'Ask': data[0]['Ask'], 'Avg': avg}
else:
return {'Orders': None, 'Change': None, 'Ask': None, 'Avg': None}
class laker_kernel(object):
'''
Uses expodential moving average. Works OK at times. Threshhold values need to be tweaked.
USe this for a template.
Most of the functions will return a boolean and a weight. The weight is used to
determine outcome when you are running multiple kernels. Kernels with higher weight
have opinions that are more highly regarded.
'''
def __init__(self, name):
# super(market_item, self).__init__(target=target, name=name)
self.name = name
#Where the main health value is stored in the dictionary.
self.main_v = 'Main'
#Number of prices to be cached.
self.p_cache_size = 39
def buy_new(self, c_t, best_n):
'''
Returns a boolean and weight if the new best coin should be
picked up and dump the current one being held
:param c_t:
:param best_n:
:return: tuple of boolean and weight
'''
return c_t[self.main_v] / best_n.health[self.name][self.main_v] < 0.98, 1.0
def treshold_check(self, best_n):
'''
Does the best coin pass the threshold to make it investable?
:param best_n:
:return: tuple of boolean and weight
'''
return best_n.health[self.name][self.main_v] > 1.02, 1.0
def should_sell(self, t_health, current_trading):
'''
Should the current coin be dumped as it is doing poorly?
:param t_health:
:param current_trading:
:return:
'''
c_t = t_health[current_trading.name]
print('Curr: ' + current_trading.name + ', ' + str(c_t[self.main_v]))
# Second variable is the weight for decision
return c_t[self.main_v] <= 1.09, 1.0
def best_health(self, t_health, threads):
'''
Returns the best performing coin based on the kernel.
GOAL: return something like top 5 or 10
:param t_health:
:param threads:
:return:
'''
best = None
best_n = None
for k, v in t_health.items():
try:
tmp = v[self.main_v] # v['Change']*v['Orders']
except TypeError:
tmp = None
if tmp is not None and (best is None or best < tmp): # and tmp > 5.0:
best = tmp
best_n = k
# return (best_n,best)
if best_n is not None:
return threads[best_n]
else:
return None
def i_health_check(self, data, c_name):
'''
Returns individual health for one coin
:param data:
:param c_name:
:return:
'''
l = data.__len__()
if l >= 8:
orders = 0
try:
orders = data[0]['OpenBuyOrders'] / float(data[0]['OpenSellOrders'])
except ZeroDivisionError:
orders = data[0]['OpenBuyOrders']
low = None
# avg = self.data[0]['Ask']
exp = 0.0
avg = 1.0
x = 0
a = 0.3
while x < l:
if x != l-1:
#avg += (data[x]['Ask']/data[x+1]['Ask'])/(2.23**(x+1.0))#maybe add by one
taa = (data[x]['Ask'] / data[x + 1]['Ask'])
if x != 0:
taa += (1.0 - a)**(x)
avg *= taa
# avg += self.data[x]['Ask']
if low == None or data[x]['Ask'] < low[1]:
low = (data[x]['TimeStamp'], data[x]['Ask'], x)
x += 1
try:
dif = low[1] / (data[0]['Ask'] - low[1])
except ZeroDivisionError as ex:
dif = 0
#avg /= l
#exp /= l
avg *= a
return {'Orders': orders, 'Change': dif, 'Ask': data[0]['Ask'], self.main_v: avg}
else:
return {'Orders': None, 'Change': None, 'Ask': None, self.main_v: None}
\ No newline at end of file
def getkeys():
'''
Get your api key from Bittrex and supply it below. Use to supply the Bittrex object
:return:
'''
return 'key', 'secret_key'
\ No newline at end of file
import bittrex.bittrex as bx
import logging
class e_balance(object):
def __init__(self,bittrex):
self.all = {'BTC':0.500}
self.b = bittrex
def deduct(self,coin,amount):
print(coin+': '+str(amount))
self.all.setdefault(coin, 0.0)
if amount > self.all[coin]:
print('Error! Not enough coin!: '+coin)
else:
self.all[coin] -= amount
def add(self,coin,amount):
print(coin+': '+str(amount))
self.all.setdefault(coin,0.0)
self.all[coin] += amount
class e_trader(object):
def __init__(self,bittrex,bal):
self.b = bittrex
self.bal = bal
self.m_2_c = {'BTC':'USDT-BTC'}
def buy_market_e(self,market,amount,ask):
#b.get_ticker(market)['Ask']
tt = market.split('-')
base = tt[0]
head = tt[1]
am = (amount*ask)
am = am + (am*0.0025)
self.bal.deduct(base,am)
self.bal.add(head,amount)
self.m_2_c.setdefault(head,market)
def sell_market_e(self,market,amount,ask):
tt = market.split('-')
base = tt[0]
head = tt[1]
am = (amount*ask)
am = am - (am*0.0025)
self.bal.deduct(head, amount)
self.bal.add(base, am)
\ No newline at end of file
# Created by http://www.gitignore.io
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
### PyCharm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
## Directory-based project format
.idea/
/*.iml
# if you remove the above rule, at least ignore user-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# and these sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# and, if using gradle::
# .idea/gradle.xml
# .idea/libraries
## File-based project format
*.ipr
*.iws
## Additional for IntelliJ
out/
# generated by mpeltonen/sbt-idea plugin
.idea_modules/
# generated by JIRA plugin
atlassian-ide-plugin.xml
# generated by Crashlytics plugin (for Android Studio and Intellij)
com_crashlytics_export_strings.xml
### SublimeText ###
# workspace files are user-specific
*.sublime-workspace
# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
# *.sublime-project
#sftp configuration file
sftp-config.json
### Linux ###
*~
# KDE directory preferences
.directory
### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### OSX ###
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
#JSON file containing API keys and API secrets
secrets.json
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2014 Eric Somdahl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
\ No newline at end of file
python-bittrex
==============
Python bindings for bittrex. I am Not associated -- use at your own risk, etc.
Tips are appreciated:
* BTC: 1D7F9ZF6BCoCh2MncK15jxHM1T5BPX9Ajd
* LTC: LaasG9TRa9p32noN2oKUVVqrDFp4Ja1NK3
In order to run the integration tests, a file called "secrets.json" must be added to the test folder.
Structure it as follows, adding your API keys:
<pre>
<code>
{
"key": "mykey",
"secret": "mysecret"
}
</code>
</pre>
This diff is collapsed.
__author__ = 'eric'
import unittest
import json
from bittrex.bittrex import Bittrex
def test_basic_response(unit_test, result, method_name):
unit_test.assertTrue(result['success'], "{0:s} failed".format(method_name))
unit_test.assertTrue(result['message'] is not None, "message not present in response")
unit_test.assertTrue(result['result'] is not None, "result not present in response")
def test_auth_basic_failures(unit_test, result, test_type):
unit_test.assertFalse(result['success'], "{0:s} failed".format(test_type))
unit_test.assertTrue('invalid' in str(result['message']).lower(), "{0:s} failed response message".format(test_type))
unit_test.assertIsNone(result['result'], "{0:s} failed response result not None".format(test_type))
class TestBittrexPublicAPI(unittest.TestCase):
"""
Integration tests for the Bittrex public API.
These will fail in the absence of an internet connection or if bittrex API goes down
"""
def setUp(self):
self.bittrex = Bittrex(None, None)
def test_handles_none_key_or_secret(self):
self.bittrex = Bittrex(None, None)
# could call any public method here
actual = self.bittrex.get_markets()
self.assertTrue(actual['success'], "failed with None key and None secret")
self.bittrex = Bittrex("123", None)
actual = self.bittrex.get_markets()
self.assertTrue(actual['success'], "failed with None secret")
self.bittrex = Bittrex(None, "123")
self.assertTrue(actual['success'], "failed with None key")
def test_get_markets(self):
actual = self.bittrex.get_markets()
test_basic_response(self, actual, "get_markets")
self.assertTrue(isinstance(actual['result'], list), "result is not a list")
self.assertTrue(len(actual['result']) > 0, "result list is 0-length")
def test_get_currencies(self):
actual = self.bittrex.get_currencies()
test_basic_response(self, actual, "get_currencies")
pass
class TestBittrexAccountAPI(unittest.TestCase):
"""
Integration tests for the Bittrex Account API.
* These will fail in the absence of an internet connection or if bittrex API goes down.
* They require a valid API key and secret issued by Bittrex.
* They also require the presence of a JSON file called secrets.json.
It is structured as such:
{
"key": "12341253456345",
"secret": "3345745634234534"
}
"""
def setUp(self):
with open("secrets.json") as secrets_file:
self.secrets = json.load(secrets_file)
secrets_file.close()
self.bittrex = Bittrex(self.secrets['key'], self.secrets['secret'])
def test_handles_invalid_key_or_secret(self):
self.bittrex = Bittrex('invalidkey', self.secrets['secret'])
actual = self.bittrex.get_balance('BTC')
test_auth_basic_failures(self, actual, 'Invalid key, valid secret')
self.bittrex = Bittrex(None, self.secrets['secret'])
actual = self.bittrex.get_balance('BTC')
test_auth_basic_failures(self, actual, 'None key, valid secret')
self.bittrex = Bittrex(self.secrets['key'], 'invalidsecret')
actual = self.bittrex.get_balance('BTC')
test_auth_basic_failures(self, actual, 'valid key, invalid secret')
self.bittrex = Bittrex(self.secrets['key'], None)
actual = self.bittrex.get_balance('BTC')
test_auth_basic_failures(self, actual, 'valid key, None secret')
self.bittrex = Bittrex('invalidkey', 'invalidsecret')
actual = self.bittrex.get_balance('BTC')
test_auth_basic_failures(self, actual, 'invalid key, invalid secret')
pass
def test_get_balance(self):
actual = self.bittrex.get_balance('BTC')
test_basic_response(self, actual, "getbalance")
self.assertTrue(isinstance(actual['result'], dict), "result is not a dict")
self.assertEqual(actual['result']['Currency'],
"BTC",
"requested currency {0:s} does not match returned currency {1:s}"
.format("BTC", actual['result']['Currency']))
if __name__ == '__main__':
unittest.main()
certifi==2017.4.17
chardet==3.0.3
idna==2.5
requests==2.17.3
urllib3==1.21.1
#!/usr/bin/env python
from distutils.core import setup
setup(name='python-bittrex',
version='0.1.2',
packages=['bittrex'],
modules=['bittrex'],
description='Python bindings for bittrex API.',
author='Eric Somdahl',
author_email='eric@corsairconsulting.com',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Topic :: Office/Business :: Financial',
])
# Byte-compiled / optimized / DLL files
*~
secrets.json
markets.json
*.table
*.db
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations