CBOE Emulator  1.0
mean_reversion.hpp
1 // A mean reversion trading strategy.
2 // Copyright 2020 Christian Kauten
3 //
4 // Author: Christian Kauten (kautenja@auburn.edu)
5 //
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16 //
17 // Reference: High frequency trading strategies, market fragility and price
18 // spikes: an agent based model perspective
19 // Reference: TODO
20 //
21 
22 #ifndef STRATEGIES_MEAN_REVERSION_HPP
23 #define STRATEGIES_MEAN_REVERSION_HPP
24 
25 #include "data_feed/receiver.hpp"
26 #include "order_entry/client.hpp"
27 #include "maths/probability.hpp"
28 #include "maths/exponential_moving_variance.hpp"
29 #include <nlohmann/json.hpp>
30 #include <atomic>
31 #include <iostream>
32 
34 namespace Strategies {
35 
42  private:
46  DataFeedReceiver receiver;
48  OrderEntry::Client client;
50  asio::steady_timer timer;
52  uint32_t sleep_time;
54  float P_act;
56  std::atomic<bool> is_running;
57 
61  double deviations;
64 
66  inline void start_strategy() {
67  timer.expires_after(std::chrono::milliseconds(sleep_time));
68  timer.async_wait([this](const std::error_code& error) {
69  if (error) { // TODO: handle error code
70  std::cout << "MeanReversion::start_strategy - " << error << std::endl;
71  return;
72  }
73  if (Maths::Probability::boolean(P_act)) do_strategy();
74  start_strategy();
75  });
76  }
77 
79  void do_strategy() {
80  if (client.has_active_order()) // cancel existing orders
82  // update the exponential moving variance
83  auto change = midpoint.process(receiver.get_book().last_price());
84  // calculate the decision boundary
85  double decision_boundary = deviations * midpoint.get_stddev();
86  // place an order (take a position)
87  if (change >= decision_boundary) { // price increasing
88  // take a short position, i.e., sell
89  auto best_sell = receiver.get_book().last_best_sell();
90  // check for underflow
91  if (best_sell <= std::numeric_limits<OrderEntry::Price>::min() + 1) return;
92  // decrement the price
93  auto price = best_sell - 1;
94  // send the limit order
95  client.send<OrderEntry::Messages::OrderRequest>(price, size, OrderEntry::Side::Sell);
96  }
97  else if (change <= -decision_boundary) { // price decreasing
98  // take a long position, i.e., buy
99  auto best_buy = receiver.get_book().last_best_buy();
100  // check for overflow
101  if (best_buy >= std::numeric_limits<OrderEntry::Price>::max() - 1) return;
102  // increment the price
103  auto price = best_buy + 1;
104  // send the order
105  client.send<OrderEntry::Messages::OrderRequest>(price, size, OrderEntry::Side::Buy);
106  }
107  }
108 
109  public:
117  asio::io_context& feed_context,
118  asio::io_context& context,
119  nlohmann::json options
120  ) :
121  receiver(
122  feed_context,
123  asio::ip::make_address(options["data_feed"]["listen"].get<std::string>()),
124  asio::ip::make_address(options["data_feed"]["group"].get<std::string>()),
125  options["data_feed"]["port"].get<uint16_t>(),
126  *this
127  ),
128  client(
129  context,
130  options["order_entry"]["host"].get<std::string>(),
131  std::to_string(options["order_entry"]["port"].get<uint16_t>())
132  ),
133  timer(context),
134  sleep_time(options["strategy"]["sleep_time"].get<uint32_t>()),
135  P_act(options["strategy"]["P_act"].get<double>()),
136  is_running(false),
137  size(options["strategy"]["size"].get<OrderEntry::Quantity>()),
138  deviations(options["strategy"]["deviations"].get<double>()),
139  midpoint(options["strategy"]["weight"].get<double>(), options["strategy"]["average"].get<double>()) {
140  // login to the order entry client
141  auto username = OrderEntry::make_username(options["order_entry"]["username"].get<std::string>());
142  auto password = OrderEntry::make_password(options["order_entry"]["password"].get<std::string>());
143  client.send<OrderEntry::Messages::LoginRequest>(username, password);
144  }
145 
151  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::StartOfSession& message) {
152  if (is_running) {
153  std::cerr << "received start of session when already running" << std::endl;
154  return;
155  }
156  // start the strategy
157  start_strategy();
158  // set the running flag to true
159  is_running = true;
160  }
161 
167  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::EndOfSession& message) {
168  if (not is_running) {
169  std::cerr << "received end of session when not running" << std::endl;
170  return;
171  }
172  // stop the strategy
173  timer.cancel();
174  is_running = false;
175  }
176 
182  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::Clear& message) { }
183 
189  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::AddOrder& message) { }
190 
196  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::DeleteOrder& message) { }
197 
203  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::Trade& message) { }
204 };
205 
206 } // namespace Strategies
207 
208 #endif // STRATEGIES_MEAN_REVERSION_HPP
OrderEntry
Logic for sending/receiving application messages in a financial market.
Definition: authorizer.hpp:26
DataFeed::LOB::LimitOrderBook::last_price
Price last_price() const
Return the current price of the asset using last prices.
Definition: limit_order_book.hpp:283
Maths::ExponentialMovingVariance::get_stddev
T get_stddev() const
Return the current value of the exponential moving standard deviation .
Definition: exponential_moving_variance.hpp:139
DataFeed::Receiver< MeanReversion >
OrderEntry::Messages::LoginRequest
A request that indicates a client is attempting to create a new session.
Definition: messages.hpp:248
OrderEntry::make_password
Password make_password(std::string password)
Make a password from the given input string.
Definition: messages.hpp:62
DataFeed::Messages::Trade
A message that indicates a market order matches with a limit order.
Definition: messages.hpp:387
OrderEntry::Client::has_active_order
bool has_active_order() const
Return true if the client has an active order.
Definition: client.hpp:267
OrderEntry::Client::send
void send(Args &&...args)
Write a message asynchronously (non-blocking).
Definition: client.hpp:299
Maths::ExponentialMovingVariance< double >
DataFeed::LOB::LimitOrderBook::last_best_sell
Price last_best_sell() const
Return the last best sell price.
Definition: limit_order_book.hpp:262
DataFeed::Messages::DeleteOrder
A message that indicates a limit order was added to the book.
Definition: messages.hpp:332
OrderEntry::Messages::OrderRequest
A request to place a new limit / market order in the book.
Definition: messages.hpp:502
DataFeed::Receiver::get_book
const LOB::LimitOrderBook & get_book()
Return the limit order book for this receiver.
Definition: receiver.hpp:214
Strategies::MeanReversion::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::StartOfSession &message)
Handle a start of session message.
Definition: mean_reversion.hpp:151
DataFeed::Messages::EndOfSession
A message that indicates the end of a trading session.
Definition: messages.hpp:506
DataFeed::Messages::Clear
A message that indicates to clear all orders in the order book.
Definition: messages.hpp:213
Maths::Probability::boolean
bool boolean()
Return the result of a coin toss.
Definition: probability.hpp:105
Strategies::MeanReversion::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::Clear &message)
Handle a clear book message.
Definition: mean_reversion.hpp:182
DataFeed::Messages::StartOfSession
A message that indicates the start of a trading session.
Definition: messages.hpp:460
Strategies::MeanReversion::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::EndOfSession &message)
Handle an end of session message.
Definition: mean_reversion.hpp:167
DataFeed::LOB::LimitOrderBook::last_best_buy
Price last_best_buy() const
Return the last best buy price.
Definition: limit_order_book.hpp:268
OrderEntry::Client
A client for interacting with the direct market access server.
Definition: client.hpp:42
OrderEntry::Messages::PurgeRequest
A request to cancel all active orders in the book.
Definition: messages.hpp:917
OrderEntry::make_username
Username make_username(std::string username)
Make a username from the given input string.
Definition: messages.hpp:46
OrderEntry::Quantity
uint32_t Quantity
A type for order quantities.
Definition: messages.hpp:133
Maths::ExponentialMovingVariance::process
T process(T observation)
Calculate the next average and variance based on observation .
Definition: exponential_moving_variance.hpp:113
Strategies::MeanReversion::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::Trade &message)
Handle a trade message.
Definition: mean_reversion.hpp:203
Strategies::MeanReversion::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::DeleteOrder &message)
Handle a delete order message.
Definition: mean_reversion.hpp:196
Strategies
Direct market access trading strategies.
Definition: iceberg_liquidity_consumer.hpp:33
DataFeed::Messages::AddOrder
A message that indicates a limit order was added to the book.
Definition: messages.hpp:259
Strategies::MeanReversion::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::AddOrder &message)
Handle an add order message.
Definition: mean_reversion.hpp:189
Strategies::MeanReversion
The mean reversion trader strategy logic.
Definition: mean_reversion.hpp:41
Strategies::MeanReversion::MeanReversion
MeanReversion(asio::io_context &feed_context, asio::io_context &context, nlohmann::json options)
Initialize the strategy.
Definition: mean_reversion.hpp:116