solanaexpert commited on
Commit
4ef32b8
1 Parent(s): 929e939

Upload 10 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ BTC_USDT_15m_2020-01-01_2024-07-25.csv filter=lfs diff=lfs merge=lfs -text
37
+ BTC_USDT_1m_2020-01-01_2024-07-25.csv filter=lfs diff=lfs merge=lfs -text
38
+ BTC_USDT_5m_2020-01-01_2024-07-25.csv filter=lfs diff=lfs merge=lfs -text
20240726_080540_1d_greatest_candles.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Prediction for BTC (USDT):
2
+ - Last Timestamp: 1970-01-01 00:51:30
3
+ - Predicted Value: 64903.8037
4
+
5
+ Date heure prédiction environs 26/07/2024 10h25 : Cours actuel = 67080
6
+ https://www.tradingview.com/x/LWmnhQFi/
7
+
8
+
9
+
10
+
11
+
12
+ gitpod /workspace/CryptoForex-Trader-Framework/CCXT_ICHIMOKU (main) $ cd julie_scanner/
13
+ gitpod /workspace/CryptoForex-Trader-Framework/CCXT_ICHIMOKU/julie_scanner (main) $ python bluewenne8.py --timeframe 1d --train
14
+ Training model using the following BTC-related files:
15
+ - downloaded_history/BTC_USDT_15m_2020-01-01_2024-07-25.csv
16
+ - downloaded_history/BTC_USDT_1d_2020-01-01_2024-07-25.csv
17
+ - downloaded_history/BTC_USDT_1h_2020-01-01_2024-07-25.csv
18
+ - downloaded_history/BTC_USDT_1m_2020-01-01_2024-07-25.csv
19
+ - downloaded_history/BTC_USDT_4h_2020-01-01_2024-07-25.csv
20
+ - downloaded_history/BTC_USDT_5m_2020-01-01_2024-07-25.csv
21
+ Model trained. RMSE: 77.3184
22
+ gitpod /workspace/CryptoForex-Trader-Framework/CCXT_ICHIMOKU/julie_scanner (main) $ python bluewenne8.py --timeframe 1d --use-existing
23
+ Using the following BTC-related files for prediction:
24
+ - downloaded_history/BTC_USDT_15m_2020-01-01_2024-07-25.csv
25
+ - downloaded_history/BTC_USDT_1d_2020-01-01_2024-07-25.csv
26
+ - downloaded_history/BTC_USDT_1h_2020-01-01_2024-07-25.csv
27
+ - downloaded_history/BTC_USDT_1m_2020-01-01_2024-07-25.csv
28
+ - downloaded_history/BTC_USDT_4h_2020-01-01_2024-07-25.csv
29
+ - downloaded_history/BTC_USDT_5m_2020-01-01_2024-07-25.csv
30
+ gitpod /workspace/CryptoForex-Trader-Framework/CCXT_ICHIMOKU/julie_scanner (main) $
31
+
BTC_USDT_15m_2020-01-01_2024-07-25.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ece2e5e706f3ecaca7dbeaeb0126c879532c232d911381269d967240b6cd7346
3
+ size 10583706
BTC_USDT_1d_2020-01-01_2024-07-25.csv ADDED
The diff for this file is too large to render. See raw diff
 
BTC_USDT_1h_2020-01-01_2024-07-25.csv ADDED
The diff for this file is too large to render. See raw diff
 
BTC_USDT_1m_2020-01-01_2024-07-25.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:caa7fcf77ec4172e8afbf5aa9027c85273039d6d3f1562b0a184a64c9abf4aaa
3
+ size 156083703
BTC_USDT_4h_2020-01-01_2024-07-25.csv ADDED
The diff for this file is too large to render. See raw diff
 
BTC_USDT_5m_2020-01-01_2024-07-25.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d223f6e48d10b29965c158d33d067b88f89e78b4771311a733d5524b7fe39c32
3
+ size 31538522
bluewenne8.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ccxt
2
+ import sys
3
+ import os
4
+ import argparse
5
+ import time
6
+ from datetime import datetime, timezone
7
+ import pytz
8
+ import threading
9
+ import csv
10
+ import pandas as pd
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.ensemble import RandomForestRegressor
13
+ from sklearn.preprocessing import StandardScaler
14
+ from sklearn.metrics import mean_squared_error
15
+ import joblib
16
+
17
+ def fetch_markets(exchange):
18
+ try:
19
+ markets = exchange.fetch_markets()
20
+ symbols = [market['symbol'] for market in markets if market['spot'] and market['symbol'].endswith('/USDT')]
21
+ return symbols
22
+ except (ccxt.ExchangeError, ccxt.NetworkError, ccxt.DDoSProtection) as e:
23
+ print(f"Exchange error: {str(e)}")
24
+ os.kill(os.getpid(), 9)
25
+ sys.exit(-999)
26
+
27
+ def fetch_ohlcv(exchange, symbol, timeframe, limit=1000):
28
+ try:
29
+ all_candles = []
30
+ since = exchange.parse8601('2020-01-01T00:00:00Z') # Start date can be adjusted
31
+ while True:
32
+ candles = exchange.fetch_ohlcv(symbol, timeframe, since=since, limit=limit)
33
+ if not candles:
34
+ break
35
+ all_candles.extend(candles)
36
+ since = candles[-1][0] + 1
37
+ if len(candles) < limit:
38
+ break
39
+ return all_candles
40
+ except Exception as e:
41
+ print(f"Error fetching OHLCV data for {symbol}: {str(e)}")
42
+ return []
43
+
44
+ def fetch_current_price(exchange, symbol):
45
+ try:
46
+ ticker = exchange.fetch_ticker(symbol)
47
+ return ticker['ask'] if 'ask' in ticker else None
48
+ except Exception as e:
49
+ print(f"Error fetching current price for {symbol}: {str(e)}")
50
+ return None
51
+
52
+ def format_candle_time(timestamp):
53
+ return datetime.fromtimestamp(timestamp / 1000, tz=timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
54
+
55
+ def save_history_to_file(symbol, timeframe, ohlcv):
56
+ directory = "downloaded_history"
57
+ if not os.path.exists(directory):
58
+ os.makedirs(directory)
59
+
60
+ if not ohlcv:
61
+ print(f"No OHLCV data to save for {symbol}")
62
+ return
63
+
64
+ start_date = format_candle_time(ohlcv[0][0]).split()[0]
65
+ end_date = format_candle_time(ohlcv[-1][0]).split()[0]
66
+ filename = (f"{directory}/{symbol.replace('/', '_')}_{timeframe}_{start_date}_{end_date}.csv").replace(" ", "_").replace(":", "-")
67
+
68
+ with open(filename, 'w', newline='') as csvfile:
69
+ writer = csv.writer(csvfile)
70
+ writer.writerow(['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume'])
71
+ for candle in ohlcv:
72
+ timestamp, open_price, high_price, low_price, close_price, volume = candle
73
+ writer.writerow([format_candle_time(timestamp), open_price, high_price, low_price, close_price, volume])
74
+
75
+ print(f"Saved history to {filename}")
76
+
77
+ def load_data_from_files(directory, symbol_filter=None):
78
+ all_data = []
79
+ filenames = []
80
+ for filename in os.listdir(directory):
81
+ if filename.endswith(".csv"):
82
+ if symbol_filter and not filename.startswith(symbol_filter):
83
+ continue # Skip files that do not start with the symbol filter
84
+ filepath = os.path.join(directory, filename)
85
+ df = pd.read_csv(filepath)
86
+ df['symbol'] = filename.split('_')[0] # Adjust this if your filenames have different formats
87
+ timeframe = filename.split('_')[1] # Extract timeframe from filename
88
+ df['Timeframe'] = timeframe
89
+ all_data.append(df)
90
+ filenames.append(filepath)
91
+ return pd.concat(all_data, ignore_index=True) if all_data else pd.DataFrame(), filenames
92
+
93
+ def preprocess_data(df):
94
+ df['Timestamp'] = pd.to_datetime(df['Timestamp'])
95
+ df.set_index('Timestamp', inplace=True)
96
+ df.sort_index(inplace=True)
97
+ df['Target'] = df['Close'].shift(-1)
98
+ df.dropna(inplace=True)
99
+
100
+ X = df[['Open', 'High', 'Low', 'Close', 'Volume']]
101
+ y = df['Target']
102
+
103
+ return X, y
104
+
105
+ def train_model(X, y):
106
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
107
+ scaler = StandardScaler()
108
+ X_train_scaled = scaler.fit_transform(X_train)
109
+ X_test_scaled = scaler.transform(X_test)
110
+
111
+ model = RandomForestRegressor(n_estimators=100, random_state=42)
112
+ model.fit(X_train_scaled, y_train)
113
+
114
+ y_pred = model.predict(X_test_scaled)
115
+ mse = mean_squared_error(y_test, y_pred)
116
+ rmse = mse**0.5
117
+ print(f"Model trained. RMSE: {rmse:.4f}")
118
+
119
+ return model, scaler
120
+
121
+ def predict_next_candle(model, scaler, data):
122
+ data_scaled = scaler.transform(data[['Open', 'High', 'Low', 'Close', 'Volume']])
123
+ prediction = model.predict(data_scaled)
124
+ return prediction
125
+
126
+ def analyze_symbol(exchange, symbol, timeframe, output_file):
127
+ try:
128
+ ohlcv = fetch_ohlcv(exchange, symbol, timeframe)
129
+ if not ohlcv:
130
+ return
131
+
132
+ save_history_to_file(symbol, timeframe, ohlcv)
133
+
134
+ max_candle = max(ohlcv, key=lambda x: x[2] - x[3])
135
+ open_price = max_candle[1]
136
+ close_price = max_candle[4]
137
+ highest_price = max_candle[2]
138
+ lowest_price = max_candle[3]
139
+ timestamp = max_candle[0]
140
+ candle_date_time = format_candle_time(timestamp)
141
+
142
+ greatest_candle_info = (
143
+ f"Symbol: {symbol}, Timeframe: {timeframe}, "
144
+ f"Open: {open_price:.4f}, Close: {close_price:.4f}, "
145
+ f"High: {highest_price:.4f}, Low: {lowest_price:.4f}, "
146
+ f"Range: {highest_price - lowest_price:.4f}, "
147
+ f"Greatest Candle DateTime: {candle_date_time}\n"
148
+ )
149
+
150
+ current_price = fetch_current_price(exchange, symbol)
151
+ if current_price is None:
152
+ return
153
+
154
+ current_time = datetime.now(pytz.UTC).strftime('%Y-%m-%d %H:%M:%S')
155
+ result = (
156
+ f"[{current_time}] {symbol} (BINANCE:{symbol.replace('/', '')}) "
157
+ f"Timeframe: {timeframe}, Current price: {current_price:.4f}\n"
158
+ f"{greatest_candle_info}\n"
159
+ )
160
+ print(result.strip())
161
+
162
+ with open(output_file, 'a') as f:
163
+ f.write(result)
164
+
165
+ except Exception as e:
166
+ print(f"Error analyzing symbol {symbol}: {str(e)}")
167
+
168
+ def write_predictions_to_file(output_file, predictions):
169
+ with open(output_file, 'a') as f:
170
+ for symbol, last_timestamp, timeframe, prediction in predictions:
171
+ # Convert integer timestamp to datetime if needed
172
+ if isinstance(last_timestamp, int):
173
+ last_timestamp = datetime.fromtimestamp(last_timestamp / 1000, tz=timezone.utc)
174
+
175
+ last_timestamp_str = last_timestamp.strftime('%Y-%m-%d %H:%M:%S')
176
+ f.write(f"Prediction for {symbol} ({timeframe}):\n")
177
+ f.write(f"- Last Timestamp: {last_timestamp_str}\n")
178
+ f.write(f"- Predicted Value: {prediction[-1]:.4f}\n") # Show the last prediction value
179
+ f.write("\n")
180
+
181
+ def worker(exchange, symbols, timeframe, output_file):
182
+ for symbol in symbols:
183
+ if symbol in fetch_markets(exchange):
184
+ analyze_symbol(exchange, symbol, timeframe, output_file)
185
+ else:
186
+ print(f"Skipping invalid symbol {symbol}")
187
+
188
+ def main():
189
+ parser = argparse.ArgumentParser(description='Show details of the greatest historical candle, save historical data, and train a model.')
190
+ parser.add_argument('--timeframe', type=str, required=True, help='Timeframe for the candlestick analysis')
191
+ parser.add_argument('--train', action='store_true', help='Train model using existing historical data')
192
+ parser.add_argument('--use-existing', action='store_true', help='Use existing historical data files')
193
+ args = parser.parse_args()
194
+
195
+ timeframe = args.timeframe
196
+ train_model_flag = args.train
197
+ use_existing_flag = args.use_existing
198
+ script_name = os.path.basename(__file__).split('.')[0]
199
+ result_directory = f"scan_results_{script_name}"
200
+
201
+ if not os.path.exists(result_directory):
202
+ os.makedirs(result_directory)
203
+
204
+ output_file = os.path.join(result_directory, f"{datetime.now(pytz.UTC).strftime('%Y%m%d_%H%M%S')}_{timeframe}_greatest_candles.txt")
205
+
206
+ if train_model_flag:
207
+ historical_data_dir = "downloaded_history"
208
+ symbol_filter = 'BTC_USDT' # Filter files that start with BTC_USDT
209
+ df, filenames = load_data_from_files(historical_data_dir, symbol_filter)
210
+ if df.empty:
211
+ print("No historical data found for training.")
212
+ return
213
+
214
+ print("Training model using the following BTC-related files:")
215
+ for filename in filenames:
216
+ print(f"- {filename}")
217
+
218
+ X, y = preprocess_data(df)
219
+ if X.empty or y.empty:
220
+ print("No valid data available for training.")
221
+ return
222
+
223
+ model, scaler = train_model(X, y)
224
+
225
+ joblib.dump(model, 'model.pkl')
226
+ joblib.dump(scaler, 'scaler.pkl')
227
+
228
+ elif use_existing_flag:
229
+ model = joblib.load('model.pkl')
230
+ scaler = joblib.load('scaler.pkl')
231
+
232
+ historical_data_dir = "downloaded_history"
233
+ symbol_filter = 'BTC_USDT' # Filter files that start with BTC_USDT
234
+ df, filenames = load_data_from_files(historical_data_dir, symbol_filter)
235
+ if df.empty:
236
+ print("No historical data found for prediction.")
237
+ return
238
+
239
+ print("Using the following BTC-related files for prediction:")
240
+ for filename in filenames:
241
+ print(f"- {filename}")
242
+
243
+ predictions = []
244
+ for symbol in df['symbol'].unique():
245
+ symbol_data = df[df['symbol'] == symbol]
246
+ timeframe = symbol_data['Timeframe'].iloc[0] # Get timeframe for prediction
247
+ last_timestamp = symbol_data.index[-1] # Get the last timestamp
248
+ next_candle_prediction = predict_next_candle(model, scaler, symbol_data)
249
+ predictions.append((symbol, last_timestamp, timeframe, next_candle_prediction))
250
+
251
+ write_predictions_to_file(output_file, predictions)
252
+
253
+ else:
254
+ exchange = ccxt.binance()
255
+ symbols = fetch_markets(exchange)
256
+ worker(exchange, symbols, timeframe, output_file)
257
+
258
+ if __name__ == "__main__":
259
+ main()
model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ca7bf25e061e840ba65bd4fa810e5723eebb24e31e6c42095a37e929c3bc5ba
3
+ size 22440675601
scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bfeca91480e3af15a494593dbd3ae7443ab7d28a2ef9523ec4125dc37fea0a04
3
+ size 1071