-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoinBasePriceTracker.py
352 lines (196 loc) · 7.23 KB
/
CoinBasePriceTracker.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 19 12:08:52 2020
@author: TimboSlicerr
Tracks the Prices of Selected CryptoCurrencies from CoinBase, and periodically saves the data to a csv file
"""
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 8 11:23:50 2020
@author: TimboSlicerr
"""
# /root/thinclient_drives/Document/CBPRO
import cbpro
import requests, json, matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from multiprocessing.pool import ThreadPool
from multiprocessing import Pool
import multiprocessing
from apscheduler.schedulers.background import BackgroundScheduler
import time
from datetime import datetime, timedelta
import threading
import math
import os
from pytz import timezone
key = ''
b64secret = ''
passphrase = ''
auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)
minuteFirst = {}
BuySellList = {}
breakValue = False
global hours
global minutes
global days
global iteration
global index
global minLength
global currencyIndex
global totalminutes
global currencyIL
minutes = 0
hours = 0
days = 0
iteration = 1
totalminutes = 0
currencyIL = ['BTC-USD', 'ETH-USD', 'LTC-USD', 'BCH-USD', 'ADA-USD', 'DOT-USD', 'SHIB-USD', 'POLY-USD']
currencyIL = sorted(currencyIL)
def setUp():
for cur in currencyIL:
minuteFirst[cur] = []
print("Select Interval: Minutes, Seconds, or Hours: \nType M, S, or H then hit Enter")
intervalType = input()
print("Enter length for the Interval to Run: ")
intervalLength = float(input())
minLength = 0.00
if(intervalType == 'H'):
print("Enter the number of Minutes:")
minLength = float(input())
currencyIndex = 0
public_client = cbpro.PublicClient()
def checkTicker():
global min1int, hour1int
global minuteFirst
global secfloat
global minutes, hours, days
global iteration, index
global currencyIndex
global tempProduct
global tempPrice
global totalminutes
global currencyIL
for item in range(3):
tempProduct = {}
tempPrice = 0.00
prID = ''
curLength = len(currencyIL)
if(currencyIndex <= curLength-1):
prID = currencyIL[currencyIndex]
if(iteration == 1):
prID = 'BTC-USD'
tempProduct = public_client.get_product_ticker(product_id=prID)
tempPrice = float(tempProduct['price'])
elif(iteration != 1 and currencyIndex <= curLength-1):
# print(currencyIndex)
print(prID)
if(prID == 'BTC-USD'):
currencyIndex = currencyIndex + 1
continue
elif(prID != 'BTC-USD'):
tempProduct = public_client.get_product_ticker(product_id=prID)
tempPrice = float(tempProduct['price'])
currencyIndex = currencyIndex + 1
central = timezone('US/Central')
now2 = datetime.now(central)
# timenow2=now2.strftime("%H:%M:%S.%f")
sec2 = now2.strftime('%S.%f')
sec2float = float(sec2)
curSec = sec2float - sec1float
if(sec2float < sec1float):
curSec = (60 - sec1float) + sec2float
if(curSec > 59 and iteration == 1):
minutes = minutes + 1
totalminutes = totalminutes + 1
if(minutes >= 60 and iteration == 1):
hours = hours + 1
minutes = 0
if(hours >= 24 and iteration == 1):
days = days + 1
hours = 0
pool = multiprocessing.Pool(1)
pool.map(createDataFrames())
curSecInt = int(curSec)
if(curSecInt%15 == 0 and iteration == 1 and curSecInt != 60):
currencyIndex = 0
if(iteration >= 3):
iteration = 1
else:
iteration = iteration + 1
print(str(curSec) + ' - seconds')
if(prID == ''):
continue
print(str(minutes) + ' - minutes')
print(str(hours) + ' - hours')
print(str(days) + ' - days')
print('\n')
print(prID)
priceFloat = tempPrice
print(str(priceFloat) + ' - current Price')
firstIteration = True
if(prID == 'BTC-USD'):
if(curSec >= 1):
firstIteration = False
if(curSec < 1):
minuteFirst[prID].append(priceFloat)
if(prID != 'BTC-USD'):
if(curSec < 15):
minuteFirst[prID].append(priceFloat)
def ScheduleChecks():
global sec1float, min1int, hour1int, secfloat
global job1, scheduler
scheduler = BackgroundScheduler()
setUp()
job1 = scheduler.add_job(checkTicker, 'interval', id='priceCheck',seconds =1)
central = timezone('US/Central')
now = datetime.now(central)
startTime=now.strftime("%H:%M:%S.%f")
sec1 = now.strftime('%S.%f')
min1 = now.strftime('%M')
hour1 = now.strftime('%H')
print(min1)
print(sec1)
sec1float = float(sec1) + 1
min1int = int(min1)
hour1int = int(hour1)
if(intervalType == 'S'):
scheduler.start()
time.sleep(intervalLength)
job1.remove()
scheduler.shutdown()
# t1.join()
if(intervalType == 'M'):
scheduler.start()
time.sleep(int(intervalLength*60))
job1.remove()
# t1.join()
if(intervalType == 'H'):
scheduler.start()
sleepvar = (intervalLength*60*60)
sleepvar = sleepvar + (minLength*60)
time.sleep(int(sleepvar))
job1.remove()
scheduler.shutdown()
# t1.join()
def createDataFrames():
central = timezone('US/Central')
now = datetime.now(central)
for cur in currencyIL:
endTime=now.strftime("%D.%H.%M.")
endTime = endTime.replace('/', '.')
curID = cur.split('-')[0]
folderpath = "/home/timbowarrior/"
folderpath2 = folderpath + '/' + curID
filepath = folderpath2 + '.' + endTime
CSVName = filepath + 'MinuteData' + '.csv'
if not os.path.exists(folderpath2):
os.makedirs(folderpath2)
print(CSVName)
Minute = pd.DataFrame(minuteFirst[cur])
Minute.to_csv(CSVName, sep='\t')
t1 = threading.Thread(target=ScheduleChecks)
t1.start()
t1.join()