Skip to content

Commit d20fd6f

Browse files
first commit
0 parents  commit d20fd6f

13 files changed

+295372
-0
lines changed

Diff for: .gitignore

+129
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
pip-wheel-metadata/
24+
share/python-wheels/
25+
*.egg-info/
26+
.installed.cfg
27+
*.egg
28+
MANIFEST
29+
30+
# PyInstaller
31+
# Usually these files are written by a python script from a template
32+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
33+
*.manifest
34+
*.spec
35+
36+
# Installer logs
37+
pip-log.txt
38+
pip-delete-this-directory.txt
39+
40+
# Unit test / coverage reports
41+
htmlcov/
42+
.tox/
43+
.nox/
44+
.coverage
45+
.coverage.*
46+
.cache
47+
nosetests.xml
48+
coverage.xml
49+
*.cover
50+
*.py,cover
51+
.hypothesis/
52+
.pytest_cache/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
target/
76+
77+
# Jupyter Notebook
78+
.ipynb_checkpoints
79+
80+
# IPython
81+
profile_default/
82+
ipython_config.py
83+
84+
# pyenv
85+
.python-version
86+
87+
# pipenv
88+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
90+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
91+
# install all needed dependencies.
92+
#Pipfile.lock
93+
94+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
95+
__pypackages__/
96+
97+
# Celery stuff
98+
celerybeat-schedule
99+
celerybeat.pid
100+
101+
# SageMath parsed files
102+
*.sage.py
103+
104+
# Environments
105+
.env
106+
.venv
107+
env/
108+
venv/
109+
ENV/
110+
env.bak/
111+
venv.bak/
112+
113+
# Spyder project settings
114+
.spyderproject
115+
.spyproject
116+
117+
# Rope project settings
118+
.ropeproject
119+
120+
# mkdocs documentation
121+
/site
122+
123+
# mypy
124+
.mypy_cache/
125+
.dmypy.json
126+
dmypy.json
127+
128+
# Pyre type checker
129+
.pyre/

Diff for: balances.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import os
2+
3+
from binance.client import Client
4+
5+
# init
6+
api_key = os.environ.get('binance_api')
7+
api_secret = os.environ.get('binance_secret')
8+
9+
client = Client(api_key, api_secret)
10+
11+
## main
12+
13+
# get balances for all assets & some account information
14+
print(client.get_account())
15+
16+
# get balance for a specific asset only (BTC)
17+
print(client.get_asset_balance(asset='BTC'))
18+
19+
# get balances for futures account
20+
print(client.futures_account_balance())
21+
22+
# get balances for margin account
23+
# will raise an exception if margin account is not activated
24+
#print(client.get_margin_account())

Diff for: btc_bars3.csv

+294,805
Large diffs are not rendered by default.

Diff for: btc_historical_csv.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import csv
2+
import json
3+
import os
4+
5+
import pandas as pd
6+
from binance.client import Client
7+
8+
# init
9+
api_key = os.environ.get('binance_api')
10+
api_secret = os.environ.get('binance_secret')
11+
12+
client = Client(api_key, api_secret)
13+
14+
## main
15+
16+
# valid intervals - 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M
17+
# get timestamp of earliest date data is available
18+
timestamp = client._get_earliest_valid_timestamp('BTCUSDT', '1d')
19+
print(timestamp)
20+
21+
# request historical candle (or klines) data
22+
bars = client.get_historical_klines('BTCUSDT', '1d', timestamp, limit=1000)
23+
# print(bars)
24+
25+
# option 1 - save to file using json method - this will retain Python format (list of lists)
26+
with open('btc_bars.json', 'w') as e:
27+
json.dump(bars, e)
28+
29+
# option 2 - save as CSV file using the csv writer library
30+
with open('btc_bars.csv', 'w', newline='') as f:
31+
wr = csv.writer(f)
32+
for line in bars:
33+
wr.writerow(line)
34+
35+
# option 3 - save as CSV file without using a library. Shorten to just date, open, high, low, close
36+
with open('btc_bars2.csv', 'w') as d:
37+
for line in bars:
38+
d.write(f'{line[0]}, {line[1]}, {line[2]}, {line[3]}, {line[4]}\n')
39+
40+
# delete unwanted data - just keep date, open, high, low, close
41+
for line in bars:
42+
del line[5:]
43+
44+
# option 4 - create a Pandas DataFrame and export to CSV
45+
btc_df = pd.DataFrame(bars, columns=['date', 'open', 'high', 'low', 'close'])
46+
btc_df.set_index('date', inplace=True)
47+
print(btc_df.head())
48+
# export DataFrame to csv
49+
btc_df.to_csv('btc_bars3.csv')

Diff for: buy_bnb.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import os
2+
3+
from binance.client import Client
4+
5+
# init
6+
api_key = os.environ.get('binance_api')
7+
api_secret = os.environ.get('binance_secret')
8+
9+
client = Client(api_key, api_secret)
10+
11+
12+
# functions
13+
14+
def topup_bnb(min_balance: float, topup: float):
15+
''' Top up BNB balance if it drops below minimum specified balance '''
16+
bnb_balance = client.get_asset_balance(asset='BNB')
17+
bnb_balance = float(bnb_balance['free'])
18+
if bnb_balance < min_balance:
19+
qty = round(topup - bnb_balance, 5)
20+
print(qty)
21+
order = client.order_market_buy(symbol='BNBUSDT', quantity=qty)
22+
return order
23+
return False
24+
25+
26+
# example
27+
min_balance = 1.0
28+
topup = 2.5
29+
order = topup_bnb(min_balance, topup)

Diff for: create_order.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import os
2+
3+
from binance.client import Client
4+
from binance.enums import *
5+
from binance.exceptions import BinanceAPIException, BinanceOrderException
6+
7+
# init
8+
api_key = os.environ.get('binance_api')
9+
api_secret = os.environ.get('binance_secret')
10+
11+
client = Client(api_key, api_secret)
12+
13+
## main
14+
15+
# create order
16+
17+
# make a test order first. This will raise an exception if the order is incorrect.
18+
buy_order_limit = client.create_test_order(
19+
symbol='ETHUSDT',
20+
side='BUY',
21+
type='LIMIT',
22+
timeInForce='GTC',
23+
quantity=100,
24+
price=200)
25+
26+
buy_order = client.create_test_order(symbol='ETHUSDT', side='BUY', type='MARKET', quantity=100)
27+
28+
# create a real order if the test orders did not raise an exception
29+
try:
30+
buy_limit = client.create_order(
31+
symbol='ETHUSDT',
32+
side='BUY',
33+
type='LIMIT',
34+
timeInForce='GTC',
35+
quantity=100,
36+
price=200)
37+
38+
# same order but with helper function
39+
buy_limit = client.order_limit_buy(symbol='ETHUSDT', quantity=100, price=200)
40+
41+
# market order using a helper function
42+
market_order = client.order_market_sell(symbol='ETHUSDT', quantity=100)
43+
44+
# cancel previous orders
45+
cancel = client.cancel_order(symbol='ETHUSDT', orderId=buy_limit['orderId'])
46+
except BinanceAPIException as e:
47+
# error handling goes here
48+
print(e)
49+
except BinanceOrderException as e:
50+
# error handling goes here
51+
print(e)
52+
53+
# using binance constants - the library has hard coded commonly used strings
54+
# https://python-binance.readthedocs.io/en/latest/constants.html#
55+
56+
# this order uses required strings such as 'BUY' and 'MARKET' which are prone to spelling errors
57+
buy_order = client.create_test_order(symbol='ETHUSDT', side='BUY', type='MARKET', quantity=100)
58+
59+
# binance constants can be used instead
60+
buy_order = client.create_test_order(symbol='ETHUSDT', side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=100)

Diff for: indicators.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import btalib
2+
import pandas as pd
3+
4+
# load DataFrame
5+
btc_df = pd.read_csv('btc_bars3.csv', index_col=0)
6+
# btc_df.set_index('date', inplace=True)
7+
btc_df.index = pd.to_datetime(btc_df.index, unit='ms')
8+
9+
# calculate 20 moving average using Pandas
10+
btc_df['20sma'] = btc_df.close.rolling(20).mean()
11+
print(btc_df.tail(5))
12+
13+
# calculate just the last value for the 20 moving average
14+
mean = btc_df.close.tail(20).mean()
15+
16+
# get the highest closing price in 2020
17+
max_val = btc_df.close['2020'].max()
18+
19+
print(mean)
20+
print(max_val)
21+
22+
# technical indicators using bta-lib
23+
24+
# sma
25+
sma = btalib.sma(btc_df.close)
26+
print(sma.df)
27+
28+
# create sma and attach as column to original df
29+
btc_df['sma'] = btalib.sma(btc_df.close, period=20).df
30+
print(btc_df.tail())
31+
32+
# calculate rsi and macd
33+
rsi = btalib.rsi(btc_df, period=14)
34+
macd = btalib.macd(btc_df, pfast=20, pslow=50, psignal=13)
35+
36+
print(rsi.df)
37+
print(macd.df)
38+
39+
# access last rsi value
40+
print(rsi.df.rsi[-1])
41+
42+
# join the rsi and macd calculations as columns in original df
43+
btc_df = btc_df.join([rsi.df, macd.df])
44+
print(btc_df.tail())

Diff for: latest_btc_price.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import os
2+
3+
from binance.client import Client
4+
5+
# init
6+
api_key = os.environ.get('binance_api')
7+
api_secret = os.environ.get('binance_secret')
8+
9+
client = Client(api_key, api_secret)
10+
11+
## main
12+
13+
# get latest price from Binance API
14+
btc_price = client.get_symbol_ticker(symbol='BTCUSDT')
15+
# print full output (dictionary)
16+
print(btc_price)
17+
# print just the price
18+
print(btc_price['price'])

0 commit comments

Comments
 (0)