Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
78 commits
Select commit Hold shift + click to select a range
3417869
Imports
Oct 7, 2021
4a4b32c
Preparations for Vers. 10 (1)
Dec 24, 2021
8edea5f
Update Messages and ServerVersions
Aug 12, 2022
7c353ae
Adapt ContractData Message
Aug 12, 2022
edafd55
Tests of ib-api are passing
Aug 12, 2022
e097b31
Updates in incoming ticks-protocol
Aug 25, 2022
66a853f
Merge branch 'ver_10' of https://github.com/ib-ruby/ib-api into ver_10
Aug 25, 2022
b0f0a38
class extentions need to be required relative
topofocus Dec 8, 2022
5540353
Adaption of request_marketdata to recent TWS-Versions
Jan 15, 2023
cd1e103
Upate for Hostorical- and Realtimedata in V10.19ff
topofocus Jan 22, 2023
6a5c0de
Update connection.rb
moritzkork Feb 10, 2023
d8f332d
Merge pull request #30 from moritzkork/patch-2
topofocus Feb 10, 2023
6736df6
update connection.rb, refactoring method process_messages
topofocus Feb 16, 2023
91c3f90
update server-versions
Feb 28, 2023
17dd5b1
update server-versions, inserted necessary kommas
Feb 28, 2023
f7d5108
correct server-versions
topofocus Mar 9, 2023
ff184b6
refactoring of class-extensions (with tests)
topofocus Apr 1, 2024
2a6cc6b
Refacturing: IBSupport --> IB::Support
topofocus Apr 1, 2024
3d89c2d
Separation of Socket & PrepareData, rename IBSocket to IB::Socket
topofocus Apr 2, 2024
b776491
Apply Zeitwerk
topofocus Apr 4, 2024
e35d67c
completed zeitwerk integration
topofocus Apr 4, 2024
53a24e7
Introducing plugins to extend the functionality
topofocus Apr 11, 2024
01e3ef0
Update README.md
topofocus Apr 11, 2024
fd2ccb8
Update README.md
topofocus Apr 11, 2024
dc13dd1
including connection tools and managed-accounts plugins
topofocus Apr 12, 2024
d3b138b
Typo while including connection-tools
topofocus Apr 12, 2024
6527aa1
Documentation for plugins
topofocus Apr 12, 2024
363cd9b
Including "roll" plugin for Options and Futures. Redesign of Option.n…
topofocus Apr 23, 2024
bb9bee9
IB::Straddle:: force verification of contracts
topofocus Apr 23, 2024
3ee1723
Including plugins 'advance-account', 'auto-adjust', 'managed-accounts…
topofocus Apr 26, 2024
92ba09a
**Testing of Order parameters **
topofocus Apr 27, 2024
67897c0
Update to server-versions, premilary changes to order and open_order
topofocus Apr 29, 2024
eaf7fa5
Open Order adjustments
topofocus Jun 3, 2024
e60abfd
writes socket messages to debug log
psmandzich May 5, 2024
2810268
serialize only underlying attributes within class
psmandzich May 5, 2024
5e00e05
make known_servers a contant to be callable in message generation
psmandzich May 5, 2024
a22301e
apply latest place_order api structure from python code
psmandzich May 5, 2024
4685833
Tests for managed accounts, verify and auto-adjust plugins
topofocus Jun 14, 2024
b24ab24
Adaption of OpenOrder to V10, incl. tests
topofocus Jun 18, 2024
df647bc
Introducing server_version methods for models and messages,
topofocus Jun 20, 2024
d837d2c
include plugin »symbols«
topofocus Jun 20, 2024
02b6082
Limit-order test with order-serializers
topofocus Jun 20, 2024
32df99a
Tests on OrderPrototypes
topofocus Jun 21, 2024
251f321
Added Pegged2Stock OrderPrototype
topofocus Jun 22, 2024
475e892
improved methods Order#to_human + Order#as_table
topofocus Jun 23, 2024
7ac97cb
Refactoring of IB::Contract
topofocus Jun 24, 2024
99067bc
Improved Stock#merge functionality
topofocus Jun 24, 2024
606475f
commissioning of /bin/console
topofocus Jun 24, 2024
4537aa7
Update to README
topofocus Jun 24, 2024
2a26d65
New Order-Prototype: Adaptive,
topofocus Jun 26, 2024
d8f72d9
Adaption of Option/Future#roll and Calendar SpreadPrototype to V10
topofocus Jun 27, 2024
5e1c0fe
Refactoring of serialisation of combo-legs in the order-process
topofocus Jun 28, 2024
2735308
Implementation of a simple state machine, fitting of plugins
topofocus Jul 8, 2024
013bb7c
refacturing of equality of contracts (def ==), receiving tick-prices
topofocus Jul 10, 2024
1c501d5
Minor updates to order & co
topofocus Jul 12, 2024
99d270a
retab
topofocus Jul 16, 2024
5064701
Order#place: ensure that only con_di and exchange are transmitted if …
topofocus Jul 24, 2024
ebf4caa
removing debug related outputs
topofocus Jul 25, 2024
cbd26f2
Fixing fetching market_price plugin for spreads and complex contracts
topofocus Aug 2, 2024
ab5b27d
Fixing Test for OptenPosition Message
topofocus Aug 2, 2024
11ce517
Transfer to new host
topofocus Oct 22, 2024
6177759
Added BigDecimal/util to provide 'to_d' method to numeric and string …
topofocus Oct 24, 2024
bd67406
Option greeks: contract.greek.greeks? is satisfied, if delta, gamma a…
topofocus Oct 25, 2024
f44a395
Connection.reconnect
topofocus Oct 28, 2024
b64ae0a
Fixed account.preview(order) and order.check_margin(treshold)
topofocus Nov 5, 2024
4b9d79c
Mark all Workflow-State-Methods as `protected
topofocus Nov 17, 2024
cf40645
Reimplementing RawMessageParser (Brandon Coleman)
topofocus Nov 19, 2024
b5907f5
Updates/Fixes to Spread-Prototype StockSpread
topofocus Nov 21, 2024
70c9bb8
Adapted Spread-Prototypes to V-10, incl. Specs
topofocus Nov 21, 2024
453fdee
Fixed using Spreads (IB::Bag) as contract in orders
topofocus Nov 22, 2024
15cea6c
Enabling usage of `as_table` for incompletely initialized contracts
topofocus Nov 24, 2024
dab5dc0
Option#next_expiry raises IB::LoadError if no contract found in the …
topofocus Nov 27, 2024
7b4aadb
Updated Order-Conditions (testing required)
topofocus Apr 7, 2025
05fcbd9
Default time-zones for contracts; using time-zones to fetch historica…
topofocus Apr 28, 2025
e370fd1
Contract#verify raises an error if the connection is interrupted
topofocus May 1, 2025
c0e5f58
make Contract#verify more robust.
topofocus May 5, 2025
80a2d4b
Disable verifying length of message buffer
topofocus May 7, 2025
4402616
Contract#multiplier needs to be decimal for adjustment to crypto
topofocus Oct 7, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
*.gem
*.rbc
*.swp
*.swo
/.config
/coverage/
/InstalledFiles
Expand Down
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ gemspec

gem 'rspec'
gem 'rspec-its'
gem 'rspec-given'
gem 'rspec-collection_matchers'
gem 'guard'
gem 'guard-rspec'
104 changes: 0 additions & 104 deletions Gemfile.lock

This file was deleted.

79 changes: 34 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
# ib-api
Ruby interface to Interactive Brokers' TWS API

Reimplementation of the basic functions of ib-ruby
Reimplementation of ib-ruby

---
__STATUS: Preparing for a new GEM-Release, scheduled for July__ (delayed to August)
__STATUS: Gem-Release is still pending

---


__Documentation: [https://ib-ruby.github.io/ib-doc/](https://ib-ruby.github.io/ib-doc/)__ (_work in progress_)

----
`ib-ruby` offers a modular access to the TWS-API-Interface of Interactive Brokers.

`ib-api` provides a simple interface to low-level TWS API-calls.
`ib-api` offers a modular access to the TWS-API-Interface of Interactive Brokers.

----

Expand All @@ -23,7 +22,7 @@ Install in the usual way
$ gem install ib-api
```

In its plain vanilla usage, it just exchanges messages with the TWS. Any response is stored in the `recieved-Array`.
In its plain vanilla usage, it just exchanges messages with the TWS. Any response is stored in the `received-array`.

It needs just a few lines of code to place an order

Expand Down Expand Up @@ -52,53 +51,43 @@ puts ib.recieved[:OrderStatus].to_human

```

##### User-specific Actions
Besides storing any TWS-response in an array, callbacks are implemented.
## Plugins

**IB-API** ships with simple plugins to facilitate automations

The user subscribes to a certain response and defines the actions in a typically ruby manner. These actions
can be defined globaly
```ruby
ib = IB::Connection.new do |tws|
# Subscribe to TWS alerts/errors and order-related messages
tws.subscribe(:Alert, :OpenOrder, :OrderStatus, :OpenOrderEnd) { |msg| puts msg.to_human }
end
require 'ib-api'
# connect with default parameters
ib = IB::Connection.new do | c |
c.activate_plugin "verify"
end

g = IB::Stock.new symbol: 'GE'
puts g.verify.first.attributes
{:symbol=>"GE", :sec_type=>"STK", :last_trading_day=>"", :strike=>0.0, :right=>"", :exchange=>"SMART", :currency=>"USD", :local_symbol=>"GE", :trading_class=>"GE", :con_id=>498843743, :multiplier=>0, :primary_exchange=>"NYSE", }
```

or occationally
Currently implemented plugins

* connection-tools: ensure that a connection is established and active
* verify: get contract details from the tws
* symbols: use predefined symbols
* managed-accounts: fetch and organize account- and portfoliovalues
* advanced-account: perform account-based previewing, opening, modifying and closing of Positions
* process-orders: account-based bookkeeping of orders
* auto-adjust: properly adjust the orderprice to the next valid min-tick of the contract
* market-price: fetch the current market-price of a contract
* eod: retrieve EOD-Data for the given contract
* greeks: read current option greeks
* roll: easy rolling of futures and options
* option-chain: build option-chains for given strikes and expiries
* spread-prototypes: create limit, stop, market, etc. orders through prototypes
* probability-of-expiring: calculate the probability of expiring for the option-contract


```ruby
# first define actions
q = Queue.new # Initialize as Queue
request_id = nil # declare variable
a = ib.subscribe(:Alert, :ContractData, :ContractDataEnd ) do |msg|
case msg
when Messages::Incoming::Alert
q.close if msg.code == 200 # No security found
when Messages::Incoming::ContractData # security returned
q.push msg.contract if msg.request_id == request_id
when Messages::Incoming::ContractDataEnd
q.close if msg.request_id == request_id
end # case
end
# perform request
request_id = ib.send_message :RequestContractData, :contract => Stock.new(symbol: 'T')

while contract = q.pop
puts contract.as_table
end
┌───────┬────────┬──────────┬──────────┬────────┬────────────┬───────────────┬───────┬────────┬──────────┐
│ │ symbol │ con_id │ exchange │ expiry │ multiplier │ trading-class │ right │ strike │ currency │
╞═══════╪════════╪══════════╪══════════╪════════╪════════════╪═══════════════╪═══════╪════════╪══════════╡
│ Stock │ T │ 37018770 │ SMART │ │ │ T │ │ │ USD │
└───────┴────────┴──────────┴──────────┴────────┴────────────┴───────────────┴───────┴────────┴──────────┘

ib.unsubscribe a # release subscriptions

```
## Minimal TWS-Version

`ib-api` is tested via the _stable IB-Gateway_ (Version 9.72) and should work with any current tws-installation.
`ib-api` is tested via the _stable IB-Gateway_ (Version 10.19) and should work with any current tws-installation.

## Tests

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
972.5
10.19.1
8 changes: 8 additions & 0 deletions api.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,12 @@ Gem::Specification.new do |spec|
spec.add_dependency 'activemodel'
spec.add_dependency 'ox'
spec.add_dependency 'terminal-table'
spec.add_dependency 'zeitwerk'
spec.add_dependency 'workflow', '~> 3.1'
# spec.add_dependency 'dry-schema'
# spec.add_dependency 'dry-struct'
# spec.add_dependency 'dry-core'
# spec.add_dependency 'dry-configurable'
# spec.add_dependency 'dry-monads' # future use

end
73 changes: 39 additions & 34 deletions bin/console
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env ruby
### loads the active-orient environment
### loads the active-orient environment
### and starts an interactive shell
###
### Parameter: t)ws | g)ateway (or number of port ) Default: Gateway ,
Expand All @@ -17,9 +17,9 @@ class Array
# i.e
#
# 2.5.0 :006 > C.received[:OpenOrder].local_id
# => [16, 17, 21, 20, 19, 8, 7]
# => [16, 17, 21, 20, 19, 8, 7]
# 2.5.0 :007 > C.received[:OpenOrder].contract.to_human
# => ["<Bag: IECombo SMART USD legs: >", "<Stock: GE USD>", "<Stock: GE USD>", "<Stock: GE USD>", "<Stock: GE USD>", "<Stock: WFC USD>", "<Stock: WFC USD>"]
# => ["<Bag: IECombo SMART USD legs: >", "<Stock: GE USD>", "<Stock: GE USD>", "<Stock: GE USD>", "<Stock: GE USD>", "<Stock: WFC USD>", "<Stock: WFC USD>"]
#
# its included only in the console, for inspection purposes

Expand All @@ -31,61 +31,66 @@ class Array
end
end # Array

class Object
def inspect
respond_to?(:to_human) ? to_human : super
end
end

# read items from console.yml
read_yml = -> (key) do
# read items from console.yml
read_yml = -> (key) do
YAML::load_file( File.expand_path('../console.yml',__FILE__))[key]
end


puts
puts ">> IB-Core Interactive Console <<"
puts
puts ">> IB-API Interactive Console <<"
puts '-'* 45
puts
puts
puts "Namespace is IB ! "
puts
puts '-'* 45
include IB
require 'irb'
client_id = ARGV[1] || read_yml[:client_id]
specified_port = ARGV[0] || 'Gateway'
port = case specified_port
when Integer
specified_port # just use the number
specified_host = ARGV[0] || 'Gateway'
host = case specified_host
when /^[gG]/
read_yml[:gateway]
when /^[Tt]/
read_yml[:tws]
else
raise "Specify target from console.yml: `g|t` instead of #{specified_host}"
end

ARGV.clear

## The Block takes instructions which are executed after initializing all instance-variables
## and prior to the connection-process
## Here we just subscribe to some events
C = Connection.new client_id: client_id, port: port do |c| # future use__ , optional_capacities: "+PACEAPI" do |c|

c.subscribe( :ContractData, :BondContractData) { |msg| c.logger.info { msg.contract.to_human } }
c.subscribe( :Alert, :ContractDataEnd, :ManagedAccounts, :OrderStatus ) {| m| c.logger.info { m.to_human } }
c.subscribe( :PortfolioValue, :AccountValue, :OrderStatus, :OpenOrderEnd, :ExecutionData ) {| m| c.logger.info { m.to_human }}
# c.subscribe :ManagedAccounts do |msg|
# puts "------------------------------- Managed Accounts ----------------------------------"
# puts "Detected Accounts: #{msg.accounts.account.join(' -- ')} "
# puts
# end
C = Connection.new client_id: client_id, host: host
C.logger.level = Logger::WARN

C.subscribe(:Alert){ |m| puts "A: "+ m.message }
C.subscribe(:AccountUpdateTime){ }

C.received = true
C.activate_plugin :connection_tools, :symbols, :market_price,
"order-prototypes", "spread-prototypes",
"advanced_account", 'process_orders'
C.logger.level = Logger::INFO
puts C.workflow_state
C.get_account_data
C.request_open_orders
C.logger.level = Logger::ERROR
puts "Connection established on #{host}"

c.subscribe( :OpenOrder){ |msg| "Open Order detected and stored: C.received[:OpenOrders] " }
end
#C.logger.level = Logger::FATAL
unless C.received[:OpenOrder].blank?
puts "------------------------------- OpenOrders ----------------------------------"
puts C.received[:OpenOrder].to_human.join "\n"
puts "---------------------------------------- OpenOrders -------------------------------------------"
puts C.clients.map{ |c| c.orders.map &:to_human }.flatten.join("\n")
end
puts "Connection established on Port #{port}, client_id #{client_id} used"
puts ""
puts Terminal::Table.new title: 'Active Plugins',
rows: C.plugins.delete_if{ |x| x =~ /\// }.sort.each_slice(4),
style: { border: :unicode }
puts
puts "----> C points to the connection-instance"
puts
puts "some basic Messages are subscribed and accordingly displayed"
puts '-'* 45

IRB.start(__FILE__)
4 changes: 2 additions & 2 deletions bin/console.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
:gateway: 4002
:tws: 7496
:gateway: "localhost:4002"
:tws: "tws:7496"
:client_id: 2000
Loading