Method: Cotcube::Level#save_swaps

Defined in:
lib/cotcube-level/helpers.rb

#save_swaps(swaps, interval:, swap_type:, contract:, sym: nil, quiet: false) ⇒ Object

the name says it all. just note the addition of a digest, that serves to check whether same swap has been yet saved to the cache.

there are actually 3 types of information, that are saved here:

  1. a swap

  2. an ‘empty’ information, referring to an interval that has been processed but no swaps were found

  3. an ‘exceeded’ information, referring to another swap, that has been exceeded



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/cotcube-level/helpers.rb', line 140

def save_swaps(swaps, interval:, swap_type:, contract:, sym: nil, quiet: false)
  file = get_jsonl_name(interval: interval, swap_type: swap_type, contract: contract, sym: sym)
  swaps = [ swaps ] unless swaps.is_a? Array
  swaps.each do |swap|
    raise "Illegal swap info: Must contain keys :datetime, :side... #{swap}" unless (i[ datetime side ] - swap.keys).empty?
    i[ interval swap_type ].map {|key| swap.delete(key) }
    sorted_keys = [ :datetime, :side ] + ( swap.keys - [ :datetime, :side ])
    swap_json = swap.slice(*sorted_keys).to_json
    digest = Digest::SHA256.hexdigest swap_json
    res = `cat #{file} | grep '"digest":"#{digest}"'`.strip
    unless res.empty?
      puts "Cannot save swap, it is already in #{file}:".light_red unless quiet
      p swap unless quiet
    else
      swap[:digest] = digest
      sorted_keys += i[digest]
      File.open(file, 'a+'){|f| f.write(swap.slice(*sorted_keys).to_json + "\n") }
    end
  end
end