Crypto backtesting
Loading...
Searching...
No Matches
binance.py
Go to the documentation of this file.
1import os
2import csv
3from datetime import datetime
4from binance.client import Client
5from binance.exceptions import BinanceAPIException, BinanceOrderException
6
7# Get API key from environment variable
8api_key = os.getenv('BINANCE_API_KEY')
9api_secret = os.getenv('BINANCE_API_SECRET')
10
11try:
12
13 # Initialize the client
14 client = Client(api_key, api_secret)
15
16 # Get account info
17 info = client.get_account()
18
19 # Calculate number of non-zero balances
20 non_zero_balances = 0
21 for balance in info['balances']:
22 if float(balance['free']) > 0:
23 non_zero_balances += 1
24
25 print("Non-zero balances: ", non_zero_balances)
26
27 # Get all open orders
28 open_orders = client.get_open_orders()
29 print("Open orders: ", len(open_orders))
30
31 # Open file using CSV library
32 with open('summary.csv', 'r') as file:
33 reader = csv.reader(file)
34 next(reader)
35 for row in reader:
36 # Get date from column 0
37 date = row[0]
38 dt = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
39
40 # Get symbol from column 1
41 exchange_and_symbol = row[1]
42
43 # Split out the symbol into two coins
44 tokens = exchange_and_symbol.split('-')
45
46 # Join 1 and 2 into a symbol like ETHBTC
47 symbol = tokens[1] + tokens[2]
48
49 print(f"{dt} {symbol}")
50
51 symbol_spot = client.get_symbol_ticker(symbol=symbol)
52 price = float(symbol_spot['price'])
53 print(price)
54
55 # try to execute
56 symbol_spot = client.get_symbol_ticker(symbol="ETHBTC")
57 eth_price = float(symbol_spot['price'])
58 print("ETHBTC: ", eth_price)
59
60except BinanceAPIException as e:
61 print("API error: ", e)
62
63except BinanceOrderException as e:
64 print("Order error: ", e)