Skip to content

Commit

Permalink
Merge pull request #4 from ib-ruby/technical_analysis
Browse files Browse the repository at this point in the history
Version 1.1
  • Loading branch information
topofocus authored May 16, 2021
2 parents 4d55ca7 + 3b0f0be commit ac9eb46
Show file tree
Hide file tree
Showing 16 changed files with 306 additions and 318 deletions.
8 changes: 3 additions & 5 deletions bin/console
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ read_yml = -> (key) do
puts "Namespace is IB ! "
puts
puts '-'* 45
include LogDev
include IB
require 'irb'
client_id = ARGV[1] || read_yml[:client_id]
Expand All @@ -63,16 +62,15 @@ read_yml = -> (key) do
end

ARGV.clear
logger = default_logger # Logger.new STDOUT

## 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| logger.info { msg.contract.to_human } }
c.subscribe( :Alert, :ContractDataEnd, :ManagedAccounts, :OrderStatus ) {| m| logger.info { m.to_human } }
c.subscribe( :PortfolioValue, :AccountValue, :OrderStatus, :OpenOrderEnd, :ExecutionData ) {| m| logger.info { m.to_human }}
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(' -- ')} "
Expand Down
14 changes: 8 additions & 6 deletions bin/gateway
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ LogLevel = Logger::DEBUG ##INFO # DEBUG # ERROR
#require File.expand_path(File.dirname(__FILE__) + "/../config/boot")

require 'ib-gateway'
require 'ib/verify'
require 'ib/market-price'
require 'ib/option-chain'
require 'ib/eod'
Expand Down Expand Up @@ -48,7 +49,6 @@ read_yml = -> (key) do
puts
puts "Namespace is IB ! "
puts
puts '-'* 45

include IB
require 'irb'
Expand All @@ -74,14 +74,16 @@ read_yml = -> (key) do
## and prior to the connection-process
## Here we just subscribe to some events
begin
G = Gateway.new get_account_data: true, serial_array: true,
client_id: client_id, port: port, logger: logger,
watchlists: [:Spreads, :BuyAndHold]
G = Gateway.new get_account_data: true, serial_array: true,
client_id: client_id, port: port , logger: logger,
watchlists: [:Spreads, :Stillhalter, :BuyAndHold]
rescue IB::TransmissionError => e
puts "E: #{e.inspect}"
end

C = G.tws

C.subscribe(:TickGeneric, :TickOption, :TickRequestParameters, :MarketDataType, :TickString, :TickSize ){|x| x }
unless C.received[:OpenOrder].blank?
puts "------------------------------- OpenOrders ----------------------------------"
puts C.received[:OpenOrder].to_human.join "\n"
Expand All @@ -98,7 +100,7 @@ read_yml = -> (key) do

begin
IRB.start(__FILE__)
rescue IB::OrderAttributeError => e
puts "OrderAtttributeerror"
#rescue IB::OrderAttributeError => e
# puts "OrderAtttribute ERROR"
end

1 change: 1 addition & 0 deletions ib-extensions.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Gem::Specification.new do |spec|


spec.add_dependency "ox"
spec.add_dependency "ib-api", "~> 972.4"
spec.add_development_dependency "bundler", "~> 2.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency 'rspec-collection_matchers'
Expand Down
4 changes: 3 additions & 1 deletion lib/ib/alerts/base-alert.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ def self.alert_134 msg
# acts as prototype for any generated method
#require 'active_support'

mattr_accessor :logger

def self.method_missing( method_id, msg , *args, &block )
if msg.is_a? IB::Messages::Incoming::Alert
Expand All @@ -62,6 +61,9 @@ def self.method_missing( method_id, msg , *args, &block )


class << self
def logger
IB::Connection.logger || IB::Gateway.logger
end

def ignore_alert *codes
codes.each do |n|
Expand Down
11 changes: 4 additions & 7 deletions lib/ib/eod.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def eod start:nil, to: Date.today, duration: nil , what: :trades
recieved = Queue.new
r = nil
# the hole response is transmitted at once!
a= tws.subscribe(IB::Messages::Incoming::HistoricalData) do |msg|
a = tws.subscribe(IB::Messages::Incoming::HistoricalData) do |msg|
if msg.request_id == con_id
# msg.results.each { |entry| puts " #{entry}" }
r = block_given? ? msg.results.map{|y| yield y} : msg.results
Expand Down Expand Up @@ -134,17 +134,14 @@ def eod start:nil, to: Date.today, duration: nil , what: :trades

Timeout::timeout(5) do # max 5 sec.
sleep 0.1
last_time = recieved.pop # blocks until a message is ready on the queue
loop do
sleep 0.1
break if recieved.closed? || recieved.empty? # finish if data received
end
recieved.pop # blocks until a message is ready on the queue
break if recieved.closed? || recieved.empty? # finish if data received
end
tws.unsubscribe a
tws.unsubscribe b

r # the collected result

end
end # def
end # class
end # module
Expand Down
2 changes: 1 addition & 1 deletion lib/ib/extensions/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module IB
module Extensions
VERSION = "1.0"
VERSION = "1.1"
end
end
38 changes: 14 additions & 24 deletions lib/ib/gateway.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,18 @@ module IB
=end

class Gateway
class Gateway

include LogDev # provides default_logger
include AccountInfos # provides Handling of Account-Data provided by the tws
include OrderHandling
include Support::Logging # provides default_logger
include AccountInfos # provides Handling of Account-Data provided by the tws
include OrderHandling

# include GWSupport # introduces update_or_create, first_or_create and intercept to the Array-Class
# include GWSupport # introduces update_or_create, first_or_create and intercept to the Array-Class

# from active-support. Add Logging at Class + Instance-Level
mattr_accessor :logger
# similar to the Connection-Class: current represents the active instance of Gateway
mattr_accessor :current
mattr_accessor :tws
# from active-support. Add Logging at Class + Instance-Level
# similar to the Connection-Class: current represents the active instance of Gateway
mattr_accessor :current
mattr_accessor :tws



Expand All @@ -100,16 +99,16 @@ def initialize port: 4002, # 7497,
connect: true,
get_account_data: false,
serial_array: false,
logger: default_logger,
logger: nil,
watchlists: [] , # array of watchlists (IB::Symbols::{watchlist}) containing descriptions for complex positions
**other_agruments_which_are_ignored,
&b

host, port = (host+':'+port.to_s).split(':')

self.logger = logger
logger.info { '-' * 20 +' initialize ' + '-' * 20 }
logger.tap{|l| l.progname = 'Gateway#Initialize' }
self.class.configure_logger logger

self.logger.info { '-' * 20 +' initialize ' + '-' * 20 }

@connection_parameter = { received: serial_array, port: port, host: host, connect: false, logger: logger, client_id: client_id }

Expand All @@ -124,8 +123,6 @@ def initialize port: 4002, # 7497,
Thread.report_on_exception = true
# https://blog.bigbinary.com/2018/04/18/ruby-2-5-enables-thread-report_on_exception-by-default.html
Gateway.current = self
# establish Alert-framework
IB::Alert.logger = logger
# initialise Connection without connecting
prepare_connection &b
# finally connect to the tws
Expand Down Expand Up @@ -182,7 +179,6 @@ def update_local_order order
def connect maximal_count_of_retry=100

i= -1
logger.progname = 'Gateway#connect'
begin
tws.connect
rescue Errno::ECONNREFUSED => e
Expand Down Expand Up @@ -229,7 +225,6 @@ def connect maximal_count_of_retry=100


def reconnect
logger.progname = 'Gateway#reconnect'
if tws.present?
disconnect
sleep 1
Expand All @@ -239,7 +234,6 @@ def reconnect
end

def disconnect
logger.progname = 'Gateway#disconnect'

tws.disconnect if tws.present?
@accounts = [] # each{|y| y.update_attribute :connected, false }
Expand All @@ -256,7 +250,6 @@ def disconnect
=end

def send_message what, *args
logger.tap{|l| l.progname = 'Gateway#SendMessage' }
begin
if check_connection
tws.send_message what, *args
Expand All @@ -275,7 +268,6 @@ def send_message what, *args

def cancel_order *orders

logger.tap{|l| l.progname = 'Gateway#CancelOrder' }

orders.compact.each do |o|
local_id = if o.is_a? (IB::Order)
Expand Down Expand Up @@ -345,7 +337,7 @@ def account_data account_or_id=nil

def prepare_connection &b
tws.disconnect if tws.is_a? IB::Connection
self.tws = IB::Connection.new **@connection_parameter
self.tws = IB::Connection.new **@connection_parameter.merge( logger: self.logger )
@accounts = @local_orders = Array.new

# prepare Advisor-User hierachy
Expand Down Expand Up @@ -378,7 +370,6 @@ def initialize_managed_accounts
end

man_id = tws.subscribe( :ManagedAccounts ) do |msg|
logger.progname = 'Gateway#InitializeManagedAccounts'
if @accounts.empty?
# just validate the message and put all together into an array
@accounts = msg.accounts_list.split(',').map do |a|
Expand All @@ -396,7 +387,6 @@ def initialize_alerts

tws.subscribe( :AccountUpdateTime ){| msg | logger.debug{ msg.to_human }}
tws.subscribe(:Alert) do |msg|
logger.progname = 'Gateway#Alerts'
logger.debug " ----------------#{msg.code}-----"
# delegate anything to IB::Alert
IB::Alert.send("alert_#{msg.code}", msg )
Expand Down
1 change: 0 additions & 1 deletion lib/ib/gateway/account-infos.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ module AccountInfos
=end
def get_account_data *accounts, watchlists: []

logger.progname = 'Gateway#get_account_data'

@account_data_subscription ||= subscribe_account_updates

Expand Down
Loading

0 comments on commit ac9eb46

Please sign in to comment.