Module: IB::Eod

Included in:
Contract
Defined in:
lib/ib/eod.rb

Defined Under Namespace

Modules: BuisinesDays

Instance Method Summary collapse

Instance Method Details

#eod(start: nil, to: nil, duration: nil, what: :trades, polars: false) ⇒ Object

atility ) shape: (3, 8) ┌────────────┬──────────┬──────────┬──────────┬──────────┬────────┬──────────┬────────┐ │ time ┆ open ┆ high ┆ low ┆ close ┆ volume ┆ wap ┆ trades │ │ — ┆ — ┆ — ┆ — ┆ — ┆ — ┆ — ┆ — │ │ date ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ i64 ┆ f64 ┆ i64 │ ╞════════════╪══════════╪══════════╪══════════╪══════════╪════════╪══════════╪════════╡ │ 2019-12-31 ┆ 0.134933 ┆ 0.177794 ┆ 0.115884 ┆ 0.138108 ┆ 0 ┆ 0.178318 ┆ 0 │ │ 2020-01-31 ┆ 0.139696 ┆ 0.190494 ┆ 0.120646 ┆ 0.185732 ┆ 0 ┆ 0.19097 ┆ 0 │ │ 2020-02-28 ┆ 0.185732 ┆ 0.436549 ┆ 0.134933 ┆ 0.39845 ┆ 0 ┆ 0.435866 ┆ 0 │ └────────────┴──────────┴──────────┴──────────┴──────────┴────────┴──────────┴────────┘



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
# File 'lib/ib/eod.rb', line 154

def eod start: nil, to: nil, duration: nil , what: :trades, polars: false

 # error "EOD:: Start-Date (parameter: to) must be a Date-Object" unless to.is_a? Date
  normalize_duration = ->(d) do
    if d.is_a?(Integer) || !["D","M","W","Y"].include?( d[-1].upcase )
      d.to_i.to_s + "D"
    else
      d.gsub(" ","")
    end.insert(-2, " ")
  end

  get_end_date = -> do
    d = normalize_duration.call(duration)
    case  d[-1]
    when "D"
      start + d.to_i - 1
    when 'W'
      Date.commercial( start.year, start.cweek + d.to_i - 1, 1)
    when 'M'
      Date.new( start.year, start.month + d.to_i - 1 , start.day )
    end
  end

  if to.nil?
  #  case   eod start= Date.new ...
    to =   if start.present? && duration.nil?
  # case    eod start= Date.new
             duration = BuisinesDays.business_days_between(start, to).to_s + "D"
             Date.today #  assign to var: to
           elsif start.present? && duration.present?
  # case    eod start= Date.new , duration: 'nN'
             get_end_date.call  # assign to var: to
           elsif duration.present?
  # case    start is not present, we are collecting until the present day
              Date.today         # assign to var: to
           else
             duration =  "1D"
             Date.today
           end
  end

  barsize = case normalize_duration.call(duration)[-1].upcase
            when "W"
              :week1
            when "M"
              :month1
            else
              :day1
            end


 get_bars(to.to_time.to_ib , normalize_duration[duration], barsize, what, polars)

end

#from_csv(file: nil) ⇒ Object

read csv-data into bars



218
219
220
221
222
223
224
# File 'lib/ib/eod.rb', line 218

def from_csv file: nil
  file ||=  "#{symbol}.csv"
  self.bars = []
  CSV.foreach( file,  headers: true, header_converters: :symbol) do |row|
    self.bars << IB::Bar.new( **row.to_h )
  end
end

#get_bars(end_date_time, duration, bar_size, what_to_show, polars) ⇒ Object



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
# File 'lib/ib/eod.rb', line 226

def get_bars(end_date_time, duration, bar_size, what_to_show, polars)

  tws = IB::Connection.current
  received =  Queue.new
  r = nil
  # the hole response is transmitted at once!
  a = tws.subscribe(IB::Messages::Incoming::HistoricalData) do |msg|
    if msg.request_id == con_id
      self.bars = if polars
                    # msg.results.each { |entry| puts "  #{entry}" }
                    Polars::DataFrame.new  msg.results.map( &:invariant_attributes )
                  else
                    msg.results
                  end
    end
    received.push Time.now
  end
  b = tws.subscribe( IB::Messages::Incoming::Alert) do  |msg|
    if [321,162,200].include? msg.code
      tws.logger.info msg.message
      # TWS Error 200: No security definition has been found for the request
      # TWS Error 354: Requested market data is not subscribed.
      # TWS Error 162  # Historical Market Data Service error
      received.close
    elsif msg.code.to_i == 2174
      tws.logger.info "Please switch to the \"10-19\"-Branch of the git-repository"
    end
  end


  tws.send_message IB::Messages::Outgoing::RequestHistoricalData.new(
    :request_id => con_id,
    :contract =>  self,
    :end_date_time => end_date_time, 
    :duration => duration, # see ib/messages/outgoing/bar_request.rb => max duration for 5sec bar lookback is 10 000 - i.e. will yield 2000 bars
    :bar_size =>  bar_size, #  IB::BAR_SIZES.key(:hour)
    :what_to_show => what_to_show,
    :use_rth => 0,
    :format_date => 2,
    :keep_up_todate => 0)

  received.pop # blocks until a message is ready on the queue or the queue is closed

  tws.unsubscribe a
  tws.unsubscribe b

  block_given? ?  bars.map{|y| yield y} : bars  # return bars or result of block

end

#to_csv(file: "#{symbol}.csv") ⇒ Object

creates (or overwrites) the specified file (or symbol.csv) and saves bar-data



210
211
212
213
214
215
# File 'lib/ib/eod.rb', line 210

def to_csv file: "#{symbol}.csv"
  if bars.present?
    headers = bars.first.invariant_attributes.keys
    CSV.open( file, 'w' ) {|f| f << headers ; bars.each {|y| f << y.invariant_attributes.values } }
  end
end