-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdashboard.py
More file actions
1709 lines (1413 loc) · 80.7 KB
/
Copy pathdashboard.py
File metadata and controls
1709 lines (1413 loc) · 80.7 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#how to run
#writefile will create the file
#we cannot see pylance nor autocompletions when using %%writefile
#conda activate py313
#cd /d D:\OneDrive\Documents\Jupyter_Notebooks\polymarket
#streamlit run dashboard.py
#Libraries & imports used
#System and related
import sys;import inspect;import warnings;import functools;import time;import os;import json;import sqlite3;import datetime;import math
#Data & Data Types
import pandas;import requests;import threading
#Visualization & App
import streamlit;import plotly.express
from streamlit_autorefresh import st_autorefresh
#Global variables
IsExceptionRaised=False
# Decorator definition
def Exec_Decorator_GeneralChecks(TxtVersion:str="1.0",IsLogTimeNeeded:bool=False,TxtNameAuthor:str="Sgdva",TxtNameContributors:str="Sgdva"):
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Checks for the general functions considered for a python and appends the version of it.
:extrainfo:
Only way to know what is considered general, go to this function and read the methods of it. So far we got:
1. Set the version of said function.
2. Execution timing for the routine.
3. Author of function
4. Contributors/forkers of function
--------------
Parameters, Raises & Returns:
--------------
:param TxtVersion: The version of the procedure to run.
:param IsLogTimeNeeded: If we need to log the execution time the routine takes to be performed.
:param TxtNameAuthor: (Optional) The author of the function.
:param TxtNameContributors: (Optional) The contributors of the function.
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: None
:rtype: None
--------------
# Sample data:
N/A
--------------
# How-To-Use:
append @Decorator_GeneralChecks before the function itself
@Exec_Decorator_GeneralChecks(TxtVersion="1.2",IsLogTimeNeeded=True)
def Exec_CopyFile...
print(Exec_CopyFile.__version__)
Exec_CopyFile(TxtToCopyFrom='C:/Users/U1245609/Downloads/Test.txt',TxtLocalPath='C:/Users/U1245609/Downloads/sss/Test.txt')
print(Exec_CopyFile.execution_time)
"""
#End: docstring
global IsExceptionRaised
def Decorator_Function(TxtRoutineToAnalyze):
@functools.wraps(TxtRoutineToAnalyze)
def Decorator_GeneralChecks(*args,**kwargs):
global IsExceptionRaised
TxtCallerFunction= TxtRoutineToAnalyze.__name__;IsExceptionRaised=False
if IsLogTimeNeeded==True: # 1. if IsLogTimeNeeded==True
NumTimeStart = time.perf_counter()
try: # 1. try (General try for the function)
VarResult=TxtRoutineToAnalyze(*args,**kwargs)
return VarResult
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 1. if IsExceptionRaised==True
raise
else: # 1. if IsExceptionRaised==True
#TxtExceptionType = type(ObjException).__name__
#ObjException.__traceback__ = None
#raise ValueError("Err01{}: Unhandled exception. Further Details: Type '{}'. Description: '{}'".format(TxtCallerFunction, TxtExceptionType,str(ObjException)))
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
finally: # 1. try (General try for the function)
if IsLogTimeNeeded==True: # 2. if IsLogTimeNeeded==True
Decorator_GeneralChecks.execution_time = round(time.perf_counter() - NumTimeStart,4)
Decorator_GeneralChecks.__version__ = TxtVersion
return Decorator_GeneralChecks
return Decorator_Function
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
@streamlit.cache_resource
def Return_DictTxtServerCache() -> dict:
#Begin: docstring
"""Information:
--------------
:definitionWID: Returns a cached dictionary object shared across all Streamlit sessions. Used to persist server-level data until restart.
--------------
Parameters, Raises & Returns:
--------------
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: Dictionary with keys 'LastFetch' (float timestamp) and 'Data' (list).
:rtype: dict
--------------
# Sample data:
{"LastFetch": 0.0, "Data": []}
--------------
# How-To-Use:
DictObjCache = Return_DictTxtServerCache()
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try for the function)
return {
"LastFetchEpoch": 0.0,
"Data": [],
# Precomputed display/notification artifacts so reruns are read-only:
"Spikes": [],
"ClosingSoon": [],
"WatchData": [],
"SortedData": [],
"LastFetchISO": "",
"IsFetching": False,
"IsForceRefreshRequested": False,
"LastFetchErr": ""}
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
@streamlit.cache_resource
def Return_DictObjBackgroundWorker() -> dict:
#Begin: docstring
"""Information:
--------------
:definitionWID: Starts a daemon thread background worker that ensures scheduled refresh/update execution.
--------------
Parameters, Raises & Returns:
--------------
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: Dict with StopEvent, Thread object and Lock used for synchronization.
:rtype: dict
--------------
# Sample data:
N/A
--------------
# How-To-Use:
DictObjWorker = Return_DictObjBackgroundWorker()
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name; IsExceptionRaised = False
try: # 1. try (General try)
ObjStopEvent = threading.Event(); ObjLock = threading.Lock()
DictTxtCache = Return_DictTxtServerCache()
def Exec_WorkerLoop():
#Begin: docstring
"""Information:
--------------
:definitionWID: Worker loop that handles scheduled refresh/update execution.
--------------
Parameters, Raises & Returns:
--------------
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: None
:rtype: None
--------------
# Sample data:
N/A
--------------
# How-To-Use:
Exec_WorkerLoop()
"""
#End: docstring
while not ObjStopEvent.is_set(): # 1. while not ObjStopEvent.is_set
try: # 1. try (worker cycle)
DictTxtConfig = Return_DictTxtConfig()
NumUpdateInterval = int(DictTxtConfig.get("NumUpdateInterval", 60))
NumFetchLimit = int(DictTxtConfig.get("NumFetchLimit", 100))
NumVolThreshold = float(DictTxtConfig.get("NumVolThreshold", 2000.0))
ArrTxtWatchlist = DictTxtConfig.get("ArrTxtWatchlist", [])
#Returns the warning 2026-01-25 18:29:13.547 Thread 'PolyOddWatcherWorker': missing ScriptRunContext! This warning can be ignored when running in bare mode.
#More info @ https://discuss.streamlit.io/t/warning-for-missing-scriptruncontext/83893/18
#For the fix we are going to move that call outside the worker loop (and outside the thread), so it runs on the main Streamlit script context only once.
#DictTxtCache = Return_DictTxtServerCache()
NumIntervalSec = max(1.0, NumUpdateInterval * 60.0)
NumNow = time.time(); NumLastFetch = float(DictTxtCache.get("LastFetchEpoch", 0.0))
IsNeverFetched = (NumLastFetch <= 0.0)
IsForceRefresh = bool(DictTxtCache.get("IsForceRefreshRequested", False))
IsTimeUp = IsNeverFetched or ((NumNow - NumLastFetch) >= NumIntervalSec) or (IsForceRefresh == True)
if IsForceRefresh == True: DictTxtCache["IsForceRefreshRequested"] = False
if IsTimeUp == True: # 1. if IsTimeUp == True
with ObjLock: # 1. with ObjLock
NumNow2 = time.time(); NumLastFetch2 = float(DictTxtCache.get("LastFetchEpoch", 0.0))
IsNeverFetched2 = (NumLastFetch2 <= 0.0); IsTimeUp2 = IsNeverFetched2 or ((NumNow2 - NumLastFetch2) >= NumIntervalSec)
if IsTimeUp2 == True: # 2. if IsTimeUp2 == True
try: # 2. try (Fetching data from the server)
DictTxtCache["IsFetching"] = True;DictTxtCache["LastFetchErr"] = ""
ArrDictTxtMarkets = Return_ArrDictTxtMarkets_Core(NumFetchLimit=NumFetchLimit,ArrTxtWatchlistIds=ArrTxtWatchlist)
DictTxtCache["Data"] = ArrDictTxtMarkets;DictTxtCache["LastFetchEpoch"] = time.time();DictTxtCache["LastFetchISO"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if ArrDictTxtMarkets: # 3. if ArrDictTxtMarkets
ArrDictTxtSpikes = Return_ArrDictTxtSuddenSpikes(ArrDictTxtCurrentData=ArrDictTxtMarkets,NumThreshold=NumVolThreshold)
ArrDictTxtClosingSoon = Return_ArrDictTxtClosingSoon(ArrDictTxtCurrentData=ArrDictTxtMarkets)
ArrTxtWatchData = [
ItemData for ItemData in ArrDictTxtMarkets
if str(ItemData.get("id")) in ArrTxtWatchlist or ItemData.get("slug") in ArrTxtWatchlist
]
ArrTxtSortedData = sorted(ArrDictTxtMarkets,key=lambda ItemData: float(ItemData.get("volume", 0)),reverse=True)
DictTxtCache["WatchData"] = ArrTxtWatchData;DictTxtCache["Spikes"] = ArrDictTxtSpikes
DictTxtCache["ClosingSoon"] = ArrDictTxtClosingSoon;DictTxtCache["SortedData"] = ArrTxtSortedData
if DictTxtConfig.get("IsSaveCSV") == True: Exec_SaveToCSV(ArrDictTxtData=ArrDictTxtMarkets)
if DictTxtConfig.get("IsSendTelegramWatchlist") and ArrTxtWatchData: # 4. if DictTxtConfig.get("IsSendTelegramWatchlist") and ArrTxtWatchData
TxtMsg = Return_TxtFormattedMessage("Your Watchlist Updates", ArrTxtWatchData)
Exec_Telegram_SendMsg(TxtBotToken=DictTxtConfig["TxtBotToken"],TxtChatID=DictTxtConfig["TxtChatID"],
TxtMessage=TxtMsg,TxtChatIDThread=DictTxtConfig.get("TxtChatIDThread", ""),IsSendHyperLinks=True)
if DictTxtConfig.get("IsSendTelegramSpikes") and ArrDictTxtSpikes: # 5. if DictTxtConfig.get("IsSendTelegramSpikes") and ArrDictTxtSpikes
TxtMsg = Return_TxtFormattedMessage("Sudden Volume Spikes", ArrDictTxtSpikes)
Exec_Telegram_SendMsg(TxtBotToken=DictTxtConfig["TxtBotToken"],TxtChatID=DictTxtConfig["TxtChatID"],
TxtMessage=TxtMsg,TxtChatIDThread=DictTxtConfig.get("TxtChatIDThread", ""),IsSendHyperLinks=True)
if DictTxtConfig.get("IsSendTelegramClosing") and ArrDictTxtClosingSoon: # 6. if DictTxtConfig.get("IsSendTelegramClosing") and ArrDictTxtClosingSoon
TxtMsg = Return_TxtFormattedMessage("Markets Closing Soon", ArrDictTxtClosingSoon)
Exec_Telegram_SendMsg(TxtBotToken=DictTxtConfig["TxtBotToken"],TxtChatID=DictTxtConfig["TxtChatID"],
TxtMessage=TxtMsg,TxtChatIDThread=DictTxtConfig.get("TxtChatIDThread", ""),IsSendHyperLinks=True)
if DictTxtConfig.get("IsSendTelegramFeed") and ArrTxtSortedData: # 7. if DictTxtConfig.get("IsSendTelegramFeed") and ArrTxtSortedData
TxtMsg = Return_TxtFormattedMessage("Top Market Feed", ArrTxtSortedData)
Exec_Telegram_SendMsg(TxtBotToken=DictTxtConfig["TxtBotToken"],TxtChatID=DictTxtConfig["TxtChatID"],
TxtMessage=TxtMsg,TxtChatIDThread=DictTxtConfig.get("TxtChatIDThread", ""),IsSendHyperLinks=True)
except Exception as ObjException: # 2. try (Fetching data from the server)
DictTxtCache["LastFetchErr"] = str(ObjException)
finally: # 2. try (Fetching data from the server)
DictTxtCache["IsFetching"] = False
for _ in range(30):
if ObjStopEvent.is_set(): break
if bool(DictTxtCache.get("IsForceRefreshRequested", False)) == True: break
time.sleep(1)
except Exception: # 1. try (worker cycle)
time.sleep(5)
ObjThread = threading.Thread(target=Exec_WorkerLoop, name="PolyOddWatcherWorker", daemon=True)
ObjThread.start()
return {"StopEvent": ObjStopEvent, "Thread": ObjThread, "Lock": ObjLock}
except Exception as ObjException: # 1. try (General try)
if IsExceptionRaised == True: # 99. if IsExceptionRaised == True
raise
else: # 99. if IsExceptionRaised == True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction, str(ObjException)))
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Return_NumPruneDB(NumDaysToKeep:int=30) -> int:
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Deletes records older than NumDaysToKeep.
--------------
Parameters, Raises & Returns:
--------------
:param NumDaysToKeep: The number of days to keep records for.
:raises ValueError:[1] If an unhandled exception occurs. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: Number of records deleted.
:rtype: int
--------------
# Sample data:
N/A.
--------------
# How-To-Use:
NumDeleted=Return_NumPruneDB(NumDaysToKeep=30)
"""
#End: docstring
global IsExceptionRaised
try:
ObjConn = sqlite3.connect("market_history.db")
ObjCursor = ObjConn.cursor()
# Calculate Threshold Date
ObjThresholdDate = datetime.datetime.now() - datetime.timedelta(days=NumDaysToKeep)
TxtThresholdIso = ObjThresholdDate.isoformat()
# Execute Delete
ObjCursor.execute("DELETE FROM vol_history WHERE last_updated < ?", (TxtThresholdIso,))
NumDeleted = ObjCursor.rowcount
ObjConn.commit(); ObjCursor.close(); ObjConn.close()
return NumDeleted
except Exception as e:
if IsExceptionRaised: raise
else: raise ValueError(f"Prune DB Failed: {e}")
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Exec_SaveToCSV(ArrDictTxtData:list,TxtFilename:str="market_data_log.csv"):
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Appends the current market data snapshot to a CSV log file for future analysis.
Adds a timestamp to every row to allow time-series analysis.
:note: FLATTENS the data structure. Instead of dumping raw JSON, it extracts specific Market/Outcome rows for easier analysis in Excel/AI.
--------------
Parameters, Raises & Returns:
--------------
:param ArrDictTxtData: The list of dictionaries containing current market events.
:param TxtFilename: The name of the CSV file to save the data to.
:raises ValueError:[1] If an unhandled exception occurs. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: None
:rtype: None
--------------
# Sample data:
N/A
--------------
# How-To-Use:
Exec_SaveToCSV(ArrDictTxtData=ArrDictTxtData)
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try)
if not ArrDictTxtData: # 1. if No Data
return
ArrDictTxtCleanRows = []
TxtTimestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for ItemDictEvent in ArrDictTxtData: # 1. for ItemDictEvent
# Extract Top-Level Event Data
TxtEventTitle = ItemDictEvent.get('title', '')
TxtEventID = str(ItemDictEvent.get('id', ''))
# The 'markets' key contains the actual betting options. We must loop through them.
ArrDictMarkets = ItemDictEvent.get('markets', [])
for ItemDictMarket in ArrDictMarkets: # 2. for ItemDictMarket
# Extract Specific Market Data
TxtGroupTitle = ItemDictMarket.get('groupItemTitle', '') # Used in grouped markets (e.g. "January", "February")
TxtQuestion = ItemDictMarket.get('question', '')
# If GroupTitle exists, append it to Title for clarity (e.g. "Trump Deportation - <250k")
if TxtGroupTitle and str(TxtGroupTitle).strip() != "": # 2. if TxtGroupTitle
TxtFullTitle = "{} - {}".format(TxtEventTitle, TxtGroupTitle)
else: # 2. else
TxtFullTitle = TxtEventTitle
# Parse Prices safely
try: # 2. try (Parse Odds)
ArrTxtOutcomes = json.loads(ItemDictMarket.get('outcomes', '[]'))
ArrNumPrices = json.loads(ItemDictMarket.get('outcomePrices', '[]'))
except: # 2. except (Parse Odds)
ArrTxtOutcomes = []; ArrNumPrices = []
# Create a serialized string for easy AI parsing later: "Yes:0.55|No:0.45"
ArrTxtOddsSummary = []
for NumIndex in range(len(ArrTxtOutcomes)): # 3. for NumIndex
if NumIndex < len(ArrNumPrices): # 3. if valid index
ArrTxtOddsSummary.append("{}:{}".format(ArrTxtOutcomes[NumIndex], ArrNumPrices[NumIndex]))
TxtOddsStr = "|".join(ArrTxtOddsSummary)
# Build the Clean Row
DictCleanRow = {
"LogTimestamp": TxtTimestamp,
"EventID": TxtEventID,
"MarketID": str(ItemDictMarket.get('id', '')),
"FullTitle": TxtFullTitle,
"RawQuestion": TxtQuestion,
"Volume": float(ItemDictMarket.get('volume', 0)),
"Liquidity": float(ItemDictMarket.get('liquidity', 0)),
"OddsSummary": TxtOddsStr,
"BestAsk": float(ItemDictMarket.get('bestAsk', 0)),
"BestBid": float(ItemDictMarket.get('bestBid', 0)),
"EndDate": ItemDictMarket.get('endDate', ''),
"URL": "https://polymarket.com/event/" + str(ItemDictEvent.get('slug', ''))
}
ArrDictTxtCleanRows.append(DictCleanRow)
# Create DataFrame from the CLEAN rows
if ArrDictTxtCleanRows: # 4. if ArrDictTxtCleanRows
dfLog = pandas.DataFrame(ArrDictTxtCleanRows)
# Check if file exists to write header
IsHeaderNeeded = not os.path.exists(TxtFilename)
# Append to CSV (mode='a') used to add new data to the end of an existing CSV file without overwriting its current conten
dfLog.to_csv(TxtFilename, mode='a', header=IsHeaderNeeded, index=False)
except Exception as ObjException: # 1. try (General try)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
# --- COMMUNICATION FUNCTIONS ---
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Exec_Telegram_SendMsg(TxtBotToken:str,TxtChatID:str,TxtMessage:str,TxtChatIDThread:str="",IsSendHyperLinks:bool=False):
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Sends a telegram message to the specified TxtChatID with the TxtBotToken given.
:links:
For more information, refer to the Telegram Bot API documentation:
- [Telegram Bot API](https://core.telegram.org/bots/api#sendmessage)
--------------
Parameters, Raises & Returns:
--------------
:param TxtBotToken: The token given by botfather for the bot, the format is like xxxx:xxxx.
:param TxtChatID: The chat id the bot will be interacting to, to identify it, begin a chat with the bot, access to the url (IE: https://api.telegram.org/botxxx:xxxx/) to see the updates requested and detect the chatID.
:param TxtMessage: it needs to be a text greater than 0 and less or equal to 4096 characters.
:param TxtChatIDThread: (Optional) If there is a specific thread the bot should send the message to, it will be specified here.
:param IsSendHyperLinks: (Optional) If the message should include hyperlinks, it will be specified here.
:param VarVerify: It can be either a boolean to turn on/off SSL verification, or can be the path to the pem certificate file. - [Requests documents](https://requests.readthedocs.io/en/latest/user/advanced/)
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:raises ValueError:[2] If the length of TxtMessage is less than 1 or greater than 4096 characters.
:raises ValueError:[3,4] If VarVerify is neither a bool or a valid string path.
:raises requests.exceptions.RequestException:[1] If telegram request had an error code.
:return: None
:rtype: None
--------------
# Sample data:
N/A
--------------
# How-To-Use:
Exec_Telegram_SendMsg(TxtBotToken="xxx:xxx",TxtChatID=-40965627,TxtMessage="Test")
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try
if len(TxtMessage)<1: raise ValueError("Empty Message")
TxtUrl = f'https://api.telegram.org/bot{TxtBotToken}/sendMessage'
DictTxtData = {'chat_id': TxtChatID,'text': TxtMessage}
if IsSendHyperLinks==True: # 1. if IsSendHyperLinks==True
DictTxtData['parse_mode'] = 'HTML';DictTxtData['disable_web_page_preview'] = True
if TxtChatIDThread and str(TxtChatIDThread).strip() != "": # 2. if TxtChatIDThread and str(TxtChatIDThread).strip() != ""
DictTxtData['message_thread_id'] = TxtChatIDThread
ObjResponse = requests.post(url=TxtUrl, data=DictTxtData)
JSONResponse = ObjResponse.json()
if JSONResponse.get("ok") == False: # 3. if JSONResponse.get("ok") == False
IsExceptionRaised=True;raise requests.exceptions.RequestException(f"Telegram Error: {JSONResponse.get('description')}")
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
# --- DATABASE & CONFIG FUNCTIONS ---
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Exec_InitDB(TxtDBPath:str="market_history.db"):
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Initializes the SQLite database to store market history. Checks for table existence and attempts schema migration if necessary.
--------------
Parameters, Raises & Returns:
--------------
:param TxtDBPath: (Optional) Path to the SQLite database file. Default is "market_history.db".
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: None
:rtype: None
--------------
# Sample data:
N/A. Architecture specific.
--------------
# How-To-Use:
Exec_InitDB()
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try for the function)
ObjConn = sqlite3.connect(TxtDBPath)
ObjCursor = ObjConn.cursor()
ObjCursor.execute('''
CREATE TABLE IF NOT EXISTS vol_history (
market_id TEXT PRIMARY KEY,
title TEXT,
last_volume REAL,
last_odds TEXT,
last_updated TEXT
)
''')
try: ObjCursor.execute("ALTER TABLE vol_history ADD COLUMN last_odds TEXT")
except: pass
ObjConn.commit(); ObjCursor.close(); ObjConn.close()
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction, str(ObjException)))
#End: ValueError:[1]
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Return_DictTxtConfig() -> dict:
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Loads configuration from JSON file 'config.json'. Returns empty dict if not found or error.
--------------
Parameters, Raises & Returns:
--------------
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: Dictionary containing configuration.
:rtype: dict
--------------
# Sample data:
N/A. Architecture specific.
--------------
# How-To-Use:
DictConfig = Return_DictTxtConfig()
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try for the function)
if os.path.exists("config.json"): # 1. if os.path.exists("config.json")
with open("config.json", "r") as ObjFile:
return json.load(ObjFile)
return {}
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Exec_SaveConfig(DictConfig:dict):
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Saves the configuration dictionary to 'config.json'.
--------------
Parameters, Raises & Returns:
--------------
:param DictConfig: The dictionary containing configuration settings.
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: None
:rtype: None
--------------
# Sample data:
N/A. Architecture specific.
--------------
# How-To-Use:
Exec_SaveConfig(DictConfig=DictConfig)
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try for the function)
with open("config.json", "w") as ObjFile: # 1. with open("config.json", "w") as ObjFile
json.dump(DictConfig, ObjFile)
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
# --- HELPER FUNCTIONS (FORMATTING) ---
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Return_TxtHumanVolume(NumVolume:float) -> str:
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Formats numbers to K/M/B.
--------------
Parameters, Raises & Returns:
--------------
:param NumVolume: The volume to format.
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: The formatted volume.
:rtype: str
--------------
# Sample data:
NumVolume=1000000
--------------
# How-To-Use:
TxtHumanVolume=Return_TxtHumanVolume(NumVolume=NumVolume)
Expected: '1M'
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try for the function)
if NumVolume >= 1_000_000_000: # 1. if NumVolume >= 1B
return "${:.2f}B".format(NumVolume/1_000_000_000)
elif NumVolume >= 1_000_000: # 1. if NumVolume >= 1B
return "${:.2f}M".format(NumVolume/1_000_000)
elif NumVolume >= 1_000: # 1. if NumVolume >= 1B
return "${:.0f}K".format(NumVolume/1_000)
else: # 1. if NumVolume >= 1B
return "${:.0f}".format(NumVolume)
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Return_TxtMultiOutcomeOdds(ItemEvent:dict, TxtPrevOdds:str="") -> str:
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Returns Full Odds Breakdown sorted by chance with Delta Trends. Calculates trends if previous odds are provided.
--------------
Parameters, Raises & Returns:
--------------
:param ItemEvent: The event dictionary containing market data.
:param TxtPrevOdds: (Optional) String representing previous odds (format: "Name:Price|Name:Price") for trend calculation.
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: Formatted string with odds and trends.
:rtype: str
--------------
# Sample data:
N/A. Architecture specific.
--------------
# How-To-Use:
TxtMultiOutcomeOdds=Return_TxtMultiOutcomeOdds(ItemEvent=ItemEvent,TxtPrevOdds=TxtPrevOdds)
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try for the function)
ArrDictTxtMarkets = ItemEvent.get('markets', [])
ArrTxtCandidates = []
# Parse Previous Odds
DictTxtPrevOdds = {}
if str(TxtPrevOdds).strip() != "": # 1. if str(TxtPrevOdds).strip() != ""
try: # 2. try (Parse history)
ArrTxtParts = TxtPrevOdds.split("|")
for ItemTxtPart in ArrTxtParts: # 1. for TxtPart in ArrTxtParts
TxtKey, TxtVal = ItemTxtPart.split(":")
DictTxtPrevOdds[TxtKey] = float(TxtVal)
except: # 2. try (Parse history)
pass
# Logic A: Multiple Markets (Grouped)
for ItemMarket in ArrDictTxtMarkets: # 2. for ItemMarket in ArrDictTxtMarkets
if ItemMarket.get('closed') == True: # 2. if ItemMarket.get('closed') == True
continue
TxtGroupTitle = ItemMarket.get('groupItemTitle', '')
try: # 3. try (Parse prices and outcomes)
ArrNumPrices = json.loads(ItemMarket.get('outcomePrices', '["0","0"]'))
ArrTxtOutcomes = json.loads(ItemMarket.get('outcomes', '["Yes","No"]'))
except: # 3. try (Parse prices and outcomes)
ArrNumPrices = ["0", "0"]; ArrTxtOutcomes = ["Yes", "No"]
TxtName = ""; NumPrice = 0.0
if TxtGroupTitle and len(ArrNumPrices) >= 1: # 3. if TxtGroupTitle and len(ArrNumPrices) >= 1
TxtName = TxtGroupTitle
NumPrice = float(ArrNumPrices[0])
elif len(ArrTxtOutcomes) > 2: # 3. if TxtGroupTitle and len(ArrNumPrices) >= 1
for CounterArrTxtOutcomes in range(len(ArrTxtOutcomes)): # 3. for CounterArrTxtOutcomes in range(len(ArrTxtOutcomes))
ArrTxtCandidates.append({"Name": ArrTxtOutcomes[CounterArrTxtOutcomes], "Price": float(ArrNumPrices[CounterArrTxtOutcomes])})
continue
elif len(ArrTxtOutcomes) == 2 and not TxtGroupTitle: # 3. if TxtGroupTitle and len(ArrNumPrices) >= 1
TxtName = "Yes"; NumPrice = float(ArrNumPrices[0])
if TxtName: # 4. if TxtName
ArrTxtCandidates.append({"Name": TxtName, "Price": NumPrice})
# Sort by Price Descending
ArrTxtCandidates = sorted(ArrTxtCandidates, key=lambda ItemCandidate: ItemCandidate['Price'], reverse=True)
# Build Rich String
ArrTxtFormatted = []
for ItemCandidate in ArrTxtCandidates: # 4. for ItemCandidate in ArrTxtCandidates
NumYes = ItemCandidate['Price']; NumNo = 1.0 - NumYes
# Trend Calculation
TxtTrend = "(➖)"
if ItemCandidate['Name'] in DictTxtPrevOdds: # 5. if History
NumPrev = DictTxtPrevOdds[ItemCandidate['Name']]
NumDiff = NumYes - NumPrev
if abs(NumDiff) >= 0.005: # 6. if abs(NumDiff) >= 0.005
if NumDiff > 0: # 7. if NumDiff > 0
TxtTrend = "🔼{:.0%}".format(abs(NumDiff))
else: # 8. if NumDiff > 0
TxtTrend = "🔽{:.0%}".format(abs(NumDiff))
# Format: ▶Name 🟢Yes X% 🔴No Y% Trend
TxtStr = "▶{}: 🟢Yes {:.0%} 🔴No {:.0%} {}".format(ItemCandidate['Name'], NumYes, NumNo, TxtTrend)
ArrTxtFormatted.append(TxtStr)
if not ArrTxtFormatted: # 9. if not ArrTxtFormatted
return "No active odds"
return " | ".join(ArrTxtFormatted)
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Return_TxtOddsForDB(ItemMarket:dict) -> str:
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Serializes market odds into a string format for database storage.
--------------
Parameters, Raises & Returns:
--------------
:param ItemMarket: The market dictionary containing odds data.
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: A serialized string of odds (e.g., "Yes:0.5|No:0.5").
:rtype: str
--------------
# Sample data:
N/A. Architecture specific.
--------------
# How-To-Use:
TxtOddsForDB = Return_TxtOddsForDB(ItemMarket)
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
try: # 1. try (General try for the function)
ArrDictTxtMarkets = ItemMarket.get('markets', [])
ArrTxtSerialized = []
for ItemSubMarket in ArrDictTxtMarkets: # 1. for ItemSubMarket in ArrDictTxtMarkets
if ItemSubMarket.get('closed') == True: # 1. if ItemSubMarket.get('closed') == True
continue
TxtGroupTitle = ItemSubMarket.get('groupItemTitle', '')
try: # 2. try (Safe JSON load)
ArrNumPrices = json.loads(ItemSubMarket.get('outcomePrices', '["0","0"]'))
except: # 2. try (Safe JSON load)
ArrNumPrices = ["0", "0"]
if TxtGroupTitle and len(ArrNumPrices) >= 1: # 2. if TxtGroupTitle and len(ArrNumPrices) >= 1
ArrTxtSerialized.append("{}:{}".format(TxtGroupTitle, ArrNumPrices[0]))
elif not TxtGroupTitle: # 2. if TxtGroupTitle and len(ArrNumPrices) >= 1
try: # 3. try (Safe JSON load)
ArrTxtOutcomes = json.loads(ItemSubMarket.get('outcomes', '["Yes","No"]'))
except: # 3. try (Safe JSON load)
ArrTxtOutcomes = ["Yes", "No"]
for CounterArrTxtOutcomes in range(len(ArrTxtOutcomes)): # 2. for CounterArrTxtOutcomes in range(len(ArrTxtOutcomes))
if CounterArrTxtOutcomes < len(ArrNumPrices): # 3. if CounterArrTxtOutcomes < len(ArrNumPrices)
ArrTxtSerialized.append("{}:{}".format(ArrTxtOutcomes[CounterArrTxtOutcomes], ArrNumPrices[CounterArrTxtOutcomes]))
return "|".join(ArrTxtSerialized)
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
raise
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
# --- CORE LOGIC FUNCTIONS ---
@streamlit.cache_data(ttl=60)
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Return_ArrDictTxtMarkets(NumFetchLimit:int=100, ArrTxtWatchlistIds:list=[]) -> list:
return Return_ArrDictTxtMarkets_Core(NumFetchLimit=NumFetchLimit, ArrTxtWatchlistIds=ArrTxtWatchlistIds)
def Return_ArrDictTxtMarkets_Core(NumFetchLimit:int=100, ArrTxtWatchlistIds:list=[]) -> list:
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Fetches active market events via pagination and specific watchlist lookup.
--------------
Parameters, Raises & Returns:
--------------
:param NumFetchLimit: Limit for the broad fetch of active markets.
:param ArrTxtWatchlistIds: List of IDs or Slugs to specifically hunt for.
:raises ValueError:[1] If an unhandled exception occurs during execution.
:return: A list of unique market event dictionaries.
:rtype: list
--------------
# Sample data:
N/A. Architecture specific.
--------------
# How-To-Use:
Return_ArrDictTxtMarkets_Core = Return_ArrDictTxtMarkets_Core()
"""
#End: docstring
global IsExceptionRaised
TxtCallerFunction = inspect.currentframe().f_code.co_name;IsExceptionRaised=False
ArrJSONCombinedData = []
try: # 1. try (General try for the function)
# 1. Paginated Broad Fetch
NumOffset = 0; NumBatchSize = 100
while len(ArrJSONCombinedData) < NumFetchLimit: # 1. while len(ArrJSONCombinedData) < NumFetchLimit
try: # 2. try (Fetch batch)
TxtBaseUrl = "https://gamma-api.polymarket.com/events?limit={}&active=true&closed=false&offset={}".format(NumBatchSize, NumOffset)
ObjResponse = requests.get(TxtBaseUrl)
ObjResponse.raise_for_status()
ArrJSONBatch = ObjResponse.json()
if not ArrJSONBatch: # 1. if not ArrJSONBatch
break
ArrJSONCombinedData.extend(ArrJSONBatch)
NumOffset += NumBatchSize
if len(ArrJSONCombinedData) >= NumFetchLimit: # 2. if len(ArrJSONCombinedData) >= NumFetchLimit
ArrJSONCombinedData = ArrJSONCombinedData[:NumFetchLimit];break
time.sleep(0.05)
except Exception: # 2. try (Fetch batch)
break
# 2. Hunt for Missing Watchlist Items
if len(ArrTxtWatchlistIds) > 0: # 3. if len(ArrTxtWatchlistIds) > 0
for TxtWatchId in ArrTxtWatchlistIds: # 1. for TxtWatchId in ArrTxtWatchlistIds
if len(TxtWatchId.strip()) > 0: # 4. if len(TxtWatchId.strip()) > 0
try: # 3. try (Fetch watchlist item)
TxtTarget = TxtWatchId.strip()
# Check if already present in broadly fetched data
IsAlreadyFound = any(str(ItemData.get('id')) == TxtTarget or ItemData.get('slug') == TxtTarget for ItemData in ArrJSONCombinedData)
if not IsAlreadyFound: # 5. if not IsAlreadyFound
# Try fetching by Slug first
TxtWatchUrl = "https://gamma-api.polymarket.com/events?slug={}".format(TxtTarget)
ObjWatchResponse = requests.get(TxtWatchUrl)
if ObjWatchResponse.status_code == 200: # 6. if ObjWatchResponse.status_code == 200
ArrJSONResult = ObjWatchResponse.json()
if isinstance(ArrJSONResult, list): # 7. if isinstance(ArrJSONResult, list)
ArrJSONCombinedData.extend(ArrJSONResult)
else: # 7. if isinstance(ArrJSONResult, list)
ArrJSONCombinedData.append(ArrJSONResult)
else: # 6. if ObjWatchResponse.status_code == 200
# Fallback: Try fetching by ID
TxtDirectUrl = "https://gamma-api.polymarket.com/events/{}".format(TxtTarget)
ObjDirectRes = requests.get(TxtDirectUrl)
if ObjDirectRes.status_code == 200: # 8. if ObjDirectRes.status_code == 200
ArrJSONCombinedData.append(ObjDirectRes.json())
except: # 3. try (Fetch watchlist item)
pass
# Remove duplicates based on ID
DictTxtUniqueRecords = {ItemData['id']: ItemData for ItemData in ArrJSONCombinedData if 'id' in ItemData}
return list(DictTxtUniqueRecords.values())
except Exception as ObjException: # 1. try (General try for the function)
#Begin: ValueError:[1]
if IsExceptionRaised==True: # 99. if IsExceptionRaised==True
return [] # Specific return for this function as per user code logic
else: # 99. if IsExceptionRaised==True
raise ValueError("Err01{}: Unhandled exception. Further Details: '{}'".format(TxtCallerFunction,str(ObjException)))
#End: ValueError:[1]
@Exec_Decorator_GeneralChecks(TxtVersion="1.0")
def Return_ArrDictTxtSuddenSpikes(ArrDictTxtCurrentData:list, NumThreshold:float=2000.0) -> list:
#Begin: docstring
"""Information:
--------------
--------------
:definitionWID: Returns a list of sudden spikes based on volume.
--------------
Parameters, Raises & Returns:
--------------
:param ArrDictTxtCurrentData: List of current market data.
:param NumThreshold: Threshold for volume.
:raises ValueError:[1] If an unhandled exception occurs during execution. How to get the log? ExceptionLog: except ValueError as TxtExceptionValueError
:return: A list of unique market event dictionaries.
:rtype: list
--------------
# Sample data:
N/A. Architecture specific.
--------------
# How-To-Use:
ArrDictTxtSuddenSpikes = Return_ArrDictTxtSuddenSpikes(ArrDictTxtCurrentData=ArrDictTxtCurrentData)
"""
#End: docstring