-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathbinance.py
127 lines (103 loc) · 3.87 KB
/
binance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from ccxtbt import CCXTStore
import backtrader as bt
from datetime import datetime, timedelta, timezone
import json
class TestStrategy(bt.Strategy):
def __init__(self):
pass
# self.sma = bt.indicators.SMA(self.data, period=21)
def next(self):
# Get cash and balance
# New broker method that will let you get the cash and balance for
# any wallet. It also means we can disable the getcash() and getvalue()
# rest calls before and after next which slows things down.
# NOTE: If you try to get the wallet balance from a wallet you have
# never funded, a KeyError will be raised! Change LTC below as approriate
# if self.live_data:
# cash, value = self.broker.get_wallet_balance('USDT')
# else:
# # Avoid checking the balance during a backfill. Otherwise, it will
# # Slow things down.
# cash = value = 'NA'
for data in self.datas:
print(
f"{data.datetime.datetime()},"
f"{data._name},"
# f"{cash}, {value}, "
f"{data.open[0]}, "
f"{data.high[0]}, "
f"{data.low[0]}, "
f"{data.close[0]}, "
f"{data.volume[0]}, "
# f"{self.sma[0]} "
)
def notify_data(self, data, status, *args, **kwargs):
dn = data._name
dt = datetime.utcnow().replace(tzinfo=timezone.utc)
msg = "Data Status: {}".format(data._getstatusname(status))
print(dt, dn, msg)
if data._getstatusname(status) == "LIVE":
self.live_data = True
else:
self.live_data = False
with open("./params.json", "r") as f:
params = json.load(f)
cerebro = bt.Cerebro(quicknotify=True)
# Add the strategy
cerebro.addstrategy(TestStrategy)
#
# # Create our actual binance store
# config = {
# "apiKey": params["binance_actual"]["apikey"],
# "secret": params["binance_actual"]["secret"],
# "enableRateLimit": True,
# }
# Create our binance/testnet store
config = {'urls': {'api': 'https://testnet.binance.vision/api'},
"apiKey": params["binance_testnet"]["apikey"],
"secret": params["binance_testnet"]["secret"],
"enableRateLimit": True,
}
# IMPORTANT NOTE - Kraken (and some other exchanges) will not return any values
# for get cash or value if You have never held any BNB coins in your account.
# So switch BNB to a coin you have funded previously if you get errors
store = CCXTStore(
exchange="binance", currency="USDT", config=config, retries=5, debug=False, sandbox=True
)
# Get the broker and pass any kwargs if needed.
# ----------------------------------------------
# Broker mappings have been added since some exchanges expect different values
# to the defaults. Case in point, Kraken vs Bitmex. NOTE: Broker mappings are not
# required if the broker uses the same values as the defaults in CCXTBroker.
broker_mapping = {
"order_types": {
bt.Order.Market: "market",
bt.Order.Limit: "limit",
bt.Order.Stop: "stop-loss", # stop-loss for kraken, stop for bitmex
bt.Order.StopLimit: "stop limit",
},
"mappings": {
"closed_order": {"key": "status", "value": "closed"},
"canceled_order": {"key": "result", "value": 1},
},
}
broker = store.getbroker(broker_mapping=broker_mapping)
cerebro.setbroker(broker)
# Get our data
# Drop newest will prevent us from loading partial data from incomplete candles
hist_start_date = datetime.utcnow() - timedelta(minutes=30)
data = store.getdata(
dataname="BNB/USDT",
name="BNBUSDT",
timeframe=bt.TimeFrame.Minutes,
fromdate=hist_start_date,
# todate=datetime(2021, 7, 15),
compression=1,
ohlcv_limit=500,
drop_newest=True,
historical=False,
)
# Add the feed
cerebro.adddata(data)
# Run the strategy
cerebro.run()