-
Notifications
You must be signed in to change notification settings - Fork 7
/
strategy.rs
295 lines (262 loc) · 9.08 KB
/
strategy.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
use geger::common::log::setup_log;
use geger::core::actions_context::ActionsContext;
use geger::core::engine::Engine;
use geger::core::event_loop::Actor;
use geger::core::events::Event;
use geger::core::gateway_router::{CancelOrderRequest, NewOrderRequest};
use geger::core::market_data::{MarketDataEvent, Quote};
use geger::core::message_bus::{
CrossbeamMessageSender, Message, MessageHandler, MessageSender, SimpleMessage, Topic,
};
use geger::core::types::{Exchange, OrderStatus, OrderType, Side, Symbol, TimeInForce, Timestamp};
use geger::sim::broker::SimBrokerConfig;
use geger::sim::environment::SimulatedTradingMarketDataProvider;
use log::{debug, error, warn, LevelFilter};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::sync::{Arc, Mutex};
const SIM_BROKER_EXCHANGE: &str = "test_exchange";
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QuoteDef {
#[serde(rename(deserialize = "s"))]
pub symbol: Symbol,
#[serde(default)]
pub exchange: Exchange,
#[serde(rename(deserialize = "b"))]
pub bid: f64,
#[serde(rename(deserialize = "a"))]
pub ask: f64,
#[serde(rename(deserialize = "bs"))]
pub bid_size: Option<f64>,
#[serde(rename(deserialize = "as"))]
pub ask_size: Option<f64>,
#[serde(rename(deserialize = "e"))]
pub exchange_timestamp: f64,
#[serde(rename(deserialize = "r"))]
pub received_timestamp: f64,
}
impl From<QuoteDef> for Quote {
fn from(def: QuoteDef) -> Quote {
let QuoteDef {
symbol,
exchange: _,
bid,
ask,
bid_size,
ask_size,
exchange_timestamp,
received_timestamp,
} = def;
Quote {
event_id: None,
symbol,
exchange: SIM_BROKER_EXCHANGE.to_string(),
bid,
ask,
bid_size,
ask_size,
exchange_timestamp: (exchange_timestamp * 1_000.0) as u64,
received_timestamp: (received_timestamp * 1_000.0) as u64,
}
}
}
struct FileMarketDataProvider {
files: Vec<String>,
events_buffer: Vec<QuoteDef>,
directory: String,
idx: usize,
file_idx: usize,
last_ts: u64,
}
impl FileMarketDataProvider {
fn new(directory: &str) -> Self {
let mut files = vec![];
let paths = fs::read_dir(directory).unwrap();
for path in paths {
let dir_entry = path.as_ref().unwrap();
if dir_entry.file_type().unwrap().is_file() {
files.push(dir_entry.file_name().into_string().unwrap());
}
}
files.sort();
let events_buffer = vec![];
Self {
files,
events_buffer,
directory: directory.to_string(),
idx: 0,
file_idx: 0,
last_ts: 0,
}
}
fn read_events_to_buffer(&mut self) -> Result<(), String> {
self.events_buffer = vec![];
self.idx = 0;
if self.files.len() == self.file_idx + 1 {
return Err("no market data event".to_string());
}
let file_name = &self.files[self.file_idx];
let file_path = format!("{}/{}", &self.directory, file_name);
let contents = fs::read(file_path.clone()).unwrap();
println!("content {} loaded", &file_path);
self.file_idx += 1;
let quotes = match rmp_serde::from_read_ref::<_, Vec<QuoteDef>>(&contents) {
Ok(v) => v,
Err(e) => {
let err_msg = format!("failed deserialize quote {:?}", e);
error!("{}", &err_msg);
return Err(err_msg);
}
};
self.events_buffer = quotes;
Ok(())
}
}
impl SimulatedTradingMarketDataProvider for FileMarketDataProvider {
fn next_event(&mut self) -> Option<MarketDataEvent> {
let quote = match self.events_buffer.get(self.idx) {
Some(val) => val,
None => {
if let Err(err) = self.read_events_to_buffer() {
debug!("failed to read events: {}", err);
return None;
}
match self.events_buffer.get(self.idx) {
Some(val) => val,
None => return None,
}
}
};
let event = MarketDataEvent::NewQuote((*quote).clone().into());
if event.exchange_timestamp() < self.last_ts {
panic!("incorrect sequence of events")
};
self.idx += 1;
self.last_ts = event.exchange_timestamp();
Some(event)
}
}
#[derive(Debug)]
struct SampleStrategy {
has_open_order: bool,
last_ts: Timestamp,
seen_events: Vec<Event>,
}
impl SampleStrategy {
fn new() -> Self {
Self {
has_open_order: false,
last_ts: 0,
seen_events: vec![],
}
}
fn on_quote<M: Message, MS: MessageSender<M>>(
&mut self,
quote: &Quote,
actions_context: &mut ActionsContext<M, MS>,
) {
if !self.has_open_order {
let request = NewOrderRequest {
request_id: "".to_string(),
client_order_id: "1".to_string(),
exchange: SIM_BROKER_EXCHANGE.to_string(),
r#type: OrderType::LIMIT,
time_in_force: TimeInForce::GTC,
price: Some(quote.ask),
trigger_price: None,
symbol: quote.symbol.clone(),
quantity: 1.0,
side: Side::BUY,
creation_ts: quote.received_timestamp,
};
debug!("new order request: {:?}", &request);
if let Err(err) = actions_context.send_order(request) {
panic!("{:?}", err)
};
self.has_open_order = true
}
}
}
impl<MS: MessageSender<SimpleMessage>> Actor<SimpleMessage, MS> for SampleStrategy {
fn on_event(&mut self, event: &Event, actions_context: &mut ActionsContext<SimpleMessage, MS>) {
if event.timestamp() < self.last_ts {
panic!(
"timestamp sequence is broken. event: {:#?} seen_events: {:#?}",
event, self.seen_events
)
}
self.seen_events.push((*event).clone());
self.last_ts = event.timestamp();
match event {
Event::NewQuote(quote) => self.on_quote(quote, actions_context),
Event::UDSOrderUpdate(msg) => match msg.order_status {
OrderStatus::NEW => {
let request = CancelOrderRequest {
request_id: "".to_string(),
client_order_id: msg.client_order_id.as_ref().unwrap().clone(),
exchange_order_id: msg.exchange_order_id.as_ref().unwrap().clone(),
exchange: msg.exchange.clone(),
symbol: msg.symbol.clone(),
creation_ts: msg.exchange_timestamp,
};
debug!("new cancel request: {:?}", &request);
actions_context
.send_message(SimpleMessage::new(
Some("UDS".to_string()),
format!("{:?}", msg),
))
.unwrap();
actions_context.cancel_order(request).unwrap();
}
OrderStatus::CANCELED => {
self.has_open_order = false;
}
_ => {}
},
_ => {}
}
}
}
#[derive(Debug)]
enum MyActors {
Strategy(SampleStrategy),
}
impl<MS: MessageSender<SimpleMessage>> Actor<SimpleMessage, MS> for MyActors {
fn on_event(&mut self, event: &Event, actions_context: &mut ActionsContext<SimpleMessage, MS>) {
match self {
MyActors::Strategy(s) => s.on_event(event, actions_context),
}
}
}
impl MessageHandler<SimpleMessage, CrossbeamMessageSender<SimpleMessage>> for MyActors {
fn on_new_message(
&mut self,
message: &SimpleMessage,
_actions_context: &ActionsContext<SimpleMessage, CrossbeamMessageSender<SimpleMessage>>,
) {
warn!("received new message: {:?}", message)
}
fn get_topics(&self) -> Vec<Topic> {
return vec![];
}
}
fn main() {
if let Err(err) = setup_log(Some(LevelFilter::Debug), None) {
panic!("{:?}", err)
}
let md_provider = FileMarketDataProvider::new("data/examples/strategy");
let mut engine = Engine::new();
let mut sim_broker_configs = HashMap::new();
sim_broker_configs.insert(SIM_BROKER_EXCHANGE.to_string(), SimBrokerConfig::default());
let strategy = Arc::new(Mutex::new(MyActors::Strategy(SampleStrategy::new())));
engine.add_actor(strategy.clone());
engine.add_message_handler(strategy.clone());
engine.add_exchange(SIM_BROKER_EXCHANGE.to_string());
let execution_info = engine
.execute_with_sim_environment(md_provider, None, sim_broker_configs, true)
.unwrap();
for th in execution_info.threads {
th.unwrap().join().unwrap()
}
}