bitmex_client 0.2.0

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 765d35d03eea4ba1f685327413669ae1163a0992
4
+ data.tar.gz: dea5541cb4eebaff47dc84f31ace7c500b02c31c
5
+ SHA512:
6
+ metadata.gz: b9ed6d0de83450d5cda902a038dcb5b8ac96c3a958a0a2fe4d2f93a41dac59446a3b4077a6c968bfa664b6a012eb3a7823133b0208d0a84e79963f4147851773
7
+ data.tar.gz: a3a226f39ff1a5ee0d998c7c82d57acae0c90033d3d9f25ee02f891a432b330289819f56e1f3a3063f93db9c031a7eeb2fc2c2d988932d1203c4bf6e69b5f589
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /vendor/bundle/
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at sir.yes.sir.maru@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://gems.ruby-china.com"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in bitmex.gemspec
6
+ gemspec
@@ -0,0 +1,27 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ bitmex_client (0.2.0)
5
+ faraday (~> 0.15.4)
6
+ faraday_middleware (~> 0.12.2)
7
+
8
+ GEM
9
+ remote: https://gems.ruby-china.com/
10
+ specs:
11
+ faraday (0.15.4)
12
+ multipart-post (>= 1.2, < 3)
13
+ faraday_middleware (0.12.2)
14
+ faraday (>= 0.7.4, < 1.0)
15
+ multipart-post (2.0.0)
16
+ rake (12.3.1)
17
+
18
+ PLATFORMS
19
+ ruby
20
+
21
+ DEPENDENCIES
22
+ bitmex_client!
23
+ bundler (~> 1.17.1)
24
+ rake (~> 12.3.1)
25
+
26
+ BUNDLED WITH
27
+ 1.17.1
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 horizon67
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,50 @@
1
+ # Bitmex
2
+
3
+ A Ruby wrapper for the [Bitmex API v1](https://www.bitmex.com/api/explorer/)
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ gem install bitmex_client
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ See https://www.bitmex.com/api/explorer/ for details.
14
+
15
+ ### HTTP API
16
+
17
+ #### Example
18
+
19
+ ```ruby
20
+ # configure
21
+ BitmexClient.configure do |config|
22
+ config.adapter = Faraday.default_adapter # default: Faraday.default_adapter
23
+ config.url = 'https://www.bitmex.com' # default: https://www.bitmex.com
24
+ config.user_agent = 'Bitmex Ruby Gem' # default: 'Bitmex Ruby Gem [Gem Version]'
25
+ config.loud_logger = true # default false
26
+ end
27
+
28
+ # public API
29
+ public_client = BitmexClient.http_public_client
30
+ p public_client.instrument # will print instrument
31
+
32
+ # private API
33
+ private_client = BitmexClient.http_private_client('YOUR_API_KEY', 'YOUR_API_SECRET')
34
+ private_client.create_order("XBTUSD", 100, {price: 6700, execInst: "ParticipateDoNotInitiate", ordType: 'Limit', side: 'Sell'})
35
+ # you can order
36
+
37
+ p private_client.position # will print your positions
38
+ p private_client.user_wallet # will print your wallet
39
+
40
+ ```
41
+
42
+ ## Contributing
43
+
44
+ Bug reports and pull requests are welcome on GitHub at https://github.com/markgeek/bitmex_client. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
45
+
46
+
47
+ ## License
48
+
49
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
50
+
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "bitmex"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,27 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "bitmex_client/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "bitmex_client"
8
+ spec.version = BitmexClient::VERSION
9
+ spec.authors = ["markgeek"]
10
+ spec.email = ["mark.geek.lee@gmail.com"]
11
+
12
+ spec.summary = %q{Bitmex API wrapper.}
13
+ spec.description = %q{Bitmex API wrapper.}
14
+ spec.homepage = "https://github.com/markgeek/bitmex_client"
15
+ spec.license = "MIT"
16
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_dependency 'faraday', '~> 0.15.4'
24
+ spec.add_dependency 'faraday_middleware', '~> 0.12.2'
25
+ spec.add_development_dependency "bundler", "~> 1.17.1"
26
+ spec.add_development_dependency "rake", "~> 12.3.1"
27
+ end
@@ -0,0 +1,17 @@
1
+ require 'bitmex_client/version'
2
+ require 'bitmex_client/http'
3
+ require 'bitmex_client/configuration'
4
+
5
+ module BitmexClient
6
+ extend Configuration
7
+
8
+ def http_public_client
9
+ Bitmex::HTTP::Public::Client.new
10
+ end
11
+
12
+ def http_private_client(key, secret)
13
+ Bitmex::HTTP::Private::Client.new(key, secret)
14
+ end
15
+
16
+ module_function :http_public_client, :http_private_client
17
+ end
@@ -0,0 +1,35 @@
1
+ require 'faraday'
2
+ require File.expand_path('../version', __FILE__)
3
+
4
+ module BitmexClient
5
+ module Configuration
6
+ VALID_OPTIONS_KEYS = [
7
+ :adapter,
8
+ :url,
9
+ :user_agent,
10
+ :loud_logger
11
+ ].freeze
12
+
13
+ DEFAULT_ADAPTER = Faraday.default_adapter
14
+ DEFAULT_URL = 'https://www.bitmex.com'.freeze
15
+ DEFAULT_USER_AGENT = "Bitmex Ruby Gem #{BitmexClient::VERSION}".freeze
16
+ DEFAULT_LOUD_LOGGER = false
17
+
18
+ attr_accessor *VALID_OPTIONS_KEYS
19
+
20
+ def self.extended(base)
21
+ base.reset
22
+ end
23
+
24
+ def configure
25
+ yield self
26
+ end
27
+
28
+ def reset
29
+ self.adapter = DEFAULT_ADAPTER
30
+ self.url = DEFAULT_URL
31
+ self.user_agent = DEFAULT_USER_AGENT
32
+ self.loud_logger = DEFAULT_LOUD_LOGGER
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,27 @@
1
+ require 'bitmex_client'
2
+ require 'bitmex_client/http/public'
3
+ require 'bitmex_client/http/private'
4
+ require 'faraday'
5
+ require 'faraday_middleware'
6
+ Dir[File.expand_path('../../faraday/*.rb', __FILE__)].each{|f| require f}
7
+
8
+ module BitmexClient
9
+ module HTTP
10
+ class Connection
11
+ extend Forwardable
12
+
13
+ def_delegators :@connection, :get, :post, :delete
14
+
15
+ def initialize(key, secret)
16
+ @connection = Faraday::Connection.new(:url => Bitmex.url) do |f|
17
+ f.request :json
18
+ f.response :json, :parser_options => { :symbolize_names => true }
19
+ f.use FaradayMiddleware::Authentication, key, secret
20
+ f.use FaradayMiddleware::RaiseHttpException
21
+ f.use FaradayMiddleware::LoudLogger if Bitmex.loud_logger
22
+ f.adapter Bitmex.adapter
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,91 @@
1
+ module BitmexClient
2
+ module HTTP
3
+ module Private
4
+ class Client
5
+
6
+ def initialize(key, secret)
7
+ @connection = Connection.new(key, secret)
8
+ end
9
+
10
+ # @see https://www.bitmex.com/api/explorer/#!/Execution/Execution_get
11
+ def execution(options = {})
12
+ @connection.get('/api/v1/execution', options).body
13
+ end
14
+
15
+ # @see https://www.bitmex.com/api/explorer/#!/Execution/Execution_getTradeHistory
16
+ def execution_trade_history(options = {})
17
+ @connection.get('/api/v1/execution/tradeHistory', options).body
18
+ end
19
+
20
+ # @see https://www.bitmex.com/api/explorer/#!/Leaderboard/Leaderboard_getName
21
+ def leaderboard_name
22
+ @connection.get('/api/v1/leaderboard/name').body
23
+ end
24
+
25
+ # @see https://www.bitmex.com/api/explorer/#!/Order/Order_getOrders
26
+ def order(options = {})
27
+ @connection.get('/api/v1/order', options).body
28
+ end
29
+
30
+ # @see https://www.bitmex.com/api/explorer/#!/Order/Order_new
31
+ def create_order(symbol, order_qty, options = {})
32
+ @connection.post('/api/v1/order', { symbol: symbol, orderQty: order_qty }.merge(options)).body
33
+ end
34
+
35
+ # @see https://www.bitmex.com/api/explorer/#!/Order/Order_cancel
36
+ def cancel_order(id, cid)
37
+ @connection.delete('/api/v1/order', {orderID: id, clOrdID: cid }).body
38
+ end
39
+
40
+ # @see https://www.bitmex.com/api/explorer/#!/Order/Order_cancelAll
41
+ def cancel_all_order
42
+ @connection.delete('/api/v1/order/all').body
43
+ end
44
+
45
+ # @see https://www.bitmex.com/api/explorer/#!/Position/Position_get
46
+ def position(options = {})
47
+ @connection.get('/api/v1/position', options).body
48
+ end
49
+
50
+ # @see https://www.bitmex.com/api/explorer/#!/Order/Order_closePosition
51
+ def close_position(symbol, price = nil)
52
+ options = {
53
+ symbol: symbol,
54
+ price: price
55
+ }.delete_if { |_, v| v.nil? }
56
+ @connection.post('/api/v1/order/closePosition', options).body
57
+ end
58
+
59
+ # @see https://www.bitmex.com/api/explorer/#!/Trade/Trade_getBucketed
60
+ def trade_bucketed(bin_size = '1m', options = {})
61
+ @connection.get('/api/v1/trade/bucketed', { binSize: bin_size }.merge(options)).body
62
+ end
63
+
64
+ # @see https://www.bitmex.com/api/explorer/#!/User/User_get
65
+ def user
66
+ @connection.get('/api/v1/user').body
67
+ end
68
+
69
+ # @see https://www.bitmex.com/api/explorer/#!/User/User_getAffiliateStatus
70
+ def user_affiliate_status
71
+ @connection.get('/api/v1/user/affiliateStatus').body
72
+ end
73
+
74
+ # @see https://www.bitmex.com/api/explorer/#!/User/User_getWallet
75
+ def user_wallet(currency = 'XBt')
76
+ @connection.get('/api/v1/user/wallet', { currency: currency }).body
77
+ end
78
+
79
+ # @see https://www.bitmex.com/api/explorer/#!/User/User_getWalletHistory
80
+ def user_wallet_history(currency = 'XBt')
81
+ @connection.get('/api/v1/user/walletHistory', { currency: currency }).body
82
+ end
83
+
84
+ # @see https://www.bitmex.com/api/explorer/#!/User/User_getWalletSummary
85
+ def user_wallet_summary(currency = 'XBt')
86
+ @connection.get('/api/v1/user/walletSummary', { currency: currency }).body
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,82 @@
1
+ module BitmexClient
2
+ module HTTP
3
+ module Public
4
+ class Client
5
+
6
+ def initialize
7
+ @connection = Connection.new(nil, nil)
8
+ end
9
+
10
+ # @see https://www.bitmex.com/api/explorer/#!/Announcement/Announcement_get
11
+ def announcement(options = {})
12
+ @connection.get('/api/v1/announcement', options).body
13
+ end
14
+
15
+ # @see https://www.bitmex.com/api/explorer/#!/Announcement/Announcement_getUrgent
16
+ def announcement_urgent(options = {})
17
+ @connection.get('/api/v1/announcement/urgent', options).body
18
+ end
19
+
20
+ # @see https://www.bitmex.com/api/explorer/#!/Funding/Funding_get
21
+ def funding(options = {})
22
+ @connection.get('/api/v1/funding', options).body
23
+ end
24
+
25
+ # @see https://www.bitmex.com/api/explorer/#!/Instrument/Instrument_get
26
+ def instrument(options = {})
27
+ @connection.get('/api/v1/instrument', options).body
28
+ end
29
+
30
+ # @see https://www.bitmex.com/api/explorer/#!/Instrument/Instrument_getActive
31
+ def instrument_active
32
+ @connection.get('/api/v1/instrument/active').body
33
+ end
34
+
35
+ # @see https://www.bitmex.com/api/explorer/#!/Insurance/Insurance_get
36
+ def insurance(options = {})
37
+ @connection.get('/api/v1/insurance', options).body
38
+ end
39
+
40
+ # @see https://www.bitmex.com/api/explorer/#!/Leaderboard/Leaderboard_get
41
+ def leaderboard(options = {})
42
+ @connection.get('/api/v1/leaderboard', options).body
43
+ end
44
+
45
+ # @see https://www.bitmex.com/api/explorer/#!/Liquidation/Liquidation_get
46
+ def liquidation(options = {})
47
+ @connection.get('/api/v1/liquidation', options).body
48
+ end
49
+
50
+ # @see https://www.bitmex.com/api/explorer/#!/OrderBook/OrderBook_getL2
51
+ def order_book_l2(symbol, depth = 25)
52
+ @connection.get('/api/v1/orderBook/L2', { symbol: symbol, depth: depth }).body
53
+ end
54
+
55
+ # @see https://www.bitmex.com/api/explorer/#!/Settlement/Settlement_get
56
+ def settlement(options = {})
57
+ @connection.get('/api/v1/settlement', options).body
58
+ end
59
+
60
+ # @see https://www.bitmex.com/api/explorer/#!/Stats/Stats_get
61
+ def stats
62
+ @connection.get('/api/v1/stats').body
63
+ end
64
+
65
+ # @see https://www.bitmex.com/api/explorer/#!/Stats/Stats_history
66
+ def stats_history
67
+ @connection.get('/api/v1/stats/history').body
68
+ end
69
+
70
+ # @see https://www.bitmex.com/api/explorer/#!/Stats/Stats_historyUSD
71
+ def stats_history_usd
72
+ @connection.get('/api/v1/stats/historyUSD').body
73
+ end
74
+
75
+ # @see https://www.bitmex.com/api/explorer/#!/Trade/Trade_get
76
+ def trade(options = {})
77
+ @connection.get('/api/v1/trade', options).body
78
+ end
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,3 @@
1
+ module BitmexClient
2
+ VERSION = '0.2.0'
3
+ end
@@ -0,0 +1,27 @@
1
+ require 'faraday'
2
+ require 'active_support/time'
3
+
4
+ module FaradayMiddleware
5
+ class Authentication < Faraday::Middleware
6
+
7
+ def initialize(app, key, secret)
8
+ super(app)
9
+ @key = key
10
+ @secret = secret
11
+ end
12
+
13
+ def call(env)
14
+ return @app.call(env) if @key.nil? || @secret.nil?
15
+
16
+ timestamp = (Time.now - 600).to_i.to_s
17
+ method = env[:method].to_s.upcase
18
+ path = env[:url].path + (env[:url].query ? '?' + env[:url].query : '')
19
+ body = env[:body] || ''
20
+ signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @secret, method + path + timestamp + body)
21
+ env[:request_headers]['api-expires'] = timestamp
22
+ env[:request_headers]['api-key'] = @key if @key
23
+ env[:request_headers]['api-signature'] = signature
24
+ @app.call env
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,63 @@
1
+ require 'faraday'
2
+
3
+ module FaradayMiddleware
4
+ class LoudLogger < Faraday::Middleware
5
+ extend Forwardable
6
+
7
+ def_delegators :@logger, :debug, :info, :warn, :error, :fatal
8
+ def initialize(app, options = {})
9
+ @app = app
10
+ @logger = options.fetch(:logger) {
11
+ require 'logger'
12
+ ::Logger.new($stdout)
13
+ }
14
+ end
15
+
16
+ def call(env)
17
+ start_time = Time.now
18
+ info { request_info(env) }
19
+ debug { request_debug(env) }
20
+ @app.call(env).on_complete do
21
+ end_time = Time.now
22
+ response_time = end_time - start_time
23
+ info { response_info(env, response_time) }
24
+ debug { response_debug(env) }
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ def request_info(env)
31
+ "Started %s request to: %s" % [ env[:method].to_s.upcase, env[:url] ]
32
+ end
33
+
34
+ def response_info(env, response_time)
35
+ "Response from %s; Status: %d; Time: %.1fms" % [ env[:url], env[:status], (response_time * 1_000.0) ]
36
+ end
37
+
38
+ def request_debug(env)
39
+ debug_message("Request", env[:request_headers], env[:body])
40
+ end
41
+
42
+ def response_debug(env)
43
+ debug_message("Response", env[:response_headers], env[:body])
44
+ end
45
+
46
+ def debug_message(name, headers, body)
47
+ <<-MESSAGE.gsub(/^ +([^ ])/m, '\\1')
48
+ #{name} Headers:
49
+ ----------------
50
+ #{format_headers(headers)}
51
+ #{name} Body:
52
+ -------------
53
+ #{body}
54
+ MESSAGE
55
+ end
56
+
57
+ def format_headers(headers)
58
+ length = headers.map {|k,v| k.to_s.size }.max
59
+ headers.map { |name, value| "#{name.to_s.ljust(length)} : #{value}" }.join("\n")
60
+ end
61
+
62
+ end
63
+ end
@@ -0,0 +1,58 @@
1
+ require 'faraday'
2
+
3
+ module FaradayMiddleware
4
+ class RaiseHttpException < Faraday::Middleware
5
+
6
+ def initialize(app)
7
+ super app
8
+ @parser = nil
9
+ end
10
+
11
+ def call(env)
12
+ @app.call(env).on_complete do |response|
13
+ case response[:status].to_i
14
+ when 400
15
+ raise Bitmex::BadRequest, error_message_400(response)
16
+ when 404
17
+ raise Bitmex::NotFound, error_message_400(response)
18
+ when 429
19
+ raise Bitmex::TooManyRequests, error_message_400(response)
20
+ when 500
21
+ raise Bitmex::InternalServerError, error_message_500(response, "Something is technically wrong.")
22
+ when 502
23
+ raise Bitmex::BadGateway, error_message_500(response, "The server returned an invalid or incomplete response.")
24
+ when 503
25
+ raise Bitmex::ServiceUnavailable, error_message_500(response, "Bitmex is rate limiting your requests.")
26
+ when 504
27
+ raise Bitmex::GatewayTimeout, error_message_500(response, "504 Gateway Time-out")
28
+ end
29
+ end
30
+ end
31
+
32
+ private
33
+
34
+ def error_message_400(response)
35
+ "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:status]}#{error_body(response[:body])}"
36
+ end
37
+
38
+ def error_body(body)
39
+ # body gets passed as a string, not sure if it is passed as something else from other spots?
40
+ if not body.nil? and not body.empty? and body.kind_of?(String)
41
+ # removed multi_json thanks to wesnolte's commit
42
+ body = ::JSON.parse(body)
43
+ end
44
+
45
+ if body.nil?
46
+ nil
47
+ elsif body['meta'] and body['meta']['error_message'] and not body['meta']['error_message'].empty?
48
+ ": #{body['meta']['error_message']}"
49
+ elsif body['error_message'] and not body['error_message'].empty?
50
+ ": #{body['error_type']}: #{body['error_message']}"
51
+ end
52
+ end
53
+
54
+ def error_message_500(response, body=nil)
55
+ "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{[response[:status].to_s + ':', body].compact.join(' ')}"
56
+ end
57
+ end
58
+ end
metadata ADDED
@@ -0,0 +1,119 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bitmex_client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - markgeek
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-12-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.15.4
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.15.4
27
+ - !ruby/object:Gem::Dependency
28
+ name: faraday_middleware
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.12.2
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.12.2
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 1.17.1
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 1.17.1
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 12.3.1
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 12.3.1
69
+ description: Bitmex API wrapper.
70
+ email:
71
+ - mark.geek.lee@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - CODE_OF_CONDUCT.md
78
+ - Gemfile
79
+ - Gemfile.lock
80
+ - LICENSE.txt
81
+ - README.md
82
+ - Rakefile
83
+ - bin/console
84
+ - bin/setup
85
+ - bitmex_client.gemspec
86
+ - lib/bitmex_client.rb
87
+ - lib/bitmex_client/configuration.rb
88
+ - lib/bitmex_client/http.rb
89
+ - lib/bitmex_client/http/private.rb
90
+ - lib/bitmex_client/http/public.rb
91
+ - lib/bitmex_client/version.rb
92
+ - lib/faraday/authentication.rb
93
+ - lib/faraday/loud_logger.rb
94
+ - lib/faraday/raise_http_exception.rb
95
+ homepage: https://github.com/markgeek/bitmex_client
96
+ licenses:
97
+ - MIT
98
+ metadata: {}
99
+ post_install_message:
100
+ rdoc_options: []
101
+ require_paths:
102
+ - lib
103
+ required_ruby_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ requirements: []
114
+ rubyforge_project:
115
+ rubygems_version: 2.6.11
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: Bitmex API wrapper.
119
+ test_files: []