18
18
from trader .cli .cli_renderer import CliRenderer
19
19
from trader .cli .command_line import common_options , default_config
20
20
from trader .common .exceptions import TraderConnectionException , TraderException
21
- from trader .common .helpers import contract_from_dict , DictHelper
21
+ from trader .common .helpers import contract_from_dict , DictHelper , ListHelper
22
22
from trader .common .logging_helper import LogLevels , set_log_level , setup_logging
23
23
from trader .common .reactivex import SuccessFail
24
24
from trader .container import Container as TraderContainer
25
25
from trader .data .data_access import DictData , PortfolioSummary , TickData , TickStorage
26
26
from trader .data .universe import SecurityDefinition , Universe , UniverseAccessor
27
27
from trader .listeners .ibreactive import IBAIORx , WhatToShow
28
- from trader .messaging .clientserver import RPCClient
28
+ from trader .messaging .clientserver import consume , RPCClient
29
29
from trader .messaging .trader_service_api import TraderServiceApi
30
30
from trader .objects import BarSize , TradeLogSimple
31
31
from trader .trading .strategy import Strategy , StrategyConfig , StrategyState
32
- from typing import Any , Dict , List , Optional , Tuple , Union
32
+ from typing import Any , Callable , cast , Coroutine , Dict , List , Optional , Tuple , TypeVar , Union
33
33
34
34
import asyncio
35
35
import click
65
65
zmq_server_address = container .config ()['zmq_rpc_server_address' ],
66
66
zmq_server_port = container .config ()['zmq_rpc_server_port' ],
67
67
error_table = error_table ,
68
- timeout = 10 ,
68
+ timeout = 5 ,
69
69
)
70
70
71
71
renderer = CliRenderer ()
@@ -90,7 +90,7 @@ def closure(message, color=None, nl=True, err=False, **styles):
90
90
91
91
92
92
def connect ():
93
- if not remoted_client .connected :
93
+ if not remoted_client .is_setup :
94
94
asyncio .get_event_loop ().run_until_complete (remoted_client .connect ())
95
95
96
96
@@ -116,67 +116,68 @@ def setup_cli(cli_renderer: CliRenderer):
116
116
117
117
return remoted_client , cli_client_id
118
118
119
- def resolve_conid_to_security_definition_db (
120
- conid : int ,
119
+ def resolve_symbol_arctic (
120
+ symbol : Union [ int , str ] ,
121
121
arctic_server_address : str ,
122
122
arctic_universe_library : str ,
123
123
) -> Optional [SecurityDefinition ]:
124
124
accessor = UniverseAccessor (arctic_server_address , arctic_universe_library )
125
- universe_security_definition = accessor .resolve_conid (conid )
126
- if universe_security_definition :
127
- return universe_security_definition [1 ]
128
- else :
129
- return None
125
+ return ListHelper .first (accessor .resolve_symbol (symbol ))
130
126
131
- def resolve_conid_to_security_definition (
132
- conid : int ,
133
- ) -> Optional [SecurityDefinition ]:
134
- result = remoted_client .rpc (
135
- return_type = list [tuple [Universe , SecurityDefinition ]]
136
- ).resolve_symbol_to_security_definitions (conid )
137
- if result :
138
- return result [0 ][1 ]
139
- else :
140
- return None
141
127
142
- def resolve_symbol_to_security_definitions (
128
+ def resolve_symbol (
143
129
symbol : Union [str , int ],
144
- ) -> List [Tuple [Universe , SecurityDefinition ]]:
145
- return remoted_client .rpc (
146
- return_type = list [tuple [Universe , SecurityDefinition ]]
147
- ).resolve_symbol_to_security_definitions (symbol )
130
+ exchange : str = '' ,
131
+ universe : str = '' ,
132
+ ) -> List [SecurityDefinition ]:
133
+ return consume (remoted_client .rpc (return_type = list [SecurityDefinition ]).resolve_symbol (symbol , exchange , universe ))
134
+
148
135
149
136
def __resolve (
150
137
symbol : Union [str , int ],
151
138
arctic_server_address : str ,
152
139
arctic_universe_library : str ,
153
- primary_exchange : Optional [str ] = ''
140
+ exchange : str = '' ,
141
+ universe : str = '' ,
154
142
) -> List [Dict [str , Any ]]:
155
- if not primary_exchange : primary_exchange = ''
156
- accessor = UniverseAccessor (arctic_server_address , arctic_universe_library )
157
- universe_definitions = accessor .resolve_symbol (symbol )
143
+ # it's best to call the trader_runtime resolve method, as it can talk to Interactive Brokers if
144
+ # the symbol is not found in any available universes
145
+ temp_results : List [Tuple [str , SecurityDefinition ]] = []
146
+
147
+ if remoted_client .is_setup :
148
+ temp_results .extend (
149
+ consume (
150
+ remoted_client .rpc (return_type = list [tuple [str , SecurityDefinition ]]).resolve_universe (symbol , exchange , universe )
151
+ )
152
+ )
153
+ else :
154
+ accessor = UniverseAccessor (arctic_server_address , arctic_universe_library )
155
+ temp_results .extend (accessor .resolve_universe_name (symbol = symbol , exchange = exchange , universe = universe ))
158
156
159
157
results : List [Dict ] = []
160
- for universe , definition in universe_definitions :
158
+ for universe_name , definition in temp_results :
161
159
results .append ({
162
- 'universe' : universe . name ,
160
+ 'universe' : universe_name ,
163
161
'conId' : definition .conId ,
164
162
'symbol' : definition .symbol ,
163
+ 'secType' : definition .secType ,
165
164
'exchange' : definition .exchange ,
166
165
'primaryExchange' : definition .primaryExchange ,
167
166
'currency' : definition .currency ,
168
167
'longName' : definition .longName ,
169
168
'category' : definition .category ,
170
169
'minTick' : definition .minTick ,
170
+ 'bondType' : definition .bondType ,
171
+ 'description' : definition .description ,
171
172
})
172
- return [ r for r in results if primary_exchange in r [ 'primaryExchange' ]]
173
+ return results
173
174
174
175
175
176
def __resolve_contract (
176
177
symbol : Union [str , int ],
177
178
arctic_server_address : str ,
178
179
arctic_universe_library : str ,
179
- primary_exchange : Optional [ str ] = ''
180
+ primary_exchange : str = ''
180
181
) -> List [Contract ]:
181
182
results = []
182
183
descriptions = __resolve (symbol , arctic_server_address , arctic_universe_library , primary_exchange )
@@ -599,16 +600,17 @@ def mapper(portfolio: PortfolioSummary) -> List:
599
600
)
600
601
601
602
df = pd .DataFrame (data = xs , columns = [
602
- 'account' , 'conId' , 'localSymbol' , 'dailyPNL' , 'unrealizedPNL' , 'realizedPNL ' , 'marketPrice ' , 'currency' ,
603
+ 'account' , 'conId' , 'localSymbol' , 'dailyPNL' , 'unrealizedPNL' , 'marketPrice ' , 'realizedPNL ' , 'currency' ,
603
604
'position' , 'marketValue' , 'averageCost' ,
604
605
])
605
606
606
607
return df .sort_values (by = 'dailyPNL' , ascending = False )
607
608
608
609
def strategy_helper () -> pd .DataFrame :
609
610
connect ()
610
- strategy_list : SuccessFail [List [StrategyConfig ]] = remoted_client .rpc (
611
- return_type = SuccessFail [List [StrategyConfig ]]).get_strategies ()
611
+ strategy_list : SuccessFail [List [StrategyConfig ]] = consume (
612
+ remoted_client .rpc (return_type = SuccessFail [List [StrategyConfig ]]).get_strategies ()
613
+ )
612
614
if strategy_list .is_success () and strategy_list .obj :
613
615
result = []
614
616
for s in strategy_list .obj :
@@ -788,7 +790,8 @@ def clear():
788
790
789
791
@cli .command (no_args_is_help = True )
790
792
@click .option ('--symbol' , required = True , help = 'symbol to resolve to conId' )
791
- @click .option ('--primary_exchange' , required = False , default = 'NASDAQ' , help = 'exchange for symbol [not required]' )
793
+ @click .option ('--exchange' , required = False , help = 'exchange for symbol [not required]' )
794
+ @click .option ('--universe' , required = False , help = 'universe to check for symbol [not required]' )
792
795
@click .option ('--ib' , required = False , default = False , is_flag = True , help = 'force resolution from IB' )
793
796
@click .option ('--sec_type' , required = False , default = 'STK' , help = 'IB security type [STK is default]' )
794
797
@click .option ('--currency' , required = False , default = 'USD' , help = 'IB security currency' )
@@ -798,7 +801,8 @@ def resolve(
798
801
symbol : str ,
799
802
arctic_server_address : str ,
800
803
arctic_universe_library : str ,
801
- primary_exchange : str ,
804
+ exchange : str ,
805
+ universe : str ,
802
806
ib : bool ,
803
807
sec_type : str ,
804
808
currency : str ,
@@ -810,15 +814,15 @@ def resolve(
810
814
contract = asyncio .get_event_loop ().run_until_complete (client .get_conid (
811
815
symbols = symbol ,
812
816
secType = sec_type ,
813
- primaryExchange = primary_exchange ,
817
+ primaryExchange = exchange ,
814
818
currency = currency
815
819
))
816
820
if contract and type (contract ) is list :
817
821
renderer .rich_list (contract )
818
822
elif contract and type (contract ) is Contract :
819
823
renderer .rich_dict (contract .__dict__ )
820
824
else :
821
- results = __resolve (symbol , arctic_server_address , arctic_universe_library , primary_exchange )
825
+ results = __resolve (symbol , arctic_server_address , arctic_universe_library , exchange , universe )
822
826
if len (results ) > 0 :
823
827
renderer .rich_table (results , False )
824
828
else :
@@ -851,7 +855,7 @@ def snapshot(
851
855
)
852
856
853
857
# awaitable = remoted_client.rpc(return_type=Ticker).get_snapshot(contract, delayed)
854
- ticker = remoted_client .rpc (return_type = Ticker ).get_snapshot (contract , delayed )
858
+ ticker = consume ( remoted_client .rpc (return_type = Ticker ).get_snapshot (contract , delayed ) )
855
859
snap = {
856
860
'symbol' : ticker .contract .symbol if ticker .contract else '' ,
857
861
'exchange' : ticker .contract .exchange if ticker .contract else '' ,
@@ -987,21 +991,6 @@ def options(
987
991
plot_chain (symbol , list_dates , date , True , risk_free_rate )
988
992
989
993
990
- # @main.group()
991
- # def loadtest():
992
- # pass
993
-
994
-
995
- # @loadtest.command('start')
996
- # def load_test_start():
997
- # remoted_client.rpc().start_load_test()
998
-
999
-
1000
- # @loadtest.command('stop')
1001
- # def load_test_stop():
1002
- # remoted_client.rpc().stop_load_test()
1003
-
1004
-
1005
994
# CLI_BOOK
1006
995
@cli .group ()
1007
996
def book ():
@@ -1081,7 +1070,7 @@ def strategy_enable(
1081
1070
name : str ,
1082
1071
paper : bool ,
1083
1072
):
1084
- success_fail = remoted_client .rpc ().enable_strategy (name , paper )
1073
+ success_fail = consume ( remoted_client .rpc ().enable_strategy (name , paper ) )
1085
1074
if success_fail .is_success ():
1086
1075
renderer .rich_dict ({'state' : success_fail .obj })
1087
1076
else :
@@ -1093,7 +1082,7 @@ def strategy_enable(
1093
1082
def strategy_disable (
1094
1083
name : str ,
1095
1084
):
1096
- success_fail = remoted_client .rpc ().disable_strategy (name )
1085
+ success_fail = consume ( remoted_client .rpc ().disable_strategy (name ) )
1097
1086
if success_fail .is_success ():
1098
1087
renderer .rich_dict ({'state' : success_fail .obj })
1099
1088
else :
@@ -1168,8 +1157,7 @@ def __trade_helper(
1168
1157
if limit and limit <= 0.0 :
1169
1158
raise ValueError ('limit price can be less than or equal to 0.0: {}' .format (limit ))
1170
1159
1171
- universe_definitions = resolve_symbol_to_security_definitions (symbol )
1172
- definitions = list ({t [1 ] for t in universe_definitions })
1160
+ definitions = resolve_symbol (symbol )
1173
1161
1174
1162
if len (definitions ) == 0 :
1175
1163
click .echo ('no contract found for symbol {}' .format (symbol ))
@@ -1184,7 +1172,7 @@ def __trade_helper(
1184
1172
contract = Universe .to_contract (security )
1185
1173
1186
1174
action = 'BUY' if buy else 'SELL'
1187
- trade : SuccessFail [Trade ] = remoted_client .rpc (return_type = SuccessFail [Trade ]).place_order_simple (
1175
+ trade : SuccessFail [Trade ] = consume ( remoted_client .rpc (return_type = SuccessFail [Trade ]).place_order_simple (
1188
1176
contract = contract ,
1189
1177
action = action ,
1190
1178
equity_amount = equity_amount ,
@@ -1193,7 +1181,7 @@ def __trade_helper(
1193
1181
market_order = market ,
1194
1182
stop_loss_percentage = stop_loss_percentage ,
1195
1183
debug = debug ,
1196
- )
1184
+ ))
1197
1185
1198
1186
output_dict = {
1199
1187
'result' : trade .success_fail ,
@@ -1400,5 +1388,3 @@ def error_out():
1400
1388
arctic_universe_library = arctic_universe_library ,
1401
1389
args = args ,
1402
1390
)
1403
-
1404
-
0 commit comments