-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStorageLayer.java
More file actions
100 lines (83 loc) · 3.33 KB
/
Copy pathStorageLayer.java
File metadata and controls
100 lines (83 loc) · 3.33 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
import java.sql.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class StorageLayer extends Thread {
private static final String DB_URL = "jdbc:sqlite:trades.db";
private static final TradeRecord POISON = new TradeRecord(-1, -1, -1, 0, 0);
private final BlockingQueue<TradeRecord> tradeQueue = new LinkedBlockingQueue<>();
private boolean driverAvailable = false;
public StorageLayer() {
super("StorageLayer");
setDaemon(true);
loadDriver();
if (driverAvailable) initDb();
}
public void record(TradeRecord trade) {
if (driverAvailable) tradeQueue.offer(trade);
}
public void shutdown() {
tradeQueue.offer(POISON);
}
@Override
public void run() {
if (!driverAvailable) {
System.err.println("[Storage] Driver unavailable — storage disabled.");
return;
}
try (Connection conn = DriverManager.getConnection(DB_URL)) {
conn.setAutoCommit(false);
String sql = "INSERT INTO trades(trade_id,buy_order_id,sell_order_id,price,quantity,executed_at) "
+ "VALUES(?,?,?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int batchCount = 0;
while (true) {
TradeRecord t = tradeQueue.take();
if (t == POISON) break;
stmt.setInt (1, t.tradeId);
stmt.setInt (2, t.buyOrderId);
stmt.setInt (3, t.sellOrderId);
stmt.setDouble(4, t.price);
stmt.setInt (5, t.quantity);
stmt.setLong (6, t.executedAt);
stmt.addBatch();
batchCount++;
if (batchCount % 500 == 0) {
stmt.executeBatch();
conn.commit();
}
}
stmt.executeBatch();
conn.commit();
System.out.println("[Storage] All trades flushed to trades.db");
}
} catch (SQLException | InterruptedException e) {
System.err.println("[Storage] Error: " + e.getMessage());
}
}
private void loadDriver() {
try {
Class.forName("org.sqlite.JDBC");
driverAvailable = true;
} catch (ClassNotFoundException e) {
System.err.println("[Storage] sqlite-jdbc jar not found — trades will NOT be persisted.");
}
}
private void initDb() {
try (Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = conn.createStatement()) {
stmt.execute(
"CREATE TABLE IF NOT EXISTS trades (" +
" trade_id INTEGER PRIMARY KEY," +
" buy_order_id INTEGER NOT NULL," +
" sell_order_id INTEGER NOT NULL," +
" price REAL NOT NULL," +
" quantity INTEGER NOT NULL," +
" executed_at INTEGER NOT NULL" +
")"
);
System.out.println("[Storage] Database ready.");
} catch (SQLException e) {
System.err.println("[Storage] DB init error: " + e.getMessage());
}
}
}