├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── exchange
│ │ └── core2
│ │ └── rest
│ │ ├── CommandEventsRouter.java
│ │ ├── Config.java
│ │ ├── GatewayState.java
│ │ ├── RestGatewayApplication.java
│ │ ├── WebSocketConfig.java
│ │ ├── commands
│ │ ├── ApiErrorCodes.java
│ │ ├── HelloMessage.java
│ │ ├── RestApiCancelOrder.java
│ │ ├── RestApiMoveOrder.java
│ │ ├── RestApiPlaceOrder.java
│ │ ├── admin
│ │ │ ├── RestApiAccountBalanceAdjustment.java
│ │ │ ├── RestApiAddSymbol.java
│ │ │ ├── RestApiAddUser.java
│ │ │ ├── RestApiAdminAsset.java
│ │ │ ├── RestApiRequestMarketData.java
│ │ │ └── StompApiNotificationMessage.java
│ │ └── util
│ │ │ └── ArithmeticHelper.java
│ │ ├── controllers
│ │ ├── GreetingController.java
│ │ ├── RestControllerHelper.java
│ │ ├── SyncAdminApiAccountsController.java
│ │ ├── SyncAdminApiSymbolsController.java
│ │ ├── SyncTradeAccountApiController.java
│ │ ├── SyncTradeChartsApiController.java
│ │ ├── SyncTradeMiscApiController.java
│ │ └── SyncTradeOrdersApiController.java
│ │ ├── events
│ │ ├── MatchingRole.java
│ │ ├── NewTradeRecord.java
│ │ ├── OrderBookEvent.java
│ │ ├── OrderSizeChangeRecord.java
│ │ ├── OrderUpdateEvent.java
│ │ ├── ReduceRecord.java
│ │ ├── RejectionRecord.java
│ │ ├── RestGenericResponse.java
│ │ └── admin
│ │ │ ├── SymbolUpdateAdminEvent.java
│ │ │ ├── UserBalanceAdjustmentAdminEvent.java
│ │ │ └── UserCreatedAdminEvent.java
│ │ └── model
│ │ ├── api
│ │ ├── GatewayOrderState.java
│ │ ├── RestApiAccountState.java
│ │ ├── RestApiAccountTradeHistory.java
│ │ ├── RestApiAsset.java
│ │ ├── RestApiBar.java
│ │ ├── RestApiDeal.java
│ │ ├── RestApiExchangeInfo.java
│ │ ├── RestApiOrder.java
│ │ ├── RestApiOrderBook.java
│ │ ├── RestApiSymbol.java
│ │ ├── RestApiTime.java
│ │ ├── RestApiUserState.java
│ │ ├── RestApiUserTradesHistory.java
│ │ ├── StompAccountUpdate.java
│ │ ├── StompApiTick.java
│ │ ├── StompOrderUpdate.java
│ │ └── TimeFrame.java
│ │ └── internal
│ │ ├── BarsData.java
│ │ ├── ChartData.java
│ │ ├── GatewayAssetSpec.java
│ │ ├── GatewayBarLast.java
│ │ ├── GatewayBarStatic.java
│ │ ├── GatewayDeal.java
│ │ ├── GatewayOrder.java
│ │ ├── GatewaySymbolSpec.java
│ │ ├── GatewayUserProfile.java
│ │ └── TickRecord.java
└── resources
│ ├── application.properties
│ ├── db
│ └── migration
│ │ └── V0000__initial_schema.sql
│ ├── index.html
│ ├── javascript
│ ├── application.js
│ ├── atmosphere.js
│ └── jquery-2.0.3.js
│ ├── logback.xml
│ └── static
│ ├── app.js
│ ├── index.html
│ └── main.css
└── test
├── java
└── exchange
│ └── core2
│ └── rest
│ ├── ITExchangeGatewayHttp.java
│ ├── TestConfiguraton.java
│ └── support
│ ├── StompTestClient.java
│ ├── TestService.java
│ └── TestSupport.java
└── resources
└── it-local.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | .mvn/
3 |
4 | ### IntelliJ IDEA ###
5 | .idea
6 | *.iws
7 | *.iml
8 | *.ipr
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - oraclejdk8
4 | sudo: false
5 | script: mvn clean verify
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # exchange-gateway-rest
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | exchange.core2
7 | exchange-gateway-rest
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | Exchange REST Gateway
12 | Java Exchange Market Gateway
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.7.0
18 |
19 |
20 |
21 |
22 | false
23 |
24 | UTF-8
25 | UTF-8
26 | 1.8
27 |
28 | 25.0-jre
29 | 3.6.1
30 | 3.7
31 |
32 | 3.1.0
33 |
34 | 9.2.0
35 |
36 |
37 |
38 |
39 |
40 |
41 | com.google.guava
42 | guava
43 | ${guava.version}
44 |
45 |
46 |
47 | org.apache.commons
48 | commons-lang3
49 | ${commons-lang3.version}
50 |
51 |
52 |
53 | org.apache.commons
54 | commons-math3
55 | ${commons-math3.version}
56 |
57 |
58 |
59 |
60 | org.eclipse.collections
61 | eclipse-collections-api
62 | 9.2.0
63 |
64 |
65 | org.eclipse.collections
66 | eclipse-collections
67 | 9.2.0
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | exchange.core2
76 | exchange-core
77 | 0.5.5-SNAPSHOT
78 |
79 |
80 |
81 |
82 | org.springframework.boot
83 | spring-boot-starter-websocket
84 |
85 |
86 |
87 | org.webjars
88 | webjars-locator-core
89 |
90 |
91 | org.webjars
92 | sockjs-client
93 | 1.0.2
94 |
95 |
96 | org.webjars
97 | stomp-websocket
98 | 2.3.3
99 |
100 |
101 | org.webjars
102 | bootstrap
103 | 3.3.7
104 |
105 |
106 | org.webjars
107 | jquery
108 | 3.1.0
109 |
110 |
111 |
112 | com.fasterxml.jackson.datatype
113 | jackson-datatype-jsr310
114 |
115 |
116 |
117 | org.projectlombok
118 | lombok
119 | 1.18.24
120 |
121 |
122 |
123 | org.slf4j
124 | slf4j-api
125 |
126 |
127 |
128 | com.google.guava
129 | guava
130 |
131 |
132 | org.apache.commons
133 | commons-lang3
134 |
135 |
136 | org.springframework.boot
137 | spring-boot-configuration-processor
138 |
139 |
140 | org.springframework.boot
141 | spring-boot-starter
142 |
143 |
144 |
145 |
146 | org.hibernate.javax.persistence
147 | hibernate-jpa-2.1-api
148 | 1.0.0.Final
149 |
150 |
151 | org.springframework.boot
152 | spring-boot-starter-jdbc
153 |
154 |
155 | org.apache.tomcat
156 | tomcat-jdbc
157 |
158 |
159 |
160 |
161 | org.springframework.boot
162 | spring-boot-starter-data-jpa
163 |
164 |
165 | org.postgresql
166 | postgresql
167 | runtime
168 |
169 |
170 | org.hibernate
171 | hibernate-java8
172 |
173 |
174 | org.flywaydb
175 | flyway-core
176 |
177 |
178 | com.zaxxer
179 | HikariCP
180 | ${HikariCP.version}
181 |
182 |
183 |
184 |
185 | org.eclipse.collections
186 | eclipse-collections-api
187 |
188 |
189 | org.eclipse.collections
190 | eclipse-collections
191 |
192 |
193 |
194 |
195 | junit
196 | junit
197 | test
198 |
199 |
200 | org.mockito
201 | mockito-core
202 | test
203 |
204 |
205 | org.springframework.boot
206 | spring-boot-starter-test
207 | test
208 |
209 |
210 |
211 |
212 |
213 |
214 | default
215 |
216 | true
217 |
218 |
219 |
220 |
221 | org.apache.maven.plugins
222 | maven-surefire-plugin
223 |
224 |
225 |
226 |
227 |
228 |
229 | it
230 |
231 |
232 |
233 | org.apache.maven.plugins
234 | maven-surefire-plugin
235 |
236 |
237 | true
238 |
239 | **/IT*.java
240 | **/*IntegrationTest.java
241 |
242 |
243 | **/remote/**/*.class
244 | **/stress/**/*.class
245 | **/*Remote*Test.java
246 | **/*Stress*Test.java
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/CommandEventsRouter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest;
17 |
18 | import exchange.core2.core.IEventsHandler;
19 | import exchange.core2.core.IEventsHandler.RejectEvent;
20 | import exchange.core2.core.common.L2MarketData;
21 | import exchange.core2.core.common.MatcherEventType;
22 | import exchange.core2.core.common.MatcherTradeEvent;
23 | import exchange.core2.core.common.cmd.CommandResultCode;
24 | import exchange.core2.core.common.cmd.OrderCommand;
25 | import exchange.core2.core.common.cmd.OrderCommandType;
26 | import exchange.core2.rest.commands.util.ArithmeticHelper;
27 | import exchange.core2.rest.events.MatchingRole;
28 | import exchange.core2.rest.events.NewTradeRecord;
29 | import exchange.core2.rest.events.OrderBookEvent;
30 | import exchange.core2.rest.events.OrderSizeChangeRecord;
31 | import exchange.core2.rest.events.OrderUpdateEvent;
32 | import exchange.core2.rest.events.ReduceRecord;
33 | import exchange.core2.rest.events.RejectionRecord;
34 | import exchange.core2.rest.events.admin.UserBalanceAdjustmentAdminEvent;
35 | import exchange.core2.rest.events.admin.UserCreatedAdminEvent;
36 | import exchange.core2.rest.model.api.StompApiTick;
37 | import exchange.core2.rest.model.api.StompOrderUpdate;
38 | import exchange.core2.rest.model.internal.GatewayOrder;
39 | import exchange.core2.rest.model.internal.GatewaySymbolSpec;
40 | import exchange.core2.rest.model.internal.GatewayUserProfile;
41 | import exchange.core2.rest.model.internal.TickRecord;
42 | import java.math.BigDecimal;
43 | import java.util.ArrayList;
44 | import java.util.List;
45 | import java.util.function.ObjLongConsumer;
46 | import lombok.extern.slf4j.Slf4j;
47 | import org.agrona.collections.MutableReference;
48 | import org.springframework.beans.factory.annotation.Autowired;
49 | import org.springframework.messaging.simp.SimpMessagingTemplate;
50 | import org.springframework.stereotype.Service;
51 |
52 |
53 | @Service
54 | @Slf4j
55 | public class CommandEventsRouter implements ObjLongConsumer {
56 |
57 | @Autowired
58 | private GatewayState gatewayState;
59 |
60 | @Autowired
61 | private SimpMessagingTemplate simpMessagingTemplate;
62 | //
63 | // @Autowired
64 | // private WebSocketServer webSocketServer;
65 |
66 | public static final String STOMP_TOPIC_TICKS_PREFIX = "/topic/ticks/";
67 | public static final String STOMP_TOPIC_ORDER_PREFIX = "/topic/orders/";
68 |
69 | /**
70 | * TODO put non-latency-critical commands into a queue
71 | *
72 | * @param cmd command placeholder
73 | */
74 | @Override
75 | public void accept(OrderCommand cmd, long seq) {
76 | log.debug("seq={} EVENT CMD: {}", seq, cmd);
77 |
78 | // processData(seq, cmd);
79 |
80 | // final CommandResultCode resultCode = cmd.resultCode;
81 | // final int ticket = cmd.userCookie;
82 | //
83 | //
84 | // if (resp == null) {
85 | // log.error("can not find resp #{}", ticket);
86 | // return;
87 | // }
88 | //
89 | // Object data = (resultCode == CommandResultCode.SUCCESS)
90 | // ? processData(cmd)
91 | // : null;
92 | //
93 | // RestGenericResponse response = RestGenericResponse.builder()
94 | // .ticket(ticket)
95 | // .coreResultCode(resultCode.getCode())
96 | // .data(data)
97 | // .build();
98 | //
99 | // resp.json(response).done();
100 |
101 | // processing events in original order
102 |
103 | // TODO
104 |
105 | if (cmd.command == OrderCommandType.BINARY_DATA_COMMAND || cmd.command == OrderCommandType.BINARY_DATA_QUERY) {
106 | // ignore binary commands further
107 | return;
108 | }
109 |
110 | final GatewaySymbolSpec symbolSpec = gatewayState.getSymbolSpec(cmd.symbol);
111 |
112 | // activate order (dont send update because placing is sync)
113 | if (cmd.command == OrderCommandType.PLACE_ORDER && cmd.resultCode == CommandResultCode.SUCCESS) {
114 | final GatewayUserProfile userProfile = gatewayState.getOrCreateUserProfile(cmd.uid);
115 | userProfile.activateOrder(cmd.orderId);
116 | }
117 |
118 | // update order price
119 | if (cmd.command == OrderCommandType.MOVE_ORDER && cmd.resultCode == CommandResultCode.SUCCESS) {
120 | final GatewayUserProfile userProfile = gatewayState.getOrCreateUserProfile(cmd.uid);
121 | userProfile.updateOrderPrice(
122 | cmd.orderId,
123 | ArithmeticHelper.fromLongPrice(cmd.price, symbolSpec),
124 | order -> sendOrderUpdate(cmd.uid, order));
125 | }
126 |
127 | MatcherTradeEvent firstEvent = cmd.matcherEvent;
128 | if (firstEvent == null) {
129 | return;
130 | }
131 | if (firstEvent.eventType == MatcherEventType.REDUCE) {
132 | if (firstEvent.nextEvent != null) {
133 | throw new IllegalStateException("Only single REDUCE event is expected");
134 | }
135 | final GatewayUserProfile profile = gatewayState.getOrCreateUserProfile(cmd.uid);
136 | profile.cancelOrder(cmd.orderId, order -> sendOrderUpdate(cmd.uid, order));
137 | return;
138 | }
139 |
140 | final MutableReference rejectEvent = new MutableReference<>(null);
141 | List ticks = new ArrayList<>();
142 | cmd.processMatcherEvents(evt -> {
143 | log.debug("INTERNAL EVENT: " + evt);
144 | if (evt.eventType == MatcherEventType.TRADE) {
145 |
146 | // resolve trade price
147 | final BigDecimal tradePrice = ArithmeticHelper.fromLongPrice(evt.price, symbolSpec);
148 |
149 | // update taker's profile
150 | final GatewayUserProfile takerProfile = gatewayState.getOrCreateUserProfile(cmd.uid);
151 | takerProfile.tradeOrder(
152 | cmd.orderId,
153 | evt.size,
154 | tradePrice,
155 | MatchingRole.TAKER,
156 | cmd.timestamp,
157 | evt.matchedOrderId,
158 | evt.matchedOrderUid,
159 | order -> sendOrderUpdate(cmd.uid, order));
160 |
161 | // update maker's profile
162 | final GatewayUserProfile makerProfile = gatewayState.getOrCreateUserProfile(evt.matchedOrderUid);
163 | makerProfile.tradeOrder(
164 | evt.matchedOrderId,
165 | evt.size,
166 | tradePrice,
167 | MatchingRole.MAKER,
168 | cmd.timestamp,
169 | cmd.orderId,
170 | cmd.uid,
171 | order -> sendOrderUpdate(evt.matchedOrderUid, order));
172 |
173 | // todo aggregate ticks having same price
174 | ticks.add(new TickRecord(tradePrice, evt.size, cmd.timestamp, cmd.action));
175 |
176 | } else if (evt.eventType == MatcherEventType.REJECT) {
177 | rejectEvent.set(new IEventsHandler.RejectEvent(
178 | cmd.symbol,
179 | evt.size,
180 | evt.price,
181 | cmd.orderId,
182 | cmd.uid,
183 | cmd.timestamp));
184 | } else if (evt.eventType == MatcherEventType.REDUCE) {
185 | //todo reduce
186 | }
187 | });
188 |
189 | if (rejectEvent.ref != null) {
190 | final GatewayUserProfile profile = gatewayState.getOrCreateUserProfile(cmd.uid);
191 | profile.rejectOrder(rejectEvent, order -> sendOrderUpdate(cmd.uid, order));
192 | }
193 |
194 | if (!ticks.isEmpty()) {
195 | gatewayState.addTicks(symbolSpec.symbolCode, ticks);
196 |
197 | ticks.forEach(tick -> {
198 | final StompApiTick apiTick = new StompApiTick(tick.getPrice(), tick.getSize(), tick.getTimestamp());
199 | simpMessagingTemplate.convertAndSend(STOMP_TOPIC_TICKS_PREFIX + symbolSpec.symbolCode, apiTick);
200 | log.debug("#### Sent tick {} {}", STOMP_TOPIC_TICKS_PREFIX + symbolSpec.symbolCode, apiTick);
201 | // simpMessagingTemplate.convertAndSend("abc", "symbol123");
202 |
203 | });
204 | }
205 |
206 | }
207 |
208 | private void processData(long seq, OrderCommand cmd) {
209 | switch (cmd.command) {
210 |
211 | case PLACE_ORDER:
212 | case MOVE_ORDER:
213 | case CANCEL_ORDER:
214 | handleOrderCommand(cmd);
215 | break;
216 |
217 | case ORDER_BOOK_REQUEST:
218 | handleOrderBookCommand(cmd);
219 | break;
220 |
221 | case BALANCE_ADJUSTMENT:
222 | balanceAdjustment(cmd);
223 | break;
224 |
225 | case ADD_USER:
226 | handleAddUser(cmd);
227 | break;
228 | }
229 | }
230 |
231 | private OrderUpdateEvent handleOrderCommand(OrderCommand cmd) {
232 | List tradeRecords = new ArrayList<>();
233 |
234 | // TODO implement remaining size
235 |
236 | cmd.processMatcherEvents(evt -> {
237 | if (evt.eventType == MatcherEventType.TRADE) {
238 | MatchingRole role = evt.matchedOrderId == cmd.orderId ? MatchingRole.MAKER : MatchingRole.TAKER;
239 | tradeRecords.add(NewTradeRecord.builder().filledSize(evt.size).fillPrice(evt.price).matchingRole(role).build());
240 |
241 | } else if (evt.eventType == MatcherEventType.REDUCE) {
242 |
243 | tradeRecords.add(ReduceRecord.builder().reducedSize(evt.size).build());
244 |
245 | } else if (evt.eventType == MatcherEventType.REJECT) {
246 |
247 | tradeRecords.add(RejectionRecord.builder().rejectedSize(evt.size).build());
248 |
249 | } else {
250 |
251 | throw new UnsupportedOperationException("unknown event type");
252 | }
253 | });
254 |
255 | long activeSize = cmd.size - tradeRecords.stream().mapToLong(OrderSizeChangeRecord::getAffectedSize).sum();
256 | return OrderUpdateEvent.builder().price(cmd.price).orderId(cmd.orderId).activeSize(activeSize).trades(tradeRecords).build();
257 | }
258 |
259 | private UserBalanceAdjustmentAdminEvent balanceAdjustment(OrderCommand cmd) {
260 | UserBalanceAdjustmentAdminEvent apiEvent = UserBalanceAdjustmentAdminEvent.builder()
261 | .uid(cmd.uid)
262 | .transactionId(cmd.orderId)
263 | .amount(cmd.price)
264 | .balance(cmd.size)
265 | .build();
266 | //webSocketServer.broadcast(apiEvent);
267 | return apiEvent;
268 | }
269 |
270 |
271 | private OrderBookEvent handleOrderBookCommand(OrderCommand cmd) {
272 |
273 | if (cmd.marketData == null) {
274 | log.error("No market data object found");
275 | //future.response().code(500).done();
276 | //resp.chunk("{error:FAILED".getBytes());
277 | return null;
278 | }
279 |
280 | log.debug("MARKET DATA: " + cmd.marketData.copy());
281 |
282 | L2MarketData marketData = cmd.marketData;
283 | OrderBookEvent orderBook = new OrderBookEvent(
284 | "UNKNOWN",
285 | marketData.timestamp,
286 | marketData.getAskPricesCopy(),
287 | marketData.getAskVolumesCopy(),
288 | marketData.getBidPricesCopy(),
289 | marketData.getBidVolumesCopy()
290 | );
291 |
292 | //log.debug("req.isAsync()={} req.isDone()={}", req.isAsync(), req.isDone());
293 |
294 | // try {
295 | // Thread.sleep(10000);
296 | // } catch (InterruptedException e) {
297 | // //
298 | // }
299 |
300 | //resp.json(orderBook).done();
301 |
302 | // webSocketServer.broadcast(orderBook);
303 |
304 | return orderBook;
305 | }
306 |
307 | private UserCreatedAdminEvent handleAddUser(OrderCommand cmd) {
308 | UserCreatedAdminEvent apiEvent = UserCreatedAdminEvent.builder().uid(cmd.uid).build();
309 | //webSocketServer.broadcast(apiEvent);
310 | return apiEvent;
311 | }
312 |
313 | private void sendOrderUpdate(long uid, GatewayOrder gatewayOrder) {
314 |
315 | final StompOrderUpdate orderUpdate = StompOrderUpdate.builder()
316 | .uid(uid)
317 | .orderId(gatewayOrder.getOrderId())
318 | .price(gatewayOrder.getPrice())
319 | .size(gatewayOrder.getSize())
320 | .filled(gatewayOrder.getFilled())
321 | .state(gatewayOrder.getState())
322 | .userCookie(gatewayOrder.getUserCookie())
323 | .action(gatewayOrder.getAction())
324 | .orderType(gatewayOrder.getOrderType())
325 | .symbol(gatewayOrder.getSymbol())
326 | .build();
327 |
328 | simpMessagingTemplate.convertAndSend(STOMP_TOPIC_ORDER_PREFIX + "uid/" + uid, orderUpdate);
329 | }
330 | }
331 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/Config.java:
--------------------------------------------------------------------------------
1 | package exchange.core2.rest;
2 |
3 | import exchange.core2.core.ExchangeCore;
4 | import exchange.core2.core.common.config.ExchangeConfiguration;
5 | import exchange.core2.core.common.config.InitialStateConfiguration;
6 | import exchange.core2.core.common.config.LoggingConfiguration;
7 | import exchange.core2.core.common.config.OrdersProcessingConfiguration;
8 | import exchange.core2.core.common.config.PerformanceConfiguration;
9 | import exchange.core2.core.common.config.ReportsQueriesConfiguration;
10 | import exchange.core2.core.common.config.SerializationConfiguration;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.context.annotation.Bean;
13 | import org.springframework.context.annotation.Configuration;
14 |
15 | /**
16 | *
Created by qdd on 2022/5/26.
17 | */
18 | @Configuration
19 | public class Config {
20 |
21 | @Autowired
22 | CommandEventsRouter eventsRouter;
23 |
24 | @Bean
25 | public ExchangeCore exchangeCore() {
26 | final ExchangeConfiguration exchangeConfiguration = ExchangeConfiguration.defaultBuilder()
27 | .initStateCfg(InitialStateConfiguration.CLEAN_TEST)
28 | .performanceCfg(PerformanceConfiguration.baseBuilder().build())
29 | .reportsQueriesCfg(ReportsQueriesConfiguration.createStandardConfig())
30 | .ordersProcessingCfg(OrdersProcessingConfiguration.DEFAULT)
31 | .loggingCfg(LoggingConfiguration.DEFAULT)
32 | .serializationCfg(SerializationConfiguration.DEFAULT)
33 | .build();
34 |
35 | ExchangeCore core = ExchangeCore.builder()
36 | .resultsConsumer(eventsRouter)
37 | .exchangeConfiguration(exchangeConfiguration)
38 | .build();
39 |
40 | core.startup();
41 |
42 | return core;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/GatewayState.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest;
17 |
18 | import exchange.core2.core.ExchangeCore;
19 | import exchange.core2.rest.model.api.TimeFrame;
20 | import exchange.core2.rest.model.internal.*;
21 | import lombok.extern.slf4j.Slf4j;
22 | import org.eclipse.collections.impl.map.mutable.ConcurrentHashMap;
23 | import org.springframework.beans.factory.annotation.Autowired;
24 | import org.springframework.stereotype.Service;
25 |
26 | import javax.annotation.PostConstruct;
27 | import javax.annotation.PreDestroy;
28 | import java.util.List;
29 | import java.util.Map;
30 | import java.util.Optional;
31 | import java.util.concurrent.atomic.AtomicInteger;
32 | import java.util.function.Function;
33 | import java.util.stream.Collectors;
34 |
35 |
36 | // TODO separate interfaces for admin and user
37 | @Service
38 | @Slf4j
39 | public class GatewayState {
40 |
41 | private final AtomicInteger syncRequestsSequence = new AtomicInteger(0);
42 |
43 | // promises cache (TODO can be changed to queue?)
44 |
45 | private final Map symbolsByCode = new ConcurrentHashMap<>();
46 | private final Map symbolsById = new ConcurrentHashMap<>();
47 |
48 | private final Map assetsByCode = new ConcurrentHashMap<>();
49 | private final Map assetsById = new ConcurrentHashMap<>();
50 |
51 | private final Map userProfiles = new ConcurrentHashMap<>();
52 |
53 | private final Map charts = new ConcurrentHashMap<>();
54 |
55 | // @Autowired
56 | // private ExchangeCore exchangeCore;
57 |
58 | public GatewaySymbolSpec getSymbolSpec(String symbolCode) {
59 | return symbolsByCode.get(symbolCode);
60 | }
61 |
62 | public GatewaySymbolSpec getSymbolSpec(int symbolId) {
63 | return symbolsById.get(symbolId);
64 | }
65 |
66 | public boolean registerNewSymbol(GatewaySymbolSpec spec) {
67 | if (symbolsById.putIfAbsent(spec.symbolId, spec) == null) {
68 | symbolsByCode.put(spec.symbolCode, spec);
69 | charts.put(spec.symbolCode, new ChartData());
70 | return true;
71 | }
72 | return false;
73 | }
74 |
75 | public List getActiveAssets(Function mapper) {
76 | return assetsById.values().stream()
77 | .filter(a -> a.active)
78 | .map(mapper)
79 | .collect(Collectors.toList());
80 | }
81 |
82 | public List getActiveSymbols(Function mapper) {
83 | return symbolsById.values().stream()
84 | .filter(s -> s.status == GatewaySymbolSpec.GatewaySymbolLifecycle.ACTIVE)
85 | .map(mapper)
86 | .collect(Collectors.toList());
87 | }
88 |
89 | public boolean registerNewAsset(GatewayAssetSpec spec) {
90 |
91 | // TODO implement validation and lifesycle
92 | if (assetsByCode.putIfAbsent(spec.assetCode, spec) == null) {
93 | assetsById.put(spec.assetId, spec);
94 | return true;
95 | }
96 | return false;
97 | }
98 |
99 | public GatewayAssetSpec getAssetSpec(String assetCode) {
100 | return assetsByCode.get(assetCode);
101 | }
102 |
103 | public GatewayAssetSpec getAssetSpec(int assetId) {
104 | return assetsById.get(assetId);
105 | }
106 |
107 | public GatewaySymbolSpec activateSymbol(final int symbolId) {
108 |
109 | final GatewaySymbolSpec newSpec = symbolsById.compute(symbolId, (k, v) ->
110 | (v != null && v.status == GatewaySymbolSpec.GatewaySymbolLifecycle.NEW)
111 | ? v.withStatus(GatewaySymbolSpec.GatewaySymbolLifecycle.ACTIVE)
112 | : null);
113 |
114 | if (newSpec != null) {
115 | symbolsByCode.put(newSpec.symbolCode, newSpec);
116 | }
117 |
118 | return newSpec;
119 | }
120 |
121 | public Optional getUserProfile(long uid) {
122 | return Optional.ofNullable(userProfiles.get(uid));
123 | }
124 |
125 | public GatewayUserProfile getOrCreateUserProfile(long uid) {
126 | return userProfiles.computeIfAbsent(uid, k -> new GatewayUserProfile());
127 | }
128 |
129 | public void addTicks(String symbol, List records) {
130 | charts.compute(symbol, (s, chart) -> chart == null ? new ChartData() : chart).addTicks(records);
131 | }
132 |
133 | public Optional> getBars(String symbolCode, int barsNum, TimeFrame timeFrame) {
134 | return Optional.ofNullable(charts.get(symbolCode)).map(chartData -> chartData.getBarsData(barsNum, timeFrame));
135 | }
136 | //
137 | // @PostConstruct
138 | // public void start() {
139 | // log.debug("START1");
140 | // exchangeCore.startup();
141 | // }
142 | //
143 | // @PreDestroy
144 | // public void stop() {
145 | // log.debug("STOP1");
146 | // exchangeCore.shutdown();
147 | // }
148 |
149 | }
150 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/RestGatewayApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest;
17 |
18 | import org.springframework.boot.SpringApplication;
19 | import org.springframework.boot.autoconfigure.SpringBootApplication;
20 |
21 |
22 | @SpringBootApplication
23 | public class RestGatewayApplication {
24 | public static void main(String[] args) {
25 | SpringApplication.run(RestGatewayApplication.class, args);
26 | }
27 |
28 |
29 | // @Bean
30 | // public Consumer resultsConsumer() {
31 | // return cmd -> {
32 | // System.out.println(">>>" + cmd);
33 | // };
34 | // }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/WebSocketConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest;
17 |
18 | import org.springframework.context.annotation.Configuration;
19 | import org.springframework.messaging.simp.config.MessageBrokerRegistry;
20 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
21 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
22 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
23 |
24 | @Configuration
25 | @EnableWebSocketMessageBroker
26 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
27 |
28 | @Override
29 | public void configureMessageBroker(MessageBrokerRegistry config) {
30 | config.enableSimpleBroker("/topic");
31 | config.setApplicationDestinationPrefixes("/app");
32 | }
33 |
34 | @Override
35 | public void registerStompEndpoints(StompEndpointRegistry registry) {
36 | registry.addEndpoint("/ticks-websocket").setAllowedOrigins("*").withSockJS();
37 | }
38 |
39 | }
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/ApiErrorCodes.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands;
17 |
18 | import lombok.AllArgsConstructor;
19 |
20 | @AllArgsConstructor
21 | public enum ApiErrorCodes {
22 |
23 | SYMBOL_ALREADY_EXISTS(1000, 400, "symbol already exists"),
24 | UNKNOWN_BASE_ASSET(1001, 400, "unknown base asset"),
25 | UNKNOWN_QUOTE_CURRENCY(1002, 400, "unknown quote currency"),
26 | ASSET_ALREADY_EXISTS(1003, 400, "asset already exists"),
27 | UNKNOWN_CURRENCY(1004, 400, "unknown currency"),
28 | PRECISION_IS_TOO_HIGH(1005, 400, "precision is too high, reduce precision"),
29 | UNKNOWN_SYMBOL(1006, 400, "unknown symbol"),
30 | UNKNOWN_SYMBOL_404(1007, 404, "symbol not found"),
31 |
32 | INVALID_CONFIGURATION(1008, 400, "invalid configuration: %s"),
33 |
34 | INVALID_PRICE(1009, 400, "invalid price"),
35 | UNKNOWN_USER_404(1010, 404, "unknown user"),
36 | ;
37 |
38 | public final int gatewayErrorCode;
39 | public final int httpStatus;
40 | public final String errorDescription;
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/HelloMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands;
17 |
18 |
19 | public class HelloMessage {
20 |
21 | private String name;
22 |
23 | public HelloMessage() {
24 | }
25 |
26 | public HelloMessage(String name) {
27 | this.name = name;
28 | }
29 |
30 | public String getName() {
31 | return name;
32 | }
33 |
34 | public void setName(String name) {
35 | this.name = name;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/RestApiCancelOrder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 | import lombok.Getter;
22 |
23 | @Getter
24 | public final class RestApiCancelOrder {
25 |
26 | private final long orderId;
27 |
28 | private final String symbol;
29 |
30 | // TODO remove
31 | private final long uid;
32 |
33 | @JsonCreator
34 | public RestApiCancelOrder(
35 | @JsonProperty("orderId") long orderId,
36 | @JsonProperty("symbol") String symbol,
37 | @JsonProperty("uid") long uid) {
38 |
39 | this.orderId = orderId;
40 | this.symbol = symbol;
41 | this.uid = uid;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | return "[CANCEL " + orderId + "]";
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/RestApiMoveOrder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 | import lombok.Getter;
22 |
23 | import java.math.BigDecimal;
24 |
25 | @Getter
26 | public final class RestApiMoveOrder {
27 |
28 | private final BigDecimal price;
29 |
30 | @JsonCreator
31 | public RestApiMoveOrder(
32 | @JsonProperty("price") BigDecimal price) {
33 |
34 | this.price = price;
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return "[MOVE " + price + "]";
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/RestApiPlaceOrder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 | import exchange.core2.core.common.OrderAction;
22 | import exchange.core2.core.common.OrderType;
23 | import lombok.Getter;
24 |
25 | import java.math.BigDecimal;
26 |
27 | @Getter
28 | public final class RestApiPlaceOrder {
29 |
30 | private final BigDecimal price;
31 | private final long size; // only integer sizes allowed
32 |
33 | private final int userCookie;
34 | private final OrderAction action;
35 | private final OrderType orderType;
36 |
37 | @JsonCreator
38 | public RestApiPlaceOrder(
39 | @JsonProperty("price") BigDecimal price,
40 | @JsonProperty("size") long size,
41 | @JsonProperty("userCookie") int userCookie,
42 | @JsonProperty("action") OrderAction action,
43 | @JsonProperty("orderType") OrderType orderType) {
44 |
45 | this.price = price;
46 | this.size = size;
47 | this.userCookie = userCookie;
48 | this.action = action;
49 | this.orderType = orderType;
50 | }
51 |
52 | @Override
53 | public String toString() {
54 | return "[ADD " + (action == OrderAction.ASK ? 'A' : 'B') + orderType
55 | + price + ":" + size + "]";
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/admin/RestApiAccountBalanceAdjustment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands.admin;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 | import lombok.Getter;
22 |
23 | import java.math.BigDecimal;
24 |
25 | @Getter
26 | public final class RestApiAccountBalanceAdjustment {
27 |
28 | //public final long uid;
29 | public final long transactionId;
30 | public final BigDecimal amount;
31 | public final String currency;
32 |
33 | @JsonCreator
34 | public RestApiAccountBalanceAdjustment(
35 | //@JsonProperty("uid") long uid,
36 | @JsonProperty("transactionId") long transactionId,
37 | @JsonProperty("amount") BigDecimal amount,
38 | @JsonProperty("currency") String currency) {
39 |
40 | //this.uid = uid;
41 | this.transactionId = transactionId;
42 | this.amount = amount;
43 | this.currency = currency;
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | return "[BALANCE_ADJ " + amount + " " + currency + " transactionId:" + transactionId + "]";
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/admin/RestApiAddSymbol.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands.admin;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 | import exchange.core2.core.common.SymbolType;
22 | import lombok.Builder;
23 |
24 | import java.math.BigDecimal;
25 |
26 | public final class RestApiAddSymbol {
27 |
28 | public final int symbolId;
29 | public final String symbolCode;
30 |
31 | public final SymbolType symbolType;
32 |
33 | public final String baseAsset; // base asset
34 | public final String quoteCurrency; // quote/counter currency (OR futures contract currency)
35 | public final BigDecimal lotSize; // lot size in base asset units
36 | public final BigDecimal stepSize; // step size in quote currency units
37 |
38 | public final BigDecimal takerFee; // TODO check invariant: taker fee is not less than maker fee
39 | public final BigDecimal makerFee;
40 |
41 | public final BigDecimal marginBuy;
42 | public final BigDecimal marginSell;
43 |
44 | public final BigDecimal priceHighLimit;
45 | public final BigDecimal priceLowLimit;
46 |
47 | @JsonCreator
48 | @Builder
49 | public RestApiAddSymbol(
50 | @JsonProperty("symbolCode") String symbolCode,
51 | @JsonProperty("symbolId") int symbolId,
52 | @JsonProperty("symbolType") SymbolType symbolType,
53 | @JsonProperty("baseAsset") String baseAsset,
54 | @JsonProperty("quoteCurrency") String quoteCurrency,
55 | @JsonProperty("lotSize") BigDecimal lotSize,
56 | @JsonProperty("stepSize") BigDecimal stepSize,
57 | @JsonProperty("takerFee") BigDecimal takerFee,
58 | @JsonProperty("makerFee") BigDecimal makerFee,
59 | @JsonProperty("marginBuy") BigDecimal marginBuy,
60 | @JsonProperty("marginSell") BigDecimal marginSell,
61 | @JsonProperty("priceHighLimit") BigDecimal priceHighLimit,
62 | @JsonProperty("priceLowLimit") BigDecimal priceLowLimit) {
63 |
64 | this.symbolCode = symbolCode;
65 | this.symbolId = symbolId;
66 |
67 | this.symbolType = symbolType;
68 |
69 | this.baseAsset = baseAsset;
70 | this.quoteCurrency = quoteCurrency;
71 | this.lotSize = lotSize;
72 | this.stepSize = stepSize;
73 | this.takerFee = takerFee;
74 | this.makerFee = makerFee;
75 |
76 | this.marginBuy = marginBuy;
77 | this.marginSell = marginSell;
78 | this.priceHighLimit = priceHighLimit;
79 | this.priceLowLimit = priceLowLimit;
80 | }
81 |
82 | @Override
83 | public String toString() {
84 | return "[ADDSYMBOL " + symbolCode + " " + symbolId + "]";
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/admin/RestApiAddUser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands.admin;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 | import lombok.Getter;
22 |
23 | @Getter
24 | public final class RestApiAddUser {
25 |
26 | private final long uid;
27 |
28 | @JsonCreator
29 | public RestApiAddUser(@JsonProperty("uid") long uid) {
30 |
31 | this.uid = uid;
32 | }
33 |
34 | @Override
35 | public String toString() {
36 | return "[ADDUSER " + uid + "]";
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/admin/RestApiAdminAsset.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands.admin;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 |
22 | public final class RestApiAdminAsset {
23 |
24 | public final String assetCode;
25 | public final int assetId;
26 | public final int scale; // asset scale - 2 for most currencies, 8 for BTC, 0 for JPY, etc
27 |
28 | @JsonCreator
29 | public RestApiAdminAsset(
30 | @JsonProperty("assetCode") String assetCode,
31 | @JsonProperty("assetId") int assetId,
32 | @JsonProperty("scale") int scale) {
33 |
34 | this.assetCode = assetCode;
35 | this.assetId = assetId;
36 | this.scale = scale;
37 | }
38 |
39 | @Override
40 | public String toString() {
41 | return "[ASSET " + assetCode + " " + assetId + "]";
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/admin/RestApiRequestMarketData.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands.admin;
17 |
18 |
19 | import com.fasterxml.jackson.annotation.JsonCreator;
20 | import com.fasterxml.jackson.annotation.JsonProperty;
21 | import lombok.Getter;
22 |
23 | @Getter
24 | public final class RestApiRequestMarketData {
25 |
26 | private final String symbolName;
27 |
28 | @JsonCreator
29 | public RestApiRequestMarketData(@JsonProperty("symbolName") String symbolName) {
30 |
31 | this.symbolName = symbolName;
32 | }
33 |
34 | @Override
35 | public String toString() {
36 | return "[REQ_MARKET_DATA " + symbolName + "]";
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/admin/StompApiNotificationMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands.admin;
17 |
18 | public class StompApiNotificationMessage {
19 |
20 | private String content;
21 |
22 | public StompApiNotificationMessage() {
23 | }
24 |
25 | public StompApiNotificationMessage(String content) {
26 | this.content = content;
27 | }
28 |
29 | public String getContent() {
30 | return content;
31 | }
32 |
33 | }
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/commands/util/ArithmeticHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.commands.util;
17 |
18 | import lombok.extern.slf4j.Slf4j;
19 | import exchange.core2.rest.model.internal.GatewayAssetSpec;
20 | import exchange.core2.rest.model.internal.GatewaySymbolSpec;
21 |
22 | import java.math.BigDecimal;
23 |
24 | @Slf4j
25 | public class ArithmeticHelper {
26 |
27 | /**
28 | * Convert price for one lot (order book price) from core long to BigDecimal.
29 | *
30 | * @param price core price
31 | * @param symbolSpec gateway symbol spec
32 | * @return big decimal value
33 | */
34 | public static BigDecimal fromLongPrice(long price, GatewaySymbolSpec symbolSpec) {
35 |
36 | //log.debug("symbolSpec.quoteCurrency.scale={}",symbolSpec.quoteCurrency.scale);
37 | //log.debug("symbolSpec.stepSize={}",symbolSpec.stepSize);
38 | //BigDecimal res = BigDecimal.valueOf(price).scaleByPowerOfTen(symbolSpec.quoteCurrency.scale).multiply(symbolSpec.stepSize);
39 | BigDecimal res = BigDecimal.valueOf(price).scaleByPowerOfTen(-symbolSpec.quoteCurrency.scale);
40 | //log.debug("res={}",res);
41 | return res;
42 | }
43 |
44 | public static BigDecimal fromLongPrice(long price, GatewayAssetSpec assetSpecSpec) {
45 | return BigDecimal.valueOf(price).scaleByPowerOfTen(-assetSpecSpec.scale);
46 | }
47 |
48 | public static BigDecimal toBaseUnits(BigDecimal price, GatewayAssetSpec assetSpec) {
49 | return price.scaleByPowerOfTen(assetSpec.scale);
50 | }
51 |
52 | /**
53 | * Check if BigDecimal is integer value and >=0
54 | *
55 | * @param value - value to examine
56 | * @return tre if it is integer and not negative
57 | */
58 | public static boolean isIntegerNotNegativeValue(BigDecimal value) {
59 | //log.debug("value={} scale()={}", value, value.stripTrailingZeros().scale());
60 | return value.compareTo(BigDecimal.ZERO) >= 0 && value.stripTrailingZeros().scale() <= 0;
61 | }
62 |
63 | /**
64 | * Check if BigDecimal is integer value and >0
65 | *
66 | * @param value - value to examine
67 | * @return tre if it is integer and positive
68 | */
69 | public static boolean isIntegerPositiveNotZeroValue(BigDecimal value) {
70 | //log.debug("value={} scale()={}", value, value.stripTrailingZeros().scale());
71 | return value.compareTo(BigDecimal.ZERO) > 0 && value.stripTrailingZeros().scale() <= 0;
72 | }
73 |
74 | public static boolean isZero(BigDecimal value) {
75 | return value.compareTo(BigDecimal.ZERO) == 0;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/controllers/GreetingController.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.controllers;
17 |
18 |
19 | import exchange.core2.rest.commands.HelloMessage;
20 | import exchange.core2.rest.commands.admin.StompApiNotificationMessage;
21 | import exchange.core2.rest.model.api.StompApiTick;
22 | import lombok.extern.slf4j.Slf4j;
23 | import org.springframework.beans.factory.annotation.Autowired;
24 | import org.springframework.messaging.handler.annotation.MessageMapping;
25 | import org.springframework.messaging.handler.annotation.SendTo;
26 | import org.springframework.messaging.simp.SimpMessagingTemplate;
27 | import org.springframework.stereotype.Controller;
28 | import org.springframework.web.util.HtmlUtils;
29 |
30 | import javax.annotation.PostConstruct;
31 | import java.math.BigDecimal;
32 | import java.time.Instant;
33 | import java.util.Random;
34 | import java.util.concurrent.CompletableFuture;
35 | import java.util.concurrent.ThreadLocalRandom;
36 |
37 | @Slf4j
38 | @Controller
39 | public class GreetingController {
40 |
41 | @Autowired
42 | private SimpMessagingTemplate simpMessagingTemplate;
43 |
44 | @MessageMapping("/hello")
45 | @SendTo("/topic/notifications")
46 | public StompApiNotificationMessage greeting(HelloMessage message) throws Exception {
47 | log.debug("Greeting 1 {}", message);
48 | Thread.sleep(200); // simulated delay
49 | log.debug("Greeting 2 {}", message);
50 | return new StompApiNotificationMessage("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
51 | }
52 |
53 | // @PostConstruct
54 | // public void start() {
55 | // CompletableFuture.supplyAsync(() -> {
56 | //
57 | // while (true) {
58 | // try {
59 | // Thread.sleep(2000);
60 | // } catch (InterruptedException e) {
61 | // e.printStackTrace();
62 | // }
63 | // log.debug("Sending heartbit...");
64 | // simpMessagingTemplate.convertAndSend("/topic/notifications", new StompApiNotificationMessage(Instant.now().toString()));
65 | //
66 | // Random rnd = ThreadLocalRandom.current();
67 | // simpMessagingTemplate.convertAndSend(
68 | // "/topic/ticks/XBTCUSDT",
69 | // new StompApiTick(BigDecimal.valueOf(rnd.nextFloat()), rnd.nextInt(100), System.currentTimeMillis()));
70 | // }
71 | //
72 | // });
73 | //
74 | // }
75 |
76 | }
--------------------------------------------------------------------------------
/src/main/java/exchange/core2/rest/controllers/RestControllerHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Maksim Zheravin
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package exchange.core2.rest.controllers;
17 |
18 | import lombok.extern.slf4j.Slf4j;
19 | import exchange.core2.core.common.cmd.CommandResultCode;
20 | import exchange.core2.core.common.cmd.OrderCommand;
21 | import exchange.core2.rest.commands.ApiErrorCodes;
22 | import exchange.core2.rest.events.RestGenericResponse;
23 | import org.springframework.http.HttpStatus;
24 | import org.springframework.http.ResponseEntity;
25 |
26 | import java.util.function.Supplier;
27 |
28 | @Slf4j
29 | public class RestControllerHelper {
30 |
31 | public static ResponseEntity errorResponse(ApiErrorCodes errMessage, String... args) {
32 |
33 | RestGenericResponse