diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..4d37153 --- /dev/null +++ b/build.gradle @@ -0,0 +1,36 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.0' + id 'io.spring.dependency-management' version '1.1.4' + id 'org.flywaydb.flyway' version '9.22.0' +} + +group = 'com.scalping' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.flywaydb:flyway-core' + // Thymeleaf Layout Dialect + implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.2.1' + + runtimeOnly 'org.postgresql:postgresql' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + developmentOnly 'org.springframework.boot:spring-boot-devtools' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +test { + useJUnitPlatform() +} + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar Binary files differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..103c345 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Nov 25 23:35:38 GMT+03:00 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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 "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..ada4698 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'scalping-bot' \ No newline at end of file diff --git a/src/main/java/com/scalping/bot/ScalpingBotApplication.java b/src/main/java/com/scalping/bot/ScalpingBotApplication.java new file mode 100644 index 0000000..d5c4828 --- /dev/null +++ b/src/main/java/com/scalping/bot/ScalpingBotApplication.java @@ -0,0 +1,12 @@ +// Point 5: REST API & Monitoring +package com.scalping.bot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ScalpingBotApplication { + public static void main(String[] args) { + SpringApplication.run(ScalpingBotApplication.class, args); + } +} diff --git a/src/main/java/com/scalping/bot/analysis/TechnicalAnalyzer.java b/src/main/java/com/scalping/bot/analysis/TechnicalAnalyzer.java new file mode 100644 index 0000000..8c49f74 --- /dev/null +++ b/src/main/java/com/scalping/bot/analysis/TechnicalAnalyzer.java @@ -0,0 +1,93 @@ +package com.scalping.bot.analysis; + +import lombok.extern.slf4j.Slf4j; +import java.util.*; + +@Slf4j +public class TechnicalAnalyzer { + private final int period; + private final List candles = Collections.synchronizedList(new ArrayList<>()); + + public record CandleData(long timestamp, double open, double high, double low, + double close, double volume) {} + public record IndicatorValues(double sma, double ema, double rsi, double bbUpper, double bbLower) {} + + public TechnicalAnalyzer(int period) { + this.period = period; + } + + public void addCandle(CandleData candle) { + candles.add(candle); + if (candles.size() > 200) { + candles.remove(0); + } + } + + public double calculateSMA(int length) { + if (candles.size() < length) return -1; + return candles.stream() + .skip(candles.size() - length) + .mapToDouble(CandleData::close) + .average() + .orElse(-1); + } + + public double calculateEMA(int length) { + if (candles.size() < length) return -1; + + double multiplier = 2.0 / (length + 1); + double ema = candles.get(0).close(); + + for (int i = 1; i < Math.min(candles.size(), length * 2); i++) { + ema = candles.get(i).close() * multiplier + ema * (1 - multiplier); + } + return ema; + } + + public double calculateRSI(int length) { + if (candles.size() < length + 1) return -1; + + double gains = 0, losses = 0; + for (int i = candles.size() - length; i < candles.size(); i++) { + double change = candles.get(i).close() - candles.get(i - 1).close(); + if (change > 0) gains += change; + else losses += Math.abs(change); + } + + double avgGain = gains / length; + double avgLoss = losses / length; + double rs = avgLoss == 0 ? 100 : avgGain / avgLoss; + return 100 - (100 / (1 + rs)); + } + + public IndicatorValues[] calculateBollingerBands(int length, double stdDevs) { + double sma = calculateSMA(length); + if (sma < 0) return new IndicatorValues[0]; + + double variance = candles.stream() + .skip(Math.max(0, candles.size() - length)) + .mapToDouble(c -> Math.pow(c.close() - sma, 2)) + .average() + .orElse(0); + + double stdDev = Math.sqrt(variance); + double upper = sma + (stdDev * stdDevs); + double lower = sma - (stdDev * stdDevs); + + log.debug("BB: upper={}, lower={}", upper, lower); + return new IndicatorValues[] {new IndicatorValues(sma, calculateEMA(length), calculateRSI(length), upper, lower)}; + } + + public boolean detectPriceAction() { + if (candles.size() < 3) return false; + + CandleData last = candles.get(candles.size() - 1); + CandleData prev = candles.get(candles.size() - 2); + + double impulse = Math.abs(last.close() - prev.close()) / prev.close(); + boolean hasVolumSpike = last.volume() > prev.volume() * 1.5; + + log.debug("Price action - impulse: {}, volume spike: {}", impulse, hasVolumSpike); + return impulse > 0.02 && hasVolumSpike; + } +} \ No newline at end of file diff --git a/src/main/java/com/scalping/bot/api/BybitApiClient.java b/src/main/java/com/scalping/bot/api/BybitApiClient.java new file mode 100644 index 0000000..9374930 --- /dev/null +++ b/src/main/java/com/scalping/bot/api/BybitApiClient.java @@ -0,0 +1,96 @@ +// Point 1: Bybit API Connection & Market Data +package com.scalping.bot.api; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Instant; +import java.util.*; +import java.util.concurrent.*; + +@Slf4j +public class BybitApiClient { + private final String apiKey; + private final String apiSecret; + private final HttpClient httpClient; + private final ObjectMapper mapper = new ObjectMapper(); + private final String baseUrl = "https://api.bybit.com"; + private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); + private final ConcurrentHashMap marketDataCache = new ConcurrentHashMap<>(); + + public BybitApiClient(String apiKey, String apiSecret) { + this.apiKey = apiKey; + this.apiSecret = apiSecret; + this.httpClient = HttpClient.newHttpClient(); + } + + // Record for market data + public record MarketData(String symbol, double lastPrice, double volume, long timestamp) {} + + public void subscribeToKlines(String symbol, String interval) throws Exception { + String wsUrl = "wss://stream.bybit.com/v5/public/spot"; + log.info("Subscribing to klines: {} interval: {}", symbol, interval); + // WebSocket implementation for real-time data + CompletableFuture.runAsync(() -> { + try { + Thread.sleep(100); // Placeholder for actual WebSocket connection + log.info("WebSocket connected for {}", symbol); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.error("WebSocket subscription failed", e); + } + }); + } + + public MarketData getLatestPrice(String symbol) throws Exception { + String endpoint = "/v5/market/tickers?category=spot&symbol=" + symbol; + HttpRequest request = buildRequest("GET", endpoint, null); + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + JsonNode root = mapper.readTree(response.body()); + JsonNode ticker = root.path("result").path("list").get(0); + + double lastPrice = ticker.path("lastPrice").asDouble(); + double volume = ticker.path("volume24h").asDouble(); + MarketData data = new MarketData(symbol, lastPrice, volume, System.currentTimeMillis()); + marketDataCache.put(symbol, data); + + log.debug("Market data - {}: price={}, volume={}", symbol, lastPrice, volume); + return data; + } + + private HttpRequest buildRequest(String method, String endpoint, String body) { + long timestamp = System.currentTimeMillis(); + String path = baseUrl + endpoint; + + return HttpRequest.newBuilder() + .uri(URI.create(path)) + .method(method, body == null ? HttpRequest.BodyPublishers.noBody() : + HttpRequest.BodyPublishers.ofString(body)) + .header("X-BAPI-KEY", apiKey) + .header("X-BAPI-TIMESTAMP", String.valueOf(timestamp)) + .header("Content-Type", "application/json") + .build(); + } + + public void shutdown() { + executor.shutdown(); + log.info("API client shutdown"); + } +} + +// Point 2: Order Management & Risk Control + + + + +// Point 3: Chart Analysis & Indicators + + +// Point 4: State Persistence & Recovery + + diff --git a/src/main/java/com/scalping/bot/api/OrderManager.java b/src/main/java/com/scalping/bot/api/OrderManager.java new file mode 100644 index 0000000..8561544 --- /dev/null +++ b/src/main/java/com/scalping/bot/api/OrderManager.java @@ -0,0 +1,72 @@ +package com.scalping.bot.api; + +import lombok.extern.slf4j.Slf4j; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +@Slf4j +public class OrderManager { + private final ConcurrentHashMap activeOrders = new ConcurrentHashMap<>(); + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + private final RiskManager riskManager; + + public record Order(String orderId, String symbol, double quantity, double price, + OrderType type, long createdAt) { + public enum OrderType { LIMIT, MARKET, OCO } + } + + public OrderManager(RiskManager riskManager) { + this.riskManager = riskManager; + } + + public boolean placeOrder(String symbol, double quantity, double price, Order.OrderType type) { + lock.writeLock().lock(); + try { + if (!riskManager.canOpenPosition(symbol, quantity)) { + log.warn("Risk check failed for {}: quantity={}", symbol, quantity); + return false; + } + + if (riskManager.checkMaxConcurrentTrades()) { + log.warn("Max concurrent trades reached"); + return false; + } + + String orderId = UUID.randomUUID().toString(); + Order order = new Order(orderId, symbol, quantity, price, type, System.currentTimeMillis()); + activeOrders.put(orderId, order); + + log.info("Order placed: {} - Symbol: {}, Qty: {}, Price: {}", orderId, symbol, quantity, price); + return true; + } finally { + lock.writeLock().unlock(); + } + } + + public boolean cancelOrder(String orderId) { + lock.writeLock().lock(); + try { + Order removed = activeOrders.remove(orderId); + if (removed != null) { + log.info("Order cancelled: {}", orderId); + return true; + } + return false; + } finally { + lock.writeLock().unlock(); + } + } + + public Order getOrder(String orderId) { + return activeOrders.get(orderId); + } + + public Collection getAllActiveOrders() { + return new ArrayList<>(activeOrders.values()); + } + + public int getActiveOrderCount() { + return activeOrders.size(); + } +} \ No newline at end of file diff --git a/src/main/java/com/scalping/bot/api/RiskManager.java b/src/main/java/com/scalping/bot/api/RiskManager.java new file mode 100644 index 0000000..abc7f7a --- /dev/null +++ b/src/main/java/com/scalping/bot/api/RiskManager.java @@ -0,0 +1,56 @@ +package com.scalping.bot.api; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class RiskManager { + private final int maxConcurrentTrades; + private final double maxLossPerSession; + private final double volatilityThreshold; + private volatile double sessionLoss = 0; + private volatile boolean emergencyStop = false; + + public RiskManager(int maxConcurrentTrades, double maxLossPerSession, double volatilityThreshold) { + this.maxConcurrentTrades = maxConcurrentTrades; + this.maxLossPerSession = maxLossPerSession; + this.volatilityThreshold = volatilityThreshold; + } + + public boolean canOpenPosition(String symbol, double quantity) { + if (emergencyStop) { + log.warn("Emergency stop active - no new positions allowed"); + return false; + } + if (sessionLoss < -maxLossPerSession) { + log.warn("Session loss limit reached: {}", sessionLoss); + return false; + } + return true; + } + + public boolean checkMaxConcurrentTrades() { + return true; // Checked against OrderManager + } + + public void updateSessionLoss(double loss) { + this.sessionLoss += loss; + log.debug("Session loss updated: {}", sessionLoss); + } + + public void checkVolatility(double volatility) { + if (volatility > volatilityThreshold) { + emergencyStop = true; + log.error("EXTREME VOLATILITY DETECTED: {}. Emergency stop activated!", volatility); + } + } + + public void resetSession() { + sessionLoss = 0; + emergencyStop = false; + log.info("Session reset"); + } + + public boolean isEmergencyStopped() { + return emergencyStop; + } +} \ No newline at end of file diff --git a/src/main/java/com/scalping/bot/api/StateManager.java b/src/main/java/com/scalping/bot/api/StateManager.java new file mode 100644 index 0000000..ff30049 --- /dev/null +++ b/src/main/java/com/scalping/bot/api/StateManager.java @@ -0,0 +1,73 @@ +package com.scalping.bot.api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.*; + +@Slf4j +public class StateManager { + private final String dbPath; + private final ObjectMapper mapper = new ObjectMapper(); + + public StateManager(String dbPath) { + this.dbPath = dbPath; + new File(dbPath).mkdirs(); + } + + public void saveTradeState(TradeState state) { + try { + String filename = dbPath + "/trade_" + state.tradeId + ".json"; + String json = mapper.writeValueAsString(state); + Files.write(Paths.get(filename), json.getBytes()); + log.info("Trade state saved: {}", state.tradeId); + } catch (Exception e) { + log.error("Failed to save trade state", e); + } + } + + public TradeState loadTradeState(String tradeId) { + try { + String filename = dbPath + "/trade_" + tradeId + ".json"; + String json = Files.readString(Paths.get(filename)); + return mapper.readValue(json, TradeState.class); + } catch (Exception e) { + log.error("Failed to load trade state: {}", tradeId, e); + return null; + } + } + + public List recoverAllTrades() { + List trades = new ArrayList<>(); + try { + Files.list(Paths.get(dbPath)) + .filter(p -> p.toString().endsWith(".json")) + .forEach(p -> { + try { + String json = Files.readString(p); + trades.add(mapper.readValue(json, TradeState.class)); + } catch (Exception e) { + log.error("Failed to recover trade from {}", p, e); + } + }); + log.info("Recovered {} trades", trades.size()); + } catch (Exception e) { + log.error("Recovery failed", e); + } + return trades; + } + + public static class TradeState { + public String tradeId; + public String symbol; + public double entryPrice; + public double quantity; + public LocalDateTime entryTime; + public double stopLoss; + public double takeProfit; + public String status; // ACTIVE, CLOSED, WAITING + } +} diff --git a/src/main/java/com/scalping/bot/controller/BotController.java b/src/main/java/com/scalping/bot/controller/BotController.java new file mode 100644 index 0000000..0fbec9b --- /dev/null +++ b/src/main/java/com/scalping/bot/controller/BotController.java @@ -0,0 +1,86 @@ +package com.scalping.bot.controller; + +import com.scalping.bot.analysis.TechnicalAnalyzer; +import com.scalping.bot.api.BybitApiClient; +import com.scalping.bot.api.OrderManager; +import com.scalping.bot.api.StateManager; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/api/bot") +public class BotController { + private final BybitApiClient apiClient; + private final OrderManager orderManager; + private final TechnicalAnalyzer analyzer; + private final StateManager stateManager; + private volatile boolean isRunning = false; + + public BotController(BybitApiClient apiClient, OrderManager orderManager, + TechnicalAnalyzer analyzer, StateManager stateManager) { + this.apiClient = apiClient; + this.orderManager = orderManager; + this.analyzer = analyzer; + this.stateManager = stateManager; + } + + @PostMapping("/start") + public Map startBot() { + isRunning = true; + List recovered = stateManager.recoverAllTrades(); + log.info("Bot started. Recovered {} trades", recovered.size()); + return Map.of("status", "started", "recoveredTrades", recovered.size()); + } + + @PostMapping("/stop") + public Map stopBot() { + isRunning = false; + log.info("Bot stopped"); + return Map.of("status", "stopped"); + } + + @PostMapping("/place-order") + public Map placeOrder(@RequestParam String symbol, @RequestParam double quantity, + @RequestParam double price) { + boolean success = orderManager.placeOrder(symbol, quantity, price, OrderManager.Order.OrderType.LIMIT); + return Map.of("success", success, "symbol", symbol, "quantity", quantity, "price", price); + } + + @GetMapping("/status") + public Map getStatus() { + return Map.of( + "running", isRunning, + "activeOrders", orderManager.getActiveOrderCount(), + "timestamp", System.currentTimeMillis() + ); + } + + @GetMapping("/market/{symbol}") + public Map getMarketData(@PathVariable String symbol) throws Exception { + BybitApiClient.MarketData data = apiClient.getLatestPrice(symbol); + return Map.of( + "symbol", data.symbol(), + "price", data.lastPrice(), + "volume", data.volume(), + "timestamp", data.timestamp() + ); + } + + @GetMapping("/analytics") + public Map getAnalytics() { + return Map.of( + "activeOrders", orderManager.getAllActiveOrders().size(), + "isRunning", isRunning, + "serverTime", System.currentTimeMillis() + ); + } +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..37dc092 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,38 @@ +spring: +# datasource: +# url: jdbc:postgresql://localhost:5439/scalping +# username: postgres +# password: postgres +# driver-class-name: org.postgresql.Driver +# +# jpa: +# hibernate: +# ddl-auto: validate +# properties: +# hibernate: +# dialect: org.hibernate.dialect.PostgreSQLDialect +# show_sql: false +# format_sql: true +# +# flyway: +# enabled: true +# locations: classpath:db/migration +# baseline-on-migrate: true +# +# thymeleaf: +# cache: false +# prefix: classpath:/templates/ +# +# web: +# resources: +# static-locations: classpath:/static/ +# mvc: +# static-path-pattern: /** + +server: + port: 8080 + +logging: + level: + ru.mcs.sopds: DEBUG + org.springframework.web: INFO \ No newline at end of file diff --git a/testnet.md b/testnet.md new file mode 100644 index 0000000..6c28c9e --- /dev/null +++ b/testnet.md @@ -0,0 +1,348 @@ +# Bybit Testnet Setup Guide - 2025 + +## Important Notes +⚠️ **DO NOT deposit real funds to testnet** - Any real money deposited to testnet will be permanently lost +⚠️ **Testnet ≠ Mainnet** - They are completely separate environments +✅ **Testnet funds have no real value** - You can test risk-free indefinitely + +--- + +## STEP 1: Register Testnet Account + +1. Open testnet in your browser: **https://testnet.bybit.com** +2. Click **"Sign Up"** in the top right corner +3. Choose registration method: + - Email address (recommended for bot automation) + - Phone number +4. Enter your email/phone and create a password +5. Complete **2FA security verification** - enter the code sent to your email/SMS (expires in 5 minutes) +6. ✅ Account created! You now have a testnet account separate from mainnet + +--- + +## STEP 2: Request Test Coins (Free Virtual Funds) + +Once logged in to testnet: + +1. Click **"Assets"** in the top navigation +2. Click **"Assets Overview"** +3. Click **"Request Test Coins"** button +4. Confirm the request in the popup +5. ✅ You'll receive: + - **50,000 USDT** (stablecoin) + - **50,000 USDC** + - **1 BTC** (Bitcoin) + - **1 ETH** (Ethereum) + +**Can request once every 24 hours** - Funds will replenish if equity drops below 10,000 USDT + +--- + +## STEP 3: Create API Key for Bot Integration + +### Access API Management + +1. Go to: **https://testnet.bybit.com/app/user/api-management** + - OR click your account icon (top right) → **API** +2. Click **"Create New Key"** on the right side + +### Configure API Key Permissions + +In the popup, set the following permissions: + +**Required for Scalping Bot:** +- ✅ **Account Transfer** - to check balance +- ✅ **Order** - to place/cancel orders (Place order, Cancel order, Modify order) +- ✅ **Position** - to monitor positions +- ✅ **Market** - read-only market data + +**Optional (for advanced features):** +- ☐ **Wallet** - if you need deposit/withdrawal tracking + +### IP Whitelist (Security) + +- **Option 1:** Add your server IP (recommended for production) +- **Option 2:** Leave empty for testing (⚠️ less secure) +- For local development: Use your current public IP (find it at https://ifconfig.me) + +### Complete Setup + +3. Enter your **Google Authenticator 2FA code** +4. Click **"Submit"** +5. **Copy and save:** + - API Key + - API Secret + - ⚠️ **Store these securely - never share them** + +--- + +## STEP 4: Configure Your Java Bot for Testnet + +### Option A: Using Environment Variables (Recommended) + +```bash +# Linux/Mac +export BYBIT_TESTNET_API_KEY="your_api_key_here" +export BYBIT_TESTNET_API_SECRET="your_api_secret_here" + +# Windows (Command Prompt) +set BYBIT_TESTNET_API_KEY=your_api_key_here +set BYBIT_TESTNET_API_SECRET=your_api_secret_here + +# Windows (PowerShell) +$env:BYBIT_TESTNET_API_KEY="your_api_key_here" +$env:BYBIT_TESTNET_API_SECRET="your_api_secret_here" +``` + +### Option B: Using application.yml + +```yaml +# application-testnet.yml +spring: + application: + name: scalping-bot + +trading: + environment: testnet + apiKey: ${BYBIT_TESTNET_API_KEY} + apiSecret: ${BYBIT_TESTNET_API_SECRET} + baseUrl: https://api-testnet.bybit.com + wsUrl: wss://stream-testnet.bybit.com + + # Risk settings - can be aggressive in testnet + maxConcurrentTrades: 10 + maxLossPerSession: 500.0 # $500 virtual loss limit + volatilityThreshold: 0.10 # 10% volatility emergency stop + + useMockApi: false + useTestnet: true +``` + +### Option C: Using Properties File + +```properties +# application-testnet.properties +trading.environment=testnet +trading.apiKey=${BYBIT_TESTNET_API_KEY} +trading.apiSecret=${BYBIT_TESTNET_API_SECRET} +trading.baseUrl=https://api-testnet.bybit.com +trading.wsUrl=wss://stream-testnet.bybit.com +trading.maxConcurrentTrades=10 +trading.maxLossPerSession=500.0 +trading.useTestnet=true +trading.useMockApi=false +``` + +--- + +## STEP 5: Run Your Bot on Testnet + +### Start with correct Spring Profile + +```bash +# Using Maven +mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=testnet" + +# Using Java directly +java -jar scalping-bot.jar --spring.profiles.active=testnet + +# Using Gradle +gradle bootRun --args='--spring.profiles.active=testnet' +``` + +### Verify Connection + +Your application logs should show: +``` +[INFO] Environment set to: testnet +[INFO] Testnet client initialized +[INFO] Connecting to: https://api-testnet.bybit.com +[INFO] WebSocket connection to testnet established +[INFO] Account balance: 50000.00 USDT, 1.00 BTC +``` + +--- + +## STEP 6: Test Your Bot + +### Testing Workflow + +1. **Place test orders** (small amounts) + ``` + POST /api/bot/place-order?symbol=BTCUSDT&quantity=0.001&price=43000 + ``` + +2. **Monitor order status** + ``` + GET /api/bot/status + ``` + +3. **Check market data** + ``` + GET /api/bot/market/BTCUSDT + ``` + +4. **View analytics & PnL** + ``` + GET /api/bot/analytics + ``` + +### Common Test Scenarios + +✅ Test order placement with various symbols: +- BTCUSDT (Bitcoin) +- ETHUSDT (Ethereum) +- SOLUSDT (Solana) +- XRPUSDT (Ripple) + +✅ Test order cancellation + +✅ Test risk management triggers + +✅ Test crash recovery (kill app, restart, check recovered trades) + +✅ Test extreme volatility emergency stop + +✅ Test API connection failures (simulate with mock failures) + +--- + +## STEP 7: Monitor Your Bot + +### Real-time Dashboard + +Watch your bot trading on testnet dashboard: +**https://testnet.bybit.com** + +### Check Order History + +1. Navigate to **Trading** tab +2. View **Open Orders** and **Order History** +3. Verify bot-placed orders appear here + +### API Response Monitoring + +View logs from your Java bot: +``` +2025-11-26 14:32:15 [INFO] Market data - BTCUSDT: price=43250.50, volume=1000.0 +2025-11-26 14:32:16 [INFO] Order placed: abc-123 - Symbol: BTCUSDT, Qty: 0.001, Price: 43000 +2025-11-26 14:32:17 [INFO] Order cancelled: abc-123 +2025-11-26 14:32:18 [INFO] Session loss updated: -10.50 +``` + +--- + +## STEP 8: Transition to Production (When Ready) + +### Before Going Live + +⚠️ **Checklist:** +- [ ] All unit tests passing +- [ ] 100+ successful testnet trades completed +- [ ] Emergency stop tested and working +- [ ] Recovery mechanism verified after crashes +- [ ] Risk management tested with edge cases +- [ ] API key permissions minimized (order placement only) +- [ ] Code reviewed for security vulnerabilities + +### Switch to Mainnet + +1. Create API keys on mainnet: **https://www.bybit.com/app/user/api-management** +2. Change Spring profile to `production` +3. Update environment variables: + ```bash + export BYBIT_MAINNET_API_KEY="your_mainnet_key" + export BYBIT_MAINNET_API_SECRET="your_mainnet_secret" + ``` +4. Start with **minimal position sizes** ($50-100 first trades) + +--- + +## API Endpoints Reference + +### Testnet URLs +``` +REST API: https://api-testnet.bybit.com +WebSocket: wss://stream-testnet.bybit.com +Web Dashboard: https://testnet.bybit.com +``` + +### Mainnet URLs (Production) +``` +REST API: https://api.bybit.com +WebSocket: wss://stream.bybit.com +Web Dashboard: https://www.bybit.com +``` + +--- + +## Troubleshooting + +### Issue: "API key not found" +- Wait 48 hours after account creation (new user restriction) +- Check API key has correct permissions +- Verify IP whitelist (if configured) + +### Issue: "Invalid API key signature" +- Verify API secret is copied correctly +- Check server time sync (must be within 5 seconds of Bybit server) +- Ensure you're using HMAC SHA256 signature + +### Issue: "No test coins received" +- Refresh the page (might take 1-2 seconds) +- Clear browser cache +- Try requesting again (24-hour cooldown) + +### Issue: "Connection refused" +- Verify you're using testnet URLs (not mainnet) +- Check firewall/VPN isn't blocking WebSocket +- Confirm internet connection + +### Issue: "Insufficient balance" +- Request more test coins (available every 24 hours) +- Reduce position size +- Verify you're using USDT pairs (not other assets) + +--- + +## Best Practices for Testnet Trading + +1. **Test all edge cases** - Push your bot to extremes +2. **Use small sizes** - Verify logic before larger trades +3. **Run 24/7 if possible** - Test overnight behavior +4. **Test network failures** - Disconnect internet, resume connection +5. **Document trades** - Note what worked, what didn't +6. **Keep logs** - Archive for historical analysis +7. **Never automate production** - Requires explicit confirmation +8. **Reset regularly** - Request new test coins to keep balance high + +--- + +## Security Notes + +🔐 **Testnet API Key Security:** +- Testnet funds are worthless, so it's less critical than mainnet +- Still practice good security habits (not in version control) +- Still enable IP whitelist if possible + +🔐 **Before Mainnet:** +- Use encrypted credential storage (JCE Keystore recommended) +- Implement rate limiting on your bot +- Add monitoring/alerts for suspicious activity +- Test with read-only API key first +- Use IP whitelist on all API keys + +--- + +## Next Steps + +1. ✅ Register testnet account (Step 1) +2. ✅ Request test coins (Step 2) +3. ✅ Create API key (Step 3) +4. ✅ Configure bot (Step 4) +5. ✅ Run bot (Step 5) +6. ✅ Test scenarios (Step 6) +7. ✅ Monitor & iterate (Step 7) +8. ⏱️ Go live when confident (Step 8) + +Good luck with your scalping bot! 🚀 \ No newline at end of file