file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
TrackPositionChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/TrackPositionChangeEvent.java
package org.bff.javampd.player; /** * Represents a change in the position of a playing song. * * @author Bill * @version 1.0 */ public class TrackPositionChangeEvent extends java.util.EventObject { private final long newElapsedTime; /** * Creates a new instance of TrackPositionEvent. * * @param source the object on which the Event initially occurred * @param newTime the new elapsed time of the song */ public TrackPositionChangeEvent(Object source, long newTime) { super(source); this.newElapsedTime = newTime; } /** * Returns the elapsed time of the playing song. * * @return the new elapsed time */ public long getElapsedTime() { return newElapsedTime; } }
723
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
VolumeChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/VolumeChangeListener.java
package org.bff.javampd.player; /** * The listener interface for receiving volume change events. The class that is interested in * processing a volume change event implements this interface, and the object created with that * class is registered with a component using the component's <CODE>addVolumeChangeListener</CODE> * method. When the position event occurs, that object's <CODE>volumeChanged</CODE> method is * invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface VolumeChangeListener { /** * Invoked when a mpd volume change event occurs. * * @param event the event received */ void volumeChanged(VolumeChangeEvent event); }
687
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerProperties.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/PlayerProperties.java
package org.bff.javampd.player; import lombok.Getter; import org.bff.javampd.server.MPDProperties; public class PlayerProperties extends MPDProperties { @Getter private enum Command { XFADE("player.crossfade"), CURRSONG("player.currentsong"), NEXT("player.next"), PAUSE("player.pause"), PLAY("player.play"), PLAYID("player.play.id"), PREV("player.prev"), REPEAT("player.repeat"), RANDOM("player.random"), SEEK("player.seek"), SEEKID("player.seek.id"), STOP("player.stop"), CONSUME("player.consume"), SINGLE("player.single"), SETVOL("player.set.volume"), MIX_RAMP_DB("player.mixrampdb"), MIX_RAMP_DELAY("player.mixrampdelay"); private final String key; Command(String key) { this.key = key; } } public String getXFade() { return getPropertyString(Command.XFADE.getKey()); } public String getCurrentSong() { return getPropertyString(Command.CURRSONG.getKey()); } public String getNext() { return getPropertyString(Command.NEXT.getKey()); } public String getPause() { return getPropertyString(Command.PAUSE.getKey()); } public String getPlay() { return getPropertyString(Command.PLAY.getKey()); } public String getPlayId() { return getPropertyString(Command.PLAYID.getKey()); } public String getPrevious() { return getPropertyString(Command.PREV.getKey()); } public String getRepeat() { return getPropertyString(Command.REPEAT.getKey()); } public String getRandom() { return getPropertyString(Command.RANDOM.getKey()); } public String getSeek() { return getPropertyString(Command.SEEK.getKey()); } public String getSeekId() { return getPropertyString(Command.SEEKID.getKey()); } public String getStop() { return getPropertyString(Command.STOP.getKey()); } public String getSetVolume() { return getPropertyString(Command.SETVOL.getKey()); } public String getConsume() { return getPropertyString(Command.CONSUME.getKey()); } public String getSingle() { return getPropertyString(Command.SINGLE.getKey()); } public String getMixRampDelay() { return getPropertyString(Command.MIX_RAMP_DELAY.getKey()); } public String getMixRampDb() { return getPropertyString(Command.MIX_RAMP_DB.getKey()); } }
2,337
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerBasicChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/PlayerBasicChangeEvent.java
package org.bff.javampd.player; import lombok.Getter; /** * Represents a change in the status of a music player. * * @author Bill */ @Getter public class PlayerBasicChangeEvent extends java.util.EventObject { /** * -- GETTER -- Returns the that occurred. * * @return the {@link Status} */ private final Status status; public enum Status { PLAYER_STOPPED, PLAYER_STARTED, PLAYER_PAUSED, PLAYER_UNPAUSED } /** * Creates a new instance of PlayerBasicChangeEvent * * @param source the object on which the Event initially occurred * @param status the {@link Status} */ public PlayerBasicChangeEvent(Object source, Status status) { super(source); this.status = status; } }
740
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
Player.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/Player.java
package org.bff.javampd.player; import java.util.Optional; import lombok.Getter; import org.bff.javampd.audioinfo.MPDAudioInfo; import org.bff.javampd.playlist.MPDPlaylistSong; /** * @author bill */ public interface Player { /** The status of the player. */ @Getter enum Status { STATUS_STOPPED("stop"), STATUS_PLAYING("play"), STATUS_PAUSED("pause"); private final String prefix; Status(String prefix) { this.prefix = prefix; } } /** * Returns the current song either playing or queued for playing. * * @return the current song */ Optional<MPDPlaylistSong> getCurrentSong(); /** * Adds a {@link PlayerChangeListener} to this object to receive {@link PlayerChangeEvent}s. * * @param pcl the PlayerChangeListener to add */ void addPlayerChangeListener(PlayerChangeListener pcl); /** * Removes a {@link PlayerChangeListener} from this object. * * @param pcl the PlayerChangeListener to remove */ void removePlayerChangedListener(PlayerChangeListener pcl); /** * Adds a {@link VolumeChangeListener} to this object to receive {@link VolumeChangeEvent}s. * * @param vcl the VolumeChangeListener to add */ void addVolumeChangeListener(VolumeChangeListener vcl); /** * Removes a {@link VolumeChangeListener} from this object. * * @param vcl the VolumeChangeListener to remove */ void removeVolumeChangedListener(VolumeChangeListener vcl); /** Starts the player. */ void play(); /** * Starts the player with the specified {@link MPDPlaylistSong}. * * @param song the song to start the player with */ void playSong(MPDPlaylistSong song); /** * Seeks to the desired location in the current song. If the location is larger than the length of * the song or is less than 0 then the parameter is ignored. * * @param secs the location to seek to */ void seek(long secs); /** * Seeks to the desired location in the specified song. If the location is larger than the length * of the song or is less than 0 then the parameter is ignored. * * @param song the song to seek in * @param secs the location to seek to */ void seekSong(MPDPlaylistSong song, long secs); /** Stops the player. */ void stop(); /** Pauses the player. */ void pause(); /** Plays the next song in the playlist. */ void playNext(); /** Plays the previous song in the playlist. */ void playPrevious(); /** Mutes the volume of the player. */ void mute(); /** Unmutes the volume of the player. */ void unMute(); /** * Returns the instantaneous bitrate of the currently playing song. * * @return the instantaneous bitrate in kbps */ int getBitrate(); /** * Returns the current volume of the player. * * @return the volume of the player (0-100) */ int getVolume(); /** * Sets the volume of the player. The volume is between 0 and 100, any volume less that 0 results * in a volume of 0 while any volume greater than 100 results in a volume of 100. * * @param volume the volume level (0-100) */ void setVolume(int volume); /** * Returns if the player is repeating. * * @return is the player repeating */ boolean isRepeat(); /** * Sets the repeating status of the player. * * @param shouldRepeat should the player repeat the current song */ void setRepeat(boolean shouldRepeat); /** * Returns if the player is in random play mode. * * @return true if the player is in random mode false otherwise */ boolean isRandom(); /** * Sets the random status of the player. So the songs will be played in random order * * @param shouldRandom should the player play in random mode */ void setRandom(boolean shouldRandom); /** Plays the playlist in a random order. */ void randomizePlay(); /** Plays the playlist in order. */ void unRandomizePlay(); /** * Returns the cross fade of the player in seconds. * * @return the cross fade of the player in seconds */ int getXFade(); /** * Sets the cross fade of the player in seconds. * * @param xFade the amount of cross fade to set in seconds */ void setXFade(int xFade); /** * Returns the elapsed time of the current song in seconds. * * @return the elapsed time of the song in seconds */ long getElapsedTime(); /** * Returns the total time of the current song in seconds. * * @return the elapsed time of the song in seconds */ long getTotalTime(); /** * Returns the {@link org.bff.javampd.audioinfo.MPDAudioInfo} about the current status of the * player. If the status is unknown {@code null} will be returned. Any individual parameter that * is not known will be a -1 * * @return the sample rate */ MPDAudioInfo getAudioDetails(); /** * Returns the current status of the player. * * @return the status of the player */ Status getStatus(); /** * Set 'consume' state of the player. * * @param consume should consume be turned on */ void setConsume(boolean consume); /** * Set 'single' state of the player. * * @param single should the single mode be turned on */ void setSingle(boolean single); /** * The threshold at which songs will be overlapped. Like crossfading but doesn’t fade the track * volume, just overlaps. * * @return the threshold at which songs will be overlapped */ Optional<Integer> getMixRampDb(); /** * Sets the threshold at which songs will be overlapped. Like crossfading but doesn’t fade the * track volume, just overlaps. The songs need to have MixRamp tags added by an external tool. 0dB * is the normalized maximum volume so use negative values * * @param db the threshold at which songs will be overlapped */ void setMixRampDb(int db); /** * Additional time subtracted from the overlap calculated by mixrampdb. * * @return additional time subtracted from the overlap calculated by mixrampdb */ Optional<Integer> getMixRampDelay(); /** * Additional time subtracted from the overlap calculated by mixrampdb. A value of <code>0 * </code> disables MixRamp overlapping and falls back to crossfading. * * @param delay additional time subtracted from the overlap calculated by mixrampdb */ void setMixRampDelay(int delay); }
6,404
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
VolumeChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/VolumeChangeEvent.java
package org.bff.javampd.player; import lombok.Getter; /** * Represents a change in the volume of a MPD player. * * @author Bill * @version 1.0 */ @Getter public class VolumeChangeEvent extends java.util.EventObject { /** * -- GETTER -- Returns the new volume level. * * @return the new volume */ private final int volume; /** * Creates a new instance of MusicPlayerStatusChangedEvent * * @param source the object on which the Event initially occurred * @param volume the new volume */ public VolumeChangeEvent(Object source, int volume) { super(source); this.volume = volume; } }
633
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
TrackPositionChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/TrackPositionChangeListener.java
package org.bff.javampd.player; /** * The listener interface for receiving track position change events. The class that is interested * in processing a position event implements this interface, and the object created with that class * is registered with a component using the component's <CODE>addTrackPositionChangeListener</CODE> * method. When the position event occurs, that object's <CODE>trackPositionChanged</CODE> method is * invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface TrackPositionChangeListener { /** * Invoked when a track position change occurs. * * @param event the event fired */ void trackPositionChanged(TrackPositionChangeEvent event); }
720
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
VolumeChangeDelegate.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/VolumeChangeDelegate.java
package org.bff.javampd.player; import java.util.ArrayList; import java.util.List; /** * Handles volume change eventing. * * @author bill */ public class VolumeChangeDelegate { private final List<VolumeChangeListener> volListeners; public VolumeChangeDelegate() { volListeners = new ArrayList<>(); } public synchronized void addVolumeChangeListener(VolumeChangeListener vcl) { volListeners.add(vcl); } public synchronized void removeVolumeChangedListener(VolumeChangeListener vcl) { volListeners.remove(vcl); } /** * Sends the appropriate {@link VolumeChangeEvent} to all registered {@link VolumeChangeListener}. * * @param source source of event * @param volume the new volume */ public synchronized void fireVolumeChangeEvent(Object source, int volume) { var vce = new VolumeChangeEvent(source, volume); for (VolumeChangeListener vcl : volListeners) { vcl.volumeChanged(vce); } } }
960
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerChangeEvent.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/PlayerChangeEvent.java
package org.bff.javampd.player; import lombok.Getter; /** * Represents a change in the status of a MPD music player. * * @author Bill */ @Getter public class PlayerChangeEvent extends java.util.EventObject { /** * -- GETTER -- Returns the that occurred. * * @return the specific {@link Event} */ private final Event event; public enum Event { PLAYER_STOPPED, PLAYER_STARTED, PLAYER_PAUSED, PLAYER_NEXT, PLAYER_PREVIOUS, PLAYER_MUTED, PLAYER_UNMUTED, PLAYER_SONG_SET, PLAYER_SEEKING } /** * Creates a new instance of PlayerChangeEvent * * @param source the object on which the Event initially occurred * @param event the {@link Event} */ public PlayerChangeEvent(Object source, Event event) { super(source); this.event = event; } }
824
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
PlayerBasicChangeListener.java
/FileExtraction/Java_unseen/finnyb_javampd/src/main/java/org/bff/javampd/player/PlayerBasicChangeListener.java
package org.bff.javampd.player; /** * The listener interface for receiving basic player events. The class that is interested in * processing a player event implements this interface, and the object created with that class is * registered with a component using the component's <CODE>addBasicPlayerChangeListener</CODE> * method. When the player event occurs, that object's <CODE>playerBasicChange</CODE> method is * invoked. * * @author Bill * @version 1.0 */ @FunctionalInterface public interface PlayerBasicChangeListener { /** * Invoked when a player change event occurs. * * @param event the event fired */ void playerBasicChange(PlayerBasicChangeEvent event); }
693
Java
.java
finnyb/javampd
35
21
13
2013-11-21T15:24:25Z
2024-04-27T11:03:48Z
RateLimitTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/test/java/test/RateLimitTest.java
package test; import cqt.goai.exchange.util.RateLimit; import org.junit.Assert; import org.junit.Test; /** * @author GOAi */ public class RateLimitTest { @Test public void test() throws InterruptedException { RateLimit NO = RateLimit.NO; for (int i = 0; i < 10000; i++) { // 次次需要更新 Assert.assertTrue(NO.timeout(false)); } RateLimit limit = RateLimit.limit(300); Assert.assertFalse(limit.timeout()); // 300毫秒之内,不需要推送 Thread.sleep(200); Assert.assertFalse(limit.timeout()); // 300毫秒之内,不需要推送 Thread.sleep(200); Assert.assertTrue(limit.timeout()); // 300毫秒之外,需要推送 Assert.assertFalse(limit.timeout()); // 300毫秒之内,不需要推送 } }
832
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ExchangeException.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/ExchangeException.java
package cqt.goai.exchange; import dive.common.model.Message; /** * 交易所信息处理异常 * @author GOAi */ public class ExchangeException extends RuntimeException { private static final long serialVersionUID = -8633608065854161508L; private Integer code = Message.CODE_FAILED; public ExchangeException(String message) { super(message); } public ExchangeException(ExchangeError error, String message) { super(message); this.code = error.getCode(); } public ExchangeException(String message, Throwable throwable) { super(message, throwable); } public ExchangeException(ExchangeError error, String message, Throwable throwable) { super(message, throwable); this.code = error.getCode(); } public Integer getCode() { return code; } }
853
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ExchangeError.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/ExchangeError.java
package cqt.goai.exchange; /** * 交易所相关错误码 * * @author GOAi */ public enum ExchangeError { // 交易所不支持 EXCHANGE(1001), // 币对不支持 SYMBOL(1002), // K线周期不支持 PERIOD(1003); // public static final Integer ERROR_TOKEN = 1001; // 授权错误 private int code; ExchangeError(int code) { this.code = code; } public int getCode() { return code; } }
461
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ExchangeManager.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/ExchangeManager.java
package cqt.goai.exchange; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.http.binance.BinanceExchange; import cqt.goai.exchange.http.bitfinex.BitfinexExchange; import cqt.goai.exchange.http.huobi.pro.HuobiProExchange; import cqt.goai.exchange.http.okexv3.Okexv3Exchange; import cqt.goai.exchange.web.socket.WebSocketExchange; import cqt.goai.exchange.web.socket.okexv3.Okexv3WebSocketExchange; import org.slf4j.Logger; /** * 统一获取Exchange对象 * @author GOAi */ public class ExchangeManager { /** * 获取HttpExchange * Simple Factory Pattern 简单工厂模式 * 获取实例对象即可,没有太多的拓展性 * @param name 交易所名 * @param log 日志 */ public static HttpExchange getHttpExchange(ExchangeName name, Logger log) { if (null != name) { switch (name) { case OKEXV3: return new Okexv3Exchange(log); case BITFINEX: return new BitfinexExchange(log); case HUOBIPRO: return new HuobiProExchange(log); case BINANCE: return new BinanceExchange(log); default: } } throw new ExchangeException(ExchangeError.EXCHANGE, "exchange name is not supported"); } /** * 获取WSExchange * 简单工厂模式 * @param name 交易所名 * @param log 日志 */ public static WebSocketExchange getWebSocketExchange(ExchangeName name, Logger log) { if (null != name) { switch (name) { case OKEXV3: return new Okexv3WebSocketExchange(log); default: } } throw new ExchangeException(ExchangeError.EXCHANGE, "exchange name is not supported"); } }
1,770
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ExchangeName.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/ExchangeName.java
package cqt.goai.exchange; import cqt.goai.exchange.util.CompleteList; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static cqt.goai.exchange.Action.*; import static cqt.goai.exchange.Action.ORDER; import static cqt.goai.exchange.util.CompleteList.*; /** * 交易所名称 * * @author GOAi */ public enum ExchangeName { /** * OKEX V3 版本, ALL * https://www.okex.com/docs/zh/ * CompleteList.ALL */ OKEXV3("okexv3", CompleteList.ALL), /** * bitfinex * https://docs.bitfinex.com/v1/docs/rest-general * https://docs.bitfinex.com/v2/docs/rest-auth * CompleteList.MARKET * CompleteList.ACCOUNT * CompleteList.TRADE * CompleteList.ORDER */ BITFINEX("bitfinex", CompleteList.exclude(PUSH)), /** * huobipro * https://github.com/huobiapi/API_Docs */ HUOBIPRO("huobipro", CompleteList.exclude(PUSH)), /** * binance * https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md */ BINANCE("binance", CompleteList.exclude(PUSH)); /** * 交易所名称,唯一识别 */ private String name; /** * 已完成的功能 */ private List<Action> functions; ExchangeName(String name, Action... actions) { this.name = name; this.functions = null == actions ? new ArrayList<>() : Arrays.asList(actions); } public String getName() { return this.name; } public List<Action> getFunctions() { return this.functions; } /** * 根据名称获取 */ public static ExchangeName getByName(String name) { for (ExchangeName en : ExchangeName.values()) { if (en.name.equals(name)) { return en; } } return null; } @Override public String toString() { return this.name; } }
1,947
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BaseExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/BaseExchange.java
package cqt.goai.exchange; import org.slf4j.Logger; /** * 交易所基本信息 * @author GOAi */ public class BaseExchange { /** * 日志 */ protected final Logger log; /** * 交易所名称 */ protected final ExchangeName name; public BaseExchange(ExchangeName name, Logger log) { this.name = name; this.log = log; } }
390
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ExchangeUtil.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/ExchangeUtil.java
package cqt.goai.exchange; import dive.http.okhttp.OkHttp; /** * 工具类 * @author GOAi */ public class ExchangeUtil { /** * okhttp util */ public static final OkHttp OKHTTP = new OkHttp(); }
219
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ExchangeInfo.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/ExchangeInfo.java
package cqt.goai.exchange; import cqt.goai.exchange.util.Seal; import cqt.goai.model.enums.Period; import cqt.goai.model.market.Row; import lombok.Data; import java.util.List; /** * 封装请求信息 * @author GOAi */ @Data public class ExchangeInfo implements Cloneable { /** * 请求行为 */ private Action action; /** * 请求币对 */ private String symbol; /** * access */ private String access; /** * secret */ private String secret; /** * 获取Kline需要指定周期 */ private Period period; /** * 限价单 价格 */ private String price; /** * 限价单 数量 */ private String amount; /** * 市价买单 总价 */ private String quote; /** * 市价卖单数量 */ private String base; /** * 多个市价买单或卖单的价格数量信息 */ private List<Row> rows; /** * 取消订单id */ private String cancelId; /** * 取消订单的id信息 */ private List<String> cancelIds; /** * 获取订单id */ private String orderId; /** * 推送id */ private String pushId; /** * 标识解析方式 */ private String extra; private ExchangeInfo(Action action, String symbol, String access, String secret) { this.action = action; this.symbol = symbol; this.access = access; this.secret = secret; } private ExchangeInfo(Action action, String symbol, String access, String secret, String pushId) { this(action, symbol, access, secret); this.pushId = pushId; } // 市场 public static ExchangeInfo ticker(String symbol, String access, String secret) { return new ExchangeInfo(Action.TICKER, symbol, access, secret); } public static ExchangeInfo klines(String symbol, String access, String secret, Period period) { ExchangeInfo info = new ExchangeInfo(Action.KLINES, symbol, access, secret); info.period = period; return info; } public static ExchangeInfo depth(String symbol, String access, String secret) { return new ExchangeInfo(Action.DEPTH, symbol, access, secret); } public static ExchangeInfo trades(String symbol, String access, String secret) { return new ExchangeInfo(Action.TRADES, symbol, access, secret); } // 账户 public static ExchangeInfo balances(String symbol, String access, String secret) { return new ExchangeInfo(Action.BALANCES, symbol, access, secret); } public static ExchangeInfo account(String symbol, String access, String secret) { return new ExchangeInfo(Action.ACCOUNT, symbol, access, secret); } // 交易 public static ExchangeInfo precisions(String symbol, String access, String secret) { return new ExchangeInfo(Action.PRECISIONS, symbol, access, secret); } public static ExchangeInfo precision(String symbol, String access, String secret) { return new ExchangeInfo(Action.PRECISION, symbol, access, secret); } public static ExchangeInfo buyLimit(String symbol, String access, String secret, String price, String amount) { ExchangeInfo info = new ExchangeInfo(Action.BUY_LIMIT, symbol, access, secret); info.price = price; info.amount = amount; return info; } public static ExchangeInfo sellLimit(String symbol, String access, String secret, String price, String amount) { ExchangeInfo info = new ExchangeInfo(Action.SELL_LIMIT, symbol, access, secret); info.price = price; info.amount = amount; return info; } public static ExchangeInfo buyMarket(String symbol, String access, String secret, String quote) { ExchangeInfo info = new ExchangeInfo(Action.BUY_MARKET, symbol, access, secret); info.quote = quote; return info; } public static ExchangeInfo sellMarket(String symbol, String access, String secret, String base) { ExchangeInfo info = new ExchangeInfo(Action.SELL_MARKET, symbol, access, secret); info.base = base; return info; } public static ExchangeInfo multiBuy(String symbol, String access, String secret, List<Row> rows) { ExchangeInfo info = new ExchangeInfo(Action.MULTI_BUY, symbol, access, secret); info.rows = rows; return info; } public static ExchangeInfo multiSell(String symbol, String access, String secret, List<Row> rows) { ExchangeInfo info = new ExchangeInfo(Action.MULTI_SELL, symbol, access, secret); info.rows = rows; return info; } public static ExchangeInfo cancelOrder(String symbol, String access, String secret, String cancelId) { ExchangeInfo info = new ExchangeInfo(Action.CANCEL_ORDER, symbol, access, secret); info.cancelId = cancelId; return info; } public static ExchangeInfo cancelOrders(String symbol, String access, String secret, List<String> cancelIds) { ExchangeInfo info = new ExchangeInfo(Action.CANCEL_ORDERS, symbol, access, secret); info.cancelIds = cancelIds; return info; } // 订单接口 public static ExchangeInfo orders(String symbol, String access, String secret) { return new ExchangeInfo(Action.ORDERS, symbol, access, secret); } public static ExchangeInfo historyOrders(String symbol, String access, String secret) { return new ExchangeInfo(Action.HISTORY_ORDERS, symbol, access, secret); } public static ExchangeInfo order(String symbol, String access, String secret, String orderId) { ExchangeInfo info = new ExchangeInfo(Action.ORDER, symbol, access, secret); info.orderId = orderId; return info; } public static ExchangeInfo orderDetails(String symbol, String access, String secret, String orderId) { ExchangeInfo info = new ExchangeInfo(Action.ORDER_DETAILS, symbol, access, secret); info.orderId = orderId; return info; } public static ExchangeInfo orderDetailAll(String symbol, String access, String secret) { ExchangeInfo info = new ExchangeInfo(Action.ORDER_DETAILS, symbol, access, secret); return info; } // 推送接口 public static ExchangeInfo onTicker(String symbol, String access, String secret, String pushId) { return new ExchangeInfo(Action.ON_TICKER, symbol, access, secret, pushId); } public static ExchangeInfo onKlines(String symbol, String access, String secret, Period period, String pushId) { ExchangeInfo info = new ExchangeInfo(Action.ON_KLINES, symbol, access, secret, pushId); info.period = period; return info; } public static ExchangeInfo onDepth(String symbol, String access, String secret, String pushId) { return new ExchangeInfo(Action.ON_DEPTH, symbol, access, secret, pushId); } public static ExchangeInfo onTrades(String symbol, String access, String secret, String pushId) { return new ExchangeInfo(Action.ON_TRADES, symbol, access, secret, pushId); } public static ExchangeInfo onAccount(String symbol, String access, String secret, String pushId) { return new ExchangeInfo(Action.ON_ACCOUNT, symbol, access, secret, pushId); } public static ExchangeInfo onOrders(String symbol, String access, String secret, String pushId) { return new ExchangeInfo(Action.ON_ORDERS, symbol, access, secret, pushId); } /** * 错误提示 */ public String tip() { switch (action) { case TICKER : return action + " " + symbol + " " + Seal.seal(access); case KLINES : return action + " " + symbol + " " + Seal.seal(access) + " " + period; case DEPTH : return action + " " + symbol + " " + Seal.seal(access); case TRADES : return action + " " + symbol + " " + Seal.seal(access); case BALANCES : return action + " " + symbol + " " + Seal.seal(access); case ACCOUNT : return action + " " + symbol + " " + Seal.seal(access); case PRECISIONS : return action + " " + symbol + " " + Seal.seal(access); case PRECISION : return action + " " + symbol + " " + Seal.seal(access); case BUY_LIMIT : return action + " " + symbol + " " + Seal.seal(access) + " " + price + " " + amount; case SELL_LIMIT : return action + " " + symbol + " " + Seal.seal(access) + " " + price + " " + amount; case BUY_MARKET : return action + " " + symbol + " " + Seal.seal(access) + " " + quote; case SELL_MARKET : return action + " " + symbol + " " + Seal.seal(access) + " " + base; case MULTI_BUY : return action + " " + symbol + " " + Seal.seal(access) + " " + rows; case MULTI_SELL : return action + " " + symbol + " " + Seal.seal(access) + " " + rows; case CANCEL_ORDER : return action + " " + symbol + " " + Seal.seal(access) + " " + cancelId; case CANCEL_ORDERS : return action + " " + symbol + " " + Seal.seal(access) + " " + cancelIds; case ORDERS : return action + " " + symbol + " " + Seal.seal(access); case HISTORY_ORDERS : return action + " " + symbol + " " + Seal.seal(access); case ORDER : return action + " " + symbol + " " + Seal.seal(access) + " " + orderId; case ORDER_DETAILS : return action + " " + symbol + " " + Seal.seal(access) + " " + orderId; case ON_TICKER : return action + " " + symbol + " " + Seal.seal(access) + " " + pushId; case ON_KLINES : return action + " " + symbol + " " + Seal.seal(access) + " " + period + " " + pushId; case ON_DEPTH : return action + " " + symbol + " " + Seal.seal(access) + " " + pushId; case ON_TRADES : return action + " " + symbol + " " + Seal.seal(access) + " " + pushId; case ON_ACCOUNT : return action + " " + symbol + " " + Seal.seal(access) + " " + pushId; case ON_ORDERS : return action + " " + symbol + " " + Seal.seal(access) + " " + pushId; default: } return null; } public ExchangeInfo setPrice(String price) { this.price = price; return this; } public ExchangeInfo setAmount(String amount) { this.amount = amount; return this; } public ExchangeInfo setCancelId(String cancelId) { this.cancelId = cancelId; return this; } @Override public final ExchangeInfo clone() { try { return (ExchangeInfo) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return new ExchangeInfo(this.action, this.symbol, this.access, this.secret); } }
11,070
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Action.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/Action.java
package cqt.goai.exchange; /** * 请求行为动作 * @author GOAi */ public enum Action { // 市场接口 TICKER, KLINES, DEPTH, TRADES, // 账户接口 BALANCES, ACCOUNT, // 交易接口 PRECISIONS, PRECISION, BUY_LIMIT, SELL_LIMIT, BUY_MARKET, SELL_MARKET, MULTI_BUY, MULTI_SELL, CANCEL_ORDER, CANCEL_ORDERS, // 订单接口 ORDERS, HISTORY_ORDERS, ORDER, ORDER_DETAILS, // 推送接口 ON_TICKER, ON_KLINES, ON_DEPTH, ON_TRADES, ON_ACCOUNT, ON_ORDERS }
590
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
HistoryOrdersDetailsByTimestamp.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/HistoryOrdersDetailsByTimestamp.java
package cqt.goai.exchange.http; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.model.trade.OrderDetails; import dive.http.common.MimeHttp; import dive.http.common.MimeRequest; import org.slf4j.Logger; import java.util.List; /** * 获取历史订单明细 * * @author GOAi */ public interface HistoryOrdersDetailsByTimestamp { /** * 获取请求工具 * @return 请求工具 */ MimeHttp getHttp(); /** * 获取日志输出 * @return 日志 */ Logger getLog(); /** * 获取交易所名称 * @return 交易所名称 */ ExchangeName getExchangeName(); /** * 获取历史订单明细 * @param symbol 币对 * @param access access * @param secret secret * @param start 开始时间 * @param end 结束时间 * @return 订单明细 */ default OrderDetails getHistoryOrdersDetails(String symbol, String access, String secret, Long start, Long end) { List<MimeRequest> mimeRequests = this.historyOrdersDetailsRequests(symbol, access, secret, start, end, 0); List<String> results = HttpExchange.results(mimeRequests, this.getHttp(), this.getLog()); return this.parseHistoryOrdersDetails(results, symbol, access, secret); } /** * 获取历史订单明细请求 * @param symbol 币对 * @param access access * @param secret secret * @param start 开始时间戳 * @param end 截止时间戳 * @param delay 延时 * @return 请求 */ List<MimeRequest> historyOrdersDetailsRequests(String symbol, String access, String secret, Long start, Long end, long delay); /** * 解析历史订单明细 * @param results 请求结果 * @param symbol 币对 * @param access access * @param secret secret * @return 订单明细 */ default OrderDetails parseHistoryOrdersDetails(List<String> results, String symbol, String access, String secret) { return HttpExchange.analyze(results, ExchangeInfo.historyOrders(symbol, access, secret), this::transformHistoryOrdersDetails, this.getExchangeName(), this.getLog()); } /** * 解析历史订单明细 * @param results 请求结果 * @param info 请求信息 * @return 结果 */ OrderDetails transformHistoryOrdersDetails(List<String> results, ExchangeInfo info); }
2,476
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TradeByFillOrKill.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/TradeByFillOrKill.java
package cqt.goai.exchange.http; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import dive.http.common.MimeHttp; import dive.http.common.MimeRequest; import org.slf4j.Logger; import java.util.List; /** * fok交易 * * @author GOAi */ public interface TradeByFillOrKill { /** * 获取请求工具 * @return 请求工具 */ MimeHttp getHttp(); /** * 获取日志输出 * @return 日志 */ Logger getLog(); /** * 获取交易所名称 * @return 交易所名称 */ ExchangeName getExchangeName(); /** * 下fok买单 * @param access access * @param secret secret * @param symbol 币对 * @param price 价格 * @param amount 数量 * @return 订单id */ default String buyFillOrKill(String symbol, String access, String secret, String price, String amount) { List<MimeRequest> mimeRequests = this.buyFillOrKillRequests(symbol, access, secret, price, amount, 0); List<String> results = HttpExchange.results(mimeRequests, this.getHttp(), this.getLog()); return this.parseBuyFillOrKill(results, symbol, access, secret, price, amount); } /** * 获取fok买单请求 * @param symbol 币对 * @param access access * @param secret secret * @param price 价格 * @param amount 数量 * @param delay 延时 * @return 请求 */ List<MimeRequest> buyFillOrKillRequests(String symbol, String access, String secret, String price, String amount, long delay); /** * 解析fok订单 * @param results 请结果 * @param symbol 币对 * @param access access * @param secret secret * @param price 价格 * @param amount 数量 * @return 订单id */ default String parseBuyFillOrKill(List<String> results, String symbol, String access, String secret, String price, String amount) { return HttpExchange.analyze(results, ExchangeInfo.buyLimit(symbol, access, secret, price, amount), this::transformBuyFillOrKill, this.getExchangeName(), this.getLog()); } /** * 解析订单id * @param results 请结果 * @param info 请求信息 * @return 订单id */ String transformBuyFillOrKill(List<String> results, ExchangeInfo info); /** * 下fok卖单 * @param access access * @param secret secret * @param symbol 币对 * @param price 价格 * @param amount 数量 * @return 订单id */ default String sellFillOrKill(String symbol, String access, String secret, String price, String amount) { List<MimeRequest> mimeRequests = this.sellFillOrKillRequests(symbol, access, secret, price, amount, 0); List<String> results = HttpExchange.results(mimeRequests, this.getHttp(), this.getLog()); return this.parseSellFillOrKill(results, symbol, access, secret, price, amount); } /** * 获取fok卖单请求 * @param symbol 币对 * @param access access * @param secret secret * @param price 价格 * @param amount 数量 * @param delay 延时 * @return 请求 */ List<MimeRequest> sellFillOrKillRequests(String symbol, String access, String secret, String price, String amount, long delay); /** * 解析订单id * @param results 请结果 * @param symbol 币对 * @param access access * @param secret secret * @param price 价格 * @param amount 数量 * @return 订单id */ default String parseSellFillOrKill(List<String> results, String symbol, String access, String secret, String price, String amount) { return HttpExchange.analyze(results, ExchangeInfo.buyLimit(symbol, access, secret, price, amount), this::transformSellFillOrKill, this.getExchangeName(), this.getLog()); } /** * 解析订单id * @param results 请结果 * @param info 请求信息 * @return 订单id */ String transformSellFillOrKill(List<String> results, ExchangeInfo info); }
4,080
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
HistoryOrdersByTimestamp.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/HistoryOrdersByTimestamp.java
package cqt.goai.exchange.http; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.model.trade.Orders; import dive.http.common.MimeHttp; import dive.http.common.MimeRequest; import org.slf4j.Logger; import java.util.List; /** * 根据时间戳获取历史订单 * * @author GOAi */ public interface HistoryOrdersByTimestamp { /** * 获取请求工具 * @return 请求工具 */ MimeHttp getHttp(); /** * 获取日志输出 * @return 日志 */ Logger getLog(); /** * 获取交易所名称 * @return 交易所名称 */ ExchangeName getExchangeName(); /** * 获取历史订单 * @param access access * @param secret secret * @param symbol 币对 * @param start 开始时间 * @param end 结束时间 * @return Orders */ default Orders getHistoryOrders(String symbol, String access, String secret, Long start, Long end) { List<MimeRequest> mimeRequests = this.historyOrdersRequests(symbol, access, secret, start, end, 0); List<String> results = HttpExchange.results(mimeRequests, this.getHttp(), this.getLog()); return this.parseHistoryOrders(results, symbol, access, secret); } /** * 获取历史订单请求 * @param symbol 币对 * @param access access * @param secret secret * @param start 开始时间戳 * @param end 截止时间戳 * @param delay 延时 * @return 请求 */ List<MimeRequest> historyOrdersRequests(String symbol, String access, String secret, Long start, Long end, long delay); /** * 解析历史订单 * @param results 请结果 * @param symbol 币对 * @param access access * @param secret secret * @return 订单列表 */ default Orders parseHistoryOrders(List<String> results, String symbol, String access, String secret) { return HttpExchange.analyze(results, ExchangeInfo.historyOrders(symbol, access, secret), this::transformHistoryOrders, this.getExchangeName(), this.getLog()); } /** * 解析历史订单明细 * @param results 请结果 * @param info 请求信息 * @return 结果 */ Orders transformHistoryOrders(List<String> results, ExchangeInfo info); }
2,374
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
HttpExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/HttpExchange.java
package cqt.goai.exchange.http; import cqt.goai.exchange.*; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.model.enums.Period; import cqt.goai.model.market.Klines; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Ticker; import cqt.goai.model.market.Trades; import cqt.goai.model.trade.*; import dive.http.common.MimeHttp; import dive.http.common.MimeRequest; import org.slf4j.Logger; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.math.BigDecimal; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static dive.common.util.Util.exist; /** * Http请求,每个交易所的Http请求方式都要继承该类 * Abstract Factory Pattern 抽象工厂模式 * 任何一个交易所必须有这些接口,实现这些功能,提供这些Model,每个交易所实现方式不一样 * * @author GOAi */ public class HttpExchange extends BaseExchange { /** * http请求工具 */ protected final MimeHttp http; private HttpExchange(ExchangeName name, MimeHttp http, Logger log) { super(name, log); this.http = http; } public HttpExchange(ExchangeName name, Logger log) { this(name, ExchangeUtil.OKHTTP, log); } // =============== post request ================ protected void postRequest(ExchangeInfo info) { } // =============== change symbol =============== /** * 每个交易所使用的币对不一致,该方法针对需要的不同币对方式进行转换 * * @param info 请求信息 * @return 转换后的币对形式 */ public String symbol(ExchangeInfo info) { return info.getSymbol(); } // =============== tick =============== /** * 获取Ticker * * @param info 请求信息 * @return Ticker */ public final Ticker getTicker(ExchangeInfo info) { return this.get(info, this::tickerRequests, this::parseTicker); } /** * 获取Ticker的Http请求信息,每个交易所不一样 * * @param info 请求信息 * @param delay 延迟,毫秒,若通过其他节点请求则延时一段时间,封装的加密信息不至于过期失效 * @return Http请求信息 */ public List<MimeRequest> tickerRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } /** * 获取Ticker * * @param results 交易所返回的Ticker信息 * @param info 请求信息 * @return 处理后的Ticker */ public final Ticker parseTicker(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformTicker, this.name, this.log); } /** * 解析交易所返回的Ticker信息,每个交易所不一样 * * @param results 交易所返回的Ticker信息 * @param info 请求信息 * @return 处理后的Ticker */ protected Ticker transformTicker(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformTicker is not supported"); } // =============== klines =============== public final Klines getKlines(ExchangeInfo info) { return this.get(info, this::klinesRequests, this::parseKlines); } public List<MimeRequest> klinesRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Klines parseKlines(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformKlines, this.name, this.log); } protected Klines transformKlines(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformKlines is not supported"); } // =============== depth =============== public final Depth getDepth(ExchangeInfo info) { return this.get(info, this::depthRequests, this::parseDepth); } public List<MimeRequest> depthRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Depth parseDepth(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformDepth, this.name, this.log); } protected Depth transformDepth(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformKlines is not supported"); } // =============== trades =============== public final Trades getTrades(ExchangeInfo info) { return this.get(info, this::tradesRequests, this::parseTrades); } public List<MimeRequest> tradesRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Trades parseTrades(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformTrades, this.name, this.log); } protected Trades transformTrades(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformTrades is not supported"); } // =============== balances =============== public final Balances getBalances(ExchangeInfo info) { return this.get(info, this::balancesRequests, this::parseBalances); } public List<MimeRequest> balancesRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Balances parseBalances(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformBalances, this.name, this.log); } protected Balances transformBalances(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformBalances is not supported"); } // =============== account =============== public final Account getAccount(ExchangeInfo info) { return this.get(info, this::accountRequests, this::parseAccount); } public List<MimeRequest> accountRequests(ExchangeInfo info, long delay) { return this.balancesRequests(info, delay); } public final Account parseAccount(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformAccount, this.name, this.log); } protected Account transformAccount(List<String> results, ExchangeInfo info) { Balances balances = this.transformBalances(results, info); String[] symbols = CommonUtil.split(info.getSymbol()); Balance base = new Balance(null, symbols[0], BigDecimal.ZERO, BigDecimal.ZERO); Balance count = new Balance(null, symbols[1], BigDecimal.ZERO, BigDecimal.ZERO); for (Balance b : balances) { if (b.getCurrency().equals(symbols[0])) { base = b; } else if (b.getCurrency().equals(symbols[1])) { count = b; } } return new Account(System.currentTimeMillis(), base, count); } // =============== precisions =============== public final Precisions getPrecisions(ExchangeInfo info) { return this.get(info, this::precisionsRequests, this::parsePrecisions); } public List<MimeRequest> precisionsRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Precisions parsePrecisions(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformPrecisions, this.name, this.log); } protected Precisions transformPrecisions(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformPrecisions is not supported"); } // =============== precision =============== public final Precision getPrecision(ExchangeInfo info) { return this.get(info, this::precisionRequests, this::parsePrecision); } public List<MimeRequest> precisionRequests(ExchangeInfo info, long delay) { List<MimeRequest> requests = this.precisionsRequests(info, delay); if (requests.isEmpty()) { return this.depthRequests(info, delay); } return requests; } public final Precision parsePrecision(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformPrecision, this.name, this.log); } protected Precision transformPrecision(List<String> results, ExchangeInfo info) { List<MimeRequest> requests = this.precisionsRequests(info, 0); if (requests.isEmpty()) { // 走转换深度路线 Depth depth = this.transformDepth(results, info); return CommonUtil.parsePrecisionByDepth(depth, info.getSymbol()); } Precisions precisions = this.transformPrecisions(results, info); return precisions.stream() .filter(p -> info.getSymbol().equals(p.getSymbol())) .findAny() .orElse(null); } // =============== buy limit =============== public final String buyLimit(ExchangeInfo info) { return this.get(info, this::buyLimitRequests, this::parseBuyLimit); } public List<MimeRequest> buyLimitRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final String parseBuyLimit(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformBuyLimit, this.name, this.log); } public String transformBuyLimit(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformBuyLimit is not supported"); } // =============== sell limit =============== public final String sellLimit(ExchangeInfo info) { return this.get(info, this::sellLimitRequests, this::parseSellLimit); } public List<MimeRequest> sellLimitRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final String parseSellLimit(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformSellLimit, this.name, this.log); } public String transformSellLimit(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformSellLimit is not supported"); } // =============== buy market =============== public final String buyMarket(ExchangeInfo info) { return this.get(info, this::buyMarketRequests, this::parseBuyMarket); } public List<MimeRequest> buyMarketRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final String parseBuyMarket(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformBuyMarket, this.name, this.log); } public String transformBuyMarket(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformBuyMarket is not supported"); } // =============== sell market =============== public final String sellMarket(ExchangeInfo info) { return this.get(info, this::sellMarketRequests, this::parseSellMarket); } public List<MimeRequest> sellMarketRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final String parseSellMarket(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformSellMarket, this.name, this.log); } public String transformSellMarket(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformSellMarket is not supported"); } // =============== multi buy market =============== public final List<String> multiBuy(ExchangeInfo info) { return this.get(info, this::multiBuyRequests, this::parseMultiBuy); } public List<MimeRequest> multiBuyRequests(ExchangeInfo info, long delay) { return Stream.iterate(0, i -> i + 1) .limit(info.getRows().size()) .map(i -> this.buyLimitRequests(info.clone() .setPrice(info.getRows().get(i).getPrice().toPlainString()) .setAmount(info.getRows().get(i).getAmount().toPlainString()), delay + i)) .flatMap(Collection::stream) .collect(Collectors.toList()); } public final List<String> parseMultiBuy(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformMultiBuy, this.name, this.log); } public List<String> transformMultiBuy(List<String> results, ExchangeInfo info) { return Stream.iterate(0, i -> i + 1) .limit(results.size()) .map(i -> this.transformBuyLimit(results.subList(i, i + 1), info.clone().setPrice(info.getRows().get(i).getPrice().toPlainString()) .setAmount(info.getRows().get(i).getAmount().toPlainString()))) .collect(Collectors.toList()); } // =============== multi sell market =============== public final List<String> multiSell(ExchangeInfo info) { return this.get(info, this::multiSellRequests, this::parseMultiSell); } public List<MimeRequest> multiSellRequests(ExchangeInfo info, long delay) { return Stream.iterate(0, i -> i + 1) .limit(info.getRows().size()) .map(i -> this.sellLimitRequests(info.clone() .setPrice(info.getRows().get(i).getPrice().toPlainString()) .setAmount(info.getRows().get(i).getAmount().toPlainString()), delay + i)) .flatMap(Collection::stream) .collect(Collectors.toList()); } public final List<String> parseMultiSell(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformMultiSell, this.name, this.log); } public List<String> transformMultiSell(List<String> results, ExchangeInfo info) { return Stream.iterate(0, i -> i + 1) .limit(results.size()) .map(i -> this.transformSellLimit(results.subList(i, i + 1), info.clone() .setPrice(info.getRows().get(i).getPrice().toPlainString()) .setAmount(info.getRows().get(i).getAmount().toPlainString()))) .collect(Collectors.toList()); } // =============== cancel order =============== public final Boolean cancelOrder(ExchangeInfo info) { return this.get(info, this::cancelOrderRequests, this::parseCancelOrder); } public List<MimeRequest> cancelOrderRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Boolean parseCancelOrder(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformCancelOrder, this.name, this.log); } protected Boolean transformCancelOrder(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformCancelOrder is not supported"); } // =============== cancel orders =============== public final List<String> cancelOrders(ExchangeInfo info) { return this.get(info, this::cancelOrdersRequests, this::parseCancelOrders); } public List<MimeRequest> cancelOrdersRequests(ExchangeInfo info, long delay) { return Stream.iterate(0, i -> i + 1) .limit(info.getCancelIds().size()) .map(i -> this.cancelOrderRequests(info.clone().setCancelId(info.getCancelIds().get(i)), delay + i)) .flatMap(Collection::stream) .collect(Collectors.toList()); } public final List<String> parseCancelOrders(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformCancelOrders, this.name, this.log); } public List<String> transformCancelOrders(List<String> results, ExchangeInfo info) { return Stream.iterate(0, i -> i + 1) .limit(results.size()) .filter(i -> { Boolean result = this.transformCancelOrder(results.subList(i, i + 1), info.clone() .setCancelId(info.getCancelIds().get(i))); return null != result && result; }) .map(i -> info.getCancelIds().get(i)) .collect(Collectors.toList()); } // =============== orders =============== public final Orders getOrders(ExchangeInfo info) { return this.get(info, this::ordersRequests, this::parseOrders); } public List<MimeRequest> ordersRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Orders parseOrders(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformOrders, this.name, this.log); } protected Orders transformOrders(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformOrders is not supported"); } // =============== historyOrders =============== public final Orders getHistoryOrders(ExchangeInfo info) { return this.get(info, this::historyOrdersRequests, this::parseHistoryOrders); } public List<MimeRequest> historyOrdersRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Orders parseHistoryOrders(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformHistoryOrders, this.name, this.log); } protected Orders transformHistoryOrders(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformHistoryOrders is not supported"); } // =============== order =============== public final Order getOrder(ExchangeInfo info) throws ExchangeException { return this.get(info, this::orderRequests, this::parseOrder); } public List<MimeRequest> orderRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final Order parseOrder(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformOrder, this.name, this.log); } protected Order transformOrder(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformOrder is not supported"); } // =============== details =============== public final OrderDetails getOrderDetails(ExchangeInfo info) { return this.get(info, this::orderDetailsRequests, this::parseOrderDetails); } public List<MimeRequest> orderDetailsRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final OrderDetails parseOrderDetails(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformOrderDetails, this.name, this.log); } protected OrderDetails transformOrderDetails(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformOrderDetails is not supported"); } public final OrderDetails getOrderDetailAll(ExchangeInfo info) { return this.get(info, this::orderDetailAllRequests, this::parseOrderDetailAll); } public List<MimeRequest> orderDetailAllRequests(ExchangeInfo info, long delay) { return Collections.emptyList(); } public final OrderDetails parseOrderDetailAll(List<String> results, ExchangeInfo info) { return HttpExchange.analyze(results, info, this::transformOrderDetailAll, this.name, this.log); } public OrderDetails transformOrderDetailAll(List<String> results, ExchangeInfo info) { throw new ExchangeException("transformOrderDetailAll is not supported"); } // =============== tools =============== /** * 统一转换币对方式,主要是报错 * * @param info 请求信息 * @param change 转换函数 * @return 转换结果 */ protected String symbol(ExchangeInfo info, Function<String, String> change) { String symbol = info.getSymbol(); Exception exception; try { return change.apply(symbol); } catch (Exception e) { this.log.error("{} {} exception is {}", super.name, info.tip(), e.getMessage()); exception = e; } String message = String.format("%s %s can not identify symbol: %s", super.name, info.tip(), symbol); this.log.error(message); if (exist(exception)) { throw new ExchangeException(ExchangeError.SYMBOL, message, exception); } throw new ExchangeException(ExchangeError.SYMBOL, message); } /** * 执行Http请求信息 * * @param requests Http请求信息 * @return 执行结果 */ protected static List<String> results(List<MimeRequest> requests, MimeHttp http, Logger log) { if (null == requests) { return null; } return requests.stream() // .map(r -> r.execute(http)) .map(r -> r.execute(http, (url, method, request, body, code, response, result) -> { if (null != result) { return; } log.info("url: " + url); log.info("method: " + method); log.info("requestHeader: " + request); log.info("body: " + body); log.info("code: " + code); log.info("responseHeader: " + response); //noinspection ConstantConditions log.info("result: " + result); })) .collect(Collectors.toList()); } /** * 统一请求 * * @param info 请求信息 * @param requests 生成Http请求信息 * @param analyze 解析请求结果 * @param <R> 请求类型 * @return 请求结果 */ private <R> R get(ExchangeInfo info, BiFunction<ExchangeInfo, Long, List<MimeRequest>> requests, BiFunction<List<String>, ExchangeInfo, R> analyze) { List<MimeRequest> mimeRequests = requests.apply(info, 0L); List<String> results; try { results = HttpExchange.results(mimeRequests, this.http, this.log); } catch (Exception e){ this.postRequest(info); throw e; } return analyze.apply(results, info); } /** * 解析请求结果 * * @param results 请求结果 * @param info 请求信息 * @param analyze 解析函数 * @param <R> 结果类型 * @return 结果 */ static <R> R analyze(List<String> results, ExchangeInfo info, BiFunction<List<String>, ExchangeInfo, R> analyze, ExchangeName name, Logger log) { Exception exception = null; try { R r = analyze.apply(results, info); if (exist(r)) { return r; } } catch (Exception e) { log.error("{} {} exception is {}", name.getName(), info.tip(), e); exception = e; } String message = String.format("%s %s failed. results is %s", name.getName(), info.tip(), "[" + String.join(",", results) + "]"); log.error(message); if (exist(exception)) { throw new ExchangeException(message, exception); } throw new ExchangeException(message); } /** * K线周期转换 * * @param info 请求信息 * @param function 转换函数 * @param <R> 结果类型 * @return 结果 */ protected <R> R period(ExchangeInfo info, Function<Period, R> function) { R r = function.apply(info.getPeriod()); if (exist(r)) { return r; } String message = String.format("%s %s period is nonsupport: %s", name, info.tip(), info.getPeriod()); log.error(message); throw new ExchangeException(ExchangeError.PERIOD, message); } protected static String hmacSha256(String message, String secret) { try { final String hmacSHA256 = "HmacSHA256"; Mac sha256hMac = Mac.getInstance(hmacSHA256); SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), hmacSHA256); sha256hMac.init(secretKeySpec); return new String(encodeHex(sha256hMac.doFinal(message.getBytes()))); } catch (Exception e) { throw new RuntimeException("Unable to sign message.", e); } } private static char[] encodeHex(byte[] data) { int l = data.length; char[] out = new char[l << 1]; int i = 0; for (int var5 = 0; i < l; ++i) { out[var5++] = DIGITS_LOWER[(240 & data[i]) >>> 4]; out[var5++] = DIGITS_LOWER[15 & data[i]]; } return out; } private static final char[] DIGITS_LOWER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; }
25,429
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BitfinexExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/bitfinex/BitfinexExchange.java
package cqt.goai.exchange.http.bitfinex; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeException; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HistoryOrdersByTimestamp; import cqt.goai.exchange.http.HistoryOrdersDetailsByTimestamp; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.http.TradeByFillOrKill; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.exchange.util.bitfinex.BitfinexUtil; import cqt.goai.model.enums.State; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import dive.http.common.MimeHttp; import dive.http.common.MimeRequest; import dive.http.common.model.Parameter; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import static dive.common.util.Util.useful; /** * @author */ public class BitfinexExchange extends HttpExchange implements HistoryOrdersByTimestamp, HistoryOrdersDetailsByTimestamp, TradeByFillOrKill { private static final String SITE = "api.bitfinex.com"; private static final String ADDRESS = "https://" + SITE; private static final String TICKER = "/v1/pubticker/"; private static final String KLINES = "/v2/candles/trade"; private static final String DEPTH = "/v1/book/"; private static final String TRADES = "/v1/trades/"; private static final String ACCOUNT = "/v1/balances"; private static final String ORDERS = "/v1/orders"; private static final String HISTORY_ORDERS = "/v2/auth/r/orders/{Symbol}/hist"; private static final String ORDER = "/v1/order/status"; private static final String ORDER_DETAILS = "/v2/auth/r/order/{Symbol}:{OrderId}/trades"; private static final String PRECISIONS = "/v1/symbols_details"; private static final String ORDER_NEW = "/v1/order/new"; private static final String MULTI_ORDERS = "/v1/order/new/multi"; private static final String ORDER_CANCEL = "/v1/order/cancel"; private static final String CANCEL_MULTI_ORDERS = "/v1/order/cancel/multi"; private static final String HISTORY_ORDERS_DETAILS = "/v2/auth/r/trades/{Symbol}/hist"; public BitfinexExchange(Logger log) { super(ExchangeName.BITFINEX, log); } @Override protected void postRequest(ExchangeInfo info) { switch (info.getAction()) { case TICKER: case KLINES: case DEPTH: case TRADES: case PRECISION: case PRECISIONS: return; default: this.unlock(info); } } @Override public String symbol(ExchangeInfo info) { return symbol(info, s -> s.replace("_", "")); } @Override public List<MimeRequest> tickerRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + TICKER + this.symbol(info)) .build(); return Collections.singletonList(request); } @Override protected Ticker transformTicker(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject d = JSON.parseObject(result); /*{ "mid":"3953.05", "bid":"3953.0", "ask":"3953.1", "last_price":"3953.1", "low":"3902.0", "high":"4227.0", "volume":"37560.79069276", "timestamp":"1545458269.236464" }*/ BigDecimal timestamp = d.getBigDecimal("timestamp"); Long time = timestamp.multiply(CommonUtil.THOUSAND).longValue(); // BigDecimal open = null; BigDecimal high = d.getBigDecimal("high"); BigDecimal low = d.getBigDecimal("low"); BigDecimal close = d.getBigDecimal("last_price"); BigDecimal volume = d.getBigDecimal("volume"); return new Ticker(result, time, null, high, low, close, volume); } return null; } @Override public List<MimeRequest> klinesRequests(ExchangeInfo info, long delay) { String timeFrame = period(info, BitfinexUtil::getPeriod); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + KLINES + ":{TimeFrame}:t{Symbol}/{Section}") //":" + timeFrame + ":t" + this.symbol(info) + "/hist?limit=" + 200 + "&sortOrder=" + 1) .replace("TimeFrame", timeFrame) .replace("Symbol", this.symbol(info)) .replace("Section", "hist") .body("limit", 200) .body("sortOrder", -1) .build(); return Collections.singletonList(request); } @Override protected Klines transformKlines(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray array = JSON.parseArray(result); List<Kline> klines = new ArrayList<>(array.size()); long step = info.getPeriod().getValue(); Long lastTime = null; BigDecimal lastClose = null; // new ... old for (int i = array.size() - 1; 0 <= i; i--) { JSONArray t = array.getJSONArray(i); /* [ MTS 1364824380000, OPEN 99.01, CLOSE 99.01, HIGH 99.01, LOW 99.01, VOLUME 6 ] */ Long time = t.getLong(0) / 1000; if (null != lastTime) { while (lastTime + step < time) { // lastTime = lastTime + step; klines.add(new Kline(String.format("[%s,%s,%s,%s,%s,%s]", lastTime * 1000, lastClose, lastClose, lastClose, lastClose, 0), lastTime, lastClose, lastClose, lastClose, lastClose, BigDecimal.ZERO)); } } Kline kline = CommonUtil.parseKlineByIndex(result, t, time, 1); klines.add(kline); lastTime = time; lastClose = kline.getClose(); } Collections.reverse(klines); return new Klines(klines); } return null; } @Override public List<MimeRequest> depthRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + DEPTH + this.symbol(info) + "?limit_bids=200&limit_asks=200") .build(); return Collections.singletonList(request); } @Override protected Depth transformDepth(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSONObject.parseObject(result); return BitfinexUtil.parseDepth(r); } return null; } @Override public List<MimeRequest> tradesRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + TRADES + this.symbol(info) + "?limit_trades=200") .build(); return Collections.singletonList(request); } @Override protected Trades transformTrades(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseArray(result); return BitfinexUtil.parseTrades(r); } return null; } @Override public List<MimeRequest> balancesRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ACCOUNT, "request", ACCOUNT, "nonce", nonce); } @Override protected Balances transformBalances(List<String> results, ExchangeInfo info) { this.unlock(info); String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseArray(result); List<Balance> balances = BitfinexUtil.parseBalances(r); return new Balances(balances); } return null; } @Override public List<MimeRequest> accountRequests(ExchangeInfo info, long delay) { return this.balancesRequests(info, delay); } @Override protected Account transformAccount(List<String> results, ExchangeInfo info) { this.unlock(info); Account account = super.transformAccount(results, info); Balance base = account.getBase(); Balance count = account.getQuote(); String[] symbols = CommonUtil.split(info.getSymbol()); if (null == base) { base = new Balance(String.format("{\"type\":\"exchange\"," + "\"currency\":\"%s\"," + "\"amount\":\"%s\"," + "\"available\":\"%s\"}", symbols[0].toLowerCase(), 0, 0), symbols[0], BigDecimal.ZERO, BigDecimal.ZERO); } if (null == count) { count = new Balance(String.format("{\"type\":\"exchange\"," + "\"currency\":\"%s\"," + "\"amount\":\"%s\"," + "\"available\":\"%s\"}", symbols[1].toLowerCase(), 0, 0), symbols[1], BigDecimal.ZERO, BigDecimal.ZERO); } return new Account(System.currentTimeMillis(), base, count); } @Override public List<MimeRequest> precisionsRequests(ExchangeInfo info, long delay) { if (System.currentTimeMillis() < lastRequest + MIN_GAP) { return Collections.emptyList(); } MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + PRECISIONS) .build(); return Collections.singletonList(request); } @Override protected Precisions transformPrecisions(List<String> results, ExchangeInfo info) { String result; if (System.currentTimeMillis() < lastRequest + MIN_GAP) { result = precisionsResult; } else { result = results.get(0); precisionsResult = result; lastRequest = System.currentTimeMillis(); } return new Precisions(BitfinexUtil.parsePrecisions(result)); } @Override public List<MimeRequest> precisionRequests(ExchangeInfo info, long delay) { List<MimeRequest> requests = new LinkedList<>(this.depthRequests(info, delay)); requests.addAll(this.precisionsRequests(info, delay)); return requests; } @Override protected Precision transformPrecision(List<String> results, ExchangeInfo info) { Precisions precisions; if (1 < results.size()) { // 有请求币对信息 precisions = this.transformPrecisions(results.subList(1, 2), info); } else { precisions = new Precisions(BitfinexUtil.parsePrecisions(precisionsResult)); } Precision precision = null; for (Precision p : precisions) { if (info.getSymbol().equals(p.getSymbol())) { precision = p; break; } } if (null == precision) { return null; } // 解析深度信息获取 数量最小精度 Depth depth = this.transformDepth(results, info); Precision p = CommonUtil.parsePrecisionByDepth(depth, info.getSymbol()); return new Precision(precision.getData(), precision.getSymbol(), p.getBase(), p.getQuote(), precision.getBaseStep(), precision.getQuoteStep(), precision.getMinBase(), precision.getMinQuote(), precision.getMaxBase(), precision.getMaxQuote()); } @Override public List<MimeRequest> buyLimitRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ORDER_NEW, "request", ORDER_NEW, "nonce", nonce, "symbol", this.symbol(info), "amount", info.getAmount(), "price", info.getPrice(), "side", "buy", "type", "exchange limit", "ocoorder ", "false"); } @Override public String transformBuyLimit(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseId(results.get(0)); } @Override public List<MimeRequest> sellLimitRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ORDER_NEW, "request", ORDER_NEW, "nonce", nonce, "symbol", this.symbol(info), "amount", info.getAmount(), "price", info.getPrice(), "side", "sell", "type", "exchange limit", "ocoorder ", "false"); } @Override public String transformSellLimit(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseId(results.get(0)); } @Override public List<MimeRequest> buyMarketRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ORDER_NEW, "request", ORDER_NEW, "nonce", nonce, "symbol", this.symbol(info), "amount", info.getQuote(), "price", info.getQuote(), "side", "buy", "type", "exchange market", "ocoorder ", "false"); } @Override public String transformBuyMarket(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseId(results.get(0)); } @Override public List<MimeRequest> sellMarketRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ORDER_NEW, "request", ORDER_NEW, "nonce", nonce, "symbol", this.symbol(info), "amount", info.getBase(), "price", info.getBase(), "side", "sell", "type", "exchange market", "ocoorder ", "false"); } @Override public String transformSellMarket(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseId(results.get(0)); } @Override public List<MimeRequest> multiBuyRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); List<Map<String, Object>> orders = this.getMultiOrders(info, "buy"); return this.post(info, MULTI_ORDERS, "request", MULTI_ORDERS, "nonce", nonce, "orders", orders); } @Override public List<String> transformMultiBuy(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseOrderIds(results.get(0)); } @Override public List<MimeRequest> multiSellRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); List<Map<String, Object>> orders = this.getMultiOrders(info, "sell"); return this.post(info, MULTI_ORDERS, "request", MULTI_ORDERS, "nonce", nonce, "orders", orders); } @Override public List<String> transformMultiSell(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseOrderIds(results.get(0)); } @Override public List<MimeRequest> cancelOrderRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ORDER_CANCEL, "request", ORDER_CANCEL, "nonce", nonce, "symbol", this.symbol(info), "order_id", Long.parseLong(info.getCancelId())); } @Override protected Boolean transformCancelOrder(List<String> results, ExchangeInfo info) { this.unlock(info); String result = results.get(0); if (useful(result)) { BitfinexUtil.parseOrder(result, JSON.parseObject(result)); return true; } return null; } @Override public List<MimeRequest> cancelOrdersRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, CANCEL_MULTI_ORDERS, "request", CANCEL_MULTI_ORDERS, "nonce", nonce, "symbol", this.symbol(info), "order_ids", info.getCancelIds().stream() .map(Long::parseLong) .collect(Collectors.toList())); } /** * 一个都没取消 */ private static final String NONE = "None to cancel"; @Override public List<String> transformCancelOrders(List<String> results, ExchangeInfo info) { this.unlock(info); log.info("results -> {}", results); String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseArray(result).getJSONObject(0); result = r.getString("result"); if (null == result) { return null; } if (NONE.equals(result)) { return Collections.emptyList(); } if (result.contains(String.valueOf(info.getCancelIds().size()))) { return info.getCancelIds(); } } return null; } @Override public List<MimeRequest> ordersRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ORDERS, "request", ORDERS, "nonce", nonce); } @Override protected Orders transformOrders(List<String> results, ExchangeInfo info) { this.unlock(info); String result = results.get(0); if (useful(result)) { List<Order> orders = this.parseOrders(result, this.symbol(info).toLowerCase()); orders = orders.stream() .filter(o -> o.getState() == State.SUBMIT || o.getState() == State.PARTIAL) .sorted((o1, o2) -> o2.getTime().compareTo(o1.getTime())) .collect(Collectors.toList()); return new Orders(orders); } return null; } @Override public List<MimeRequest> historyOrdersRequests(ExchangeInfo info, long delay) { return this.historyOrdersRequests(info.getSymbol(), info.getAccess(), info.getSecret(), null, System.currentTimeMillis(), delay); } @Override public Orders transformHistoryOrders(List<String> results, ExchangeInfo info) { this.unlock(info); String result = results.get(0); if (useful(result)) { List<Order> orders = BitfinexUtil.parseOrders(result); orders = orders.stream() .sorted((o1, o2) -> o2.getTime().compareTo(o1.getTime())) .collect(Collectors.toList()); return new Orders(orders); } return null; } @Override public List<MimeRequest> orderRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); return this.post(info, ORDER, "request", ORDER, "nonce", nonce, "symbol", this.symbol(info), "order_id", Long.parseLong(info.getOrderId())); } @Override protected Order transformOrder(List<String> results, ExchangeInfo info) { this.unlock(info); String result = results.get(0); if (useful(result)) { return BitfinexUtil.parseOrder(result, JSON.parseObject(result)); } return null; } @Override public List<MimeRequest> orderDetailsRequests(ExchangeInfo info, long delay) { String nonce = this.lock(info); String symbol = this.symbol(info); String path = ORDER_DETAILS.replace("{Symbol}", "t" + symbol) .replace("{OrderId}", info.getOrderId()); Parameter para = Parameter.build(); String parameter = para.sort().json(JSON::toJSONString); // signature = `/api/${apiPath}${nonce}${JSON.stringify(body)}` String signature = CommonUtil.hmacSha384("/api" + path + nonce + parameter, info.getSecret()); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + path) .post() .header("bfx-nonce", nonce) .header("bfx-apikey", info.getAccess()) .header("bfx-signature", signature) .body(parameter) .build(); return Collections.singletonList(request); } @Override public OrderDetails transformOrderDetails(List<String> results, ExchangeInfo info) { this.unlock(info); String result = results.get(0); if (useful(result)) { List<OrderDetail> details = BitfinexUtil.parseOrderDetails(result); details = details.stream() .sorted((d1, d2) -> d2.getTime().compareTo(d1.getTime())) .collect(Collectors.toList()); return new OrderDetails(details); } return null; } // ======================== tools ===================== /** * 上次币对请求结果 */ private static String precisionsResult; /** * 上次币对请求时间 */ private static long lastRequest; /** * 最小间隔12s */ private static final long MIN_GAP = 1000 * 12; /** * 签名算法需要用nonce,必须要求递增,所以在高并发下,不能能够使用当前时间戳 * 用map存储每次使用过的nonce * key --> symbol:access */ private static final ConcurrentHashMap<String, Long> NONCE = new ConcurrentHashMap<>(); /** * 高并发下,两次请求无法确定请求的先后,只好对所有的要求签名方法进行加锁,等一个请求结果回来了,再请求下一个 * key --> symbol:access */ private static final ConcurrentHashMap<String, ReentrantLock> LOCKS = new ConcurrentHashMap<>(); /** * 尝试等待获取锁的时间,毫秒 */ private static final int WAIT = 3000; /** * 最大锁时间,超过该时间,强制解锁 */ private static final int MAX_LOCK_TIME = 1000 * 20; private String getKey(ExchangeInfo info) { // 不清楚用什么做key合适,symbol:access 还是会报nonce异常,搞不好是根据ip来的,那就连map也不用了 return info.getSymbol() + ":" + info.getAccess(); } /** * 获取nonce * @param info 请求信息 * @return nonce */ private String getNonce(ExchangeInfo info) { String key = this.getKey(info); Long nonce = NONCE.get(key); long now = System.currentTimeMillis(); if (null == nonce) { nonce = now; } else if (nonce == now) { nonce++; } else if (nonce < now) { nonce = now; } NONCE.put(key, nonce); return String.valueOf(nonce); } /** * 进行加锁 * @param info 请求信息 */ private String lock(ExchangeInfo info) { String key = this.getKey(info); Lock lock = LOCKS.computeIfAbsent(key, k -> new ReentrantLock()); try { if (lock.tryLock(WAIT, TimeUnit.MILLISECONDS)) { return this.getNonce(info); } else { Long nonce = NONCE.get(key); if (nonce + MAX_LOCK_TIME < System.currentTimeMillis()) { this.unlock(info); } throw new ExchangeException("there are too many request. locks already!!"); } } catch (Exception e) { throw new RuntimeException(e); } } /** * 解锁 * @param info 请求信息 */ private void unlock(ExchangeInfo info) { String key = this.getKey(info); ReentrantLock lock = LOCKS.get(key); if (null != lock && lock.isLocked()) { lock.unlock(); } } /** * post请求 * @param info 请求信息 * @param path 请求路径 * @param others 其他参数 * @return 封装请求信息 */ private List<MimeRequest> post(ExchangeInfo info, String path, Object... others) { String access = info.getAccess(); String secret = info.getSecret(); String parameter = CommonUtil.addOtherParameterToJson(Parameter.build(), others); String payload = Base64.getEncoder().encodeToString(parameter.getBytes()); String signature = CommonUtil.hmacSha384(payload, secret); return Collections.singletonList(new MimeRequest.Builder() .url(ADDRESS + path) .post() .header("X-BFX-APIKEY", access) .header("X-BFX-PAYLOAD", payload) .header("X-BFX-SIGNATURE", signature) .build()); } /** * 解析orders * @param result 请求结果 * @return orders */ private List<Order> parseOrders(String result, String symbol) { JSONArray r = JSON.parseArray(result); List<Order> orders = new LinkedList<>(); for (int i = 0; i < r.size(); i++) { JSONObject o = r.getJSONObject(i); if (symbol.equalsIgnoreCase(o.getString("symbol"))) { orders.add(BitfinexUtil.parseOrder(r.getString(i), o)); } } return orders; } /** * 解析订单id * @param result 原始数据 * @return 订单id */ private String parseId(String result) { if (useful(result)) { JSONObject r = JSON.parseObject(result); return r.getString("id"); } return null; } /** * 统一定制多笔订单的请求信息 * @param info 请信息 * @param side 买卖方向 * @return 请求信息 */ private List<Map<String, Object>> getMultiOrders(ExchangeInfo info, String side) { String symbol = this.symbol(info); return info.getRows().stream().map(r -> { /* * symbol: 'BTCUSD', * amount: '0.011', * price: '1000', * exchange: 'bitfinex', * side: 'buy', * type: 'exchange market' */ Map<String, Object> map = new HashMap<>(6); map.put("symbol", symbol); map.put("amount", r.getAmount()); map.put("price", r.getPrice()); map.put("exchange", "bitfinex"); map.put("side", side); map.put("type", "exchange limit"); return map; }).collect(Collectors.toList()); } private static final String SUCCESS = "success"; private static final String STATUS = "status"; /** * 取出多个下单结果的id * @param result 请求结果 * @return 订单id */ private List<String> parseOrderIds(String result) { JSONObject r = JSON.parseObject(result); if (!SUCCESS.equals(r.getString(STATUS))) { return null; } JSONArray array = r.getJSONArray("order_ids"); List<String> ids = new ArrayList<>(array.size()); for (int i = 0; i < array.size(); i++) { ids.add(array.getJSONObject(i).getString("id")); } return ids; } // ======================== special api ========================== /** * v2版本的post请求封装 * @param info 请求信息 access secret symbol * @param nonce nonce * @param path 路径 * @param others 其他参数 * @return 请求信息 */ private static List<MimeRequest> postV2(ExchangeInfo info, String nonce, String path, Object... others) { String access = info.getAccess(); String secret = info.getSecret(); String parameter = CommonUtil.addOtherParameterToJson(Parameter.build(), others); // signature = `/api/${apiPath}${nonce}${JSON.stringify(body)}` String signature = CommonUtil.hmacSha384("/api" + path + nonce + parameter, secret); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + path) .post() .header("bfx-nonce", nonce) .header("bfx-apikey", access) .header("bfx-signature", signature) .body(parameter) .build(); return Collections.singletonList(request); } /** * 获取参数列表 获取历史订单和历史订单明细都需要这些 * @param start 开始时间 * @param end 结束时间 * @param limit 限制个数 * @return 参数列表 */ private static List<Object> getParameterList(Long start, Long end, Integer limit) { List<Object> list = new LinkedList<>(); if (null != start) { list.add("start"); list.add(start); } if (null != end) { list.add("end"); list.add(end); } list.add("limit"); list.add(limit); return list; } @Override public MimeHttp getHttp() { return super.http; } @Override public ExchangeName getExchangeName() { return this.name; } @Override public Logger getLog() { return this.log; } @Override public List<MimeRequest> historyOrdersRequests(String symbol, String access, String secret, Long start, Long end, long delay) { ExchangeInfo info = ExchangeInfo.historyOrders(symbol, access, secret); String nonce = this.lock(info); symbol = this.symbol(info); String path = HISTORY_ORDERS.replace("{Symbol}", "t" + symbol); List<Object> list = BitfinexExchange.getParameterList(start, end, 500); list.add("sortOrder"); list.add(-1); return BitfinexExchange.postV2(info, nonce, path, list.toArray(new Object[]{})); } @Override public List<MimeRequest> historyOrdersDetailsRequests(String symbol, String access, String secret, Long start, Long end, long delay) { ExchangeInfo info = ExchangeInfo.historyOrders(symbol, access, secret); String nonce = this.lock(info); symbol = this.symbol(info); String path = HISTORY_ORDERS_DETAILS.replace("{Symbol}", "t" + symbol); List<Object> list = BitfinexExchange.getParameterList(start, end, 1000); return BitfinexExchange.postV2(info, nonce, path, list.toArray(new Object[]{})); } /** * 解析历史订单明细 * [ * 334330310, ID integer Trade database id * "tVSYBTC", PAIR string Pair (BTCUSD, …) * 1548318500000, MTS_CREATE integer Execution timestamp * 21775101099, ORDER_ID integer Order id * 109.5576846, EXEC_AMOUNT float Positive means buy, negative means sell * 0.0000081, EXEC_PRICE float Execution price * null, ORDER_TYPE string Order type * null, ORDER_PRICE float Order price * -1, MAKER int 1 if true, 0 if false * -0.21911537, FEE float Fee * "VSY" FEE_CURRENCY string Fee currency * ] * * * @param results 请求结果 * @return 历史订单明细 */ @Override public OrderDetails transformHistoryOrdersDetails(List<String> results, ExchangeInfo info) { return this.transformOrderDetails(results, info); } @Override public List<MimeRequest> buyFillOrKillRequests(String symbol, String access, String secret, String price, String amount, long delay) { ExchangeInfo info = ExchangeInfo.buyLimit(symbol, access, secret, price, amount); String nonce = this.lock(info); return this.post(info, ORDER_NEW, "request", ORDER_NEW, "nonce", nonce, "symbol", this.symbol(info), "amount", info.getAmount(), "price", info.getPrice(), "side", "buy", "type", "exchange fill-or-kill", "ocoorder ", "false"); } @Override public String transformBuyFillOrKill(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseId(results.get(0)); } @Override public List<MimeRequest> sellFillOrKillRequests(String symbol, String access, String secret, String price, String amount, long delay) { ExchangeInfo info = ExchangeInfo.sellLimit(symbol, access, secret, price, amount); String nonce = this.lock(info); return this.post(info, ORDER_NEW, "request", ORDER_NEW, "nonce", nonce, "symbol", this.symbol(info), "amount", info.getAmount(), "price", info.getPrice(), "side", "sell", "type", "exchange fill-or-kill", "ocoorder ", "false"); } @Override public String transformSellFillOrKill(List<String> results, ExchangeInfo info) { this.unlock(info); return this.parseId(results.get(0)); } }
33,978
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Okexv3Exchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/okexv3/Okexv3Exchange.java
package cqt.goai.exchange.http.okexv3; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.exchange.util.okexv3.Okexv3Util; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import dive.common.crypto.Base64Util; import dive.common.crypto.HmacUtil; import dive.common.math.RandomUtil; import dive.http.common.MimeRequest; import dive.http.common.model.Header; import dive.http.common.model.Parameter; import org.slf4j.Logger; import java.math.BigDecimal; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.stream.Collectors; import static dive.common.util.DateUtil.SECOND; import static dive.common.util.DateUtil.formatISO8601; import static dive.common.util.UrlUtil.urlEncode; import static dive.common.util.Util.exist; import static dive.common.util.Util.useful; /** * OKExV3Exchange * * @author GOAi */ public class Okexv3Exchange extends HttpExchange { private static final String SITE = "www.okex.com"; private static final String ADDRESS = "https://" + SITE; private static final String TICKER = "/api/spot/v3/instruments/{instrumentId}/ticker"; private static final String KLINES = "/api/spot/v3/instruments/{instrumentId}/candles"; private static final String DEPTH = "/api/spot/v3/instruments/{instrumentId}/book?size=200"; private static final String TRADES = "/api/spot/v3/instruments/{instrumentId}/trades"; private static final String ACCOUNT = "/api/spot/v3/accounts/"; private static final String BALANCES = "/api/spot/v3/accounts"; private static final String ORDERS = "/api/spot/v3/orders_pending"; private static final String HISTORY_ORDERS = "/api/spot/v3/orders"; private static final String ORDER = "/api/spot/v3/orders/"; private static final String ORDER_DETAILS = "/api/spot/v3/fills"; private static final String PRECISIONS = "/api/spot/v3/instruments"; private static final String CREATE_ORDER = "/api/spot/v3/orders"; private static final String CREATE_ORDERS = "/api/spot/v3/batch_orders"; private static final String CANCEL_ORDER = "/api/spot/v3/cancel_orders/"; private static final String CANCEL_ORDERS = "/api/spot/v3/cancel_batch_orders"; public Okexv3Exchange(Logger log) { super(ExchangeName.OKEXV3, log); } @Override public String symbol(ExchangeInfo info) { return symbol(info, s -> s.replace("_", "-").toLowerCase()); } @Override public final List<MimeRequest> tickerRequests(ExchangeInfo info, long delay) { String url = TICKER.replace("{instrumentId}", this.symbol(info)); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + url) .build(); return Collections.singletonList(request); } @Override protected final Ticker transformTicker(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); return Okexv3Util.parseTicker(result, r); } return null; } @Override public final List<MimeRequest> klinesRequests(ExchangeInfo info, long delay) { int size = 200; //granularity必须是[60 180 300 900 1800 3600 7200 14400 21600 43200 86400 604800] Integer granularity = period(info, Okexv3Util::getPeriod); Long now = System.currentTimeMillis(); Long past = now - SECOND * granularity * size; String start = urlEncode(formatISO8601(past)); String end = urlEncode(formatISO8601(now)); String url = KLINES.replace("{instrumentId}", this.symbol(info)) + "?end=" + end + "&granularity=" + granularity + "&start=" + start; MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + url) .build(); return Collections.singletonList(request); } @Override protected final Klines transformKlines(List<String> results, ExchangeInfo info) { // 默认200根 int size = 200; String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseArray(result); List<Kline> list = new ArrayList<>(r.size()); if (0 < r.size()) { for (int i = 0; i < r.size(); i++) { Kline kline = Okexv3Util.parseKline(r.getString(i), r.getJSONArray(i)); list.add(kline); if (size <= list.size()) { break; } } } return new Klines(list); } return null; } @Override public List<MimeRequest> depthRequests(ExchangeInfo info, long delay) { String url = DEPTH.replace("{instrumentId}", this.symbol(info)); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + url) .build(); return Collections.singletonList(request); } @Override protected Depth transformDepth(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSONObject.parseObject(result) ; return Okexv3Util.parseDepth(r); } return null; } @Override public List<MimeRequest> tradesRequests(ExchangeInfo info, long delay) { Integer size = 100; String url = TRADES.replace("{instrumentId}", this.symbol(info)) + "?limit=" + size; MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + url) .build(); return Collections.singletonList(request); } @Override protected Trades transformTrades(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseArray(result); return Okexv3Util.parseTrades(r); } return null; } @Override public List<MimeRequest> balancesRequests(ExchangeInfo info, long delay) { return Okexv3Exchange.get(delay, BALANCES, info); } @Override protected Balances transformBalances(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseArray(result); List<Balance> balances = new ArrayList<>(r.size()); for (int i = 0, l = r.size(); i < l; i++) { balances.add(Okexv3Util.parseBalance(r.getString(i), r.getJSONObject(i))); } return new Balances(balances); } return null; } @Override public List<MimeRequest> accountRequests(ExchangeInfo info, long delay) { List<MimeRequest> requests = new ArrayList<>(2); String[] ss = CommonUtil.split(info.getSymbol().toLowerCase()); for (String s : ss) { String url = ACCOUNT + s; Header header = sign(delay, "GET", url, null, info); // Builder Pattern 建造者模式 MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + url) .header(header) .build(); requests.add(request); } return requests; } @Override protected Account transformAccount(List<String> results, ExchangeInfo info) { String baseResult = results.get(0); String countResult = results.get(1); if (useful(baseResult) && useful(countResult)) { JSONObject br = JSON.parseObject(baseResult); JSONObject cr = JSON.parseObject(countResult); Balance base = Okexv3Util.parseBalance(baseResult, br); Balance count = Okexv3Util.parseBalance(countResult, cr); return new Account(System.currentTimeMillis(), base, count); } return null; } @Override public List<MimeRequest> precisionsRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + PRECISIONS) .build(); return Collections.singletonList(request); } @Override protected Precisions transformPrecisions(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseArray(result); List<Precision> precisions = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { JSONObject t = r.getJSONObject(i); /* * { * "base_currency":"DASH", // 目标币 * "product_id":"DASH-BTC", // 币对 * "base_increment":"0.000001", // 目标币精度 * "min_size":"0.001", // 目标币最小数量 * "base_min_size":"0.001", // 目标币最小数量 * "quote_increment":"0.00000001", // 计价币精度 * "size_increment":"0.000001", // 目标币精度 * "instrument_id":"DASH-BTC", // 币对 * "quote_currency":"BTC", // 计价币 * "tick_size":"0.00000001" // 计价币精度 * } */ String symbol = t.getString("instrument_id").replace("-", "_"); // 最小币步长 BigDecimal stepBase = t.getBigDecimal("base_increment").stripTrailingZeros(); // 最小价格步长 BigDecimal stepCount = t.getBigDecimal("quote_increment").stripTrailingZeros(); // 交易时币精度,amount Integer base = stepBase.scale(); // 计价货币精度,price Integer count = stepCount.scale(); // 最小买卖数量 BigDecimal minBase = t.getBigDecimal("base_min_size"); // 最小买价格 // BigDecimal minCount = null; // 最大买卖数量 // BigDecimal maxBase = null; // 最大买价格 // BigDecimal maxCount = null; precisions.add(new Precision(r.getString(i), symbol, base, count, stepBase, stepCount, minBase, null, null, null)); } return new Precisions(precisions); } return null; } @Override public List<MimeRequest> precisionRequests(ExchangeInfo info, long delay) { return this.precisionsRequests(info, delay); } @Override protected Precision transformPrecision(List<String> results, ExchangeInfo info) { Precisions precisions = this.transformPrecisions(results, info); return precisions.stream() .filter(p -> info.getSymbol().equals(p.getSymbol())) .findAny() .orElse(null); } @Override public List<MimeRequest> buyLimitRequests(ExchangeInfo info, long delay) { return this.createOrder(info, delay, "limit", "buy", "price", info.getPrice(), "size", info.getAmount()); } @Override public String transformBuyLimit(List<String> results, ExchangeInfo info) { return Okexv3Exchange.parseOrderId(results.get(0)); } @Override public List<MimeRequest> sellLimitRequests(ExchangeInfo info, long delay) { return this.createOrder(info, delay, "limit", "sell", "price", info.getPrice(), "size", info.getAmount()); } @Override public String transformSellLimit(List<String> results, ExchangeInfo info) { return Okexv3Exchange.parseOrderId(results.get(0)); } @Override public List<MimeRequest> buyMarketRequests(ExchangeInfo info, long delay) { return this.createOrder(info, delay, "market", "buy", "notional", info.getQuote()); } @Override public String transformBuyMarket(List<String> results, ExchangeInfo info) { return Okexv3Exchange.parseOrderId(results.get(0)); } @Override public List<MimeRequest> sellMarketRequests(ExchangeInfo info, long delay) { return this.createOrder(info, delay, "market", "sell", "size", info.getBase()); } @Override public String transformSellMarket(List<String> results, ExchangeInfo info) { return Okexv3Exchange.parseOrderId(results.get(0)); } @Override public List<MimeRequest> multiBuyRequests(ExchangeInfo info, long delay) { return this.createOrders(info, delay, "buy"); } @Override public List<String> transformMultiBuy(List<String> results, ExchangeInfo info) { List<String> rs = this.parseMultiOrderIds(results, info.getSymbol().toLowerCase()); if (null != rs && !rs.isEmpty()) { return rs; } return null; } @Override public List<MimeRequest> multiSellRequests(ExchangeInfo info, long delay) { return this.createOrders(info, delay, "sell"); } @Override public List<String> transformMultiSell(List<String> results, ExchangeInfo info) { return this.transformMultiBuy(results, info); } @Override public List<MimeRequest> cancelOrderRequests(ExchangeInfo info, long delay) { String symbol = this.symbol(info); String url = CANCEL_ORDER + info.getCancelId(); Parameter parameter = Parameter.build("instrument_id", symbol); String body = parameter.json(JSON::toJSONString); return this.post(delay, body, info, url); } @Override protected Boolean transformCancelOrder(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); if (r.containsKey(RESULT)) { return r.getBoolean(RESULT); } } return null; } @Override public List<MimeRequest> cancelOrdersRequests(ExchangeInfo info, long delay) { String symbol = this.symbol(info); List<String> ids = info.getCancelIds(); if (null == ids || ids.isEmpty()) { return Collections.emptyList(); } int max = 4; List<List<Long>> lists = new LinkedList<>(); for (int i = 0, l = ids.size() / max + 1; i < l; i++) { List<Long> list = ids.stream() .skip(i * max) .limit(max) .map(Long::valueOf) .collect(Collectors.toList()); if (!list.isEmpty()) { lists.add(list); } } return lists.stream() .map(s -> Parameter.build("instrument_id", symbol).add("order_ids", s)) .map(p -> "[" + p.sort().json(JSON::toJSONString) + "]") .map(body -> MimeRequest.builder() .url(ADDRESS + CANCEL_ORDERS) .post() .header(sign(delay, "POST", CANCEL_ORDERS, body, info)) .body(body) .build()) .collect(Collectors.toList()); } @Override public List<String> transformCancelOrders(List<String> results, ExchangeInfo info) { String symbol = this.symbol(info); return results.stream() .map(JSON::parseObject) .filter(o -> o.containsKey(symbol)) .map(o -> o.getJSONObject(symbol)) .filter(o -> o.containsKey(RESULT) && o.getBoolean(RESULT)) .map(o -> o.getJSONArray("order_id")) .map(a -> a.toJavaList(String.class)) .flatMap(Collection::stream) .collect(Collectors.toList()); } @Override public List<MimeRequest> ordersRequests(ExchangeInfo info, long delay) { String url = ORDERS + "?instrument_id=" + this.symbol(info); return Okexv3Exchange.get(delay, url, info); } @Override protected Orders transformOrders(List<String> results, ExchangeInfo info) { List<Order> orders = parseOrders(results.get(0)); return exist(orders) ? new Orders(orders) : null; } @Override public List<MimeRequest> historyOrdersRequests(ExchangeInfo info, long delay) { String symbol = this.symbol(info); Parameter parameter = Parameter.build(); parameter.add("instrument_id", symbol); parameter.add("status", "all"); parameter.add("limit", "100"); String url = HISTORY_ORDERS + "?" + parameter.sort().concat(); return Okexv3Exchange.get(delay, url, info); } @Override protected Orders transformHistoryOrders(List<String> results, ExchangeInfo info) { List<Order> orders = Okexv3Exchange.parseOrders(results.get(0)); if (null == orders) { return null; } orders = orders.stream() .sorted((o1, o2) -> o2.getTime().compareTo(o1.getTime())) .collect(Collectors.toList()); return new Orders(orders); } @Override public List<MimeRequest> orderRequests(ExchangeInfo info, long delay) { String url = ORDER + info.getOrderId() + "?instrument_id=" + this.symbol(info); return Okexv3Exchange.get(delay, url, info); } @Override protected Order transformOrder(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); return Okexv3Util.parseOrder(result, r); } return null; } @Override public List<MimeRequest> orderDetailsRequests(ExchangeInfo info, long delay) { List<MimeRequest> requests = new ArrayList<>(2); requests.addAll(this.orderRequests(info, delay)); String url = ORDER_DETAILS + "?instrument_id=" + this.symbol(info) + "&order_id=" + info.getOrderId(); requests.addAll(Okexv3Exchange.get(delay, url, info)); return requests; } @Override public OrderDetails transformOrderDetails(List<String> results, ExchangeInfo info) { Order order = this.transformOrder(results, info); String side = order.getSide().name().toLowerCase(); String result = results.get(1); if (useful(result)) { List<OrderDetail> details = Okexv3Exchange.parseOrderDetails(result, side); if (null != details) { return new OrderDetails(details); } } return null; } // ========== tools ========== /** * 统一签名 * * @param delay 时间戳延时 * @param method 请求类型 * @param action url * @param body 请求参数 * @param info 参数 * @return 加密Header */ private static Header sign(long delay, String method, String action, String body, ExchangeInfo info) { String access = info.getAccess(); String secret = info.getSecret(); String epoch = formatEpoch(System.currentTimeMillis() + delay); String[] ss = CommonUtil.split(secret); String sign = epoch + method + action + (useful(body) ? body : ""); try { sign = Base64Util.base64EncodeToString(HmacUtil.hmac(sign.getBytes(), ss[0], HmacUtil.HMAC_SHA256)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } Header header = Header.build(); header.add("OK-ACCESS-KEY", access); header.add("OK-ACCESS-SIGN", sign); header.add("OK-ACCESS-TIMESTAMP", epoch); header.add("OK-ACCESS-PASSPHRASE", ss[1]); return header; } public static String formatEpoch(Long time) { if (null == time) { return ""; } return String.format("%s.%03d", time / 1000, time % 1000); } /** * get请求 */ private static List<MimeRequest> get(long delay, String url, ExchangeInfo info) { Header header = sign(delay, "GET", url, null, info); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + url) .header(header) .build(); return Collections.singletonList(request); } private static final String P = "{"; private static final String CODE = "code"; private static final int ERROR_CODE = 33007; private static final String RESULT = "result"; private static final String TRUE = "true"; /** * 解析多个订单 * @param result 原始文件 * @return 多个订单 */ private static List<Order> parseOrders(String result) { if (useful(result)) { if (result.trim().startsWith(P)) { JSONObject r = JSON.parseObject(result); if (r.containsKey(CODE) && ERROR_CODE == r.getInteger(CODE)) { return Collections.emptyList(); } } JSONArray r = JSON.parseArray(result); List<Order> orders = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { Order order = Okexv3Util.parseOrder(r.getString(i), r.getJSONObject(i)); if (exist(order)) { orders.add(order); } else { return null; } } return orders; } return null; } /** * 解析订单明细 * * @param result 原始数据 * @param side 买卖方向 * @return 订单明细 */ private static List<OrderDetail> parseOrderDetails(String result, String side) { if (useful(result)) { JSONArray r = JSON.parseArray(result); List<OrderDetail> details = new LinkedList<>(); for (int i = 0; i < r.size(); i++) { JSONObject t = r.getJSONObject(i); /* * [{ * * "exec_type": "T", * "fee": "0.018", * "instrument_id": "ETH-USDT", * "ledger_id": "1706", * "order_id": "1798782957193216", * "price": "90", * "side": "points_fee", * "size": "0", * "timestamp": "2018-11-14T08:14.09000Z" * }, * { * "created_at":"2019-01-23T04:44:54.000Z", * "exec_type":"T", * "fee":"0", * "instrument_id":"LTC-USDT", * "ledger_id":"3463324607", * "liquidity":"T", * "order_id":"2194321788247040", * "price":"31.4824", * "product_id":"LTC-USDT", * "side":"sell", * "size":"0.03198611", * "timestamp":"2019-01-23T04:44:54.000Z" * } */ if (!side.equals(t.getString("side"))) { continue; } Long time = t.getDate("timestamp").getTime(); String orderId = t.getString("order_id"); String detailId = t.getString("ledger_id"); BigDecimal price = t.getBigDecimal("price"); BigDecimal amount = t.getBigDecimal("size"); BigDecimal fee = t.getBigDecimal("fee"); details.add(new OrderDetail(r.getString(i), time, orderId, detailId, price, amount, fee, null)); } return details; } return null; } /** * 创建订单 * * @param info 请求信息 * @param delay 延迟 * @param type 订单类型 limit market * @param side 买卖方向 buy sell * @param others 其他参数 * @return 订单请求 */ private List<MimeRequest> createOrder(ExchangeInfo info, long delay, String type, String side, String... others) { String symbol = this.symbol(info); Parameter parameter = Parameter.build(); parameter.add("type", type); parameter.add("side", side); parameter.add("instrument_id", symbol); String body = CommonUtil.addOtherParameterToJson(parameter, others); return this.post(delay, body, info, CREATE_ORDER); } /** * post请求 */ private List<MimeRequest> post(long delay, String body, ExchangeInfo info, String url) { Header header = sign(delay, "POST", url, body, info); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + url) .post() .header(header) .body(body) .build(); return Collections.singletonList(request); } /** * 解析订单id */ private static String parseOrderId(String result) { if (useful(result)) { JSONObject r = JSON.parseObject(result); if (r.containsKey(RESULT) && TRUE.equals(r.getString(RESULT))) { return r.getString("order_id"); } } return null; } /** * 批量下单 */ private MimeRequest createOrders(ExchangeInfo info, long delay, String side, long startId, String... others) { String symbol = this.symbol(info); Parameter parameter = Parameter.build(); parameter.add("type", "limit"); parameter.add("side", side); parameter.add("instrument_id", symbol); List<String> multiBody = new LinkedList<>(); for (int i = 0; i < others.length; i++) { parameter.put("client_oid", startId++); parameter.put("price", others[i]); parameter.put("size", others[++i]); multiBody.add(parameter.sort().json(JSON::toJSONString)); } String body = "[" + String.join(",", multiBody) + "]"; Header header = sign(delay, "POST", CREATE_ORDERS, body, info); return new MimeRequest.Builder() .url(ADDRESS + CREATE_ORDERS) .post() .header(header) .body(body) .build(); } /** * 批量下单 */ private List<MimeRequest> createOrders(ExchangeInfo info, long delay, String side) { List<Row> rows = info.getRows(); List<List<Row>> split = CommonUtil.split(rows, 4); return split.stream() .map(rs -> this.createOrders(info, delay, side, RandomUtil.uid(), rs.stream() .map(r -> Arrays.asList(r.getPrice().toPlainString(), r.getAmount().toPlainString())) .flatMap(Collection::stream) .collect(Collectors.toList()) .toArray(new String[]{}))) .collect(Collectors.toList()); } /** * 批量下单的结果 * * @param results 下单结果 * @param symbol 币对,转换好的 * @return ids */ private List<String> parseMultiOrderIds(List<String> results, String symbol) { return results.stream() .map(JSON::parseObject) .filter(r -> r.containsKey(symbol)) .map(r -> r.getJSONArray(symbol)) .map(a -> a.toJavaList(JSONObject.class)) .flatMap(Collection::stream) .filter(o -> o.containsKey(RESULT) && o.getBoolean(RESULT)) .map(o -> o.getString("order_id")) .collect(Collectors.toList()); } }
28,237
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BinanceExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/binance/BinanceExchange.java
package cqt.goai.exchange.http.binance; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.model.enums.Side; import cqt.goai.model.enums.State; import cqt.goai.model.enums.Type; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import dive.common.crypto.HmacUtil; import dive.http.common.MimeRequest; import dive.http.common.model.Method; import dive.http.common.model.Parameter; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import static dive.common.math.BigDecimalUtil.div; import static dive.common.math.BigDecimalUtil.greater; import static dive.common.util.Util.useful; import static java.math.BigDecimal.ZERO; /** * @author xxx */ public class BinanceExchange extends HttpExchange { private static final String SITE = "api.binance.com"; private static final String ADDRESS = "https://" + SITE; private static final String TICKER = "/api/v1/ticker/24hr"; private static final String KLINES = "/api/v1/klines"; private static final String DEPTH = "/api/v1/depth"; private static final String TRADES = "/api/v1/aggTrades"; private static final String BALANCES = "/api/v3/account"; private static final String PRECISIONS = "/api/v1/exchangeInfo"; private static final String ORDER = "/api/v3/order"; private static final String ORDERS = "/api/v3/openOrders"; private static final String ORDERS_HISTORY = "/api/v3/allOrders"; public BinanceExchange(Logger log) { super(ExchangeName.BINANCE, log); } @Override public String symbol(ExchangeInfo info) { return symbol(info, s -> s.replace("_", "")); } @Override public List<MimeRequest> tickerRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + TICKER + "?symbol=" + this.symbol(info)) .build(); return Collections.singletonList(request); } @Override protected Ticker transformTicker(List<String> results, ExchangeInfo info) { String result = results.get(0).trim(); if (useful(result)) { JSONObject r; if (result.startsWith(LEFT_SQUARE_BRACKETS)) { r = JSON.parseArray(result).getJSONObject(0); } else { r = JSON.parseObject(result); } Long time = r.getLong("closeTime"); return CommonUtil.parseTicker(r.toJSONString(), r, time, "openPrice", "highPrice", "lowPrice", "lastPrice", "volume"); } return null; } @Override public List<MimeRequest> klinesRequests(ExchangeInfo info, long delay) { Integer size = 400; String type = period(info, period -> { switch (period) { case MIN1: return "1m"; case MIN3: return "3m"; case MIN5: return "5m"; case MIN15: return "15m"; case MIN30: return "30m"; case HOUR1: return "1h"; case HOUR2: return "2h"; // case HOUR3: return "3h"; case HOUR4: return "4h"; case HOUR6: return "6h"; case HOUR12: return "12h"; case DAY1: return "1d"; case DAY3: return "3d"; case WEEK1: return "1w"; // case WEEK2: return "2w"; case MONTH1: return "1M"; default: return null; } }); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + KLINES + "?symbol=" + this.symbol(info) + "&limit=" + size + "&interval=" + type) .build(); return Collections.singletonList(request); } @Override protected Klines transformKlines(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray array = JSON.parseArray(result); List<Kline> klines = new ArrayList<>(array.size()); for (int i = array.size() - 1; 0 <= i; i--) { JSONArray t = array.getJSONArray(i); /* * 1499040000000, // Open time * "0.01634790", // Open * "0.80000000", // High * "0.01575800", // Low * "0.01577100", // Close * "148976.11427815", // Volume * 1499644799999, // Close time * "2434.19055334", // Quote asset volume * 308, // Number of trades * "1756.87402397", // Taker buy base asset volume * "28.46694368", // Taker buy quote asset volume * "17928899.62484339" // Ignore. */ Long time = t.getLong(0) / 1000; Kline kline = CommonUtil.parseKlineByIndex(array.getString(i), t, time, 1); klines.add(kline); // if (size <= records.size()) break; } return new Klines(klines); } return null; } @Override public List<MimeRequest> depthRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + DEPTH + "?symbol=" + this.symbol(info)) .build(); return Collections.singletonList(request); } @Override protected Depth transformDepth(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSONObject.parseObject(result); JSONArray asks = r.getJSONArray("asks"); JSONArray bids = r.getJSONArray("bids"); Long time = System.currentTimeMillis(); return CommonUtil.parseDepthByIndex(time, asks, bids); } return null; } @Override public List<MimeRequest> tradesRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + TRADES + "?symbol=" + this.symbol(info) + "&limit=100") .build(); return Collections.singletonList(request); } @Override protected Trades transformTrades(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { try { JSONArray r = JSON.parseArray(result); List<Trade> trades = new ArrayList<>(r.size()); for (int i = r.size() - 1; 0 <= i; i--) { JSONObject t = r.getJSONObject(i); /* * "a": 26129, // Aggregate tradeId * "p": "0.01633102", // Price * "q": "4.70443515", // Quantity * "f": 27781, // First tradeId * "l": 27781, // Last tradeId * "T": 1498793709153, // Timestamp * "m": true, // Was the buyer the maker? * "M": true // Was the trade the best price match? */ Long time = t.getLong("T"); String id = t.getString("f") + "_" + t.getString("l"); Side side = t.getBoolean("m") ? Side.SELL : Side.BUY; BigDecimal price = t.getBigDecimal("p"); BigDecimal amount = t.getBigDecimal("q"); Trade trade = new Trade(r.getString(i), time, id, side, price, amount); trades.add(trade); } return new Trades(trades); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override public List<MimeRequest> balancesRequests(ExchangeInfo info, long delay) { return this.get(info, delay, BALANCES); } @Override protected Balances transformBalances(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseObject(result).getJSONArray("balances"); List<Balance> balances = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { JSONObject t = r.getJSONObject(i); String currency = t.getString("asset"); BigDecimal free = t.getBigDecimal("free"); BigDecimal used = t.getBigDecimal("locked"); balances.add(new Balance(r.getString(i), currency, free, used)); } return new Balances(balances); } return null; } @Override public List<MimeRequest> precisionsRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + PRECISIONS) .build(); return Collections.singletonList(request); } /** * { * "symbol":"ETHBTC", * "status":"TRADING", * "baseAsset":"ETH", * "baseAssetPrecision":8, * "quoteAsset":"BTC", * "quotePrecision":8, * "orderTypes":Array[5], * "icebergAllowed":true, * "filters":[ * { * "filterType":"PRICE_FILTER", * "minPrice":"0.00000000", * "maxPrice":"0.00000000", * "tickSize":"0.00000100" * }, * { * "filterType":"PERCENT_PRICE", * "multiplierUp":"10", * "multiplierDown":"0.1", * "avgPriceMins":5 * }, * { * "filterType":"LOT_SIZE", * "minQty":"0.00100000", * "maxQty":"100000.00000000", * "stepSize":"0.00100000" * }, * { * "filterType":"MIN_NOTIONAL", * "minNotional":"0.00100000", * "applyToMarket":true, * "avgPriceMins":5 * }, * { * "filterType":"ICEBERG_PARTS", * "limit":10 * }, * { * "filterType":"MAX_NUM_ALGO_ORDERS", * "maxNumAlgoOrders":5 * } * ] * } */ @Override protected Precisions transformPrecisions(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); JSONArray symbols = r.getJSONArray("symbols"); List<Precision> precisions = new ArrayList<>(symbols.size()); for (int i = 0; i < symbols.size(); i++) { JSONObject t = symbols.getJSONObject(i); if (!"TRADING".equals(t.getString("status"))) { continue; } String data = symbols.getString(i); String symbol = t.getString("baseAsset") + "_" + t.getString("quoteAsset"); Integer base = t.getInteger("baseAssetPrecision"); Integer quote = t.getInteger("quotePrecision"); JSONArray filters = t.getJSONArray("filters"); JSONObject baseFilter = null; JSONObject priceFilter = null; for (int j = 0; j < filters.size(); j++) { JSONObject temp = filters.getJSONObject(j); if ("PRICE_FILTER".equals(temp.getString("filterType"))) { priceFilter = temp; } else if ("LOT_SIZE".equals(temp.getString("filterType"))){ baseFilter = temp; } } BigDecimal baseStep = this.getBigDecimal(baseFilter, "stepSize"); BigDecimal quoteStep = this.getBigDecimal(priceFilter, "tickSize"); BigDecimal minBase = this.getBigDecimal(baseFilter, "minQty"); BigDecimal minQuote = this.getBigDecimal(priceFilter, "minPrice"); BigDecimal maxBase = this.getBigDecimal(baseFilter, "maxQty"); BigDecimal maxQuote = this.getBigDecimal(priceFilter, "maxPrice"); Precision precision = new Precision(data, symbol, base, quote, baseStep, quoteStep, minBase, minQuote, maxBase, maxQuote); precisions.add(precision); } return new Precisions(precisions); } return null; } @Override public List<MimeRequest> buyLimitRequests(ExchangeInfo info, long delay) { return this.postOrder(info, delay, "symbol", this.symbol(info), "side", "BUY", "type", "LIMIT", "timeInForce", "GTC", "quantity", info.getAmount(), "price", info.getPrice()); } @Override public String transformBuyLimit(List<String> results, ExchangeInfo info) { return this.getId(results); } @Override public List<MimeRequest> sellLimitRequests(ExchangeInfo info, long delay) { return this.postOrder(info, delay, "symbol", this.symbol(info), "side", "SELL", "type", "LIMIT", "timeInForce", "GTC", "quantity", info.getAmount(), "price", info.getPrice()); } @Override public String transformSellLimit(List<String> results, ExchangeInfo info) { return this.getId(results); } @Override public List<MimeRequest> buyMarketRequests(ExchangeInfo info, long delay) { return this.postOrder(info, delay, "symbol", this.symbol(info), "side", "BUY", "type", "MARKET", "timeInForce", "GTC", "quantity", info.getQuote()); } @Override public String transformBuyMarket(List<String> results, ExchangeInfo info) { return this.getId(results); } @Override public List<MimeRequest> sellMarketRequests(ExchangeInfo info, long delay) { return this.postOrder(info, delay, "symbol", this.symbol(info), "side", "SELL", "type", "MARKET", "timeInForce", "GTC", "quantity", info.getBase()); } @Override public String transformSellMarket(List<String> results, ExchangeInfo info) { return this.getId(results); } @Override public List<MimeRequest> cancelOrderRequests(ExchangeInfo info, long delay) { return this.request(info, delay, ORDER, Method.DELETE, "orderId", info.getCancelId(), "symbol", this.symbol(info)); } @Override protected Boolean transformCancelOrder(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { this.parseOrder(null, JSON.parseObject(result)); return true; } return null; } @Override public List<MimeRequest> ordersRequests(ExchangeInfo info, long delay) { return this.get(info, delay, ORDERS, "symbol", this.symbol(info)); } @Override protected Orders transformOrders(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONArray r = JSON.parseArray(result); List<Order> orders = new LinkedList<>(); for (int i = 0; i < r.size(); i++) { orders.add(this.parseOrder(r.getString(i), r.getJSONObject(i))); } orders = orders.stream().sorted(CommonUtil::sortOrder).collect(Collectors.toList()); return new Orders(orders); } return null; } @Override public List<MimeRequest> historyOrdersRequests(ExchangeInfo info, long delay) { return this.get(info, delay, ORDERS_HISTORY, "symbol", this.symbol(info), "limit", 500); } @Override protected Orders transformHistoryOrders(List<String> results, ExchangeInfo info) { return this.transformOrders(results, info); } @Override public List<MimeRequest> orderRequests(ExchangeInfo info, long delay) { return this.get(info, delay, ORDER, "symbol", this.symbol(info), "orderId", info.getOrderId()); } @Override protected Order transformOrder(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return this.parseOrder(result, JSON.parseObject(result)); } return null; } @Override public List<MimeRequest> orderDetailsRequests(ExchangeInfo info, long delay) { return this.get(info, delay, ORDER, "symbol", this.symbol(info), "orderId", info.getOrderId()); } @Override protected OrderDetails transformOrderDetails(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return this.parseOrderDetails(JSON.parseObject(result)); } return null; } // ====================== tools ============================ private static final String LEFT_SQUARE_BRACKETS = "["; private static final String FILLS = "fills"; private List<MimeRequest> request(ExchangeInfo info, long delay, String api, Method method, Object... others) { String access = info.getAccess(); String secret = info.getSecret(); Parameter parameter = Parameter.build("timestamp", System.currentTimeMillis() + delay); CommonUtil.addOtherParameter(parameter, others); String para = parameter.concat(); String sign = HmacUtil.HmacSHA256(para, secret); MimeRequest request = new MimeRequest.Builder() .url(ADDRESS + api + "?" + para + "&signature=" + sign) .header("X-MBX-APIKEY", access) .method(method) .body(Method.POST == method ? "" : null) .build(); return Collections.singletonList(request); } private List<MimeRequest> get(ExchangeInfo info, long delay, String api, Object... others) { return this.request(info, delay, api, Method.GET, others); } private List<MimeRequest> postOrder(ExchangeInfo info, long delay, Object... others) { return this.request(info, delay, BinanceExchange.ORDER, Method.POST, others); } private Order parseOrder(String result, JSONObject t) { /* * "symbol": "LTCBTC", * "orderId": 1, * "clientOrderId": "myOrder1", * "price": "0.1", * "origQty": "1.0", * "executedQty": "0.0", * "cummulativeQuoteQty": "0.0", * "status": "NEW", * "timeInForce": "GTC", * "type": "LIMIT", * "side": "BUY", * "stopPrice": "0.0", * "icebergQty": "0.0", * "time": 1499827319559, * "updateTime": 1499827319559, * "isWorking": true */ Long time = t.getLong("updateTime"); String id = t.getString("orderId"); State state = null; switch (t.getString("status")) { case "NEW": state = State.SUBMIT; break; case "PARTIALLY_FILLED": state = State.PARTIAL; break; case "FILLED": state = State.FILLED; break; case "CANCELED": state = State.CANCEL; break; case "PENDING_CANCEL": state = State.CANCEL; break; case "REJECTED": state = State.CANCEL; break; case "EXPIRED": state = State.CANCEL; break; default: } Side side = Side.valueOf(t.getString("side")); Type type = null; //STOP_LOSS //STOP_LOSS_LIMIT //TAKE_PROFIT //TAKE_PROFIT_LIMIT //LIMIT_MAKER switch (t.getString("type")) { case "LIMIT" : type = Type.LIMIT; break; case "MARKET" : type = Type.MARKET; break; default: } BigDecimal price = t.getBigDecimal("price"); BigDecimal amount = t.getBigDecimal("origQty"); BigDecimal deal = t.getBigDecimal("executedQty"); BigDecimal average = greater(deal, ZERO) ? div(t.getBigDecimal("cummulativeQuoteQty"), deal) : ZERO; return new Order(result, time, id, side, type, greater(deal, ZERO) && state == State.CANCEL ? State.UNDONE : state, price, amount, deal, average); } private OrderDetails parseOrderDetails(JSONObject t) { /* * "symbol": "LTCBTC", * "orderId": 1, * "clientOrderId": "myOrder1", * "price": "0.1", * "origQty": "1.0", * "executedQty": "0.0", * "cummulativeQuoteQty": "0.0", * "status": "NEW", * "timeInForce": "GTC", * "type": "LIMIT", * "side": "BUY", * "stopPrice": "0.0", * "icebergQty": "0.0", * "time": 1499827319559, * "updateTime": 1499827319559, * "isWorking": true */ Long time = t.getLong("updateTime"); String id = t.getString("orderId"); Side side = Side.valueOf(t.getString("side")); List<OrderDetail> details = new LinkedList<>(); if (t.containsKey(FILLS)) { JSONArray fills = t.getJSONArray(FILLS); for (int i = 0; i < fills.size(); i++) { JSONObject tt = fills.getJSONObject(i); BigDecimal price = tt.getBigDecimal("price"); BigDecimal amount = tt.getBigDecimal("qty"); BigDecimal fee = tt.getBigDecimal("commission"); String feeCurrency = tt.getString("commissionAsset"); details.add(new OrderDetail(fills.getString(i), time, id, null, price, amount, fee, feeCurrency, side)); } } return new OrderDetails(details); } private BigDecimal getBigDecimal(JSONObject t, String name) { if (null == t) { return null; } BigDecimal number = t.getBigDecimal(name); if (greater(number, ZERO)) { return number; } return null; } private String getId(List<String> results) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); return r.getString("orderId"); } return null; } }
23,047
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
HuobiProExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/http/huobi/pro/HuobiProExchange.java
package cqt.goai.exchange.http.huobi.pro; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeException; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.util.Seal; import cqt.goai.exchange.util.huobi.pro.HoubiProUtil; import cqt.goai.model.enums.Side; import cqt.goai.model.enums.State; import cqt.goai.model.enums.Type; import cqt.goai.model.market.Klines; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Ticker; import cqt.goai.model.market.Trades; import cqt.goai.model.trade.*; import dive.common.crypto.Base64Util; import dive.common.crypto.HmacUtil; import dive.common.util.DateUtil; import dive.http.common.MimeRequest; import dive.http.common.model.Parameter; import dive.cache.mime.PersistCache; import org.slf4j.Logger; import java.math.BigDecimal; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.format.DateTimeFormatter; import java.util.*; import static dive.common.math.BigDecimalUtil.div; import static dive.common.math.BigDecimalUtil.greater; import static dive.common.util.Util.exist; import static dive.common.util.Util.useful; import static java.math.BigDecimal.ZERO; /** * @author GOAi */ public class HuobiProExchange extends HttpExchange { private static final PersistCache<String, String> CACHE = new PersistCache<>("huobipro"); private static final String OK = "ok"; private static final String ERROR = "error"; private static final String ERROR_CODE = "err-code"; private static final String ORDER_ERROR = "order-orderstate-error"; private static final String BASE_RECORD = "base-record-invalid"; private static final String STATUS = "status"; private static final String DATA = "data"; protected String site = "api.huobi.pro"; protected String address = "https://" + site; protected String apiTicker = "/market/detail/merged"; protected String apiKlines = "/market/history/kline"; protected String apiDepth = "/market/depth"; protected String apiTrades = "/market/history/trade"; protected String apiAccountId = "/v1/account/accounts"; protected String apiBalances = "/v1/account/accounts/{account-id}/balance"; protected String apiPrecisions = "/v1/common/symbols"; protected String apiPlace = "/v1/order/orders/place"; protected String apiCancel = "/v1/order/orders/{order-id}/submitcancel"; // private static final String CANCEL_ALL = "/v1/order/orders/batchcancel"; protected String apiOrders = "/v1/order/openOrders"; protected String apiHistoryOrders = "/v1/order/orders"; protected String apiOrder = "/v1/order/orders/{order-id}"; protected String apiOrderDetails = "/v1/order/orders/{order-id}/matchresults"; public HuobiProExchange(Logger log) { super(ExchangeName.HUOBIPRO, log); } protected HuobiProExchange(ExchangeName name, Logger log) { super(name, log); } @Override public String symbol(ExchangeInfo info) { return symbol(info, s -> s.replace("_", "").toLowerCase()); } @Override public List<MimeRequest> tickerRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(address + apiTicker) .body("symbol", this.symbol(info)) .build(); return Collections.singletonList(request); } @Override protected Ticker transformTicker(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parseTicker(result); } return null; } @Override public List<MimeRequest> klinesRequests(ExchangeInfo info, long delay) { String period = super.period(info, HoubiProUtil::getPeriod); MimeRequest request = new MimeRequest.Builder() .url(address + apiKlines) .body("symbol", this.symbol(info)) .body("period", period) .body("size", 400) .build(); return Collections.singletonList(request); } @Override protected Klines transformKlines(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parseKlines(result); } return null; } @Override public List<MimeRequest> depthRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(address + apiDepth) .body("symbol", this.symbol(info)) .body("type", "step0") .build(); return Collections.singletonList(request); } @Override protected Depth transformDepth(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parseDepth(result); } return null; } @Override public List<MimeRequest> tradesRequests(ExchangeInfo info, long delay) { MimeRequest request = new MimeRequest.Builder() .url(address + apiTrades) .body("symbol", this.symbol(info)) .body("size", 100) .build(); return Collections.singletonList(request); } @Override protected Trades transformTrades(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parseTrades(result); } return null; } @Override public List<MimeRequest> balancesRequests(ExchangeInfo info, long delay) { String access = info.getAccess(); String secret = info.getSecret(); String accountId = this.getAccountId(access, secret); String url = apiBalances.replace("{account-id}", accountId); Parameter parameter = this.addParam(access, delay); return this.get(parameter, secret, url); } @Override protected Balances transformBalances(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parseBalances(result); } return null; } @Override public List<MimeRequest> accountRequests(ExchangeInfo info, long delay) { return this.balancesRequests(info, delay); } @Override protected Account transformAccount(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parseAccount(result, info.getSymbol()); } return null; } @Override public List<MimeRequest> precisionsRequests(ExchangeInfo info, long delay) { String url = address + apiPrecisions; MimeRequest request = new MimeRequest.Builder() .url(url) .build(); return Collections.singletonList(request); } @Override protected Precisions transformPrecisions(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parsePrecisions(result); } return null; } @Override public List<MimeRequest> precisionRequests(ExchangeInfo info, long delay) { return this.precisionsRequests(info, delay); } @Override protected Precision transformPrecision(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { return HoubiProUtil.parsePrecision(result, symbol(info)); } return null; } @Override public List<MimeRequest> buyLimitRequests(ExchangeInfo info, long delay) { return this.place(info, delay, info.getPrice(), info.getAmount(), BUY_LIMIT); } @Override public String transformBuyLimit(List<String> results, ExchangeInfo info) { return this.getOrderId(results.get(0)); } @Override public List<MimeRequest> sellLimitRequests(ExchangeInfo info, long delay) { return this.place(info, delay, info.getPrice(), info.getAmount(), SELL_LIMIT); } @Override public String transformSellLimit(List<String> results, ExchangeInfo info) { return this.getOrderId(results.get(0)); } @Override public List<MimeRequest> buyMarketRequests(ExchangeInfo info, long delay) { return this.place(info, delay, null, info.getQuote(), BUY_MARKET); } @Override public String transformBuyMarket(List<String> results, ExchangeInfo info) { return this.getOrderId(results.get(0)); } @Override public List<MimeRequest> sellMarketRequests(ExchangeInfo info, long delay) { return this.place(info, delay, null, info.getBase(), SELL_MARKET); } @Override public String transformSellMarket(List<String> results, ExchangeInfo info) { return this.getOrderId(results.get(0)); } @Override public List<MimeRequest> cancelOrderRequests(ExchangeInfo info, long delay) { String access = info.getAccess(); String secret = info.getSecret(); String id = info.getCancelId(); String url = apiCancel.replace("{order-id}", id); Parameter parameter = this.addParam(access, delay); parameter.add("Signature", encode(this.sign(secret, "POST", site, url, parameter))); MimeRequest request = new MimeRequest.Builder() .url(address + url + "?" + parameter.concat()) .post() .header("Accept-Language", "zh-CN") .body("") .build(); return Collections.singletonList(request); } @Override protected Boolean transformCancelOrder(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { return true; } if (ERROR.equals(r.getString(STATUS)) && ORDER_ERROR.equals(r.getString(ERROR_CODE))) { return false; } } return null; } /*@Override public List<MimeRequest> cancelOrdersRequests(ExchangeInfo info, long delay) { String access = info.getAccess(); String secret = info.getSecret(); List<String> ids = info.getCancelIds(); List<MimeRequest> list = new ArrayList<>(); if (!exist(ids) || 0 == ids.size()) { return list; } List<List<String>> split = CommonUtil.split(ids, 50); return split.stream().map(group -> { Parameter parameter = this.addParam(access, delay, "order-ids", group); parameter.add("Signature", encode(this.sign(secret, "POST", site, CANCEL_ALL, parameter))); parameter.put("Timestamp", parameter.get("Timestamp").toString().replace("%3A", ":")); parameter.put("Signature", parameter.get("Signature").toString().replace("%2B", "+").replace("%3D", "=")); return new MimeRequest.Builder() .url(address + CANCEL_ALL) .post() .header("Accept-Language", "zh-CN") .body(parameter.json(JSON::toJSONString)) .build(); }).collect(Collectors.toList()); } @Override public List<String> transformCancelOrders(List<String> results, ExchangeInfo info) { List<String> ids = new LinkedList<>(); for (int i = 0; i < results.size(); i++) { String result = results.get(i); JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray temp = r.getJSONObject("data").getJSONArray("success"); for (int j = 0; j < temp.size(); i++) { ids.add(temp.getString(j)); } } else { return null; } } return ids; }*/ @Override public List<MimeRequest> ordersRequests(ExchangeInfo info, long delay) { String access = info.getAccess(); String secret = info.getSecret(); Parameter parameter = this.addParam(access, delay, "account-id", this.getAccountId(access, secret), "symbol", this.symbol(info), "size", String.valueOf(500)); return this.get(parameter, secret, apiOrders); } @Override protected Orders transformOrders(List<String> results, ExchangeInfo info) { String result = results.get(0); List<Order> orders = this.parseOrders(result, info.tip()); return exist(orders) ? new Orders(orders) : null; } @Override public List<MimeRequest> historyOrdersRequests(ExchangeInfo info, long delay) { String access = info.getAccess(); String secret = info.getSecret(); Integer size = 100; String s = "submitting" + "%2Csubmitted" + "%2Cpartial-filled" + "%2Cpartial-canceled" + "%2Cfilled" + "%2Ccanceled"; Parameter parameter = this.addParam(access, delay, "symbol", symbol(info), "states", s, "size", String.valueOf(size)); return this.get(parameter, secret, apiHistoryOrders); } @Override protected Orders transformHistoryOrders(List<String> results, ExchangeInfo info) { return this.transformOrders(results, info); } @Override public List<MimeRequest> orderRequests(ExchangeInfo info, long delay) { return this.getRequests(info, delay, apiOrder); } @Override protected Order transformOrder(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONObject data = r.getJSONObject("data"); return parseOrder(r.getString("data"), data, info.tip()); } } return null; } @Override public List<MimeRequest> orderDetailsRequests(ExchangeInfo info, long delay) { return this.getRequests(info, delay, apiOrderDetails); } @Override public OrderDetails transformOrderDetails(List<String> results, ExchangeInfo info) { String result = results.get(0); if (useful(result)) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { return new OrderDetails(this.parseOrderDetails(r)); } if (BASE_RECORD.equals(r.get(ERROR_CODE))) { return new OrderDetails(Collections.emptyList()); } } return null; } // =================================== tools ====================================== private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); private static final String BUY_LIMIT = "buy-limit"; private static final String BUY_MARKET = "buy-market"; private static final String SELL_LIMIT = "sell-limit"; private static final String SELL_MARKET = "sell-market"; private static final String SUBMITTING = "submitting"; private static final String SUBMITTED = "submitted"; private static final String PARTIAL_FILLED = "partial-filled"; private static final String PARTIAL_CANCELED = "partial-canceled"; private static final String FILLED = "filled"; private static final String CANCELED = "canceled"; private static final String CANCELLING = "cancelling"; /** * 获取UTC时间 * @param delay 延迟 * @return UTC时间 */ private static String getUTCTimeString(long delay) { // 1、取得本地时间: Calendar cal = Calendar.getInstance(); // 2、取得时间偏移量: int zoneOffset = cal.get(Calendar.ZONE_OFFSET); // 3、取得夏令时差: int dstOffset = cal.get(Calendar.DST_OFFSET); // 4、本地时间扣除差量,即可以取得UTC时间: cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset)); // 5、网络延迟时间 cal.add(Calendar.MILLISECOND, (int) delay); return DateUtil.format(new Date(cal.getTime().getTime()), DTF); } /** * 编码转换 * @param value 值 * @return 编码后 */ private static String encode(String value) { return value.replace(":", "%3A") .replace("=", "%3D") .replace("/", "%2F") .replace(" ", "%20") .replace(",", "%2C") .replace("+", "%2B"); } /** * 添加参数 * @param access access * @param delay 延迟 * @param kv 其他参数 * @return 请求参数 */ private Parameter addParam(String access, long delay, Object... kv) { Parameter map = Parameter.build(); map.put("AccessKeyId", access); map.put("SignatureMethod", "HmacSHA256"); map.put("SignatureVersion", "2"); map.put("Timestamp", HuobiProExchange.encode(HuobiProExchange.getUTCTimeString(delay))); for (int i = 0; i < kv.length; i++) { map.put(kv[i].toString(), kv[++i]); } return map; } /** * 签名 * @param secret 秘钥 * @param method 请求方法 * @param address 请求地址 * @param api 请求路径 * @param map 参数 * @return 签名 */ private String sign(String secret, String method, String address, String api, Parameter map) { StringBuilder builder = new StringBuilder(); builder.append(method).append("\n"); builder.append(address).append("\n"); this.addSignParam(builder, api); List<String> keys = new ArrayList<>(map.size()); keys.addAll(map.keySet()); Collections.sort(keys); StringBuilder sb = new StringBuilder(); if (keys.size() >= 1) { sb.append(keys.get(0)).append("=") .append(encode(map.get(keys.get(0)).toString())); for (int i = 1, s = keys.size(); i < s; i++) { sb.append("&").append(keys.get(i)).append("=") .append(encode(map.get(keys.get(i)).toString())); } } builder.append(sb.toString()); try { byte[] sign = HmacUtil.hmac(builder.toString().getBytes(), secret, HmacUtil.HMAC_SHA256); return Base64Util.base64EncodeToString(sign); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } throw new ExchangeException(super.name.getName() + " sign error."); } /** * exshell 不需要这个 * @param builder 签名串 * @param api api */ protected void addSignParam(StringBuilder builder, String api) { builder.append(api).append("\n"); } /** * 获取account id * @param access access * @param secret secret * @return 请求结果 */ private synchronized String getAccounts(String access, String secret) { Parameter parameter = this.addParam(access, 0); parameter.add("Signature", encode(this.sign(secret, "GET", site, apiAccountId, parameter))); return new MimeRequest.Builder() .url(address + apiAccountId + "?" + parameter.concat()) .build() .execute(super.http); } /** * 获取account id * @param access access * @param secret secret * @return account id */ private String getAccountId(String access, String secret) { String id = this.getCache().get(access); if (!useful(id)) { String result = this.getAccounts(access, secret); if (useful(result)) { JSONObject r = JSON.parseObject(result); if (r.containsKey(STATUS) && OK.equals(r.getString(STATUS))) { JSONArray data = r.getJSONArray(DATA); for (int i = 0, s = data.size(); i < s; i++) { JSONObject t = data.getJSONObject(i); String accountId = t.getString("id"); String type = t.getString("type"); if ("spot".equals(type)) { id = accountId; this.getCache().set(access, id); return id; } } } } throw new ExchangeException(super.name.getName() + " " + Seal.seal(access) + " account_id: result is " + result); } return id; } /** * 获取缓存 * @return 缓存 */ protected PersistCache<String, String> getCache() { return CACHE; } /** * get请求 * @param parameter 请求参数 * @param secret 秘钥 * @param api 请求路径 * @return 请求信息 */ private List<MimeRequest> get(Parameter parameter, String secret, String api) { parameter.add("Signature", encode(this.sign(secret, "GET", site, api, parameter))); MimeRequest request = new MimeRequest.Builder() .url(address + api + "?" + parameter.concat()) .build(); return Collections.singletonList(request); } /** * 解析订单 * @param result 订单结果 * @param data json * @param tip 错误提示 * @return 解析订单 */ protected Order parseOrder(String result, JSONObject data, String tip) { Long time = data.getLong("created-at"); String id = data.getString("id"); String[] types = data.getString("type").split("-"); Side side = Side.valueOf(types[0].toUpperCase()); Type type = null; switch (types[1]) { case "limit": type = Type.LIMIT; break; case "market": type = Type.MARKET; break; case "ioc": type = Type.IMMEDIATE_OR_CANCEL; break; default: } State state; switch (data.getString("state")) { case SUBMITTING: case SUBMITTED: state = State.SUBMIT; break; case PARTIAL_FILLED: state = State.PARTIAL; break; case CANCELLING: state = State.SUBMIT; break; case FILLED: state = State.FILLED; break; case CANCELED: state = State.CANCEL; break; case PARTIAL_CANCELED: state = State.UNDONE; break; default: log.error("{} {} parseOrder state --> {}", name, tip, data); return null; } BigDecimal price = data.getBigDecimal("price"); BigDecimal amount = data.getBigDecimal("amount"); BigDecimal deal = null != data.getBigDecimal("field-amount") ? data.getBigDecimal("field-amount") : data.getBigDecimal("filled-amount"); BigDecimal fieldCashAmount = null != data.getBigDecimal("field-cash-amount") ? data.getBigDecimal("field-cash-amount") : data.getBigDecimal("filled-cash-amount"); BigDecimal average = exist(deal) && greater(deal, ZERO) ? div(fieldCashAmount, deal, 16) : null; if (state == State.SUBMIT && null != deal && greater(deal, ZERO)) { state = State.PARTIAL; } return new Order(result, time, id, side, type, state, price, amount, deal, average); } /** * 解析订单列表 * @param result 请求结果 * @param tip 错误提示 * @return 解析结果 */ private List<Order> parseOrders(String result, String tip) { if (useful(result)) { try { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray data = r.getJSONArray("data"); List<Order> orders = new ArrayList<>(data.size()); for (int i = 0, l = data.size(); i < l; i++) { Order order = this.parseOrder(data.getString(i), data.getJSONObject(i), tip); if (exist(order)) { orders.add(order); } } return orders; } } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 订单 和 订单明细 * @param info 请求信息 * @param delay 延时 * @param api api * @return 请求信息 */ private List<MimeRequest> getRequests(ExchangeInfo info, long delay, String api) { String access = info.getAccess(); String secret = info.getSecret(); String id = info.getOrderId(); String url = api.replace("{order-id}", id); Parameter parameter = this.addParam(access, delay); return this.get(parameter, secret, url); } /** * 下单 * @param info 请求信息 * @param delay 延时 * @param price 价格 * @param amount 数量 * @param type 类型 * @return 请求信息 */ private List<MimeRequest> place(ExchangeInfo info, long delay, String price, String amount, String type) { String symbol = this.symbol(info); String access = info.getAccess(); String secret = info.getSecret(); String accountId = this.getAccountId(access, secret); Parameter parameter = this.addParam(access, delay); String sign = this.sign(secret, "POST", site, apiPlace, parameter); parameter.add("Signature", encode(sign)); Parameter param = Parameter.build() .add("account-id", accountId) .add("amount", amount) .add("source", "api") .add("symbol", symbol) .add("type", type); if (useful(price)) { param.add("price", price); } MimeRequest request = new MimeRequest.Builder() .url(address + apiPlace + "?" + parameter.concat()) .post() .header("Accept-Language", "zh-CN") // .header("Content-Type", "application/json;charset=UTF-8") .body(param.json(JSON::toJSONString)) .build(); return Collections.singletonList(request); } /** * 解析id * @param result 请求结果 * @return 订单id */ private String getOrderId(String result) { if (useful(result)) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { return r.getString("data"); } } return null; } /** * 解析订单明细 * @param r json * @return 订单明细 */ private List<OrderDetail> parseOrderDetails(JSONObject r) { JSONArray data = r.getJSONArray("data"); /* * "data": [ * { * "id": 29553, * "order-id": 59378, * "match-id": 59335, * "symbol": "ethusdt", * "type": "buy-limit", * "source": "api", * "price": "100.1000000000", * "filled-amount": "9.1155000000", * "filled-fees": "0.0182310000", * "created-at": 1494901400435 * } * ] */ List<OrderDetail> details = new ArrayList<>(data.size()); for (int i = 0; i < data.size(); i++) { JSONObject t = data.getJSONObject(i); Long time = t.getLong("created-at"); String orderId = t.getString("order-id"); String detailId = t.getString("match-id"); BigDecimal price = t.getBigDecimal("price"); BigDecimal amount = t.getBigDecimal("filled-amount"); BigDecimal fee = t.getBigDecimal("filled-fees"); OrderDetail detail = new OrderDetail(data.getString(i), time, orderId, detailId, price, amount, fee, null); details.add(detail); } return details; } }
28,633
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BaseWebSocketClient.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/web/socket/BaseWebSocketClient.java
package cqt.goai.exchange.web.socket; import cqt.goai.exchange.util.RateLimit; import cqt.goai.model.enums.Period; import cqt.goai.model.market.Klines; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Ticker; import cqt.goai.model.market.Trades; import cqt.goai.model.trade.Account; import cqt.goai.model.trade.Orders; import org.slf4j.Logger; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import static dive.common.util.Util.exist; /** * WebSocket连接 * @author GOAi */ public abstract class BaseWebSocketClient { /** * 日志 */ protected final Logger log; /** * 币对 */ protected final String symbol; /** * access */ protected final String access; /** * secret */ protected final String secret; /** * 连接ping的频率 本链接最近更新频率, 高于该频率不发送ping */ protected final RateLimit limit; /** * 消费函数 */ private Consumer<Ticker> onTicker; private ConcurrentHashMap<Period, Consumer<Klines>> onKlines = new ConcurrentHashMap<>(); private Consumer<Depth> onDepth; private Consumer<Trades> onTrades; private Consumer<Account> onAccount; private Consumer<Orders> onOrders; public BaseWebSocketClient(String symbol, String access, String secret, RateLimit limit, Logger log) { this.symbol = symbol; this.access = access; this.secret = secret; this.limit = limit; this.log = log; } /** * 第一次连接需要做的 */ public abstract void open(); /** * 连接断开 */ public abstract void closed(); /** * 发送message * @param message message */ protected abstract void send(String message); /** * ping */ public void ping() { if (this.limit.timeout(true)) { this.send("ping"); } } /** * 处理收到的新信息 * @param message 收到信息 */ protected abstract void transform(String message); /** * 主动断开 * @param code code * @param reason reason */ public abstract void close(int code, String reason); /** * 命令日志 * @param command 命令 * @param url url */ protected void commandLog(String command, String url) { this.log.info("websocket send: {} to {}", command, url); } // ===================== ticker ===================== /** * 注册推送Ticker * @param onTicker 推送函数 */ public void onTicker(Consumer<Ticker> onTicker) { this.onTicker = onTicker; this.askTicker(); } /** * 发送订阅信息 */ protected abstract void askTicker(); /** * 接收到Ticker后 * @param ticker ticker */ protected void onTicker(Ticker ticker) { if (exist(this.onTicker)) { this.onTicker.accept(ticker); } } /** * 取消推送Ticker */ public abstract void noTicker(); // ===================== klines ===================== /** * 注册推送Klines * @param onKlines 推送函数 * @param period 周期 */ public void onKlines(Consumer<Klines> onKlines, Period period) { this.onKlines.put(period, onKlines); this.askKlines(period); } /** * 发送订阅信息 * @param period 周期 */ protected abstract void askKlines(Period period); /** * 接收到Ticker后 * @param klines klines * @param period 周期 */ protected void onKlines(Klines klines, Period period) { if (this.onKlines.containsKey(period)) { this.onKlines.get(period).accept(klines); } } /** * 取消推送Klines * @param period 周期 */ public abstract void noKlines(Period period); // ===================== depth ===================== /** * 注册推送Depth * @param onDepth 推送函数 */ public void onDepth(Consumer<Depth> onDepth) { this.onDepth = onDepth; this.askDepth(); } /** * 发送订阅信息 */ protected abstract void askDepth(); /** * 接收到Depth后 * @param depth depth */ protected void onDepth(Depth depth) { if (exist(this.onDepth)) { this.onDepth.accept(depth); } } /** * 取消推送Ticker */ public abstract void noDepth(); // ===================== trades ===================== /** * 注册推送Trades * @param onTrades 推送函数 */ public void onTrades(Consumer<Trades> onTrades) { this.onTrades = onTrades; this.askTrades(); } /** * 发送订阅信息 */ protected abstract void askTrades(); /** * 接收到Trades后 * @param trades Trades */ protected void onTrades(Trades trades) { if (exist(this.onTrades)) { this.onTrades.accept(trades); } } /** * 取消推送Trades */ public abstract void noTrades(); // ===================== account ===================== /** * 注册推送Account * @param onAccount 推送函数 */ public void onAccount(Consumer<Account> onAccount) { this.onAccount = onAccount; this.askAccount(); } /** * 发送订阅信息 */ protected abstract void askAccount(); /** * 接收到Account后 * @param account account */ protected void onAccount(Account account) { if (exist(this.onAccount)) { this.onAccount.accept(account); } } /** * 取消推送Account */ public abstract void noAccount(); // ===================== orders ===================== /** * 注册推送Orders * @param onOrders 推送函数 */ public void onOrders(Consumer<Orders> onOrders) { this.onOrders = onOrders; this.askOrders(); } /** * 发送订阅信息 */ protected abstract void askOrders(); /** * 接收到Orders后 * @param orders orders */ protected void onOrders(Orders orders) { if (exist(this.onOrders)) { this.onOrders.accept(orders); } } /** * 取消推送Orders */ public abstract void noOrders(); }
6,492
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
WebSocketExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/web/socket/WebSocketExchange.java
package cqt.goai.exchange.web.socket; import cqt.goai.exchange.BaseExchange; import cqt.goai.exchange.ExchangeException; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.model.enums.Period; import cqt.goai.model.market.Klines; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Ticker; import cqt.goai.model.market.Trades; import cqt.goai.model.trade.Account; import cqt.goai.model.trade.Orders; import dive.common.math.RandomUtil; import org.slf4j.Logger; import java.util.concurrent.*; import java.util.function.Consumer; /** * WebSocket请求,每个交易所的WebSocket请求方式都要继承该类 * @author GOAi */ public class WebSocketExchange extends BaseExchange { /** * 每个连接加入ping的id,取消时用 */ private String id; /** * 需要ping的连接 */ private static final ConcurrentHashMap<String, WebSocketExchange> EXCHANGES = new ConcurrentHashMap<>(); static { ScheduledExecutorService timer = new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutor.DiscardPolicy()); timer.scheduleAtFixedRate(() -> EXCHANGES.values().stream().parallel().forEach(WebSocketExchange::ping), 7, 7, TimeUnit.SECONDS); } public WebSocketExchange(ExchangeName name, Logger log) { super(name, log); this.ping(this); } /** * 定时某些交易所需要定时向服务器发送ping */ protected void ping() {} /** * 加入ping * @param e ping对象 */ private void ping(WebSocketExchange e) { if (null != this.id && EXCHANGES.containsKey(this.id)) { return; } this.id = RandomUtil.token(); EXCHANGES.put(this.id, e); } /** * 取消ping */ protected void noPing() { EXCHANGES.remove(this.id); } // =============== ticker =============== /** * 获取Ticker * @param info 请求信息 * @param onTicker 消费函数 * @return 订阅id */ public boolean onTicker(ExchangeInfo info, Consumer<Ticker> onTicker) { throw new ExchangeException(super.name + " " + info.getSymbol() + " onTicker is not supported."); } public void noTicker(String pushId) { throw new ExchangeException(super.name + " noTicker is not supported. pushId: " + pushId); } // =============== klines =============== /** * 获取Klines * @param info 请求信息 * @param onKlines 消费函数 * @return 订阅id */ public boolean onKlines(ExchangeInfo info, Consumer<Klines> onKlines) { throw new ExchangeException(super.name + " " + info.getSymbol() + " onKlines " + info.getPeriod() + " is not supported."); } public void noKlines(Period period, String pushId) { throw new ExchangeException(super.name + " noKlines " + period + " is not supported. pushId: " + pushId); } // =============== depth =============== /** * 获取Depth * @param info 请求信息 * @param onDepth 消费函数 * @return 订阅id */ public boolean onDepth(ExchangeInfo info, Consumer<Depth> onDepth) { throw new ExchangeException(super.name + " " + info.getSymbol() + " onDepth is not supported."); } public void noDepth(String pushId) { throw new ExchangeException(super.name + " noDepth is not supported. pushId: " + pushId); } // =============== trades =============== /** * 获取Trades * @param info 请求信息 * @param onTrades 消费函数 * @return 订阅id */ public boolean onTrades(ExchangeInfo info, Consumer<Trades> onTrades) { throw new ExchangeException(super.name + " " + info.getSymbol() + " onTrades is not supported."); } public void noTrades(String pushId) { throw new ExchangeException(super.name + " noTrades is not supported. pushId: " + pushId); } // =============== account =============== /** * 获取Account * @param info 请求信息 * @param onAccount 消费函数 * @return 订阅id */ public boolean onAccount(ExchangeInfo info, Consumer<Account> onAccount) { throw new ExchangeException(super.name + " " + info.getSymbol() + " onAccount is not supported."); } public void noAccount(String pushId) { throw new ExchangeException(super.name + " noAccount is not supported. pushId: " + pushId); } // =============== orders =============== /** * 获取Orders * @param info 请求信息 * @param onOrders 消费函数 * @return 订阅id */ public boolean onOrders(ExchangeInfo info, Consumer<Orders> onOrders) { throw new ExchangeException(super.name + " " + info.getSymbol() + " onOrders is not supported."); } public void noOrders(String pushId) { throw new ExchangeException(super.name + " noOrders is not supported. pushId: " + pushId); } }
5,007
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
WebSocketInfo.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/web/socket/WebSocketInfo.java
package cqt.goai.exchange.web.socket; import cqt.goai.exchange.Action; import cqt.goai.model.enums.Period; import lombok.Data; import java.util.Objects; import java.util.function.Consumer; /** * WebSocket推送封装的信息 * @author GOAi */ @Data public class WebSocketInfo<T> { /** * 推送id */ private String id; /** * 推送行为类型 */ private Action action; /** * 推送币对 */ private String symbol; /** * 推送用户 */ private String access; /** * 消费函数 */ private Consumer<T> consumer; /** * 周期 */ private Period period; public WebSocketInfo(String id, Action action, String symbol, String access, Consumer<T> consumer) { this.id = id; this.action = action; this.symbol = symbol; this.access = access; this.consumer = consumer; } public WebSocketInfo(String id, Action action, String symbol, String access, Consumer<T> consumer, Period period) { this.id = id; this.action = action; this.symbol = symbol; this.access = access; this.consumer = consumer; this.period = period; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WebSocketInfo<?> onInfo = (WebSocketInfo<?>) o; return Objects.equals(id, onInfo.id); } @Override public int hashCode() { return Objects.hash(id); } }
1,628
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Okexv3WebSocketExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/web/socket/okexv3/Okexv3WebSocketExchange.java
package cqt.goai.exchange.web.socket.okexv3; import cqt.goai.exchange.Action; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.util.RateLimit; import cqt.goai.exchange.web.socket.BaseWebSocketClient; import cqt.goai.exchange.web.socket.WebSocketExchange; import cqt.goai.exchange.web.socket.WebSocketInfo; import cqt.goai.model.enums.Period; import cqt.goai.model.market.Klines; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Ticker; import cqt.goai.model.market.Trades; import cqt.goai.model.trade.Account; import cqt.goai.model.trade.Orders; import org.slf4j.Logger; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Consumer; import static dive.common.util.Util.exist; /** * @author GOAi */ public class Okexv3WebSocketExchange extends WebSocketExchange { /** * ping的频率限制 */ private static final RateLimit LIMIT = RateLimit.limit(1000 * 17); /** * 订阅id和每个订阅基本信息 id -> info */ private static final ConcurrentHashMap<String, WebSocketInfo> CONSUMERS = new ConcurrentHashMap<>(); /** * 同一币对的连接 */ private static final ConcurrentHashMap<String, Okexv3WebSocketClient> CLIENTS = new ConcurrentHashMap<>(); /** * ticker订阅信息 symbol -> info , Ticker来了,推送Ticker的地方 */ private static final ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketInfo<Ticker>>> TICKERS = new ConcurrentHashMap<>(); /** * klines订阅信息 symbol -> (period -> info) */ private static final ConcurrentHashMap<String, ConcurrentHashMap<Period, ConcurrentLinkedQueue<WebSocketInfo<Klines>>>> KLINES = new ConcurrentHashMap<>(); /** * depth订阅信息 symbol -> info , Depth来了,推送Depth的地方 */ private static final ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketInfo<Depth>>> DEPTH = new ConcurrentHashMap<>(); /** * trades订阅信息 symbol -> info , Trades来了,推送Trades的地方 */ private static final ConcurrentHashMap<String, ConcurrentLinkedQueue<WebSocketInfo<Trades>>> TRADES = new ConcurrentHashMap<>(); /** * 每个实例的连接 */ private Okexv3WebSocketClient client; /** * 每个实例的账户余额推送 */ private final ConcurrentLinkedQueue<WebSocketInfo<Account>> accounts = new ConcurrentLinkedQueue<>(); /** * 每个实例的订单 */ private final ConcurrentLinkedQueue<WebSocketInfo<Orders>> orders = new ConcurrentLinkedQueue<>(); public Okexv3WebSocketExchange(Logger log) { super(ExchangeName.OKEXV3, log); } @Override protected void ping() { if (!Okexv3WebSocketExchange.LIMIT.timeout()) { return; } // 已经到了ping的时间了,就要遍历每个连接,ping一下 Okexv3WebSocketExchange.CLIENTS.values().parallelStream().forEach(BaseWebSocketClient::ping); if (null != this.client) { this.client.ping(); } } /** * 统一添加订阅 * @param list 订阅list * @param onInfo 订阅信息 * @param symbol 订阅币对 */ private <T> Okexv3WebSocketClient addInfo(ConcurrentLinkedQueue<WebSocketInfo<T>> list, WebSocketInfo<T> onInfo, String symbol) { if (!list.isEmpty()) { // 该币对已经有订阅, 加入订阅队列即可 list.add(onInfo); } else { // 无订阅 list.add(onInfo); // 取出这个币对的连接 Okexv3WebSocketClient client = Okexv3WebSocketExchange.CLIENTS.get(symbol); if (!exist(client)) { // 该币对无连接,新建一个 client = new Okexv3WebSocketClient(symbol, super.log); Okexv3WebSocketExchange.CLIENTS.put(symbol, client); } // 对这个连接订阅ticker return client; } return null; } @Override public boolean onTicker(ExchangeInfo info, Consumer<Ticker> onTicker) { String symbol = info.getSymbol(); String access = info.getAccess(); String id = info.getPushId(); WebSocketInfo<Ticker> onInfo = new WebSocketInfo<>(id, Action.ON_TICKER, symbol, access, onTicker); ConcurrentLinkedQueue<WebSocketInfo<Ticker>> list = Okexv3WebSocketExchange.TICKERS .computeIfAbsent(symbol, k -> new ConcurrentLinkedQueue<>()); Okexv3WebSocketClient client = this.addInfo(list, onInfo, symbol); if (null != client) { // 对这个连接订阅ticker client.onTicker(ticker -> list.stream() .parallel() .forEach(i -> i.getConsumer().accept(ticker))); } // 将这个订阅添加到总记录里 Okexv3WebSocketExchange.CONSUMERS.put(id, onInfo); return true; } @Override public void noTicker(String pushId) { WebSocketInfo info = Okexv3WebSocketExchange.CONSUMERS.get(pushId); if (null != info) { String symbol = info.getSymbol(); ConcurrentLinkedQueue<WebSocketInfo<Ticker>> list = Okexv3WebSocketExchange.TICKERS .getOrDefault(symbol, null); if (null != list) { if (list.size() <= 1) { // 这是最后一个订阅,需要取消订阅 Okexv3WebSocketClient client = Okexv3WebSocketExchange.CLIENTS.get(symbol); if (null != client) { client.noTicker(); } } list.remove(info); } Okexv3WebSocketExchange.CONSUMERS.remove(pushId); } } @Override public boolean onKlines(ExchangeInfo info, Consumer<Klines> onKlines) { String symbol = info.getSymbol(); String access = info.getAccess(); Period period = info.getPeriod(); String id = info.getPushId(); WebSocketInfo<Klines> onInfo = new WebSocketInfo<>(id, Action.ON_KLINES, symbol, access, onKlines, period); ConcurrentLinkedQueue<WebSocketInfo<Klines>> list = Okexv3WebSocketExchange.KLINES .computeIfAbsent(symbol, k -> new ConcurrentHashMap<>(16)) .computeIfAbsent(period, p -> new ConcurrentLinkedQueue<>()); Okexv3WebSocketClient client = this.addInfo(list, onInfo, symbol); if (null != client) { // 对这个连接订阅klines client.onKlines(klines -> list.stream().parallel() .forEach(i -> i.getConsumer().accept(klines)), period); } // 将这个订阅添加到总记录里 Okexv3WebSocketExchange.CONSUMERS.put(id, onInfo); return true; } @Override public void noKlines(Period period, String pushId) { WebSocketInfo info = Okexv3WebSocketExchange.CONSUMERS.get(pushId); if (null != info) { String symbol = info.getSymbol(); ConcurrentHashMap<Period, ConcurrentLinkedQueue<WebSocketInfo<Klines>>> klines = Okexv3WebSocketExchange.KLINES.getOrDefault(period, null); if (null != klines) { ConcurrentLinkedQueue<WebSocketInfo<Klines>> list = klines.getOrDefault(symbol, null); if (null != list) { if (list.size() <= 1) { // 这是最后一个订阅,需要取消订阅 Okexv3WebSocketClient client = Okexv3WebSocketExchange.CLIENTS.get(symbol); if (null != client) { client.noKlines(period); } } list.remove(info); } } Okexv3WebSocketExchange.CONSUMERS.remove(pushId); } } @Override public boolean onDepth(ExchangeInfo info, Consumer<Depth> onDepth) { String symbol = info.getSymbol(); String access = info.getAccess(); String id = info.getPushId(); WebSocketInfo<Depth> onInfo = new WebSocketInfo<>(id, Action.ON_DEPTH, symbol, access, onDepth); ConcurrentLinkedQueue<WebSocketInfo<Depth>> list = Okexv3WebSocketExchange.DEPTH .computeIfAbsent(symbol, k -> new ConcurrentLinkedQueue<>()); Okexv3WebSocketClient client = this.addInfo(list, onInfo, symbol); if (null != client) { // 对这个连接订阅depth client.onDepth(depth -> list.stream().parallel() .forEach(i -> i.getConsumer().accept(depth))); } // 将这个订阅添加到总记录里 Okexv3WebSocketExchange.CONSUMERS.put(id, onInfo); return true; } @Override public void noDepth(String pushId) { WebSocketInfo info = Okexv3WebSocketExchange.CONSUMERS.get(pushId); if (null != info) { String symbol = info.getSymbol(); ConcurrentLinkedQueue<WebSocketInfo<Depth>> list = Okexv3WebSocketExchange.DEPTH .getOrDefault(symbol, null); if (null != list) { if (list.size() <= 1) { // 这是最后一个订阅,需要取消订阅 Okexv3WebSocketClient client = Okexv3WebSocketExchange.CLIENTS.get(symbol); if (null != client) { client.noDepth(); } } list.remove(info); } Okexv3WebSocketExchange.CONSUMERS.remove(pushId); } } @Override public boolean onTrades(ExchangeInfo info, Consumer<Trades> onTrades) { String symbol = info.getSymbol(); String access = info.getAccess(); String id = info.getPushId(); WebSocketInfo<Trades> onInfo = new WebSocketInfo<>(id, Action.ON_TRADES, symbol, access, onTrades); ConcurrentLinkedQueue<WebSocketInfo<Trades>> list = Okexv3WebSocketExchange.TRADES .computeIfAbsent(symbol, k -> new ConcurrentLinkedQueue<>()); Okexv3WebSocketClient client = this.addInfo(list, onInfo, symbol); if (null != client) { // 对这个连接订阅ticker client.onTrades(trades -> list.stream().parallel() .forEach(i -> i.getConsumer().accept(trades))); } // 将这个订阅添加到总记录里 Okexv3WebSocketExchange.CONSUMERS.put(id, onInfo); return true; } @Override public void noTrades(String pushId) { WebSocketInfo info = Okexv3WebSocketExchange.CONSUMERS.get(pushId); if (null != info) { String symbol = info.getSymbol(); ConcurrentLinkedQueue<WebSocketInfo<Trades>> list = Okexv3WebSocketExchange.TRADES .getOrDefault(symbol, null); if (null != list) { if (list.size() <= 1) { // 这是最后一个订阅,需要取消订阅 Okexv3WebSocketClient client = Okexv3WebSocketExchange.CLIENTS.get(symbol); if (null != client) { client.noTrades(); } } list.remove(info); } Okexv3WebSocketExchange.CONSUMERS.remove(pushId); } } @Override public boolean onAccount(ExchangeInfo info, Consumer<Account> onAccount) { String symbol = info.getSymbol(); String access = info.getAccess(); String secret = info.getSecret(); String id = info.getPushId(); WebSocketInfo<Account> onInfo = new WebSocketInfo<>(id, Action.ON_ACCOUNT, symbol, access, onAccount); if (null == this.client) { this.client = new Okexv3WebSocketClient(symbol, access, secret, super.log); } this.accounts.add(onInfo); // 对这个连接订阅account this.client.onAccount(account -> this.accounts.stream().parallel() .forEach(i -> i.getConsumer().accept(account))); // 将这个订阅添加到总记录里 Okexv3WebSocketExchange.CONSUMERS.put(id, onInfo); return true; } @Override public void noAccount(String pushId) { WebSocketInfo info = Okexv3WebSocketExchange.CONSUMERS.get(pushId); if (null != info) { if (!this.accounts.isEmpty()) { if (this.accounts.size() <= 1) { // 这是最后一个订阅,需要取消订阅 this.client.noAccount(); } this.accounts.remove(info); } Okexv3WebSocketExchange.CONSUMERS.remove(pushId); } } @Override public boolean onOrders(ExchangeInfo info, Consumer<Orders> onOrders) { String symbol = info.getSymbol(); String access = info.getAccess(); String secret = info.getSecret(); String id = info.getPushId(); WebSocketInfo<Orders> onInfo = new WebSocketInfo<>(id, Action.ON_ORDERS, symbol, access, onOrders); if (null == this.client) { this.client = new Okexv3WebSocketClient(symbol, access, secret, super.log); } this.orders.add(onInfo); // 对这个连接订阅orders this.client.onOrders(orders -> this.orders.stream().parallel() .forEach(i -> i.getConsumer().accept(orders))); // 将这个订阅添加到总记录里 Okexv3WebSocketExchange.CONSUMERS.put(id, onInfo); return true; } @Override public void noOrders(String pushId) { WebSocketInfo info = Okexv3WebSocketExchange.CONSUMERS.get(pushId); if (null != info) { if (!this.orders.isEmpty()) { if (this.orders.size() <= 1) { // 这是最后一个订阅,需要取消订阅 this.client.noOrders(); } this.orders.remove(info); } Okexv3WebSocketExchange.CONSUMERS.remove(pushId); } } }
14,497
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Okexv3WebSocketClient.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/web/socket/okexv3/Okexv3WebSocketClient.java
package cqt.goai.exchange.web.socket.okexv3; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.*; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.exchange.util.OkhttpWebSocket; import cqt.goai.exchange.util.RateLimit; import cqt.goai.exchange.util.Seal; import cqt.goai.exchange.util.okexv3.Okexv3Util; import cqt.goai.exchange.web.socket.BaseWebSocketClient; import cqt.goai.model.enums.Period; import cqt.goai.model.market.*; import cqt.goai.model.trade.Account; import cqt.goai.model.trade.Balance; import cqt.goai.model.trade.Orders; import dive.common.crypto.Base64Util; import dive.common.crypto.HmacUtil; import org.slf4j.Logger; import java.math.BigDecimal; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import java.util.zip.CRC32; import static dive.common.util.Util.exist; /** * OKExV3的websocket连接 * @author GOAi */ public class Okexv3WebSocketClient extends BaseWebSocketClient { private static final String URL = "wss://real.okex.com:10442/ws/v3"; /** * 推送回调 */ private OkhttpWebSocket client; /** * 是否需要登录 */ private final boolean doLogin; /** * 是否已经连接 */ private boolean connected = false; /** * 标记是否登录 */ private boolean login = false; /** * 标记是否主动关闭 */ private boolean dead = false; /** * 普通命令 */ private CopyOnWriteArrayList<String> commands = new CopyOnWriteArrayList<>(); /** * 需要登录的命令 */ private CopyOnWriteArrayList<String> loginCommands = new CopyOnWriteArrayList<>(); private ConcurrentHashMap<Period, ConcurrentLinkedDeque<Kline>> klines = new ConcurrentHashMap<>(); private ConcurrentHashMap<Period, Lock> klinesLocks = new ConcurrentHashMap<>(); private ConcurrentHashMap<BigDecimal, Row> asks = new ConcurrentHashMap<>(); private ConcurrentHashMap<BigDecimal, Row> bids = new ConcurrentHashMap<>(); private Lock depthLock = new ReentrantLock(); private RateLimit depthLimit = RateLimit.second10(); private Balance base; private Balance count; Okexv3WebSocketClient(String symbol, Logger log) { super(symbol, null, null, RateLimit.second13(), log); this.client = new OkhttpWebSocket(URL, Okexv3Util::uncompress, this::open, this::transform, this::closed, this.log); this.doLogin = false; } Okexv3WebSocketClient(String symbol, String access, String secret, Logger log) { super(symbol, access, secret, RateLimit.second13(), log); this.client = new OkhttpWebSocket(URL, Okexv3Util::uncompress, this::open, this::transform, this::closed, this.log); this.doLogin = true; } @Override public void open() { this.connected = true; if (this.doLogin) { this.login(); } this.commands.forEach(this::send); } /** * 登录 */ private void login() { /* * {"op":"login","args":["985d5b66-57ce-40fb-b714-afc0b9787083","xxx","1538054050.975", * "xxx"]} */ String access = super.access; String[] split = CommonUtil.split(super.secret); String secret = split[0]; String passphrase = split[1]; long timestamp = System.currentTimeMillis() / 1000; String sign = null; try { sign = Base64Util.base64EncodeToString(HmacUtil.hmac((timestamp + "GET/users/self/verify").getBytes(), secret, HmacUtil.HMAC_SHA256)); } catch (NoSuchAlgorithmException | InvalidKeyException ignored) { } super.commandLog(String.format("{\"op\":\"login\",\"args\":[\"%s\",\"%s\",\"%s\",\"%s\"]}", Seal.seal(access), Seal.seal(passphrase), timestamp, sign), Okexv3WebSocketClient.URL); String message = String.format("{\"op\":\"login\",\"args\":[\"%s\",\"%s\",\"%s\",\"%s\"]}", access, passphrase, timestamp, sign); this.client.send(message); } @Override public void closed() { this.connected = false; if (!this.dead) { this.client.connect(); } } @Override protected void send(String message) { super.commandLog(message, Okexv3WebSocketClient.URL); this.client.send(message); } @Override public void ping() { // okhttp 30s 未收消息会关闭连接 // 所以定时发个命令,也算是接收消息了 if (this.limit.timeout(true)) { this.client.send(ALIVE); } } @Override protected void transform(String message) { JSONObject r = JSON.parseObject(message); if (r.containsKey(EVENT)) { switch (r.getString(EVENT)) { case "subscribe": this.log.info("{} subscribe success: {}", super.symbol, message); return; case "unsubscribe": this.log.info("{} unsubscribe success: {}", super.symbol, message); return; case "login": if (r.containsKey(SUCCESS) && r.getBoolean(SUCCESS)) { this.log.info("{} {} login success: {}", Seal.seal(super.access), super.symbol, message); Account account = ExchangeManager.getHttpExchange(ExchangeName.OKEXV3, this.log) .getAccount(ExchangeInfo.ticker(super.symbol, super.access, super.secret)); if (null != account) { this.base = account.getBase(); this.count = account.getQuote(); } this.login = true; this.loginCommands.forEach(this::send); } return; case "error": if (r.containsKey(ERROR_CODE)) { switch (r.getInteger(ERROR_CODE)) { case ERROR_CODE_LOGGED_OUT: this.login = false; this.login(); break; case ERROR_CODE_LOGGED_IN: this.login = true; return; case ERROR_CODE_ERROR_COMMAND: if (r.getString(MESSAGE).endsWith(ALIVE)) { this.limit.update(); return; } default: } } default: } } if (r.containsKey(TABLE)) { String table = r.getString(TABLE); switch (table) { case "spot/ticker": // 解析Ticker this.transformTicker(r); return; case "spot/depth": // 解析Depth if (this.transformDepth(r)) { return; } super.limit.update(); break; case "spot/trade": // 解析Trades this.transformTrades(r); return; case "spot/account": // 解析account log.info("account: {}", message); this.transformAccount(r); return; case "spot/order": // 解析Trades this.transformOrders(r); return; default: } if (table.startsWith(KLINE_START)) { this.transformKlines(table, r); return; } } this.log.error("can not transform: {}", message); } private void transformOrders(JSONObject r) { Orders orders = Okexv3Util.parseOrders(r.getJSONArray("data")); if (exist(orders)) { super.onOrders(orders); } super.limit.update(); } private void transformAccount(JSONObject r) { Balance balance = Okexv3Util.parseBalance(r.getJSONArray("data").getString(0), r.getJSONArray("data").getJSONObject(0)); if (exist(balance)) { boolean update = false; if (super.symbol.startsWith(balance.getCurrency())) { this.base = balance; update = true; } else if (super.symbol.endsWith(balance.getCurrency())) { this.count = balance; update = true; } if (update) { super.onAccount(new Account(System.currentTimeMillis(), this.base, this.count)); } } super.limit.update(); } private void transformTrades(JSONObject r) { Trades trades = Okexv3Util.parseTrades(r.getJSONArray("data")); if (exist(trades)) { super.onTrades(trades); } super.limit.update(); } private boolean transformDepth(JSONObject r) { String action = r.getString("action"); if (PARTIAL.equals(action) || UPDATE.equals(action)) { try { if (this.depthLock.tryLock(TRY_TIME, TimeUnit.MILLISECONDS)) { try { Depth depth = null; r = r.getJSONArray("data").getJSONObject(0); if (PARTIAL.equals(action)) { // 全更新 depth = Okexv3Util.parseDepth(r); this.depthLimit.update(); this.updateLocalRows(depth.getAsks().getList(), depth.getBids().getList()); } else { // 部分更新 Long time = r.getDate("timestamp").getTime(); // 把更新的替换 List<Row> asks = CommonUtil.parseRowsByIndex(r.getJSONArray("asks")); List<Row> bids = CommonUtil.parseRowsByIndex(r.getJSONArray("bids")); asks.forEach(row -> this.asks.put(row.getPrice(), row)); bids.forEach(row -> this.bids.put(row.getPrice(), row)); // 排序过滤 asks = this.asks.values().stream() .filter(row -> 0 < row.getAmount().compareTo(BigDecimal.ZERO)) .sorted(Comparator.comparing(Row::getPrice)) .limit(MAX) .collect(Collectors.toList()); bids = this.bids.values().stream() .filter(row -> 0 < row.getAmount().compareTo(BigDecimal.ZERO)) .sorted((r1, r2) -> r2.getPrice().compareTo(r1.getPrice())) .limit(MAX) .collect(Collectors.toList()); boolean check = this.depthCheckSum(asks, bids, r); if (check) { depth = new Depth(time, new Rows(asks), new Rows(bids)); } this.updateLocalRows(asks, bids); } if (exist(depth)) { super.onDepth(depth); } super.limit.update(); return true; } finally { this.depthLock.unlock(); } } } catch (InterruptedException e) { e.printStackTrace(); } } return false; } private boolean depthCheckSum(List<Row> asks, List<Row> bids, JSONObject r) { // 检查 // 校验个数 int size = 25; StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { if (i < bids.size()) { // COLON ':' sb.append(bids.get(i).getPrice().toPlainString()) .append(COLON) .append(bids.get(i).getAmount().toPlainString()) .append(COLON); } if (i < asks.size()) { // COLON ':' sb.append(asks.get(i).getPrice().toPlainString()) .append(COLON) .append(asks.get(i).getAmount().toPlainString()) .append(COLON); } } if (0 < sb.length() && COLON == sb.charAt(sb.length() - 1) && r.containsKey(CHECK_SUM)) { sb.deleteCharAt(sb.length() - 1); long check = Okexv3WebSocketClient.crc32(sb.toString().getBytes()); Long checkSum = r.getLong(CHECK_SUM); if (check != checkSum) { // 校验不通过 if (this.depthLimit.timeout(true)) { // 如果10s都不是完全正确的,则强制注册推送完整版 this.send("subscribe", "spot/depth", false); return false; } } } this.depthLimit.update(); return true; } private static long crc32(byte[] data) { CRC32 crc32 = new CRC32(); crc32.update(data); return crc32.getValue(); } private void updateLocalRows(List<Row> asks, List<Row> bids) { this.asks.clear(); asks.forEach(row -> this.asks.put(row.getPrice(), row)); this.bids.clear(); bids.forEach(row -> this.bids.put(row.getPrice(), row)); } private void transformKlines(String table, JSONObject r) { String type = table.substring(11); type = type.substring(0, type.length() - 1); Period period = Period.parse(Integer.valueOf(type)); String result = r.getJSONArray("data").getJSONObject(0).getString("candle"); Kline kline = Okexv3Util.parseKline(result, r.getJSONArray("data").getJSONObject(0).getJSONArray("candle")); if (exist(kline)) { Klines klines = this.onKline(kline, period); if (null != klines) { super.onKlines(klines, period); } } super.limit.update(); } private void transformTicker(JSONObject r) { String result = r.getJSONArray("data").getString(0); Ticker ticker = Okexv3Util.parseTicker(result, r.getJSONArray("data").getJSONObject(0)); if (exist(ticker)) { super.onTicker(ticker); } super.limit.update(); } /** * 尝试时间 */ private static final long TRY_TIME = 3000; /** * k线保留最大长度 */ private static final int MAX = 200; /** * 构造Klines * @param kline 最新的k线 * @param period 周期 * @return 100根k线 */ private Klines onKline(Kline kline, Period period) { Lock lock = this.klinesLocks.computeIfAbsent(period, p -> new ReentrantLock()); try { if (lock.tryLock(TRY_TIME, TimeUnit.MILLISECONDS)) { try { ConcurrentLinkedDeque<Kline> klines = this.klines.computeIfAbsent(period, p -> new ConcurrentLinkedDeque<>()); if (klines.isEmpty()) { // 如果没有k线,则通过http方式获取 try { Klines cs = ExchangeManager.getHttpExchange(ExchangeName.OKEXV3, this.log) .getKlines(ExchangeInfo.klines(super.symbol, "", "", period)); klines.addAll(cs.getList()); } catch (Exception e) { e.printStackTrace(); this.log.error(e.getMessage()); } } if (klines.isEmpty()) { klines.add(kline); } else { // 取出第1根,比较时间,相同则替换,不相同则插入,然后判断长度, Kline c = klines.peek(); if (c.getTime().equals(kline.getTime())) { // 相同 klines.poll(); klines.addFirst(kline); } else { klines.addFirst(kline); while (MAX < klines.size()) { klines.pollLast(); } } } return new Klines(new ArrayList<>(klines)); } finally { lock.unlock(); } } } catch (InterruptedException e) { e.printStackTrace(); this.log.error(e.getMessage()); } return null; } @Override public void close(int code, String reason) { this.dead = true; this.client.close(code, reason); } /** * 统一发送信息 * @param command 命令 subscribe unsubscribe * @param channel 订阅类型 spot/ticker spot/candle60s 等 */ private void send(String command, String channel, boolean record) { String symbol = super.symbol.replace("_", "-"); String message = String.format("{\"op\":\"%s\",\"args\":[\"%s:%s\"]}", command, channel, symbol); super.commandLog(message, Okexv3WebSocketClient.URL); if (record) { this.commands.add(message); } if (this.connected) { this.send(message); } } @Override protected void askTicker() { this.send("subscribe", "spot/ticker", true); } @Override public void noTicker() { this.send("unsubscribe", "spot/ticker", true); } @Override protected void askKlines(Period period) { String channel = Okexv3WebSocketClient.getChannel(period); this.send("subscribe", channel, true); } /** * 获取K线channel * @param period 周期 * @return channel */ private static String getChannel(Period period) { /* * swap/candle60s // 1分钟k线数据频道 * swap/candle180s // 3分钟k线数据频道 * swap/candle300s // 5分钟k线数据频道 * swap/candle900s // 15分钟k线数据频道 * swap/candle1800s // 30分钟k线数据频道 * swap/candle3600s // 1小时k线数据频道 * swap/candle7200s // 2小时k线数据频道 * swap/candle14400s // 4小时k线数据频道 * swap/candle21600 // 6小时k线数据频道 * swap/candle43200s // 12小时k线数据频道 * swap/candle86400s // 1day k线数据频道 * swap/candle604800s // 1week k线数据频道 */ Integer granularity = Okexv3Util.getPeriod(period); if (null == granularity) { throw new ExchangeException(ExchangeError.PERIOD, "OKEx is not supported for period: " + period.name()); } return "spot/candle" + granularity + "s"; } @Override public void noKlines(Period period) { String channel = Okexv3WebSocketClient.getChannel(period); this.send("unsubscribe", channel, true); } @Override protected void askDepth() { this.send("subscribe", "spot/depth", true); } @Override public void noDepth() { this.send("unsubscribe", "spot/depth", true); } @Override protected void askTrades() { this.send("subscribe", "spot/trade", true); } @Override public void noTrades() { this.send("unsubscribe", "spot/trade", true); } @Override protected void askAccount() { // this.askTicker(); String[] split = CommonUtil.split(super.symbol); String message1 = "{\"op\": \"subscribe\", \"args\": [\"spot/account:" + split[0] + "\"]}"; String message2 = "{\"op\": \"subscribe\", \"args\": [\"spot/account:" + split[1] + "\"]}"; this.loginCommand(message1); this.loginCommand(message2); } private void loginCommand(String command) { this.loginCommands.add(command); if (this.login) { super.commandLog(command, Okexv3WebSocketClient.URL); this.send(command); } } @Override public void noAccount() { String[] split = CommonUtil.split(super.symbol); String message1 = "{\"op\": \"unsubscribe\", \"args\": [\"spot/account:" + split[0] + "\"]}"; String message2 = "{\"op\": \"unsubscribe\", \"args\": [\"spot/account:" + split[1] + "\"]}"; this.loginCommand(message1); this.loginCommand(message2); } @Override protected void askOrders() { String message = "{\"op\":\"subscribe\",\"args\":[\"spot/order:" + super.symbol.replace("_", "-") + "\"]}"; this.loginCommands.add(message); this.send(message); } @Override public void noOrders() { String message = "{\"op\":\"unsubscribe\",\"args\":[\"spot/order:" + super.symbol.replace("_", "-") + "\"]}"; this.loginCommands.add(message); this.send(message); } // ================= tools ================= private static final String EVENT = "event"; private static final String TABLE = "table"; private static final String MESSAGE = "message"; private static final String ALIVE = "alive"; private static final String KLINE_START = "spot/candle"; private static final String PARTIAL = "partial"; private static final String UPDATE = "update"; private static final char COLON = ':'; private static final String CHECK_SUM = "checksum"; private static final String SUCCESS = "success"; private static final String ERROR_CODE = "errorCode"; private static final int ERROR_CODE_LOGGED_OUT = 30041; private static final int ERROR_CODE_LOGGED_IN = 30042; private static final int ERROR_CODE_ERROR_COMMAND = 30039; }
23,125
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Md5Util.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/Md5Util.java
package cqt.goai.exchange.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author GOAi * @description */ public class Md5Util { private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; public static String md5(String str) { try { if (str == null || str.trim().length() == 0) { return ""; } byte[] bytes = str.getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(bytes); bytes = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(HEX_DIGITS[(b & 0xf0) >> 4]).append(HEX_DIGITS[b & 0xf]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } // public static String md5(String str) { // return md5(str).toLowerCase(); // } }
1,115
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
CompleteList.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/CompleteList.java
package cqt.goai.exchange.util; import cqt.goai.exchange.Action; import java.util.*; import java.util.stream.Stream; import static cqt.goai.exchange.Action.*; /** * 便捷标识交易所接口的完成情况 * @author GOAi */ public class CompleteList { public static Action[] ALL; public static Action[] MARKET; public static Action[] ACCOUNT; public static Action[] TRADE; public static Action[] ORDER; public static Action[] PUSH; static { MARKET = new Action[]{TICKER, KLINES, DEPTH, TRADES}; ACCOUNT = new Action[]{BALANCES, Action.ACCOUNT}; TRADE = new Action[]{PRECISIONS, PRECISION, BUY_LIMIT, SELL_LIMIT, BUY_MARKET, SELL_MARKET, MULTI_BUY, MULTI_SELL, CANCEL_ORDER, CANCEL_ORDERS}; ORDER = new Action[]{ORDERS, HISTORY_ORDERS, Action.ORDER, ORDER_DETAILS}; PUSH = new Action[]{ON_TICKER, ON_KLINES, ON_DEPTH, ON_TRADES, ON_ACCOUNT, ON_ORDERS}; Set<Action> list = new HashSet<>(); list.addAll(Arrays.asList(MARKET)); list.addAll(Arrays.asList(ACCOUNT)); list.addAll(Arrays.asList(TRADE)); list.addAll(Arrays.asList(ORDER)); list.addAll(Arrays.asList(PUSH)); ALL = list.toArray(new Action[]{}); } public static Action[] include(Object... actions) { Set<Action> set = new HashSet<>(); for (Object o : actions) { if (o instanceof Action) { set.add((Action) o); } else if ("Action[]".equals(o.getClass().getSimpleName()) && o.getClass().getComponentType() == Action.class) { set.addAll(Arrays.asList((Action[]) o)); } } return set.toArray(new Action[]{}); } public static Action[] exclude(Action[] exclude) { Set<Action> all = new HashSet<>(Arrays.asList(ALL)); Stream.of(exclude).forEach(all::remove); return all.toArray(new Action[]{}); } public static Action[] exclude(Object... actions) { Action[] exclude = CompleteList.include(actions); Set<Action> all = new HashSet<>(Arrays.asList(ALL)); Stream.of(exclude).forEach(all::remove); return all.toArray(new Action[]{}); } }
2,240
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
RateLimit.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/RateLimit.java
package cqt.goai.exchange.util; /** * 频率限制 * 2种限制 * 1. 主动推送限制频率,limit毫秒内只有一次 * 2. 超时限制,推送则更新,30s未推送需要重连 * * @author GOAi */ public class RateLimit { /** * 无限制 */ public static final RateLimit NO = new RateLimit(0); /** * 上次true时间 * 这里判断时间应当非常快没有阻塞的,就不考虑并发问题了,反正限制的频率都是主动推送,不必那么精确的 * AtomicLong 和 Lock 都可以实现并发安全,但是得不偿失,因为即使多推送一次,无伤大雅 */ private long last; /** * 频率限制,若为5000,则在下个5000毫秒内,不会返回true */ private final long limit; private RateLimit(long limit) { this.limit = limit; this.last = 0; } /** * 获取实例 * @param milliseconds 毫秒 * @return 实例 */ public static RateLimit limit(long milliseconds) { return new RateLimit(milliseconds); } public static RateLimit second() { return new RateLimit(1000); } public static RateLimit second5() { return new RateLimit(1000 * 5); } public static RateLimit second10() { return new RateLimit(1000 * 10); } public static RateLimit second15() { return new RateLimit(1000 * 15); } public static RateLimit second20() { return new RateLimit(1000 * 20); } public static RateLimit second30() { return new RateLimit(1000 * 30); } public static RateLimit second3() { return new RateLimit(1000 * 3); } public static RateLimit second13() { return new RateLimit(1000 * 13); } public static RateLimit second23() { return new RateLimit(1000 * 23); } /** * limit内不会再次返回true * @param update 是否更新 * @return 是否到了下一次 */ public boolean timeout(boolean update) { if (limit <= 0) { return true; } long now = System.currentTimeMillis(); boolean result = last + limit < now; if (update && result) { this.last = now; } return result; } /** * limit内不会再次返回true * @return 是否到了下一次 */ public boolean timeout() { return this.timeout(true); } /** * 更新时间, 收到消息更新一下 */ public void update() { this.last = System.currentTimeMillis(); } /** * 是否有限制 * @return 是否有限制 */ public boolean isLimit() { return 0 < this.limit; } @Override public String toString() { return "RateLimit{" + "limit=" + limit + '}'; } }
2,771
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Seal.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/Seal.java
package cqt.goai.exchange.util; import static dive.common.util.Util.useful; /** * 隐藏字符串 * @author GOAi */ public class Seal { /** * 隐藏字符串 */ public static String seal(String secret) { if (!useful(secret)) { return ""; } int length = secret.length(); switch (length) { case 1: return "*"; case 2: return "**"; default: } int margin = 5; int div = length / 3; if (margin <= div) { return secret.substring(0, margin) + getStar(length - margin * 2) + secret.substring(length - margin); } else { return secret.substring(0, div) + getStar(length - div * 2) + secret.substring(length - div); } } /** * 获取指定长度的* */ private static String getStar(int length) { StringBuilder sb = new StringBuilder(); while (sb.length() < length) { sb.append("*"); } return sb.toString(); } }
1,128
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
OkhttpWebSocket.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/OkhttpWebSocket.java
package cqt.goai.exchange.util; import okhttp3.*; import okio.ByteString; import org.slf4j.Logger; import java.util.function.Consumer; import java.util.function.Function; /** * 推送回调 * @author GOAi */ public class OkhttpWebSocket extends WebSocketListener { private static final OkHttpClient OKHTTP_CLIENT = new OkHttpClient(); /** * 连接url */ private final String url; /** * 收到消息转码方式 */ private final Function<ByteString, String> decode; /** * 连接开始 */ private final Runnable open; /** * 接收消息,转码后,交给谁 */ private final Consumer<String> receive; /** * 断开后回调 */ private final Runnable closed; /** * 日志 */ private Logger log; /** * 连接对象 */ private WebSocket webSocket; public OkhttpWebSocket(String url, Function<ByteString, String> decode, Runnable open, Consumer<String> receive, Runnable closed, Logger log) { this.url = url; this.decode = decode; this.open = open; this.receive = receive; this.closed = closed; this.log = log; this.connect(); } /** * 连接 */ public void connect() { if (null != this.webSocket) { this.webSocket.cancel(); this.webSocket = null; } OKHTTP_CLIENT.newWebSocket(new Request.Builder() .url(this.url) .build(), this); } /** * 打开连接回调 */ @Override public void onOpen(WebSocket webSocket, Response response) { this.webSocket = webSocket; if (null != this.open) { this.open.run(); } } /** * 发送消息 * @param message 消息 */ public void send(String message) { if (null != this.webSocket) { this.webSocket.send(message); } } /** * 收到消息 */ @Override public void onMessage(WebSocket webSocket, ByteString bytes) { if (null != this.receive) { String message = this.decode.apply(bytes); this.receive.accept(message); } } /** * 连接正在关闭 */ @Override public void onClosing(WebSocket webSocket, int code, String reason) { super.onClosing(webSocket, code, reason); this.log.info("onClosing --> {} {} {}", webSocket, code, reason); if (null != this.closed) { this.closed.run(); } } /** * 连接关闭回调 */ @Override public void onClosed(WebSocket webSocket, int code, String reason) { super.onClosed(webSocket, code, reason); this.log.info("onClosed --> {} {} {}", webSocket, code, reason); if (null != this.closed) { this.closed.run(); } } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { super.onFailure(webSocket, t, response); t.printStackTrace(); this.log.info("onFailure --> {} {} {}", webSocket, t, response); if (null != this.closed) { this.closed.run(); } } /** * 主动断开 * @param code code * @param reason reason */ public void close(int code, String reason) { if (null != this.webSocket) { this.webSocket.close(code, reason); } } }
3,514
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
CommonUtil.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/CommonUtil.java
package cqt.goai.exchange.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeException; import cqt.goai.model.enums.Side; import cqt.goai.model.enums.State; import cqt.goai.model.enums.Type; import cqt.goai.model.market.*; import cqt.goai.model.trade.Order; import cqt.goai.model.trade.OrderDetail; import cqt.goai.model.trade.Precision; import dive.common.crypto.HexUtil; import dive.http.common.model.Parameter; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.math.BigDecimal; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import static dive.common.math.BigDecimalUtil.greater; import static dive.common.util.Util.useful; import static java.math.BigDecimal.ZERO; /** * 公共工具类 * * @author GOAi */ public class CommonUtil { public static final BigDecimal THOUSAND = new BigDecimal("1000"); private static final String ALGORITHM_SHA256 = "SHA-256"; /** * 统一获取Ticker * * @param result 原始文件 * @param r json * @param time 时间 * @param open 开 键名 * @param high 高 键名 * @param low 低 键名 * @param last 收 键名 * @param volume 量 键名 * @return Ticker */ public static Ticker parseTicker(String result, JSONObject r, Long time, String open, String high, String low, String last, String volume) { return new Ticker(result, time, getBigDecimal(r, open), getBigDecimal(r, high), getBigDecimal(r, low), getBigDecimal(r, last), getBigDecimal(r, volume)); } /** * 读取指定属性 * * @param r json * @param name 名称 * @return BigDecimal */ private static BigDecimal getBigDecimal(JSONObject r, String name) { return null != name && r.containsKey(name) ? r.getBigDecimal(name) : null; } /** * 根据序号解析Kline * * @param result 原始文件 * @param r array * @param time 时间 * @return Kline */ public static Kline parseKlineByIndex(String result, JSONArray r, Long time, int first) { BigDecimal open = r.getBigDecimal(first); BigDecimal high = r.getBigDecimal(first + 1); BigDecimal low = r.getBigDecimal(first + 2); BigDecimal close = r.getBigDecimal(first + 3); BigDecimal volume = r.getBigDecimal(first + 4); return new Kline(result, time, open, high, low, close, volume); } /** * 解析档位 * * @param result 元素数据 * @param row 数组 * @return 档位 */ public static Row parseRowByIndex(String result, JSONArray row) { BigDecimal price = row.getBigDecimal(0); BigDecimal amount = row.getBigDecimal(1); return new Row(result, price, amount); } /** * 解析rows */ public static List<Row> parseRowsByIndex(JSONArray rs) { List<Row> rows = new ArrayList<>(rs.size()); for (int i = 0, l = rs.size(); i < l; i++) { rows.add(CommonUtil.parseRowByIndex(rs.getString(i), rs.getJSONArray(i))); } return rows; } /** * 统一解析Depth * @param time 时间 * @param asks 卖盘 * @param bids 买盘 * @return Depth */ public static Depth parseDepthByIndex(Long time, JSONArray asks, JSONArray bids) { return new Depth(time, new Rows(CommonUtil.parseRowsByIndex(asks)), new Rows(CommonUtil.parseRowsByIndex(bids))); } /** * 解析档位 * * @param result 元素数据 * @param row 数组 * @return 档位 */ public static Row parseRowByKey(String result, JSONObject row) { return new Row(result, row.getBigDecimal("price"), row.getBigDecimal("amount")); } /** * 解析订单 * @param result 原始数据 * @param r json * @param time 时间 * @param side 方向 * @param type 类型 * @param state 状态 * @param idKey id键名 * @param priceKey 价格键名 * @param amountKey 数量键名 * @param dealKey 已成交数量键名 * @param averageKey 均价键名 * @return Order */ public static Order parseOrder(String result, JSONObject r, Long time, Side side, Type type, State state, String idKey, String priceKey, String amountKey, String dealKey, String averageKey) { String id = r.getString(idKey); BigDecimal price = getBigDecimal(r, priceKey); BigDecimal amount = getBigDecimal(r, amountKey); BigDecimal deal = getBigDecimal(r, dealKey); BigDecimal average = getBigDecimal(r, averageKey); if (state == State.CANCEL && null != deal && greater(deal, ZERO)) { state = State.UNDONE; } return new Order(result, time, id, side, type, state, price, amount, deal, average); } /** * 经常需要对下划线分割 * * @param content 分割内容 * @param first true 第一个_分割,false 最后一个_分割 */ public static String[] split(String content, boolean first) { if (useful(content)) { int i = first ? content.indexOf("_") : content.lastIndexOf("_"); if (0 < i) { return new String[]{content.substring(0, i), content.substring(i + 1)}; } } throw new ExchangeException("can not split content: " + content); } /** * 经常需要对下划线分割 */ public static String[] split(String content) { return CommonUtil.split(content, true); } /** * 订单排序方法 * * @param o1 o1 * @param o2 o2 * @return 排序 */ public static int sortOrder(Order o1, Order o2) { return o2.getTime().compareTo(o1.getTime()); } /** * 订单排序方法 * * @param d1 d1 * @param d2 d2 * @return 排序 */ public static int sortOrderDetail(OrderDetail d1, OrderDetail d2) { return d2.getTime().compareTo(d1.getTime()); } /** * 添加参数 * * @param parameter 参数对象 * @param others 其他内容 */ public static void addOtherParameter(Parameter parameter, Object[] others) { for (int i = 0; i < others.length; i++) { parameter.add((String) others[i], others[++i]); } } /** * 添加其他参数 * * @param parameter 参数对象 * @param others 其他内容 * @return 排序后json */ public static String addOtherParameterToJson(Parameter parameter, Object[] others) { CommonUtil.addOtherParameter(parameter, others); return parameter.sort().json(JSON::toJSONString); } /** * hmac sha384 * * @param message 信息 * @param secret 秘钥 * @return 加密结果 */ public static String hmacSha384(String message, String secret) { Exception exception = null; try { Mac mac = Mac.getInstance("HmacSHA384"); SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA384"); mac.init(secretKeySpec); return HexUtil.hexEncode(mac.doFinal(message.getBytes()), false); } catch (NoSuchAlgorithmException ignored) { } catch (InvalidKeyException e) { e.printStackTrace(); exception = e; } throw new ExchangeException("hmacSha384 error.", exception); } /** * hmac HmacSHA256 * * @param message 信息 * @param secret 秘钥 * @return 加密结果 */ public static String hmacSha256(String message, String secret) { Exception exception = null; try { Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); mac.init(secretKeySpec); return HexUtil.hexEncode(mac.doFinal(message.getBytes()), false); } catch (NoSuchAlgorithmException ignored) { } catch (InvalidKeyException e) { e.printStackTrace(); exception = e; } throw new ExchangeException("hmacSha256 error.", exception); } /** * 从深度信息解析精度 * * @param depth 深度 * @param symbol 币对 * @return 精度 */ public static Precision parsePrecisionByDepth(Depth depth, String symbol) { int base = 0; int count = 0; List<Row> rows = depth.getAsks().getList(); rows.addAll(depth.getBids().getList()); for (Row r : rows) { int c = r.getPrice().scale(); int b = r.getAmount().scale(); if (count < c) { count = c; } if (base < b) { base = b; } } return new Precision(null, symbol, base, count, null, null, null, null, null, null); } /** * 按大小分割 * @param list 列表 * @param max 最大数量 * @param <T> 基础类型 * @return 分割后流 */ public static <T> List<List<T>> split(List<T> list, int max) { List<List<T>> split = new LinkedList<>(); for (int i = 0; i < list.size() / max + 1; i++) { List<T> temp = list.stream() .skip(i * max) .limit(max) .collect(Collectors.toList()); if (!temp.isEmpty()) { split.add(temp); } } return split; } }
10,065
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BitfinexUtil.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/bitfinex/BitfinexUtil.java
package cqt.goai.exchange.util.bitfinex; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.model.enums.Period; import cqt.goai.model.enums.Side; import cqt.goai.model.enums.State; import cqt.goai.model.enums.Type; import cqt.goai.model.market.*; import cqt.goai.model.trade.Balance; import cqt.goai.model.trade.Order; import cqt.goai.model.trade.OrderDetail; import cqt.goai.model.trade.Precision; import dive.common.math.BigDecimalUtil; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static dive.common.math.BigDecimalUtil.*; /** * @author */ public class BitfinexUtil { private static final String EXCHANGE_LIMIT = "exchange limit"; private static final String EXCHANGE_MARKET = "exchange market"; private static final String EXCHANGE_FOK = "exchange fill-or-kill"; /** * bitfinex 的周期换算 * * @param period 周期 * @return 周期长度 秒 */ public static String getPeriod(Period period) { switch (period) { // '1m', '5m', '15m', '30m', '1h', '3h', '6h', '12h', '1D', '7D', '14D', '1M' case MIN1: return "1m"; // case MIN3: return "3m"; case MIN5: return "5m"; case MIN15: return "15m"; case MIN30: return "30m"; case HOUR1: return "1h"; // case HOUR2: return "2h"; case HOUR3: return "3h"; // case HOUR4: return "4h"; case HOUR6: return "6h"; case HOUR12: return "12h"; case DAY1: return "1D"; // case DAY3: return "3D"; case WEEK1: return "7D"; case WEEK2: return "14D"; case MONTH1: return "1M"; default: return null; } } /** * 统一解析Depth */ public static Depth parseDepth(JSONObject r) { Long[] time = new Long[]{0L}; List<Row> asks = BitfinexUtil.parseRows(r.getJSONArray("asks"), time); List<Row> bids = BitfinexUtil.parseRows(r.getJSONArray("bids"), time); return new Depth(time[0], new Rows(asks), new Rows(bids)); } /** * 解析rows */ private static List<Row> parseRows(JSONArray rs, Long[] time) { List<Row> rows = new ArrayList<>(rs.size()); for (int i = 0, l = rs.size(); i < l; i++) { JSONObject t = rs.getJSONObject(i); rows.add(CommonUtil.parseRowByKey(rs.getString(i), t)); Long timestamp = t.getBigDecimal("timestamp").multiply(CommonUtil.THOUSAND).longValue(); if (time[0] < timestamp) { time[0] = timestamp; } } return rows; } /** * 统一解析Trades */ public static Trades parseTrades(JSONArray r) { List<Trade> trades = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { JSONObject t = r.getJSONObject(i); /*{ "timestamp":1548042361, "tid":333729405, "price":"3584.3", "amount":"0.015", "exchange":"bitfinex", "type":"sell" },*/ Long time = t.getLong("timestamp"); String id = t.getString("tid"); Side side = Side.valueOf(t.getString("type").toUpperCase()); BigDecimal price = t.getBigDecimal("price"); BigDecimal amount = t.getBigDecimal("amount"); trades.add(new Trade(r.getString(i), time, id, side, price, amount)); } return new Trades(trades); } /** * 解析所有余额 * @param array 数组 * @return 余额列表 */ public static List<Balance> parseBalances(JSONArray array) { List<Balance> balances = new ArrayList<>(array.size()); for (int i = 0, l = array.size(); i < l; i++) { balances.add(BitfinexUtil.parseBalance(array.getString(i), array.getJSONObject(i))); } return balances; } /** * 解析单个币种余额 * * @param result 原始数据 * @param r json * @return Balance */ private static Balance parseBalance(String result, JSONObject r) { /* { "type":"exchange", "currency":"ltc", "amount":"0.11996", "available":"0.11996" } */ String coin = r.getString("currency").toUpperCase(); BigDecimal free = r.getBigDecimal("available"); BigDecimal frozen = sub(r.getBigDecimal("amount"), free); return new Balance(result, coin, free, frozen); } private static final String CANCELLED = "is_cancelled"; private static final String LIVE = "is_live"; /** * 统一解析order * @param result 原始文件 * @param o json * @return Order */ public static Order parseOrder(String result, JSONObject o) { /* { "id":21597779146, "cid":26899733859, "cid_date":"2019-01-18", "gid":null, "symbol":"ltcusd", "exchange":"bitfinex", "price":"26.0", "avg_execution_price":"0.0", "side":"buy", "type":"exchange limit", "timestamp":"1547796500.0", "is_live":true, "is_cancelled":false, "is_hidden":false, "oco_order":null, "was_forced":false, "original_amount":"0.4", "remaining_amount":"0.4", "executed_amount":"0.0", "src":"api" } */ Long time = o.getBigDecimal("timestamp").multiply(CommonUtil.THOUSAND).longValue(); String id = o.getString("id"); Side side = Side.valueOf(o.getString("side").toUpperCase()); String t = o.getString("type"); Type type = null; if (EXCHANGE_LIMIT.equals(t)) { type = Type.LIMIT; } else if (EXCHANGE_MARKET.equals(t)) { type = Type.MARKET; } else if (EXCHANGE_FOK.equals(t)) { type = Type.FILL_OR_KILL; } State state; BigDecimal price = o.getBigDecimal("price"); BigDecimal amount = o.getBigDecimal("original_amount"); BigDecimal deal = o.getBigDecimal("executed_amount"); BigDecimal average = o.getBigDecimal("avg_execution_price"); if (o.getBoolean(CANCELLED)) { state = State.CANCEL; if (greater(deal, BigDecimalUtil.ZERO)) { state = State.UNDONE; } } else if (o.getBoolean(LIVE)) { state = State.SUBMIT; if (greater(deal, BigDecimalUtil.ZERO)) { state = State.PARTIAL; } if (greaterOrEqual(deal, amount)) { state = State.FILLED; } } else { state = State.FILLED; } return new Order(result, time, id, side, type, state, price, amount, deal, average); } /** * [ * 21597693840, ID int64 Order ID * null, GID int Group ID * 26665933660, CID int Client Order ID * "tLTCUSD", SYMBOL string Pair (tBTCUSD, …) * 1547796266000, MTS_CREATE int Millisecond timestamp of creation * 1547796266000, MTS_UPDATE int Millisecond timestamp of update * 0, AMOUNT float Remaining amount. * -0.4, AMOUNT_ORIG float Original amount, positive means buy, negative means sell. * "EXCHANGE LIMIT", TYPE string The type of the order: LIMIT, MARKET, STOP, TRAILING STOP, EXCHANGE MARKET, EXCHANGE LIMIT, EXCHANGE STOP, EXCHANGE TRAILING STOP, FOK, EXCHANGE FOK. * null, TYPE_PREV string Previous order type * null, _PLACEHOLDER, * null, _PLACEHOLDER, * "0", FLAGS int Upcoming Params Object (stay tuned) * "EXECUTED @ 31.962(-0.4)", ORDER_STATUS string Order Status: ACTIVE, EXECUTED, PARTIALLY FILLED, CANCELED * null, _PLACEHOLDER, * null, _PLACEHOLDER, * 30, PRICE float Price * 31.962, PRICE_AVG float Average price * 0, PRICE_TRAILING float The trailing price * 0, PRICE_AUX_LIMIT float Auxiliary Limit price (for STOP LIMIT) * null, _PLACEHOLDER, * null, _PLACEHOLDER, * null, _PLACEHOLDER, * 0, NOTIFY int 1 if Notify flag is active, 0 if not * 0, HIDDEN int 1 if Hidden, 0 if not hidden * null, PLACED_ID int If another order caused this order to be placed (OCO) this will be that other order's ID * null, * null, * "API>BFX", * null, * null, * null * ] * @param result 原始数据 * @return 订单列表 */ public static List<Order> parseOrders(String result) { JSONArray r = JSON.parseArray(result); List<Order> orders = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { JSONArray t = r.getJSONArray(i); String data = r.getString(i); Long time = t.getLong(4); String id = t.getString(0); Side side = null; Double s = t.getDouble(7); if (0 < s) { side = Side.BUY; } else if (s < 0) { side = Side.SELL; } Type type = null; String orderType = t.getString(8); if ("EXCHANGE LIMIT".equals(orderType)) { type = Type.LIMIT; } else if ("EXCHANGE MARKET".equals(orderType)) { type = Type.MARKET; } else if ("EXCHANGE FOK".equals(orderType)) { type = Type.FILL_OR_KILL; } State state = null; String orderState = t.getString(13); if (orderState.contains("ACTIVE")) { state = State.SUBMIT; } else if (orderState.contains("EXECUTED")) { state = State.FILLED; } else if (orderState.contains("PARTIALLY FILLED")) { state = State.UNDONE; } else if (orderState.contains("CANCELED")) { state = State.CANCEL; } BigDecimal price = t.getBigDecimal(16); BigDecimal amount = t.getBigDecimal(7).abs(); BigDecimal deal = amount.subtract(t.getBigDecimal(6).abs()); BigDecimal average = t.getBigDecimal(17); if (state == State.SUBMIT && greater(deal, BigDecimal.ZERO)) { state = State.PARTIAL; } if (state == State.CANCEL && greater(deal, BigDecimal.ZERO)) { state = State.UNDONE; } orders.add(new Order(data, time, id, side, type, state, price, amount, deal, average)); } return orders; } /** * 解析订单详情 * [ * 333168795, ID integer Trade database id * "tLTCUSD", PAIR string Pair (BTCUSD, …) * 1547796266000, MTS_CREATE integer Execution timestamp * 21597693840, ORDER_ID integer Order id * -0.4, EXEC_AMOUNT float Positive means buy, negative means sell * 31.962, EXEC_PRICE float Execution price * null, _PLACEHOLDER, * null, _PLACEHOLDER, * -1, MAKER int 1 if true, -1 if false * -0.0255696, FEE float Fee * "USD" FEE_CURRENCY string Fee currency * ] * @param result 元素数据 * @return 订单详情列表 */ public static List<OrderDetail> parseOrderDetails(String result) { JSONArray r = JSON.parseArray(result); List<OrderDetail> details = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { JSONArray t = r.getJSONArray(i); String data = r.getString(i); Long time = t.getLong(2); String orderId = t.getString(3); String detailId = t.getString(0); BigDecimal price = t.getBigDecimal(5); BigDecimal amount = t.getBigDecimal(4).abs(); BigDecimal fee = t.getBigDecimal(9).abs(); String feeCurrency = t.getString(10); details.add(new OrderDetail(data, time, orderId, detailId, price, amount, fee, feeCurrency)); } return details; } /** * 解析币对精度信息 * @param result 原始数据 * @return 精度列表 */ public static List<Precision> parsePrecisions(String result) { JSONArray r = JSON.parseArray(result); List<Precision> precisions = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { /* * { * "pair":"vsyusd", * "price_precision":5, * "initial_margin":"30.0", * "minimum_margin":"15.0", * "maximum_order_size":"50000.0", * "minimum_order_size":"0.001", * "expiration":"NA", * "margin":false * } * "pair":"btcusd", "price_precision":5, "initial_margin":"30.0", "minimum_margin":"15.0", "maximum_order_size":"2000.0", "minimum_order_size":"0.004", "expiration":"NA", "margin":true */ JSONObject t = r.getJSONObject(i); String data = r.getString(i); String symbol = new StringBuilder(t.getString("pair").toUpperCase()) .insert(3, "_").toString(); // Integer base = null; Integer count = t.getInteger("price_precision"); // BigDecimal baseStep = null; // BigDecimal countStep = null; BigDecimal minBase = t.getBigDecimal("minimum_order_size"); // BigDecimal minCount = null; BigDecimal maxBase = t.getBigDecimal("maximum_order_size"); // BigDecimal maxCount = null; precisions.add(new Precision(data, symbol, null, count, null, null, minBase, null, maxBase, null)); } return precisions; } }
14,996
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Okexv3Util.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/okexv3/Okexv3Util.java
package cqt.goai.exchange.util.okexv3; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.model.enums.Period; import cqt.goai.model.enums.Side; import cqt.goai.model.enums.State; import cqt.goai.model.enums.Type; import cqt.goai.model.market.*; import cqt.goai.model.trade.Balance; import cqt.goai.model.trade.Order; import cqt.goai.model.trade.Orders; import okio.ByteString; import org.apache.commons.compress.compressors.deflate64.Deflate64CompressorInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import static dive.common.math.BigDecimalUtil.div; import static dive.common.math.BigDecimalUtil.greater; import static java.math.BigDecimal.ZERO; /** * @author GOAi */ public class Okexv3Util { /** * okexv3 的周期换算 * @param period 周期 * @return 周期长度 秒 */ public static Integer getPeriod(Period period) { switch (period) { case MIN1: case MIN3: case MIN5: case MIN15: case MIN30: case HOUR1: case HOUR2: // case HOUR3 : return 7200; case HOUR4: case HOUR6: case HOUR12: case DAY1: // case DAY3 : return 604800; case WEEK1: return period.getValue(); // case WEEK2 : return 604800; // case MONTH1 : return 604800; default: return null; } } /** * http 和 ws 解析方式相同 * @param result 原始文件 * @param r json * @return Ticker */ public static Ticker parseTicker(String result, JSONObject r) { /* { * "instrument_id":"ETH-USDT", * "last":"131.6299", * "best_bid":"131.6299", * "best_ask":"131.6857", * "open_24h":"149.8823", * "high_24h":"150.5", * "low_24h":"130.9743", * "base_volume_24h":"879069.0066515", * "quote_volume_24h":"124634731.57238156", * "timestamp":"2019-01-10T09:26:55.932Z" * } */ Long time = r.getDate("timestamp").getTime(); BigDecimal open = r.getBigDecimal("open_24h"); BigDecimal high = r.getBigDecimal("high_24h"); BigDecimal low = r.getBigDecimal("low_24h"); BigDecimal last = r.getBigDecimal("last"); BigDecimal volume = r.getBigDecimal("base_volume_24h"); return new Ticker(result, time, open, high, low, last, volume); } /** * ws 解析方式 * @param result 原始文件 * @param r json * @return Kline */ public static Kline parseKline(String result, JSONArray r) { /* {"candle": * ["2019-01-15T09:51:00.000Z", * "3594.0579", * "3595.5917", * "3593.9239", * "3595.5917", * "19.24375778"], * "instrument_id":"BTC-USDT"} */ Long time = r.getDate(0).getTime() / 1000; return CommonUtil.parseKlineByIndex(result, r, time, 1); } /** * 统一解析Depth */ public static Depth parseDepth(JSONObject r) { Long time = r.getDate("timestamp").getTime(); return CommonUtil.parseDepthByIndex(time, r.getJSONArray("asks"), r.getJSONArray("bids")); } /** * 统一解析Trades */ public static Trades parseTrades(JSONArray r) { List<Trade> trades = new ArrayList<>(r.size()); for (int i = 0, l = r.size(); i < l; i++) { /* * [ * { * "time":"2019-01-11T14:02:02.536Z", * "timestamp":"2019-01-11T14:02:02.536Z", * "trade_id":"861471459", * "price":"3578.8482", * "size":"0.0394402", * "side":"sell" * }, */ JSONObject t = r.getJSONObject(i); Long time = t.getDate("timestamp").getTime(); String id = t.getString("trade_id"); Side side = Side.valueOf(t.getString("side").toUpperCase()); BigDecimal price = t.getBigDecimal("price"); BigDecimal amount = t.getBigDecimal("size"); Trade trade = new Trade(r.getString(i), time, id, side, price, amount); trades.add(trade); } return new Trades(trades.stream() .sorted((t1, t2) -> t2.getTime().compareTo(t1.getTime())) .collect(Collectors.toList())); } /** * 解析单个币种余额 * * @param result 原始数据 * @param r json * @return Balance */ public static Balance parseBalance(String result, JSONObject r) { /* * { * "frozen":"0", * "hold":"0", * "id":"6278097", * "currency":"USDT", * "balance":"127.613453580677953", * "available":"127.613453580677953", * "holds":"0" * } */ return new Balance(result, r.getString("currency"), r.getBigDecimal("available"), r.getBigDecimal("hold")); } /** * 解析Order * @param result 原始数据 * @param t json * @return Order */ public static Order parseOrder(String result, JSONObject t) { /* * { * "order_id": "125678", * "notional": "12.4", * "price": "0.10000000", * "size": "0.01000000", * "instrument_id": "BTC-USDT", * "side": "buy", * "type": "limit", * "timestamp": "2016-12-08T20:02:28.538Z", * "filled_size": "0.00000000", * "filled_notional": "0.0000000000000000", * "status": "open" * } */ Long time = t.getDate("timestamp").getTime(); String id = t.getString("order_id"); Side side = Side.valueOf(t.getString("side").toUpperCase()); Type type = Type.valueOf(t.getString("type").toUpperCase()); State state = null; switch (t.getString("status")) { case "open": state = State.SUBMIT; break; case "part_filled": state = State.PARTIAL; break; case "canceling": state = State.CANCEL; break; case "filled": state = State.FILLED; break; case "cancelled": state = State.CANCEL; break; case "failure": state = State.CANCEL; break; case "ordering": state = State.SUBMIT; break; default: } BigDecimal price = t.getBigDecimal("price"); BigDecimal amount = t.getBigDecimal("size"); BigDecimal deal = t.getBigDecimal("filled_size"); BigDecimal average = ZERO; if (greater(deal, ZERO)) { average = div(t.getBigDecimal("filled_notional"), deal, 8, RoundingMode.HALF_UP); if (State.CANCEL.equals(state)) { state = State.UNDONE; } } return new Order(result, time, id, side, type, state, price, amount, deal, average); } /** * 统一解析orders * @param r json * @return orders */ public static Orders parseOrders(JSONArray r) { List<Order> orders = new LinkedList<>(); for (int i = 0; i< r.size(); i++) { orders.add(Okexv3Util.parseOrder(r.getString(i), r.getJSONObject(i))); } return new Orders(orders); } /** * WebSocket解压缩函数 * @param bytes 压缩字符串 * @return 解压缩后结果 */ public static String uncompress(ByteString bytes) { try (final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayInputStream in = new ByteArrayInputStream(bytes.toByteArray()); final Deflate64CompressorInputStream zin = new Deflate64CompressorInputStream(in)) { final byte[] buffer = new byte[1024]; int offset; while (-1 != (offset = zin.read(buffer))) { out.write(buffer, 0, offset); } return out.toString(); } catch (final IOException e) { throw new RuntimeException(e); } } }
8,805
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
HoubiProUtil.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/exchange/src/main/java/cqt/goai/exchange/util/huobi/pro/HoubiProUtil.java
package cqt.goai.exchange.util.huobi.pro; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.model.enums.Period; import cqt.goai.model.enums.Side; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import lombok.extern.slf4j.Slf4j; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author GOAi */ @Slf4j public class HoubiProUtil { private static final String OK = "ok"; private static final String STATUS = "status"; private static final String DATA = "data"; /** * 解析Ticker * { * "status":"ok", * "ch":"market.btcusdt.detail.merged", * "ts":1549000056454, * "tick":{ * "amount":15726.99857982195, * "open":3465.23, * "close":3420, * "high":3479.57, * "id":100158976057, * "count":155478, * "low":3402.52, * "version":100158976057, * "ask":[ * 3420, * 16.61527792397661 * ], * "vol":53984154.95959691, * "bid":[ * 3419.99, * 2.9407 * ] * } * } * @param result 原始数据 * @return Ticker */ public static Ticker parseTicker(String result) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { Long time = r.getLong("ts"); return CommonUtil.parseTicker(result, r.getJSONObject("tick"), time, "open", "high", "low", "close", "amount"); } return null; } /** * 火币 的周期换算 * * @param period 周期 * @return 周期长度 秒 */ public static String getPeriod(Period period) { switch (period) { case MIN1: return "1min"; // case MIN3: return "3min"; case MIN5: return "5min"; case MIN15: return "15min"; case MIN30: return "30min"; case HOUR1: return "60min"; // case HOUR2: return "2hour"; // case HOUR3: return "3hour"; // case HOUR4: return "4hour"; // case HOUR6: return "6hour"; // case HOUR12: return "12hour"; case DAY1: return "1day"; // case DAY3: return "3day"; case WEEK1: return "1week"; // case WEEK2: return "2week"; case MONTH1: return "1mon"; default: return null; } } /** * 解析 K线 * { * "id":1549000800, * "open":3418.43, * "close":3418.44, * "low":3418.43, * "high":3418.44, * "amount":0.33941184633926585, * "vol":1160.258958, * "count":11 * } * @param result 原始数据 * @return Klines */ public static Klines parseKlines(String result) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray data = r.getJSONArray(DATA); List<Kline> klines = new ArrayList<>(data.size()); for (int i = 0; i < data.size(); i++) { JSONObject t = data.getJSONObject(i); Long time = t.getLong("id"); BigDecimal open = t.getBigDecimal("open"); BigDecimal high = t.getBigDecimal("high"); BigDecimal low = t.getBigDecimal("low"); BigDecimal close = t.getBigDecimal("close"); BigDecimal volume = t.getBigDecimal("amount"); klines.add(new Kline(data.getString(i), time, open, high, low, close, volume)); } return new Klines(klines); } return null; } /** * 解析 深度 * { * "status":"ok", * "ch":"market.btcusdt.depth.step0", * "ts":1549001152532, * "tick":{ * "bids":[ * [ * 3415.41, * 0.0183 * ], ... * ], * "asks":[ * [ * 3415.96, * 0.0542 * ], ... * ], * "ts":1549001152017, * "version":100159087527 * } * } * @param result 原始数据 * @return Depth */ public static Depth parseDepth(String result) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONObject tick = r.getJSONObject("tick"); Long time = tick.getLong("ts"); return CommonUtil.parseDepthByIndex(time, tick.getJSONArray("asks"), tick.getJSONArray("bids")); } return null; } /** * 解析 行情 * * @param result 原始数据 * @return Trades */ public static Trades parseTrades(String result) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray data = r.getJSONArray(DATA); List<Trade> trades = new ArrayList<>(data.size()); for (int i = 0; i < data.size(); i++) { JSONObject t = data.getJSONObject(i).getJSONArray(DATA).getJSONObject(0); /* * { * "id":100159178954, * "ts":1549002100105, * "data":[ * { * "amount":0.009000000000000000, * "ts":1549002100105, * "id":10015917895423497145394, * "price":3414.610000000000000000, * "direction":"buy" * } * ] * } */ Long time = t.getLong("ts"); String id = t.getString("id"); Side side = Side.valueOf(t.getString("direction").toUpperCase()); BigDecimal price = t.getBigDecimal("price"); BigDecimal amount = t.getBigDecimal("amount"); Trade trade = new Trade(data.getJSONObject(i).getString(DATA), time, id, side, price, amount); trades.add(trade); } return new Trades(trades); } return null; } /** * 解析所有币的余额 * * @param result 原始数据 * @return Balances */ public static Balances parseBalances(String result) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray list = r.getJSONObject("data").getJSONArray("list"); int size = list.size() / 2; List<Balance> balances = new ArrayList<>(size); Map<String, JSONObject> free = new HashMap<>(size); Map<String, JSONObject> frozen = new HashMap<>(size); for (int i = 0; i < list.size(); i++) { JSONObject t = list.getJSONObject(i); String coin = t.getString("currency").toUpperCase(); String type = t.getString("type"); if ("trade".equals(type)) { free.put(coin, t); } else if ("frozen".equals(type)) { frozen.put(coin, t); } } for (String coin : free.keySet()) { JSONObject f1 = free.get(coin); JSONObject f2 = frozen.get(coin); balances.add(new Balance("[" + f1.toJSONString() + "," + f2.toJSONString() + "]", coin, f1.getBigDecimal("balance"), f2.getBigDecimal("balance"))); } return new Balances(balances); } return null; } /** * 解析 币对余额 * 单独写 不用解析所有的币了 * @param result 原始数据 * @param symbol 币对 * @return Account */ public static Account parseAccount(String result, String symbol) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray list = r.getJSONObject("data").getJSONArray("list"); JSONObject freeBase = null; JSONObject frozenBase = null; JSONObject freeCount = null; JSONObject frozenCount = null; String[] symbols = symbol.split("_"); String base = symbols[0].toLowerCase(); String count = symbols[1].toLowerCase(); for (int i = 0; i < list.size(); i++) { JSONObject t = list.getJSONObject(i); String coin = t.getString("currency"); String type = t.getString("type"); if (base.equals(coin)) { if ("trade".equals(type)) { freeBase = t; } else if ("frozen".equals(type)) { frozenBase = t; } } else if (count.equals(coin)) { if ("trade".equals(type)) { freeCount = t; } else if ("frozen".equals(type)) { frozenCount = t; } } } if (null != freeBase && null != frozenBase && null != freeCount && null != frozenCount) { return new Account(System.currentTimeMillis(), new Balance("[" + freeBase.toJSONString() + "," + frozenBase.toJSONString() + "]", base.toUpperCase(), freeBase.getBigDecimal("balance"), frozenBase.getBigDecimal("balance")), new Balance("[" + freeCount.toJSONString() + "," + frozenCount.toJSONString() + "]", count.toUpperCase(), freeCount.getBigDecimal("balance"), frozenCount.getBigDecimal("balance"))); } } return null; } /** * 解析 精度 * * @param result 原始信息 * @return 解析结果 */ public static Precisions parsePrecisions(String result) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray data = r.getJSONArray(DATA); List<Precision> precisions = new ArrayList<>(data.size()); for (int i = 0; i < data.size(); i++) { JSONObject t = data.getJSONObject(i); String symbol = t.getString("base-currency") + "_" + t.getString("quote-currency"); symbol = symbol.toUpperCase(); Integer base = t.getInteger("amount-precision"); Integer count = t.getInteger("price-precision"); Precision precision = new Precision(data.getString(i), symbol, base, count, null, null, null, null, null, null); precisions.add(precision); } return new Precisions(precisions); } return null; } /** * 解析单个精度 * @param result 请求结果 * @param symbol 解析币对 * @return 精度 */ public static Precision parsePrecision(String result, String symbol) { JSONObject r = JSON.parseObject(result); if (OK.equals(r.getString(STATUS))) { JSONArray data = r.getJSONArray(DATA); for (int i = 0; i < data.size(); i++) { JSONObject t = data.getJSONObject(i); if (symbol.equalsIgnoreCase(t.getString("symbol"))) { symbol = t.getString("base-currency") + "_" + t.getString("quote-currency"); symbol = symbol.toUpperCase(); Integer base = t.getInteger("amount-precision"); Integer count = t.getInteger("price-precision"); return new Precision(data.getString(i), symbol, base, count, null, null, null, null, null, null); } } } return null; } }
12,438
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Application.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/Application.java
package cqt.goai.run; import cqt.goai.run.main.Minister; /** * 启动类 * * @author GOAi */ public class Application { /** * 主启动函数 * @param args 启动参数 */ public static void main(String[] args) { Minister.run(args); } }
280
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
RunTask.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/RunTask.java
package cqt.goai.run.main; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Klines; import cqt.goai.model.market.Ticker; import cqt.goai.model.market.Trades; import cqt.goai.model.trade.Account; import cqt.goai.model.trade.Orders; import cqt.goai.run.exchange.Exchange; import cqt.goai.run.notice.BaseNotice; import cqt.goai.run.notice.Notice; import dive.cache.mime.PersistCache; import dive.common.util.DateUtil; import dive.common.util.TryUtil; import org.slf4j.Logger; import java.io.*; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; /** * 抽象任务类 * * @author GOAi */ public class RunTask { /** * 是否准备好推送,init方法结束后设置为true */ private Boolean ready = false; /** * 准备好了才推送 */ final Supplier<Boolean> isReady = () -> this.ready; /** * 原始日志工具 */ private Logger originLog; /** * 用户日志 */ protected Logger log; /** * 通知对象 */ protected Notice notice; /** * 配置名称 */ protected String strategyName; /** * 本实例id */ protected Integer id; /** * 本实例配置 */ protected JSONObject config; /** * 默认e */ protected Exchange e; /** * 获取exchange 参数为json字符串 * {"name":"xxx","symbol":"BTC_USD","access":"xxx","secret":"xxx"} */ protected Function<String, Exchange> getExchange; public RunTask() {} /** * 初始化设置 * @param strategyName 配置名称 * @param id 实例id * @param config 实例配置 */ void init(String strategyName, Integer id, JSONObject config, Logger log, List<BaseNotice> notices) { this.originLog = log; this.log = new UserLogger(log); this.notice = new Notice(log, notices); this.strategyName = strategyName; this.id = id; this.config = config; } /** * 初始化方法 */ protected void init() {} /** * 默认循环 */ protected void loop() {} /** * 退出方法 */ protected void destroy() {} /** * 重写该方法,可自动对e进行主动推送Ticker * @param ticker 主动推送的ticker */ protected void onTicker(Ticker ticker) { } /** * 重写该方法,可自动对e进行主动推送Klines * K线是1分钟K线,100个 * @param klines K线 */ protected void onKlines(Klines klines) { } /** * 重写该方法,可自动对e进行主动推送Depth * @param depth 盘口深度 */ protected void onDepth(Depth depth) { } /** * 重写该方法,可自动对e进行主动推送Trades * @param trades 交易信息 */ protected void onTrades(Trades trades) { } /** * 重写该方法,可自动对e进行主动推送币对余额 * @param account 币对余额 */ protected void onAccount(Account account) { } /** * 重写该方法,可自动对e进行主动推送Orders * @param orders 订单信息 */ protected void onOrders(Orders orders) { } void setGetExchange(Function<String, Exchange> getExchange) { this.getExchange = getExchange; } /** * 睡眠一段时间 * @param millis 毫秒 */ protected void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 重试获取 * @param supplier 获取函数 * @param times 次数 * @param millis 失败暂停时间 * @param <T> 结果对象 * @return 结果 */ protected <T> T retry(Supplier<T> supplier, int times, long millis) { return TryUtil.retry(supplier, times, () -> this.sleep(millis)); } /** * 重试获取 * @param supplier 获取函数 * @param times 次数 * @param <T> 结果对象 * @return 结果 */ protected <T> T retry(Supplier<T> supplier, int times) { return retry(supplier, times, 3000); } /** * 重试获取 * @param supplier 获取函数 * @param <T> 结果对象 * @return 结果 */ protected <T> T retry(Supplier<T> supplier) { return retry(supplier, 5, 1000); } // ============================ /** * 全局持久化 */ private static final PersistCache<String, Serializable> PERSIST_CACHE = new PersistCache<>(".global"); /** * 全局保存 * @param key 键 * @param value 值 */ protected void global(String key, Serializable value) { PERSIST_CACHE.set(key, value); } /** * 读取值 * @param key 键 * @param <T> 值类型 * @return 读取的值 */ @SuppressWarnings("unchecked") protected <T> T global(String key) { return (T) PERSIST_CACHE.get(key); } /** * 持久化缓存 */ private PersistCache<String, Serializable> persistCache; /** * 初始化缓存 */ private void initPersistCache() { if (null == this.persistCache) { synchronized (this) { if (null == this.persistCache) { this.persistCache = new PersistCache<>(".global_" + id); } } } } /** * 实例内保存 * @param key 键 * @param value 值 */ protected void store(String key, Serializable value) { this.initPersistCache(); this.persistCache.set(key, value); } /** * 读取值 * @param key 键 * @param <T> 值类型 * @return 读取的值 */ @SuppressWarnings("unchecked") protected <T> T store(String key) { this.initPersistCache(); return (T) this.persistCache.get(key); } /** * 实时信息保存路径 */ private static final String PATH_REALTIME = ".realtime"; static { File file = new File(PATH_REALTIME); if (!file.exists()) { boolean result = file.mkdir(); if (!result) { throw new RuntimeException("can not create dir: " + PATH_REALTIME); } } } /** * 存储实时信息 * @param key 键 * @param value 值 */ protected void show(String key, Object value) { String message = JSON.toJSONString(value); File file = new File(PATH_REALTIME + "/" + key); if (!file.exists()) { try { boolean result = file.createNewFile(); if (!result) { throw new RuntimeException("can not create file: " + file.getPath()); } } catch (IOException e1) { e1.printStackTrace(); } } FileOutputStream os = null; try { os = new FileOutputStream(file, false); os.write(message.getBytes()); } catch (IOException e1) { e1.printStackTrace(); } finally { if (null != os) { try { os.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } /** * 默认值保存的实时信息 * @param value 值 */ protected void show(String value) { Map<String, String> map = new HashMap<>(2); map.put("type", "string"); map.put("value", value); this.show(".default", map); } /** * 默认值保存的实时表格信息 * @param comment 描述信息 * @param headers 表头 * @param lists 每一行 */ protected void show(String comment, List<String> headers, List<Object>... lists) { Map<String, Object> map = new HashMap<>(4); map.put("type", "table"); map.put("comment", comment); map.put("header", headers); map.put("value", lists); this.show(".default", map); } /** * 输出盈利的时间序列数据 * @param profit 盈利 */ protected void profit(double profit) { String date = DateUtil.formatISO8601(new Date()); String p = String.format("%8.8f", profit); String message = date + " " + p; this.originLog.info("PROFIT {}", message); File file = new File(".profit"); try (FileWriter fw = new FileWriter(file, true)){ fw.write(message + "\n"); } catch (IOException e) { e.printStackTrace(); } } }
8,866
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Minister.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/Minister.java
package cqt.goai.run.main; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; import ch.qos.logback.core.util.OptionHelper; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeException; import cqt.goai.exchange.ExchangeUtil; import cqt.goai.model.other.RunInfo; import cqt.goai.model.other.RunState; import cqt.goai.run.Application; import cqt.goai.run.annotation.Scheduled; import cqt.goai.run.annotation.ScheduledScope; import cqt.goai.run.notice.BaseNotice; import cqt.goai.run.notice.EmailNotice; import cqt.goai.run.notice.TelegramNotice; import dive.common.crypto.AESUtil; import dive.common.crypto.DHUtil; import dive.http.common.MimeRequest; import dive.http.common.model.Parameter; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; import static cqt.goai.run.main.Const.DEFAULT_SCHEDULED_METHOD; import static cqt.goai.run.main.Const.LEFT_SQUARE_BRACKETS; import static dive.common.util.Util.exist; import static dive.common.util.Util.useful; /** * 管理类 * * @author GOAi */ @Slf4j public class Minister { /** * 单例 * Singleton Pattern 单例模式 * 只需要一个对象管理所有的配置和运行实例即可 */ private static Minister instance; /** * 所有程序运行相关信息 */ private final Secretary secretary = new Secretary(); /** * 所有配置信息 * @author GOAi */ private class Secretary { /** * 标识系统状态,初始正在启动 */ RunInfo runInfo = new RunInfo(System.currentTimeMillis(), RunState.STARTING); /** * 策略名称 */ String strategyName = ""; /** * 运行类名 */ String className = null; /** * 是否以debug模式启动 */ Boolean debug = false; /** * 多个实例配置 */ Map<Integer, JSONObject> configs = new HashMap<>(); /** * 运行类 */ Class<?> taskClass = null; /** * 运行类中需要定时任务的方法 */ List<MethodInfo> methods = new LinkedList<>(); /** * 多个运行实例 */ ConcurrentHashMap<Integer, TaskManager> managers = new ConcurrentHashMap<>(); /** * 是否初始化完毕 */ boolean ready = false; private List<BaseNotice> notices; } private Minister() {} // 私有构造器 /** * 获取单例 */ static Minister getInstance() { if (null == instance) { synchronized (Minister.class) { if (null == instance) { instance = new Minister(); } } } return instance; } boolean isDebug() { return this.secretary.debug; } /** * 运行入口 * @param args 启动参数 */ public static void run(String[] args) { Minister.pid(); Minister minister = getInstance(); // 处理配置 minister.config(args); try { minister.run(); // 运行 } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); minister.secretary.runInfo.setRunState(RunState.ERROR); minister.secretary.runInfo.setEndTime(System.currentTimeMillis()); minister.updateRunInfo(minister.secretary.runInfo); System.exit(-1); } } /** * 获取配置信息 2种获取配置的方式 * 1. args中的url参数 * 例: --url=http://localhost:7758/config?token=token * 若配置--url表明从node请求获取配置信息 * 2. 指定配置文件 * 例: --name=/data/my_config.yml --> 全路径 * --name=my_config.yml --> 相对路径 运行jar同目录下的my_config.yml文件 * 若jar同目录下无该文件,则从resources获取 * 默认文件名为config.yml * @param args 启动参数 */ private void config(String[] args) { this.updateRunInfo(this.secretary.runInfo); // 尝试从网络获取配置 JSONObject config = this.getConfigByUrl(args); if (!exist(config)) { // 从本地获取配置 config = this.getConfigByLocal(args); } if (null != config) { this.config(config); } else { String message = "config can not be null"; log.error(message); throw new ExchangeException(message); } } /** * 尝试从网络获取配置 */ private JSONObject getConfigByUrl(String[] args) { // 若存在--url参数,从node处获取config for (String arg : args) { if (arg.startsWith(Const.START_URL)) { String url = arg.substring(6); log.info("config url --> {}", url); String[] keys = DHUtil.dhKeyToBase64(); String pk = keys[0]; log.info("response config pk --> {}", pk); String response = MimeRequest.builder() .url(url) .post() .body(Parameter.build("pk", pk).json(JSON::toJSONString)) .execute(ExchangeUtil.OKHTTP); if (!exist(response)) { log.info("response data empty"); return new JSONObject(); } JSONObject json = JSONObject.parseObject(response); if(json.getInteger("code") != 200){ log.info("response data error ---> {}", response); return new JSONObject(); } String pubKey = Util.getParamByUrl(url, "key"); pubKey = new String(Base64.getDecoder().decode(pubKey)); String configs = AESUtil.aesDecryptByBase64(json.getString("data"), DHUtil.aesKeyToBase64(pubKey, keys[1])); if (json.containsKey("run_mode") && "debug".equals(json.getString("run_mode"))) { log.info("configs -> {}", configs); } if (new File("debug").exists()) { log.info("configs -> {}", configs); } return JSON.parseObject(configs); } } return null; } /** * 从本地文件获取配置 */ private JSONObject getConfigByLocal(String[] args) { // 默认配置文件名 String name = "config.yml"; // 若存在--name参数,更新配置文件名 for (String arg : args) { if (arg.startsWith("--name=")) { name = arg.substring(7); log.info("config name change to: {}", name); break; } } log.info("load config from local"); // 查找同目录下config.yml文件 File file = new File(name); if (file.isAbsolute()) { // 若是绝对路径直接用 log.info("load file by --name: {}", name); } else { // 获取运行路径 String path = Application.class.getProtectionDomain() .getCodeSource().getLocation().getPath(); final String split = "/"; if (!path.endsWith(split)) { path = path.substring(0, path.lastIndexOf(split)) + split; } if (new File(path + name).exists()) { log.info("load file {} : {}", name, path + name); // 全路径 name = path + name; file = new File(name); } else { // 调用resource下config文件 log.info("load file {} from resources", name); } } Map map; try { if (file.isAbsolute()) { map = new Yaml().load(new FileInputStream(file)); } else { map = new Yaml().load( Application.class.getClassLoader().getResourceAsStream(name)); } } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); String message = String.format("load file %s failed.", name); throw new RuntimeException(message); } return JSON.parseObject(JSON.toJSONString(map)); } /** * 处理配置文件 * @param config 配置文件 */ private void config(JSONObject config) { // 统一处理配置文件 // 获取简单的配置 this.configSimple(config); this.configNotices(config); // 获取每个实例的运行配置 this.configs(config); } /** * 获取并设置简单的配置 */ private void configSimple(JSONObject config) { String strategyName = config.getString(Const.CONFIG_STRATEGY_NAME); if (useful(strategyName)) { this.secretary.strategyName = strategyName; log.info("strategy name --> {}", strategyName); } else { throw new ExchangeException("config '" + Const.CONFIG_STRATEGY_NAME + "' can not be null"); } String className = config.getString(Const.CONFIG_CLASS_NAME); if (useful(className)) { this.secretary.className = className; log.info("task class name --> {}", className); } else { throw new ExchangeException("config '" + Const.CONFIG_CLASS_NAME + "' can not be null"); } if (config.containsKey(Const.CONFIG_RUN_MODE) && "debug".equalsIgnoreCase(config.getString(Const.CONFIG_RUN_MODE))) { this.secretary.debug = true; log.info("config run mode --> {}", config.getString(Const.CONFIG_RUN_MODE)); } } /** * 获取通知配置 * @param config 配置 */ private void configNotices(JSONObject config) { this.secretary.notices = new LinkedList<>(); if (config.containsKey("notices")) { JSONArray ns = config.getJSONArray("notices"); for (int i = 0; i < ns.size(); i++) { JSONObject c = ns.getJSONObject(i); switch (c.getString("type")) { case "email" : this.secretary.notices.add(new EmailNotice(log, this.secretary.strategyName, c)); break; case "telegram" : this.secretary.notices.add(new TelegramNotice(log, this.secretary.strategyName, c)); break; default: } } } } /** * 获取并配置每个配置实例 */ private void configs(JSONObject config) { String tempConfigs = config.getString(Const.CONFIG_CONFIGS); if (tempConfigs.startsWith(LEFT_SQUARE_BRACKETS)) { JSONArray configs = config.getJSONArray(Const.CONFIG_CONFIGS); if (null == configs) { throw new ExchangeException("configs in config can not be null"); } for (int i = 0; i < configs.size(); i++) { JSONObject c = configs.getJSONObject(i); Integer id = c.getInteger("id"); if (null == id) { log.error("can not mapping config, there is no id: {}", c); continue; } if (id < 1) { log.error("can not mapping config, id can not less then 1", c); continue; } if (0 == i) { this.getNotices(c); } this.secretary.configs.put(id, c); } } else { Integer id = 1; JSONObject c = config.getJSONObject(Const.CONFIG_CONFIGS); this.getNotices(c); this.secretary.configs.put(id, c); } log.info("config init configs size --> {}", this.secretary.configs.size()); } /** * 兼容以前的配置 * @param config 配置 */ private void getNotices(JSONObject config) { if (config.containsKey("telegramGroup")) { JSONObject c = new JSONObject(); c.put("token", config.getString("telegramToken")); c.put("chatId", config.getString("telegramGroup")); this.secretary.notices.add(new TelegramNotice(log, this.secretary.strategyName,c)); } } /** * 运行程序 */ private void run() { // 获取任务类信息 Class<?> taskClass; try { taskClass = Class.forName(this.secretary.className); } catch (Exception e) { throw new ExchangeException("can not find(load) class: " + this.secretary.className); } // 测试实例化对象和是否为RunTask子类 try { Object test = taskClass.newInstance(); if (!(test instanceof RunTask)) { String message = "task class must extends RunTask: " + this.secretary.className; throw new ExchangeException(message); } } catch (InstantiationException | IllegalAccessException e) { throw new ExchangeException( "class must has public non-parameter constructor: " + this.secretary.className); } this.secretary.taskClass = taskClass; // 检查定时任务 this.checkSchedules(taskClass); this.checkSchedules(RunTask.class); this.checkLoop(); // 启动任务 this.secretary.configs.forEach(this::checkTask); log.info("start successful. instance size: {}", this.secretary.managers.size()); this.updateRunInfo(this.secretary.runInfo.setRunState(RunState.STARTED)); this.secretary.ready = true; ScheduledExecutorService running = new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutor.DiscardPolicy()); //这个定时任务,让程序不停止,否则,没有运行实例定时任务,程序就会结束 running.scheduleAtFixedRate(this::checkManagers, 0, 1, TimeUnit.MINUTES); // 关闭程序回调 Runtime.getRuntime().addShutdownHook(new Thread( () -> { // 修改状态 -> 停止中 this.updateRunInfo(this.secretary.runInfo.setRunState(RunState.STOPPING)); // 调用正在运行任务的停止方法 this.secretary.managers.values() .parallelStream().forEach(TaskManager::destroy); // 修改状态 -> 已停止 this.updateRunInfo(this.secretary.runInfo.setRunState(RunState.STOPPED)); running.shutdown(); })); } /** * 把定时任务检索出来 */ private void checkSchedules(Class<?> clazz) { Method[] methods = clazz.getDeclaredMethods(); for (Method m : methods) { if (m.getName().equals(DEFAULT_SCHEDULED_METHOD)) { continue; } Scheduled[] schedules = m.getAnnotationsByType(Scheduled.class); if (exist(schedules) && 0 < schedules.length) { m.setAccessible(true); List<ScheduledInfo> sis = new ArrayList<>(schedules.length); for (Scheduled s : schedules) { sis.add(new ScheduledInfo(s.cron(), s.fixedRate(), s.delay())); } if (!sis.isEmpty()) { ScheduledScope scheduledScope = m.getAnnotation(ScheduledScope.class); this.secretary.methods.add(new MethodInfo(m, null == scheduledScope ? MethodScope.INSTANCE : scheduledScope.value(), sis)); } } } } /** * 检查默认循环任务 */ private void checkLoop() { if (this.secretary.configs.isEmpty()) { return; } try { Method method = this.secretary.taskClass .getDeclaredMethod(DEFAULT_SCHEDULED_METHOD); ScheduledScope scheduledScope = method.getAnnotation(ScheduledScope.class); method.setAccessible(true); this.secretary.methods.add(new MethodInfo(method, null == scheduledScope ? MethodScope.INSTANCE : scheduledScope.value(), Collections.singletonList(new ScheduledInfo(null, 1000, 1000)))); } catch (NoSuchMethodException ignored) { } } /** * 启动一个实例 * @param id 配置id * @param config 配置 */ private void checkTask(Integer id, JSONObject config) { ConcurrentHashMap<Integer, TaskManager> managers = this.secretary.managers; if (id < 0) { id = -id; // 停止指定任务 if (managers.containsKey(id)) { managers.get(id).destroy(); managers.remove(id); } return; } TaskManager manager = managers.get(id); if (exist(manager)) { // 如果已经有这个实例了,就关闭 manager.destroy(); } try { RunTask runTask = (RunTask) this.secretary.taskClass.newInstance(); // 统一的配置从这里设置 Logger log = this.initLog(id); runTask.init(this.secretary.strategyName, id, config, log, this.secretary.notices); manager = new TaskManager(id, runTask, log, this.secretary.methods.stream().map(MethodInfo::copy).collect(Collectors.toList()), this.secretary.debug); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); } if (null != manager) { managers.put(id, manager); } else { managers.remove(id); } } /** * 初始化日志 */ private Logger initLog(Integer id) { // 实例化log,每个实例存放地方不一致 ch.qos.logback.classic.Logger logger = ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(this.secretary.strategyName + "-" + id)); LoggerContext context = logger.getLoggerContext(); TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>(); policy.setFileNamePattern(OptionHelper.substVars( "logs/past/" + id + "/%d{yyyy-MM-dd}.log.gz", context)); policy.setMaxHistory(31); policy.setContext(context); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %5level - [%thread] %logger : %msg%n"); RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>(); appender.setContext(context); appender.setName(this.secretary.strategyName + "-" + id); appender.setFile(OptionHelper.substVars("logs/" + id + "/log.log", context)); appender.setAppend(true); // 同一文件多输入完整检查 appender.setPrudent(false); appender.setRollingPolicy(policy); appender.setEncoder(encoder); policy.setParent(appender); policy.start(); encoder.start(); appender.start(); logger.setLevel(Level.INFO); // 终端输出 logger.setAdditive(true); logger.addAppender(appender); return logger; } /** * 核对检查运行状态,未运行的要运行,停止的要关闭 */ private void checkManagers() { Set<Integer> need = this.secretary.configs.keySet(); Set<Integer> running = this.secretary.configs.keySet(); Set<Integer> start = new HashSet<>(); Set<Integer> stop = new HashSet<>(); for (Integer id : need) { if (!running.contains(id)) { start.add(id); } } for (Integer id : running) { if (!need.contains(id)) { stop.add(id); } } start.forEach(id -> this.checkTask(id, this.secretary.configs.get(id))); stop.forEach(id -> this.checkTask(-id, this.secretary.configs.get(id))); } /** * 获取TaskManager */ Map<Integer, TaskManager> getManagers() { return this.secretary.managers; } boolean isReady() { return this.secretary.ready; } /** * 更新系统状态 */ private void updateRunInfo(RunInfo info) { if (info.getRunState() == RunState.STOPPED) { info.setEndTime(System.currentTimeMillis()); } File file = new File(".run_info"); if (Util.checkFile(file)) { Util.writeFile(file, JSON.toJSONString(info)); } } /** * 是否正在停止 * @return 是否正在停止 */ boolean isStopping() { return this.secretary.runInfo.getRunState() == RunState.STOPPING; } // ==================== tools ==================== /** * 输出程序启动的pid */ private static void pid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); log.info("process mark: {}", name); int index = name.indexOf("@"); if (index != -1) { int pid = Integer.parseInt(name.substring(0, index)); getInstance().secretary.runInfo.setPid(pid); log.info("process id: {}", pid); File file = new File("PID"); if (Util.checkFile(file)) { Util.writeFile(file, String.valueOf(pid)); } } } }
22,617
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
UserLogger.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/UserLogger.java
package cqt.goai.run.main; import org.slf4j.Logger; import org.slf4j.Marker; /** * 用户的log * * @author GOAi */ public class UserLogger implements Logger { private final Logger log; public UserLogger(Logger log) { this.log = log; } @Override public String getName() { return log.getName(); } @Override public boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public void trace(String msg) { log.trace("USER " + msg); } @Override public void trace(String format, Object arg) { log.trace("USER " + format, arg); } @Override public void trace(String format, Object arg1, Object arg2) { log.trace("USER " + format, arg1, arg2); } @Override public void trace(String format, Object... arguments) { log.trace("USER " + format, arguments); } @Override public void trace(String msg, Throwable t) { log.trace("USER " + msg, t); } @Override public boolean isTraceEnabled(Marker marker) { return log.isTraceEnabled(marker); } @Override public void trace(Marker marker, String msg) { log.trace(marker, "USER " + msg); } @Override public void trace(Marker marker, String format, Object arg) { log.trace(marker, "USER " + format, arg); } @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { log.trace(marker, "USER " + format, arg1, arg2); } @Override public void trace(Marker marker, String format, Object... argArray) { log.trace(marker, "USER " + format, argArray); } @Override public void trace(Marker marker, String msg, Throwable t) { log.trace(marker, "USER " + msg, t); } @Override public boolean isDebugEnabled() { return log.isDebugEnabled(); } @Override public void debug(String msg) { log.debug("USER " + msg); } @Override public void debug(String format, Object arg) { log.debug("USER " + format, arg); } @Override public void debug(String format, Object arg1, Object arg2) { log.debug("USER " + format, arg1, arg2); } @Override public void debug(String format, Object... arguments) { log.debug("USER " + format, arguments); } @Override public void debug(String msg, Throwable t) { log.debug("USER " + msg, t); } @Override public boolean isDebugEnabled(Marker marker) { return log.isDebugEnabled(marker); } @Override public void debug(Marker marker, String msg) { log.debug(marker, "USER " + msg); } @Override public void debug(Marker marker, String format, Object arg) { log.debug(marker, "USER " + format, arg); } @Override public void debug(Marker marker, String format, Object arg1, Object arg2) { log.debug(marker, "USER " + format, arg1, arg2); } @Override public void debug(Marker marker, String format, Object... arguments) { log.debug(marker, "USER " + format, arguments); } @Override public void debug(Marker marker, String msg, Throwable t) { log.debug(marker, "USER " + msg, t); } @Override public boolean isInfoEnabled() { return log.isInfoEnabled(); } @Override public void info(String msg) { log.info("USER " + msg); } @Override public void info(String format, Object arg) { log.info("USER " + format, arg); } @Override public void info(String format, Object arg1, Object arg2) { log.info("USER " + format, arg1, arg2); } @Override public void info(String format, Object... arguments) { log.info("USER " + format, arguments); } @Override public void info(String msg, Throwable t) { log.info("USER " + msg, t); } @Override public boolean isInfoEnabled(Marker marker) { return log.isInfoEnabled(marker); } @Override public void info(Marker marker, String msg) { log.info(marker, "USER " + msg); } @Override public void info(Marker marker, String format, Object arg) { log.info(marker, "USER " + format, arg); } @Override public void info(Marker marker, String format, Object arg1, Object arg2) { log.info(marker, "USER " + format, arg1, arg2); } @Override public void info(Marker marker, String format, Object... arguments) { log.info(marker, "USER " + format, arguments); } @Override public void info(Marker marker, String msg, Throwable t) { log.info(marker, "USER " + msg, t); } @Override public boolean isWarnEnabled() { return log.isWarnEnabled(); } @Override public void warn(String msg) { log.warn("USER " + msg); } @Override public void warn(String format, Object arg) { log.warn("USER " + format, arg); } @Override public void warn(String format, Object... arguments) { log.warn("USER " + format, arguments); } @Override public void warn(String format, Object arg1, Object arg2) { log.warn("USER " + format, arg1, arg2); } @Override public void warn(String msg, Throwable t) { log.warn("USER " + msg, t); } @Override public boolean isWarnEnabled(Marker marker) { return log.isWarnEnabled(marker); } @Override public void warn(Marker marker, String msg) { log.warn(marker, "USER " + msg); } @Override public void warn(Marker marker, String format, Object arg) { log.warn(marker, "USER " + format, arg); } @Override public void warn(Marker marker, String format, Object arg1, Object arg2) { log.warn(marker, "USER " + format, arg1, arg2); } @Override public void warn(Marker marker, String format, Object... arguments) { log.warn(marker, "USER " + format, arguments); } @Override public void warn(Marker marker, String msg, Throwable t) { log.warn(marker, "USER " + msg, t); } @Override public boolean isErrorEnabled() { return log.isErrorEnabled(); } @Override public void error(String msg) { log.error("USER " + msg); } @Override public void error(String format, Object arg) { log.error("USER " + format, arg); } @Override public void error(String format, Object arg1, Object arg2) { log.error("USER " + format, arg1, arg2); } @Override public void error(String format, Object... arguments) { log.error("USER " + format, arguments); } @Override public void error(String msg, Throwable t) { log.error("USER " + msg, t); } @Override public boolean isErrorEnabled(Marker marker) { return log.isErrorEnabled(marker); } @Override public void error(Marker marker, String msg) { log.error(marker, "USER " + msg); } @Override public void error(Marker marker, String format, Object arg) { log.error(marker, "USER " + format, arg); } @Override public void error(Marker marker, String format, Object arg1, Object arg2) { log.error(marker, "USER " + format, arg1, arg2); } @Override public void error(Marker marker, String format, Object... arguments) { log.error(marker, "USER " + format, arguments); } @Override public void error(Marker marker, String msg, Throwable t) { log.error(marker, "USER " + msg, t); } }
7,687
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TaskManager.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/TaskManager.java
package cqt.goai.run.main; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeException; import cqt.goai.exchange.util.CommonUtil; import cqt.goai.model.market.Klines; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Ticker; import cqt.goai.model.market.Trades; import cqt.goai.model.trade.Account; import cqt.goai.model.trade.Orders; import cqt.goai.run.exchange.Exchange; import cqt.goai.run.exchange.factory.BaseExchangeFactory; import cqt.goai.run.exchange.factory.LocalExchangeFactory; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import org.quartz.impl.triggers.CronTriggerImpl; import org.quartz.impl.triggers.SimpleTriggerImpl; import org.slf4j.Logger; import java.lang.reflect.*; import java.math.BigDecimal; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Function; import static dive.common.util.Util.exist; /** * 单个实例管理类,主要是初始化和定时任务 * @author GOAi */ class TaskManager { /** * 生成LocalExchange */ private static final BaseExchangeFactory LOCAL_FACTORY = new LocalExchangeFactory(); /** * 日志 */ Logger log; /** * 是否debug模式,不用proxy exchange代理,不忽略异常 */ private boolean debug; /** * 实例id */ private Integer id; /** * 实例对象 */ private RunTask runTask; /** * 实例类 */ private Class<?> taskClass; /** * 配置 */ private JSONObject config; /** * 定时任务 */ private Scheduler scheduler; /** * 定时方法 */ private List<ScheduledMethod> methodTasks; /** * 交易所列表,删除时需要 */ private List<Exchange> exchangeList = new LinkedList<>(); /** * 单个主动推送,name + type(type) */ private ConcurrentHashMap<String, Exchange> pushSingle = new ConcurrentHashMap<>(); /** * 多个主动推送, name + type(e, type) */ private ConcurrentHashMap<String, List<Exchange>> pushCollections = new ConcurrentHashMap<>(); /** * 构造器 * @param id 实例id * @param runTask 实例 * @param log 日志 * @param methods 模板定时任务 * @throws Exception 异常 */ TaskManager(Integer id, RunTask runTask, Logger log, List<MethodInfo> methods, boolean debug) throws Exception { this.log = log; this.debug = debug; this.id = id; this.runTask = runTask; this.taskClass = runTask.getClass(); this.config = runTask.config; try { this.runTask.setGetExchange(this::getExchange); // 子类参数未知,只能反射注入,检测设置主动推送函数 this.inject(); this.pushSingle.forEach((filed, e) -> this.checkPush(e, filed, true)); if (this.pushSingle.containsKey(E)) { this.checkPush(this.pushSingle.get(E), "", true); } this.pushCollections.forEach((filed, es) -> es.forEach(e -> this.checkPush(e, filed, false))); // 检查定时任务并加入任务队列 this.scheduler(methods); // 执行init this.runTask.init(); log.info("init {} successful.", this.id); // 准备完成 Field field = RunTask.class.getDeclaredField("ready"); field.setAccessible(true); field.set(this.runTask, true); field.setAccessible(false); if (null != this.scheduler) { this.scheduler.start(); } } catch (Exception e) { this.destroy(); /* * Chain of Responsibility 责任链模式 * 出错层层抛出直到被处理,异常的封装抛出是典型的责任链模式 */ throw e; } } /** * 简单类型的注入 */ private static LinkedHashMap<Function<Class<?>, Boolean>, Function<String, ?>> injectMap; static { injectMap = new LinkedHashMap<>(); injectMap.put((t) -> t == Double.class, Double::valueOf); injectMap.put((t) -> "double".equals(t.getName()), Double::valueOf); injectMap.put((t) -> t == Integer.class, Integer::valueOf); injectMap.put((t) -> "int".equals(t.getName()), c -> new BigDecimal(c).intValue()); injectMap.put((t) -> t == Long.class, Long::valueOf); injectMap.put((t) -> "long".equals(t.getName()), c -> new BigDecimal(c).longValue()); injectMap.put((t) -> t == String.class, s -> s); injectMap.put((t) -> t == JSONObject.class, JSON::parseObject); injectMap.put((t) -> t == JSONArray.class, JSON::parseArray); injectMap.put((t) -> t == BigDecimal.class, BigDecimal::new); injectMap.put((t) -> t == Boolean.class, Boolean::valueOf); injectMap.put((t) -> "boolean".equals(t.getName()), Boolean::valueOf); } /** * 注入属性 */ private void inject() { if (!exist(this.config)) { return; } NEXT: for (String key : this.config.keySet()) { try { Field field = this.taskClass.getDeclaredField(key); String content = this.config.getString(key); boolean flag = field.isAccessible(); field.setAccessible(true); content = TaskManager.trim(content); Class<?> type = field.getType(); // 简单类型的注入 for (Function<Class<?>, Boolean> condition : TaskManager.injectMap.keySet()) { Function<String, ?> change = TaskManager.injectMap.get(condition); if (condition.apply(type)) { field.set(this.runTask, change.apply(content)); this.log.info("inject field {} : {}", key, content); continue NEXT; } } // 复杂类型的注入 Object value = this.inject(type, field, content, key); if (null != value) { field.set(this.runTask, value); this.log.info("inject field {} : {}", key, value); } else { throw new Exception(key + " can not recognize config: " + content); } field.setAccessible(flag); } catch (NoSuchFieldException ignored) { } catch (Exception e) { e.printStackTrace(); this.log.error(e.getMessage()); } } this.configE(); } /** * 进行特殊注入 * @param type 类型 * @param field 属性 * @param content 内容 * @param key 属性名 * @return 注入值 * @throws Exception 异常 */ private Object inject(Class<?> type, Field field, String content, String key) throws Exception { Object value = null; if (type == Exchange.class) { Exchange exchange = this.getExchange(content); this.pushSingle.put(key, exchange); value = exchange; } else if (type.isEnum()) { Enum[] objects = (Enum[]) field.getType().getEnumConstants(); for (Enum o : objects) { if (o.name().equals(content)) { value = o; break; } } if (null == value) { throw new Exception(key + " can not recognize config: " + content); } } else if (Arrays.asList(type.getInterfaces()).contains(Injectable.class)) { Injectable inject = this.getInjectable(type); inject.inject(content, this::getExchange); value = inject; }else if (type == List.class && field.getGenericType() instanceof ParameterizedType) { Class<?> genericClass = Class.forName(((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0].getTypeName()); // 处理集合类型 for (Function<Class<?>, Boolean> condition : TaskManager.injectMap.keySet()) { Function<String, ?> change = TaskManager.injectMap.get(condition); if (condition.apply(genericClass)) { JSONArray array = JSON.parseArray(content); List<Object> list = new ArrayList<>(array.size()); for (int i = 0; i < array.size(); i++) { list.add(change.apply(array.getString(i))); } return list; } } if (genericClass == Exchange.class) { JSONArray array = JSON.parseArray(content); List<Exchange> list = new ArrayList<>(array.size()); for (int i = 0; i < array.size(); i++) { list.add(this.getExchange(array.getString(i))); } this.pushCollections.put(key, new ArrayList<>(list)); value = list; } else if (Arrays.asList(genericClass.getInterfaces()).contains(Injectable.class)) { JSONArray array = JSON.parseArray(content); List<Injectable> list = new ArrayList<>(array.size()); for (int i = 0; i < array.size(); i++) { Injectable inject = this.getInjectable(genericClass); inject.inject(array.getString(i), this::getExchange); list.add(inject); } value = list; } } return value; } /** * 获取一个injectable实例 * @param type 类型 * @return 实例 * @throws Exception 异常 */ private Injectable getInjectable(Class<?> type) throws Exception { Constructor c = type.getDeclaredConstructors()[0]; boolean flag = c.isAccessible(); c.setAccessible(true); Injectable inject; int length = c.getParameterCount(); if (0 == length) { inject = (Injectable) c.newInstance(); } else if (1 == length && c.getParameterTypes()[0] == this.taskClass) { inject = (Injectable) c.newInstance(this.runTask); } else { throw new RuntimeException("can not get instance: " + type.getName()); } c.setAccessible(flag); return inject; } /** * 根据配置获取Exchange * @param content 配置 * @return Exchange */ private Exchange getExchange(String content) { JSONObject c = JSON.parseObject(content); if (!c.containsKey(NAME) || !c.containsKey(SYMBOL)) { String message = "can not load Exchange by config: " + content; this.log.error(message); throw new ExchangeException(message); } if (!c.containsKey(ACCESS)) { c.put(ACCESS, ""); } if (!c.containsKey(SECRET)) { c.put(SECRET, ""); } // FIXME 这里应该判断加载: // 1. 本地Exchange // 2. 指定NodeExchange(本地构造签名) // 3. 指定NodeExchange(Node构造签名) // 1. 本地Exchange // FIXME Test Exchange exchange = LOCAL_FACTORY.getExchange(!this.debug, this.log, c, this.runTask.isReady); // 保存,等销毁时要取消订阅的 this.exchangeList.add(exchange); // FIXME 应该返回代理对象 return exchange; } /** * 配置e */ private void configE() { if (this.config.containsKey(E)) { try { Field field = null; try { field = this.taskClass.getDeclaredField(E); } catch (NoSuchFieldException | SecurityException ignored) { } if (null != field) { // 有设置e,无需通过父类设置 return; } field = RunTask.class.getDeclaredField(E); boolean flag = field.isAccessible(); field.setAccessible(true); Exchange exchange = this.getExchange(TaskManager.trim(this.config.getString(E))); if (exist(exchange)) { field.set(this.runTask, exchange); this.pushSingle.put(E, exchange); this.checkPush(exchange, "", false); this.log.info("inject field e : {}", exchange); } field.setAccessible(flag); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } } /** * 检查主动推送 * @param exchange 推送交易所 * @param prefix 前缀 * @param single 是否单个推送 */ private void checkPush(Exchange exchange, String prefix, boolean single) { // FIXME 检查是否需要主动推送 checkPush(exchange, exchange::setOnTicker, prefix, "onTicker", single, Ticker.class); checkPush(exchange, exchange::setOnKlines, prefix, "onKlines", single, Klines.class); checkPush(exchange, exchange::setOnDepth, prefix, "onDepth", single, Depth.class); checkPush(exchange, exchange::setOnTrades, prefix, "onTrades", single, Trades.class); checkPush(exchange, exchange::setOnAccount, prefix, "onAccount", single, Account.class); checkPush(exchange, exchange::setOnOrders, prefix, "onOrders", single, Orders.class); } /** * 检查是否需要主动推送 * @param set 交易所推送设置方法 * @param prefix 属性名 * @param type 推送类型 * @param exchange 被推送的交易所 * @param parameterType 参数列表 */ private void checkPush(Exchange exchange, Consumer<Consumer> set, String prefix, String type, boolean single, Class<?> parameterType) { try { String methodName; if ("".equals(prefix)) { methodName = type; } else { methodName = prefix + type.substring(0, 1).toUpperCase() + type.substring(1); } Method method; if (single) { method = this.taskClass.getDeclaredMethod(methodName, parameterType); } else { method = this.taskClass.getDeclaredMethod(methodName, Exchange.class, parameterType); } if (exist(method)) { method.setAccessible(true); this.log.info("config push: field: {} name:{} symbol:{} methodName: {}", "".equals(prefix) ? E : prefix, exchange.getName(), exchange.getSymbol(), methodName); if (single) { set.accept(ticker -> { try { method.invoke(this.runTask, ticker); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); this.log.error(e.getMessage()); } }); } else { set.accept(ticker -> { try { method.invoke(this.runTask, exchange, ticker); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); this.log.error(e.getMessage()); } }); } } } catch (NoSuchMethodException e) { // e.printStackTrace(); } } /** * 设置定时任务 * @param methods 定时任务 * @throws SchedulerException E */ private void scheduler(List<MethodInfo> methods) throws SchedulerException { if (0 < methods.size()) { this.methodTasks = new LinkedList<>(); for (MethodInfo mi : methods) { List<ScheduledInfo> schedules = mi.getSchedules(); // 尝试从配置中找该方法的配置信息 String methodName = mi.getMethod().getName(); List<String> cs = new LinkedList<>(); if (exist(this.config)) { for (String key : this.config.keySet()) { if (key.startsWith(methodName)) { cs.add(key); } } } if (0 < cs.size()) { // 该方法若有配置 schedules = new ArrayList<>(cs.size()); for (String key : cs) { String value = this.config.getString(key); if (value.contains("*")) { schedules.add(new ScheduledInfo(value, 0, 0)); } else { try { long f = new BigDecimal(value) .multiply(CommonUtil.THOUSAND).longValue(); schedules.add(new ScheduledInfo(null, f, 0)); } catch (Exception e) { this.log.error("can not format " + value + " to number."); } } } } for (ScheduledInfo si : schedules) { this.methodTasks.add(new ScheduledMethod(this.log, this.id, this.runTask, mi.getMethod(), mi.getLock(), si.copy(), mi.getMethodScope())); } } List<ScheduleJob> list = new LinkedList<>(); for (int i = 0; i < this.methodTasks.size(); i++) { ScheduledMethod mt = this.methodTasks.get(i); if (null != mt.getScheduledInfo().getTrigger()) { list.add(this.checkJob(mt, i)); } } this.log.info("{} tasks size: {}", id, list.size()); Properties properties = new Properties(); properties.put("org.quartz.scheduler.instanceName", this.taskClass.getSimpleName() + ":" + this.id); // 最大个数 properties.put("org.quartz.threadPool.threadCount", String.valueOf((int)(list.size() * 1.5 + 0.5))); SchedulerFactory schedulerFactory = new StdSchedulerFactory(properties); this.scheduler = schedulerFactory.getScheduler(); for (ScheduleJob sj : list) { this.scheduler.scheduleJob(sj.jobDetail, sj.trigger); } } } /** * 添加任务 */ private ScheduleJob checkJob(ScheduledMethod mt, int number) { Method method = mt.getMethod(); Trigger trigger = mt.getScheduledInfo().getTrigger(); String description = this.id + "-" + method.getName() + "-" + number; this.log.info("{} {}", description, mt.getScheduledInfo().getTip()); JobDetail jobDetail = JobBuilder.newJob(ScheduledJob.class) .withDescription(description) .withIdentity(this.taskClass.getSimpleName(), description) .build(); if (trigger instanceof CronTriggerImpl) { ((CronTriggerImpl) trigger).setName(description); } if (trigger instanceof SimpleTriggerImpl) { ((SimpleTriggerImpl) trigger).setName(description); } return new ScheduleJob(jobDetail, trigger); } /** * 定时任务 */ private class ScheduleJob { private JobDetail jobDetail; private Trigger trigger; ScheduleJob(JobDetail jobDetail, Trigger trigger) { this.jobDetail = jobDetail; this.trigger = trigger; } } /** * 清除所有任务,准备销毁 */ void destroy() { try { if (null != this.scheduler && !this.scheduler.isShutdown()) { this.scheduler.shutdown(); } this.exchangeList.forEach(Exchange::destroy); } catch (SchedulerException e) { e.printStackTrace(); } this.runTask.destroy(); log.info("destroy {} successful.", this.id); } List<ScheduledMethod> getMethodTasks() { return this.methodTasks; } RunTask getRunTask() { return this.runTask; } // ===================== tools ===================== private static final String E = "e"; private static final String N = "\n"; private static final String R = "\r"; private static final String T = "\t"; private static final String Z = "\0"; private static final String NAME = "name"; private static final String SYMBOL = "symbol"; private static final String ACCESS = "access"; private static final String SECRET = "secret"; /** * 去除字符串首尾无效字符 * @param v 字符串 */ private static String trim(String v) { v = v.trim(); while (v.startsWith(N) || v.startsWith(R) || v.startsWith(T) || v.startsWith(Z)) { v = v.substring(1); } while (v.endsWith(N) || v.endsWith(R) || v.endsWith(T) || v.endsWith(Z)) { v = v.substring(1); } return v; } }
21,717
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ScheduledJob.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/ScheduledJob.java
package cqt.goai.run.main; import lombok.extern.slf4j.Slf4j; import org.quartz.Job; import org.quartz.JobExecutionContext; import java.util.List; import static dive.common.util.Util.exist; /** * 从Configs中找到要执行的任务,执行 * @author GOAi */ @Slf4j public class ScheduledJob implements Job { private static Minister minister = Minister.getInstance(); /** * Command Pattern 命令模式 * 封装任务命令定时执行 * @param context 任务内容 */ @Override public void execute(JobExecutionContext context) { if (!ScheduledJob.minister.isReady()) { return; } /* * Interpreter Patter 解释器模式 * 定义规则,不同解释器解释结果不同 * 运算表达式 统一的解释方法,加减乘除不同的处理方式 */ String description = context.getJobDetail().getDescription(); String[] split = description.split("-"); Integer id = Integer.valueOf(split[0]); Integer index = Integer.valueOf(split[2]); TaskManager manager = ScheduledJob.minister.getManagers().get(id); if (!exist(manager)) { log.error("can not find TaskManager: {}", description); return; } List<ScheduledMethod> methodTasks = manager.getMethodTasks(); if (methodTasks.size() <= index) { manager.log.error("can not find MethodTask: {}, methodTasks.size: {}", description, methodTasks.size()); return; } ScheduledMethod mt = methodTasks.get(index); mt.invoke(description); } }
1,664
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ScheduledInfo.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/ScheduledInfo.java
package cqt.goai.run.main; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.quartz.Trigger; import org.quartz.impl.triggers.CronTriggerImpl; import org.quartz.impl.triggers.SimpleTriggerImpl; import java.text.ParseException; import java.util.Date; import static dive.common.util.Util.exist; import static dive.common.util.Util.useful; /** * 单个方法的定时信息 * @author GOAi */ @Getter @Slf4j class ScheduledInfo { /** * cron定时 */ private String cron; /** * 固定频率 */ private long fixedRate; /** * 延时 */ private long delay; /** * 触发器 */ private Trigger trigger; /** * 提示信息 */ private String tip; /** * 构造器 */ ScheduledInfo(String cron, long fixedRate, long delay) { this.cron = cron; this.fixedRate = fixedRate; this.delay = delay; initTrigger(); } /** * 设置触发器 */ private void initTrigger() { initCronTrigger(); if (exist(trigger)) { return; } initSimpleTrigger(); if (exist(trigger)) { return; } log.error("init trigger error --> cron: {}, fixedRate: {}, delay: {}", this.cron, this.fixedRate, this.delay); } /** * 重置触发器 */ void setCron(String cron) { this.cron = cron; this.trigger = null; initCronTrigger(); } /** * 重置触发器 */ void setRate(long fixedRate) { this.fixedRate = fixedRate; this.delay = 3000; initSimpleTrigger(); } /** * 使用前应该复制一份 */ ScheduledInfo copy() { return new ScheduledInfo(this.cron, this.fixedRate, this.delay); } /** * 设置触发器 */ private void initCronTrigger() { if (!useful(this.cron)) { return; } try { CronTriggerImpl cronTrigger = new CronTriggerImpl(); cronTrigger.setCronExpression(this.cron); this.tip = "cron: " + this.cron; this.trigger = cronTrigger; this.fixedRate = -1; this.delay = -1; } catch (ParseException e) { log.error("can not format {} to cron", this.cron); } } /** * 设置触发器 */ private void initSimpleTrigger() { if (this.fixedRate <= 0 || this.delay < 0) { return; } SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl(); simpleTrigger.setRepeatInterval(this.fixedRate); this.tip = "fixedRate: " + this.fixedRate + " ms delay: " + this.delay + " ms"; // 无限次 simpleTrigger.setRepeatCount(-1); simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + this.delay)); this.trigger = simpleTrigger; this.cron = ""; } }
2,980
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Notice.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/Notice.java
package cqt.goai.run.main; import cqt.goai.exchange.ExchangeUtil; import dive.http.common.MimeRequest; import org.slf4j.Logger; import static dive.common.util.Util.useful; /** * 通知对象 * * @author GOAi */ public class Notice { private final Logger log; private final String telegramGroup; private final String token; public Notice(Logger log, String telegramGroup, String token) { this.log = log; this.telegramGroup = telegramGroup; this.token = token; } /** * 高级通知,发电报 * @param message 消息 */ public void noticeHigh(String message) { this.log.info("NOTICE_HIGH {}", message); // FIX ME 发电报通知 if (useful(this.telegramGroup)) { new MimeRequest.Builder() .url("https://api.telegram.org/bot" + token + "/sendMessage") .post() .body("chat_id", this.telegramGroup) .body("text", message) .body("parse_mode", "HTML") .execute(ExchangeUtil.OKHTTP); } } /** * 低级通知,打日志 * @param message 消息 */ public void noticeLow(String message) { this.log.info("NOTICE_LOW {}", message); } }
1,310
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Const.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/Const.java
package cqt.goai.run.main; /** * 常量 * @author GOAi */ class Const { /** * 获取配置的url */ static final String START_URL = "--url="; /** * 配置文件名称,可以相对路径或绝对路径 */ static final String START_NAME = "--name="; /** * 策略名称 */ static final String CONFIG_STRATEGY_NAME = "strategy_name"; /** * 启动类名,java的run需要 */ static final String CONFIG_CLASS_NAME = "class_name"; /** * 每个实例的配置 */ static final String CONFIG_CONFIGS = "configs"; /** * 运行模式 如果是debug,不使用ProxyExchange */ static final String CONFIG_RUN_MODE = "run_mode"; // static final String CONFIG_RUN_MODE_DEBUG = "DEBUG"; /** * 默认的定时方法 */ static final String DEFAULT_SCHEDULED_METHOD = "loop"; // 魔法变量 static final String LEFT_SQUARE_BRACKETS = "["; }
974
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Util.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/Util.java
package cqt.goai.run.main; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static dive.common.util.Util.exist; /** * 工具类 * @author GOAi */ class Util { /** * 检查文件是否存在 */ static boolean checkFile(File file) { if (null == file) { return false; } if (file.isDirectory()) { return false; } if (!file.exists()) { try { boolean result = file.createNewFile(); if (!result) { return false; } } catch (IOException e) { e.printStackTrace(); } } return true; } /** * 写文件 * @param file 文件 * @param message 写的内容 */ static void writeFile(File file, String message) { try (FileOutputStream os = new FileOutputStream(file, false)){ os.write(message.getBytes()); } catch (IOException e) { e.printStackTrace(); } } /** * 获取url参数 * @param url url */ static Map<String, String> getParamsByUrl(String url){ String params = url.substring(url.indexOf("?") + 1); if(!exist(params)){ return null; } String[] paramsArr = params.split("&"); Map<String, String> map = new HashMap<>(); for(String param : paramsArr){ String[] keyValue = param.split("="); map.put(keyValue[0], keyValue[1]); } return map; } /** * 获取url指定参数 * @param url url * @param name 参数名 */ static String getParamByUrl(String url, String name){ Map<String, String> map = getParamsByUrl(url); if(map.isEmpty() || !map.containsKey(name)){ return null; } return map.get(name); } }
1,993
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
MethodScope.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/MethodScope.java
package cqt.goai.run.main; /** * 定时任务方法运行范围 * * @author GOAi */ public enum MethodScope { /** * 全局唯一 */ GLOBAL, /** * 实例唯一 */ INSTANCE, /** * 循环任务唯一 */ SCHEDULED, /** * 不限制 */ NONE }
319
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ScheduledMethod.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/ScheduledMethod.java
package cqt.goai.run.main; import lombok.Getter; import org.slf4j.Logger; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** * 单个定时任务方法 * * @author GOAi */ @Getter class ScheduledMethod { private static Minister minister = Minister.getInstance(); private final Logger log; private final Integer id; private final RunTask runTask; private final Method method; private final MethodScope methodScope; private final ReentrantLock lock; private final ScheduledInfo scheduledInfo; ScheduledMethod(Logger log, Integer id, RunTask runTask, Method method, ReentrantLock lock, ScheduledInfo scheduledInfo, MethodScope methodScope) { this.log = log; this.id = id; this.runTask = runTask; this.method = method; this.methodScope = methodScope; this.lock = lock; this.scheduledInfo = scheduledInfo; } void invoke(String description) { if (minister.isStopping()) { return; } try { if (null == lock || lock.tryLock(0, TimeUnit.MILLISECONDS)) { try { method.invoke(runTask); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); log.error("run method failed : {} --> {} exception: {}", description, method.getName(), e); } finally { if (null != lock && lock.isLocked()) { lock.unlock(); } } } else { if (minister.isDebug()) { log.error("{} lock is locked... {}", description, id); } } } catch (InterruptedException e) { e.printStackTrace(); } } }
1,993
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
MethodInfo.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/MethodInfo.java
package cqt.goai.run.main; import lombok.Getter; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.locks.ReentrantLock; /** * 方法运行信息 * * @author GOAi */ @Getter class MethodInfo { /** * 方法 */ private final Method method; /** * 方法运行范围 */ private final MethodScope methodScope; /** * 方法运行锁,重点是全局一个锁,不检查无锁,实例内只用一个,定时范围新生成 */ private final ReentrantLock globalLock; /** * 实例锁 */ private final ReentrantLock instanceLock; /** * 定时任务信息 */ private final List<ScheduledInfo> schedules; MethodInfo(Method method, MethodScope methodScope, List<ScheduledInfo> schedules) { this.method = method; this.methodScope = methodScope; this.schedules = schedules; if (methodScope == MethodScope.GLOBAL) { this.globalLock = new ReentrantLock(); this.instanceLock = null; } else { this.globalLock = null; this.instanceLock = null; } } private MethodInfo(Method method, MethodScope methodScope, ReentrantLock globalLock, ReentrantLock instanceLock, List<ScheduledInfo> schedules) { this.method = method; this.methodScope = methodScope; this.globalLock = globalLock; this.instanceLock = instanceLock; this.schedules = schedules; } MethodInfo copy() { switch (methodScope) { case INSTANCE: return new MethodInfo(method, methodScope, null, new ReentrantLock(), schedules); case SCHEDULED: return new MethodInfo(method, methodScope, null, null, schedules); default: return this; } } ReentrantLock getLock() { switch (methodScope) { case GLOBAL: return this.globalLock; case INSTANCE: return this.instanceLock; case SCHEDULED: return new ReentrantLock(); default: return null; } } }
2,098
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Injectable.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/main/Injectable.java
package cqt.goai.run.main; import cqt.goai.run.exchange.Exchange; import java.util.function.Function; /** * 自定义类型实现该接口,可实现自动注入 * @author GOAi */ public interface Injectable { /** * 注入 * * @param config 配置内容 * @param getExchange 获取exchange 参数为json字符串 * {"name":"xxx","symbol":"BTC_USD","access":"xxx","secret":"xxx"} */ void inject(String config, Function<String, Exchange> getExchange); }
511
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ScheduledScope.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/annotation/ScheduledScope.java
package cqt.goai.run.annotation; import cqt.goai.run.main.MethodScope; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 方法范围 * * @author GOAi */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ScheduledScope { /** * 默认实例范围 * @return 方法运行范围 */ MethodScope value() default MethodScope.INSTANCE; }
509
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Schedules.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/annotation/Schedules.java
package cqt.goai.run.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 单个方法允许设置多个定时任务 * @author GOAi */ @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Schedules { Scheduled[] value(); }
418
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Scheduled.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/annotation/Scheduled.java
package cqt.goai.run.annotation; import java.lang.annotation.*; /** * 定时任务 * @author GOAi */ @Repeatable(Schedules.class) @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Scheduled { /** * cron方式 优先 */ String cron() default ""; /** * 固定频率,毫秒 */ long fixedRate() default 0; /** * 延时,毫秒 */ long delay() default 0; }
480
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
FourFunction.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/FourFunction.java
package cqt.goai.run.exchange; /** * @author GOAi */ @FunctionalInterface public interface FourFunction<T, U, K, L, R> { /** * 接受6个参数 * @param t t * @param u u * @param k k * @param l l */ R apply(T t, U u, K k, L l); }
271
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
LocalExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/LocalExchange.java
package cqt.goai.run.exchange; import cqt.goai.exchange.ExchangeException; import cqt.goai.exchange.ExchangeInfo; import cqt.goai.exchange.ExchangeManager; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.util.RateLimit; import cqt.goai.exchange.util.Seal; import cqt.goai.exchange.web.socket.WebSocketExchange; import cqt.goai.model.enums.Period; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import cqt.goai.run.exchange.model.ModelManager; import cqt.goai.run.exchange.model.ModelObserver; import cqt.goai.run.exchange.model.TradesObserver; import dive.common.math.RandomUtil; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; /** * 完全本地自主连接的Exchange * @author GOAi */ public class LocalExchange extends BaseExchange { /** * http方式 */ private HttpExchange httpExchange; /** * websocket方式 */ private WebSocketExchange webSocketExchange; public LocalExchange(Logger log, ExchangeName name, String symbol, String access, String secret, Supplier<Boolean> ready) { super(log, name, symbol, access, secret, ready); this.httpExchange = ExchangeManager.getHttpExchange(name, log); } @Override public HttpExchange getHttpExchange() { return this.httpExchange; } /** * 检查WebSocketExchange */ private void checkWebSocketExchange() { if (null == this.webSocketExchange) { synchronized (LocalExchange.class) { if (null == this.webSocketExchange) { this.webSocketExchange = ExchangeManager.getWebSocketExchange(super.name, super.log); } } } } @Override public void destroy() { if (null == this.webSocketExchange) { return; } super.ticker.getObservers().values().forEach(o -> this.webSocketExchange.noTicker(o.getId())); super.klines.forEach((p, c) -> c.getObservers().values() .forEach(o -> this.webSocketExchange.noKlines(p, o.getId()))); super.depth.getObservers().values().forEach(o -> this.webSocketExchange.noDepth(o.getId())); super.trades.getObservers().values().forEach(o -> this.webSocketExchange.noTrades(o.getId())); super.account.getObservers().values().forEach(o -> this.webSocketExchange.noAccount(o.getId())); super.orders.getObservers().values().forEach(o -> this.webSocketExchange.noOrders(o.getId())); } @Override public Ticker getTicker(boolean latest) { if (super.ticker.on()) { // 如果有推送ticker 直接返回缓存的 return super.ticker.getModel(); } else { if (!latest && !super.ticker.getLimit().timeout(false)) { // 如果允许不是最新的,并且没有超时(3s) 可以返回缓存的 return super.ticker.getModel(); } // http 方式获取最新的 Ticker ticker = this.httpExchange.getTicker( ExchangeInfo.ticker(super.symbol, super.access, super.secret)); // 更新缓存 super.ticker.update(ticker); return ticker; } } @Override public Klines getKlines(Period period, boolean latest) { if (null == period) { period = Period.MIN1; } ModelManager<Klines> manager = super.klines.computeIfAbsent(period, p -> new ModelManager<>(RateLimit.second3())); if (manager.on()) { // 如果有推送klines 直接返回缓存的 return manager.getModel(); } else { if (!latest && !manager.getLimit().timeout(false)) { // 如果允许不是最新的,并且没有超时(3s) 可以返回缓存的 return manager.getModel(); } // http 方式获取最新的 Klines klines = this.httpExchange.getKlines( ExchangeInfo.klines(super.symbol, super.access, super.secret, period)); // 更新缓存 manager.update(klines); return klines; } } @Override public Depth getDepth(boolean latest) { if (super.depth.on()) { // 如果有推送depth 直接返回缓存的 return super.depth.getModel(); } else { if (!latest && !super.depth.getLimit().timeout(false)) { // 如果允许不是最新的,并且没有超时(3s) 可以返回缓存的 return super.depth.getModel(); } // http 方式获取最新的 Depth depth = this.httpExchange.getDepth( ExchangeInfo.depth(super.symbol, super.access, super.secret)); // 更新缓存 super.depth.update(depth); return depth; } } @Override public Trades getTrades(boolean latest) { if (super.trades.on()) { // 如果有推送trades 直接返回缓存的 return super.trades.getModel(); } else { if (!latest && !super.trades.getLimit().timeout(false)) { // 如果允许不是最新的,并且没有超时(3s) 可以返回缓存的 return super.trades.getModel(); } // http 方式获取最新的 Trades trades = this.httpExchange.getTrades( ExchangeInfo.trades(super.symbol, super.access, super.secret)); // 更新缓存 super.trades.update(trades); return trades; } } @Override public Balances getBalances() { return this.httpExchange.getBalances( ExchangeInfo.balances(super.symbol, super.access, super.secret)); } @Override public Account getAccount(boolean latest) { if (super.account.on()) { // 如果有推送account 直接返回缓存的 return super.account.getModel(); } else { if (!latest && !super.account.getLimit().timeout(false)) { // 如果允许不是最新的,并且没有超时(3s) 可以返回缓存的 return super.account.getModel(); } // http 方式获取最新的 Account account = this.httpExchange.getAccount( ExchangeInfo.account(super.symbol, super.access, super.secret)); // 更新缓存 super.account.update(account); return account; } } @Override public Precisions getPrecisions() { return this.httpExchange.getPrecisions( ExchangeInfo.precisions(super.symbol, super.access, super.secret)); } @Override public Precision getPrecision() { if (null == super.precision) { synchronized (this) { if (null == super.precision) { super.precision = this.httpExchange.getPrecision( ExchangeInfo.precision(super.symbol, super.access, super.secret)); } } } return super.precision; } @Override public String buyLimit(BigDecimal price, BigDecimal amount) { price = super.checkCount(price, false); amount = super.checkBase(amount); return this.httpExchange.buyLimit( ExchangeInfo.buyLimit(super.symbol, super.access, super.secret, price.toPlainString(), amount.toPlainString())); } @Override public String sellLimit(BigDecimal price, BigDecimal amount) { price = super.checkCount(price, true); amount = super.checkBase(amount); return this.httpExchange.sellLimit( ExchangeInfo.sellLimit(super.symbol, super.access, super.secret, price.toPlainString(), amount.toPlainString())); } @Override public String buyMarket(BigDecimal count) { count = super.checkCount(count, false); return this.httpExchange.buyMarket( ExchangeInfo.buyMarket(super.symbol, super.access, super.secret, count.toPlainString())); } @Override public String sellMarket(BigDecimal base) { base = super.checkBase(base); return this.httpExchange.sellMarket( ExchangeInfo.sellMarket(super.symbol, super.access, super.secret, base.toPlainString())); } @Override public List<String> multiBuy(List<Row> bids) { bids = super.checkRows(bids, false); if (bids.isEmpty()) { return Collections.emptyList(); } return this.httpExchange.multiBuy( ExchangeInfo.multiBuy(super.symbol, super.access, super.secret, bids)); } @Override public List<String> multiSell(List<Row> asks) { asks = super.checkRows(asks, true); if (asks.isEmpty()) { return Collections.emptyList(); } return this.httpExchange.multiSell( ExchangeInfo.multiSell(super.symbol, super.access, super.secret, asks)); } @Override public boolean cancelOrder(String id) { return this.httpExchange.cancelOrder( ExchangeInfo.cancelOrder(super.symbol, super.access, super.secret, id)); } @Override public List<String> cancelOrders(List<String> ids) { if (null == ids || ids.isEmpty()) { return Collections.emptyList(); } return this.httpExchange.cancelOrders( ExchangeInfo.cancelOrders(super.symbol, super.access, super.secret, ids)); } @Override public Orders getOrders() { return this.httpExchange.getOrders( ExchangeInfo.orders(super.symbol, super.access, super.secret)); } @Override public Orders getHistoryOrders() { return this.httpExchange.getHistoryOrders( ExchangeInfo.historyOrders(super.symbol, super.access, super.secret)); } @Override public Order getOrder(String id) { return this.httpExchange.getOrder( ExchangeInfo.order(super.symbol, super.access, super.secret, id)); } @Override public OrderDetails getOrderDetails(String id) { return this.httpExchange.getOrderDetails( ExchangeInfo.orderDetails(super.symbol, super.access, super.secret, id)); } @Override public OrderDetails getOrderDetailAll() { return this.httpExchange.getOrderDetailAll( ExchangeInfo.orderDetailAll(super.symbol, super.access, super.secret)); } @Override public void setOnTicker(Consumer<Ticker> onTicker, RateLimit limit) { checkWebSocketExchange(); ModelObserver<Ticker> mo = new ModelObserver<>(onTicker, limit, RandomUtil.token()); boolean success = this.webSocketExchange.onTicker( ExchangeInfo.onTicker(super.symbol, super.access, super.secret, mo.getId()), ticker -> super.onTicker(ticker, mo.getId())); if (!success) { throw new ExchangeException("can not register ticker: " + super.getName() + " " + super.getSymbol() + " " + Seal.seal(super.getAccess())); } super.ticker.observe(mo); log.info("observe successful! {} {} {} {}", name.getName(), symbol, "onTicker", limit); } @Override public void setOnKlines(Consumer<Klines> onKlines, Period period, RateLimit limit) { checkWebSocketExchange(); ModelObserver<Klines> mo = new ModelObserver<>(onKlines, limit, RandomUtil.token()); boolean success = this.webSocketExchange.onKlines( ExchangeInfo.onKlines(super.symbol, super.access, super.secret, period, mo.getId()), klines -> super.onKlines(period, klines, mo.getId())); if (!success) { throw new ExchangeException("can not register klines: " + super.getName() + " " + super.getSymbol() + " " + Seal.seal(super.getAccess())); } super.klines.computeIfAbsent(period, p -> new ModelManager<>(RateLimit.second3())) .observe(mo); log.info("observe successful! {} {} {} {}", name.getName(), symbol, "onKlines", period); } @Override public void setOnDepth(Consumer<Depth> onDepth, RateLimit limit) { checkWebSocketExchange(); ModelObserver<Depth> mo = new ModelObserver<>(onDepth, limit, RandomUtil.token()); boolean success = this.webSocketExchange.onDepth( ExchangeInfo.onDepth(super.symbol, super.access, super.secret, mo.getId()), depth -> super.onDepth(depth, mo.getId())); if (!success) { throw new ExchangeException("can not register depth: " + super.getName() + " " + super.getSymbol() + " " + Seal.seal(super.getAccess())); } super.depth.observe(mo); log.info("observe successful! {} {} {} {}", name.getName(), symbol, "onDepth", limit); } @Override public void setOnTrades(Consumer<Trades> onTrades, RateLimit limit) { checkWebSocketExchange(); TradesObserver to = new TradesObserver(onTrades, limit, RandomUtil.token(), 200); boolean success = this.webSocketExchange.onTrades( ExchangeInfo.onTrades(super.symbol, super.access, super.secret, to.getId()), trades -> super.onTrades(trades, to.getId())); if (!success) { throw new ExchangeException("can not register trades: " + super.getName() + " " + super.getSymbol() + " " + Seal.seal(super.getAccess())); } super.trades.observe(to); log.info("observe successful! {} {} {} {}", name.getName(), symbol, "onTrades", limit); } @Override public void setOnAccount(Consumer<Account> onAccount) { checkWebSocketExchange(); ModelObserver<Account> mo = new ModelObserver<>(onAccount, RateLimit.NO, RandomUtil.token()); boolean success = this.webSocketExchange.onAccount( ExchangeInfo.onAccount(super.symbol, super.access, super.secret, mo.getId()), account -> super.onAccount(account, mo.getId())); if (!success) { throw new ExchangeException("can not register account: " + super.getName() + " " + super.getSymbol() + " " + Seal.seal(super.getAccess())); } super.account.observe(mo); log.info("observe successful! {} {} {} {}", name.getName(), symbol, "onAccount", RateLimit.NO); } @Override public void setOnOrders(Consumer<Orders> onOrders) { checkWebSocketExchange(); ModelObserver<Orders> mo = new ModelObserver<>(onOrders, RateLimit.NO, RandomUtil.token()); boolean success = this.webSocketExchange.onOrders( ExchangeInfo.onOrders(super.symbol, super.access, super.secret, mo.getId()), orders -> super.onOrders(orders, mo.getId())); if (!success) { throw new ExchangeException("can not register orders: " + super.getName() + " " + super.getSymbol() + " " + Seal.seal(super.getAccess())); } super.orders.observe(mo); log.info("observe successful! {} {} {} {}", name.getName(), symbol, "onOrders", RateLimit.NO); } // ===================== tools ======================== @Override public String toString() { return "LocalExchange{" + super.toString() + '}'; } }
15,792
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ProxyExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/ProxyExchange.java
package cqt.goai.run.exchange; import com.alibaba.fastjson.JSON; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.util.RateLimit; import cqt.goai.exchange.util.Seal; import cqt.goai.model.enums.Period; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import cqt.goai.run.exchange.model.LogAction; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.function.*; /** * @author GOAi */ public class ProxyExchange implements Exchange { /** * 被代理的交易所 */ private Exchange e; /** * 日志 */ private Logger log; public ProxyExchange(Exchange exchange) { this.e = exchange; this.log = this.e.getLog(); } @Override public ExchangeName getExchangeName() { return this.e.getExchangeName(); } @Override public String getName() { return this.e.getName(); } @Override public String getSymbol() { return this.e.getSymbol(); } @Override public String getAccess() { return this.e.getAccess(); } @Override public String getSecret() { return this.e.getSecret(); } @Override public Logger getLog() { return this.e.getLog(); } @Override public HttpExchange getHttpExchange() { return this.e.getHttpExchange(); } @Override public void destroy() { this.run(this.e::destroy); } @Override public BigDecimal checkCount(BigDecimal count, boolean ceil) { return this.get(this.e::checkCount, count, ceil); } @Override public BigDecimal checkBase(BigDecimal base) { return this.get(this.e::checkBase, base); } @Override public List<Row> checkRows(List<Row> rows, boolean ceil) { return this.get(this.e::checkRows, rows, ceil); } // =================== market ======================= @Override public Ticker getTicker() { return this.get(this.e::getTicker); } @Override public Ticker getTicker(boolean latest) { return this.get(this.e::getTicker, latest); } @Override public Klines getKlines() { return this.get(this.e::getKlines); } @Override public Klines getKlines(Period period) { return this.get(this.e::getKlines, period); } @Override public Klines getKlines(boolean latest) { return this.get(this.e::getKlines, latest); } @Override public Klines getKlines(Period period, boolean latest) { return this.get(this.e::getKlines, period, latest); } @Override public Depth getDepth() { return this.get(this.e::getDepth); } @Override public Depth getDepth(boolean latest) { return this.get(this.e::getDepth, latest); } @Override public Trades getTrades() { return this.get(this.e::getTrades); } @Override public Trades getTrades(boolean latest) { return this.get(this.e::getTrades, latest); } // =================== account ======================= @Override public Balances getBalances() { return this.get(this.e::getBalances); } @Override public Account getAccount() { return this.get(this.e::getAccount); } @Override public Account getAccount(boolean latest) { return this.get(this.e::getAccount, latest); } // =================== trade ======================= @Override public Precisions getPrecisions() { return this.get(this.e::getPrecisions); } @Override public Precision getPrecision() { return this.get(this.e::getPrecision); } @Override public String buyLimit(BigDecimal price, BigDecimal amount) { Exception error = null; try { price = this.e.checkCount(price, false); amount = this.e.checkBase(amount); } catch (Exception e) { error = e; } if (null != error || null == price || null == amount) { this.log.error("{} {} {} buy limit: price: {} amount:{} error: {}", this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), price, amount, error); return null; } LogAction la = LogAction.buyLimit(this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), price, amount); return this.single(this.e::buyLimit, price, amount, la); } @Override public String sellLimit(BigDecimal price, BigDecimal amount) { Exception error = null; try { price = this.e.checkCount(price, true); amount = this.e.checkBase(amount); } catch (Exception e) { error = e; } if (null != error || null == price || null == amount) { this.log.error("{} {} {} sell limit: price: {} amount:{} error: {}", this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), price, amount, error); return null; } LogAction la = LogAction.sellLimit(this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), price, amount); return this.single(this.e::sellLimit, price, amount, la); } @Override public String buyMarket(BigDecimal count) { Exception error = null; try { count = this.e.checkCount(count, false); } catch (Exception e) { error = e; } if (null != error || null == count) { this.log.error("{} {} {} buy market: quote: {} error: {}", this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), count, error); return null; } LogAction la = LogAction.buyMarket(this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), count); return this.single(this.e::buyMarket, count, la); } @Override public String sellMarket(BigDecimal base) { Exception error = null; try { base = this.e.checkBase(base); } catch (Exception e) { error = e; } if (null != error || null == base) { this.log.error("{} {} {} sell market: base: {} error: {}", this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), base, error); return null; } LogAction la = LogAction.sellMarket(this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), base); return this.single(this.e::sellMarket, base, la); } @Override public List<String> multiBuy(List<Row> bids) { Exception error = null; try { bids = this.e.checkRows(bids, false); } catch (Exception e) { error = e; } if (null != error || null == bids || bids.isEmpty()) { this.log.error("{} {} {} multi buy: bids: {} error: {}", this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), bids, error); return null; } LogAction la = LogAction.multiBuy(this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), bids); return this.multi(this.e::multiBuy, bids, la); } @Override public List<String> multiSell(List<Row> asks) { Exception error = null; try { asks = this.e.checkRows(asks, true); } catch (Exception e) { error = e; } if (null != error || null == asks || asks.isEmpty()) { this.log.error("{} {} {} multi sell: asks: {} error: {}", this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), asks, error); return null; } LogAction la = LogAction.multiSell(this.getName(), this.getSymbol(), Seal.seal(this.getAccess()), asks); return this.multi(this.e::multiSell, asks, la); } @Override public boolean cancelOrder(String id) { Boolean result = this.get(this.e::cancelOrder, id); if (null != result) { return result; } return false; } @Override public List<String> cancelOrders(List<String> ids) { return this.get(this.e::cancelOrders, ids); } // =================== order ======================= @Override public Orders getOrders() { return this.get(this.e::getOrders); } @Override public Orders getHistoryOrders() { return this.get(this.e::getHistoryOrders); } @Override public Order getOrder(String id) { return this.get(this.e::getOrder, id); } @Override public OrderDetails getOrderDetails(String id) { return this.get(this.e::getOrderDetails, id); } @Override public OrderDetails getOrderDetailAll() { return this.get(this.e::getOrderDetailAll); } // =================== push ======================= @Override public void setOnTicker(Consumer<Ticker> onTicker) { this.run(this.e::setOnTicker, onTicker); } @Override public void setOnTicker(Consumer<Ticker> onTicker, RateLimit limit) { this.run(this.e::setOnTicker, onTicker, limit); } @Override public void setOnKlines(Consumer<Klines> onKlines) { this.run(this.e::setOnKlines, onKlines); } @Override public void setOnKlines(Consumer<Klines> onKlines, Period period, RateLimit limit) { this.run(this.e::setOnKlines, onKlines, period, limit); } @Override public void setOnDepth(Consumer<Depth> onDepth) { this.run(this.e::setOnDepth, onDepth); } @Override public void setOnDepth(Consumer<Depth> onDepth, RateLimit limit) { this.run(this.e::setOnDepth, onDepth, limit); } @Override public void setOnTrades(Consumer<Trades> onTrades) { this.run(this.e::setOnTrades, onTrades); } @Override public void setOnTrades(Consumer<Trades> onTrades, RateLimit limit) { this.run(this.e::setOnTrades, onTrades, limit); } @Override public void setOnAccount(Consumer<Account> onAccount) { this.run(this.e::setOnAccount, onAccount); } @Override public void setOnOrders(Consumer<Orders> onOrders) { this.run(this.e::setOnOrders, onOrders); } // =================== tools ======================= @Override public String toString() { return "ProxyExchange{" + "e=" + e + '}'; } private void run(Runnable runnable) { try { runnable.run(); } catch (Exception ignored) { } } private <T> void run(Consumer<T> consumer, T t) { try { consumer.accept(t); } catch (Exception ignored) { } } private <T, K> void run(BiConsumer<T, K> consumer, T t, K k) { try { consumer.accept(t, k); } catch (Exception ignored) { } } private <T, U, K> void run(TrConsumer<T, U, K> consumer, T t, U u, K k) { try { consumer.accept(t, u, k); } catch (Exception ignored) { } } private <R> R get(Supplier<R> supplier) { try { return supplier.get(); } catch (Exception ignored) { } return null; } private <T, R> R get(Function<T, R> function, T t) { try { return function.apply(t); } catch (Exception ignored) { } return null; } private <T, K, R> R get(BiFunction<T, K, R> function, T t, K k) { try { return function.apply(t, k); } catch (Exception ignored) { } return null; } private <T, U, K, L, R> R get(FourFunction<T, U, K, L, R> function, T t, U u, K k, L l) { try { return function.apply(t, u, k, l); } catch (Exception ignored) { } return null; } private List<String> multi(Function<List<Row>, List<String>> multi, List<Row> rows, LogAction la) { List<String> ids = this.get(multi, rows); if (null != ids) { la.setIds(new ArrayList<>(ids)); } this.log.info("{} {}", la.getAction(), JSON.toJSONString(la)); return ids; } private String single(Function<BigDecimal, String> single, BigDecimal number, LogAction la) { String id = this.get(single, number); return this.checkId(id, la); } private String checkId(String id, LogAction la) { if (null != id) { la.setId(id); } this.log.info("{} {}", la.getAction(), JSON.toJSONString(la)); return id; } private String single(BiFunction<BigDecimal, BigDecimal, String> single, BigDecimal price, BigDecimal amount, LogAction la) { String id = this.get(single, price, amount); return this.checkId(id, la); } }
13,176
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TrConsumer.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/TrConsumer.java
package cqt.goai.run.exchange; /** * @author GOAi */ @FunctionalInterface public interface TrConsumer<T, U, K> { /** * 接受3个参数 * @param t t * @param u u * @param k k */ void accept(T t, U u, K k); }
244
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BaseExchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/BaseExchange.java
package cqt.goai.run.exchange; import cqt.goai.exchange.ExchangeException; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.util.RateLimit; import cqt.goai.exchange.util.Seal; import cqt.goai.model.enums.Period; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import cqt.goai.run.exchange.model.ModelManager; import lombok.EqualsAndHashCode; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import static dive.common.math.BigDecimalUtil.greater; import static dive.common.math.BigDecimalUtil.less; import static dive.common.util.Util.exist; /** * 基本获取交易所信息类, * - 继承该类可直接调用Market和Trade数据, * - 重载方法可实现主动推送(2种方式,主动注册有推送 和 被重载则推送) * @author GOAi */ @EqualsAndHashCode public class BaseExchange implements Exchange { /** * 日志 */ protected final Logger log; /** * 交易所名 */ protected final ExchangeName name; /** * 币对 */ protected final String symbol; /** * access */ protected final String access; /** * secret */ protected final String secret; /** * 是否可以进行主动推送 */ protected final Supplier<Boolean> ready; /** * 缓存的ticker,主动推送情况下,getTicker就直接返回这个 */ protected ModelManager<Ticker> ticker = new ModelManager<>(RateLimit.second3()); protected ConcurrentHashMap<Period, ModelManager<Klines>> klines = new ConcurrentHashMap<>(); protected ModelManager<Depth> depth = new ModelManager<>(RateLimit.second3()); protected ModelManager<Trades> trades = new ModelManager<>(RateLimit.second3()); protected ModelManager<Account> account = new ModelManager<>(RateLimit.second()); protected ModelManager<Orders> orders = new ModelManager<>(RateLimit.NO); protected Precision precision; BaseExchange(Logger log, ExchangeName name, String symbol, String access, String secret, Supplier<Boolean> ready) { this.log = log; this.name = name; this.symbol = symbol; this.access = access; this.secret = secret; this.ready = ready; } @Override public ExchangeName getExchangeName() { return name; } @Override public String getName() { return name.getName(); } @Override public String getSymbol() { return symbol; } @Override public String getAccess() { return access; } @Override public String getSecret() { return secret; } @Override public Logger getLog() { return log; } @Override public HttpExchange getHttpExchange() { throw new ExchangeException("getHttpExchange is not supported."); } /** * 取消所有订阅 */ @Override public void destroy() { throw new ExchangeException("destroy is not supported."); } /** * 检查目标币精度 * @param count 被检查的值 * @param ceil 是否向上取整 * @return 检查后的值 */ @Override public BigDecimal checkCount(BigDecimal count, boolean ceil) { this.checkPrecision(); if (null == this.precision) { return count; } return this.checkPrecision(count, ceil ? BigDecimal.ROUND_CEILING : BigDecimal.ROUND_FLOOR, this.precision.getMinQuote(), this.precision.getMaxQuote(), this.precision.getQuoteStep(), this.precision.getQuote()); } /** * 检查目标币精度 * @param base 被检查的值 * @return 检查后的值 */ @Override public BigDecimal checkBase(BigDecimal base) { this.checkPrecision(); if (null == this.precision) { return base; } return this.checkPrecision(base, BigDecimal.ROUND_FLOOR, this.precision.getMinBase(), this.precision.getMaxBase(), this.precision.getBaseStep(), this.precision.getBase()); } /** * 检查精度 * @param value 被检查数字 * @param roundingMode 精度不对时处理方式 * @param min 最小值 * @param max 最大值 * @param step 最小递增精度 * @param precision 最小精度 * @return 检查后结果 */ private BigDecimal checkPrecision(BigDecimal value, int roundingMode, BigDecimal min, BigDecimal max, BigDecimal step, Integer precision) { if (null != min && less(value, min)) { String message = String.format("precision is wrong. value is %s but the min require is %s", value, min); log.error(message); throw new ExchangeException(message); } if (null != max && greater(value, max)) { String message = String.format("precision is wrong. value is %s but the max require is %s", value, max); log.error(message); throw new ExchangeException(message); } if (null != step) { BigDecimal times = value.divide(step, 32, BigDecimal.ROUND_HALF_UP).stripTrailingZeros(); int scale = times.scale(); if (0 < scale) { // 没有被整除 times = times.setScale(0, roundingMode); return step.multiply(times); } else { return value; } } if (null != precision) { value = value.setScale(precision, roundingMode); return this.checkPrecision(value, roundingMode, min, max, null, null); } return value; } /** * 本地缓存一份精度数据 */ private void checkPrecision() { if (null == this.precision) { synchronized (HttpExchange.class) { if (null == this.precision) { this.precision = this.getPrecision(); } } } } /** * 精度调整 */ @Override public List<Row> checkRows(List<Row> rows, boolean ceil) { return rows.stream() .map(r -> { BigDecimal price; BigDecimal amount; try { price = this.checkCount(r.getPrice(), ceil); amount = this.checkBase(r.getAmount()); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); return Row.row(null, null); } return Row.row(price, amount); }).filter(r -> exist(r.getPrice(), r.getAmount())) .collect(Collectors.toList()); } // =================== ticker ======================= /** * 获取Ticker */ @Override public final Ticker getTicker() { return this.getTicker(false); } /** * 获取Ticker * @param latest http方式, 允许不是最新的 */ @Override public Ticker getTicker(boolean latest) { throw new ExchangeException("getTicker is not supported. latest:" + latest); } // =================== klines ======================= /** * 获取Klines */ @Override public final Klines getKlines() { return this.getKlines(Period.MIN1, false); } /** * 获取Klines 默认可以取不是最新的 * @param period K线周期 */ @Override public Klines getKlines(Period period) { return this.getKlines(Period.MIN1, false); } /** * 获取Klines 默认周期为MIN1 * @param latest http方式, 允许不是最新的 */ @Override public Klines getKlines(boolean latest) { return this.getKlines(Period.MIN1, latest); } /** * 获取Klines * @param period K线周期 * @param latest http方式, 允许不是最新的 */ @Override public Klines getKlines(Period period, boolean latest) { throw new ExchangeException("getKlines is not supported. latest:" + latest); } // =================== Depth ======================= /** * 获取Depth */ @Override public final Depth getDepth() { return this.getDepth(false); } /** * 获取Depth * @param latest http方式, 允许不是最新的 */ @Override public Depth getDepth(boolean latest) { throw new ExchangeException("getDepth is not supported. latest:" + latest); } // =================== trades ======================= /** * 获取Trades */ @Override public final Trades getTrades() { return this.getTrades(false); } /** * 获取Trades * @param latest http方式, 允许不是最新的 */ @Override public Trades getTrades(boolean latest) { throw new ExchangeException("getTrades is not supported. latest:" + latest); } // =================== account ======================= /** * 获取账户所有余额 */ @Override public Balances getBalances() { throw new ExchangeException("getBalances is not supported."); } /** * 获取Account */ @Override public final Account getAccount() { return this.getAccount(false); } /** * 获取Account * @param latest http方式, 允许不是最新的 */ @Override public Account getAccount(boolean latest) { throw new ExchangeException("getAccount is not supported. latest:" + latest); } // =================== reminder ======================= /** * 获取所有币对精度信息 */ @Override public Precisions getPrecisions() { throw new ExchangeException("getPrecisions is not supported."); } /** * 获取币对精度信息 */ @Override public Precision getPrecision() { throw new ExchangeException("getPrecision is not supported."); } /** * 限价买 * 自动结算精度,价格向下截断,数量向下截断 * @return 订单id */ @Override public String buyLimit(BigDecimal price, BigDecimal amount) { throw new ExchangeException("buyByLimit is not supported."); } /** * 限价卖 * 自动结算精度,价格向上截断,数量向上截断 * @return 订单id */ @Override public String sellLimit(BigDecimal price, BigDecimal amount) { throw new ExchangeException("sellByLimit is not supported."); } /** * 市价买 * 自动结算精度,价格向下截断 * @return 订单id */ @Override public String buyMarket(BigDecimal count) { throw new ExchangeException("buyByMarket is not supported."); } /** * 市价卖 * 自动结算精度,数量向上截断 * @return 订单id */ @Override public String sellMarket(BigDecimal base) { throw new ExchangeException("sellByMarket is not supported."); } /** * 多买 * @param bids 多对买单 * @return 订单id */ @Override public List<String> multiBuy(List<Row> bids) { throw new ExchangeException("multiBuy is not supported."); } /** * 多卖 * @param asks 多对卖单 * @return 订单id */ @Override public List<String> multiSell(List<Row> asks) { throw new ExchangeException("multiSell is not supported."); } /** * 取消单个订单 * @param id 订单id * @return 取消成功与否 */ @Override public boolean cancelOrder(String id) { throw new ExchangeException("cancelOrder is not supported."); } /** * 取消多个订单 * @param ids 多个订单id * @return 成功取消的订单id */ @Override public List<String> cancelOrders(List<String> ids) { throw new ExchangeException("cancelOrders is not supported."); } /** * 获取活跃订单 */ @Override public Orders getOrders() { throw new ExchangeException("getOrders is not supported."); } /** * 获取历史订单 */ @Override public Orders getHistoryOrders() { throw new ExchangeException("getHistoryOrders is not supported."); } /** * 获取指定订单 */ @Override public Order getOrder(String id) { throw new ExchangeException("getOrder is not supported."); } /** * 获取订单成交明细 */ @Override public OrderDetails getOrderDetails(String id) { throw new ExchangeException("getOrderDetails is not supported."); } /** * 获取所有订单成交明细 */ @Override public OrderDetails getOrderDetailAll() { throw new ExchangeException("getOrderDetailAll is not supported."); } // ========================== push =========================== /** * 设置onTicker, 默认无频率限制 * @param onTicker 消费函数 */ @Override public final void setOnTicker(Consumer<Ticker> onTicker) { this.setOnTicker(onTicker, RateLimit.NO); } /** * 设置onTicker * @param onTicker 消费函数 * @param limit 推送频率限制 */ @Override public void setOnTicker(Consumer<Ticker> onTicker, RateLimit limit) { throw new ExchangeException("setOnTicker is not supported."); } /** * 更新本地ticker并推送Ticker */ void onTicker(Ticker ticker, String id) { this.ticker.on(this.ready.get(), ticker, id); } /** * 设置onTicker, 默认1MIN, 频率无频率限制 * @param onKlines 消费函数 */ @Override public final void setOnKlines(Consumer<Klines> onKlines) { this.setOnKlines(onKlines, Period.MIN1, RateLimit.NO); } /** * 设置onTicker * @param onKlines 消费函数 * @param period 推送K线周期 */ @Override public void setOnKlines(Consumer<Klines> onKlines, Period period, RateLimit limit) { throw new ExchangeException("setOnKlines is not supported."); } /** * 更新本地ticker并推送Ticker */ void onKlines(Period period, Klines klines, String id) { if (this.klines.containsKey(period)) { this.klines.get(period).on(this.ready.get(), klines, id); } } /** * 设置onDepth, 默认无频率限制 * @param onDepth 消费函数 */ @Override public final void setOnDepth(Consumer<Depth> onDepth) { this.setOnDepth(onDepth, RateLimit.NO); } /** * 设置onDepth * @param onDepth 消费函数 * @param limit 推送频率限制 */ @Override public void setOnDepth(Consumer<Depth> onDepth, RateLimit limit) { throw new ExchangeException("setOnDepth is not supported."); } /** * 更新本地depth并推送depth */ void onDepth(Depth depth, String id) { this.depth.on(this.ready.get(), depth, id); } /** * 设置onTrades, 默认无频率限制 * @param onTrades 消费函数 */ @Override public final void setOnTrades(Consumer<Trades> onTrades) { this.setOnTrades(onTrades, RateLimit.NO); } /** * 设置onTrades * @param onTrades 消费函数 * @param limit 推送频率限制 */ @Override public void setOnTrades(Consumer<Trades> onTrades, RateLimit limit) { throw new ExchangeException("setOnTrades is not supported."); } /** * 更新本地trades并推送trades */ void onTrades(Trades trades, String id) { this.trades.on(this.ready.get(), trades, id); } /** * 设置onAccount, 默认无频率限制 * @param onAccount 消费函数 */ @Override public void setOnAccount(Consumer<Account> onAccount) { throw new ExchangeException("setOnAccount is not supported."); } /** * 更新本地account并推送account */ void onAccount(Account account, String id) { this.account.on(this.ready.get(), account, id); } /** * 设置onOrders, 默认无频率限制 * @param onOrders 消费函数 */ @Override public void setOnOrders(Consumer<Orders> onOrders) { throw new ExchangeException("setOnOrders is not supported."); } /** * 更新本地account并推送account */ void onOrders(Orders orders, String id) { this.orders.on(this.ready.get(), orders, id); } @Override public String toString() { return "BaseExchange{" + "name='" + this.name + '\'' + ", symbol='" + this.symbol + '\'' + ", access='" + Seal.seal(this.access) + '\'' + ", secret='" + Seal.seal(this.secret) + '\'' + '}'; } }
17,390
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Exchange.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/Exchange.java
package cqt.goai.run.exchange; import cqt.goai.exchange.ExchangeName; import cqt.goai.exchange.http.HttpExchange; import cqt.goai.exchange.util.RateLimit; import cqt.goai.model.enums.Period; import cqt.goai.model.market.*; import cqt.goai.model.trade.*; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.List; import java.util.function.Consumer; /** * 交易所接口 * @author GOAi */ public interface Exchange { /** * 所属交易所信息 * @return 交易所信息 */ ExchangeName getExchangeName(); /** * 交易所名 * @return 交易所名 */ String getName(); /** * 币对 * @return 币对 */ String getSymbol(); /** * access * @return access */ String getAccess(); /** * secret * @return secret */ String getSecret(); /** * 日志 * @return 日志 */ Logger getLog(); /** * 获取http请求对象 方便调用特殊api * @return HttpExchange */ HttpExchange getHttpExchange(); /** * 取消所有订阅 */ void destroy(); /** * 检查价格 * @param count 价格 * @param ceil 取整方向 * @return 调整后 */ BigDecimal checkCount(BigDecimal count, boolean ceil); /** * 检查数量 * @param base 数量 * @return 调整后 */ BigDecimal checkBase(BigDecimal base); /** * 检查多个精度 * @param rows 多个 * @param ceil 取整方向 * @return 调整后 */ List<Row> checkRows(List<Row> rows, boolean ceil); // =================== ticker ======================= /** * 获取Ticker * @return Ticker */ Ticker getTicker(); /** * 获取Ticker * @param latest http方式, false -> 允许不是最新的 true -> 必须最新的 * @return Ticker */ Ticker getTicker(boolean latest); // =================== klines ======================= /** * 获取Klines * @return Klines */ Klines getKlines(); /** * 获取Klines 默认可以取不是最新的 * @param period K线周期 * @return Klines */ Klines getKlines(Period period); /** * 获取Klines 默认周期为MIN1 * @param latest http方式, 允许不是最新的 * @return Klines */ Klines getKlines(boolean latest); /** * 获取Klines * @param period K线周期 * @param latest http方式, 允许不是最新的 * @return Klines */ Klines getKlines(Period period, boolean latest); // =================== Depth ======================= /** * 获取Depth * @return Depth */ Depth getDepth(); /** * 获取Depth * @param latest http方式, 允许不是最新的 * @return Depth */ Depth getDepth(boolean latest); // =================== trades ======================= /** * 获取Trades * @return Trades */ Trades getTrades(); /** * 获取Trades * @param latest http方式, 允许不是最新的 * @return Trades */ Trades getTrades(boolean latest); // =================== account ======================= /** * 获取账户所有余额 * @return Balances */ Balances getBalances(); /** * 获取Account * @return Account */ Account getAccount(); /** * 获取Account * @param latest http方式, 允许不是最新的 * @return Account */ Account getAccount(boolean latest); // =================== trade ======================= /** * 获取所有币对精度信息 * @return Precisions */ Precisions getPrecisions(); /** * 获取币对精度信息 * @return Precision */ Precision getPrecision(); /** * 限价买 * 自动结算精度,价格向下截断,数量向下截断 * @param price 订单价格 * @param amount 订单数量 * @return 订单id */ String buyLimit(BigDecimal price, BigDecimal amount); /** * 限价买 * 自动结算精度,价格向下截断,数量向下截断 * @param price 订单价格 * @param amount 订单数量 * @return 订单id */ default String buyLimit(double price, double amount) { return this.buyLimit(new BigDecimal(price), new BigDecimal(amount)); } /** * 限价卖 * 自动结算精度,价格向上截断,数量向上截断 * @param price 订单价格 * @param amount 订单数量 * @return 订单id */ String sellLimit(BigDecimal price, BigDecimal amount); /** * 限价卖 * 自动结算精度,价格向上截断,数量向上截断 * @param price 订单价格 * @param amount 订单数量 * @return 订单id */ default String sellLimit(double price, double amount) { return this.sellLimit(new BigDecimal(price), new BigDecimal(amount)); } /** * 市价买 * 自动结算精度,价格向下截断 * @param count 订单总价 * @return 订单id */ String buyMarket(BigDecimal count); /** * 市价卖 * 自动结算精度,数量向上截断 * @param base 订单数量 * @return 订单id */ String sellMarket(BigDecimal base); /** * 多买 * @param bids 多对买单 * @return 订单id */ List<String> multiBuy(List<Row> bids); /** * 多卖 * @param asks 多对卖单 * @return 订单id */ List<String> multiSell(List<Row> asks); /** * 取消单个订单 * @param id 订单id * @return 取消成功与否 */ boolean cancelOrder(String id); /** * 取消多个订单 * @param ids 多个订单id * @return 成功取消的订单id */ List<String> cancelOrders(List<String> ids); // =================== order ======================= /** * 获取活跃订单 * @return Orders */ Orders getOrders(); /** * 获取历史订单 * @return Orders */ Orders getHistoryOrders(); /** * 获取历史订单 * @param id 订单id * @return Order */ Order getOrder(String id); /** * 获取订单成交明细 * @param id 订单id * @return OrderDetails */ OrderDetails getOrderDetails(String id); /** * 获取所有订单成交明细 * @return getOrderDetailAll */ OrderDetails getOrderDetailAll(); // =================== push ======================= /** * 设置onTicker, 默认无频率限制 * @param onTicker 消费函数 */ void setOnTicker(Consumer<Ticker> onTicker); /** * 设置onTicker * @param onTicker 消费函数 * @param limit 推送频率限制 */ void setOnTicker(Consumer<Ticker> onTicker, RateLimit limit); /** * 设置onTicker, 默认1MIN, 频率无频率限制 * @param onKlines 消费函数 */ void setOnKlines(Consumer<Klines> onKlines); /** * 设置onTicker * @param onKlines 消费函数 * @param period 推送K线周期 * @param limit 频率限制 */ void setOnKlines(Consumer<Klines> onKlines, Period period, RateLimit limit); /** * 设置onDepth, 默认无频率限制 * @param onDepth 消费函数 */ void setOnDepth(Consumer<Depth> onDepth); /** * 设置onDepth * @param onDepth 消费函数 * @param limit 推送频率限制 */ void setOnDepth(Consumer<Depth> onDepth, RateLimit limit); /** * 设置onTrades, 默认无频率限制 * @param onTrades 消费函数 */ void setOnTrades(Consumer<Trades> onTrades); /** * 设置onTrades * @param onTrades 消费函数 * @param limit 推送频率限制 */ void setOnTrades(Consumer<Trades> onTrades, RateLimit limit); /** * 设置onAccount, 默认无频率限制 * @param onAccount 消费函数 */ void setOnAccount(Consumer<Account> onAccount); /** * 设置onOrders, 默认无频率限制 * @param onOrders 消费函数 */ void setOnOrders(Consumer<Orders> onOrders); /** * 获取Exchange json * @param name 交易所名 * @param symbol 币对 * @param access access * @param secret secret * @return 交易所json */ static String getExchangeJson(String name, String symbol, String access, String secret) { return String.format("{\"name\":\"%s\",\"symbol\":\"%s\",\"access\":\"%s\",\"secret\":\"%s\"}", name, symbol, access, secret); } }
8,781
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BaseExchangeFactory.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/factory/BaseExchangeFactory.java
package cqt.goai.run.exchange.factory; import com.alibaba.fastjson.JSONObject; import cqt.goai.run.exchange.Exchange; import org.slf4j.Logger; import java.util.function.Supplier; /** * @author GOAi */ public abstract class BaseExchangeFactory { /** * Exchange工厂 * Factory Method Pattern 工厂方法模式 * 有多种Exchange类型,不同的工厂产生的Exchange底层实现不一样 * @param proxy 是否包装代理 * @param log 日志 * @param config 配置信息 * @param ready 是否准备好接收推送 * @return Exchange */ public abstract Exchange getExchange(boolean proxy, Logger log, JSONObject config, Supplier<Boolean> ready); }
711
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
LocalExchangeFactory.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/factory/LocalExchangeFactory.java
package cqt.goai.run.exchange.factory; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeName; import cqt.goai.run.exchange.Exchange; import cqt.goai.run.exchange.LocalExchange; import cqt.goai.run.exchange.ProxyExchange; import org.slf4j.Logger; import java.util.function.Supplier; /** * 本地实现Exchange * @author GOAi */ public class LocalExchangeFactory extends BaseExchangeFactory { @Override public Exchange getExchange(boolean proxy, Logger log, JSONObject config, Supplier<Boolean> ready) { Exchange exchange = new LocalExchange(log, ExchangeName.getByName(config.getString("name")), config.getString("symbol"), config.getString("access"), config.getString("secret"), ready); if (proxy) { exchange = new ProxyExchange(exchange); } return exchange; } }
930
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ModelObserver.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/model/ModelObserver.java
package cqt.goai.run.exchange.model; import cqt.goai.exchange.util.RateLimit; import java.util.function.Consumer; /** * 某个具体订阅 * @author GOAi */ public class ModelObserver<T> { /** * 消费函数 */ final Consumer<T> consumer; /** * 频率限制 */ final RateLimit limit; /** * 推送id */ private final String id; public ModelObserver(Consumer<T> consumer, RateLimit limit, String id) { this.consumer = consumer; this.limit = limit; this.id = id; } /** * 接收model * @param model 新的对象 */ void on(T model) { if (this.limit.timeout()) { this.consumer.accept(model); } } public String getId() { return id; } }
797
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
LogAction.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/model/LogAction.java
package cqt.goai.run.exchange.model; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.Action; import cqt.goai.model.market.Row; import lombok.Data; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * @author GOAi */ @Data public class LogAction { private String name; private String symbol; private String access; private Action action; private BigDecimal price; private BigDecimal amount; private BigDecimal quote; private BigDecimal base; private List<Row> rows; private String id; private List<String> ids; private LogAction(String name, String symbol, String access, Action action) { this.name = name; this.symbol = symbol; this.access = access; this.action = action; } private LogAction(String name, String symbol, String access, Action action, BigDecimal price, BigDecimal amount) { this(name, symbol, access, action); this.price = price; this.amount = amount; } public static LogAction buyLimit(String name, String symbol, String access, BigDecimal price, BigDecimal amount) { return new LogAction(name, symbol, access, Action.BUY_LIMIT, price, amount); } public static LogAction sellLimit(String name, String symbol, String access, BigDecimal price, BigDecimal amount) { return new LogAction(name, symbol, access, Action.SELL_LIMIT, price, amount); } public static LogAction buyMarket(String name, String symbol, String access, BigDecimal quote) { LogAction la = new LogAction(name, symbol, access, Action.BUY_MARKET); la.quote = quote; return la; } public static LogAction sellMarket(String name, String symbol, String access, BigDecimal base) { LogAction la = new LogAction(name, symbol, access, Action.BUY_MARKET); la.base = base; return la; } public static LogAction multiBuy(String name, String symbol, String access, List<Row> rows) { LogAction la = new LogAction(name, symbol, access, Action.MULTI_BUY); la.rows = rows; return la; } public static LogAction multiSell(String name, String symbol, String access, List<Row> rows) { LogAction la = new LogAction(name, symbol, access, Action.MULTI_SELL); la.rows = rows; return la; } private static final String NAME = "name"; private static final String SYMBOL = "symbol"; private static final String ACCESS = "access"; private static final String ACTION = "action"; private static final String PRICE = "price"; private static final String AMOUNT = "amount"; private static final String QUOTE = "quote"; private static final String BASE = "base"; private static final String ROWS = "rows"; private static final String ID = "id"; private static final String IDS = "ids"; public static LogAction of(String json) { JSONObject r = JSON.parseObject(json); String name = null; String symbol = null; String access = null; Action action = null; if (r.containsKey(NAME)) { name = r.getString(NAME); } if (r.containsKey(SYMBOL)) { symbol = r.getString(SYMBOL); } if (r.containsKey(ACCESS)) { access = r.getString(ACCESS); } if (r.containsKey(ACTION)) { action = Action.valueOf(r.getString(ACTION)); } LogAction la = new LogAction(name, symbol, access, action); if (r.containsKey(PRICE)) { la.price = r.getBigDecimal(PRICE); } if (r.containsKey(AMOUNT)) { la.amount = r.getBigDecimal(AMOUNT); } if (r.containsKey(QUOTE)) { la.quote = r.getBigDecimal(QUOTE); } if (r.containsKey(BASE)) { la.base = r.getBigDecimal(BASE); } if (r.containsKey(ROWS)) { JSONArray a = r.getJSONArray(ROWS); la.rows = new ArrayList<>(a.size()); for (int i = 0; i < a.size(); i++) { la.rows.add(Row.row(a.getJSONObject(i).getBigDecimal("price"), a.getJSONObject(i).getBigDecimal("amount"))); } } if (r.containsKey(ID)) { la.id = r.getString(ID); } if (r.containsKey(IDS)) { JSONArray array = r.getJSONArray(IDS); la.ids = new ArrayList<>(array.size()); for (int i = 0; i < array.size(); i++) { la.ids.add(array.getString(i)); } } return la; } }
4,831
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
ModelManager.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/model/ModelManager.java
package cqt.goai.run.exchange.model; import cqt.goai.exchange.util.RateLimit; import java.util.concurrent.ConcurrentHashMap; /** * 管理某一类型对象 * @author GOAi */ public class ModelManager<T> { /** * 缓存对象 */ private T model; /** * model是否超时 */ private RateLimit limit; /** * 管理所有需要推送的函数 */ private ConcurrentHashMap<String, ModelObserver<T>> observers = new ConcurrentHashMap<>(); public ModelManager(RateLimit limit) { this.limit = limit; } /** * 推送model * @param ready 是否准备好接收 * @param model model * @param id 推送id */ public void on(boolean ready, T model, String id) { this.update(model); if (ready && this.on() && this.observers.containsKey(id)) { this.observers.get(id).on(model); } } /** * 是否正在推送 */ public boolean on() { return !observers.isEmpty(); } /** * 注册推送 * @param observer 注册者 */ public void observe(ModelObserver<T> observer) { this.observers.put(observer.getId(), observer); } /** * http方式不用推送 * @param model model */ public void update(T model) { this.model = model; this.limit.update(); } public T getModel() { return model; } public RateLimit getLimit() { return limit; } public ConcurrentHashMap<String, ModelObserver<T>> getObservers() { return this.observers; } }
1,611
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TradesObserver.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/exchange/model/TradesObserver.java
package cqt.goai.run.exchange.model; import cqt.goai.exchange.util.RateLimit; import cqt.goai.model.market.Trade; import cqt.goai.model.market.Trades; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Consumer; import java.util.stream.Collectors; /** * @author GOAi */ public class TradesObserver extends ModelObserver<Trades> { /** * 最多缓存个数 */ private int max; /** * 对于有频率限制的推送,不能就此丢弃Trades * 缓存起来,等到能推送的时候一起推 */ private ConcurrentLinkedDeque<Trade> trades; public TradesObserver(Consumer<Trades> consumer, RateLimit limit, String id) { this(consumer, limit, id, 200); } public TradesObserver(Consumer<Trades> consumer, RateLimit limit, String id, int max) { super(consumer, limit, id); if (limit.isLimit()) { trades = new ConcurrentLinkedDeque<>(); this.max = max; } } @Override void on(Trades model) { if (super.limit.timeout()) { if (!this.trades.isEmpty()) { this.addFirst(model); model = new Trades(new ArrayList<>(this.trades)); } this.trades.clear(); super.consumer.accept(model); } else { this.addFirst(model); } } /** * 从前面加入 */ private void addFirst(Trades trades) { List<Trade> ts = trades.getList(); for (int i = ts.size() - 1; 0 <= i; i--) { this.trades.addFirst(ts.get(i)); } // 最多保存200个 while (this.max < this.trades.size()) { this.trades.removeLast(); } } }
1,847
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BaseNotice.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/notice/BaseNotice.java
package cqt.goai.run.notice; import org.slf4j.Logger; /** * 通知对象 * * @author GOAi */ public abstract class BaseNotice { protected final Logger log; final String strategyName; BaseNotice(Logger log, String strategyName) { this.log = log; this.strategyName = strategyName; } /** * 高级通知,发电报 * @param message 消息 */ public abstract void notice(String message); }
453
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Notice.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/notice/Notice.java
package cqt.goai.run.notice; import org.slf4j.Logger; import java.util.Arrays; import java.util.List; /** * 通知管理 * * @author goai */ public class Notice { protected final Logger log; private final List<BaseNotice> list; public Notice(Logger log, List<BaseNotice> notices) { this.log = log; list = notices; } /** * 高级通知,发电报 * @param message 消息 */ public void noticeHigh(String message, NoticeType... noticeTypes) { this.log.info("NOTICE_HIGH {}", message); List<NoticeType> types = Arrays.asList(noticeTypes); list.stream().filter(n -> { if (types.isEmpty()) { return true; } Class c = n.getClass(); return (c == EmailNotice.class && types.contains(NoticeType.Email)) || (c == TelegramNotice.class && types.contains(NoticeType.Telegram)); }).forEach(n -> n.notice(message)); } /** * 低级通知,打日志 * @param message 消息 */ public void noticeLow(String message) { this.log.info("NOTICE_LOW {}", message); } }
1,170
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
EmailNotice.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/notice/EmailNotice.java
package cqt.goai.run.notice; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import java.util.stream.Collectors; /** * 邮箱通知 * * @author goai */ public class EmailNotice extends BaseNotice { private String mailSmtpHost = "smtp.exmail.qq.com"; private String mailSmtpPort = "465"; private String mailSmtpSocketFactoryPort = "465"; private String username; private String password; private String sender = "goai"; private String[] to; public EmailNotice(Logger log, String strategyName, JSONObject config) { super(log, strategyName); mailSmtpHost = config.containsKey("mailSmtpHost") ? config.getString("mailSmtpHost") : mailSmtpHost; mailSmtpPort = config.containsKey("mailSmtpPort") ? config.getString("mailSmtpPort") : mailSmtpPort; mailSmtpSocketFactoryPort = config.containsKey("mailSmtpSocketFactoryPort") ? config.getString("mailSmtpSocketFactoryPort") : mailSmtpSocketFactoryPort; username = config.getString("username"); password = config.getString("password"); sender = config.containsKey("sender") ? config.getString("sender") : sender; String to = config.getString("to"); if (to.startsWith("[")) { this.to = config.getJSONArray("to").stream() .map(Object::toString) .collect(Collectors.toList()) .toArray(new String[]{}); } else { this.to = new String[]{to}; } } private void send(String content) { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.host", mailSmtpHost); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.port", mailSmtpPort); props.setProperty("mail.smtp.timeout", "5000"); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", mailSmtpSocketFactoryPort); props.setProperty("mail.smtp.starttls.enable", "true"); props.setProperty("mail.smtp.starttls.required", "true"); props.setProperty("mail.smtp.ssl.enable", "true"); Session session = Session.getInstance(props); Transport transport = null; try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(username, sender, "UTF-8")); InternetAddress[] internetAddressTo = new InternetAddress[to.length]; for (int i = 0; i < internetAddressTo.length; i++) { internetAddressTo[i] = new InternetAddress(to[i]); } message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo); message.setSubject(strategyName, "UTF-8"); message.setContent(content, "text/plain;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); transport = session.getTransport(); transport.connect(username, password); transport.sendMessage(message, message.getAllRecipients()); } catch (UnsupportedEncodingException | MessagingException e) { e.printStackTrace(); } finally { if (null != transport) { try { transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } } } @Override public void notice(String message) { this.send(message); } }
3,986
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TelegramNotice.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/notice/TelegramNotice.java
package cqt.goai.run.notice; import com.alibaba.fastjson.JSONObject; import cqt.goai.exchange.ExchangeUtil; import dive.http.common.MimeRequest; import org.slf4j.Logger; /** * 通知对象 * * @author GOAi */ public class TelegramNotice extends BaseNotice { private final String token; private final String chatId; public TelegramNotice(Logger log, String strategyName, JSONObject config) { super(log, strategyName); this.token = config.getString("token"); this.chatId = config.getString("chatId"); } /** * 高级通知,发电报 * @param message 消息 */ @Override public void notice(String message) { new MimeRequest.Builder() .url("https://api.telegram.org/bot" + this.token + "/sendMessage") .post() .body("chat_id", this.chatId) .body("text", strategyName + "\n" + message) .body("parse_mode", "HTML") .execute(ExchangeUtil.OKHTTP); } }
1,032
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
NoticeType.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/run/src/main/java/cqt/goai/run/notice/NoticeType.java
package cqt.goai.run.notice; /** * 通知类型 * * @author goai */ public enum NoticeType { /** * 邮箱 */ Email, /** * 电报 */ Telegram }
184
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Main.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/strategy/src/main/java/Main.java
/** * 启动类 * * @author GOAi */ public class Main { public static void main(String[] args) { cqt.goai.run.Application.main(args); } }
160
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Demo.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/strategy/src/main/java/Demo.java
import cqt.goai.model.market.Ticker; import cqt.goai.run.main.RunTask; import cqt.goai.run.notice.NoticeType; import static dive.common.util.Util.exist; /** * 演示类 演示HTTP调用的基础使用方法 * @author GOAi */ public class Demo extends RunTask { /** * 以下配置对应 config.yml 中的配置名 如需使用请先定义好 引擎会自动赋值 */ private String myString; /** * 在这里可以完成策略初始化的工作 */ @Override protected void init() { log.info("myString --> {}",myString); } /** * 默认一秒执行一次该函数 可在配置表中配置loop字段 指定时间 */ @Override protected void loop() { Ticker ticker = e.getTicker(true); log.info("exchange name --> {} ticker last: {}", e.getName(), exist(ticker) ? ticker.getLast() : null); } /** * 程序关闭的时候调用 */ @Override protected void destroy() { log.info(id + " destroy"); } }
1,030
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
PrecisionTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/trade/PrecisionTest.java
package test.trade; import cqt.goai.model.trade.Precision; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; public class PrecisionTest { @Test public void test() { Precision precision = new Precision( "asda\"", "symbol", 2, 3, new BigDecimal("3"), new BigDecimal("5"), new BigDecimal("0.01"), new BigDecimal("0.001"), new BigDecimal("50").stripTrailingZeros(), new BigDecimal("0.01") ); String data = precision.to(); Assert.assertEquals("[\"YXNkYSI=\",\"symbol\",2,3,3,5,0.01,0.001,50,0.01]", data); Assert.assertEquals(precision, Precision.of(data, null)); } }
815
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
DepthTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/DepthTest.java
package test.market; import cqt.goai.model.market.Depth; import cqt.goai.model.market.Row; import cqt.goai.model.market.Rows; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; import java.util.Arrays; public class DepthTest { @Test public void test() { Depth depth = new Depth( 1546426483495L, null, new Rows( Arrays.asList(new Row("231",new BigDecimal("1"), new BigDecimal("2") ), new Row(null, new BigDecimal("0.500"), new BigDecimal("1")))) ); String data = depth.to(); Assert.assertEquals("{\"time\":1546426483495,\"asks\":null,\"bids\":[[\"MjMx\",1,2],[null,0.5,1]]}", data); Depth t = Depth.of(data, null); Assert.assertEquals(depth, t); } }
820
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
KlineTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/KlineTest.java
package test.market; import cqt.goai.model.market.Kline; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; public class KlineTest { @Test public void test() { Kline kline = new Kline( "[123,123]", 1546419093195L, new BigDecimal(1), new BigDecimal(2), null, new BigDecimal(4), new BigDecimal(5) ); String data = kline.to(); Assert.assertEquals("[\"WzEyMywxMjNd\",1546419093195,1,2,null,4,5]", data); Kline c = Kline.of(data, null); Assert.assertEquals(kline, c); } }
622
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
RowTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/RowTest.java
package test.market; import cqt.goai.model.market.Row; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; public class RowTest { @Test public void test() { Row row = new Row("12321,qwr42w3r238987c",new BigDecimal("1.12"),new BigDecimal("1.12")); String data = row.to(); Assert.assertEquals("[\"MTIzMjEscXdyNDJ3M3IyMzg5ODdj\",1.12,1.12]", data); Row r = Row.of(data, null); Assert.assertEquals(row, r); } }
489
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TradeTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/TradeTest.java
package test.market; import cqt.goai.model.enums.Side; import cqt.goai.model.market.Trade; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; public class TradeTest { @Test public void test() { Trade trade = new Trade( "[123,123]", 1546419093195L, "123", Side.BUY, new BigDecimal(1), new BigDecimal(2) ); String data = trade.to(); Assert.assertEquals("[\"WzEyMywxMjNd\",1546419093195,\"123\",\"BUY\",1,2]", data); Trade t = Trade.of(data, null); Assert.assertEquals(trade, t); } }
676
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TradesTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/TradesTest.java
package test.market; import cqt.goai.model.enums.Side; import cqt.goai.model.market.Trade; import cqt.goai.model.market.Trades; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; import java.util.Arrays; public class TradesTest { @Test public void test() { Trades trades = new Trades(Arrays.asList(new Trade( "asd{89as\"", 123L, "123", Side.BUY, new BigDecimal("1"), new BigDecimal("2") ),new Trade( null, 123L, "123", Side.SELL, new BigDecimal("1"), new BigDecimal("2") ))); String data = trades.to(); Assert.assertEquals("[[\"YXNkezg5YXMi\",123,\"123\",\"BUY\",1,2],[null,123,\"123\",\"SELL\",1,2]]", data); Trades ts = Trades.of(data, null); Assert.assertEquals(trades, ts); } }
974
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
KlinesTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/KlinesTest.java
package test.market; import cqt.goai.model.market.Kline; import cqt.goai.model.market.Klines; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; import java.util.Arrays; public class KlinesTest { @Test public void test() { Klines klines = new Klines(Arrays.asList(new Kline( "{123,\"123\"}", 1546422552967L, null, new BigDecimal("1"), new BigDecimal("2"), new BigDecimal("3"), new BigDecimal("0") ),new Kline( null, 1546422552968L, null, new BigDecimal("2"), new BigDecimal("3"), new BigDecimal("4"), new BigDecimal("5") ))); String data = klines.to(); Assert.assertEquals("[[\"ezEyMywiMTIzIn0=\",1546422552967,null,1,2,3,0],[null,1546422552968,null,2,3,4,5]]", data); Klines c = Klines.of(data, null); Assert.assertEquals(klines, c); } }
1,064
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
TickerTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/TickerTest.java
package test.market; import cqt.goai.model.market.Ticker; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; public class TickerTest { @Test public void test() { Ticker ticker = new Ticker( "{123,\"123\"}", 1546419093195L, new BigDecimal(1), new BigDecimal(2), null, new BigDecimal(4), new BigDecimal(5) ); String data = ticker.to(); Assert.assertEquals("{\"data\":\"ezEyMywiMTIzIn0=\",\"time\":1546419093195,\"open\":1,\"high\":2,\"low\":null,\"last\":4,\"volume\":5}", data); Ticker t = Ticker.of(data, null); Assert.assertEquals(ticker, t); } }
759
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
RowsTest.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/test/java/test/market/RowsTest.java
package test.market; import cqt.goai.model.market.Row; import cqt.goai.model.market.Rows; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; import java.util.Arrays; public class RowsTest { @Test public void test() { Rows rows = new Rows(Arrays.asList(new Row( "{123,\"123\"}", new BigDecimal("3"), new BigDecimal("0") ),new Row( null, new BigDecimal("3"), new BigDecimal("0") ))); String data = rows.to(); Assert.assertEquals("[[\"ezEyMywiMTIzIn0=\",3,0],[null,3,0]]", data); Rows rs = Rows.of(data, null); Assert.assertEquals(rows, rs); } }
740
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
To.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/To.java
package cqt.goai.model; /** * 对象转换 * @author GOAi */ public interface To { /** * 转字符串 * @return 字符串 */ String to(); }
169
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Util.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/Util.java
package cqt.goai.model; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import cqt.goai.model.trade.Balance; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; /** * 工具类 * @author GOAi */ public class Util { /** * 去除末尾的0, 保存时应该检查,有些交易所的数据末尾0乱七八糟的,不如都不要 * @param number 待结尾数字 * @return 结尾后数字 */ public static BigDecimal strip(BigDecimal number) { return null != number ? new BigDecimal(number.stripTrailingZeros().toPlainString()) : null; } /** * 处理Long数据 */ public static String to(Long time) { if (null == time) { return "null"; } return String.valueOf(time); } /** * 处理BigDecimal数据 */ public static String to(BigDecimal number) { if (null == number) { return "null"; } return number.toPlainString(); } /** * 处理String数据 */ public static String to(String content) { if (null == content) { return "null"; } return '\"' + content + '\"'; } /** * 处理ModelList数据 */ public static String to(BaseModelList list) { if (null == list) { return "null"; } return list.to(); } /** * 处理枚举数据 */ public static String to(Enum e) { if (null == e) { return "null"; } return '\"' + e.name() + '\"'; } /** * 处理整型数据 */ public static String to(Integer number) { if (null == number) { return "null"; } return String.valueOf(number); } /** * 处理Balance数据 */ public static String to(Balance balance) { if (null == balance) { return "null"; } return balance.to(); } /** * list 转换字符串数组 * @param list list * @param <E> 元素类型 * @return 字符串数组 */ public static <E extends To> String to(List<E> list) { if (null == list) { return null; } if (0 == list.size()) { return "[]"; } return '[' + list.stream() .map(To::to) .collect(Collectors.joining(",")) + ']'; } /** * data数据传输时变成Base64编码 * @param data 原始数据 * @return Base64编码 */ public static String encode(String data) { return null == data || "null".equals(data) ? "null" : ('\"' + Base64.getEncoder().encodeToString(data.getBytes()) + '\"'); } /** * data数据存入时解码 * @param data Base64编码 * @return 原始数据 */ public static String decode(String data) { return null == data || "null".equals(data) ? null : new String(Base64.getDecoder().decode(data.getBytes())); } /** * 单个值还原 * @param data 文本数据 * @param of 转化方法 * @param <E> 结果对象 * @return 转化结果 */ public static <E> E of(String data, Function<String, E> of) { return null == data || "null".equals(data) ? null : of.apply(data); } /** * 可能组合成ModelList的元素,在上级就已经转变成JSONArray了 * 本身的of(String data)不能使用,则重载个of(JSONArray r)方法 * @param data 数组数据 * @param of 解析JSONArray对象 * @param log 错误输出 * @return 解析结果 */ public static <T> T of(String data, Function<JSONArray, T> of, Logger log) { try { return of.apply(JSON.parseArray(data)); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); log.error("of error -> {}", data); } return null; } /** * 解析list数据并添加到ModelList对象中 * @param data 原始数据 * @param fresh 构造新的实例 * @param of JSONArray解析of * @param log 错误输出 * @param <E> 元素对象 * @return 解析成功与否 */ public static <E, T> T of(String data, Function<List<E>, T> fresh, Function<JSONArray, E> of, Logger log) { try { JSONArray r = JSON.parseArray(data); return Util.of(r, fresh, of, log); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); log.error("of error -> {}", data); } return null; } /** * 解析JSONArray数据并添加到ModelList对象中 * @param r JSONArray数据 * @param fresh 构造新的实例 * @param of JSONArray解析of * @param log 错误输出 * @param <E> 元素对象 * @return 解析成功与否 */ public static <E, T> T of(JSONArray r, Function<List<E>, T> fresh, Function<JSONArray, E> of, Logger log) { if (null == r) { return null; } try { List<E> list = new ArrayList<>(r.size()); for (int i = 0; i < r.size(); i++) { list.add(of.apply(r.getJSONArray(i))); } return fresh.apply(list); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); log.error("of error -> {}", r); } return null; } }
5,832
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
BaseModelList.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/BaseModelList.java
package cqt.goai.model; import lombok.EqualsAndHashCode; import lombok.Getter; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; /** * 处理list情况 * * 封装基本list,额外添加 to 和 of 方法 * Iterator Pattern 迭代器模式 * * @author GOAi * @param <E> list的对象 */ @Getter @EqualsAndHashCode public abstract class BaseModelList<E extends To> implements To, Iterable<E>, Serializable { private static final long serialVersionUID = 1L; /** * 底层数据 */ private List<E> list; /** * 构造器传入list对象,可选择ArrayList或LinkedList,看情况选择 * @param list list */ public BaseModelList(List<E> list) { this.list = list; } @Override public String to() { return Util.to(this.list); } public int size() { return this.list.size(); } public boolean isEmpty() { return this.list.isEmpty(); } public boolean contains(E e) { return this.list.contains(e); } @Override public Iterator<E> iterator() { return this.list.iterator(); } public Object[] toArray() { return this.list.toArray(); } public E[] toArray(E[] a) { return this.list.toArray(a); } public E get(int index) { return this.list.get(index); } public E remove(int index) { return this.list.remove(index); } public int indexOf(E e) { return this.list.indexOf(e); } public int lastIndexOf(E e) { return this.list.lastIndexOf(e); } public Stream<E> stream() { return this.list.stream(); } public Stream<E> parallelStream() { return this.list.parallelStream(); } public E first() { return this.get(0); } public E last() { return this.get(this.size() - 1); } public E getFirst() { return this.first(); } public E getLast() { return this.last(); } public void add(E e) { this.list.add(e); } public void set(List<E> eList) { this.list = eList; } @Override public String toString() { return list.toString(); } }
2,316
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Account.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/Account.java
package cqt.goai.model.trade; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import cqt.goai.model.To; import cqt.goai.model.Util; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.slf4j.Logger; import java.io.Serializable; import java.math.BigDecimal; import java.util.Objects; /** * 某个币对账户信息 * @author GOAi */ @Getter @ToString @EqualsAndHashCode public class Account implements To, Serializable { private static final long serialVersionUID = -81334812598889084L; /** * 时间戳 */ private final Long time; /** * 目标货币 BTC_USD 中的 BTC, 用USD买卖BTC */ private final Balance base; /** * 计价货币 BTC_USD 中的 USD */ private final Balance quote; public Account(Long time, Balance base, Balance quote) { this.time = time; this.base = base; this.quote = quote; } public BigDecimal getBaseFree() { Objects.requireNonNull(base); return this.base.getFree(); } public BigDecimal getBaseUsed() { Objects.requireNonNull(base); return this.base.getUsed(); } public BigDecimal getQuoteFree() { Objects.requireNonNull(quote); return this.quote.getFree(); } public BigDecimal getQuoteUsed() { Objects.requireNonNull(quote); return this.quote.getUsed(); } public double baseFree() { Objects.requireNonNull(base); return this.base.free(); } public double baseUsed() { Objects.requireNonNull(base); return this.base.used(); } public double quoteFree() { Objects.requireNonNull(quote); return this.quote.free(); } public double quoteUsed() { Objects.requireNonNull(quote); return this.quote.used(); } @Override public String to() { return '{' + "\"time\":" + Util.to(this.time) + ",\"base\":" + Util.to(this.base) + ",\"quote\":" + Util.to(this.quote) + '}'; } public static Account of(String data, Logger log) { try { JSONObject r = JSON.parseObject(data); return new Account( r.getLong("time"), Balance.of(r.getJSONArray("base")), Balance.of(r.getJSONArray("quote"))); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); log.error("of error -> {}", data); } return null; } }
2,632
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Precision.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/Precision.java
package cqt.goai.model.trade; import com.alibaba.fastjson.JSONArray; import cqt.goai.model.To; import cqt.goai.model.Util; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.slf4j.Logger; import java.io.Serializable; import java.math.BigDecimal; import java.util.Objects; /** * 某交易币对的精度 * @author GOAi */ @Getter @ToString @EqualsAndHashCode public class Precision implements To, Serializable { private static final long serialVersionUID = -5822155062030969112L; /** * 交易所返回的原始数据, 防止有些用户需要一些特殊的数据 */ private final String data; /** * 币对 */ private final String symbol; /** * 交易时币精度,amount */ private final Integer base; /** * 计价货币精度,price BTC/USD 1btc->6000usd 所以数数数的是usd,也就是写price的位置的精度 */ private final Integer quote; /** * 最小币步长 */ private final BigDecimal baseStep; /** * 最小价格步长 */ private final BigDecimal quoteStep; /** * 最小买卖数量 */ private final BigDecimal minBase; /** * 最小买价格 */ private final BigDecimal minQuote; /** * 最大买卖数量 */ private final BigDecimal maxBase; /** * 最大买价格 */ private final BigDecimal maxQuote; public Precision(String data, String symbol, Integer base, Integer quote, BigDecimal baseStep, BigDecimal quoteStep, BigDecimal minBase, BigDecimal minQuote, BigDecimal maxBase, BigDecimal maxQuote) { this.data = data; this.symbol = symbol; this.base = base; this.quote = quote; this.baseStep = Util.strip(baseStep); this.quoteStep = Util.strip(quoteStep); this.minBase = Util.strip(minBase); this.minQuote = Util.strip(minQuote); this.maxBase = Util.strip(maxBase); this.maxQuote = Util.strip(maxQuote); } @Override public String to() { return '[' + Util.encode(this.data) + "," + Util.to(this.symbol) + "," + Util.to(this.base) + "," + Util.to(this.quote) + "," + Util.to(this.baseStep) + "," + Util.to(this.quoteStep) + "," + Util.to(this.minBase) + "," + Util.to(this.minQuote) + "," + Util.to(this.maxBase) + "," + Util.to(this.maxQuote) + ']'; } public double baseStep() { Objects.requireNonNull(this.baseStep); return this.baseStep.doubleValue(); } public double quoteStep() { Objects.requireNonNull(this.quoteStep); return this.quoteStep.doubleValue(); } public double minBase() { Objects.requireNonNull(this.minBase); return this.minBase.doubleValue(); } public double minQuote() { Objects.requireNonNull(this.minQuote); return this.minQuote.doubleValue(); } public double maxBase() { Objects.requireNonNull(this.maxBase); return this.maxBase.doubleValue(); } public double maxQuote() { Objects.requireNonNull(this.maxQuote); return this.maxQuote.doubleValue(); } public static Precision of(String data, Logger log) { return Util.of(data, Precision::of, log); } static Precision of(JSONArray r) { return new Precision( Util.decode(r.getString(0)), r.getString(1), r.getInteger(2), r.getInteger(3), r.getBigDecimal(4), r.getBigDecimal(5), r.getBigDecimal(6), r.getBigDecimal(7), r.getBigDecimal(8), r.getBigDecimal(9)); } }
4,009
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Orders.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/Orders.java
package cqt.goai.model.trade; import cqt.goai.model.BaseModelList; import cqt.goai.model.Util; import org.slf4j.Logger; import java.io.Serializable; import java.util.List; /** * 多笔订单 * @author GOAi */ public class Orders extends BaseModelList<Order> implements Serializable { private static final long serialVersionUID = 3062332528451320335L; public Orders(List<Order> list) { super(list); } public static Orders of(String data, Logger log) { return Util.of(data, Orders::new, Order::of, log); } @Override public String toString() { return "Orders" + super.toString(); } }
648
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Balance.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/Balance.java
package cqt.goai.model.trade; import com.alibaba.fastjson.JSONArray; import cqt.goai.model.To; import cqt.goai.model.Util; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.slf4j.Logger; import java.io.Serializable; import java.math.BigDecimal; import java.util.Objects; /** * 某个币的余额 * @author GOAi */ @Getter @ToString @EqualsAndHashCode public class Balance implements To, Serializable { private static final long serialVersionUID = -8006911245239428396L; /** * 交易所返回的原始数据, 防止有些用户需要一些特殊的数据 */ private final String data; /** * 币的名称 BTC USD 等 */ private final String currency; /** * 可用数量 */ private final BigDecimal free; /** * 冻结数量 */ private final BigDecimal used; public Balance(String data, String currency, BigDecimal free, BigDecimal used) { this.data = data; this.currency = currency; this.free = Util.strip(free); this.used = Util.strip(used); } @Override public String to() { return '[' + Util.encode(data) + "," + Util.to(currency) + "," + Util.to(free) + "," + Util.to(used) + ']'; } public double free() { Objects.requireNonNull(this.free); return this.free.doubleValue(); } public double used() { Objects.requireNonNull(this.used); return this.used.doubleValue(); } public static Balance of(String data, Logger log) { return Util.of(data, Balance::of, log); } static Balance of(JSONArray r) { return new Balance( Util.decode(r.getString(0)), r.getString(1), r.getBigDecimal(2), r.getBigDecimal(3)); } }
1,921
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
OrderDetail.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/OrderDetail.java
package cqt.goai.model.trade; import com.alibaba.fastjson.JSONArray; import cqt.goai.model.To; import cqt.goai.model.Util; import cqt.goai.model.enums.Side; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.slf4j.Logger; import java.io.Serializable; import java.math.BigDecimal; import java.util.Objects; /** * 某笔订单的一条成交明细记录 * @author GOAi */ @Getter @ToString @EqualsAndHashCode public class OrderDetail implements To, Serializable { private static final long serialVersionUID = 8135946558399552447L; /** * 交易所返回的原始数据, 防止有些用户需要一些特殊的数据 */ private final String data; /** * 时间戳 */ private final Long time; /** * 订单id */ private final String orderId; /** * 成交明细id */ private final String detailId; /** * 成交价格 */ private final BigDecimal price; /** * 成交数量 */ private final BigDecimal amount; /** * 手续费 */ private final BigDecimal fee; /** * 手续费货币 */ private final String feeCurrency; /** * 买卖方向 */ private final Side side; public OrderDetail(String data, Long time, String orderId, String detailId, BigDecimal price, BigDecimal amount, BigDecimal fee, String feeCurrency) { this.data = data; this.time = time; this.orderId = orderId; this.detailId = detailId; this.price = Util.strip(price); this.amount = Util.strip(amount); this.fee = Util.strip(fee); this.feeCurrency = feeCurrency; this.side = null; } public OrderDetail(String data, Long time, String orderId, String detailId, BigDecimal price, BigDecimal amount, BigDecimal fee, String feeCurrency, Side side) { this.data = data; this.time = time; this.orderId = orderId; this.detailId = detailId; this.price = Util.strip(price); this.amount = Util.strip(amount); this.fee = Util.strip(fee); this.feeCurrency = feeCurrency; this.side = side; } @Override public String to() { return '[' + Util.encode(this.data) + "," + Util.to(this.time) + "," + Util.to(this.orderId) + "," + Util.to(this.detailId) + "," + Util.to(this.price) + "," + Util.to(this.amount) + "," + Util.to(this.fee) + "," + Util.to(this.feeCurrency) + "," + Util.to(this.side) + ']'; } public double price() { Objects.requireNonNull(this.price); return this.price.doubleValue(); } public double amount() { Objects.requireNonNull(this.amount); return this.amount.doubleValue(); } public double fee() { Objects.requireNonNull(this.fee); return this.fee.doubleValue(); } public static OrderDetail of(String data, Logger log) { return Util.of(data, OrderDetail::of, log); } static OrderDetail of(JSONArray r) { return new OrderDetail (Util.decode(r.getString(0)), r.getLong(1), r.getString(2), r.getString(3), r.getBigDecimal(4), r.getBigDecimal(5), r.getBigDecimal(6), r.getString(7), Util.of(r.getString(8), Side::valueOf)); } }
3,708
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
OrderDetails.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/OrderDetails.java
package cqt.goai.model.trade; import cqt.goai.model.BaseModelList; import cqt.goai.model.Util; import org.slf4j.Logger; import java.io.Serializable; import java.util.List; /** * 多个订单成交明细记录 * @author GOAi */ public class OrderDetails extends BaseModelList<OrderDetail> implements Serializable { private static final long serialVersionUID = -5883032867443051561L; public OrderDetails(List<OrderDetail> list) { super(list); } public static OrderDetails of(String data, Logger log) { return Util.of(data, OrderDetails::new, OrderDetail::of, log); } @Override public String toString() { return "OrderDetails" + super.toString(); } }
715
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Order.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/Order.java
package cqt.goai.model.trade; import com.alibaba.fastjson.JSONArray; import cqt.goai.model.To; import cqt.goai.model.Util; import cqt.goai.model.enums.Side; import cqt.goai.model.enums.State; import cqt.goai.model.enums.Type; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.slf4j.Logger; import java.io.Serializable; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Objects; import static java.math.BigDecimal.ZERO; /** * 订单 * @author GOAi */ @Getter @ToString @EqualsAndHashCode public class Order implements To, Serializable { private static final long serialVersionUID = -298726083025069628L; /** * 交易所返回的原始数据, 防止有些用户需要一些特殊的数据 */ private final String data; /** * 时间戳 */ private final Long time; /** * 订单id */ private final String id; /** * 买卖方向 */ private final Side side; /** * 订单类型 */ private final Type type; /** * 订单状态 */ private final State state; /** * 下单价格 */ private final BigDecimal price; /** * 下单数量 */ private final BigDecimal amount; /** * 成交数量 */ private final BigDecimal deal; /** * 成交均价 */ private BigDecimal average; public Order(String data, Long time, String id, Side side, Type type, State state, BigDecimal price, BigDecimal amount, BigDecimal deal, BigDecimal average) { this.data = data; this.time = time; this.id = id; this.side = side; this.type = type; this.state = state; this.price = Util.strip(price); this.amount = Util.strip(amount); this.deal = Util.strip(deal); this.average = Util.strip(average); } @Override public String to() { return '[' + Util.encode(data) + ',' + Util.to(time) + ',' + Util.to(id) + ',' + Util.to(side) + ',' + Util.to(type) + ',' + Util.to(state) + ',' + Util.to(price) + ',' + Util.to(amount) + ',' + Util.to(deal) + ',' + Util.to(average) + ']'; } public double price() { Objects.requireNonNull(this.price); return this.price.doubleValue(); } public double amount() { Objects.requireNonNull(this.amount); return this.amount.doubleValue(); } public double deal() { Objects.requireNonNull(this.deal); return this.deal.doubleValue(); } public double average() { Objects.requireNonNull(this.average); return this.average.doubleValue(); } public static Order of(String data, Logger log) { return Util.of(data, Order::of, log); } static Order of(JSONArray r) { return new Order( Util.decode(r.getString(0)), r.getLong(1), r.getString(2), Util.of(r.getString(3), Side::valueOf), Util.of(r.getString(4), Type::valueOf), Util.of(r.getString(5), State::valueOf), r.getBigDecimal(6), r.getBigDecimal(7), r.getBigDecimal(8), r.getBigDecimal(9)); } /** * 是否活跃订单 * @return 是否活跃订单 */ public boolean alive() { return this.state == State.SUBMIT || this.state == State.PARTIAL; } /** * 是否有成交 * @return 是否有成交 */ public boolean isDeal() { return this.state == State.FILLED || this.state == State.UNDONE; } /** * 成交总价 * @return 成交总价 */ public BigDecimal dealVolume() { return null == this.average ? ZERO : this.deal.multiply(this.average); } private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); public String simple() { return "Order{" + "time='" + LocalDateTime .ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()) .format(DTF) + '\'' + ", id='" + id + '\'' + ", side=" + side + ", type=" + type + ", state=" + state + ", price=" + price + ", amount=" + amount + ", deal=" + deal + ", average=" + average + '}'; } public boolean isSell() { return this.side == Side.SELL; } public boolean isBuy() { return this.side == Side.BUY; } }
4,932
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Balances.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/Balances.java
package cqt.goai.model.trade; import cqt.goai.model.BaseModelList; import cqt.goai.model.Util; import org.slf4j.Logger; import java.io.Serializable; import java.util.List; /** * 账户下所有币余额信息 * @author GOAi */ public class Balances extends BaseModelList<Balance> implements Serializable { private static final long serialVersionUID = -58830328674451561L; public Balances(List<Balance> list) { super(list); } public static Balances of(String data, Logger log) { return Util.of(data, Balances::new, Balance::of, log); } @Override public String toString() { return "Balances" + super.toString(); } }
681
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Precisions.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/trade/Precisions.java
package cqt.goai.model.trade; import cqt.goai.model.BaseModelList; import cqt.goai.model.Util; import org.slf4j.Logger; import java.io.Serializable; import java.util.List; /** * @author GOAi */ public class Precisions extends BaseModelList<Precision> implements Serializable { private static final long serialVersionUID = 6672027458716855352L; public Precisions(List<Precision> list) { super(list); } public static Precisions of(String data, Logger log) { return Util.of(data, Precisions::new, Precision::of, log); } @Override public String toString() { return "Precisions" + super.toString(); } }
664
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
Side.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/enums/Side.java
package cqt.goai.model.enums; /** * 订单方向 * @author GOAi */ public enum Side { // 买 BUY, // 卖 SELL, }
133
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z
State.java
/FileExtraction/Java_unseen/goaiquant_GOAi/engine/model/src/main/java/cqt/goai/model/enums/State.java
package cqt.goai.model.enums; /** * 订单状态 * @author GOAi */ public enum State { // 已提交 SUBMIT, // 已成交 FILLED, // 已取消 CANCEL, // 部分成交 PARTIAL, // 部分成交后取消 UNDONE, }
254
Java
.java
goaiquant/GOAi
63
31
0
2019-02-25T10:14:13Z
2019-12-10T13:02:33Z