Initial Commit

This commit is contained in:
Ziver Koc 2021-02-25 23:31:31 +01:00
commit 265d54a484
36 changed files with 109235 additions and 0 deletions

14
.gitignore vendored Normal file
View file

@ -0,0 +1,14 @@
### Trader files
trader.conf
### virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Intellij
.idea/
### Gradle
build/
bin/
target/
.gradle/

22
build.gradle Normal file
View file

@ -0,0 +1,22 @@
plugins {
id 'java'
}
group 'se.koc.trader'
version '0.0-SNAPSHOT'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation("se.koc:zutil:1.0.0-SNAPSHOT")
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}
test {
useJUnitPlatform()
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
gradlew vendored Normal file
View file

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View file

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
settings.gradle Normal file
View file

@ -0,0 +1,2 @@
rootProject.name = 'Trader'

View file

@ -0,0 +1,210 @@
package se.koc.trader;
import zutil.ObjectUtil;
import zutil.db.DBConnection;
import zutil.db.DBUpgradeHandler;
import zutil.db.SQLResultHandler;
import zutil.db.handler.PropertiesSQLResult;
import zutil.io.file.FileUtil;
import zutil.log.LogUtil;
import zutil.ui.UserMessageManager;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Static context of the application
*/
public class TraderContext {
private static final Logger logger = LogUtil.getLogger();
private static final String CONF_FILE = "trader.conf";
private static final String DB_FILE = "trader.db";
private static final String DEFAULT_DB_FILE = "/resource/trader-default.db";
public static final String PROPERTY_DB_VERSION = "trader.db_version";
public static final String PROPERTY_HTTP_PORT = "trader.http_port";
public static final String RESOURCE_ROOT;
static {
if (FileUtil.find("build/resources/") != null)
RESOURCE_ROOT = "build/resources";
else if (FileUtil.find("resource/resource/") != null)
RESOURCE_ROOT = "resource";
else
RESOURCE_ROOT = ".";
}
public static final String RESOURCE_WEB_ROOT = RESOURCE_ROOT + "/web";
private static DBConnection db;
private static UserMessageManager messageManager = new UserMessageManager();
private static Properties fileConf = new Properties();
private static Properties dbConf = new Properties();
public static void initialize(){
try {
// Read conf
if (FileUtil.find(CONF_FILE) != null) {
FileReader in = new FileReader(CONF_FILE);
fileConf.load(in);
in.close();
} else {
logger.info("No hal.conf file found");
}
if (FileUtil.find(DEFAULT_DB_FILE) == null){
logger.severe("Unable to find default DB: " + DEFAULT_DB_FILE);
System.exit(1);
}
// Init DB
File dbFile = FileUtil.find(DB_FILE);
db = new DBConnection(DBConnection.DBMS.SQLite, DB_FILE);
if(dbFile == null){
logger.info("No database file found, creating new DB...");
} else {
dbConf = db.exec("SELECT * FROM conf", new PropertiesSQLResult());
}
// Upgrade DB needed?
DBConnection referenceDB = new DBConnection(DBConnection.DBMS.SQLite, DEFAULT_DB_FILE);
Properties defaultDBConf =
referenceDB.exec("SELECT * FROM conf", new PropertiesSQLResult());
// Check DB version
final int defaultDBVersion = Integer.parseInt(defaultDBConf.getProperty(PROPERTY_DB_VERSION));
final int dbVersion = (dbConf.getProperty(PROPERTY_DB_VERSION) != null ?
Integer.parseInt(dbConf.getProperty(PROPERTY_DB_VERSION)) :
-1);
logger.info("DB version: "+ dbVersion);
if(defaultDBVersion > dbVersion ) {
logger.info("Starting DB upgrade from v" + dbVersion + " to v" + defaultDBVersion + "...");
if(dbFile != null){
File backupDB = FileUtil.getNextFile(dbFile);
logger.fine("Backing up DB to: "+ backupDB);
FileUtil.copy(dbFile, backupDB);
}
logger.fine(String.format("Upgrading DB (from: v%s, to: v%s)...", dbVersion, defaultDBVersion));
final DBUpgradeHandler handler = new DBUpgradeHandler(referenceDB);
handler.addIgnoredTable("db_version_history");
handler.addIgnoredTable("sqlite_sequence"); // sqlite internal
handler.setTargetDB(db);
logger.fine("Performing pre-upgrade activities");
// Read upgrade path preferences from the reference database
referenceDB.exec("SELECT * FROM db_version_history"
+ " WHERE db_version <= " + defaultDBVersion
+ " AND db_version > " + dbVersion,
new SQLResultHandler<Object>() {
@Override
public Object handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
while(result.next()){
if(result.getBoolean("force_upgrade")){
logger.fine("Forced upgrade enabled");
handler.setForcedDBUpgrade(true); //set to true if any of the intermediate db version requires it.
}
}
return null;
}
});
handler.upgrade();
logger.info("DB upgrade done");
setProperty(PROPERTY_DB_VERSION, defaultDBConf.getProperty(PROPERTY_DB_VERSION));
}
referenceDB.close();
} catch (Exception e){
throw new RuntimeException(e);
}
}
public static Map<String,String> getProperties() {
HashMap map = new HashMap();
map.putAll(dbConf);
map.putAll(fileConf);
return map;
}
public static boolean containsProperty(String key) {
return !ObjectUtil.isEmpty(getStringProperty(key));
}
public static String getStringProperty(String key){
String value = null;
if (fileConf != null)
value = fileConf.getProperty(key);
if (dbConf != null && value == null)
value = dbConf.getProperty(key);
return value;
}
public static String getStringProperty(String key, String defaultValue){
if (!containsProperty(key))
return defaultValue;
return getStringProperty(key);
}
public static int getIntegerProperty(String key){
String value = getStringProperty(key);
if (getStringProperty(key) == null)
return 0;
return Integer.parseInt(value);
}
public static int getIntegerProperty(String key, int defaultValue){
if (!containsProperty(key))
return defaultValue;
return getIntegerProperty(key);
}
public static boolean getBooleanProperty(String key) {
return Boolean.parseBoolean(getStringProperty(key));
}
public static boolean getBooleanProperty(String key, boolean defaultValue) {
if (!containsProperty(key))
return defaultValue;
return getBooleanProperty(key);
}
public static void setProperty(String key, String value) throws SQLException {
PreparedStatement stmt = db.getPreparedStatement("REPLACE INTO conf (key, value) VALUES (?, ?)");
stmt.setObject(1, key);
stmt.setObject(2, value);
DBConnection.exec(stmt);
dbConf.setProperty(key, value);
}
public static DBConnection getDB(){
return db;
}
/**
* For testing purposes.
*/
public static void setDB(DBConnection db){
db = db;
}
public static UserMessageManager getMessageManager() {
return messageManager;
}
}

View file

@ -0,0 +1,96 @@
package se.koc.trader;
import se.koc.trader.api.AlertEndpoint;
import se.koc.trader.struct.PluginConfig;
import se.koc.trader.web.TraderPage;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;
import zutil.log.LogUtil;
import zutil.net.http.HttpServer;
import zutil.net.http.page.HttpFilePage;
import zutil.net.http.page.HttpRedirectPage;
import zutil.plugin.PluginData;
import zutil.plugin.PluginManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Logger;
public class TraderServer {
private static final Logger logger = LogUtil.getLogger();
private static PluginManager pluginManager;
private static ScheduledExecutorService daemonExecutor;
private static HttpServer http;
public static void main(String[] args) throws SQLException {
// init logging
LogUtil.readConfiguration("logging.properties");
// Init DB and other things
TraderContext.initialize();
logger.info("Working directory: " + FileUtil.find(".").getAbsolutePath());
// init variables
pluginManager = new PluginManager();
daemonExecutor = Executors.newScheduledThreadPool(1); // We set only one thread for easier troubleshooting
http = new HttpServer(TraderContext.getIntegerProperty(TraderContext.PROPERTY_HTTP_PORT));
DBConnection db = TraderContext.getDB();
// ------------------------------------
// Initialize Plugins
// ------------------------------------
logger.info("Looking for plugins.");
// Disable plugins based on settings
for (PluginData plugin : getAllPlugins()) {
PluginConfig pluginConfig = PluginConfig.getPluginConfig(db, plugin.getName());
if (pluginConfig != null && !pluginConfig.isEnabled() && !plugin.getName().equals("Hal-Core")) {
logger.info("Disabling plugin '" + plugin.getName() + "'.");
plugin.setEnabled(false);
}
}
// ------------------------------------
// Init http server
// ------------------------------------
logger.info("Initializing HTTP Server.");
TraderPage.getRootNav().createSubNav("Sensors");
TraderPage.getRootNav().createSubNav("Events").setWeight(100);
TraderPage.getRootNav().createSubNav("Settings").setWeight(200);
http.setDefaultPage(new HttpFilePage(FileUtil.find(TraderContext.RESOURCE_WEB_ROOT)));
http.setPage("/", new HttpRedirectPage("/map"));
http.setPage(AlertEndpoint.getInstance().getPath(), AlertEndpoint.getInstance());
for (Iterator<TraderPage> it = pluginManager.getSingletonIterator(TraderPage.class); it.hasNext(); )
registerPage(it.next());
for (Iterator<TraderPage> it = pluginManager.getSingletonIterator(TraderPage.class); it.hasNext(); )
registerPage(it.next());
http.start();
}
public static List<PluginData> getEnabledPlugins() {
return pluginManager.toArray();
}
public static List<PluginData> getAllPlugins() {
return pluginManager.toArrayAll();
}
public static void registerPage(TraderPage page){
http.setPage(page.getId(), page);
}
}

View file

@ -0,0 +1,29 @@
package se.koc.trader.api;
import zutil.parser.DataNode;
import java.util.Map;
public class AlertEndpoint extends TraderAPI {
private static final String API_PATH = "/api/alert";
private static AlertEndpoint instance;
private AlertEndpoint() {
super(API_PATH);
}
@Override
protected DataNode jsonRespond(Map<String, Object> session, Map<String, String> cookie, Map<String, String> request) throws Exception {
return null;
}
public static AlertEndpoint getInstance() {
if (instance == null)
instance = new AlertEndpoint();
return instance;
}
}

View file

@ -0,0 +1,22 @@
package se.koc.trader.api;
import se.koc.trader.TraderContext;
import se.koc.trader.web.TraderPage;
import zutil.parser.DataNode;
import zutil.parser.Templator;
import java.util.Map;
public class BotEndpoint extends TraderAPI {
private static final String API_PATH = "/api/bot/.*";
public BotEndpoint() {
super(API_PATH);
}
@Override
protected DataNode jsonRespond(Map<String, Object> session, Map<String, String> cookie, Map<String, String> request) throws Exception {
return null;
}
}

View file

@ -0,0 +1,18 @@
package se.koc.trader.api;
import zutil.parser.DataNode;
import java.util.Map;
public class MarketEndpoint extends TraderAPI {
private static final String API_PATH = "/api/market/.*";
public MarketEndpoint() {
super(API_PATH);
}
@Override
protected DataNode jsonRespond(Map<String, Object> session, Map<String, String> cookie, Map<String, String> request) throws Exception {
return null;
}
}

View file

@ -0,0 +1,64 @@
package se.koc.trader.api;
import zutil.log.LogUtil;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.parser.DataNode;
import zutil.parser.Templator;
import zutil.parser.json.JSONWriter;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A interface defining a Hal json endpoint
*/
public abstract class TraderAPI implements HttpPage {
private static final Logger logger = LogUtil.getLogger();
private String path;
public TraderAPI(String path) {
this.path = path;
}
public String getPath() {
return path;
}
@Override
public void respond(HttpPrintStream out,
HttpHeader headers,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException {
out.setHeader("Content-Type", "application/json");
out.setHeader("Access-Control-Allow-Origin", "*");
out.setHeader("Pragma", "no-cache");
JSONWriter writer = new JSONWriter(out);
try{
writer.write(
jsonRespond(session, cookie, request));
} catch (Exception e){
logger.log(Level.SEVERE, null, e);
DataNode root = new DataNode(DataNode.DataType.Map);
root.set("error", e.getMessage());
writer.write(root);
}
writer.close();
}
protected abstract DataNode jsonRespond(
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws Exception;
}

View file

@ -0,0 +1,4 @@
package se.koc.trader.exchange;
public interface ExchangeMarket {
}

View file

@ -0,0 +1,4 @@
package se.koc.trader.exchange;
public interface ExchangeTrader {
}

View file

@ -0,0 +1,34 @@
package se.koc.trader.exchange.binance;
import se.koc.trader.exchange.ExchangeMarket;
import se.koc.trader.struct.Symbol;
import zutil.net.ws.rest.RESTClientFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class BinanceMarketImpl implements ExchangeMarket {
private BinanceRestAPI rest;
public BinanceMarketImpl() {
try {
rest = RESTClientFactory.createClient(new URL("https://api.binance.com"), BinanceRestAPI.class);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public List<Symbol> getSigns() {
return null; // /api/v3/ticker/price
}
public Symbol getSymbol(String symbol) {
return null; // /api/v3/ticker/price?symbol=xxx
}
}

View file

@ -0,0 +1,80 @@
package se.koc.trader.exchange.binance;
import zutil.net.ws.WSInterface;
import zutil.parser.DataNode;
/**
* @see <a href="https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md">Binance REST API sdocumentation</a>
*/
public interface BinanceRestAPI extends WSInterface {
enum CandlestickInterval {
Minute("1m"), Minute_x3("3m"), Minute_x5("5m"), Minute_x15("15m"), Minute_x30("30m"),
Hour("1h"), Hour_x2("2h"), Hour_x4("4h"), Hour_x6("6h"), Hour_x8("8h"), Hour_x12("12h"),
Day("1d"), Day_x3("3d"),
Week("1w"),
Month("1M");
String interval;
CandlestickInterval(String interval) {
this.interval = interval;
}
public String toString() {
return interval;
}
}
/**
* Test connectivity to the Rest API and get the current server time.
* <p></p><pre>GET /api/v3/time</pre>
*
* @return the current server time in EPOC
*/
@WSPath("/api/v3/time")
long getServerTime();
/**
* Current exchange trading rules and symbol information.
* <p></p><pre>GET /api/v3/exchangeInfo</pre>
*/
@WSPath("/api/v3/exchangeInfo")
DataNode getExchangeInfo();
/**
* Kline/candlestick bars for a symbol, method will return the latest data.
* Klines are uniquely identified by their open time.
* <p></p><pre>GET /api/v3/klines</pre>
*
* @param symbol is the symbol identity
* @param interval is the intervall of candlestick data
* @param limit is the maximum amount of candlesticks to return, max is 1000
*/
@WSPath("/api/v3/klines")
DataNode getCandlestickData(String symbol, CandlestickInterval interval, int limit);
/**
* Kline/candlestick bars for a symbol.
* Klines are uniquely identified by their open time.
* <p></p><pre>GET /api/v3/klines</pre>
*
* @param symbol is the symbol identity
* @param interval is the intervall of candlestick data
* @param startTime is the start of the time range of the data
* @param endTime is the end of the time range for data
* @param limit is the maximum amount of candlesticks to return, max is 1000
*/
@WSPath("/api/v3/klines")
DataNode getCandlestickData(String symbol, CandlestickInterval interval, long startTime, long endTime, int limit);
/**
* Latest price for a symbol.
* <p></p><pre>GET /api/v3/ticker/price</pre>
*
* @param symbol is the symbol identity
* @return JSON example => <pre>{"symbol": "LTCBTC", "price": "4.00000200"}</pre>
*/
@WSPath("/api/v3/ticker/price")
DataNode getPrice(String symbol);
}

View file

@ -0,0 +1,8 @@
{
"version": 0.1,
"name": "Exchange-Binance",
"description": "Plugin contains core logic for running Trader.",
"interfaces": [
{"se.koc.trader.exchange.ExchangeMarket": "se.koc.trader.exchange.binance.BinanceMarketImpl"}
]
}

View file

@ -0,0 +1,9 @@
{
"version": 0.1,
"name": "Trader-Core",
"description": "Plugin contains core logic for running Trader.",
"interfaces": [
{"se.koc.trader.api.TraderAPI": "se.hal.page.SensorOverviewWebPage"},
{"se.koc.trader.api.TraderAPI": "se.hal.page.SensorConfigWebPage"}
]
}

View file

@ -0,0 +1,76 @@
package se.koc.trader.struct;
import zutil.db.bean.DBBean;
/**
* Data class containing information about a single candlestick.
*/
@DBBean.DBTable("candlestick")
public class CandleStick {
private Symbol symbol;
private long timestampOpen;
private long timestampClosed;
private double bodyOpen;
private double bodyClose;
private double wickHigh;
private double wickLow;
private double volume;
public Symbol getSymbol() {
return symbol;
}
public void setSymbol(Symbol symbol) {
this.symbol = symbol;
}
public long getTimestampOpen() {
return timestampOpen;
}
public void setTimestampOpen(long timestampOpen) {
this.timestampOpen = timestampOpen;
}
public long getTimestampClosed() {
return timestampClosed;
}
public void setTimestampClosed(long timestampClosed) {
this.timestampClosed = timestampClosed;
}
public double getBodyOpen() {
return bodyOpen;
}
public void setBodyOpen(double bodyOpen) {
this.bodyOpen = bodyOpen;
}
public double getWickHigh() {
return wickHigh;
}
public void setWickHigh(double wickHigh) {
this.wickHigh = wickHigh;
}
public double getWickLow() {
return wickLow;
}
public void setWickLow(double wickLow) {
this.wickLow = wickLow;
}
public double getBodyClose() {
return bodyClose;
}
public void setBodyClose(double bodyClose) {
this.bodyClose = bodyClose;
}
public double getVolume() {
return volume;
}
public void setVolume(double volume) {
this.volume = volume;
}
}

View file

@ -0,0 +1,68 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.koc.trader.struct;
import zutil.db.DBConnection;
import zutil.db.bean.DBBean;
import zutil.db.bean.DBBeanSQLResultHandler;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@DBBean.DBTable(value="plugin")
public class PluginConfig extends DBBean {
private String name;
private boolean enabled;
/**
* @return a PluginConfig bean for the specific plugin name.
*/
public static PluginConfig getPluginConfig(DBConnection db, String name) throws SQLException {
PreparedStatement stmt = db.getPreparedStatement( "SELECT plugin.* FROM plugin WHERE name == ?" );
stmt.setString(1, name);
return DBConnection.exec(stmt, DBBeanSQLResultHandler.create(PluginConfig.class, db) );
}
public PluginConfig() {}
public PluginConfig(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

View file

@ -0,0 +1,48 @@
package se.koc.trader.struct;
import zutil.db.bean.DBBean;
/**
* A data class referencing a symbol
*/
@DBBean.DBTable("symbol")
public class Symbol extends DBBean {
private String baseAsset;
private String quoteAsset;
private double price;
private long priceTimestamp;
public String getBaseAsset() {
return baseAsset;
}
public void setBaseAsset(String baseAsset) {
this.baseAsset = baseAsset;
}
public String getQuoteAsset() {
return quoteAsset;
}
public void setQuoteAsset(String quoteAsset) {
this.quoteAsset = quoteAsset;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public long getPriceTimestamp() {
return priceTimestamp;
}
public void setPriceTimestamp(long priceTimestamp) {
this.priceTimestamp = priceTimestamp;
}
public String toString() {
return baseAsset + "/" +quoteAsset;
}
}

View file

@ -0,0 +1,84 @@
package se.koc.trader.web;
import se.koc.trader.TraderContext;
import zutil.io.file.FileUtil;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.parser.Templator;
import zutil.ui.Navigation;
import zutil.ui.UserMessageManager;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public abstract class TraderPage implements HttpPage{
private static final String TEMPLATE = TraderContext.RESOURCE_WEB_ROOT + "/main_index.tmpl";
private static Navigation rootNav = Navigation.createRootNav();
private static Navigation userNav = Navigation.createRootNav();
private String pageId;
private boolean showSubNav;
public TraderPage(String id){
this.pageId = id;
this.showSubNav = true;
}
public String getId(){
return pageId;
}
@Override
public void respond(HttpPrintStream out, HttpHeader header,
Map<String, Object> session, Map<String, String> cookie,
Map<String, String> request) throws IOException {
try {
List<UserMessageManager.UserMessage> messages = TraderContext.getMessageManager().getMessages();
for (UserMessageManager.UserMessage msg : messages) {
msg.decreaseTTL();
}
Templator tmpl = new Templator(FileUtil.find(TEMPLATE));
tmpl.set("rootNav", rootNav.createPagedNavInstance(header).getSubNavs());
tmpl.set("userNav", userNav.createPagedNavInstance(header).getSubNavs());
tmpl.set("content", httpRespond(session, cookie, request));
tmpl.set("alerts", messages);
tmpl.set("showSubNav", showSubNav);
if (showSubNav) {
List<Navigation> breadcrumb = Navigation.getBreadcrumb(Navigation.getPagedNavigation(header));
if (!breadcrumb.isEmpty())
tmpl.set("subNav", breadcrumb.get(1).createPagedNavInstance(header).getSubNavs());
}
out.print(tmpl.compile());
} catch (Exception e) {
throw new IOException(e);
}
}
/**
* Defines if the sub-navigation should be shown on the page
*/
protected void showSubNav(boolean show) {
this.showSubNav = show;
}
public static Navigation getRootNav(){
return rootNav;
}
public static Navigation getUserNav(){
return userNav;
}
public abstract Templator httpRespond(
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request)
throws Exception;
}

Binary file not shown.

10724
src/main/resources/web/css/bootstrap.css vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,78 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<title>Trader</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.js">
<!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico">
</head>
<body>
<header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" href="#">Company name</a>
<button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="#">Sign out</a>
</li>
</ul>
</header>
<div class="container-fluid">
<div class="row">
<nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
<div class="position-sticky pt-3">
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">
<span data-feather="home"></span>
Dashboard
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">
<span data-feather="file"></span>
Orders
</a>
</li>
</ul>
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Saved reports</span>
<a class="link-secondary" href="#" aria-label="Add a new report">
<span data-feather="plus-circle"></span>
</a>
</h6>
<ul class="nav flex-column mb-2">
<li class="nav-item">
<a class="nav-link" href="#">
<span data-feather="file-text"></span>
Current month
</a>
</li>
</ul>
</div>
</nav>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
{{content}}
</main>
</div>
</div>
</body>
</html>

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

View file

@ -0,0 +1,226 @@
var echarts = require('echarts');
var ROOT_PATH = 'https://echarts.apache.org/examples';
var UP_COLOR = '#00da3c';
var DOWN_COLOR = '#ec0000';
$.get(ROOT_PATH + '/data/asset/data/stock-DJI.json', function (rawData) {
var data = splitData(rawData);
initTradeChart(elementID, data)
}
function splitData(rawData) {
var categoryData = [];
var values = [];
var volumes = [];
for (var i = 0; i < rawData.length; i++) {
categoryData.push(rawData[i].splice(0, 1)[0]);
values.push(rawData[i]);
volumes.push([
i,
rawData[i][4],
rawData[i][0] > rawData[i][1] ? 1 : -1
]);
}
return {
categoryData: categoryData,
values: values,
volumes: volumes
};
}
function calculateMovingAverage(dayCount, data) {
var result = [];
for (var i = 0, len = data.values.length; i < len; i++) {
if (i < dayCount) {
result.push('-');
continue;
}
var sum = 0;
for (var j = 0; j < dayCount; j++) {
sum += data.values[i - j][1];
}
result.push(+(sum / dayCount).toFixed(3));
}
return result;
}
function initTradeChart(elementID, data) {
var chartDom = document.getElementById(elementID);
var myChart = echarts.init(chartDom);
myChart.setOption({
animation: false,
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
},
borderWidth: 1,
borderColor: '#ccc',
padding: 10,
textStyle: {
color: '#000'
},
position: function (pos, params, el, elRect, size) {
var obj = {top: 10};
obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
return obj;
}
},
axisPointer: {
link: {xAxisIndex: 'all'},
label: {
backgroundColor: '#777'
}
},
visualMap: {
show: false,
seriesIndex: 1,
dimension: 2,
pieces: [{
value: 1,
color: DOWN_COLOR
}, {
value: -1,
color: UP_COLOR
}]
},
grid: [
{
left: '10%',
right: '8%',
height: '50%'
},
{
left: '10%',
right: '8%',
top: '58%',
height: '13%'
}
],
xAxis: [
{
type: 'category',
data: data.categoryData,
scale: true,
boundaryGap: false,
axisLine: {onZero: false},
splitLine: {show: false},
splitNumber: 20,
min: 'dataMin',
max: 'dataMax',
axisPointer: {
z: 100
}
},
{
type: 'category',
gridIndex: 1,
data: data.categoryData,
scale: true,
boundaryGap: false,
axisLine: {onZero: false},
axisTick: {show: false},
splitLine: {show: false},
axisLabel: {show: false},
splitNumber: 20,
min: 'dataMin',
max: 'dataMax'
}
],
yAxis: [
{
scale: true,
},
{
scale: true,
gridIndex: 1,
splitNumber: 2,
axisLabel: {show: false},
axisLine: {show: false},
axisTick: {show: false},
splitLine: {show: false}
}
],
dataZoom: [
{
type: 'inside',
xAxisIndex: [0, 1],
start: 98,
end: 100
},
{
show: true,
xAxisIndex: [0, 1],
type: 'slider',
top: '85%',
start: 98,
end: 100
}
],
series: [
{
name: 'Dow-Jones index',
type: 'candlestick',
data: data.values,
itemStyle: {
color: UP_COLOR,
color0: DOWN_COLOR,
borderColor: null,
borderColor0: null
},
tooltip: {
formatter: function (param) {
param = param[0];
return [
'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">',
'Open: ' + param.data[0] + '<br/>',
'Close: ' + param.data[1] + '<br/>',
'Lowest: ' + param.data[2] + '<br/>',
'Highest: ' + param.data[3] + '<br/>'
].join('');
}
}
},
{
name: 'Volume',
type: 'bar',
xAxisIndex: 1,
yAxisIndex: 1,
data: data.volumes
},
{
name: 'MA5',
type: 'line',
data: calculateMA(7, data),
smooth: true,
lineStyle: {
opacity: 0.5
}
},
{
name: 'MA20',
type: 'line',
data: calculateMA(20, data),
smooth: true,
lineStyle: {
opacity: 0.5
}
},
{
name: 'MA50',
type: 'line',
data: calculateMA(50, data),
smooth: true,
lineStyle: {
opacity: 0.5
}
},
]
}, true);
});

View file

@ -0,0 +1,27 @@
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1">Market Overview</h1>
</div>
<h2>Open Trades</h2>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>1,001</td>
<td>random</td>
<td>data</td>
<td>placeholder</td>
<td>text</td>
</tr>
</tbody>
</table>
</div>

View file

@ -0,0 +1,47 @@
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1>Sign {{sign_name}}</h1>
</div>
<canvas id="sign_chart" class="my-4 w-100" id="myChart" width="900" height="380"></canvas>
<h2>Open Trades</h2>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>1,001</td>
<td>random</td>
<td>data</td>
<td>placeholder</td>
<td>text</td>
</tr>
<tr>
<td>1,002</td>
<td>placeholder</td>
<td>irrelevant</td>
<td>visual</td>
<td>layout</td>
</tr>
<tr>
<td>1,003</td>
<td>data</td>
<td>rich</td>
<td>dashboard</td>
<td>tabular</td>
</tr>
</tbody>
</table>
</div>
<script>
initTradeChart("sign_chart", [])
</script>

View file

@ -0,0 +1,28 @@
package se.koc.trader.exchange.binance;
import org.junit.jupiter.api.Test;
import zutil.net.ws.rest.RESTClientFactory;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
class BinanceRestAPITest {
public BinanceRestAPI getRestAPI() {
try {
return RESTClientFactory.createClient(new URL("https://api.binance.com"), BinanceRestAPI.class);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Test
public void getServerTime() {
BinanceRestAPI rest = getRestAPI();
assertTrue(rest.getServerTime() > 0, "Unable to retrieve server time");
}
}