-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
Expand file tree
/
Copy pathMain.java
More file actions
338 lines (272 loc) · 12.3 KB
/
Copy pathMain.java
File metadata and controls
338 lines (272 loc) · 12.3 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
package cli;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import io.github.ccxt.errors.AuthenticationError;
// import io.github.ccxt.wrappers.Binance;
import io.github.ccxt.Exchange;
import io.github.ccxt.BaseExchange;
import io.github.ccxt.MetaData;
import io.github.ccxt.Version;
class PrettyPrinter {
private static final Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
static void prettyPrintData(Object data) {
try {
String json = gson.toJson(data);
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Main {
public static boolean verbose = false;
public static boolean sandbox = false;
public static boolean demo = false;
public static boolean noKeys = false;
public static ArrayList<String> exchangeIds = new ArrayList<String>();
public static String exchangesPath = FileSystems.getDefault().getPath("").toAbsolutePath() + "../../../../.." + "/exchanges.json";
public static void InitOptions(BaseExchange instance, String[] args) {
if (args.length > 0) {
for (String arg : args) {
if (arg.equals("--verbose")) {
verbose = true;
// instance.verbose = true;
} else if (arg.equals("--sandbox")) {
sandbox = true;
instance.setSandboxMode(true);
} else if (arg.equals("--demo")) {
demo = true;
// instance.setDemoMode(true);
instance.enableDemoTrading(true);
} else if (arg.equals("--no-keys")) {
noKeys = true;
}
}
}
}
public static Object[] getParamsFromArgs(String[] args) {
ArrayList<Object> params = new ArrayList<Object>();
if (args.length > 2) {
for (int i = 2; i < args.length; i++) {
var arg = args[i];
if (arg.startsWith("{") || arg.startsWith("[")) {
try {
ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(arg, Object.class);
params.add(json);
} catch (Exception e) {
params.add(arg);
}
} else if (arg.equals("true") || arg.equals("false")) {
params.add(Boolean.parseBoolean(arg));
} else if (arg.equals("null")) {
params.add(null);
} else if (arg.matches("-?\\d+")) {
params.add(Integer.parseInt(arg));
} else if (arg.matches("-?\\d+\\.\\d+")) {
params.add(Double.parseDouble(arg));
}
else {
params.add(arg);
}
}
}
return params.toArray();
}
public static void setCredentials(BaseExchange instance) throws IllegalArgumentException, IllegalAccessException, IOException {
var basePath = FileSystems.getDefault().getPath("").toAbsolutePath().toString();
var prefix = (basePath.endsWith("cli")) ? "/../../" : "/../";
var keysJsonPath = basePath + prefix + "keys.json";
// System.out.perintln("Looking for keys.json at: " + keysJsonPath);
Map<String, Object> keysJsonContent = null;
if (FileSystems.getDefault().getPath(keysJsonPath).toFile().exists()) {
System.out.println("Loading credentials from: " + keysJsonPath);
// var content = FileUtils.readFileAsString(keysJsonPath);
String content = new String(Files.readAllBytes(Paths.get(keysJsonPath)));
try {
ObjectMapper mapper = new ObjectMapper();
keysJsonContent = mapper.readValue(content, Map.class);
} catch (Exception e) {
System.out.println("Error parsing keys.json: " + e.getMessage());
}
}
Map<String, Boolean> credentials = (Map<String, Boolean>)instance.requiredCredentials;
if (noKeys || credentials == null) {
return;
}
for (Map.Entry<String, Boolean> entry : credentials.entrySet()) {
String key = entry.getKey();
// attempt every declared credential, not only required ones: some exchanges (e.g.
// polymarket) mark all credentials optional and validate at call time, but still need
// them set from keys.json / env to function
String instanceIdKey = instance.id;
String credentialValue = null;
if (keysJsonContent != null && keysJsonContent.containsKey(instanceIdKey)) {
Map<String, Object> instanceCredentials = (Map<String, Object>)keysJsonContent.get(instanceIdKey);
if (instanceCredentials.containsKey(key)) {
credentialValue = instanceCredentials.get(key).toString();
System.out.println("Setting credential from keys.json: " + instanceIdKey + "." + key);
setProperty(instance, key, credentialValue);
continue;
}
}
String envKey = instanceIdKey.toUpperCase() + "_" + key.toUpperCase();
credentialValue = System.getenv(envKey);
if (credentialValue != null && credentialValue.startsWith("-----BEGIN")) {
credentialValue = credentialValue.replace("\\n", "\n");
}
if (credentialValue != null) {
System.out.println("Setting credential from ENV: " + envKey);
setProperty(instance, key, credentialValue);
}
}
}
private static void setProperty(BaseExchange instance, String key, String value)
throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = instance.getClass();
Field field = null;
// look for the field in this class and its superclasses
while (clazz != null) {
try {
field = clazz.getDeclaredField(key);
break; // found it
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass(); // go up the hierarchy
}
}
if (field != null) {
field.setAccessible(true);
field.set(instance, value);
} else {
System.out.println("No field or setter found for credential: " + key);
}
}
public static Object callDynamic(Object instance, String methodName, Object... args) {
Class<?> clazz = instance.getClass();
try {
Class<?>[] paramTypes = Arrays.stream(args)
.map(a -> a == null ? null : a.getClass())
.toArray(Class<?>[]::new);
try {
Method m = clazz.getMethod(methodName, paramTypes);
return m.invoke(instance, args);
} catch (NoSuchMethodException ignore) {
// Try matching a varargs method
}
// Try varargs method: (Object, Object[])
for (Method m : clazz.getMethods()) {
if (!m.getName().equals(methodName)) continue;
if (m.isVarArgs()) {
Class<?>[] types = m.getParameterTypes();
int fixedCount = types.length - 1;
if (args.length < fixedCount) continue;
Object[] invokeArgs = new Object[types.length];
for (int i = 0; i < fixedCount; i++) {
invokeArgs[i] = args[i];
}
// Build the varargs array
Class<?> varType = types[fixedCount].getComponentType();
int varCount = args.length - fixedCount;
Object varArray = Array.newInstance(varType, varCount);
for (int i = 0; i < varCount; i++) {
Array.set(varArray, i, args[fixedCount + i]);
}
invokeArgs[fixedCount] = varArray;
return m.invoke(instance, invokeArgs);
}
}
throw new NoSuchMethodException("Method " + methodName + " not found");
} catch (Exception e) {
throw new RuntimeException("Error calling method: " + methodName, e);
}
}
// public static void Main2() {
// var second = new Second();
// var res = second.createOrder(1,2,4);
// // var exchange = new Binance();
// // exchange.apiKey = "HEREHjhMFvuF1veWQVdUbLIy7TiCYe9fj4W6sEukmddD8TM9kPVRHMK6nS2SdV5mwE5u";
// // exchange.secret = "Suu9pWcO9zbvVuc6cSQsVuiiw2DmmA8DgHrUfePF9s2RtaHa0zxK3eAF4MfIk7Pd";
// // exchange.enableDemoTrading(true);
// try {
// // var balance = exchange.fetchBalance();
// // System.out.println(balance);
// } catch (Exception e) {
// Throwable cause = e.getCause();
// if (cause instanceof io.github.ccxt.errors.ExchangeError ae) {
// // throw ae; // or handle it
// System.out.println("Working Authentication error: " + ae.getMessage());
// }
// // if (e instanceof AuthenticationError) {
// // System.out.println("Authentication error: " + e.getMessage());
// // } else {
// // System.out.println("Error fetching balance: " + e.getMessage());
// // }
// }
// }
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("[java][" + Version.VERSION +"] CCXT CLI");
// System.out.println("User Directory: " + userDirectory);
// -p / --prediction forces the prediction namespace for ids that exist in both
// (e.g. hyperliquid); prediction-only ids resolve there automatically as a fallback.
// strip the flag so it is not mistaken for a positional method argument
var forcePrediction = false;
ArrayList<String> positionalArgs = new ArrayList<String>();
for (String arg : args) {
if (arg.equals("-p") || arg.equals("--prediction")) {
forcePrediction = true;
} else {
positionalArgs.add(arg);
}
}
args = positionalArgs.toArray(new String[0]);
if (args.length < 2) {
System.out.println("Usage: java -cp <classpath> cli.Main [--verbose] [--sandbox] [-p|--prediction] <exchange-id> [arg1 arg2 ...]");
return;
}
var exchangeName = args[0];
var methodName = args[1];
var isWsMethod = methodName.startsWith("watch");
var params = getParamsFromArgs(args);
var isProExchange = MetaData.ProExchanges.contains(exchangeName);
var instance = Exchange.dynamicallyCreateInstance(exchangeName, null, isProExchange, forcePrediction);
var callExpressionString = instance.id + "." + methodName + "(" + java.util.Arrays.toString(params) + ")";
System.out.println(callExpressionString);
try {
InitOptions(instance, args);
setCredentials(instance);
if (Main.verbose) {
instance.verbose = true;
}
instance.loadMarkets().get();
while (true) {
var f = callDynamic(instance, methodName, params);
Object response;
if (f instanceof CompletableFuture) {
response = ((CompletableFuture<?>) f).get();
} else {
response = f;
}
PrettyPrinter.prettyPrintData(response);
if (!isWsMethod) {
break;
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}