├── .gitignore ├── .gitlab-ci.yml ├── README.md ├── annotationsForContainers.md ├── continuousDeployment.sh ├── deploy.txt ├── monitoring ├── openFinDeskLogs ├── debug.log ├── error.log ├── myFatal.log └── strategies.log ├── pom.xml ├── result.md ├── shellscripting ├── src ├── main │ ├── java │ │ └── com │ │ │ └── farshad │ │ │ └── algotrading │ │ │ ├── AlgoTrader.java │ │ │ ├── LiveTrading.java │ │ │ ├── OpenFinDesklogLevels │ │ │ ├── LiveTradingLogLevel.java │ │ │ └── RLLogLevel.java │ │ │ ├── backtesting │ │ │ ├── ATSBackTest.java │ │ │ ├── BackTest.java │ │ │ ├── ExpectationMaximizationAlgorithm │ │ │ │ └── ExpectationMaximization.java │ │ │ ├── FetchingForexBacktest.java │ │ │ ├── FibonacciBackTest.java │ │ │ ├── HMM │ │ │ │ ├── BackwardAlgorithm.java │ │ │ │ └── RegimeAnalyzer.java │ │ │ ├── HMMBackTest.java │ │ │ ├── influxDbCRUD │ │ │ │ └── InfluxDbManager.java │ │ │ └── measurements │ │ │ │ ├── AUDUSDCandlePoint.java │ │ │ │ ├── EURAUDCandlePoint.java │ │ │ │ ├── EURUSDCandlePoint.java │ │ │ │ ├── GBPUSDCandlePoint.java │ │ │ │ └── timeSeriesMeasurements │ │ │ │ ├── PercentOfChange.java │ │ │ │ ├── PriceTime.java │ │ │ │ ├── Return.java │ │ │ │ └── TimeSeriesPoint.java │ │ │ ├── core │ │ │ ├── AlternatingTrendSmoothing │ │ │ │ └── ATS.java │ │ │ ├── Candle.java │ │ │ ├── Comparison.java │ │ │ ├── CurrentState.java │ │ │ ├── OpenFinDeskExitRule │ │ │ │ ├── OpenFinDeskExitRule.java │ │ │ │ ├── ParabolicSarExitRule.java │ │ │ │ └── QuantizedTpAndSlExitRule.java │ │ │ ├── Symbol.java │ │ │ ├── containerCore │ │ │ │ ├── ChanceNode.java │ │ │ │ ├── DecisionTree.java │ │ │ │ ├── StrategyContainer.java │ │ │ │ └── XYSeriesDemo.java │ │ │ ├── customizedPivotPointMethods │ │ │ │ └── CamarillaPivotPointApproach.java │ │ │ ├── fibonacciCore │ │ │ │ ├── FiboClusterManagerOld.java │ │ │ │ ├── Fibonacci.java │ │ │ │ ├── FibonacciHelper.java │ │ │ │ ├── PriceReversalZone.java │ │ │ │ └── TimeReversalZone.java │ │ │ ├── math │ │ │ │ ├── AlgoRegression.java │ │ │ │ └── test │ │ │ │ │ └── MathTest.java │ │ │ ├── openFinDeskOrder │ │ │ │ └── OpenFinDeskOrder.java │ │ │ ├── openFinDeskStore │ │ │ │ ├── OpenFinDeskStore.java │ │ │ │ ├── csv │ │ │ │ │ ├── CSV.java │ │ │ │ │ └── stocksInputData │ │ │ │ │ │ ├── OHLCData.java │ │ │ │ │ │ ├── OpenFinDeskMessage.java │ │ │ │ │ │ ├── TimeParser.java │ │ │ │ │ │ └── csv │ │ │ │ │ │ ├── CSVReader.java │ │ │ │ │ │ └── CSVWriter.java │ │ │ │ └── influxdb │ │ │ │ │ └── InfluxDB.java │ │ │ ├── sockets │ │ │ │ └── SocketUtil.java │ │ │ └── trendRangeAndWave │ │ │ │ ├── Range.java │ │ │ │ ├── Trend.java │ │ │ │ ├── TrendGenerator.java │ │ │ │ ├── Wave.java │ │ │ │ └── WaveGenerator.java │ │ │ ├── openFinDeskAnnotations │ │ │ ├── OpenFinDeskChanceNode.java │ │ │ └── StrategyContainerHandler.java │ │ │ ├── openFinDeskStrategies │ │ │ ├── CrossingTimeSeriesDetector.java │ │ │ ├── OpenFinDeskStrategy.java │ │ │ ├── candlestickDriven │ │ │ │ ├── EngulfingPatternStrategy.java │ │ │ │ └── PinBarStrategy.java │ │ │ ├── fibonacciBased │ │ │ │ ├── FibonacciConvergence.java │ │ │ │ └── TrendStrengthStrategyBasedOnInternalRetracementSequences.java │ │ │ ├── indicatorBased │ │ │ │ ├── ADXBasedTrendDetection.java │ │ │ │ ├── CrossingTwoMovingAverages.java │ │ │ │ ├── MACDbasedCrossingStrategy.java │ │ │ │ ├── ParabolicSARIndicatorForStopLoss.java │ │ │ │ ├── RSIStrategy.java │ │ │ │ └── StatisticalCrossingTwoMovingAverages.java │ │ │ ├── pivotPointBased │ │ │ │ └── CamarillaStrategy.java │ │ │ └── statisticalArbitrageBasedOnKalmanFilter │ │ │ │ ├── Cointegration.java │ │ │ │ ├── KalmanFilter.java │ │ │ │ ├── KalmanFilterBasedCointegration.java │ │ │ │ └── Process.java │ │ │ ├── riskManagement │ │ │ ├── ActionPerformer.java │ │ │ ├── moneymanagement │ │ │ │ └── MoneyManager.java │ │ │ └── positionManagement │ │ │ │ ├── Position.java │ │ │ │ └── PositionManager.java │ │ │ └── strategyContainer │ │ │ ├── container0 │ │ │ └── CheckIfADXIsOkChanceNode.java │ │ │ ├── container1 │ │ │ └── CheckIfWeHavePinBarCandlestickChanceNode.java │ │ │ ├── container2 │ │ │ └── CheckIfCrossingMACDAndTrendingADXChanceNode.java │ │ │ ├── container3 │ │ │ └── CheckIfCrossingMovingAverageChanceNode.java │ │ │ ├── container4 │ │ │ └── CheckIfEngulfingH1ADXD1.java │ │ │ ├── container5 │ │ │ └── CheckIfCamarillaAndADX.java │ │ │ └── container9 │ │ │ ├── CheckIfBothTimeFramesAgreeChanceNode.java │ │ │ └── CheckIfHigherTimeFrameIsTrendingChanceNode.java │ └── resources │ │ └── log4j.properties └── test │ └── java │ └── com │ └── farshad │ └── algotrading │ ├── TestCSVReader.java │ ├── TestComparison.java │ ├── TestRegressionAndPredictForex.java │ ├── customizedPivotPointsMethods │ └── CamarillaPivotPointTest.java │ ├── openFinDeskAnnotation │ └── OpenFinDeskAnnotationsTest.java │ └── strategyContainer │ └── StrategyContainerTest.java ├── systemd services └── todolist.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ../.idea/ 3 | target/ 4 | ver16.iml 5 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | stages: 3 | - deployStage 4 | 5 | build: 6 | stage: deployStage 7 | tags: 8 | - myshell 9 | 10 | script: 11 | - echo "algotrader" 12 | - chmod 777 continuousDeployment.sh 13 | - ./continuousDeployment.sh 14 | 15 | ... 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenFinDesk: Algorithmic Trading based on Technical Analysis 2 | ## An Opensource framework to trade Forex and CFD using technical analysis in Java 3 | This is an opensource Java framework to implement any technical trading strategy in less than a minute 4 | by using openFinDesk annotations. 5 | OpenFinDesk has many modules. Current module which is based on technical analysis is opensource. 6 | 7 | # pros 8 | * loose coupling and Java SOLID principles are considered as much as possible. 9 | * can be scaled horizontally and vertically 10 | * using influxdb,csv or any other store you like. 11 | * complete backtesting before running in live mode 12 | * a module to use Hidden Markov Model 13 | * customized log levels 14 | * testing java classes 15 | * separate risk management 16 | * separate money management 17 | * separate position management 18 | * using any approach such as Fibonacci, indicators or a combination of many strategies 19 | # cons 20 | * It is only technical analysis. 21 | * It is not based on a reactive architecture like RxJava. 22 | * refactoring is not perfect. 23 | ### Example1 24 | ``` 25 | @OpenFinDeskChanceNode(containerId=5,nodeId=0 26 | ,openfindeskStrategies={CamarillaStrategy.class, ADXBasedTrendDetection.class} 27 | ,timeFrames={"PERIOD_D1","PERIOD_H1"}) 28 | public class CheckIfCamarillaAndADX extends ChanceNode { 29 | final static Logger logger= Logger.getLogger(CheckIfCamarillaAndADX.class); 30 | 31 | @Override 32 | public void executeCurrentChanceNode() { 33 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 34 | this.openFinDeskOrder.setPosition("*"); 35 | this.openFinDeskOrder.setOrderType("noOrder"); 36 | this.openFinDeskOrder.setStrategyName("no signal from container 5"); 37 | this.openFinDeskOrder.setAction("doNothingAndWait"); 38 | this.openFinDeskOrder.setVolume("0.01"); 39 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 40 | logger.info("featureVector.get(1).getPosition()="+featureVector.get(1).getPosition()); 41 | 42 | if ((featureVector.get(0).getPosition().equals("buy")) && (featureVector.get(1).getPosition().equals("buy"))) { 43 | this.openFinDeskOrder.setOrderType("openBuy"); 44 | this.openFinDeskOrder.setAction("buyUsingFirstQuantizedLevel"); 45 | this.openFinDeskOrder.setStrategyName("Container5"); 46 | }else if ((featureVector.get(0).getPosition().equals("sell")) && (featureVector.get(1).getPosition().equals("sell"))) { 47 | this.openFinDeskOrder.setOrderType("openSell"); 48 | this.openFinDeskOrder.setAction("sellUsingFirstQuantizedLevel"); 49 | this.openFinDeskOrder.setStrategyName("Container5"); 50 | }else { 51 | this.openFinDeskOrder.setOrderType("noOrder"); 52 | this.openFinDeskOrder.setAction("doNothingAndWait"); 53 | } 54 | decisionIsMade=true; 55 | 56 | } 57 | } 58 | This informs the software to use CamarillaStrategy in daily time frame and ADX in H1 timeframe 59 | ``` 60 | ### Example2 61 | ``` 62 | @OpenFinDeskChanceNode(containerId=1,nodeId=0 63 | ,openfindeskStrategies={PinBarStrategy.class,TrendStrengthStrategyBasedOnInternalRetracementSequences.class} 64 | ,timeFrames={"PERIOD_H1","PERIOD_D1"},disabled=true) 65 | public class CheckIfWeHavePinBarCandlestickChanceNode extends ChanceNode { 66 | final static Logger logger= Logger.getLogger(CheckIfWeHavePinBarCandlestickChanceNode.class); 67 | 68 | @Override 69 | public void executeCurrentChanceNode() { 70 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 71 | this.openFinDeskOrder.setPosition("*"); 72 | this.openFinDeskOrder.setOrderType("noOrder"); 73 | this.openFinDeskOrder.setStrategyName("no signal from container 1"); 74 | this.openFinDeskOrder.setAction("doNothingAndWait"); 75 | this.openFinDeskOrder.setVolume("0.01"); 76 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 77 | logger.info("featureVector.get(1).getPosition()="+featureVector.get(1).getPosition()); 78 | if ((featureVector.get(0).getPosition().equals("bearishPinBar"))&&(featureVector.get(1).getPosition().equals("sell"))){ 79 | this.openFinDeskOrder.setOrderType("openSell"); 80 | this.openFinDeskOrder.setAction("sellUsingScalping"); 81 | this.openFinDeskOrder.setStrategyName("container1"); 82 | }else if((featureVector.get(0).getPosition().equals("bullishPinBar"))&&(featureVector.get(1).getPosition().equals("buy"))){ 83 | this.openFinDeskOrder.setOrderType("openBuy"); 84 | this.openFinDeskOrder.setAction("buyUsingScalping"); 85 | this.openFinDeskOrder.setStrategyName("container1"); 86 | } 87 | decisionIsMade=true; 88 | 89 | } 90 | } 91 | This informs the software to use PinBarStrategy in H1 time frame and TrendStrengthStrategyBasedOnInternalRetracementSequences in Daily timeframe 92 | ``` 93 | of course you can also use more complex strategies since the infrastructure is based on datastructure of decision tree 94 | and you can create any decision tree. 95 | # v8.dll 96 | since i created a dll using visual C++, i used a release version since 97 | if i put debug version,then i need a Visual C++ Redistributable on each computer. 98 | If you dont create a release version for your dll then MQL5 keeps saying: can not open dll even 99 | if you have allowed MQL5 to do so. 100 | 101 | #mql5 102 | This java infrastructure connects to mql5 via sockets. Mql5 uses your dll file. I created v8.dll based on my C++ codes. 103 | # order 104 | ## separate by comma: 105 | 7 parameters: 106 | order,symbol,orderType,executionType,tp,sl,volume 107 | 108 | * order : "order" 109 | * symbol: "EURUSD" 110 | * orderType:"ORDER_TYPE_BUY" 111 | * executionType:"instant" or "pending" 112 | * tp:"1.11034" 113 | * sl:"1.10226" 114 | * volume:"0.01" 115 | -------------------------------------------------------------------------------- /annotationsForContainers.md: -------------------------------------------------------------------------------- 1 | # annotations for statistical arbitrage 2 | 3 | 4 | ```java_holder_method_tree 5 | 6 | ``` 7 | -------------------------------------------------------------------------------- /continuousDeployment.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "starting continuous integration for statistical arbitrage---" 3 | #cd /Users/macbook/Desktop 4 | #mkdir deployresults 5 | #cd deployresults 6 | #touch result.txt 7 | #echo "ok" > result.txt 8 | ls 9 | #scp -r todolist.txt ubuntu@x.x.x.x:/home/ubuntu 10 | #ssh ubuntu@x.x.x.x "pwd && ls" 11 | -------------------------------------------------------------------------------- /deploy.txt: -------------------------------------------------------------------------------- 1 | * copy files: 2 | /lib 3 | /csv 4 | simple-1.0-SNAPSHOT.jar 5 | 6 | cd desktop 7 | 8 | scp -r simple-1.0-SNAPSHOT.jar lib/ csv/ ubuntu@37.152.185.41:/home/ubuntu 9 | scp -r simple-1.0-SNAPSHOT.jar csv/ ubuntu@37.152.185.41:/home/ubuntu 10 | scp -r algotrader-v2.x.x.jar csv/ ubuntu@37.152.185.41:/home/ubuntu 11 | scp -r algotrader-v2.x.x.jar lib/ ubuntu@37.152.185.41:/home/ubuntu 12 | scp -r algotrader-v2.x.x.jar ubuntu@37.152.185.41:/home/ubuntu 13 | 14 | scp -r algotrader-v2.x.x.jar ubuntu@37.152.185.41:/home/ubuntu 15 | 16 | 17 | scp -r algotrader-v2.x.x.jar lib/ root@79.175.151.248:/home/ 18 | 19 | 20 | scp -r algotrader-v2.x.x.jar lib/ ubuntu@194.5.192.190:/home/ubuntu 21 | 22 | * then: 23 | 24 | 25 | install java: sudo apt-get install openjdk-8-jdk 26 | 27 | 28 | java -jar simple-1.0-SNAPSHOT.jar > farshadAlgotraderLog.txt & 29 | 30 | java -jar algotrader-v2.x.x.jar > farshadAlgotraderLog.txt 31 | 32 | java -Dlog4j.configuration=/resources/log4j.properties -jar algotrader-v2.x.x.jar 33 | 34 | java -Dlog4j.configuration=file://$currDir/cfg/log4j.properties -jar ./MyProject.jar 35 | 36 | java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp 37 | java -Dlog4j.configuration=file:".\log4j.properties" -jar com.your-1.0-SNAPSHOT.jar 38 | 39 | # intellij 40 | -Dlog4j.configuration=log4j.properties 41 | # inside linux server .sh file 42 | java -Dlog4j.configuration=file:"./resources/log4j.properties" -jar algotrader-v2.x.x.jar 43 | 44 | 45 | ubuntu@ubuntu-algo-rl:~$ cat algoRunJavaFile.sh 46 | #!/bin/bash 47 | echo "now running algotrader using shell script---" 48 | cd /home/ubuntu 49 | rm -rf csv/ 50 | rm -rf farshadAlgotraderLog.txt 51 | rm -rf openFinDeskLogs/ 52 | mkdir openFinDeskLogs 53 | java -Dlog4j.configuration=file:"./resources/log4j.properties" -jar algotrader-v2.x.x.jar > farshadAlgotraderLog.txt 54 | 55 | 56 | java -jar restUsingWebflux-1.x.x.jar & 57 | -------------------------------------------------------------------------------- /monitoring: -------------------------------------------------------------------------------- 1 | memory 2 | 3 | watch -n 5 free -m 4 | 5 | sudo apt-get install htop 6 | 7 | top 8 | 9 | free -m 10 | 11 | free -m | grep "Mem:" 12 | 13 | cat /proc/meminfo 14 | 15 | -------------------------------------------------------------------------------- /openFinDeskLogs/error.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/farshad-nsh/AlgorithmicTrading/7f583de854505e678458cf3e31892ede8e422235/openFinDeskLogs/error.log -------------------------------------------------------------------------------- /openFinDeskLogs/myFatal.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/farshad-nsh/AlgorithmicTrading/7f583de854505e678458cf3e31892ede8e422235/openFinDeskLogs/myFatal.log -------------------------------------------------------------------------------- /openFinDeskLogs/strategies.log: -------------------------------------------------------------------------------- 1 | 2020-03-13 11:42:19 SIGNALS LiveTrading:43 - Trading Signals using OpenFinDesk,analyzing Forex... 2 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.farshad.algotrading 8 | algotrader 9 | v2.x.x 10 | 24 | 25 | 26 | 27 | 28 | 29 | org.apache.maven.plugins 30 | maven-dependency-plugin 31 | 32 | 33 | copy-dependencies 34 | prepare-package 35 | 36 | copy-dependencies 37 | 38 | 39 | ../target/lib 40 | false 41 | false 42 | true 43 | 44 | 45 | 46 | 47 | 48 | org.apache.maven.plugins 49 | maven-jar-plugin 50 | 51 | 52 | 53 | true 54 | lib/ 55 | com.farshad.algotrading.AlgoTrader 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | org.apache.maven.plugins 64 | maven-compiler-plugin 65 | 66 | 8 67 | 8 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.reflections 77 | reflections 78 | 0.9.11 79 | 80 | 81 | 82 | 83 | org.influxdb 84 | influxdb-java 85 | 2.17 86 | 87 | 88 | 89 | 90 | org.ta4j 91 | ta4j-core 92 | 0.12 93 | 94 | 95 | 96 | 97 | io.reactivex 98 | rxjava 99 | 1.3.8 100 | 101 | 102 | 103 | 104 | 105 | org.jfree 106 | jfreechart 107 | 1.5.0 108 | 109 | 110 | com.google.code.gson 111 | gson 112 | 2.8.5 113 | 114 | 115 | 116 | log4j 117 | log4j 118 | 1.2.17 119 | 120 | 121 | org.junit.jupiter 122 | junit-jupiter-engine 123 | 5.1.0 124 | test 125 | 126 | 127 | 135 | 136 | 137 | org.la4j 138 | la4j 139 | 0.5.5 140 | 141 | 142 | 143 | 144 | org.apache.commons 145 | commons-math3 146 | 3.4.1 147 | 148 | 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /result.md: -------------------------------------------------------------------------------- 1 | ``` 2 | 2020-03-12 19:53:05 INFO StatisticalTest:37 - delta[48]=-0.21068873015082135 3 | 2020-03-12 19:53:05 INFO StatisticalTest:70 - sampleMean=-1.6903261949313237 4 | 2020-03-12 19:53:05 INFO StatisticalTest:76 - sampleVariance=234.76295860826943 5 | 2020-03-12 19:53:05 INFO StatisticalTest:79 - sampleStandardDeviation=15.321976328407162 6 | 2020-03-12 19:53:05 INFO StatisticalTest:48 - tStatistic=-0.7722426344297403 7 | 2020-03-12 19:53:05 INFO StatisticalTest:59 - H0IsRejected=true 8 | 2020-03-12 19:53:05 INFO OpenFinDeskSpreadModeler:130 - Spread model is stationary with 95% confidence interval 9 | 2020-03-12 19:53:05 INFO OpenFinDeskSpreadModeler:131 - spreadThreshold=0.011548053601966224 10 | 2020-03-12 19:53:05 INFO OpenFinDeskSpreadModeler:132 - spreadSeries[spreadSeries.length-1]=0.0024958212073713515 11 | 2020-03-12 19:53:05 INFO StatisticalArbitrage:62 - passed:true ,buy:null ,sell:null ,volume for buy:0.0 ,volume for sell:0.0 12 | ``` 13 | -------------------------------------------------------------------------------- /shellscripting: -------------------------------------------------------------------------------- 1 | list of services: 2 | systemctl list-unit-files | grep enabled 3 | 4 | list active services: 5 | systemctl list-units --type=service --state=active 6 | 7 | list running services 8 | systemctl list-units --type=service --state=running 9 | 10 | sudo service --status-all 11 | 12 | journalctl -u algoTradingService.service 13 | 14 | just put this file inside /etc/init.d 15 | algorunatstart 16 | 17 | #!/bin/bash 18 | 19 | echo "now running algotrader using shellscript---"; 20 | 21 | ls 22 | 23 | java -jar /home/ubuntu/simple-1.0-SNAPSHOT.jar > farshadAlgotraderLog.txt & 24 | 25 | 26 | 27 | ubuntu@ubuntu-algo-rl:~$ cat algoRunJavaFile.sh 28 | #!/bin/bash 29 | echo "now running algotrader using shell script---" 30 | cd /home/ubuntu 31 | rm -rf csv/ 32 | rm -rf farshadAlgotraderLog.txt 33 | rm -rf openFinDeskLogs/ 34 | mkdir openFinDeskLogs 35 | java -Dlog4j.configuration=file:"./resources/log4j.properties" -jar algotrader-v2.x.x.jar > farshadAlgotraderLog.txt 36 | 37 | 38 | ubuntu@ubuntu-algo-rl:/etc/systemd/system$ sudo vi algoTradingService.service 39 | [Unit] 40 | #After=network.target auditd.service 41 | Description=systemd service to run java file at startup. 42 | [Service] 43 | #Type=oneshot 44 | WorkingDirectory=/home/ubuntu/ 45 | ExecStart=/bin/bash algoRunJavaFile.sh start 46 | #Restart=always 47 | #RestartSec=60 48 | User=root 49 | #Type=forking 50 | Type=simple 51 | Restart=on-failure 52 | #RestartSec=10 53 | [Install] 54 | WantedBy=multi-user.target 55 | 56 | 57 | 58 | 59 | and then: 60 | sudo systemctl enable algoTradingService.service 61 | sudo systemctl start algoTradingService.service 62 | sudo systemctl status algoTradingService.service 63 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/AlgoTrader.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading; 2 | 3 | import com.farshad.algotrading.backtesting.ATSBackTest; 4 | import com.farshad.algotrading.backtesting.BackTest; 5 | import com.farshad.algotrading.backtesting.FetchingForexBacktest; 6 | import org.apache.log4j.Logger; 7 | 8 | import java.io.IOException; 9 | 10 | 11 | /** 12 | * @author Farshad Noravesh 13 | */ 14 | public class AlgoTrader { 15 | 16 | final static Logger logger= Logger.getLogger(AlgoTrader.class); 17 | 18 | public static void main(String[] args) throws IOException, InterruptedException { 19 | 20 | String mode="live"; 21 | //String mode="backTest"; 22 | 23 | if (mode.equals("backTest")){ 24 | //BackTest backTest=new HMMBackTest(); 25 | // BackTest backTest=new FibonacciBackTest(); 26 | //BackTest backTest=new ATSBackTest(); 27 | BackTest backTest=new FetchingForexBacktest(); 28 | backTest.begin(); 29 | }else if(mode.equals("live")){ 30 | LiveTrading liveTrading=new LiveTrading(); 31 | liveTrading.beginLiveTrading(); 32 | } 33 | 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/LiveTrading.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading; 2 | 3 | import com.farshad.algotrading.OpenFinDesklogLevels.LiveTradingLogLevel; 4 | import com.farshad.algotrading.core.OpenFinDeskExitRule.QuantizedTpAndSlExitRule; 5 | import com.farshad.algotrading.core.OpenFinDeskExitRule.OpenFinDeskExitRule; 6 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 7 | import com.farshad.algotrading.core.openFinDeskStore.influxdb.InfluxDB; 8 | import com.farshad.algotrading.core.sockets.SocketUtil; 9 | import com.farshad.algotrading.openFinDeskAnnotations.StrategyContainerHandler; 10 | import org.apache.log4j.Logger; 11 | 12 | import com.farshad.algotrading.core.openFinDeskStore.csv.stocksInputData.OpenFinDeskMessage; 13 | import com.farshad.algotrading.core.Symbol; 14 | 15 | import java.io.File; 16 | import java.net.ServerSocket; 17 | 18 | import java.io.IOException; 19 | import java.util.HashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | /** 24 | * @author Farshad Noravesh 25 | */ 26 | public class LiveTrading { 27 | 28 | final static Logger logger= Logger.getLogger(LiveTrading.class); 29 | private ServerSocket ss; 30 | static int loop=0; 31 | static int symbolId=0; 32 | private StrategyContainerHandler strategyContainerHandler; 33 | public LiveTrading() throws IOException { 34 | String directory="openFinDeskLogs"; 35 | new File(directory).mkdirs(); 36 | System.setProperty("java.net.preferIPv4Stack" , "true"); 37 | ss = new ServerSocket(5555); 38 | } 39 | 40 | 41 | 42 | public void beginLiveTrading() throws IOException, InterruptedException { 43 | 44 | logger.log(LiveTradingLogLevel.PROCESS,"Live Algorithmic Trading Started"); 45 | logger.log(LiveTradingLogLevel.SIGNALS, "Trading Signals using OpenFinDesk,analyzing Forex..."); 46 | 47 | SocketUtil socketUtil=null; 48 | 49 | InfluxDB influxDB=new InfluxDB(); 50 | Symbol eurusdSymbol = new Symbol(influxDB,"EURUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 51 | Symbol audusdSymbol = new Symbol(influxDB,"AUDUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 52 | Symbol gbpusdSymbol = new Symbol(influxDB,"GBPUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 53 | Symbol euraudSymbol = new Symbol(influxDB,"EURAUD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 54 | 55 | Map idToSymbol=new HashMap<>(); 56 | idToSymbol.put(0,eurusdSymbol); 57 | idToSymbol.put(1,audusdSymbol); 58 | idToSymbol.put(2,gbpusdSymbol); 59 | idToSymbol.put(3,euraudSymbol); 60 | 61 | OpenFinDeskExitRule quantizedTpAndSlExitRule=new QuantizedTpAndSlExitRule(); 62 | 63 | while(true) { 64 | loop++; 65 | symbolId = loop % 4; 66 | System.out.println("loop=" + loop); 67 | strategyContainerHandler=new StrategyContainerHandler(); 68 | strategyContainerHandler.setNumberOfContainers(6); 69 | idToSymbol.get(symbolId).fetchCandlesFromMT5AndWriteItToOpenFinDeskStore(25); 70 | 71 | socketUtil = idToSymbol.get(symbolId).getSocketUtil(); 72 | strategyContainerHandler.setTimeSeriesForAllTimeFrames(idToSymbol.get(symbolId).getSeries()); 73 | strategyContainerHandler.handle(); 74 | 75 | List openFinDeskOrders = strategyContainerHandler.getOpenFinDeskOrders(); 76 | openFinDeskOrders.stream().forEach(op->logger.info("op="+op.getStrategyName())); 77 | 78 | for (int i = 0; i < openFinDeskOrders.size(); i++) { 79 | 80 | if (strategyContainerHandler.getContainers().get(i).isDisabled()){ 81 | continue; 82 | } 83 | 84 | logger.log(LiveTradingLogLevel.PROCESS, "oh,let me see if there is a signal for " + strategyContainerHandler.getOpenFinDeskOrders().get(i).getSymbol()+" in strategy container "+i); 85 | quantizedTpAndSlExitRule.setSeries(idToSymbol.get(symbolId).getSeries()[0]); 86 | quantizedTpAndSlExitRule.setOpenFinDeskOrder(openFinDeskOrders.get(i)); 87 | quantizedTpAndSlExitRule.applyExitRule(); 88 | openFinDeskOrders.set(i, quantizedTpAndSlExitRule.getOpenFinDeskOrder()); 89 | if (!openFinDeskOrders.get(i).getStrategyName().equals("noStrategy")) { 90 | if((openFinDeskOrders.get(i).getOrderType().equals("openBuy"))||(openFinDeskOrders.get(i).getOrderType().equals("openSell"))){ 91 | logger.log(LiveTradingLogLevel.SIGNALS, "strategy:" + openFinDeskOrders.get(i).getStrategyName() + " ,symbol:" + openFinDeskOrders.get(i).getSymbol()); 92 | logger.log(LiveTradingLogLevel.SIGNALS, "orderType:" + openFinDeskOrders.get(i).getOrderType() + " ,profitMargin:" + openFinDeskOrders.get(i).getTakeProfit() + " ,lossMargin:" + openFinDeskOrders.get(i).getStopLoss()); 93 | } 94 | } 95 | logger.info("openFinDeskOrder.getOrderType()=" + openFinDeskOrders.get(i).getOrderType()); 96 | logger.debug("---------end of processing in loop:" + loop + "-----------"); 97 | 98 | 99 | if (!(openFinDeskOrders.get(i).getOrderType().equals("noOrder"))) { 100 | String findAllTicketNumbersCommand = "findAllTicketNumbers" + "," + idToSymbol.get(symbolId).getSymbolName() + "," + "end"; 101 | OpenFinDeskMessage findAllTicketNumbersMessage = socketUtil.sendMessage(findAllTicketNumbersCommand); 102 | idToSymbol.get(symbolId).setTicketNumbers(findAllTicketNumbersMessage); 103 | String order = idToSymbol.get(symbolId).stringifyOrder(openFinDeskOrders.get(i)); 104 | logger.info("order=" + order); 105 | socketUtil.sendMessage(order); 106 | } 107 | } 108 | 109 | String getProfitForTheCurrentSymbolCommand="getProfitFromHistory"+","+ idToSymbol.get(symbolId).getSymbolName()+","+"end"; 110 | OpenFinDeskMessage profitForCurrentSymbolMessage=socketUtil.sendMessage(getProfitForTheCurrentSymbolCommand); 111 | if(!profitForCurrentSymbolMessage.getPayload().equals("")){ 112 | double reward= Double.parseDouble(profitForCurrentSymbolMessage.getPayload()); 113 | idToSymbol.get(symbolId).setReward(reward); 114 | } 115 | } 116 | } 117 | 118 | 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/OpenFinDesklogLevels/LiveTradingLogLevel.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.OpenFinDesklogLevels; 2 | 3 | 4 | import org.apache.log4j.Level; 5 | 6 | 7 | 8 | public class LiveTradingLogLevel extends Level { 9 | 10 | public static final int PROCESS_INT = DEBUG_INT -10; 11 | public static final int SOCKETUTIL_INT = INFO_INT -11; 12 | public static final int SIGNALS_INT = WARN_INT +12; 13 | 14 | 15 | public static final Level PROCESS = new LiveTradingLogLevel(PROCESS_INT, "PROCESS", 1); 16 | public static final Level SOCKETUTIL = new LiveTradingLogLevel(SOCKETUTIL_INT, "SOCKETUTIL", 2); 17 | public static final Level SIGNALS = new LiveTradingLogLevel(SIGNALS_INT, "SIGNALS", 3); 18 | 19 | 20 | 21 | public LiveTradingLogLevel(int level, String name, int value) { 22 | super(level,name, value); 23 | } 24 | 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/OpenFinDesklogLevels/RLLogLevel.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.OpenFinDesklogLevels; 2 | 3 | 4 | import org.apache.log4j.Level; 5 | 6 | public class RLLogLevel extends Level { 7 | 8 | public static final int REWARD_INT = INFO_INT -10; 9 | public static final int CURRENTSTATE_INT = INFO_INT -11; 10 | public static final int QAction_INT = INFO_INT -12; 11 | public static final int MAXForQACTION_INT = INFO_INT -13; 12 | 13 | 14 | public static final Level REWARD = new RLLogLevel(REWARD_INT, "REWARD", 1); 15 | public static final Level CURRENTSTATE = new RLLogLevel(CURRENTSTATE_INT, "CURRENTSTATE", 2); 16 | public static final Level QAction = new RLLogLevel(QAction_INT, "QACTION", 3); 17 | public static final Level MAXForQACTION = new RLLogLevel(MAXForQACTION_INT, "MaxForQACTION", 4); 18 | 19 | 20 | 21 | 22 | public RLLogLevel(int level, String name, int value) { 23 | super(level,name, value); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/ATSBackTest.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting; 2 | 3 | import com.farshad.algotrading.core.AlternatingTrendSmoothing.ATS; 4 | import com.farshad.algotrading.backtesting.influxDbCRUD.InfluxDbManager; 5 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.PriceTime; 6 | import com.farshad.algotrading.core.Symbol; 7 | import com.farshad.algotrading.core.openFinDeskStore.influxdb.InfluxDB; 8 | import org.apache.log4j.Logger; 9 | import org.ta4j.core.TimeSeries; 10 | 11 | import java.io.IOException; 12 | import java.net.ServerSocket; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | /** 16 | * @author Farshad Noravesh 17 | */ 18 | public class ATSBackTest extends BackTest { 19 | 20 | final static Logger logger= Logger.getLogger(ATSBackTest.class); 21 | private ServerSocket ss; 22 | 23 | 24 | public ATSBackTest() throws IOException { 25 | 26 | } 27 | 28 | @Override 29 | public void begin() throws IOException { 30 | logger.info("*******ATSBackTest************"); 31 | ss = new ServerSocket(5555); 32 | 33 | InfluxDB influxDB=new InfluxDB(); 34 | Symbol eurusdSymbol = new Symbol(influxDB,"EURUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 35 | Symbol audusdSymbol = new Symbol(influxDB,"AUDUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 36 | Symbol gbpusdSymbol = new Symbol(influxDB,"GBPUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 37 | 38 | 39 | //audusdSymbolD1.fetchCandlesFromMT5AndWriteItToOpenFinDeskStore(); 40 | audusdSymbol.fetchCandlesFromMT5AndWriteItToOpenFinDeskStore(30); 41 | 42 | //TimeSeries series=audusdSymbolD1.getSeries(); 43 | TimeSeries series=audusdSymbol.getSeries()[0]; 44 | 45 | List priceTimeList=new ArrayList<>(); 46 | int index=series.getBarCount(); 47 | for(int i=index-25;i priceTimeChangePointList1=ats1.getPriceChangeList(); 56 | priceTimeChangePointList1.stream().forEach(pricetimechange-> { 57 | logger.info(pricetimechange.getTime()+" "+pricetimechange.getPrice()); 58 | }); 59 | */ 60 | ATS ats=new ATS(4,priceTimeList); 61 | ats.findPriceChangePoints(); 62 | List priceTimeChangePointList=ats.getPriceChangeList(); 63 | priceTimeChangePointList.stream().forEach(pricetimechange-> { 64 | logger.info(pricetimechange.getTime()+" "+pricetimechange.getPrice()); 65 | }); 66 | 67 | 68 | InfluxDbManager influxDbManager=new InfluxDbManager("PERIOD_D1","priceTime"); 69 | influxDbManager.executeSomeQuery("DROP MEASUREMENT \"priceTime\"",PriceTime.class); 70 | influxDbManager.close(); 71 | influxDbManager=new InfluxDbManager("PERIOD_H1","priceTime"); 72 | influxDbManager.executeSomeQuery("DROP MEASUREMENT \"priceTime\"",PriceTime.class); 73 | influxDbManager.close(); 74 | 75 | 76 | 77 | //influxDbManager=new InfluxDbManager("PERIOD_D1","priceTime"); 78 | influxDbManager=new InfluxDbManager("PERIOD_H1","priceTime"); 79 | try { 80 | influxDbManager.writeTimeSeries(priceTimeChangePointList,"price"); 81 | } catch (NoSuchFieldException e) { 82 | e.printStackTrace(); 83 | } catch (IllegalAccessException e) { 84 | e.printStackTrace(); 85 | } 86 | influxDbManager.close(); 87 | 88 | 89 | 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/BackTest.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting; 2 | 3 | import com.farshad.algotrading.core.sockets.SocketUtil; 4 | import com.farshad.algotrading.core.openFinDeskStore.csv.stocksInputData.OHLCData; 5 | 6 | import java.io.IOException; 7 | import java.net.ServerSocket; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | /** 11 | * @author Farshad Noravesh 12 | */ 13 | public abstract class BackTest { 14 | 15 | private ServerSocket ss; 16 | private SocketUtil socketUtil; 17 | private List ohlcDataList; 18 | 19 | protected BackTest() throws IOException { 20 | // ss=new ServerSocket(5555); 21 | // socketUtil=new SocketUtil(ss,new Socket()); 22 | ohlcDataList=new ArrayList<>(); 23 | 24 | } 25 | 26 | public abstract void begin() throws IOException; 27 | 28 | public List fetchDataUsingMetaTrader5(String symbolName,String timeFrame,int fromCandle,int numberOfCandles) { 29 | ohlcDataList.clear(); 30 | try { 31 | String message=""; 32 | message="fetchCandles"+","+symbolName+","+timeFrame+","+fromCandle+","+numberOfCandles; 33 | socketUtil.sendMessage(message); 34 | ohlcDataList=socketUtil.getOhlcDataList(); 35 | } catch (IOException e) { 36 | e.printStackTrace(); 37 | } catch (InterruptedException e) { 38 | e.printStackTrace(); 39 | } 40 | 41 | return ohlcDataList; 42 | } 43 | 44 | public List getOhlcDataList() { 45 | return ohlcDataList; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/ExpectationMaximizationAlgorithm/ExpectationMaximization.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.ExpectationMaximizationAlgorithm; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | public class ExpectationMaximization { 6 | 7 | final static Logger logger= Logger.getLogger(ExpectationMaximization.class); 8 | 9 | 10 | private String probabilityType; 11 | 12 | private double meanOfb; 13 | private double meanOfa; 14 | 15 | private double varianceOfb; 16 | private double varianceOfa; 17 | 18 | 19 | private double[] probabilityOfxConditionedOnb; 20 | 21 | private double[] probabilityOfbConditionedOnx; 22 | 23 | private double[] probabilityOfaConditionedOnx; 24 | 25 | private double[] probabilityOfxConditionedOna; 26 | 27 | private int batchSizeOfx; 28 | 29 | 30 | 31 | private double probabilityOfb; 32 | 33 | private double probabilityOfa; 34 | 35 | public ExpectationMaximization(String probabilityType, int batchSize) { 36 | batchSizeOfx=batchSize; 37 | this.probabilityType=probabilityType; 38 | probabilityOfxConditionedOnb=new double[batchSizeOfx]; 39 | probabilityOfxConditionedOna=new double[batchSizeOfx]; 40 | probabilityOfbConditionedOnx=new double[batchSizeOfx]; 41 | probabilityOfaConditionedOnx=new double[batchSizeOfx]; 42 | } 43 | 44 | public void initializeMeanAndVariance() { 45 | probabilityOfb=0.5; 46 | probabilityOfa=1-probabilityOfb; 47 | meanOfb=1.2; 48 | meanOfa=1.4; 49 | varianceOfb=0.1; 50 | varianceOfa=0.1; 51 | } 52 | 53 | public void findMeanAndVariance(double[] batchedx) { 54 | expectationStep(batchedx); 55 | maximizationStep(batchedx); 56 | } 57 | 58 | 59 | private void expectationStep(double[] batchedx) { 60 | for(int i=0;i audusdSymbol = new Symbol(influxDB,"AUDUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 28 | Symbol gbpusdSymbol = new Symbol(influxDB,"GBPUSD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 29 | Symbol euraudSymbol = new Symbol(influxDB,"EURAUD", new String[]{"PERIOD_H1","PERIOD_D1"}, "forex",ss); 30 | 31 | 32 | // eurusdSymbol.fetchCandlesFromMT5AndWriteItToOpenFinDeskStore(100); 33 | // audusdSymbol.fetchCandlesFromMT5AndWriteItToOpenFinDeskStore(100); 34 | // gbpusdSymbol.fetchCandlesFromMT5AndWriteItToOpenFinDeskStore(100); 35 | euraudSymbol.fetchCandlesFromMT5AndWriteItToOpenFinDeskStore(100); 36 | 37 | // TimeSeries series=audusdSymbol.getSeries()[0]; 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/FibonacciBackTest.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting; 2 | 3 | 4 | import com.farshad.algotrading.backtesting.influxDbCRUD.InfluxDbManager; 5 | import com.farshad.algotrading.backtesting.measurements.AUDUSDCandlePoint; 6 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.PriceTime; 7 | import com.farshad.algotrading.core.AlternatingTrendSmoothing.ATS; 8 | import com.farshad.algotrading.core.trendRangeAndWave.Trend; 9 | import com.farshad.algotrading.core.trendRangeAndWave.TrendGenerator; 10 | import com.farshad.algotrading.core.trendRangeAndWave.Wave; 11 | import com.farshad.algotrading.core.trendRangeAndWave.WaveGenerator; 12 | import com.farshad.algotrading.core.fibonacciCore.Fibonacci; 13 | import org.apache.log4j.Logger; 14 | 15 | import java.io.IOException; 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | /** 19 | * @author Farshad Noravesh 20 | */ 21 | public class FibonacciBackTest extends BackTest { 22 | 23 | 24 | final static Logger logger= Logger.getLogger(FibonacciBackTest.class); 25 | 26 | 27 | public FibonacciBackTest() throws IOException { 28 | } 29 | 30 | @Override 31 | public void begin() { 32 | logger.info("---com.farshad.algotrading.backtesting fibonacci---"); 33 | /* 34 | List allOhlcDataList=new ArrayList<>(); 35 | int batchSize=6; 36 | int howManyBatches=2; 37 | int totalCandles=howManyBatches*batchSize; 38 | for(int i=1;i<=totalCandles;i=i+batchSize) { 39 | fetchDataUsingMetaTrader5("EURUSD", "PERIOD_H4", i-1, batchSize); 40 | allOhlcDataList.addAll(getOhlcDataList()); 41 | } 42 | allOhlcDataList.stream().forEach(candle-> System.out.println("candle.getClose())="+candle.getClose())); 43 | */ 44 | InfluxDbManager influxDbManager=new InfluxDbManager("H4","EURUSD"); 45 | //influxDbManager.writeCandles(allOhlcDataList); 46 | 47 | String query="SELECT * FROM "+influxDbManager.getMeasurement(); 48 | List candlePointList=influxDbManager.executeSomeQuery(query, AUDUSDCandlePoint.class); 49 | 50 | candlePointList.stream().forEach(candle-> 51 | { 52 | // System.out.println("candle.getClose():" + candle.getClose()); 53 | // System.out.println("candle.getTime().getEpochSecond():" + candle.getTime().getEpochSecond()); 54 | } 55 | ); 56 | influxDbManager.close(); 57 | 58 | 59 | 60 | List priceTimeList=new ArrayList<>(); 61 | 62 | for(int i=candlePointList.size()-30;i priceTimeChangePointList=ats.getPriceChangeList(); 71 | 72 | influxDbManager=new InfluxDbManager("H4","trendPointsEURUSD"); 73 | influxDbManager.executeSomeQuery("DROP MEASUREMENT \"trendPointsEURUSD\"",PriceTime.class); 74 | influxDbManager.close(); 75 | 76 | influxDbManager=new InfluxDbManager("H4","trendPointsEURUSD"); 77 | try { 78 | influxDbManager.writeTimeSeries(priceTimeChangePointList,"price"); 79 | } catch (NoSuchFieldException e) { 80 | e.printStackTrace(); 81 | } catch (IllegalAccessException e) { 82 | e.printStackTrace(); 83 | } 84 | influxDbManager.close(); 85 | 86 | TrendGenerator trendGenerator=new TrendGenerator(priceTimeChangePointList); 87 | List trendList=trendGenerator.generate(); 88 | 89 | WaveGenerator waveGenerator=new WaveGenerator(trendList,trendGenerator.getStartingIndex()); 90 | List waveList=waveGenerator.generate(); 91 | 92 | 93 | Fibonacci fibonacci=new Fibonacci(); 94 | fibonacci.addWaves(waveList); 95 | if(trendList.size()%2==1){ 96 | fibonacci.addTrend(trendList.get(trendList.size()-1)); 97 | } 98 | 99 | fibonacci.calculateTypeOfGlobalRegime(); 100 | logger.info("fibonacci.getTypeOfGlobalRegime()="+fibonacci.getTypeOfGlobalRegime()); 101 | 102 | fibonacci.calculateInternalRetracement(); 103 | fibonacci.calculateGlobalStrength(); 104 | double strength=fibonacci.getStrength(); 105 | 106 | 107 | /* 108 | FiboClusterManager fiboClusterManager=new FiboClusterManager(); 109 | waveList.forEach(w-> { 110 | fibonacci.setWave(w); 111 | fiboClusterManager.add(fibonacci); 112 | }); 113 | fiboClusterManager.manage(); 114 | */ 115 | 116 | 117 | } 118 | 119 | 120 | 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/HMM/BackwardAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.HMM; 2 | 3 | import com.farshad.algotrading.backtesting.ExpectationMaximizationAlgorithm.ExpectationMaximization; 4 | import org.apache.log4j.Logger; 5 | 6 | public class BackwardAlgorithm { 7 | 8 | final static Logger logger= Logger.getLogger(BackwardAlgorithm.class); 9 | 10 | 11 | private int numberOfHiddenStates; 12 | 13 | private int numberOfValuesInEachHiddenState; 14 | 15 | private double x[]; 16 | 17 | 18 | private double beta00; 19 | 20 | private double beta01; 21 | 22 | 23 | private double[][] transitionProbability; 24 | 25 | private int batchSize; 26 | 27 | 28 | 29 | private ExpectationMaximization expectationMaximization; 30 | 31 | 32 | public BackwardAlgorithm(int numberOfHiddenStates, int numberOfValuesInEachHiddenState,int numberOfObservationData) { 33 | this.numberOfHiddenStates = numberOfHiddenStates; 34 | this.numberOfValuesInEachHiddenState = numberOfValuesInEachHiddenState; 35 | x=new double[numberOfObservationData]; 36 | transitionProbability=new double[numberOfHiddenStates][numberOfHiddenStates]; 37 | } 38 | 39 | public void runHMM(double[] x, int batchSize) { 40 | for(int i=0;i percentageChangeList=new ArrayList<>(); 19 | private List extremeList=new ArrayList<>(); 20 | private List returnList=new ArrayList<>(); 21 | private List duration=new ArrayList<>(); 22 | 23 | public void classifyTrends(List candlePointList){ 24 | //System.out.println("size of data="+candlePointList.size()); 25 | difference =new double[candlePointList.size()]; 26 | 27 | for(int i=0;i0.2){ 36 | extremeList.add(candlePointList.get(i)); 37 | 38 | } 39 | } 40 | 41 | trendCloseDifferenceForExtreme=new double[extremeList.size()]; 42 | 43 | for(int j=0;j allOhlcDataList=new ArrayList<>(); 30 | int batchSize=6; 31 | int howManyBatches=90; 32 | int totalCandles=howManyBatches*batchSize; 33 | for(int i=1;i("PERIOD_H4","EURUSD"); 39 | influxDbManager.writeCandles(allOhlcDataList); 40 | 41 | String query="SELECT * FROM "+influxDbManager.getMeasurement(); 42 | List candlePointList=influxDbManager.executeSomeQuery(query, AUDUSDCandlePoint.class); 43 | 44 | // candlePointList.stream().forEach(candle-> System.out.println("candle.getClose():"+candle.getClose())); 45 | influxDbManager.close(); 46 | 47 | RegimeAnalyzer regimeAnalyzer=new RegimeAnalyzer(); 48 | regimeAnalyzer.classifyTrends(candlePointList); 49 | influxDbManager=new InfluxDbManager("H4","EURUSDChangeInPercent"); 50 | try { 51 | influxDbManager.writeTimeSeries(regimeAnalyzer.getPercentageChange(),"percent"); 52 | } catch (NoSuchFieldException e) { 53 | e.printStackTrace(); 54 | } catch (IllegalAccessException e) { 55 | e.printStackTrace(); 56 | } 57 | query="SELECT * FROM "+influxDbManager.getMeasurement(); 58 | influxDbManager.executeSomeQuery(query,PercentOfChange.class); 59 | influxDbManager.close(); 60 | 61 | //Now writing extreme to influxDb 62 | influxDbManager=new InfluxDbManager("H4","EURUSDExtreme"); 63 | try { 64 | influxDbManager.writeTimeSeries(regimeAnalyzer.getExtremeList(),"close"); 65 | } catch (NoSuchFieldException e) { 66 | e.printStackTrace(); 67 | } catch (IllegalAccessException e) { 68 | e.printStackTrace(); 69 | } 70 | query="SELECT * FROM "+influxDbManager.getMeasurement(); 71 | List candlePointListForExtremes=influxDbManager.executeSomeQuery(query, AUDUSDCandlePoint.class); 72 | candlePointListForExtremes.stream().forEach(candle-> System.out.println("candle:"+candle.getClose())); 73 | influxDbManager.close(); 74 | 75 | 76 | //Now writing returns to influxDb 77 | influxDbManager=new InfluxDbManager("H4","EURUSDReturn"); 78 | try { 79 | influxDbManager.writeTimeSeries(regimeAnalyzer.getReturnList(),"returnValue"); 80 | } catch (NoSuchFieldException e) { 81 | e.printStackTrace(); 82 | } catch (IllegalAccessException e) { 83 | e.printStackTrace(); 84 | } 85 | query="SELECT * FROM "+influxDbManager.getMeasurement(); 86 | List returnList=influxDbManager.executeSomeQuery(query, Return.class); 87 | //returnList.stream().forEach(returnV-> System.out.println("returnValue:"+returnV.getReturnValue())); 88 | influxDbManager.close(); 89 | 90 | //Hidden Markov Model using Backward Algorithm 91 | logger.info("size="+returnList.size()); 92 | double[] x=new double[returnList.size()]; 93 | for(int i=0;i ohlcDataList) { 44 | 45 | Pong response = influxDB.ping(); 46 | if (response.getVersion().equalsIgnoreCase("unknown")) { 47 | logger.error("Error pinging server"); 48 | return; 49 | }else{ 50 | logger.info("response.getVersion()="+response.getVersion()); 51 | } 52 | 53 | BatchPoints batchPoints = BatchPoints.database(this.database).tag("async", "true").build(); 54 | 55 | influxDB.enableBatch(); 56 | for (int i = 0; i < ohlcDataList.size(); i++) { 57 | String dateInForex=ohlcDataList.get(i).getTime().split(" ")[0]; 58 | String timeInForex=ohlcDataList.get(i).getTime().split(" ")[1]; 59 | ZoneId zoneId =ZoneId.of("UTC"); 60 | LocalDate localdate =LocalDate.parse( 61 | dateInForex.split("\\.")[0]+"-" 62 | + dateInForex.split("\\.")[1]+"-" 63 | + dateInForex.split("\\.")[2] 64 | ); 65 | LocalTime localtime = LocalTime.parse(timeInForex+":00"); 66 | ZonedDateTime zt = ZonedDateTime.of(localdate, localtime, zoneId); 67 | Point point = Point.measurement(this.measurement) 68 | .time(zt.toEpochSecond(), TimeUnit.SECONDS) 69 | .addField("open", Double.parseDouble(ohlcDataList.get(i).getOpen())) 70 | .addField("high", Double.parseDouble(ohlcDataList.get(i).getHigh())) 71 | .addField("low", Double.parseDouble((ohlcDataList.get(i).getLow()))) 72 | .addField("close", Double.parseDouble((ohlcDataList.get(i).getClose()))) 73 | .addField("volume", Integer.parseInt(ohlcDataList.get(i).getTick_volume())) 74 | .build(); 75 | batchPoints.point(point); 76 | 77 | } 78 | influxDB.write(batchPoints); 79 | } 80 | 81 | public void writeTimeSeries(List timeSeries,String fieldString) throws NoSuchFieldException, IllegalAccessException { 82 | this.timeSeries=timeSeries; 83 | BatchPoints batchPoints = BatchPoints.database(this.database).tag("async", "true").build(); 84 | influxDB.enableBatch(); 85 | for (int i = 0; i < timeSeries.size(); i++) { 86 | Field field = timeSeries.get(i).getClass().getDeclaredField(fieldString); 87 | field.setAccessible(true); 88 | Object value = field.get(timeSeries.get(i)); 89 | Point point = Point.measurement(this.measurement) 90 | .time(timeSeries.get(i).getTime().getEpochSecond(), TimeUnit.SECONDS) 91 | .addField(fieldString, (Double) value) 92 | .build(); 93 | batchPoints.point(point); 94 | } 95 | influxDB.write(batchPoints); 96 | } 97 | 98 | public List executeSomeQuery(String query,Class clazz) { 99 | Query influxDbQuery = new Query(query, this.database); 100 | QueryResult queryResult = influxDB.query(influxDbQuery); 101 | InfluxDBResultMapper resultMapper = new InfluxDBResultMapper(); 102 | List resultList = resultMapper 103 | .toPOJO(queryResult,clazz); 104 | return resultList; 105 | } 106 | 107 | public void close() { 108 | influxDB.close(); 109 | } 110 | 111 | public String getDatabase() { 112 | return database; 113 | } 114 | 115 | public void setDatabase(String database) { 116 | this.database = database; 117 | } 118 | 119 | public String getMeasurement() { 120 | return measurement; 121 | } 122 | 123 | public void setMeasurement(String measurement) { 124 | this.measurement = measurement; 125 | } 126 | 127 | 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/AUDUSDCandlePoint.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements; 2 | 3 | 4 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.TimeSeriesPoint; 5 | import org.influxdb.annotation.Column; 6 | import org.influxdb.annotation.Measurement; 7 | 8 | @Measurement(name = "AUDUSD") 9 | public class AUDUSDCandlePoint extends TimeSeriesPoint { 10 | 11 | 12 | @Column(name = "open") 13 | private double open; 14 | 15 | @Column(name = "high") 16 | private double high; 17 | 18 | @Column(name = "low") 19 | private double low; 20 | 21 | @Column(name = "close") 22 | private double close; 23 | 24 | @Column(name = "volume") 25 | private int volume; 26 | 27 | 28 | public double getOpen() { 29 | return open; 30 | } 31 | 32 | public double getHigh() { 33 | return high; 34 | } 35 | 36 | public double getLow() { 37 | return low; 38 | } 39 | 40 | public double getClose() { 41 | return close; 42 | } 43 | 44 | public int getVolume() { 45 | return volume; 46 | } 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/EURAUDCandlePoint.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements; 2 | 3 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.TimeSeriesPoint; 4 | import org.influxdb.annotation.Column; 5 | import org.influxdb.annotation.Measurement; 6 | 7 | 8 | @Measurement(name = "EURAUD") 9 | public class EURAUDCandlePoint extends TimeSeriesPoint { 10 | 11 | 12 | @Column(name = "open") 13 | private double open; 14 | 15 | @Column(name = "high") 16 | private double high; 17 | 18 | @Column(name = "low") 19 | private double low; 20 | 21 | @Column(name = "close") 22 | private double close; 23 | 24 | @Column(name = "volume") 25 | private int volume; 26 | 27 | 28 | public double getOpen() { 29 | return open; 30 | } 31 | 32 | public double getHigh() { 33 | return high; 34 | } 35 | 36 | public double getLow() { 37 | return low; 38 | } 39 | 40 | public double getClose() { 41 | return close; 42 | } 43 | 44 | public int getVolume() { 45 | return volume; 46 | } 47 | } 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/EURUSDCandlePoint.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements; 2 | 3 | 4 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.TimeSeriesPoint; 5 | import org.influxdb.annotation.Column; 6 | import org.influxdb.annotation.Measurement; 7 | 8 | @Measurement(name = "EURUSD") 9 | public class EURUSDCandlePoint extends TimeSeriesPoint { 10 | 11 | 12 | @Column(name = "open") 13 | private double open; 14 | 15 | @Column(name = "high") 16 | private double high; 17 | 18 | @Column(name = "low") 19 | private double low; 20 | 21 | @Column(name = "close") 22 | private double close; 23 | 24 | @Column(name = "volume") 25 | private int volume; 26 | 27 | 28 | public double getOpen() { 29 | return open; 30 | } 31 | 32 | public double getHigh() { 33 | return high; 34 | } 35 | 36 | public double getLow() { 37 | return low; 38 | } 39 | 40 | public double getClose() { 41 | return close; 42 | } 43 | 44 | public int getVolume() { 45 | return volume; 46 | } 47 | } 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/GBPUSDCandlePoint.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements; 2 | 3 | 4 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.TimeSeriesPoint; 5 | import org.influxdb.annotation.Column; 6 | import org.influxdb.annotation.Measurement; 7 | 8 | @Measurement(name = "GBPUSD") 9 | public class GBPUSDCandlePoint extends TimeSeriesPoint { 10 | 11 | 12 | @Column(name = "open") 13 | private double open; 14 | 15 | @Column(name = "high") 16 | private double high; 17 | 18 | @Column(name = "low") 19 | private double low; 20 | 21 | @Column(name = "close") 22 | private double close; 23 | 24 | @Column(name = "volume") 25 | private int volume; 26 | 27 | 28 | public double getOpen() { 29 | return open; 30 | } 31 | 32 | public double getHigh() { 33 | return high; 34 | } 35 | 36 | public double getLow() { 37 | return low; 38 | } 39 | 40 | public double getClose() { 41 | return close; 42 | } 43 | 44 | public int getVolume() { 45 | return volume; 46 | } 47 | } 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/timeSeriesMeasurements/PercentOfChange.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements; 2 | 3 | 4 | import org.influxdb.annotation.Column; 5 | import org.influxdb.annotation.Measurement; 6 | 7 | @Measurement(name = "EURUSDChangeInPercent") 8 | public class PercentOfChange extends TimeSeriesPoint { 9 | 10 | 11 | @Column(name = "percent") 12 | private double percent; 13 | 14 | 15 | public double getPercent() { 16 | return percent; 17 | } 18 | 19 | public void setPercent(double percent) { 20 | this.percent = percent; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/timeSeriesMeasurements/PriceTime.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements; 2 | 3 | import org.influxdb.annotation.Column; 4 | import org.influxdb.annotation.Measurement; 5 | 6 | import java.time.Instant; 7 | 8 | 9 | @Measurement(name = "priceTime") 10 | public class PriceTime extends TimeSeriesPoint { 11 | 12 | 13 | @Column(name = "price") 14 | private double price; 15 | 16 | private Instant time; 17 | 18 | 19 | public PriceTime(double price,Instant time) { 20 | this.time = time; 21 | this.price = price; 22 | } 23 | 24 | @Override 25 | public Instant getTime() { 26 | return time; 27 | } 28 | 29 | @Override 30 | public void setTime(Instant time) { 31 | this.time = time; 32 | } 33 | 34 | public double getPrice() { 35 | return price; 36 | } 37 | 38 | public void setPrice(double price) { 39 | this.price = price; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/timeSeriesMeasurements/Return.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements; 2 | 3 | import org.influxdb.annotation.Column; 4 | import org.influxdb.annotation.Measurement; 5 | 6 | 7 | @Measurement(name = "EURUSDReturn") 8 | public class Return extends TimeSeriesPoint{ 9 | 10 | @Column(name = "returnValue") 11 | private double returnValue; 12 | 13 | public double getReturnValue() { 14 | return returnValue; 15 | } 16 | 17 | public void setReturnValue(double returnValue) { 18 | this.returnValue = returnValue; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/backtesting/measurements/timeSeriesMeasurements/TimeSeriesPoint.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements; 2 | 3 | import org.influxdb.annotation.Column; 4 | 5 | import java.time.Instant; 6 | 7 | public class TimeSeriesPoint { 8 | @Column(name = "time") 9 | private Instant time; 10 | 11 | public Instant getTime() { 12 | return time; 13 | } 14 | 15 | public void setTime(Instant time) { 16 | this.time = time; 17 | } 18 | 19 | 20 | private String symbolName; 21 | 22 | 23 | public String getSymbolName() { 24 | return symbolName; 25 | } 26 | 27 | public void setSymbolName(String symbolName) { 28 | this.symbolName = symbolName; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/AlternatingTrendSmoothing/ATS.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.AlternatingTrendSmoothing; 2 | 3 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.PriceTime; 4 | import org.apache.log4j.Logger; 5 | 6 | import java.time.Instant; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class ATS { 11 | final static Logger logger= Logger.getLogger(ATS.class); 12 | 13 | public List priceChangeList; 14 | 15 | 16 | private int h; 17 | private List priceTimeList; 18 | 19 | 20 | private double slope; 21 | 22 | public ATS(int h, List priceTimeList) { 23 | this.h=h; 24 | this.priceTimeList=priceTimeList; 25 | this.priceChangeList=new ArrayList<>(); 26 | 27 | } 28 | 29 | public void findPriceChangePoints() { 30 | Instant[] b=new Instant[700]; 31 | 32 | double[] c=new double[b.length]; 33 | float r=1; 34 | c[h]=priceTimeList.get(h).getPrice(); 35 | slope = (c[h] - c[0]) ; 36 | 37 | r= (float) Math.signum(slope); 38 | 39 | int m=0; 40 | int d=0; 41 | while((m+h)(); 35 | } 36 | 37 | public List getFeatureVector() { 38 | return featureVector; 39 | } 40 | 41 | public void setFeatureVector(List featureVector) { 42 | this.featureVector = featureVector; 43 | } 44 | 45 | public String getCurrentStateInString() { 46 | return currentStateInString; 47 | } 48 | 49 | public void setCurrentStateInString(String currentStateInString) { 50 | this.currentStateInString = currentStateInString; 51 | } 52 | 53 | public int getTicketNumber() { 54 | return ticketNumber; 55 | } 56 | 57 | public void setTicketNumber(int ticketNumber) { 58 | this.ticketNumber = ticketNumber; 59 | } 60 | 61 | 62 | public double getTakeProfit() { 63 | return takeProfit; 64 | } 65 | 66 | public void setTakeProfit(double takeProfit) { 67 | this.takeProfit = takeProfit; 68 | } 69 | 70 | public double getStopLoss() { 71 | return stopLoss; 72 | } 73 | 74 | public void setStopLoss(double stopLoss) { 75 | this.stopLoss = stopLoss; 76 | } 77 | 78 | 79 | public String getPosition() { 80 | return position; 81 | } 82 | 83 | public void setPosition(String position) { 84 | this.position = position; 85 | } 86 | 87 | public double getPrice() { 88 | return price; 89 | } 90 | 91 | public void setPrice(double price) { 92 | this.price = price; 93 | } 94 | 95 | public String getVolume() { 96 | return volume; 97 | } 98 | 99 | public void setVolume(String volume) { 100 | this.volume = volume; 101 | } 102 | 103 | public String getSymbol() { 104 | return symbol; 105 | } 106 | 107 | public void setSymbol(String symbol) { 108 | this.symbol = symbol; 109 | } 110 | 111 | public double getReward() { 112 | return reward; 113 | } 114 | 115 | public void setReward(double reward) { 116 | this.reward = reward; 117 | } 118 | 119 | public double getOpeningPrice() { 120 | return openingPrice; 121 | } 122 | 123 | public void setOpeningPrice(double openingPrice) { 124 | this.openingPrice = openingPrice; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/OpenFinDeskExitRule/OpenFinDeskExitRule.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.OpenFinDeskExitRule; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import org.ta4j.core.TimeSeries; 5 | 6 | public abstract class OpenFinDeskExitRule { 7 | 8 | public TimeSeries series; 9 | 10 | 11 | private OpenFinDeskOrder openFinDeskOrder; 12 | 13 | public abstract void applyExitRule(); 14 | 15 | public void setOpenFinDeskOrder(OpenFinDeskOrder openFinDeskOrder){ 16 | this.openFinDeskOrder =openFinDeskOrder; 17 | 18 | } 19 | 20 | 21 | public TimeSeries setSeries(TimeSeries series) { 22 | this.series=series; 23 | return series; 24 | } 25 | 26 | public OpenFinDeskOrder getOpenFinDeskOrder() { 27 | return openFinDeskOrder; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/OpenFinDeskExitRule/ParabolicSarExitRule.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.OpenFinDeskExitRule; 2 | 3 | import org.ta4j.core.indicators.ParabolicSarIndicator; 4 | 5 | import static org.apache.commons.math3.util.Precision.round; 6 | 7 | public class ParabolicSarExitRule extends OpenFinDeskExitRule { 8 | 9 | @Override 10 | public void applyExitRule() { 11 | int lastIndex=series.getBarCount()-1; 12 | ParabolicSarIndicator parabolicSarIndicator=new ParabolicSarIndicator(series); 13 | getOpenFinDeskOrder().setPrice(series.getBar(lastIndex).getClosePrice().doubleValue()); 14 | getOpenFinDeskOrder().setStopLoss(parabolicSarIndicator.getValue(series.getBarCount()-1).doubleValue()); 15 | if(getOpenFinDeskOrder().getOrderType().equals("openBuy")){ 16 | getOpenFinDeskOrder().setTakeProfit(round(series.getBar(lastIndex).getClosePrice().doubleValue()+0.0015,5)); 17 | }else if(getOpenFinDeskOrder().getOrderType().equals("openSell")){ 18 | getOpenFinDeskOrder().setTakeProfit(round(series.getBar(lastIndex).getClosePrice().doubleValue()-0.0015,5)); 19 | } 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/OpenFinDeskExitRule/QuantizedTpAndSlExitRule.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.OpenFinDeskExitRule; 2 | 3 | 4 | import org.apache.log4j.Logger; 5 | 6 | import static org.apache.commons.math3.util.Precision.round; 7 | 8 | public class QuantizedTpAndSlExitRule extends OpenFinDeskExitRule { 9 | final static Logger logger= Logger.getLogger(QuantizedTpAndSlExitRule.class); 10 | 11 | private String quantizedExitRuleAction; 12 | 13 | @Override 14 | public void applyExitRule() { 15 | int lastIndex=series.getBarCount()-1; 16 | double price=0.5*(series.getBar(lastIndex).getClosePrice().doubleValue()+series.getBar(lastIndex).getOpenPrice().doubleValue()); 17 | logger.info("symbol="+ getOpenFinDeskOrder().getSymbol()); 18 | logger.info("price="+price); 19 | logger.info("orderType="+ getOpenFinDeskOrder().getOrderType()); 20 | getOpenFinDeskOrder().setPrice(price); 21 | logger.info("strategy="+getOpenFinDeskOrder().getStrategyName()); 22 | logger.info("action="+ getOpenFinDeskOrder().getAction()); 23 | setQuantizedExitRuleAction(getOpenFinDeskOrder().getAction()); 24 | logger.info("quantizedExitRuleAction="+quantizedExitRuleAction); 25 | 26 | 27 | 28 | switch(quantizedExitRuleAction) { 29 | 30 | case "buyUsingScalping": 31 | getOpenFinDeskOrder().setStopLoss(0.005); 32 | getOpenFinDeskOrder().setTakeProfit(round(0.0004,5)); 33 | break; 34 | 35 | case "buyUsingFirstQuantizedLevel": 36 | getOpenFinDeskOrder().setStopLoss(0.005); 37 | getOpenFinDeskOrder().setTakeProfit(round(0.0007,5)); 38 | break; 39 | case "buyUsingSecondQuantizedLevel": 40 | getOpenFinDeskOrder().setStopLoss(0.008); 41 | getOpenFinDeskOrder().setTakeProfit(round(0.0015,5)); 42 | break; 43 | case "buyUsingThirdQuantizedLevel": 44 | getOpenFinDeskOrder().setStopLoss(0.01); 45 | getOpenFinDeskOrder().setTakeProfit(round(0.0025,5)); 46 | break; 47 | case "sellUsingFirstQuantizedLevel": 48 | getOpenFinDeskOrder().setStopLoss(0.005); 49 | getOpenFinDeskOrder().setTakeProfit(round(0.0007,5)); 50 | break; 51 | case "sellUsingSecondQuantizedLevel": 52 | getOpenFinDeskOrder().setStopLoss(0.008); 53 | getOpenFinDeskOrder().setTakeProfit(round(0.0015,5)); 54 | break; 55 | case "sellUsingThirdQuantizedLevel": 56 | getOpenFinDeskOrder().setStopLoss(0.01); 57 | getOpenFinDeskOrder().setTakeProfit(round(0.0025,5)); 58 | break; 59 | case "sellUsingScalping": 60 | getOpenFinDeskOrder().setStopLoss(0.005); 61 | getOpenFinDeskOrder().setTakeProfit(round(0.0004,5)); 62 | break; 63 | } 64 | 65 | 66 | 67 | } 68 | 69 | 70 | 71 | private void setQuantizedExitRuleAction(String quantizedExitRuleAction) { 72 | this.quantizedExitRuleAction = quantizedExitRuleAction; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/containerCore/ChanceNode.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.containerCore; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | abstract public class ChanceNode{ 9 | 10 | public int nodeId; 11 | 12 | public ChanceNode chanceNode; 13 | 14 | public OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder("newSymbol"); 15 | 16 | public List featureVector=new ArrayList<>(); 17 | 18 | public boolean decisionIsMade; 19 | 20 | abstract public void executeCurrentChanceNode(); 21 | 22 | public ChanceNode() { 23 | decisionIsMade=false; 24 | } 25 | 26 | public ChanceNode getChanceNode() { 27 | return chanceNode; 28 | } 29 | 30 | public OpenFinDeskOrder getOpenFinDeskOrder() { 31 | return openFinDeskOrder; 32 | } 33 | 34 | public void setOpenFinDeskOrder(OpenFinDeskOrder openFinDeskOrder) { 35 | this.openFinDeskOrder = openFinDeskOrder; 36 | } 37 | 38 | public void setFeatureVector(List featureVector) { 39 | this.featureVector = featureVector; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/containerCore/DecisionTree.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.containerCore; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import org.apache.log4j.Logger; 5 | 6 | import java.util.*; 7 | 8 | public class DecisionTree { 9 | final static Logger logger= Logger.getLogger(DecisionTree.class); 10 | 11 | private List chanceNodes; 12 | 13 | private List featureVector=new ArrayList<>(); 14 | 15 | 16 | boolean decisionIsMade; 17 | 18 | public DecisionTree(List chanceNodes) { 19 | this.chanceNodes = chanceNodes; 20 | sortChanceNodes(); 21 | } 22 | 23 | private void sortChanceNodes() { 24 | List sortedChanceNodes=new ArrayList<>(); 25 | for(int i=0;i featureVector) { 38 | this.featureVector=featureVector; 39 | } 40 | 41 | public OpenFinDeskOrder makeDecision(){ 42 | decisionIsMade=false; 43 | int index=0; 44 | 45 | for(int i=0;i printResult() { 70 | return order -> { 71 | //logger.info("Subscriber thread: " + Thread.currentThread().getName()); 72 | logger.info("new suggested Order:"); 73 | logger.info("openFinDeskOrder.getPosition()="+order.getPosition()); 74 | logger.info("openFinDeskOrder.getSymbol()="+order.getSymbol()); 75 | logger.info("openFinDeskOrder.getStrategyName()="+order.getStrategyName()); 76 | //order.setOpenFinDeskOrderNumber(getRandomNumberInRange(0,10000000)); 77 | order.setOpenFinDeskOrderNumber(1111111); 78 | orderList.add(order); 79 | }; 80 | } 81 | 82 | private int getRandomNumberInRange(int min, int max) { 83 | 84 | if (min >= max) { 85 | throw new IllegalArgumentException("max must be greater than min"); 86 | } 87 | 88 | Random r = new Random(); 89 | return r.nextInt((max - min) + 1) + min; 90 | } 91 | 92 | public List getOrderList() { 93 | orderList.stream().forEach(order-> logger.info("suggestion="+order.getPosition()+"strategyName="+order.getStrategyName())); 94 | return orderList; 95 | } 96 | 97 | public DecisionTree getDecisionTree() { 98 | return decisionTree; 99 | } 100 | 101 | public List getOpenFinDeskStrategyList() { 102 | return openFinDeskStrategyList; 103 | } 104 | 105 | public OpenFinDeskOrder getFinalOrder() { 106 | return finalOrder; 107 | } 108 | 109 | 110 | public boolean isDisabled() { 111 | return disabled; 112 | } 113 | 114 | public void setDisabled(boolean disabled) { 115 | this.disabled = disabled; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/containerCore/XYSeriesDemo.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.containerCore; 2 | 3 | import org.jfree.chart.ChartFactory; 4 | import org.jfree.chart.ChartPanel; 5 | import org.jfree.chart.JFreeChart; 6 | import org.jfree.chart.plot.PlotOrientation; 7 | import org.jfree.chart.ui.ApplicationFrame; 8 | import org.jfree.data.xy.XYSeries; 9 | import org.jfree.data.xy.XYSeriesCollection; 10 | 11 | public class XYSeriesDemo extends ApplicationFrame { 12 | 13 | public XYSeries series = new XYSeries("Q action value"); 14 | 15 | 16 | 17 | 18 | public XYSeriesDemo(final String title) { 19 | super(title); 20 | /* 21 | series.add(1.0,500.2); 22 | series.add(5.0,694.1); 23 | series.add(4.0,100.0); 24 | series.add(12.5,734.4); 25 | series.add(17.3,453.2); 26 | series.add(21.2,500.2); 27 | series.add(21.9,320); 28 | series.add(25.6,734.4); 29 | series.add(30.0,453.2); 30 | */ 31 | 32 | } 33 | 34 | public void plotNow(){ 35 | final XYSeriesCollection data = new XYSeriesCollection(series); 36 | final JFreeChart chart = ChartFactory.createXYLineChart( 37 | "Reinforcement Learning Results", 38 | "iteration", 39 | "Q", 40 | data, 41 | PlotOrientation.VERTICAL, 42 | true, 43 | true, 44 | false 45 | ); 46 | 47 | final ChartPanel chartPanel = new ChartPanel(chart); 48 | chartPanel.setPreferredSize(new java.awt.Dimension(500,270)); 49 | setContentPane(chartPanel); 50 | } 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/customizedPivotPointMethods/CamarillaPivotPointApproach.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.customizedPivotPointMethods; 2 | 3 | import org.ta4j.core.TimeSeries; 4 | 5 | import java.util.Arrays; 6 | 7 | public class CamarillaPivotPointApproach { 8 | 9 | private TimeSeries timeSeries; 10 | private int numberOfBars; 11 | private double previousDayLowPrice; 12 | private double previousDayHighPrice; 13 | private double previousDayClosePrice; 14 | 15 | private double[] r; 16 | private double[] s; 17 | private double pp; 18 | 19 | public CamarillaPivotPointApproach(TimeSeries timeSeries) { 20 | this.timeSeries = timeSeries; 21 | calculatePivotPointsSuppertsAndResistance(); 22 | } 23 | 24 | private void calculatePivotPointsSuppertsAndResistance() { 25 | initializeVariables(); 26 | calculateParameters(); 27 | } 28 | 29 | private void initializeVariables() { 30 | numberOfBars=timeSeries.getBarCount(); 31 | 32 | r=new double[4]; 33 | s=new double[4]; 34 | Arrays.fill(r,0); 35 | Arrays.fill(s,0); 36 | previousDayClosePrice=timeSeries.getBar(numberOfBars-2).getClosePrice().doubleValue(); 37 | previousDayLowPrice= timeSeries.getBar(numberOfBars-2).getMinPrice().doubleValue(); 38 | previousDayHighPrice= timeSeries.getBar(numberOfBars-2).getMaxPrice().doubleValue(); 39 | } 40 | 41 | private void calculateParameters() { 42 | pp=(previousDayHighPrice+previousDayLowPrice+previousDayClosePrice)/3; 43 | r[0]=previousDayClosePrice+((previousDayHighPrice-previousDayLowPrice)*(1.0833)); 44 | r[1]=previousDayClosePrice+((previousDayHighPrice-previousDayLowPrice)*(1.1666)); 45 | r[2]=previousDayClosePrice+((previousDayHighPrice-previousDayLowPrice)*(1.2500)); 46 | r[3]=previousDayClosePrice+((previousDayHighPrice-previousDayLowPrice)*(1.5000)); 47 | 48 | s[0]=previousDayClosePrice-((previousDayHighPrice-previousDayLowPrice)*(1.0833)); 49 | s[1]=previousDayClosePrice-((previousDayHighPrice-previousDayLowPrice)*(1.1666)); 50 | s[2]=previousDayClosePrice-((previousDayHighPrice-previousDayLowPrice)*(1.2500)); 51 | s[3]=previousDayClosePrice-((previousDayHighPrice-previousDayLowPrice)*(1.5000)); 52 | } 53 | 54 | public double[] getR() { 55 | return r; 56 | } 57 | 58 | public double[] getS() { 59 | return s; 60 | } 61 | 62 | public double getPp() { 63 | return pp; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/fibonacciCore/FiboClusterManagerOld.java: -------------------------------------------------------------------------------- 1 | /* 2 | package com.farshad.algotrading.openFinDeskStrategies.fibonacciBased.com.farshad.algotrading.containerCore; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class FiboClusterManagerOld { 8 | 9 | private List priceReversalZoneList=new ArrayList<>(); 10 | private List timeReversalZoneList=new ArrayList<>(); 11 | 12 | private List fibonacciList=new ArrayList<>(); 13 | 14 | 15 | public void add(FibonacciOld fibonacci) { 16 | 17 | fibonacci.internalRetracement(); 18 | //manual test 19 | fibonacci.externalRetracement(); 20 | fibonacci.extension(); 21 | fibonacci.projection(); 22 | fibonacci.expansion(); 23 | fibonacciList.add(fibonacci); 24 | } 25 | 26 | 27 | public void manage() { 28 | System.out.println("managing fiboclusters!"); 29 | showFibonacciLevels(); 30 | PriceReversalZone priceReversalZone=new PriceReversalZone(); 31 | 32 | fibonacciList.forEach(fibonacci -> { 33 | if (fibonacci.getWave().getTrendType().equals("upward")){ 34 | priceReversalZone.setLowerPrice(fibonacci.getInternalRetracementList().get(0).getPrice()); 35 | priceReversalZone.setUpperPrice(fibonacci.getExtensionList().get(0).getPrice()); 36 | 37 | }else if (fibonacci.getWave().getTrendType().equals("downward")){ 38 | priceReversalZone.setLowerPrice(fibonacci.getExternalRetracementList().get(0).getPrice()); 39 | priceReversalZone.setUpperPrice(fibonacci.getExtensionList().get(0).getPrice()); 40 | 41 | } 42 | }); 43 | 44 | 45 | priceReversalZoneList.add(priceReversalZone); 46 | } 47 | 48 | private void showFibonacciLevels() { 49 | fibonacciList.forEach(i-> { 50 | System.out.println("i.getInternalRetracementList().get(0).getPrice()="+i.getInternalRetracementList().get(0).getPrice()); 51 | System.out.println("i.getInternalRetracementList().get(0).getTime()="+i.getInternalRetracementList().get(0).getTime()); 52 | 53 | System.out.println("i.getExternalRetracementList().get(0).getPrice()="+i.getExternalRetracementList().get(0).getPrice()); 54 | System.out.println("i.getExternalRetracementList().get(0).getTime()="+i.getExternalRetracementList().get(0).getTime()); 55 | 56 | 57 | System.out.println("i.getExtensionList().get(0).getPrice()="+i.getExtensionList().get(0).getPrice()); 58 | System.out.println("i.getExtensionList().get(0).getTime()="+i.getExtensionList().get(0).getTime()); 59 | 60 | }); 61 | 62 | } 63 | 64 | public List getPriceReversalZoneList() { 65 | return priceReversalZoneList; 66 | } 67 | 68 | public List getTimeReversalZoneList() { 69 | return timeReversalZoneList; 70 | } 71 | 72 | //getters 73 | 74 | public List getFibonacciList() { 75 | return fibonacciList; 76 | } 77 | } 78 | */ 79 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/fibonacciCore/FibonacciHelper.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.fibonacciCore; 2 | 3 | import com.farshad.algotrading.core.trendRangeAndWave.Trend; 4 | import com.farshad.algotrading.core.trendRangeAndWave.Wave; 5 | import org.apache.log4j.Logger; 6 | 7 | import java.util.List; 8 | 9 | public class FibonacciHelper { 10 | 11 | final static Logger logger= Logger.getLogger(FibonacciHelper.class); 12 | 13 | private Trend lastTrend; 14 | private List waveList; 15 | private double strength; 16 | private Fibonacci fibonacci; 17 | 18 | public FibonacciHelper(List waveList, Trend lastTrend) { 19 | this.waveList=waveList; 20 | this.lastTrend=lastTrend; 21 | } 22 | 23 | public void startProcedure() { 24 | fibonacci=new Fibonacci(); 25 | logger.info("wavelist.size="+waveList.size()); 26 | fibonacci.addWaves(waveList); 27 | if(lastTrend!=null){ 28 | fibonacci.addTrend(lastTrend); 29 | } 30 | fibonacci.calculateTypeOfGlobalRegime(); 31 | logger.info("fibonacci.getTypeOfGlobalRegime()="+fibonacci.getTypeOfGlobalRegime()); 32 | fibonacci.calculateInternalRetracement(); 33 | fibonacci.calculateGlobalStrength(); 34 | strength=fibonacci.getStrength(); 35 | } 36 | 37 | 38 | public double getStrength() { 39 | return strength; 40 | } 41 | 42 | 43 | public Fibonacci getFibonacci() { 44 | return fibonacci; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/fibonacciCore/PriceReversalZone.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.fibonacciCore; 2 | 3 | public class PriceReversalZone { 4 | 5 | private double lowerPrice; 6 | private double upperPrice; 7 | 8 | public double getLowerPrice() { 9 | return lowerPrice; 10 | } 11 | 12 | public void setLowerPrice(double lowerPrice) { 13 | this.lowerPrice = lowerPrice; 14 | } 15 | 16 | public double getUpperPrice() { 17 | return upperPrice; 18 | } 19 | 20 | public void setUpperPrice(double upperPrice) { 21 | this.upperPrice = upperPrice; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/fibonacciCore/TimeReversalZone.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.fibonacciCore; 2 | 3 | public class TimeReversalZone { 4 | private double lowerTime; 5 | private double upperTime; 6 | 7 | public double getLowerTime() { 8 | return lowerTime; 9 | } 10 | 11 | public void setLowerTime(double lowerTime) { 12 | this.lowerTime = lowerTime; 13 | } 14 | 15 | public double getUpperTime() { 16 | return upperTime; 17 | } 18 | 19 | public void setUpperTime(double upperTime) { 20 | this.upperTime = upperTime; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/math/AlgoRegression.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.math; 2 | 3 | import org.apache.commons.math3.stat.regression.SimpleRegression; 4 | import org.apache.log4j.Logger; 5 | 6 | import java.util.List; 7 | 8 | public class AlgoRegression { 9 | 10 | final static Logger logger= Logger.getLogger(AlgoRegression.class); 11 | 12 | 13 | private double slope; 14 | private double intercept; 15 | 16 | 17 | public void comparePairs(List asset1, List asset2){ 18 | 19 | SimpleRegression regression = new SimpleRegression(); 20 | for(int i=0;i row) throws IOException { 31 | //empty the file 32 | PrintWriter writer = new PrintWriter(file); 33 | writer.print(""); 34 | writer.close(); 35 | csvWriter = new FileWriter(file,true); 36 | csvWriter.append(String.join(",", row)); 37 | csvWriter.append("\n"); 38 | csvWriter.flush(); 39 | } 40 | 41 | public void writeRow(List row) throws IOException { 42 | csvWriter.append(String.join(",", row)); 43 | csvWriter.append("\n"); 44 | csvWriter.flush(); 45 | } 46 | 47 | 48 | 49 | public void writeOnTop(List row) throws IOException { 50 | 51 | //Read old Data 52 | CSVReader csvReader=new CSVReader(); 53 | csvReader.setFileName("/csv/"+file.getName()); 54 | String[] strings; 55 | List> listList=new ArrayList<>(); 56 | List stringList=new ArrayList<>(); 57 | int numberOfLines=csvReader.getLines(); 58 | 59 | for (int i = 0; i < numberOfLines; i++) { 60 | strings = csvReader.readRow(numberOfLines-i); 61 | stringList = Arrays.asList(strings); 62 | listList.add(stringList); 63 | } 64 | csvReader.closeReader(); 65 | //empty the file 66 | PrintWriter writer = new PrintWriter(file); 67 | writer.print(""); 68 | writer.close(); 69 | 70 | writeRow(row); 71 | 72 | //append old data 73 | for(int i=0;i ohlcDataList=new ArrayList<>(); 33 | 34 | PrintWriter out; 35 | 36 | public SocketUtil(ServerSocket ss,Socket client) 37 | { 38 | this.ss = ss; 39 | this.client=client; 40 | 41 | } 42 | 43 | public void setOpenFinDeskMessage(String context ,String payload) { 44 | this.openFinDeskMessage.setContext(context); 45 | this.openFinDeskMessage.setPayload(payload); 46 | } 47 | 48 | public OpenFinDeskMessage sendMessage(String message) throws IOException, InterruptedException { 49 | openFinDeskMessage=new OpenFinDeskMessage(); 50 | int numberOfLoops=2; 51 | if (message.split(",")[0].equals("fetchCandles")){ 52 | numberOfLoops= Integer.parseInt(message.split(",")[4])+1; 53 | }else{ 54 | numberOfLoops=2; 55 | } 56 | 57 | 58 | outerloop: 59 | for (int i=0;i getOhlcDataList() { 112 | return ohlcDataList; 113 | } 114 | 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/trendRangeAndWave/Range.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.trendRangeAndWave; 2 | 3 | public class Range { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/trendRangeAndWave/Trend.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.trendRangeAndWave; 2 | 3 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.PriceTime; 4 | import org.apache.log4j.Logger; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author farshad noravesh 10 | * @since version 1.0.0 11 | */ 12 | public class Trend { 13 | final static Logger logger= Logger.getLogger(TrendGenerator.class); 14 | 15 | private String trendType; //upward or downward 16 | 17 | private List priceTimePoints; 18 | 19 | public Trend(String trendType, List priceTimePoints) { 20 | this.trendType = trendType; 21 | this.priceTimePoints = priceTimePoints; 22 | logger.info("adding trend:"+trendType+" ,price1:"+priceTimePoints.get(0).getPrice()+" ,price2:"+priceTimePoints.get(1).getPrice()); 23 | } 24 | 25 | public String getTrendType() { 26 | return trendType; 27 | } 28 | 29 | public List getPriceTimePoints() { 30 | return priceTimePoints; 31 | } 32 | 33 | public double getSlope() { 34 | double priceDifference=priceTimePoints.get(1).getPrice()-priceTimePoints.get(0).getPrice(); 35 | double timeDifference=(priceTimePoints.get(1).getTime().getEpochSecond()-priceTimePoints.get(0).getTime().getEpochSecond()); 36 | double slope=priceDifference/timeDifference; 37 | logger.info("slope of trend is:"+slope); 38 | return slope; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/trendRangeAndWave/TrendGenerator.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.trendRangeAndWave; 2 | 3 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.PriceTime; 4 | import org.apache.log4j.Logger; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class TrendGenerator { 10 | final static Logger logger= Logger.getLogger(TrendGenerator.class); 11 | 12 | private int startingIndex; 13 | private List priceTimeChangePointList; 14 | 15 | private List trendList=new ArrayList<>(); 16 | 17 | 18 | public TrendGenerator(List priceTimeChangePointList) { 19 | this.priceTimeChangePointList=priceTimeChangePointList; 20 | } 21 | 22 | public List generate(){ 23 | priceTimeChangePointList.stream().forEach(priceTime -> { 24 | logger.info("priceTimeChangePointList:"+priceTime.getPrice()+" ,"+priceTime.getTime()); 25 | }); 26 | 27 | double difference=0; 28 | 29 | for(int i=0;i priceTimes=new ArrayList<>(); 31 | 32 | PriceTime currentPriceTime=priceTimeChangePointList.get(i); 33 | PriceTime nextPriceTime=priceTimeChangePointList.get(i+1); 34 | priceTimes.add(currentPriceTime); 35 | priceTimes.add(nextPriceTime); 36 | difference=nextPriceTime.getPrice()-currentPriceTime.getPrice(); 37 | if((difference>0)&&(nextPriceTime.getTime().getEpochSecond()>currentPriceTime.getTime().getEpochSecond())){ 38 | Trend trend=new Trend("upward",priceTimes); 39 | trendList.add(trend); 40 | }else if((difference<0)&&(nextPriceTime.getTime().getEpochSecond()>currentPriceTime.getTime().getEpochSecond())){ 41 | Trend trend=new Trend("downward",priceTimes); 42 | trendList.add(trend); 43 | } 44 | 45 | } 46 | 47 | startingIndex=0; 48 | 49 | if (trendList.size()!=1) { 50 | if (trendList.get(0).getTrendType().equals("downward")) { 51 | if (trendList.get(1).getPriceTimePoints().get(1).getPrice() > trendList.get(0).getPriceTimePoints().get(0).getPrice()) { 52 | startingIndex = 1; 53 | } 54 | } else { 55 | //upward 56 | if (trendList.get(0).getPriceTimePoints().get(0).getPrice() > trendList.get(1).getPriceTimePoints().get(1).getPrice()) { 57 | startingIndex = 1; 58 | } 59 | } 60 | } 61 | 62 | trendList.stream().forEach(trend -> { 63 | logger.info("trend.getTrendType()="+trend.getTrendType()); 64 | logger.info("trend.point1="+trend.getPriceTimePoints().get(0).getPrice()); 65 | logger.info("trend.point2="+trend.getPriceTimePoints().get(1).getPrice()); 66 | 67 | }); 68 | return trendList; 69 | } 70 | 71 | 72 | public int getStartingIndex() { 73 | return startingIndex; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/core/trendRangeAndWave/Wave.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.core.trendRangeAndWave; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | public class Wave { 6 | 7 | final static Logger logger= Logger.getLogger(Wave.class); 8 | 9 | 10 | private Trend firstTrend; 11 | private Trend secondTrend; 12 | private String typeOfFirstTrend; 13 | private String typeOfSecondTrend; 14 | private String typeOfWave; 15 | 16 | public Wave(Trend firstTrend,Trend secondTrend) { 17 | logger.info("adding wave with trend1:"+firstTrend.getTrendType()+" ,adding wave with trend2:"+secondTrend.getTrendType()); 18 | logger.debug("firstTrend.price[0]="+firstTrend.getPriceTimePoints().get(0).getPrice()); 19 | logger.debug("firstTrend.price[1]="+firstTrend.getPriceTimePoints().get(1).getPrice()); 20 | logger.debug("secondTrend.price[0]="+secondTrend.getPriceTimePoints().get(0).getPrice()); 21 | logger.debug("secondTrend.price[1]="+secondTrend.getPriceTimePoints().get(1).getPrice()); 22 | this.typeOfWave="rangingWave"; 23 | 24 | this.firstTrend = firstTrend; 25 | this.secondTrend= secondTrend; 26 | this.typeOfFirstTrend=firstTrend.getTrendType(); 27 | this.typeOfSecondTrend=secondTrend.getTrendType(); 28 | if(firstTrend.getTrendType().equals("downward")){ 29 | if(firstTrend.getPriceTimePoints().get(0).getPrice()>secondTrend.getPriceTimePoints().get(1).getPrice()){ 30 | typeOfWave="decreasing"; 31 | } 32 | }else if(firstTrend.getTrendType().equals("upward")){ 33 | if(firstTrend.getPriceTimePoints().get(0).getPrice() timeSeries2Value) { 83 | if (overCount < lengthOfTimeSeries) { 84 | status = "crossUp"; 85 | break; 86 | } 87 | } 88 | }else if(timeSeries1ValueAtIndex0 > timeSeries2ValueAtIndex0) { 89 | //either over or crossDown 90 | if (timeSeries1Value > timeSeries2Value) { 91 | overCount++; 92 | if (overCount == lengthOfTimeSeries) { 93 | status = "over"; 94 | break; 95 | } 96 | }else if (timeSeries1Value < timeSeries2Value) { 97 | if (overCount < lengthOfTimeSeries) { 98 | status = "crossDown"; 99 | break; 100 | } 101 | } 102 | }else{ 103 | status = "crossingAtThisMoment"; 104 | logger.debug("timeSeries1ValueAtIndex0=" + timeSeries1ValueAtIndex0); 105 | logger.debug("timeSeries2ValueAtIndex0=" + timeSeries2ValueAtIndex0); 106 | break; 107 | } 108 | 109 | } 110 | 111 | 112 | return status; 113 | } 114 | 115 | 116 | public int getCrossPoint () { 117 | return overCount; 118 | } 119 | 120 | public double getSlopeAtLatestIndex1 () { 121 | slopeAtLatestIndex1 = timeSeries1[lengthOfTimeSeries - 1] - timeSeries1[lengthOfTimeSeries - 2]; 122 | return slopeAtLatestIndex1; 123 | } 124 | 125 | public double getSlopeAtLatestIndex2 () { 126 | slopeAtLatestIndex2 = timeSeries2[lengthOfTimeSeries - 1] - timeSeries2[lengthOfTimeSeries - 2]; 127 | return slopeAtLatestIndex2; 128 | } 129 | 130 | 131 | } 132 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/OpenFinDeskStrategy.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import org.ta4j.core.*; 5 | 6 | import java.io.IOException; 7 | import java.util.concurrent.Callable; 8 | 9 | /** 10 | * @author farshad noravesh 11 | * @since version 1.0.0 12 | */ 13 | public abstract class OpenFinDeskStrategy { 14 | 15 | 16 | public TimeSeries series; 17 | 18 | public abstract Callable define() throws IOException; 19 | 20 | public OpenFinDeskStrategy() { 21 | } 22 | 23 | public void start(){ 24 | } 25 | 26 | public TimeSeries setSeries(TimeSeries series) { 27 | this.series=series; 28 | return series; 29 | } 30 | 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/candlestickDriven/EngulfingPatternStrategy.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.candlestickDriven; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 5 | import org.apache.log4j.Logger; 6 | 7 | import java.io.IOException; 8 | import java.util.concurrent.Callable; 9 | 10 | public class EngulfingPatternStrategy extends OpenFinDeskStrategy { 11 | final static Logger logger= Logger.getLogger(EngulfingPatternStrategy.class); 12 | 13 | @Override 14 | public Callable define() throws IOException { 15 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 16 | openFinDeskOrder.setSymbol(series.getName()); 17 | openFinDeskOrder.setStrategyName("EngulfingPatternStrategy"); 18 | openFinDeskOrder.setPosition("*"); 19 | int index=series.getBarCount(); 20 | double previousBarOpenPrice=series.getBar(index-3).getOpenPrice().doubleValue(); 21 | double currentBarOpenPrice=series.getBar(index-2).getOpenPrice().doubleValue(); 22 | double nextBarOpenPrice=series.getBar(index-1).getOpenPrice().doubleValue(); 23 | 24 | double previousBarClosePrice=series.getBar(index-3).getClosePrice().doubleValue(); 25 | double currentBarClosePrice=series.getBar(index-2).getClosePrice().doubleValue(); 26 | double nextBarClosePrice=series.getBar(index-1).getClosePrice().doubleValue(); 27 | 28 | if((currentBarClosePrice>previousBarOpenPrice)&&(currentBarOpenPricecurrentBarOpenPrice) { 30 | openFinDeskOrder.setPosition("bullishEngulfingCandleStick"); 31 | } 32 | }else if((currentBarOpenPrice>previousBarClosePrice)&&(currentBarClosePrice define() throws IOException { 15 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 16 | openFinDeskOrder.setSymbol(series.getName()); 17 | openFinDeskOrder.setStrategyName("PinBarStrategy"); 18 | openFinDeskOrder.setPosition("*"); 19 | 20 | int index=series.getBarCount(); 21 | double bodyLength=series.getBar(index-2).getClosePrice().doubleValue()-series.getBar(index-2).getOpenPrice().doubleValue(); 22 | double highMinusLow=series.getBar(index-2).getMaxPrice().doubleValue()-series.getBar(index-2).getMinPrice().doubleValue(); 23 | openFinDeskOrder.setParameter(String.valueOf(bodyLength)); 24 | 25 | double shadowLength=0; 26 | if(bodyLength>0){ 27 | shadowLength=series.getBar(index-1).getMaxPrice().doubleValue()-series.getBar(index-1).getClosePrice().doubleValue(); 28 | }else{ 29 | shadowLength=series.getBar(index-1).getMaxPrice().doubleValue()-series.getBar(index-1).getOpenPrice().doubleValue(); 30 | } 31 | 32 | if(highMinusLow>(3*Math.abs(bodyLength))){ 33 | if(shadowLength>3*bodyLength) { 34 | if (series.getBar(index - 1).getClosePrice().doubleValue() < series.getBar(index - 2).getClosePrice().doubleValue()) { 35 | openFinDeskOrder.setPosition("bearishPinBar"); 36 | } 37 | }else { 38 | if (series.getBar(index - 1).getClosePrice().doubleValue() > series.getBar(index - 2).getClosePrice().doubleValue()) { 39 | openFinDeskOrder.setPosition("bullishPinBar"); 40 | } 41 | } 42 | } 43 | 44 | logger.info("symbol="+openFinDeskOrder.getSymbol()); 45 | logger.info("position="+openFinDeskOrder.getPosition()); 46 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 47 | return () -> { 48 | logger.debug("Observable thread: " + Thread.currentThread().getName()); 49 | return openFinDeskOrder; 50 | }; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/fibonacciBased/FibonacciConvergence.java: -------------------------------------------------------------------------------- 1 | /* 2 | package com.farshad.algotrading.openFinDeskStrategies.fibonacciBased; 3 | 4 | import com.farshad.algotrading.containerCore.openFinDeskOrder.OpenFinDeskOrder; 5 | import com.farshad.algotrading.containerCore.trendRangeAndWave.Trend; 6 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 7 | import com.farshad.algotrading.openFinDeskStrategies.fibonacciBased.com.farshad.algotrading.containerCore.FiboClusterManagerOld; 8 | 9 | import java.util.List; 10 | import java.util.concurrent.Callable; 11 | 12 | public class FibonacciConvergence extends OpenFinDeskStrategy { 13 | 14 | 15 | 16 | @Override 17 | public Callable define() { 18 | start(); 19 | 20 | WaveExtractorOld waveExtractor=new WaveExtractorOld(); 21 | List waveList=waveExtractor.findWaves(series, WaveExtractorOld.Method.JOE_DINAPOLI); 22 | FibonacciOld fibonacci=new FibonacciOld(); 23 | FiboClusterManagerOld fiboClusterManager=new FiboClusterManagerOld(); 24 | 25 | waveList.forEach(w-> { 26 | fibonacci.setWave(w); 27 | fiboClusterManager.add(fibonacci); 28 | }); 29 | fiboClusterManager.manage(); 30 | 31 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 32 | 33 | openFinDeskOrder.setSymbol(series.getName()); 34 | openFinDeskOrder.setStrategyName("FibonacciConvergence"); 35 | openFinDeskOrder.setVolume("0.01"); 36 | openFinDeskOrder.setPosition("buyLimit"); 37 | openFinDeskOrder.setPrice(series.getBar(0).getClosePrice().doubleValue()); 38 | openFinDeskOrder.setStopLoss(fiboClusterManager.getFibonacciList().get(0).getInternalRetracementList().get(1).getPrice()); 39 | openFinDeskOrder.setTakeProfit(fiboClusterManager.getPriceReversalZoneList().get(0).getLowerPrice()); 40 | 41 | 42 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 43 | 44 | return () -> { 45 | System.out.println("Observable thread: " + Thread.currentThread().getName()); 46 | return finalOpenFinDeskOrder; 47 | }; 48 | 49 | } 50 | 51 | 52 | 53 | 54 | } 55 | */ 56 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/fibonacciBased/TrendStrengthStrategyBasedOnInternalRetracementSequences.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.fibonacciBased; 2 | 3 | import com.farshad.algotrading.backtesting.measurements.timeSeriesMeasurements.PriceTime; 4 | import com.farshad.algotrading.core.AlternatingTrendSmoothing.ATS; 5 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 6 | import com.farshad.algotrading.core.fibonacciCore.FibonacciHelper; 7 | import com.farshad.algotrading.core.trendRangeAndWave.Trend; 8 | import com.farshad.algotrading.core.trendRangeAndWave.TrendGenerator; 9 | import com.farshad.algotrading.core.trendRangeAndWave.Wave; 10 | import com.farshad.algotrading.core.trendRangeAndWave.WaveGenerator; 11 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 12 | import org.apache.log4j.Logger; 13 | 14 | import java.io.IOException; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | import java.util.concurrent.Callable; 18 | 19 | public class TrendStrengthStrategyBasedOnInternalRetracementSequences extends OpenFinDeskStrategy { 20 | final static Logger logger= Logger.getLogger(TrendStrengthStrategyBasedOnInternalRetracementSequences.class); 21 | 22 | 23 | @Override 24 | public Callable define() throws IOException { 25 | int index=series.getBarCount(); 26 | 27 | List priceTimeList=new ArrayList<>(); 28 | 29 | for(int i=index-25;i priceTimeChangePointList=ats.getPriceChangeList(); 37 | 38 | TrendGenerator trendGenerator=new TrendGenerator(priceTimeChangePointList); 39 | List trendList=new ArrayList<>(); 40 | if (priceTimeChangePointList.size()>1){ 41 | trendList=trendGenerator.generate(); 42 | } 43 | 44 | 45 | WaveGenerator waveGenerator=new WaveGenerator(trendList,trendGenerator.getStartingIndex()); 46 | List waveList=waveGenerator.generate(); 47 | FibonacciHelper fibonacciHelper=new FibonacciHelper(waveList,trendList.get(trendList.size()-1)); 48 | fibonacciHelper.startProcedure(); 49 | 50 | 51 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 52 | openFinDeskOrder.setSymbol(series.getName()); 53 | openFinDeskOrder.setStrategyName("TrendStrengthStrategyBasedOnInternalRetracementSequences"); 54 | openFinDeskOrder.setVolume("0.01"); 55 | openFinDeskOrder.setPrice(0.5*(series.getBar(index-1).getClosePrice().doubleValue()+series.getBar(index-1).getOpenPrice().doubleValue())); 56 | openFinDeskOrder.setParameter(String.valueOf(fibonacciHelper.getStrength())); 57 | if((fibonacciHelper.getFibonacci().getTypeOfGlobalRegime().equals("increasing"))){ 58 | openFinDeskOrder.setPosition("buy"); 59 | }else if((fibonacciHelper.getFibonacci().getTypeOfGlobalRegime().equals("decreasing"))){ 60 | openFinDeskOrder.setPosition("sell"); 61 | }else{ 62 | openFinDeskOrder.setPosition("*"); 63 | } 64 | 65 | 66 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 67 | return () -> { 68 | logger.debug("Observable thread: " + Thread.currentThread().getName()); 69 | return openFinDeskOrder; 70 | }; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/indicatorBased/ADXBasedTrendDetection.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.indicatorBased; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import com.farshad.algotrading.openFinDeskStrategies.CrossingTimeSeriesDetector; 5 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 6 | import org.apache.log4j.Logger; 7 | import org.ta4j.core.indicators.ParabolicSarIndicator; 8 | import org.ta4j.core.indicators.adx.ADXIndicator; 9 | import org.ta4j.core.indicators.adx.MinusDIIndicator; 10 | import org.ta4j.core.indicators.adx.PlusDIIndicator; 11 | 12 | 13 | import java.io.IOException; 14 | import java.util.concurrent.Callable; 15 | 16 | public class ADXBasedTrendDetection extends OpenFinDeskStrategy { 17 | 18 | 19 | final static Logger logger= Logger.getLogger(ADXBasedTrendDetection.class); 20 | 21 | 22 | @Override 23 | public Callable define() throws IOException { 24 | int index=series.getBarCount(); 25 | 26 | int big=20; 27 | 28 | ParabolicSarIndicator parabolicSarIndicator=new ParabolicSarIndicator(series); 29 | 30 | 31 | ADXIndicator adxIndicator=new ADXIndicator(series,14); 32 | PlusDIIndicator plusDIIndicator=new PlusDIIndicator(series,14); 33 | MinusDIIndicator minusDIIndicator=new MinusDIIndicator(series,14); 34 | 35 | 36 | 37 | int horizen=5; 38 | double[] plusDIIndicatorArray = new double[horizen]; 39 | double[] minusDIIndicatorArray = new double[horizen]; 40 | int j=0; 41 | for(int i=index-horizen;i0)){ 76 | openFinDeskOrder.setPosition("buy"); 77 | logger.info("symbol:"+series.getName()+",crossUp and crossPoint is at " + crossUpDetector.getCrossPoint() + " th index" + 78 | "with slope:" + crossUpDetector.getSlopeAtLatestIndex1()); 79 | }else if ((statusForCrossDown.equals("crossDown"))&&((crossDownDetector.getSlopeAtLatestIndex2()<0))){ 80 | openFinDeskOrder.setPosition("sell"); 81 | logger.info("symbol:"+series.getName()+",crossDown and crossPoint is at " + crossDownDetector.getCrossPoint() + " th index" + 82 | "with slope:" + crossDownDetector.getSlopeAtLatestIndex2()); 83 | }else{ 84 | 85 | openFinDeskOrder.setPosition("*"); 86 | } 87 | 88 | 89 | openFinDeskOrder.setOrderType("noOrder"); 90 | openFinDeskOrder.setPrice(series.getBar(index-1).getClosePrice().doubleValue()); 91 | //openFinDeskOrder.setStopLoss(series.getBar(index-1).getClosePrice().doubleValue() - 0.01); 92 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() + 0.01); 93 | }else{ 94 | openFinDeskOrder.setPosition("noPosition"); 95 | openFinDeskOrder.setOrderType("noOrder"); 96 | openFinDeskOrder.setPrice(series.getBar(index-1).getClosePrice().doubleValue()); 97 | // openFinDeskOrder.setStopLoss(series.getBar(index-1).getClosePrice().doubleValue() + 0.01); 98 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() - 0.01); 99 | } 100 | 101 | openFinDeskOrder.setStopLoss(parabolicSarIndicator.getValue(index-1).doubleValue()); 102 | 103 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 104 | return () -> { 105 | logger.debug("Observable thread: " + Thread.currentThread().getName()); 106 | return openFinDeskOrder; 107 | }; 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/indicatorBased/CrossingTwoMovingAverages.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.indicatorBased; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import com.farshad.algotrading.openFinDeskStrategies.CrossingTimeSeriesDetector; 5 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 6 | import org.apache.log4j.Logger; 7 | import org.ta4j.core.indicators.EMAIndicator; 8 | import org.ta4j.core.indicators.helpers.ClosePriceIndicator; 9 | import java.io.IOException; 10 | import java.util.concurrent.Callable; 11 | 12 | public class CrossingTwoMovingAverages extends OpenFinDeskStrategy { 13 | 14 | 15 | final static Logger logger= Logger.getLogger(CrossingTwoMovingAverages.class); 16 | 17 | 18 | @Override 19 | public Callable define() throws IOException { 20 | int index=series.getBarCount(); 21 | 22 | ClosePriceIndicator closePrice = new ClosePriceIndicator(series); 23 | int big=14; 24 | EMAIndicator shortEma = new EMAIndicator(closePrice, 5); 25 | EMAIndicator longEma = new EMAIndicator(closePrice, big); 26 | 27 | for(int i=index-1;i>index-2;i--){ 28 | logger.info("CrossingTwoMovingAverages:latest time :"+series.getBar(i).getEndTime()+" closePrice:"+series.getBar(i).getClosePrice()); 29 | logger.info("symbol:"+series.getName()+",5-ticks-EMA value at the "+i+"th index: " + shortEma.getValue(i).doubleValue()); 30 | logger.info("symbol:"+series.getName()+","+big+"-ticks-EMA value at the "+i+"th index: " + longEma.getValue(i).doubleValue()); 31 | } 32 | int horizen=5; 33 | 34 | double[] shortEmaArray = new double[horizen]; 35 | double[] longEmaArray = new double[horizen]; 36 | int j=0; 37 | for(int i=index-horizen;i0)){ 59 | if(series.getBar(index-1).getClosePrice().doubleValue()>shortEma.getValue(index-1).doubleValue()) 60 | { 61 | openFinDeskOrder.setPosition("buy"); 62 | openFinDeskOrder.setOrderType("openBuy"); 63 | } 64 | }else if ((status.equals("crossDown"))&&((crossingTimeSeriesDetector.getSlopeAtLatestIndex2()<0))){ 65 | if(series.getBar(index-1).getClosePrice().doubleValue() { 74 | logger.debug("Observable thread: " + Thread.currentThread().getName()); 75 | return openFinDeskOrder; 76 | }; 77 | } 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/indicatorBased/MACDbasedCrossingStrategy.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.indicatorBased; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import com.farshad.algotrading.openFinDeskStrategies.CrossingTimeSeriesDetector; 5 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 6 | import org.ta4j.core.indicators.EMAIndicator; 7 | import org.ta4j.core.indicators.MACDIndicator; 8 | import org.ta4j.core.indicators.helpers.ClosePriceIndicator; 9 | 10 | import java.io.IOException; 11 | import java.util.concurrent.Callable; 12 | 13 | public class MACDbasedCrossingStrategy extends OpenFinDeskStrategy { 14 | 15 | 16 | 17 | 18 | @Override 19 | public Callable define() throws IOException { 20 | int index=series.getBarCount(); 21 | 22 | ClosePriceIndicator closePrice = new ClosePriceIndicator(series); 23 | MACDIndicator macd = new MACDIndicator(closePrice, 9, 26); 24 | EMAIndicator emaMacd = new EMAIndicator(macd, 18); 25 | 26 | 27 | int horizen=5; 28 | 29 | double[] macdArray = new double[horizen]; 30 | double[] emaMacdArray = new double[horizen]; 31 | int j=0; 32 | for(int i=index-horizen;i0)){ 54 | openFinDeskOrder.setPosition("buy"); 55 | openFinDeskOrder.setOrderType("openBuy"); 56 | openFinDeskOrder.setStopLoss(series.getBar(index-1).getClosePrice().doubleValue() - 0.01); 57 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() + 0.01); 58 | }else if ((crossUpStatus.equals("crossDown"))&&((crossUpTimeSeriesDetector.getSlopeAtLatestIndex2()<0))){ 59 | openFinDeskOrder.setPosition("sell"); 60 | openFinDeskOrder.setOrderType("openSell"); 61 | openFinDeskOrder.setStopLoss(series.getBar(index-1).getClosePrice().doubleValue() + 0.01); 62 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() - 0.01); 63 | } 64 | 65 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 66 | return () -> { 67 | System.out.println("Observable thread: " + Thread.currentThread().getName()); 68 | return openFinDeskOrder; 69 | }; 70 | } 71 | 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/indicatorBased/ParabolicSARIndicatorForStopLoss.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.indicatorBased; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 5 | import org.ta4j.core.indicators.ParabolicSarIndicator; 6 | 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.Callable; 10 | 11 | public class ParabolicSARIndicatorForStopLoss extends OpenFinDeskStrategy { 12 | 13 | 14 | 15 | 16 | @Override 17 | public Callable define() throws IOException { 18 | int index=series.getBarCount(); 19 | 20 | ParabolicSarIndicator parabolicSarIndicator=new ParabolicSarIndicator(series); 21 | System.out.println("parabolicSarIndicator.getValue(index-1)="+parabolicSarIndicator.getValue(index-1)); 22 | 23 | start(); 24 | 25 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 26 | System.out.println("symbol name inside ParabolicSARIndicatorForStopLoss:"+series.getName()); 27 | openFinDeskOrder.setSymbol(series.getName()); 28 | openFinDeskOrder.setStrategyName("ParabolicSARIndicatorForStopLoss"); 29 | openFinDeskOrder.setPosition("*"); 30 | openFinDeskOrder.setVolume("0.01"); 31 | 32 | if(series.getBar(index-1).getClosePrice().doubleValue()>=parabolicSarIndicator.getValue(index-1).doubleValue()) { 33 | openFinDeskOrder.setPosition("buy"); 34 | openFinDeskOrder.setOrderType("openBuy"); 35 | openFinDeskOrder.setPrice(series.getBar(index-1).getClosePrice().doubleValue()); 36 | openFinDeskOrder.setStopLoss(parabolicSarIndicator.getValue(index-1).doubleValue()); 37 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() + 0.03); 38 | }else{ 39 | openFinDeskOrder.setPosition("sell"); 40 | openFinDeskOrder.setOrderType("openSell"); 41 | openFinDeskOrder.setPrice(series.getBar(index-1).getClosePrice().doubleValue()); 42 | openFinDeskOrder.setStopLoss(parabolicSarIndicator.getValue(index-1).doubleValue()); 43 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() - 0.03); 44 | } 45 | 46 | 47 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 48 | return () -> { 49 | System.out.println("Observable thread: " + Thread.currentThread().getName()); 50 | return openFinDeskOrder; 51 | }; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/indicatorBased/RSIStrategy.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.indicatorBased; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 5 | import org.ta4j.core.indicators.RSIIndicator; 6 | import org.ta4j.core.indicators.helpers.ClosePriceIndicator; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.Callable; 10 | 11 | public class RSIStrategy extends OpenFinDeskStrategy { 12 | 13 | 14 | 15 | @Override 16 | public Callable define() throws IOException { 17 | int index=series.getBarCount(); 18 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 19 | openFinDeskOrder.setSymbol(series.getName()); 20 | openFinDeskOrder.setStrategyName("RSIStrategy"); 21 | openFinDeskOrder.setPosition("*"); 22 | openFinDeskOrder.setVolume("0.01"); 23 | openFinDeskOrder.setPrice(0.5*(series.getBar(index-1).getClosePrice().doubleValue()+ 24 | series.getBar(index-1).getOpenPrice().doubleValue())); 25 | 26 | 27 | ClosePriceIndicator closePrice = new ClosePriceIndicator(series); 28 | RSIIndicator rsiIndicator=new RSIIndicator(closePrice,14); 29 | if(rsiIndicator.getValue(index-1).doubleValue()>50){ 30 | openFinDeskOrder.setPosition("buy"); 31 | openFinDeskOrder.setOrderType("openBuy"); 32 | openFinDeskOrder.setStopLoss(series.getBar(index-1).getClosePrice().doubleValue() - 0.01); 33 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() + 0.01); 34 | }else{ 35 | openFinDeskOrder.setPosition("sell"); 36 | openFinDeskOrder.setOrderType("openSell"); 37 | openFinDeskOrder.setStopLoss(series.getBar(index-1).getClosePrice().doubleValue() + 0.01); 38 | openFinDeskOrder.setTakeProfit(series.getBar(index-1).getClosePrice().doubleValue() - 0.01); 39 | } 40 | 41 | start(); 42 | 43 | 44 | 45 | 46 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 47 | return () -> { 48 | System.out.println("Observable thread: " + Thread.currentThread().getName()); 49 | return openFinDeskOrder; 50 | }; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/indicatorBased/StatisticalCrossingTwoMovingAverages.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.indicatorBased; 2 | 3 | 4 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 5 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 6 | import org.ta4j.core.indicators.SMAIndicator; 7 | import org.ta4j.core.indicators.helpers.ClosePriceIndicator; 8 | 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | import java.util.concurrent.Callable; 13 | 14 | public class StatisticalCrossingTwoMovingAverages extends OpenFinDeskStrategy { 15 | 16 | 17 | public static double meanOfProbabilityDistribution; 18 | 19 | public static int batchSizeToCalculateMeanOfProbabilityDistribution; 20 | 21 | public static int indexBeforeReachingBatchSize; 22 | 23 | public static List batchList=new ArrayList<>(); 24 | 25 | private static StatisticalCrossingTwoMovingAverages statisticalCrossingTwoMovingAverages_instance=null; 26 | 27 | public StatisticalCrossingTwoMovingAverages( ) { 28 | System.out.println("first and last instance of StatisticalCrossingTwoMovingAverages created!"); 29 | batchSizeToCalculateMeanOfProbabilityDistribution=5; 30 | indexBeforeReachingBatchSize=0; 31 | } 32 | 33 | 34 | public static StatisticalCrossingTwoMovingAverages getInstance(){ 35 | if (statisticalCrossingTwoMovingAverages_instance == null){ 36 | // statisticalCrossingTwoMovingAverages_instance = new StatisticalCrossingTwoMovingAverages(eurusdSymbol.getSeriesFromFile(eurusdSymbol.getFileName())); 37 | } 38 | return statisticalCrossingTwoMovingAverages_instance; 39 | } 40 | 41 | 42 | 43 | @Override 44 | public Callable define() { 45 | int index=series.getBarCount(); 46 | 47 | indexBeforeReachingBatchSize++; 48 | System.out.println("indexBeforeReachingBatchSize="+indexBeforeReachingBatchSize); 49 | if (indexBeforeReachingBatchSizep).sum(); 55 | sum=batchList.parallelStream().mapToDouble(p->p).sum(); 56 | System.out.println("sum="+sum ); 57 | meanOfProbabilityDistribution= sum /(batchList.size()); 58 | System.out.println("meanOfProbabilityDistribution="+meanOfProbabilityDistribution); 59 | }else{ 60 | indexBeforeReachingBatchSize=0; 61 | } 62 | 63 | ClosePriceIndicator closePrice = new ClosePriceIndicator(series); 64 | int big=20; 65 | SMAIndicator shortSma = new SMAIndicator(closePrice, 5); 66 | SMAIndicator longSma = new SMAIndicator(closePrice, big); 67 | for(int i=index-1;i>index-2;i--){ 68 | System.out.println("5-ticks-SMA value at the "+i+"th index: " + shortSma.getValue(i).doubleValue()); 69 | System.out.println("20-ticks-SMA value at the "+i+"th index: " + longSma.getValue(i).doubleValue()); 70 | } 71 | 72 | 73 | start(); 74 | 75 | 76 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 77 | System.out.println("symbol name inside CrossingTwoMovingAverages:"+series.getName()); 78 | openFinDeskOrder.setSymbol(series.getName()); 79 | //openFinDeskOrder.setStrategyName("CrossingTwoMovingAverages"); 80 | openFinDeskOrder.setPosition("noPosition"); 81 | if (shortSma.getValue(index-1).doubleValue()>longSma.getValue(index-1).doubleValue()){ 82 | if(series.getBar(index-1).getClosePrice().doubleValue()>shortSma.getValue(index-1).doubleValue()) 83 | { 84 | if (series.getBar(index-1).getClosePrice().doubleValue()meanOfProbabilityDistribution) { 96 | openFinDeskOrder.setVolume("0.01"); 97 | openFinDeskOrder.setPosition("sell"); 98 | openFinDeskOrder.setPrice(series.getBar(index - 1).getClosePrice().doubleValue()); 99 | openFinDeskOrder.setStopLoss(series.getBar(index - 1).getClosePrice().doubleValue() + 0.03); 100 | openFinDeskOrder.setTakeProfit(series.getBar(index - 1).getClosePrice().doubleValue() - 0.03); 101 | } 102 | } 103 | } 104 | 105 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 106 | return () -> { 107 | System.out.println("Observable thread: " + Thread.currentThread().getName()); 108 | return openFinDeskOrder; 109 | }; 110 | 111 | } 112 | 113 | 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/pivotPointBased/CamarillaStrategy.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.pivotPointBased; 2 | 3 | import com.farshad.algotrading.core.customizedPivotPointMethods.CamarillaPivotPointApproach; 4 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 5 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 6 | import org.apache.log4j.Logger; 7 | 8 | import java.io.IOException; 9 | import java.util.concurrent.Callable; 10 | 11 | public class CamarillaStrategy extends OpenFinDeskStrategy { 12 | final static Logger logger= Logger.getLogger(CamarillaStrategy.class); 13 | 14 | @Override 15 | public Callable define() throws IOException { 16 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 17 | openFinDeskOrder.setSymbol(series.getName()); 18 | openFinDeskOrder.setStrategyName("CamarillaStrategy"); 19 | openFinDeskOrder.setPosition("*"); 20 | int lastBarIndex=series.getBarCount()-1; 21 | CamarillaPivotPointApproach camarillaPivotPointApproach=new CamarillaPivotPointApproach(series); 22 | double pp=camarillaPivotPointApproach.getPp(); 23 | double[] r=camarillaPivotPointApproach.getR(); 24 | double[] s=camarillaPivotPointApproach.getS(); 25 | 26 | double supportMargin0=series.getBar(lastBarIndex).getClosePrice().doubleValue()-s[0]; 27 | double resistanceMargin0=series.getBar(lastBarIndex).getClosePrice().doubleValue()-r[0]; 28 | 29 | double supportMargin1=series.getBar(lastBarIndex).getClosePrice().doubleValue()-s[1]; 30 | double resistanceMargin1=series.getBar(lastBarIndex).getClosePrice().doubleValue()-r[1]; 31 | 32 | 33 | double supportMargin2=series.getBar(lastBarIndex).getClosePrice().doubleValue()-s[2]; 34 | double resistanceMargin2=series.getBar(lastBarIndex).getClosePrice().doubleValue()-r[2]; 35 | 36 | 37 | double supportMargin3=series.getBar(lastBarIndex).getClosePrice().doubleValue()-s[3]; 38 | double resistanceMargin3=series.getBar(lastBarIndex).getClosePrice().doubleValue()-r[3]; 39 | 40 | 41 | if (Math.abs(supportMargin0)<0.0001){ 42 | openFinDeskOrder.setPosition("buy"); 43 | }else if(Math.abs(resistanceMargin0)<0.0001){ 44 | openFinDeskOrder.setPosition("sell"); 45 | } 46 | 47 | 48 | if (Math.abs(supportMargin1)<0.0001){ 49 | openFinDeskOrder.setPosition("buy"); 50 | }else if(Math.abs(resistanceMargin1)<0.0001){ 51 | openFinDeskOrder.setPosition("sell"); 52 | } 53 | 54 | if (Math.abs(supportMargin2)<0.0001){ 55 | openFinDeskOrder.setPosition("buy"); 56 | }else if(Math.abs(resistanceMargin2)<0.0001){ 57 | openFinDeskOrder.setPosition("sell"); 58 | } 59 | 60 | if (Math.abs(supportMargin3)<0.0001){ 61 | openFinDeskOrder.setPosition("buy"); 62 | }else if(Math.abs(resistanceMargin3)<0.0001){ 63 | openFinDeskOrder.setPosition("sell"); 64 | } 65 | 66 | logger.info("symbol="+openFinDeskOrder.getSymbol()); 67 | logger.info("position="+openFinDeskOrder.getPosition()); 68 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 69 | return () -> { 70 | logger.debug("Observable thread: " + Thread.currentThread().getName()); 71 | return openFinDeskOrder; 72 | }; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/statisticalArbitrageBasedOnKalmanFilter/Cointegration.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.openFinDeskStrategies.statisticalArbitrageBasedOnKalmanFilter; 2 | 3 | 4 | import org.la4j.Matrix; 5 | 6 | public class Cointegration { 7 | double mDelta; 8 | double mR; 9 | KalmanFilter mFilter; 10 | int mNobs = 2; 11 | 12 | public Cointegration(double delta, double r) { 13 | mDelta = delta; 14 | mR = r; 15 | 16 | Matrix vw = Matrix.identity(mNobs).multiply(mDelta / (1 - delta)); 17 | Matrix a = Matrix.identity(mNobs); 18 | 19 | Matrix x = Matrix.zero(mNobs, 1); 20 | 21 | mFilter = new KalmanFilter(mNobs, 1); 22 | mFilter.setUpdateMatrix(a); 23 | mFilter.setState(x); 24 | mFilter.setStateCovariance(Matrix.zero(mNobs, mNobs)); 25 | mFilter.setUpdateCovariance(vw); 26 | mFilter.setMeasurementCovariance(Matrix.constant(1, 1, r)); 27 | } 28 | 29 | public void step(double x, double y) { 30 | mFilter.setExtractionMatrix(Matrix.from1DArray(1, 2, new double[]{1, x})); 31 | mFilter.step(Matrix.constant(1, 1, y)); 32 | } 33 | 34 | public double getAlpha() { 35 | return mFilter.getState().getRow(0).get(0); 36 | } 37 | 38 | public double getBeta() { 39 | return mFilter.getState().getRow(1).get(0); 40 | } 41 | 42 | public double getVariance() { 43 | return mFilter.getInnovationCovariance().get(0, 0); 44 | } 45 | 46 | public double getError() { 47 | return mFilter.getInnovation().get(0, 0); 48 | } 49 | } 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/statisticalArbitrageBasedOnKalmanFilter/KalmanFilterBasedCointegration.java: -------------------------------------------------------------------------------- 1 | /* 2 | package com.farshad.algotrading.openFinDeskStrategies.statisticalArbitrageBasedOnKalmanFilter; 3 | 4 | import com.farshad.algotrading.containerCore.openFinDeskOrder.OpenFinDeskOrder; 5 | import com.farshad.algotrading.openFinDeskStrategies.OpenFinDeskStrategy; 6 | import org.ta4j.com.farshad.algotrading.containerCore.TimeSeriesPoint; 7 | import org.ta4j.com.farshad.algotrading.containerCore.TradingRecord; 8 | 9 | import java.io.IOException; 10 | import java.util.concurrent.Callable; 11 | 12 | public class KalmanFilterBasedCointegration extends OpenFinDeskStrategy { 13 | 14 | public KalmanFilterBasedCointegration(TimeSeriesPoint series, TradingRecord tradingRecord) { 15 | super(series, tradingRecord); 16 | } 17 | 18 | @Override 19 | public Callable define() throws IOException { 20 | 21 | 22 | Process process=new Process(series,tradingRecord); 23 | process.initialize(); 24 | process.calculate(); 25 | 26 | 27 | OpenFinDeskOrder openFinDeskOrder=new OpenFinDeskOrder(series.getName()); 28 | 29 | openFinDeskOrder.setSymbol("akhaber"); 30 | openFinDeskOrder.setStrategyName("KalmanFilterBasedCointegration"); 31 | 32 | openFinDeskOrder.setPosition("buy"); 33 | openFinDeskOrder.setPrice(series.getBar(0).getClosePrice().doubleValue()); 34 | openFinDeskOrder.setStopLoss(3); 35 | openFinDeskOrder.setTakeProfit(8); 36 | openFinDeskOrder.setVolume(300); 37 | 38 | 39 | OpenFinDeskOrder finalOpenFinDeskOrder = openFinDeskOrder; 40 | return () -> { 41 | System.out.println("Observable thread: " + Thread.currentThread().getName()); 42 | return openFinDeskOrder; 43 | }; 44 | } 45 | } 46 | */ 47 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/openFinDeskStrategies/statisticalArbitrageBasedOnKalmanFilter/Process.java: -------------------------------------------------------------------------------- 1 | /* 2 | package com.farshad.algotrading.openFinDeskStrategies.statisticalArbitrageBasedOnKalmanFilter; 3 | 4 | import org.apache.log4j.Logger; 5 | import org.ta4j.com.farshad.algotrading.containerCore.TimeSeriesPoint; 6 | import org.ta4j.com.farshad.algotrading.containerCore.TradingRecord; 7 | import com.farshad.algotrading.containerCore.Symbol; 8 | 9 | import java.io.IOException; 10 | 11 | public class Process { 12 | private static Logger LOGGER= Logger.getLogger(Process.class); 13 | 14 | boolean mReinvest = false; 15 | 16 | String mX, mY; 17 | //TradingContext mContext; 18 | Cointegration mCoint; 19 | 20 | TimeSeriesPoint mAlpha; 21 | TimeSeriesPoint mBeta; 22 | TimeSeriesPoint mXs; 23 | TimeSeriesPoint mYs; 24 | TimeSeriesPoint mError; 25 | TimeSeriesPoint mVariance; 26 | TimeSeriesPoint mModel; 27 | 28 | TimeSeriesPoint series; 29 | TradingRecord tradingRecord; 30 | 31 | public Process(TimeSeriesPoint series, TradingRecord tradingRecord) { 32 | this.series = series; 33 | this.tradingRecord = tradingRecord; 34 | } 35 | 36 | public void initialize() throws IOException { 37 | //mContext = context; 38 | 39 | mCoint = new Cointegration(1e-10, 1e-7); 40 | mAlpha=new Symbol("alpha").getSeriesFromFile("/src/main/java/files/sarood-M1.csv"); 41 | mBeta=new Symbol("beta").getSeriesFromFile("/src/main/java/files/sarood-M1.csv"); 42 | mXs=new Symbol("mXs").getSeriesFromFile("/src/main/java/files/sarood-M1.csv"); 43 | mYs=new Symbol("mYs").getSeriesFromFile("/src/main/java/files/sarood-M1.csv"); 44 | mError=new Symbol("mError").getSeriesFromFile("/src/main/java/files/sarood-M1.csv"); 45 | mVariance=new Symbol("mVariance").getSeriesFromFile("/src/main/java/files/sarood-M1.csv"); 46 | mModel=new Symbol("mModel").getSeriesFromFile("/src/main/java/files/sarood-M1.csv"); 47 | 48 | // mAlpha = new DoubleSeries("alpha"); 49 | //mBeta = new DoubleSeries("beta"); 50 | //mXs = new DoubleSeries("x"); 51 | //mYs = new DoubleSeries("y"); 52 | //mError = new DoubleSeries("error"); 53 | //mVariance = new DoubleSeries("variance"); 54 | //mModel = new DoubleSeries("model"); 55 | } 56 | 57 | public void calculate(){ 58 | //mContext=context; 59 | double x = mXs.getLastBar().getClosePrice().doubleValue(); 60 | double y = mYs.getLastBar().getClosePrice().doubleValue(); 61 | double alpha = mCoint.getAlpha(); 62 | double beta = mCoint.getBeta(); 63 | 64 | mCoint.step(x, y); 65 | mAlpha.add(alpha, mContext.getTime()); 66 | mBeta.add(beta, mContext.getTime()); 67 | mXs.add(x, mContext.getTime()); 68 | mYs.add(y, mContext.getTime()); 69 | mError.add(mCoint.getError(), mContext.getTime()); 70 | mVariance.add(mCoint.getVariance(), mContext.getTime()); 71 | 72 | double error = mCoint.getError(); 73 | 74 | mModel.add(beta * x + alpha, mContext.getTime()); 75 | LOGGER.info("beta * x + alpha="+beta * x + alpha+" time="+mContext.getTime() ); 76 | } 77 | 78 | } 79 | */ 80 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/riskManagement/ActionPerformer.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.riskManagement; 2 | 3 | import com.farshad.algotrading.core.openFinDeskOrder.OpenFinDeskOrder; 4 | import org.apache.log4j.Logger; 5 | import com.farshad.algotrading.riskManagement.moneymanagement.MoneyManager; 6 | 7 | public class ActionPerformer { 8 | final static Logger logger= Logger.getLogger(ActionPerformer.class); 9 | 10 | private MoneyManager moneyManager; 11 | 12 | 13 | public ActionPerformer(MoneyManager moneyManager) { 14 | this.moneyManager = moneyManager; 15 | } 16 | 17 | private int findNumberOfOpenOrders(String symbol){ 18 | return moneyManager.findNumberOfOpenOrders(symbol); 19 | } 20 | 21 | 22 | public String stringifyOrder(OpenFinDeskOrder openFinDeskOrder) { 23 | 24 | String orderType="n"; 25 | orderType = openFinDeskOrder.getOrderType(); 26 | 27 | 28 | 29 | if (moneyManager.findNumberOfOpenOrders(openFinDeskOrder.getSymbol()) listOfAllPositions = new ArrayList<>(); 25 | 26 | private Position position = new Position(); 27 | 28 | public void setPositionGap(double positionGap) { 29 | this.difference=0; 30 | this.positionGap = positionGap; 31 | } 32 | 33 | 34 | 35 | public OpenFinDeskOrder filterOrder(OpenFinDeskOrder openFinDeskOrder) { 36 | 37 | logger.debug("listOfAllPositions.size()="+listOfAllPositions.size()); 38 | goodToGo = true; 39 | 40 | for (int i = 0; i < listOfAllPositions.size(); i++) { 41 | difference=Math.abs(listOfAllPositions.get(i).getPrice() - openFinDeskOrder.getPrice()); 42 | logger.info("difference="+difference); 43 | 44 | if (difference> positionGap) { 45 | goodToGo = true; 46 | } else { 47 | goodToGo = false; 48 | logger.log(LiveTradingLogLevel.SIGNALS,"sorry,positionManager in openFinDesk Hedge Fund refused this order due to gap" + 49 | " policies!"); 50 | break; 51 | } 52 | } 53 | 54 | if (!goodToGo) { 55 | openFinDeskOrder.setOrderType("noOrder"); 56 | } 57 | 58 | return openFinDeskOrder; 59 | } 60 | 61 | 62 | 63 | 64 | public void updatePositions(String payload) { 65 | listOfAllPositions.clear(); 66 | if(!payload.equals("")) { 67 | if(!payload.equals("noPayload")){ 68 | String[] ticketsAndOpenPrices = payload.split(","); 69 | found = false; 70 | for (int i = 0; i < ticketsAndOpenPrices.length; i++) { 71 | if ((i % 2) == 0) { 72 | logger.info("tickets[" + i + "]=" + ticketsAndOpenPrices[i]); 73 | position.setTicketNumber(Integer.parseInt(ticketsAndOpenPrices[i])); 74 | } else { 75 | logger.info("openPrices[" + i + "]=" + ticketsAndOpenPrices[i]); 76 | position.setPrice(Double.valueOf(ticketsAndOpenPrices[i])); 77 | } 78 | 79 | if (i % 2 > 0) { 80 | listOfAllPositions.add(position); 81 | } 82 | } 83 | } 84 | } 85 | } 86 | 87 | 88 | 89 | 90 | public int getNumberOfOpenPositions(){ 91 | return listOfAllPositions.size(); 92 | } 93 | 94 | 95 | } 96 | 97 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container0/CheckIfADXIsOkChanceNode.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.strategyContainer.container0; 2 | 3 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 4 | import com.farshad.algotrading.openFinDeskStrategies.fibonacciBased.TrendStrengthStrategyBasedOnInternalRetracementSequences; 5 | import com.farshad.algotrading.openFinDeskStrategies.indicatorBased.ADXBasedTrendDetection; 6 | import com.farshad.algotrading.core.containerCore.ChanceNode; 7 | import org.apache.log4j.Logger; 8 | 9 | @OpenFinDeskChanceNode(containerId=0,nodeId=0 10 | ,openfindeskStrategies={ADXBasedTrendDetection.class, TrendStrengthStrategyBasedOnInternalRetracementSequences.class} 11 | ,timeFrames={"PERIOD_H1","PERIOD_D1"}) 12 | public class CheckIfADXIsOkChanceNode extends ChanceNode { 13 | final static Logger logger= Logger.getLogger(CheckIfADXIsOkChanceNode.class); 14 | 15 | @Override 16 | public void executeCurrentChanceNode() { 17 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 18 | this.openFinDeskOrder.setPosition("*"); 19 | this.openFinDeskOrder.setOrderType("noOrder"); 20 | this.openFinDeskOrder.setStrategyName("no signal from container 0"); 21 | this.openFinDeskOrder.setAction("doNothingAndWait"); 22 | this.openFinDeskOrder.setVolume("0.01"); 23 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 24 | logger.info("featureVector.get(1).getPosition()="+featureVector.get(1).getPosition()); 25 | 26 | if ((featureVector.get(0).getPosition().equals("buy")) && (featureVector.get(1).getPosition().equals("buy"))) { 27 | this.openFinDeskOrder.setOrderType("openBuy"); 28 | this.openFinDeskOrder.setAction("buyUsingSecondQuantizedLevel"); 29 | this.openFinDeskOrder.setStrategyName("container0"); 30 | }else if ((featureVector.get(0).getPosition().equals("sell")) && (featureVector.get(1).getPosition().equals("sell"))) { 31 | this.openFinDeskOrder.setOrderType("openSell"); 32 | this.openFinDeskOrder.setAction("sellUsingSecondQuantizedLevel"); 33 | this.openFinDeskOrder.setStrategyName("container0"); 34 | }else { 35 | this.openFinDeskOrder.setOrderType("noOrder"); 36 | this.openFinDeskOrder.setAction("doNothingAndWait"); 37 | } 38 | decisionIsMade=true; 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container1/CheckIfWeHavePinBarCandlestickChanceNode.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.strategyContainer.container1; 2 | 3 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 4 | import com.farshad.algotrading.openFinDeskStrategies.candlestickDriven.PinBarStrategy; 5 | import com.farshad.algotrading.openFinDeskStrategies.fibonacciBased.TrendStrengthStrategyBasedOnInternalRetracementSequences; 6 | import org.apache.log4j.Logger; 7 | import com.farshad.algotrading.core.containerCore.ChanceNode; 8 | 9 | @OpenFinDeskChanceNode(containerId=1,nodeId=0 10 | ,openfindeskStrategies={PinBarStrategy.class,TrendStrengthStrategyBasedOnInternalRetracementSequences.class} 11 | ,timeFrames={"PERIOD_H1","PERIOD_D1"},disabled=true) 12 | public class CheckIfWeHavePinBarCandlestickChanceNode extends ChanceNode { 13 | final static Logger logger= Logger.getLogger(CheckIfWeHavePinBarCandlestickChanceNode.class); 14 | 15 | @Override 16 | public void executeCurrentChanceNode() { 17 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 18 | this.openFinDeskOrder.setPosition("*"); 19 | this.openFinDeskOrder.setOrderType("noOrder"); 20 | this.openFinDeskOrder.setStrategyName("no signal from container 1"); 21 | this.openFinDeskOrder.setAction("doNothingAndWait"); 22 | this.openFinDeskOrder.setVolume("0.01"); 23 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 24 | logger.info("featureVector.get(1).getPosition()="+featureVector.get(1).getPosition()); 25 | if ((featureVector.get(0).getPosition().equals("bearishPinBar"))&&(featureVector.get(1).getPosition().equals("sell"))){ 26 | this.openFinDeskOrder.setOrderType("openSell"); 27 | this.openFinDeskOrder.setAction("sellUsingScalping"); 28 | this.openFinDeskOrder.setStrategyName("container1"); 29 | }else if((featureVector.get(0).getPosition().equals("bullishPinBar"))&&(featureVector.get(1).getPosition().equals("buy"))){ 30 | this.openFinDeskOrder.setOrderType("openBuy"); 31 | this.openFinDeskOrder.setAction("buyUsingScalping"); 32 | this.openFinDeskOrder.setStrategyName("container1"); 33 | } 34 | decisionIsMade=true; 35 | 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container2/CheckIfCrossingMACDAndTrendingADXChanceNode.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.strategyContainer.container2; 2 | 3 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 4 | import com.farshad.algotrading.openFinDeskStrategies.indicatorBased.ADXBasedTrendDetection; 5 | import com.farshad.algotrading.openFinDeskStrategies.indicatorBased.MACDbasedCrossingStrategy; 6 | import com.farshad.algotrading.core.containerCore.ChanceNode; 7 | import org.apache.log4j.Logger; 8 | 9 | @OpenFinDeskChanceNode(containerId=2,nodeId=0 10 | ,openfindeskStrategies={MACDbasedCrossingStrategy.class, ADXBasedTrendDetection.class} 11 | ,timeFrames={"PERIOD_H1","PERIOD_D1"}) 12 | public class CheckIfCrossingMACDAndTrendingADXChanceNode extends ChanceNode { 13 | final static Logger logger= Logger.getLogger(CheckIfCrossingMACDAndTrendingADXChanceNode.class); 14 | 15 | @Override 16 | public void executeCurrentChanceNode() { 17 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 18 | this.openFinDeskOrder.setPosition("*"); 19 | this.openFinDeskOrder.setOrderType("noOrder"); 20 | this.openFinDeskOrder.setStrategyName("no signal from container 2"); 21 | this.openFinDeskOrder.setAction("doNothingAndWait"); 22 | this.openFinDeskOrder.setVolume("0.01"); 23 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 24 | logger.info("featureVector.get(1).getPosition()="+featureVector.get(1).getPosition()); 25 | 26 | if ((featureVector.get(0).getPosition().equals("buy")) && (featureVector.get(1).getPosition().equals("buy"))) { 27 | this.openFinDeskOrder.setOrderType("openBuy"); 28 | this.openFinDeskOrder.setAction("buyUsingSecondQuantizedLevel"); 29 | this.openFinDeskOrder.setStrategyName("Container2"); 30 | 31 | }else if ((featureVector.get(0).getPosition().equals("sell")) && (featureVector.get(1).getPosition().equals("sell"))) { 32 | this.openFinDeskOrder.setOrderType("openSell"); 33 | this.openFinDeskOrder.setAction("sellUsingSecondQuantizedLevel"); 34 | this.openFinDeskOrder.setStrategyName("Container2"); 35 | }else { 36 | this.openFinDeskOrder.setOrderType("noOrder"); 37 | this.openFinDeskOrder.setAction("doNothingAndWait"); 38 | } 39 | decisionIsMade=true; 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container3/CheckIfCrossingMovingAverageChanceNode.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.strategyContainer.container3; 2 | 3 | 4 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 5 | import com.farshad.algotrading.openFinDeskStrategies.indicatorBased.ADXBasedTrendDetection; 6 | import com.farshad.algotrading.openFinDeskStrategies.indicatorBased.CrossingTwoMovingAverages; 7 | import com.farshad.algotrading.core.containerCore.ChanceNode; 8 | import org.apache.log4j.Logger; 9 | 10 | @OpenFinDeskChanceNode(containerId=3,nodeId=0 11 | ,openfindeskStrategies={CrossingTwoMovingAverages.class,ADXBasedTrendDetection.class} 12 | ,timeFrames={"PERIOD_H1","PERIOD_D1"},disabled=true) 13 | public class CheckIfCrossingMovingAverageChanceNode extends ChanceNode { 14 | final static Logger logger= Logger.getLogger(CheckIfCrossingMovingAverageChanceNode.class); 15 | 16 | @Override 17 | public void executeCurrentChanceNode() { 18 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 19 | this.openFinDeskOrder.setPosition("*"); 20 | this.openFinDeskOrder.setOrderType("noOrder"); 21 | this.openFinDeskOrder.setStrategyName("no signal from container 3"); 22 | this.openFinDeskOrder.setAction("doNothingAndWait"); 23 | this.openFinDeskOrder.setVolume("0.01"); 24 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 25 | if ((featureVector.get(0).getPosition().equals("buy")) && (featureVector.get(1).getPosition().equals("buy"))) { 26 | this.openFinDeskOrder.setOrderType("openBuy"); 27 | this.openFinDeskOrder.setAction("buyUsingSecondQuantizedLevel"); 28 | this.openFinDeskOrder.setStrategyName("Container3"); 29 | 30 | }else if ((featureVector.get(0).getPosition().equals("sell")) && (featureVector.get(1).getPosition().equals("sell"))) { 31 | this.openFinDeskOrder.setOrderType("openSell"); 32 | this.openFinDeskOrder.setAction("sellUsingSecondQuantizedLevel"); 33 | this.openFinDeskOrder.setStrategyName("Container3"); 34 | }else { 35 | this.openFinDeskOrder.setOrderType("noOrder"); 36 | this.openFinDeskOrder.setAction("doNothingAndWait"); 37 | } 38 | decisionIsMade=true; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container4/CheckIfEngulfingH1ADXD1.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.strategyContainer.container4; 2 | 3 | 4 | import com.farshad.algotrading.core.containerCore.ChanceNode; 5 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 6 | import com.farshad.algotrading.openFinDeskStrategies.candlestickDriven.EngulfingPatternStrategy; 7 | import com.farshad.algotrading.openFinDeskStrategies.indicatorBased.ADXBasedTrendDetection; 8 | import org.apache.log4j.Logger; 9 | 10 | @OpenFinDeskChanceNode(containerId=4,nodeId=0 11 | ,openfindeskStrategies={EngulfingPatternStrategy.class, ADXBasedTrendDetection.class} 12 | ,timeFrames={"PERIOD_H1","PERIOD_D1"}) 13 | public class CheckIfEngulfingH1ADXD1 extends ChanceNode { 14 | final static Logger logger= Logger.getLogger(CheckIfEngulfingH1ADXD1.class); 15 | 16 | 17 | @Override 18 | public void executeCurrentChanceNode() { 19 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 20 | this.openFinDeskOrder.setPosition("*"); 21 | this.openFinDeskOrder.setOrderType("noOrder"); 22 | this.openFinDeskOrder.setStrategyName("no signal from container 4"); 23 | this.openFinDeskOrder.setAction("doNothingAndWait"); 24 | this.openFinDeskOrder.setVolume("0.01"); 25 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 26 | logger.info("featureVector.get(1).getPosition()="+featureVector.get(1).getPosition()); 27 | 28 | if ((featureVector.get(0).getPosition().equals("bullishEngulfingCandleStick")) && (featureVector.get(1).getPosition().equals("buy"))) { 29 | this.openFinDeskOrder.setOrderType("openBuy"); 30 | this.openFinDeskOrder.setAction("buyUsingSecondQuantizedLevel"); 31 | this.openFinDeskOrder.setStrategyName("Container4"); 32 | }else if ((featureVector.get(0).getPosition().equals("bearishEngulfingCandleStick")) && (featureVector.get(1).getPosition().equals("sell"))) { 33 | this.openFinDeskOrder.setOrderType("openSell"); 34 | this.openFinDeskOrder.setAction("sellUsingSecondQuantizedLevel"); 35 | this.openFinDeskOrder.setStrategyName("Container4"); 36 | }else { 37 | this.openFinDeskOrder.setOrderType("noOrder"); 38 | this.openFinDeskOrder.setAction("doNothingAndWait"); 39 | } 40 | decisionIsMade=true; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container5/CheckIfCamarillaAndADX.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.strategyContainer.container5; 2 | 3 | import com.farshad.algotrading.core.containerCore.ChanceNode; 4 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 5 | import com.farshad.algotrading.openFinDeskStrategies.indicatorBased.ADXBasedTrendDetection; 6 | import com.farshad.algotrading.openFinDeskStrategies.pivotPointBased.CamarillaStrategy; 7 | import org.apache.log4j.Logger; 8 | 9 | 10 | @OpenFinDeskChanceNode(containerId=5,nodeId=0 11 | ,openfindeskStrategies={CamarillaStrategy.class, ADXBasedTrendDetection.class} 12 | ,timeFrames={"PERIOD_D1","PERIOD_H1"}) 13 | public class CheckIfCamarillaAndADX extends ChanceNode { 14 | final static Logger logger= Logger.getLogger(CheckIfCamarillaAndADX.class); 15 | 16 | @Override 17 | public void executeCurrentChanceNode() { 18 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 19 | this.openFinDeskOrder.setPosition("*"); 20 | this.openFinDeskOrder.setOrderType("noOrder"); 21 | this.openFinDeskOrder.setStrategyName("no signal from container 5"); 22 | this.openFinDeskOrder.setAction("doNothingAndWait"); 23 | this.openFinDeskOrder.setVolume("0.01"); 24 | logger.info("featureVector.get(0).getPosition()="+featureVector.get(0).getPosition()); 25 | logger.info("featureVector.get(1).getPosition()="+featureVector.get(1).getPosition()); 26 | 27 | if ((featureVector.get(0).getPosition().equals("buy")) && (featureVector.get(1).getPosition().equals("buy"))) { 28 | this.openFinDeskOrder.setOrderType("openBuy"); 29 | this.openFinDeskOrder.setAction("buyUsingFirstQuantizedLevel"); 30 | this.openFinDeskOrder.setStrategyName("Container5"); 31 | }else if ((featureVector.get(0).getPosition().equals("sell")) && (featureVector.get(1).getPosition().equals("sell"))) { 32 | this.openFinDeskOrder.setOrderType("openSell"); 33 | this.openFinDeskOrder.setAction("sellUsingFirstQuantizedLevel"); 34 | this.openFinDeskOrder.setStrategyName("Container5"); 35 | }else { 36 | this.openFinDeskOrder.setOrderType("noOrder"); 37 | this.openFinDeskOrder.setAction("doNothingAndWait"); 38 | } 39 | decisionIsMade=true; 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container9/CheckIfBothTimeFramesAgreeChanceNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | package com.farshad.algotrading.strategyContainer.container9; 3 | 4 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 5 | import com.farshad.algotrading.openFinDeskStrategies.fibonacciBased.TrendStrengthStrategyBasedOnInternalRetracementSequences; 6 | import org.apache.log4j.Logger; 7 | import com.farshad.algotrading.core.containerCore.ChanceNode; 8 | 9 | @OpenFinDeskChanceNode(containerId=9,nodeId=1 10 | ,openfindeskStrategies={TrendStrengthStrategyBasedOnInternalRetracementSequences.class, TrendStrengthStrategyBasedOnInternalRetracementSequences.class} 11 | ,timeFrames={"PERIOD_H1","PERIOD_D1"}) 12 | 13 | public class CheckIfBothTimeFramesAgreeChanceNode extends ChanceNode { 14 | final static Logger logger= Logger.getLogger(CheckIfBothTimeFramesAgreeChanceNode.class); 15 | 16 | @Override 17 | public void executeCurrentChanceNode() { 18 | this.openFinDeskOrder.setPrice(featureVector.get(0).getPrice()); 19 | this.openFinDeskOrder.setStrategyName("no signal from container 9"); 20 | 21 | this.openFinDeskOrder.setOpenFinDeskOrderNumber(featureVector.get(0).getOpenFinDeskOrderNumber()); 22 | if ((featureVector.get(0).getPosition().equals(featureVector.get(1).getPosition()))&&(featureVector.get(0).getPosition().equals("buy"))) { 23 | openFinDeskOrder.setOrderType("openBuy"); 24 | openFinDeskOrder.setPosition("buy"); 25 | openFinDeskOrder.setVolume("0.01"); 26 | openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 27 | openFinDeskOrder.setPrice(featureVector.get(0).getPrice()); 28 | this.openFinDeskOrder.setStrategyName("container9"); 29 | 30 | switch (quantize(featureVector.get(1).getParameter())) { 31 | case "LEVEL1": 32 | openFinDeskOrder.setAction("buyUsingFirstQuantizedLevel"); 33 | break; 34 | case "LEVEL2": 35 | openFinDeskOrder.setAction("buyUsingSecondQuantizedLevel"); 36 | break; 37 | case "LEVEL3": 38 | openFinDeskOrder.setAction("buyUsingThirdQuantizedLevel"); 39 | openFinDeskOrder.setVolume("0.02"); 40 | break; 41 | } 42 | }else if ((featureVector.get(0).getPosition().equals(featureVector.get(1).getPosition()))&&(featureVector.get(0).getPosition().equals("sell"))) { 43 | openFinDeskOrder.setOrderType("openSell"); 44 | openFinDeskOrder.setPosition("sell"); 45 | openFinDeskOrder.setVolume("0.01"); 46 | openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 47 | openFinDeskOrder.setPrice(featureVector.get(0).getPrice()); 48 | this.openFinDeskOrder.setStrategyName("container9"); 49 | 50 | switch (quantize(featureVector.get(1).getParameter())) { 51 | case "LEVEL1": 52 | openFinDeskOrder.setAction("sellUsingFirstQuantizedLevel"); 53 | break; 54 | case "LEVEL2": 55 | openFinDeskOrder.setAction("sellUsingSecondQuantizedLevel"); 56 | break; 57 | case "LEVEL3": 58 | openFinDeskOrder.setAction("sellUsingThirdQuantizedLevel"); 59 | openFinDeskOrder.setVolume("0.02"); 60 | break; 61 | } 62 | } 63 | 64 | //logger.info("decision="+openFinDeskOrder.getAction()); 65 | 66 | //since this is the End Node 67 | decisionIsMade=true; 68 | 69 | } 70 | 71 | 72 | private String quantize(String parameter) { 73 | String quantizedLevel=""; 74 | if (Double.valueOf(parameter)<0.33){ 75 | quantizedLevel="Level1"; 76 | }else if(Double.valueOf(parameter)<0.66){ 77 | quantizedLevel="Level2"; 78 | }else { 79 | quantizedLevel="Level3"; 80 | } 81 | return quantizedLevel; 82 | } 83 | 84 | } 85 | */ 86 | -------------------------------------------------------------------------------- /src/main/java/com/farshad/algotrading/strategyContainer/container9/CheckIfHigherTimeFrameIsTrendingChanceNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | package com.farshad.algotrading.strategyContainer.container9; 3 | 4 | import com.farshad.algotrading.containerCore.openFinDeskOrder.OpenFinDeskOrder; 5 | import com.farshad.algotrading.openFinDeskAnnotations.OpenFinDeskChanceNode; 6 | import com.farshad.algotrading.openFinDeskStrategies.fibonacciBased.TrendStrengthStrategyBasedOnInternalRetracementSequences; 7 | import org.apache.log4j.Logger; 8 | import com.farshad.algotrading.core.containerCore.ChanceNode; 9 | 10 | @OpenFinDeskChanceNode(containerId=9,nodeId=0 11 | ,openfindeskStrategies={TrendStrengthStrategyBasedOnInternalRetracementSequences.class, TrendStrengthStrategyBasedOnInternalRetracementSequences.class} 12 | ,timeFrames={"PERIOD_H1","PERIOD_D1"}) 13 | public class CheckIfHigherTimeFrameIsTrendingChanceNode extends ChanceNode { 14 | final static Logger logger= Logger.getLogger(CheckIfHigherTimeFrameIsTrendingChanceNode.class); 15 | 16 | @Override 17 | public void executeCurrentChanceNode() { 18 | openFinDeskOrder=new OpenFinDeskOrder(featureVector.get(0).getSymbol()); 19 | this.openFinDeskOrder.setPrice(featureVector.get(0).getPrice()); 20 | this.openFinDeskOrder.setOpenFinDeskOrderNumber(featureVector.get(0).getOpenFinDeskOrderNumber()); 21 | logger.info("symbol="+featureVector.get(0).getSymbol()); 22 | this.openFinDeskOrder.setSymbol(featureVector.get(0).getSymbol()); 23 | this.openFinDeskOrder.setPosition("*"); 24 | this.openFinDeskOrder.setOrderType("noOrder"); 25 | this.openFinDeskOrder.setStrategyName("no signal from container 9"); 26 | this.openFinDeskOrder.setAction("doNothingAndWait"); 27 | this.openFinDeskOrder.setVolume("0.01"); 28 | 29 | if ((featureVector.get(0).getPosition().equals("*"))||(featureVector.get(1).getPosition().equals("*"))){ 30 | // logger.info("decision="+openFinDeskOrder.getAction()); 31 | decisionIsMade=true; 32 | } 33 | } 34 | 35 | 36 | 37 | 38 | } 39 | */ 40 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Root logger option 2 | log4j.rootLogger= DEBUG,rlfile,stdout,file,errorfile,myFATAL 3 | 4 | # Direct log messages to a reinforcementLearning log file 5 | log4j.appender.rlfile=org.apache.log4j.RollingFileAppender 6 | log4j.appender.rlfile.File=./openFinDeskLogs/debug.log 7 | log4j.appender.rlfile.Threshold =DEBUG 8 | log4j.appender.rlfile.MaxFileSize=10MB 9 | log4j.appender.rlfile.MaxBackupIndex=10 10 | log4j.appender.rlfile.layout=org.apache.log4j.PatternLayout 11 | log4j.appender.rlfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 12 | 13 | # Direct log messages to stdout 14 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 15 | log4j.appender.stdout.Target=System.out 16 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 17 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 18 | log4j.appender.stdout.Threshold =DEBUG 19 | 20 | # Direct log messages to a strategies log file 21 | #log4j.logger.file = INFO 22 | log4j.appender.file=org.apache.log4j.RollingFileAppender 23 | log4j.appender.file.File=./openFinDeskLogs/strategies.log 24 | log4j.appender.file.Threshold =WARN 25 | log4j.appender.file.MaxFileSize=10MB 26 | log4j.appender.file.MaxBackupIndex=10 27 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 28 | log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 29 | 30 | # Direct log messages to a strategies log file 31 | log4j.appender.errorfile=org.apache.log4j.RollingFileAppender 32 | log4j.appender.errorfile.File=./openFinDeskLogs/error.log 33 | log4j.appender.errorfile.Threshold=ERROR 34 | log4j.appender.errorfile.MaxFileSize=10MB 35 | log4j.appender.errorfile.MaxBackupIndex=10 36 | log4j.appender.errorfile.layout=org.apache.log4j.PatternLayout 37 | log4j.appender.errorfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 38 | 39 | #fatal 40 | log4j.appender.myFATAL=org.apache.log4j.RollingFileAppender 41 | log4j.appender.myFATAL.File=./openFinDeskLogs/myFatal.log 42 | log4j.appender.myFATAL.Threshold =FATAL 43 | log4j.appender.myFATAL.MaxFileSize=10MB 44 | log4j.appender.myFATAL.MaxBackupIndex=10 45 | log4j.appender.myFATAL.layout=org.apache.log4j.PatternLayout 46 | log4j.appender.myFATAL.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 47 | -------------------------------------------------------------------------------- /src/test/java/com/farshad/algotrading/TestCSVReader.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading; 2 | 3 | import com.farshad.algotrading.core.openFinDeskStore.csv.stocksInputData.csv.CSVReader; 4 | import org.apache.log4j.Logger; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | 9 | public class TestCSVReader { 10 | final static Logger logger= Logger.getLogger(TestCSVReader.class); 11 | 12 | public static void main(String[] args) throws IOException, InterruptedException { 13 | String directory="src/main/java/files"; 14 | new File(directory).mkdirs(); 15 | File idea=new File(directory,"GBPUSD"+"-"+"M1"+".csv"); 16 | logger.info("idea.getPath()="+idea.getPath()); 17 | String fileName="/"+idea.getPath(); 18 | CSVReader csvReader=new CSVReader(); 19 | csvReader.setFileName(fileName); 20 | logger.info("csvReader.getLines() for GBPUSD="+csvReader.getLines()); 21 | 22 | 23 | idea=new File(directory,"EURUSD"+"-"+"M1"+".csv"); 24 | logger.info("idea.getPath() for EURUSD="+idea.getPath()); 25 | fileName="/"+idea.getPath(); 26 | CSVReader csvReader2=new CSVReader(); 27 | csvReader.setFileName(fileName); 28 | logger.info("csvReader.getLines() for EURUSD="+csvReader2.getLines()); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/farshad/algotrading/TestComparison.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading; 2 | 3 | import com.farshad.algotrading.core.Comparison; 4 | import org.apache.log4j.Logger; 5 | 6 | public class TestComparison { 7 | 8 | final static Logger logger= Logger.getLogger(TestComparison.class); 9 | 10 | public static void main(String[] args) { 11 | Comparison comparison=new Comparison(); 12 | // int b1=comparison.compareTwoTimes("2019.09.17 12:11","2019.09.17 12:03"); 13 | int b1=comparison.compareTwoTimesWithFormat("2019-09-16T11:58+04:30[Asia/Tehran]","2019-09-16T11:54+04:30[Asia/Tehran]"); 14 | 15 | // 2019-09-16T11:54+04:30[Asia/Tehran] 16 | logger.info("b1="+b1); 17 | long diff=comparison.getDifference(); 18 | logger.info("difference="+diff); 19 | //compareTwoTimes(t1,t2) 20 | //-1 means t1t2 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/farshad/algotrading/TestRegressionAndPredictForex.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading; 2 | 3 | import org.apache.log4j.Logger; 4 | 5 | public class TestRegressionAndPredictForex { 6 | final static Logger logger= Logger.getLogger(TestRegressionAndPredictForex.class); 7 | 8 | public static void main(String[] args) { 9 | double EURUSD=1.10813; 10 | double GBPUSD=0.02773169770280957*EURUSD+1.071629011176105; 11 | logger.info("prediction for GBPUSD="+GBPUSD); 12 | 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/farshad/algotrading/customizedPivotPointsMethods/CamarillaPivotPointTest.java: -------------------------------------------------------------------------------- 1 | package com.farshad.algotrading.customizedPivotPointsMethods; 2 | 3 | import com.farshad.algotrading.core.customizedPivotPointMethods.CamarillaPivotPointApproach; 4 | import org.apache.log4j.Logger; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.DisplayName; 7 | import org.junit.jupiter.api.Test; 8 | import org.ta4j.core.BaseTimeSeries; 9 | import org.ta4j.core.TimeSeries; 10 | 11 | import java.time.ZonedDateTime; 12 | 13 | import static org.junit.jupiter.api.Assertions.assertAll; 14 | import static org.junit.jupiter.api.Assertions.assertEquals; 15 | 16 | @DisplayName("testing Camarilla Pivot Point") 17 | public class CamarillaPivotPointTest { 18 | final static Logger logger= Logger.getLogger(CamarillaPivotPointTest.class); 19 | TimeSeries timeSeries1; 20 | 21 | @BeforeEach 22 | void init() { 23 | timeSeries1=new BaseTimeSeries.SeriesBuilder().withName("EURUSD").build(); 24 | ZonedDateTime endTime = ZonedDateTime.now(); 25 | timeSeries1.addBar(endTime, 105.42, 112.99, 104.01, 111.42, 1337); 26 | timeSeries1.addBar(endTime.plusDays(1), 111.43, 112.83, 107.77, 187.99, 1234); 27 | timeSeries1.addBar(endTime.plusDays(2), 1.0790, 1.50, 1.90, 1.42, 200); 28 | timeSeries1.addBar(endTime.plusDays(3), 147.90, 117.50, 107.90, 145.42, 4242); 29 | timeSeries1.addBar(endTime.plusDays(4), 157.90, 117.50, 107.90, 145.42, 4242); 30 | timeSeries1.addBar(endTime.plusDays(5), 167.90, 117.50, 107.90, 195.42, 4242); 31 | timeSeries1.addBar(endTime.plusDays(6), 177.90, 117.50, 107.90, 185.42, 4242); 32 | timeSeries1.addBar(endTime.plusDays(7), 107.90, 117.50, 107.90, 175.42, 4242); 33 | timeSeries1.addBar(endTime.plusDays(8), 107.90, 117.50, 107.90, 165.42, 4242); 34 | timeSeries1.addBar(endTime.plusDays(9), 107.90, 117.50, 107.90, 155.42, 4242); 35 | timeSeries1.addBar(endTime.plusDays(10), 107.90, 117.50, 107.90, 145.42, 4242); 36 | timeSeries1.addBar(endTime.plusDays(11), 107.90, 117.50, 107.90, 135.42, 4242); 37 | timeSeries1.addBar(endTime.plusDays(12), 107.90, 117.50, 107.90, 125.42, 4242); 38 | timeSeries1.addBar(endTime.plusDays(13), 107.90, 117.50, 107.90, 105.42, 4242); 39 | timeSeries1.addBar(endTime.plusDays(14), 107.90, 117.50, 107.90, 125.42, 4242); 40 | timeSeries1.addBar(endTime.plusDays(15), 107.90, 117.50, 107.90, 138.42, 4242); 41 | timeSeries1.addBar(endTime.plusDays(16), 107.90, 117.50, 107.90, 136.42, 4242); 42 | timeSeries1.addBar(endTime.plusDays(17), 107.90, 117.50, 107.90, 133.42, 4242); 43 | timeSeries1.addBar(endTime.plusDays(18), 107.90, 117.50, 107.90, 132.42, 4242); 44 | timeSeries1.addBar(endTime.plusDays(19), 107.90, 117.50, 107.90, 138.42, 4242); 45 | timeSeries1.addBar(endTime.plusDays(20), 107.90, 117.50, 107.90, 137.42, 4242); 46 | timeSeries1.addBar(endTime.plusDays(21), 107.90, 117.50, 107.90, 136.42, 4242); 47 | timeSeries1.addBar(endTime.plusDays(22), 107.90, 117.50, 107.90, 135.42, 4242); 48 | timeSeries1.addBar(endTime.plusDays(23), 107.90, 117.50, 107.90, 134.42, 4242); 49 | timeSeries1.addBar(endTime.plusDays(24), 1.90, 1.50345, 1.90, 1.42, 642); 50 | timeSeries1.addBar(endTime.plusDays(25), 1.95, 1.53, 1.98, 1.46, 345); 51 | } 52 | 53 | @DisplayName("find support and resistance and pivot point") 54 | @Test 55 | void findPivotPoints() { 56 | CamarillaPivotPointApproach camarillaPivotPointApproach=new CamarillaPivotPointApproach(timeSeries1); 57 | double pp=camarillaPivotPointApproach.getPp(); 58 | double r0=camarillaPivotPointApproach.getR()[0]; 59 | double s0=camarillaPivotPointApproach.getS()[0]; 60 | 61 | assertAll("pivot points", 62 | () -> assertEquals(1.6078166666666664, pp), 63 | () -> assertEquals(0.990417385, r0), 64 | () -> assertEquals(1.8495826149999999,s0) 65 | ); 66 | } 67 | 68 | 69 | 70 | 71 | } 72 | -------------------------------------------------------------------------------- /systemd services: -------------------------------------------------------------------------------- 1 | https://www.linode.com/docs/quick-answers/linux/start-service-at-boot/ 2 | 3 | algoRunJavaFile.sh: 4 | #!/bin/bash 5 | echo "now running algotrader using shellscript---" 6 | cd /home/ubuntu 7 | java -jar simple-1.0-SNAPSHOT.jar > farshadAlgotraderLog.txt & 8 | 9 | --------------------------------------------- 10 | chmod +x algoRunJavaFile.sh 11 | --------------------------------------------- 12 | Create a Unit file to define a systemd service: 13 | inside /etc/systemd/system/algoTradingService.service : 14 | [Unit] 15 | #After=network.target auditd.service 16 | Description=systemd service to run java file at startup. 17 | [Service] 18 | #Type=simple 19 | WorkingDirectory=/home/ubuntu/ 20 | ExecStart=/bin/bash algoRunJavaFile.sh start 21 | #Restart=always 22 | #RestartSec=60 23 | User=ubuntu 24 | Type=forking 25 | Restart=on-failure 26 | RestartSec=10 27 | [Install] 28 | WantedBy=multi-user.target 29 | --------------------------------------------- 30 | cd /etc/systemd/system 31 | 32 | sudo chmod 644 /etc/systemd/system/algoTradingService.service 33 | sudo systemctl enable algoTradingService.service 34 | sudo systemctl start algoTradingService.service 35 | sudo systemctl restart algoTradingService.service 36 | 37 | -------------------------------------------------------------------------------- /todolist.txt: -------------------------------------------------------------------------------- 1 | nothing 2 | --------------------------------------------------------------------------------