Module: Cryptum::WebSock::EventMachine

Defined in:
lib/cryptum/web_sock/event_machine.rb

Overview

This module is the primary module to handle Web Socket Events from Coinbase

Class Method Summary collapse

Class Method Details

.helpObject

Display Usage for this Module



269
270
271
272
273
# File 'lib/cryptum/web_sock/event_machine.rb', line 269

public_class_method def self.help
  puts "USAGE:
    logger = #{self}.create()
  "
end

.run(opts = {}) ⇒ Object

Supported Method Parameters

Cryptum::WS.run( )



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
# File 'lib/cryptum/web_sock/event_machine.rb', line 16

public_class_method def self.run(opts = {})
  env = opts[:env]
  option_choice = opts[:option_choice]
  terminal_win = opts[:terminal_win]
  event_history = opts[:event_history]
  indicator_status = opts[:indicator_status]
  bot_conf = opts[:bot_conf]

  max_conn_attempts = 30
  conn_attempt = 0

  begin
    conn_attempt += 1
    event_history.reconnected = true if conn_attempt > 1

    EM.run do
      # Iterate as fast as possible
      # This ensures candle timing is accurate
      # and everything is fast as possible
      # Defaults to 100ms, 5ms is the lowest possible
      delay_ms = 5
      delay_ms_cast_as_decimal = delay_ms * 0.001
      EM.set_quantum(delay_ms)

      ws = Cryptum::WebSock::Coinbase.connect(
        option_choice: option_choice,
        env: env
      )

      ws.on :open do |_event|
        ws.send(
          Cryptum::WebSock::Coinbase.subscribe_message(
            option_choice: option_choice,
            env: env
          )
        )
      end

      ws.on :message do |event|
        # TODO: The Speed of the UI is dictated by the
        # Frequency of WebSocket Messages Coming Through.
        # Explore another way to decouple required events
        # (such as keypresses) from only being triggered
        # when messages come through.

        event_history.event = JSON.parse(
          event.data,
          symbolize_names: true
        )
        event_history.event_type = event_history.event[:type].to_s.to_sym

        event_history = Cryptum::Event::Parse.websocket_msg(
          env: env,
          terminal_win: terminal_win,
          option_choice: option_choice,
          event_history: event_history,
          indicator_status: indicator_status,
          bot_conf: bot_conf
        )

        # Detect Key Press Events
        Cryptum::Event::KeyPress.detect(terminal_win: terminal_win)

        # Cancel ALL Open Orders when
        # C is pressed
        if terminal_win.key_press_event.key_c
          Cryptum::Event::Cancel.open_orders(
            terminal_win: terminal_win,
            option_choice: option_choice,
            env: env
          )
        end

        # Get the F* Out (GTFO) when
        # G is pressed
        if terminal_win.key_press_event.key_g
          event_history = Cryptum::Event::GTFO.now(
            terminal_win: terminal_win,
            option_choice: option_choice,
            env: env,
            event_history: event_history,
            bot_conf: bot_conf
          )
        end

        # Reload Bot Conf when r is Pressed
        if terminal_win.key_press_event.key_r
          bot_conf = Cryptum::Event::BotConf.reload(
            terminal_win: terminal_win,
            event_history: event_history,
            option_choice: option_choice
          )
        end

        # Only Write Order Book to File when
        # W is Pressed
        if terminal_win.key_press_event.key_w
          Cryptum::Event::OrderBook.write(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Exit if x is Pressed
        if terminal_win.key_press_event.key_x
          Cryptum::Event::Exit.gracefully(
            terminal_win: terminal_win,
            event_history: event_history,
            option_choice: option_choice,
            env: env
          )
        end

        # TAB through Order Plan / Order Execution Window Panes
        if terminal_win.key_press_event.key_tab
          Cryptum::Event::Pane.switch(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Scroll Up Order Plan / Order Execution Window Panes
        if terminal_win.key_press_event.key_up_arrow
          Cryptum::Event::Scroll.up(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Scroll Down Order Plan / Order Execution Window Panes
        if terminal_win.key_press_event.key_down_arrow
          Cryptum::Event::Scroll.down(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Scroll Up Order Plan / Order Execution Window Panes Faster
        if terminal_win.key_press_event.key_page_up
          Cryptum::Event::Scroll.page_up(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Scroll Down Order Plan / Order Execution Window Panes Faster
        if terminal_win.key_press_event.key_page_down
          Cryptum::Event::Scroll.page_down(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Scroll to Top of Order Plan / Order Execution Window Panes
        if terminal_win.key_press_event.key_home
          Cryptum::Event::Scroll.top(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Scroll to Bottom of Order Plan / Order Execution Window Panes
        if terminal_win.key_press_event.key_end
          Cryptum::Event::Scroll.bottom(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end

        # Open / Close Order Plan / Order Execution Details Window
        if terminal_win.key_press_event.key_enter
          Cryptum::Event::Pane.toggle_details(
            terminal_win: terminal_win,
            event_history: event_history
          )
        end
      end

      ws.on :close do
        raise Errno::ECONNRESET
      end

      EM.add_periodic_timer(delay_ms_cast_as_decimal) do
        order_countdown = Cryptum::UI::OrderTimer.refresh(
          option_choice: option_choice,
          event_history: event_history,
          order_timer_win: terminal_win.order_timer_section,
          indicator_status: indicator_status,
          key_press_event: terminal_win.key_press_event
        )

        if (order_countdown.zero? || order_countdown.negative?) &&
           !event_history.red_pill

          # Ready to Submit a BUY order
          event_history.order_ready = true

          # Reload Bot Conf (i.e. Risk Allocation),
          # Recalculate Order Plan, and Write to File
          terminal_win.key_press_event.key_r = true
        end
      end

      EM.add_periodic_timer(option_choice.market_trend_reset) do
        # NOTE: To ensure the integrity of event_history is maintained,
        # changes to its contenta _MUST_ stay in thos block.
        event_history.order_book[:market_trend][:buy] = 0
        event_history.order_book[:market_trend][:sell] = 0
        event_history.order_book[:last_trend_reset] = Time.now.strftime(
          '%Y-%m-%d %H:%M:%S.%N%z'
        )

        # Reload Bot Conf (i.e. Risk Allocation)
        # Recalculate Order Plan, and Write to File
        terminal_win.key_press_event.key_r = true
        # IMPORTANT:
        # Wait for Order Plan recalculation to occur
        # once Cryptum::UI::OrderPlan is refreshed
        # in Cryptum::Event _BEFORE_ writing the order
        # book to file.
      end
    end
  rescue Faye::WebSocket::API::ErrorEvent,
         Errno::ECONNREFUSED,
         Errno::ECONNRESET,
         LoadError => e

    File.open('/tmp/cryptum-errors.txt', 'a') do |f|
      f.puts Time.now.strftime('%Y-%m-%d %H:%M:%S.%N %z')
      f.puts "Module: #{self}"
      f.puts "#{e}\n\n\n"
    end

    raise e if conn_attempt > max_conn_attempts

    sleep 1
    retry
  ensure
    $stdout.flush
  end
rescue Interrupt
  # Exit Gracefully if CTRL+C is Pressed During Session
  Cryptum.exit_gracefully(
    which_self: self,
    event_history: event_history,
    option_choice: option_choice,
    env: env
  )
rescue StandardError => e
  raise e
end