1
- import alpaca_trade_api as tradeapi
2
- import threading
3
- from time import *
4
1
import json
5
2
import logging
3
+ import threading
4
+ from time import *
6
5
7
- #init
8
- logging .basicConfig (filename = 'errlog.log' ,level = logging .WARNING , format = '%(asctime)s:%(levelname)s:%(message)s' )
6
+ import alpaca_trade_api as tradeapi
7
+
8
+ # init
9
+ logging .basicConfig (
10
+ filename = 'errlog.log' ,
11
+ level = logging .WARNING ,
12
+ format = '%(asctime)s:%(levelname)s:%(message)s' ,
13
+ )
9
14
10
15
api_key = 'insert_api_key'
11
16
api_secret = 'insert_api_secret'
23
28
active_trade = False
24
29
done_for_the_day = False
25
30
26
- #check if market is open
31
+ #check if market is open
27
32
api .cancel_all_orders ()
28
33
clock = api .get_clock ()
29
34
30
35
if clock .is_open :
31
- pass
36
+ pass
32
37
else :
33
- time_to_open = clock .next_open - clock .timestamp
34
- sleep (time_to_open .total_seconds ())
38
+ time_to_open = clock .next_open - clock .timestamp
39
+ sleep (time_to_open .total_seconds ())
35
40
36
41
if len (api .list_positions ()) == 0 :
37
- searching_for_trade = True
42
+ searching_for_trade = True
38
43
else :
39
- active_trade = True
44
+ active_trade = True
40
45
41
- #init WebSocket
46
+ #init WebSocket
42
47
conn = tradeapi .stream2 .StreamConn (api_key , api_secret , base_url )
43
48
49
+
44
50
@conn .on (r'^account_updates$' )
45
51
async def on_account_updates (conn , channel , account ):
46
- order_msg .append (account )
52
+ order_msg .append (account )
53
+
47
54
48
55
@conn .on (r'^trade_updates$' )
49
56
async def on_trade_updates (conn , channel , trade ):
50
- trade_msg .append (trade )
51
- if 'fill' in trade .event :
52
- past_trades .append ([trade .order ['updated_at' ], trade .order ['symbol' ], trade .order ['side' ],
53
- trade .order ['filled_qty' ], trade .order ['filled_avg_price' ]])
54
- with open ('past_trades.csv' , 'w' ) as f :
55
- json .dump (past_trades , f , indent = 4 )
56
- print (past_trades [- 1 ])
57
+ trade_msg .append (trade )
58
+ if 'fill' in trade .event :
59
+ past_trades .append (
60
+ [
61
+ trade .order ['updated_at' ],
62
+ trade .order ['symbol' ],
63
+ trade .order ['side' ],
64
+ trade .order ['filled_qty' ],
65
+ trade .order ['filled_avg_price' ],
66
+ ]
67
+ )
68
+ with open ('past_trades.csv' , 'w' ) as f :
69
+ json .dump (past_trades , f , indent = 4 )
70
+ print (past_trades [- 1 ])
71
+
57
72
58
73
def ws_start ():
59
- conn .run (['account_updates' , 'trade_updates' ])
74
+ conn .run (['account_updates' , 'trade_updates' ])
75
+
60
76
61
- #start WebSocket in a thread
77
+ #start WebSocket in a thread
62
78
ws_thread = threading .Thread (target = ws_start , daemon = True )
63
79
ws_thread .start ()
64
80
sleep (10 )
65
81
66
82
67
- #functions
83
+ #functions
68
84
def time_to_market_close ():
69
- clock = api .get_clock ()
70
- closing = clock .next_close - clock .timestamp
71
- return round (closing .seconds / 60 )
72
-
73
- def send_order (direction ):
74
- if time_to_market_close () > 20 :
75
- if direction == 'buy' :
76
- sl = high - range_size
77
- tp = high + range_size
78
- elif direction == 'sell' :
79
- sl = low + range_size
80
- tp = low - range_size
85
+ clock = api .get_clock ()
86
+ closing = clock .next_close - clock .timestamp
87
+ return round (closing .total_seconds () / 60 )
81
88
82
- api .submit_order (symbol = 'AAPL' , qty = 100 , side = direction , type = 'market' , time_in_force = 'day' , order_class = 'bracket' , stop_loss = dict (stop_price = str (sl )), take_profit = dict (limit_price = str (tp )))
83
- return True , False
84
89
85
- else :
86
- return False , True
87
-
88
-
89
- #main loop
90
+ def send_order (direction ):
91
+ if time_to_market_close () > 20 :
92
+ if direction == 'buy' :
93
+ sl = high - range_size
94
+ tp = high + range_size
95
+ elif direction == 'sell' :
96
+ sl = low + range_size
97
+ tp = low - range_size
98
+
99
+ api .submit_order (
100
+ symbol = 'AAPL' ,
101
+ qty = 100 ,
102
+ side = direction ,
103
+ type = 'market' ,
104
+ time_in_force = 'day' ,
105
+ order_class = 'bracket' ,
106
+ stop_loss = dict (stop_price = str (sl )),
107
+ take_profit = dict (limit_price = str (tp )),
108
+ )
109
+ return True , False
110
+
111
+ else :
112
+ return False , True
113
+
114
+
115
+ # main loop
90
116
while True :
91
117
92
- try :
93
-
94
- candlesticks = api .get_barset ('AAPL' , 'minute' , limit = 10 )
95
- high = candlesticks ['AAPL' ][0 ].h
96
- low = candlesticks ['AAPL' ][0 ].l
97
- range_size = high - low
98
- if range_size / candlesticks ['AAPL' ][0 ].c < 0.003 :
99
- range_size = candlesticks ['AAPL' ][0 ].c * 0.003
100
- for candle in candlesticks ['AAPL' ]:
101
- if candle .h > high :
102
- high = candle .h
103
- elif candle .l < low :
104
- low = candle .l
105
- range_size = high - low
106
-
107
- while searching_for_trade :
108
- clock = api .get_clock ()
109
- sleep (60 - clock .timestamp .second )
110
- candlesticks = api .get_barset ('AAPL' , 'minute' , limit = 1 )
111
- if candlesticks ['AAPL' ][0 ].c > high :
112
- searching_for_trade = False
113
- order_sent , done_for_the_day = send_order ('buy' )
114
-
115
- elif candlesticks ['AAPL' ][0 ].c < low :
116
- searching_for_trade = False
117
- order_sent , done_for_the_day = send_order ('sell' )
118
-
119
- while order_sent :
120
- sleep (1 )
121
- for item in trade_msg :
122
- if item .event == 'new' :
123
- order_submitted = True
124
- order_sent = False
125
-
126
- while order_submitted :
127
- sleep (1 )
128
- for item in trade_msg :
129
- if item .order ['filled_qty' ] == '100' :
130
- order_submitted = False
131
- active_trade = True
132
- trade_msg = []
133
-
134
-
135
- while active_trade :
136
- for i in range (time_to_market_close ()- 5 ):
137
- sleep (60 )
138
- if len (api .list_positions ()) == 0 :
139
- active_trade = False
140
- searching_for_trade = True
141
- break
142
- if active_trade :
143
- done_for_the_day = True
144
- active_trade = False
145
-
146
- while done_for_the_day :
147
- api .close_all_positions ()
148
- clock = api .get_clock ()
149
- next_market_open = clock .next_open - clock .timestamp
150
- sleep (next_market_open .total_seconds ())
151
- searching_for_trade = True
152
-
153
- except Exception as e :
154
- logging .exception (e )
118
+ try :
119
+
120
+ candlesticks = api .get_barset ('AAPL' , 'minute' , limit = 10 )
121
+ high = candlesticks ['AAPL' ][0 ].h
122
+ low = candlesticks ['AAPL' ][0 ].l
123
+ range_size = high - low
124
+ if range_size / candlesticks ['AAPL' ][0 ].c < 0.003 :
125
+ range_size = candlesticks ['AAPL' ][0 ].c * 0.003
126
+ for candle in candlesticks ['AAPL' ]:
127
+ if candle .h > high :
128
+ high = candle .h
129
+ elif candle .l < low :
130
+ low = candle .l
131
+ range_size = high - low
132
+
133
+ while searching_for_trade :
134
+ clock = api .get_clock ()
135
+ sleep (60 - clock .timestamp .second )
136
+ candlesticks = api .get_barset ('AAPL' , 'minute' , limit = 1 )
137
+ if candlesticks ['AAPL' ][0 ].c > high :
138
+ searching_for_trade = False
139
+ order_sent , done_for_the_day = send_order ('buy' )
140
+
141
+ elif candlesticks ['AAPL' ][0 ].c < low :
142
+ searching_for_trade = False
143
+ order_sent , done_for_the_day = send_order ('sell' )
144
+
145
+ while order_sent :
146
+ sleep (1 )
147
+ for item in trade_msg :
148
+ if item .event == 'new' :
149
+ order_submitted = True
150
+ order_sent = False
151
+
152
+ while order_submitted :
153
+ sleep (1 )
154
+ for item in trade_msg :
155
+ if item .order ['filled_qty' ] == '100' :
156
+ order_submitted = False
157
+ active_trade = True
158
+ trade_msg = []
159
+
160
+ while active_trade :
161
+ for i in range (time_to_market_close () - 5 ):
162
+ sleep (60 )
163
+ if len (api .list_positions ()) == 0 :
164
+ active_trade = False
165
+ searching_for_trade = True
166
+ break
167
+ if active_trade :
168
+ done_for_the_day = True
169
+ active_trade = False
170
+
171
+ while done_for_the_day :
172
+ api .close_all_positions ()
173
+ clock = api .get_clock ()
174
+ next_market_open = clock .next_open - clock .timestamp
175
+ sleep (next_market_open .total_seconds ())
176
+ searching_for_trade = True
177
+
178
+ except Exception as e :
179
+ logging .exception (e )
0 commit comments