Skip to content

Commit

Permalink
leishman#3 - Better nonce generation; no more sleeping
Browse files Browse the repository at this point in the history
  • Loading branch information
Inkybro committed Mar 14, 2014
1 parent d3ba4eb commit 1d90236
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
15 changes: 11 additions & 4 deletions lib/kraken_ruby/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ def trade_balance(assets=nil, opts={})
post_private 'TradeBalance', opts
end

def open_orders(opts={})
def open_orders(trades=nil, opts={})
if trades
raise ArgumentError if !trades.is_a?(Boolean)
opts[:trades] = trades
end
post_private 'OpenOrders', opts
end

Expand Down Expand Up @@ -148,8 +152,6 @@ def add_order(opts={})
private

def post_private(method, opts={})
sleep 0.3

opts['nonce'] = nonce
post_data = encode_options(opts)

Expand All @@ -164,7 +166,12 @@ def post_private(method, opts={})
end

def nonce
Time.now.to_i.to_s.ljust(16,'0')
# no need to sleep, pretty sure... just needed to take into account
# time on a smaller scale (hence Time.now.to_f * 10000). apparently
# .to_f on Time instances returns a fractional timestamp.
# this all ensures the numbers are increasing quickly enough to
# constitute a valid nonce.
(Time.now.to_f*100000).to_i.to_s.ljust(16,'0')
end

def encode_options(opts)
Expand Down
34 changes: 33 additions & 1 deletion spec/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
# Additionally, it makes the spec suite run MUCH faster, since
# a nonce is not necessary for public requests.

# ^ SECOND FOLLOWUP TO THAT:
# i wrote a better nonce generator, that takes into account
# time on much smaller scales (perhaps like 1/1000th of a second).
# it seems to work fine.

#sleep 0.3 # to prevent rapidly pinging the Kraken server
end

Expand Down Expand Up @@ -322,7 +327,34 @@
expect { kraken.trade_balance([]) }.to raise_error(ArgumentError)
end
end
end
end

context "using open_orders()" do
context "given no input" do
it "gets a list of the user's open orders" do
result = kraken.open_orders
expect(result).to be_instance_of(Hash)
expect(result[:open]).to be_instance_of(Hash)
end
end

context "given valid input for 'trades'" do
it "gets a list of the user's open orders" do
result = kraken.open_orders(true)
expect(result).to be_instance_of(Hash)
expect(result[:open]).to be_instance_of(Hash)
end
end

context "given invalid input for 'trades'" do
it "throws an ArgumentError exception" do
expect { kraken.open_orders(1234) }.to raise_error(ArgumentError)
expect { kraken.open_orders(1234.56) }.to raise_error(ArgumentError)
expect { kraken.open_orders({}) }.to raise_error(ArgumentError)
expect { kraken.open_orders([]) }.to raise_error(ArgumentError)
end
end
end
end

end

0 comments on commit 1d90236

Please sign in to comment.