CBOE Emulator  1.0
liquidity_consumer.hpp
1 // A liquidity consumer 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: An Agent-Based Model for Market Impact
20 //
21 
22 #ifndef STRATEGIES_LIQUIDITY_CONSUMER_HPP
23 #define STRATEGIES_LIQUIDITY_CONSUMER_HPP
24 
25 #include "data_feed/receiver.hpp"
26 #include "order_entry/client.hpp"
27 #include "maths/probability.hpp"
28 #include <nlohmann/json.hpp>
29 #include <atomic>
30 #include <iostream>
31 
33 namespace Strategies {
34 
41  private:
45  DataFeedReceiver receiver;
47  OrderEntry::Client client;
49  asio::steady_timer timer;
51  uint32_t sleep_time;
53  float P_act;
55  std::atomic<bool> is_running;
56 
58  OrderEntry::Quantity minimum_size;
60  OrderEntry::Quantity maximum_size;
62  OrderEntry::Side side = OrderEntry::Side::Sell;
64  OrderEntry::Quantity size = 0;
65 
67  inline void sell_order() {
68  auto volume = receiver.get_book().volume_buy_best();
69  if (volume == 0) return;
70  if (volume > size) volume = size;
71  // std::cout << "placing sell order for " << volume << " shares" << std::endl;
72  // cast volume to order entry because it is normally a larger type.
73  // it is guaranteed within range clamping with size above
75  OrderEntry::Messages::ORDER_PRICE_MARKET,
76  static_cast<OrderEntry::Quantity>(volume),
77  OrderEntry::Side::Sell
78  );
79  size -= volume;
80  // std::cout << size << " shares left in todays order quantity" << std::endl;
81  }
82 
84  inline void buy_order() {
85  auto volume = receiver.get_book().volume_sell_best();
86  if (volume == 0) return;
87  if (volume > size) volume = size;
88  // std::cout << "placing buy order for " << volume << " shares" << std::endl;
89  // cast volume to order entry because it is normally a larger type.
90  // it is guaranteed within range clamping with size above
92  OrderEntry::Messages::ORDER_PRICE_MARKET,
93  static_cast<OrderEntry::Quantity>(volume),
94  OrderEntry::Side::Buy
95  );
96  size -= volume;
97  // std::cout << size << " shares left in todays order quantity" << std::endl;
98  }
99 
101  inline void start_strategy() {
102  timer.expires_after(std::chrono::milliseconds(sleep_time));
103  timer.async_wait([this](const std::error_code& error) {
104  if (error) { // TODO: handle error code
105  std::cout << "LiquidityConsumer::start_strategy - " << error << std::endl;
106  return;
107  }
108  if (Maths::Probability::boolean(P_act)) do_strategy();
109  start_strategy();
110  });
111  }
112 
114  void do_strategy() {
115  // make an order based on the agent's side for the day
116  switch (side) {
117  case OrderEntry::Side::Sell: { sell_order(); break; }
118  case OrderEntry::Side::Buy: { buy_order(); break; }
119  }
120  }
121 
122  public:
130  asio::io_context& feed_context,
131  asio::io_context& context,
132  nlohmann::json options
133  ) :
134  receiver(
135  feed_context,
136  asio::ip::make_address(options["data_feed"]["listen"].get<std::string>()),
137  asio::ip::make_address(options["data_feed"]["group"].get<std::string>()),
138  options["data_feed"]["port"].get<uint16_t>(),
139  *this
140  ),
141  client(
142  context,
143  options["order_entry"]["host"].get<std::string>(),
144  std::to_string(options["order_entry"]["port"].get<uint16_t>())
145  ),
146  timer(context),
147  sleep_time(options["strategy"]["sleep_time"].get<uint32_t>()),
148  P_act(options["strategy"]["P_act"].get<double>()),
149  is_running(false),
150  minimum_size(options["strategy"]["minimum_size"].get<double>()),
151  maximum_size(options["strategy"]["maximum_size"].get<double>()) {
152  // login to the order entry client
153  auto username = OrderEntry::make_username(options["order_entry"]["username"].get<std::string>());
154  auto password = OrderEntry::make_password(options["order_entry"]["password"].get<std::string>());
155  client.send<OrderEntry::Messages::LoginRequest>(username, password);
156  }
157 
163  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::StartOfSession& message) {
164  if (is_running) {
165  std::cerr << "received start of session when already running" << std::endl;
166  return;
167  }
168  // std::cout << "trading session started" << std::endl;
169  // select a random side for the day's orders
170  side = Maths::Probability::boolean() ? OrderEntry::Side::Buy : OrderEntry::Side::Sell;
171  // std::cout << "placing " << side << " orders today" << std::endl;
172  size = Maths::Probability::uniform_int(minimum_size, maximum_size);
173  // std::cout << "ordering " << size << " shares today" << std::endl;
174  // start the strategy
175  start_strategy();
176  is_running = true;
177  }
178 
184  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::EndOfSession& message) {
185  if (not is_running) {
186  std::cerr << "received end of session when not running" << std::endl;
187  return;
188  }
189  // stop the strategy
190  timer.cancel();
191  is_running = false;
192  // std::cout << "trading session ended" << std::endl;
193  }
194 
200  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::Clear& message) { }
201 
207  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::AddOrder& message) { }
208 
214  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::DeleteOrder& message) { }
215 
221  inline void did_receive(DataFeedReceiver* receiver, const DataFeed::Messages::Trade& message) { }
222 };
223 
224 } // namespace Strategies
225 
226 #endif // STRATEGIES_LIQUIDITY_CONSUMER_HPP
Strategies::LiquidityConsumer::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::StartOfSession &message)
Handle a start of session message.
Definition: liquidity_consumer.hpp:163
Strategies::LiquidityConsumer::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::Clear &message)
Handle a clear book message.
Definition: liquidity_consumer.hpp:200
DataFeed::Receiver< LiquidityConsumer >
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::send
void send(Args &&...args)
Write a message asynchronously (non-blocking).
Definition: client.hpp:299
Strategies::LiquidityConsumer::LiquidityConsumer
LiquidityConsumer(asio::io_context &feed_context, asio::io_context &context, nlohmann::json options)
Initialize the strategy.
Definition: liquidity_consumer.hpp:129
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
DataFeed::LOB::LimitOrderBook::volume_sell_best
Volume volume_sell_best() const
Return the volume at the best sell price.
Definition: limit_order_book.hpp:300
DataFeed::Messages::EndOfSession
A message that indicates the end of a trading session.
Definition: messages.hpp:506
Strategies::LiquidityConsumer::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::AddOrder &message)
Handle an add order message.
Definition: liquidity_consumer.hpp:207
Strategies::LiquidityConsumer::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::EndOfSession &message)
Handle an end of session message.
Definition: liquidity_consumer.hpp:184
DataFeed::Messages::Clear
A message that indicates to clear all orders in the order book.
Definition: messages.hpp:213
DataFeed::LOB::LimitOrderBook::volume_buy_best
Volume volume_buy_best() const
Return the volume at the best sell price.
Definition: limit_order_book.hpp:318
Maths::Probability::boolean
bool boolean()
Return the result of a coin toss.
Definition: probability.hpp:105
DataFeed::Messages::StartOfSession
A message that indicates the start of a trading session.
Definition: messages.hpp:460
Maths::Probability::uniform_int
T uniform_int(T min, T max)
Sample a number from an integer-valued uniform distribution.
Definition: probability.hpp:49
Strategies::LiquidityConsumer::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::Trade &message)
Handle a trade message.
Definition: liquidity_consumer.hpp:221
Strategies::LiquidityConsumer::did_receive
void did_receive(DataFeedReceiver *receiver, const DataFeed::Messages::DeleteOrder &message)
Handle a delete order message.
Definition: liquidity_consumer.hpp:214
OrderEntry::Client
A client for interacting with the direct market access server.
Definition: client.hpp:42
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
Strategies::LiquidityConsumer
The liquidity consumer strategy logic.
Definition: liquidity_consumer.hpp:40
OrderEntry::Side
Side
The side of an order.
Definition: messages.hpp:71
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