-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.rb
100 lines (84 loc) · 2.51 KB
/
helpers.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
module APIv2
module Helpers
def authenticate!
current_user or raise AuthorizationError
end
def redis
@r ||= KlineDB.redis
end
def current_user
@current_user ||= current_token.try(:member)
end
def current_token
@current_token ||= env['api_v2.token']
end
def current_market
@current_market ||= Market.find params[:market]
end
def time_to
params[:timestamp].present? ? Time.at(params[:timestamp]) : nil
end
def build_order(attrs)
klass = attrs[:side] == 'sell' ? OrderAsk : OrderBid
order = klass.new(
source: 'APIv2',
state: ::Order::WAIT,
member_id: current_user.id,
ask: current_market.base_unit,
bid: current_market.quote_unit,
currency: current_market.id,
ord_type: attrs[:ord_type] || 'limit',
price: attrs[:price],
volume: attrs[:volume],
origin_volume: attrs[:volume]
)
end
def create_order(attrs)
order = build_order attrs
Ordering.new(order).submit
order
rescue
Rails.logger.info "Failed to create order: #{$!}"
Rails.logger.debug order.inspect
Rails.logger.debug $!.backtrace.join("\n")
raise CreateOrderError, $!
end
def create_orders(multi_attrs)
orders = multi_attrs.map {|attrs| build_order attrs }
Ordering.new(orders).submit
orders
rescue
Rails.logger.info "Failed to create order: #{$!}"
Rails.logger.debug $!.backtrace.join("\n")
raise CreateOrderError, $!
end
def order_param
params[:order_by].downcase == 'asc' ? 'id asc' : 'id desc'
end
def format_ticker(ticker)
{ at: ticker[:at],
ticker: {
buy: ticker[:buy],
sell: ticker[:sell],
low: ticker[:low],
high: ticker[:high],
last: ticker[:last],
vol: ticker[:volume]
}
}
end
def get_k_json
key = "peatio:#{params[:market]}:k:#{params[:period]}"
if params[:timestamp]
ts = JSON.parse(redis.lindex(key, 0)).first
offset = (params[:timestamp] - ts) / 60 / params[:period]
offset = 0 if offset < 0
JSON.parse('[%s]' % redis.lrange(key, offset, offset + params[:limit] - 1).join(','))
else
length = redis.llen(key)
offset = [length - params[:limit], 0].max
JSON.parse('[%s]' % redis.lrange(key, offset, -1).join(','))
end
end
end
end