欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jAVA

程序员文章站 2022-07-08 07:58:32
...
package com.okex.ui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.okex.bean.ConfigBean;
import com.okex.bean.OrderBean;
import com.okex.bean.PayBean;
import com.okex.bean.TickerBean;
import com.okex.bean.WSBean;
import com.okex.util.HttpUtil;
import com.okex.util.TaLib;
import com.okex.ws.BuissnesWebSocketServiceImpl;
import com.okex.ws.WebSocketClient;
import com.okex.ws.WebSocketService;

public class TradeClient {

private long nowStamp = 0;
private long stamp1 = 0;
private long stamp2 = 0;
private long longJZTime = 0;
private long shortJZTime = 0;
private long longOrderTime = 0;
private long shortOrderTime = 0;
private boolean dpoKingCross = false;
private boolean dpoDeathCross = false;
private double longStop = 0;
private double shortStop = 0;
private boolean paoShort = false;
private boolean paoLong = false;
private boolean longBuy = false;
private boolean shortBuy = false;
private double huiLPrice = 0.09d;
private double huiSPrice = 0.09d;
private String longOrderIID = "";
private String shortOrderIID = "";
private double nowPrice = 0;
private double shortPrice = 0;
private double longPrice = 0;
private static TradeClient instance;
private ScheduledExecutorService executor;
private static List<TickerBean> list1 = new ArrayList<TickerBean>();
private static List<TickerBean> list2 = new ArrayList<TickerBean>();

public TradeClient() {
executor = Executors.newScheduledThreadPool(5);
}

public synchronized static TradeClient getInstance() {
if (instance == null) {
instance = new TradeClient();
}
return instance;
}

public void startWebSocket() {
Runnable task = new Runnable() {
@Override
public void run() {
String url = "wss://real.okex.com:8443/ws/v3";
List<String> args = new ArrayList<>();
args.add("swap/mark_price:EOS-USDT-SWAP");
WebSocketService service = new BuissnesWebSocketServiceImpl();
WebSocketClient client = new WebSocketClient(url, service);
client.start();
client.subscribe(args);
}
};
executor.execute(task);
}

public void startTimerTask() {
Runnable task = new Runnable() {
@Override
public void run() {
parseTicker();
parseLTrader();
parseSTrader();
}
};
executor.scheduleAtFixedRate(task, 5, 5, TimeUnit.SECONDS);
}

private void parseTicker() {
if (nowStamp > stamp1 + 1) {
updateSmallTicker();
}
if (nowStamp > stamp2 + 1) {
updateBigTicker();
}
}

public void updateSmallTicker() {
String url = "https://www.okex.com/api/swap/v3/instruments/EOS-USDT-SWAP/candles?granularity=1800";
String json = HttpUtil.sendGet(url);
if (json.startsWith("[")) {
List<TickerBean> http = HttpUtil.getData(json, true);
int end = http.size() - 1;
String utc = http.get(end).getUtc();
stamp1 = utcToStamp(utc) + 1800L;
list1.clear();
list1.addAll(http);
TaLib.SMA(http, 18);
TaLib.DPO(http, 18);
dpoKingCross = TaLib.isDPOKingCross(http);
dpoDeathCross = TaLib.isDPODeathCross(http);
writeData(http, true);
updateOrderStop();
}
}

public void updateBigTicker() {
String url = "https://www.okex.com/api/swap/v3/instruments/EOS-USDT-SWAP/candles?granularity=21600";
String json = HttpUtil.sendGet(url);
if (json.startsWith("[")) {
List<TickerBean> http = HttpUtil.getData(json, true);
int end = http.size() - 1;
String utc = http.get(end).getUtc();
stamp2 = utcToStamp(utc) + 21600L;
list2.clear();
list2.addAll(http);
writeData(http, false);
}
}

private void parseLTrader() {
if (longBuy) {
long stamp = System.currentTimeMillis() / 1000L;
int size = list1.size() - 2;
double high = list1.get(size).getHigh();
double tmp = high + huiLPrice;
long time = stamp - longOrderTime;
if (tmp > longStop && time > 3610L) {
longStop = tmp;
}
if (nowPrice < longStop && time > 1800L) {
if (nowPrice - longPrice > huiLPrice) {
paoLong = true;
}
longBuy = false;
longJZTime = nowStamp + 3610L;
sellCoin("long");
}
} else {
TaLib.MACD(list2, 12, 26, 9);
if (isMACDKingCross()) {
long stamp = System.currentTimeMillis() / 1000L;
if (stamp < longJZTime) {
return;
}
if (paoLong) {
longJZTime += 2400L;
paoLong = false;
return;
}
String config = readText("C:/config.txt");
ConfigBean bean = JSON.parseObject(config, ConfigBean.class);
if (!bean.isAllow()) {
return;
}
int num = bean.getNumber();
if (dpoKingCross) {
longOrderIID = "D" + getRandomStr();
longBuy = true;
longJZTime = stamp;
longOrderTime = stamp;
huiLPrice = nowPrice * 0.03d;
longStop = nowPrice - huiSPrice;
longPrice = nowPrice;
buyCoin(num, "1");
}
}
}
}

private void parseSTrader() {
long stamp = System.currentTimeMillis() / 1000L;
if (shortBuy) {
int size = list1.size() - 2;
double low = list1.get(size).getLow();
double tmp = low + huiSPrice;
long time  = stamp - shortOrderTime;
if (tmp < shortStop && time > 3610L) {
shortStop = tmp;
}
if (nowPrice > shortStop && time > 1800L) {
if (shortPrice - nowPrice > huiSPrice) {
paoShort = true;
}
shortBuy = false;
shortJZTime = nowStamp + 3610L;
sellCoin("short");
}
} else {
TaLib.MACD(list2, 12, 26, 9);
if (isMACDDeathCross()) {
if (stamp < shortJZTime) {
return;
}
if (paoShort) {
shortJZTime += 2400L;
paoShort = false;
return;
}
String config = readText("C:/config.txt");
ConfigBean bean = JSON.parseObject(config, ConfigBean.class);
if (!bean.isAllow()) {
return;
}
int num = bean.getNumber();
if (dpoDeathCross) {
shortOrderIID = "S" + getRandomStr();
shortBuy = true;
buyCoin(num, "2");
shortJZTime = stamp;
shortOrderTime = stamp;
huiSPrice = nowPrice * 0.03d;
shortStop = nowPrice + huiSPrice;
shortPrice = nowPrice;
}
}
}
}

public void parseJSON(String json) {
if (json.equals("pong")) {
return;
}
WSBean ws = JSON.parseObject(json, WSBean.class);
if (ws.getTable().equals("swap/mark_price")) {
String time = ws.getData().get(0).getTimestamp();
String close = ws.getData().get(0).getMark_price();
nowPrice = Double.valueOf(close);
nowStamp = utcToStamp(time);
int end2 = list2.size() - 1;
list2.get(end2).setClose(nowPrice);
if (longBuy) {
long t = nowStamp - longOrderTime;
if (nowPrice < longStop && t > 1803L) {
if (nowPrice - longPrice > huiLPrice) {
paoLong = true;
}
longBuy = false;
longJZTime = nowStamp + 3610L;
sellCoin("long");
}
}
if (shortBuy) {
long t = nowStamp - shortOrderTime;
if (nowPrice > shortStop && t > 1803L) {
if (shortPrice - nowPrice > huiSPrice) {
paoShort = true;
}
shortBuy = false;
shortJZTime = nowStamp + 3610L;
sellCoin("short");
}
}
}
}

public void buyCoin(int num, String type) {
Runnable task = new Runnable() {
@Override
public void run() {
String orderID = "";
if (type.equals("1")) {
orderID = longOrderIID;
} else {
orderID = shortOrderIID;
}
String msg = HttpUtil.createOrder(num, type, orderID);
if (msg.startsWith("{")) {
PayBean pay = JSON.parseObject(msg, PayBean.class);
String iid = pay.getOrder_id();
boolean check = true;
while (check) {
try {
Thread.sleep(40 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String json = HttpUtil.getOrderInfo(iid);
if (json.startsWith("{")) {
check = false;
OrderBean bean = JSON.parseObject(json, OrderBean.class);
String state = bean.getState();
if (state.equals("2")) {
printLog("买入,类型" + type + ",订单号" + orderID + ",价格为" + String.format("%.3f", nowPrice));
} else {
HttpUtil.cancelOrder(iid);
double wt = Double.valueOf(bean.getSize());
double cj = Double.valueOf(bean.getFilled_qty());
int nm = (int) (wt - cj);
buyCoin((int) nm, type);
}
}
}
}
}
};
executor.submit(task);
}

public void sellCoin(String type) {
HttpUtil.createMarkOrder(type);
String orderID = "";
if (type.equals("long")) {
orderID = longOrderIID;
} else {
orderID = shortOrderIID;
}
printLog("卖出,类型" + type + ",订单号" + orderID + ",价格为" + String.format("%.3f", nowPrice));
}

private void updateOrderStop() {
if (longBuy) {
long stamp = System.currentTimeMillis() / 1000L;
if (stamp - longOrderTime > 3610L) {
printLog("");
}
}
if (shortBuy) {
long stamp = System.currentTimeMillis() / 1000L;
if (stamp - shortOrderTime > 3610L) {
printLog("");
}
}
}

private void writeData(List<TickerBean> http, boolean small) {
String text = "";
if (small) {
text = readText("C:/ok_eos.txt");
} else {
text = readText("C:/ok_eos6.txt");
}
List<TickerBean> local = HttpUtil.getData(text, false);
int size = local.size() - 1;
String utc2 = local.get(size).getUtc();
long tm2 = utcToStamp(utc2);
for (int i = 0; i < http.size() - 1; i++) {
String utc3 = http.get(i).getUtc();
long stm = utcToStamp(utc3);
if (stm > tm2) {
local.add(http.get(i));
}
}
List<List<String>> temp = new ArrayList<>();
for (int i = 0; i < local.size(); i++) {
TickerBean bean = local.get(i);
List<String> str = new ArrayList<>();
str.add(bean.getUtc());
str.add(String.format("%.3f", bean.getOpen()));
str.add(String.format("%.3f", bean.getHigh()));
str.add(String.format("%.3f", bean.getLow()));
str.add(String.format("%.3f", bean.getClose()));
temp.add(str);
}
String ticker = JSON.toJSONString(temp);
if (small) {
writeText("C:/ok_eos.txt", ticker);
} else {
writeText("C:/ok_eos6.txt", ticker);
}
}

public static long utcToStamp(String utc) {
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
try {
date = sdf.parse(utc);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) +jAVA
            
    
    博客分类: Java java ;
return calendar.getTime().getTime() / 1000;
}

private boolean isMACDDeathCross() {
int end = list2.size() - 1;
double dif = list2.get(end).getDif();
double dea = list2.get(end).getDea();
if (dif < dea + 0.0028d) {
return true;
} else {
return false;
}
}

public static boolean isMACDKingCross() {
int end = list2.size() - 1;
double dif = list2.get(end).getDif();
double dea = list2.get(end).getDea();
if (dif > dea) {
return true;
} else {
return false;
}
}

public static String readText(String path) {
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
String s;
while ((s = br.readLine()) != null) {
result.append(System.lineSeparator()).append(s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}

public static void writeText(String path, String text) {
FileOutputStream fileOutputStream = null;
File file = new File(path);
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(text.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public void getBigTicker() {
String web = "https://www.okex.com/api/swap/v3/instruments/EOS-USDT-SWAP/candles?granularity=1800";
String str = HttpUtil.sendGet(web);
if (str.startsWith("[")) {
List<TickerBean> http = HttpUtil.getData(str, true);
int end = http.size() - 1;
String utc = http.get(end).getUtc();
stamp1 = utcToStamp(utc) + 1800L;
list1.clear();
list1.addAll(http);
}
String url = "https://www.okex.com/api/swap/v3/instruments/EOS-USDT-SWAP/candles?granularity=21600";
String json = HttpUtil.sendGet(url);
if (json.startsWith("[")) {
List<TickerBean> http = HttpUtil.getData(json, true);
int end = http.size() - 1;
String utc = http.get(end).getUtc();
stamp2 = utcToStamp(utc) + 21600L;
list2.clear();
list2.addAll(http);
}
}

public static String getRandomStr() {
String val = "";
Random random = new Random();
for (int i = 0; i < 16; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
if ("char".equalsIgnoreCase(charOrNum)) {
int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (random.nextInt(26) + temp);
} else if ("num".equalsIgnoreCase(charOrNum)) {
val += String.valueOf(random.nextInt(10));
}
}
return val.toUpperCase();
}

private void printLog(String msg) {
String time = "时间:" + new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date()) + "   事件:" + msg;
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:/log.txt", true)));
out.write(time + "\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
相关标签: java