huginn_bybit_agent 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e7360ce7d5fecdfe21e247f68024b0318287b48d78dab1dda7d6bc931e45c456
4
+ data.tar.gz: 20077cb7a7c0cc765109cad94c232573ed7f5a35054e3ee3f9e9adc801a222eb
5
+ SHA512:
6
+ metadata.gz: ddac1285c25e75dee7b67db9d3086edcd495bdf8bc0e9bcf3015a85b31cf3a7bd2360b639b8e59a9559a4ad67b6300b0784c3c18d728a66da901d374e44b83ba
7
+ data.tar.gz: da1f959963c9649645357fc29b251790510d369205c9c0bb9889a34a49de7925c7c692d281392e43cd412f93ba00cc1688716cd2ad6c0817036e75862a3bac99
data/LICENSE.txt ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2023 Nicolas Germain
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,362 @@
1
+ module Agents
2
+ class BybitAgent < Agent
3
+ include FormConfigurable
4
+ can_dry_run!
5
+ no_bulk_receive!
6
+ default_schedule 'every_1h'
7
+
8
+ description <<-MD
9
+ The Bybit Agent interacts with the Bybit API and can create events / tasks if wanted / needed.
10
+
11
+ The `type` can be like checking the wallet's balance, alerts.
12
+
13
+ `apikey` is needed for auth endpoint.
14
+
15
+ `secretkey` is needed for auth endpoint.
16
+
17
+ `windows` to specify how long an HTTP request is valid.
18
+
19
+ `limit` to timit for data size.
20
+
21
+ `debug` is for adding verbosity.
22
+
23
+ `expected_receive_period_in_days` is used to determine if the Agent is working. Set it to the maximum number of days
24
+ that you anticipate passing without this Agent receiving an incoming Event.
25
+ MD
26
+
27
+ event_description <<-MD
28
+ Events look like this:
29
+
30
+ {
31
+ "retCode": 0,
32
+ "retMsg": "OK",
33
+ "result": {
34
+ "balances": [
35
+ {
36
+ "coin": "ADA",
37
+ "coinId": "ADA",
38
+ "total": "500000000000",
39
+ "free": "500000000000",
40
+ "locked": "0"
41
+ }
42
+ ]
43
+ },
44
+ "retExtInfo": {},
45
+ "time": 1676117370511
46
+ }
47
+ MD
48
+
49
+ def default_options
50
+ {
51
+ 'type' => '',
52
+ 'apikey' => '',
53
+ 'windows' => '5000',
54
+ 'limit' => '10',
55
+ 'secretkey' => '',
56
+ 'debug' => 'false',
57
+ 'expected_receive_period_in_days' => '2',
58
+ 'changes_only' => 'true'
59
+ }
60
+ end
61
+
62
+ form_configurable :debug, type: :boolean
63
+ form_configurable :apikey, type: :string
64
+ form_configurable :secretkey, type: :string
65
+ form_configurable :limit, type: :string
66
+ form_configurable :windows, type: :string
67
+ form_configurable :expected_receive_period_in_days, type: :string
68
+ form_configurable :changes_only, type: :boolean
69
+ form_configurable :type, type: :array, values: ['get_balances', 'order_history', 'trade_history']
70
+ def validate_options
71
+ errors.add(:base, "type has invalid value: should be 'get_balances' 'order_history' 'trade_history'") if interpolated['type'].present? && !%w(get_balances order_history trade_history).include?(interpolated['type'])
72
+
73
+ unless options['apikey'].present? || !['get_balances', 'order_history', 'trade_history'].include?(options['type'])
74
+ errors.add(:base, "apikey is a required field")
75
+ end
76
+
77
+ unless options['secretkey'].present? || !['get_balances', 'order_history', 'trade_history'].include?(options['type'])
78
+ errors.add(:base, "secretkey is a required field")
79
+ end
80
+
81
+ unless options['limit'].present? || !['order_history', 'trade_history'].include?(options['type'])
82
+ errors.add(:base, "limit is a required field")
83
+ end
84
+
85
+ if options.has_key?('changes_only') && boolify(options['changes_only']).nil?
86
+ errors.add(:base, "if provided, changes_only must be true or false")
87
+ end
88
+
89
+ if options.has_key?('debug') && boolify(options['debug']).nil?
90
+ errors.add(:base, "if provided, debug must be true or false")
91
+ end
92
+
93
+ unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
94
+ errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working")
95
+ end
96
+ end
97
+
98
+ def working?
99
+ event_created_within?(options['expected_receive_period_in_days']) && !recent_error_logs?
100
+ end
101
+
102
+ def check
103
+ trigger_action
104
+ end
105
+
106
+ private
107
+
108
+
109
+ def new_nonce
110
+ (Time.now.to_f * 1000000).floor.to_s
111
+ end
112
+
113
+ def log_curl_output(code,body)
114
+
115
+ log "request status : #{code}"
116
+
117
+ if interpolated['debug'] == 'true'
118
+ log "body"
119
+ log body
120
+ end
121
+
122
+ end
123
+
124
+ def genSignature(payload,time_stamp)
125
+ param_str = time_stamp + interpolated['apikey'] + interpolated['windows'] + payload
126
+ if interpolated['debug'] == 'true'
127
+ log "param_str"
128
+ log param_str
129
+ end
130
+ OpenSSL::HMAC.hexdigest('sha256', interpolated['secretkey'], param_str)
131
+ end
132
+
133
+ def trade_history(base_url)
134
+
135
+ time_stamp = DateTime.now.strftime('%Q')
136
+ endPoint = "/spot/v3/private/my-trades"
137
+ tradeLinkId = SecureRandom.uuid
138
+ payload = "tradeLinkId=" + tradeLinkId + '&limit' + interpolated['limit']
139
+ signature = genSignature(payload,time_stamp)
140
+ payload="?"+payload
141
+
142
+ if interpolated['debug'] == 'true'
143
+ log "signature"
144
+ log signature
145
+ end
146
+ fullUrl = base_url + endPoint + payload
147
+ uri = URI.parse(fullUrl)
148
+ request = Net::HTTP::Get.new(uri)
149
+ request["X-BAPI-SIGN"] = signature
150
+ request["X-BAPI-API-KEY"] = interpolated['apikey']
151
+ request["X-BAPI-TIMESTAMP"] = time_stamp
152
+ request["X-BAPI-RECV-WINDOW"] = interpolated['windows']
153
+
154
+ req_options = {
155
+ use_ssl: uri.scheme == "https",
156
+ }
157
+
158
+ response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
159
+ http.request(request)
160
+ end
161
+
162
+ log_curl_output(response.code,response.body)
163
+
164
+ payload = JSON.parse(response.body)
165
+ if interpolated['changes_only'] == 'true'
166
+ if payload.to_s != memory['last_status']
167
+ if "#{memory['last_status']}" == ''
168
+ payload['result']['list'].each do | trade |
169
+ create_event :payload => trade
170
+ end
171
+ else
172
+ last_status = memory['last_status'].gsub("=>", ": ").gsub(": nil,", ": null,")
173
+ last_status = JSON.parse(last_status)
174
+ payload['result']['list'].each do | trade |
175
+ found = false
176
+ last_status['result']['list'].each do | tradebis |
177
+ if trade == tradebis
178
+ found = true
179
+ end
180
+ end
181
+ if interpolated['debug'] == 'true'
182
+ log found
183
+ end
184
+ if found == false
185
+ create_event :payload => trade
186
+ end
187
+ end
188
+ end
189
+ memory['last_status'] = payload.to_s
190
+ end
191
+ else
192
+ create_event payload: payload
193
+ if payload.to_s != memory['last_status']
194
+ memory['last_status'] = payload.to_s
195
+ end
196
+ end
197
+ end
198
+
199
+ def order_history(base_url)
200
+
201
+ time_stamp = DateTime.now.strftime('%Q')
202
+ endPoint = "/v5/order/history"
203
+ orderLinkId = SecureRandom.uuid
204
+ payload = "orderLinkId=" + orderLinkId + '&limit' + interpolated['limit'] + '&category=spot'
205
+ signature = genSignature(payload,time_stamp)
206
+ payload="?"+payload
207
+
208
+ if interpolated['debug'] == 'true'
209
+ log "signature"
210
+ log signature
211
+ end
212
+ fullUrl = base_url + endPoint + payload
213
+ uri = URI.parse(fullUrl)
214
+ request = Net::HTTP::Get.new(uri)
215
+ request["X-BAPI-SIGN"] = signature
216
+ request["X-BAPI-API-KEY"] = interpolated['apikey']
217
+ request["X-BAPI-TIMESTAMP"] = time_stamp
218
+ request["X-BAPI-RECV-WINDOW"] = interpolated['windows']
219
+
220
+ req_options = {
221
+ use_ssl: uri.scheme == "https",
222
+ }
223
+
224
+ response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
225
+ http.request(request)
226
+ end
227
+
228
+ log_curl_output(response.code,response.body)
229
+
230
+ payload = JSON.parse(response.body)
231
+ if interpolated['changes_only'] == 'true'
232
+ if payload != memory['last_status']
233
+ payload['result']['list'].each do | order |
234
+ found = false
235
+ if interpolated['debug'] == 'true'
236
+ log "order"
237
+ log order
238
+ end
239
+ if !memory['last_status'].nil? and memory['last_status'].present?
240
+ if interpolated['debug'] == 'true'
241
+ log "memory"
242
+ log memory['last_status']
243
+ end
244
+ last_status = memory['last_status']
245
+ last_status['result']['list'].each do |orderbis|
246
+ if order['id'] == orderbis['id']
247
+ found = true
248
+ end
249
+ if interpolated['debug'] == 'true'
250
+ log "orderbis"
251
+ log orderbis
252
+ log "found is #{found}!"
253
+ end
254
+ end
255
+ end
256
+ if found == false
257
+ create_event payload: order
258
+ end
259
+ end
260
+ else
261
+ if interpolated['debug'] == 'true'
262
+ log "nothing to compare"
263
+ end
264
+ end
265
+ else
266
+ create_event payload: payload
267
+ if payload != memory['last_status']
268
+ end
269
+ end
270
+ memory['last_status'] = payload
271
+ end
272
+
273
+ def get_balances(base_url)
274
+
275
+ time_stamp = DateTime.now.strftime('%Q')
276
+ endPoint = "/v5/account/wallet-balance"
277
+ orderLinkId = SecureRandom.uuid
278
+ payload = "accountType=UNIFIED"
279
+ signature = genSignature(payload,time_stamp)
280
+ payload="?"+payload
281
+
282
+ if interpolated['debug'] == 'true'
283
+ log "signature"
284
+ log signature
285
+ end
286
+ fullUrl = base_url + endPoint + payload
287
+ uri = URI.parse(fullUrl)
288
+ request = Net::HTTP::Get.new(uri)
289
+ request["X-BAPI-SIGN"] = signature
290
+ request["X-BAPI-API-KEY"] = interpolated['apikey']
291
+ request["X-BAPI-TIMESTAMP"] = time_stamp
292
+ request["X-BAPI-RECV-WINDOW"] = interpolated['windows']
293
+
294
+ req_options = {
295
+ use_ssl: uri.scheme == "https",
296
+ }
297
+
298
+ response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
299
+ http.request(request)
300
+ end
301
+
302
+ log_curl_output(response.code,response.body)
303
+
304
+ payload = JSON.parse(response.body)
305
+ if interpolated['changes_only'] == 'true'
306
+ if payload != memory['last_status']
307
+ payload['result']['list'][0]['coin'].each do | coin |
308
+ found = false
309
+ if interpolated['debug'] == 'true'
310
+ log "coin"
311
+ log coin
312
+ end
313
+ if !memory['last_status'].nil? and memory['last_status'].present?
314
+ if interpolated['debug'] == 'true'
315
+ log "memory"
316
+ log memory['last_status']
317
+ end
318
+ last_status = memory['last_status']
319
+ last_status['result']['list'][0]['coin'].each do |coinbis|
320
+ if coin['id'] == coinbis['id']
321
+ found = true
322
+ end
323
+ if interpolated['debug'] == 'true'
324
+ log "coinbis"
325
+ log coinbis
326
+ log "found is #{found}!"
327
+ end
328
+ end
329
+ end
330
+ if found == false
331
+ create_event payload: coin
332
+ end
333
+ end
334
+ else
335
+ if interpolated['debug'] == 'true'
336
+ log "nothing to compare"
337
+ end
338
+ end
339
+ else
340
+ create_event payload: payload
341
+ if payload != memory['last_status']
342
+ end
343
+ end
344
+ memory['last_status'] = payload
345
+ end
346
+
347
+ def trigger_action()
348
+
349
+ base_url = 'https://api.bybit.com'
350
+ case interpolated['type']
351
+ when "get_balances"
352
+ get_balances(base_url)
353
+ when "order_history"
354
+ order_history(base_url)
355
+ when "trade_history"
356
+ trade_history(base_url)
357
+ else
358
+ log "Error: type has an invalid value (#{type})"
359
+ end
360
+ end
361
+ end
362
+ end
@@ -0,0 +1,4 @@
1
+ require 'huginn_agent'
2
+
3
+ #HuginnAgent.load 'huginn_bybit_agent/concerns/my_agent_concern'
4
+ HuginnAgent.register 'huginn_bybit_agent/bybit_agent'
@@ -0,0 +1,13 @@
1
+ require 'rails_helper'
2
+ require 'huginn_agent/spec_helper'
3
+
4
+ describe Agents::BybitAgent do
5
+ before(:each) do
6
+ @valid_options = Agents::BybitAgent.new.default_options
7
+ @checker = Agents::BybitAgent.new(:name => "BybitAgent", :options => @valid_options)
8
+ @checker.user = users(:bob)
9
+ @checker.save!
10
+ end
11
+
12
+ pending "add specs here"
13
+ end
metadata ADDED
@@ -0,0 +1,90 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: huginn_bybit_agent
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.11
5
+ platform: ruby
6
+ authors:
7
+ - Nicolas Germain
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-11-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 2.1.0
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 2.1.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 12.3.3
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 12.3.3
41
+ - !ruby/object:Gem::Dependency
42
+ name: huginn_agent
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Write a longer description or delete this line.
56
+ email:
57
+ - ngermain@hihouhou.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - LICENSE.txt
63
+ - lib/huginn_bybit_agent.rb
64
+ - lib/huginn_bybit_agent/bybit_agent.rb
65
+ - spec/bybit_agent_spec.rb
66
+ homepage: https://github.com/hihouhou/huginn_bybit_agent
67
+ licenses:
68
+ - MIT
69
+ metadata: {}
70
+ post_install_message:
71
+ rdoc_options: []
72
+ require_paths:
73
+ - lib
74
+ required_ruby_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: '0'
84
+ requirements: []
85
+ rubygems_version: 3.3.3
86
+ signing_key:
87
+ specification_version: 4
88
+ summary: Write a short summary, because Rubygems requires one.
89
+ test_files:
90
+ - spec/bybit_agent_spec.rb