|
|
@@ -1,4 +1,6 @@
|
|
|
import json
|
|
|
+import time
|
|
|
+
|
|
|
import numpy as np
|
|
|
import pandas as pd
|
|
|
import queue
|
|
|
@@ -32,6 +34,7 @@ def on_message_trade(_ws, message):
|
|
|
trade_data.append(trade)
|
|
|
check_and_train_model()
|
|
|
predict_market_direction()
|
|
|
+ show_message()
|
|
|
|
|
|
|
|
|
def on_message_depth(_ws, message):
|
|
|
@@ -47,6 +50,7 @@ def on_message_depth(_ws, message):
|
|
|
})
|
|
|
check_and_train_model()
|
|
|
predict_market_direction()
|
|
|
+ show_message()
|
|
|
|
|
|
|
|
|
def extract_features(order_book, trade):
|
|
|
@@ -114,7 +118,7 @@ def check_and_train_model():
|
|
|
if len(X_train) > 0 and len(y_train) > 0:
|
|
|
model.fit(X_train, y_train)
|
|
|
model_trained = True # 标记模型已经被训练
|
|
|
- logger.info("Model trained with %d samples", len(X_train))
|
|
|
+ # logger.info("Model trained with %d samples", len(X_train))
|
|
|
else:
|
|
|
logger.info("Insufficient data to train the model")
|
|
|
else:
|
|
|
@@ -124,15 +128,50 @@ def check_and_train_model():
|
|
|
def predict_market_direction():
|
|
|
global model_trained
|
|
|
if len(order_book_snapshots) == 0 or len(trade_data) == 0:
|
|
|
- logger.info("Not enough data to make a prediction")
|
|
|
+ # logger.info("Not enough data to make a prediction")
|
|
|
return
|
|
|
|
|
|
if not model_trained:
|
|
|
- logger.info("Model is not trained yet")
|
|
|
+ # logger.info("Model is not trained yet")
|
|
|
return
|
|
|
|
|
|
features = extract_features(order_book_snapshots[-1], trade_data[-1])
|
|
|
if features is not None:
|
|
|
feature_vector = np.array([list(features.values())])
|
|
|
prediction = model.predict(feature_vector)
|
|
|
- logger.info("Predicted Market Direction: %s", "Up" if prediction[0] == 1 else "Down")
|
|
|
+ logger.info("Predicted Market Direction: %s", "Up" if prediction[0] == 1 else "Down")
|
|
|
+
|
|
|
+
|
|
|
+# 将消息推送到外部,看看图长什么样
|
|
|
+def show_message():
|
|
|
+ global order_book_snapshots, trade_data
|
|
|
+
|
|
|
+ if len(order_book_snapshots) > 0 and len(trade_data) > 0:
|
|
|
+ # 获取最新的订单簿数据和成交数据
|
|
|
+ latest_order_book = order_book_snapshots[-1]
|
|
|
+ latest_trade = trade_data[-1]
|
|
|
+
|
|
|
+ # 提取asks和bids数据
|
|
|
+ asks = [[float(price), float(qty)] for price, qty in latest_order_book['asks']]
|
|
|
+ bids = [[float(price), float(qty)] for price, qty in latest_order_book['bids']]
|
|
|
+
|
|
|
+ # 排序asks和bids数据
|
|
|
+ asks_sorted = sorted(asks, key=lambda x: x[0])
|
|
|
+ bids_sorted = sorted(bids, key=lambda x: x[0], reverse=True)
|
|
|
+
|
|
|
+ last_price = latest_trade['price']
|
|
|
+ last_qty = latest_trade['qty']
|
|
|
+ side = latest_trade['side']
|
|
|
+
|
|
|
+ # 生成数据字典
|
|
|
+ data = {
|
|
|
+ "asks": asks_sorted,
|
|
|
+ "bids": bids_sorted,
|
|
|
+ "last_price": last_price,
|
|
|
+ "last_qty": last_qty,
|
|
|
+ "side": side,
|
|
|
+ "time": int(time.time() * 1000)
|
|
|
+ }
|
|
|
+
|
|
|
+ # 将数据放入消息队列
|
|
|
+ messages.put(data)
|