-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpoll_account.py
177 lines (158 loc) · 6.45 KB
/
poll_account.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import threading
import time
from configparser import ConfigParser
import v20
from log_wrapper import LogWrapper
class AccountPolling(threading.Thread):
def __init__(self, account, event, lock, logname, ctx):
super().__init__()
self.account = account
self.event = event
self.lock = lock
self.ctx = ctx
self.account_id = account.id
self.last_id = self.account.lastTransactionID
self.log = LogWrapper(logname)
def update_account(self,
changes: v20.account.AccountChanges,
state: v20.account.AccountChangesState):
self.apply_changes(changes)
self.apply_transactions(changes)
# #
self.update_fields(state)
self.update_trades(state)
self.update_positions(state)
self.update_orders(state)
def get_account_changes(self):
r = self.ctx.account.changes(
self.account_id,
sinceTransactionID=self.account.lastTransactionID)
changes = r.get('changes')
state = r.get('state')
self.account.lastTransactionID = r.get('lastTransactionID')
self.update_account(changes, state)
print(f'NAV: {self.account.NAV:.2f} uPL:{self.account.unrealizedPL} opentrades: {self.account.openTradeCount}')
def run(self) -> None:
i = 0
while True:
try:
self.get_account_changes()
print(f'#{i:>3}: {self.account.NAV:.2f} {self.account.unrealizedPL}')
i+=1
time.sleep(20)
except v20.errors.V20Timeout as e:
print('account error: ',e)
except Exception as e:
print('account error: ',e)
def apply_changes(self, changes: v20.account.AccountChanges):
# Trades Opened
for to in changes.tradesOpened:
to.isLong = False
if to.currentUnits > 0:
to.isLong = True
self.account.trades.append(to)
# Trades Reduced
for tr in changes.tradesReduced:
for t in self.account.trades:
if t.id == tr.id:
t.currentUnits = tr.currentUnits
t.realizedPL = tr.realizedPL
t.averageClosePrice = tr.averageClosePrice
# Trades Closed
for tc in changes.tradesClosed:
for t in self.account.trades:
if t.id == tc.id:
self.account.trades.remove(t)
#
for cp in changes.positions:
for ap in self.account.positions:
if ap.instrument == cp.instrument:
self.account.positions.remove(ap)
self.account.positions.append(cp)
#
for occ in changes.ordersCancelled:
for o in self.account.orders:
if o.id == occ.id:
self.account.orders.remove(o)
for t in self.account.trades:
if t.id == occ.tradeID:
if occ.type == 'STOP_LOSS':
t.stopLossOrderID = None
elif occ.type == 'TAKE_PROFIT':
t.takeProfitOrderID = None
elif occ.type == 'TRAILING_STOP_LOSS':
t.trailingStopLossOrderID = None
#
for ocr in changes.ordersCreated:
self.account.orders.append(ocr)
for t in self.account.trades:
# AttributeError: 'StopOrder' object has no attribute 'tradeID'
if t.id == ocr.tradeID:
if ocr.type == 'STOP_LOSS':
t.stopLossOrderID = ocr.id
elif ocr.type == 'TAKE_PROFIT':
t.takeProfitOrderID = ocr.id
elif ocr.type == 'TRAILING_STOP_LOSS':
t.trailingStopLossOrderID = ocr.id
#
for ofi in changes.ordersFilled:
for o in self.account.orders:
if o.id == ofi.id:
self.account.orders.remove(o)
#
for otr in changes.ordersTriggered:
for o in self.account.orders:
if o.id == otr.id:
self.account.orders.remove(o)
def apply_transactions(self, changes):
for tr in changes.transactions:
if tr.type == 'ORDER_FILL':
self.account.balance = tr.accountBalance
def update_trades(self, state):
for st in state.trades:
for at in self.account.trades:
if at.id == st.id:
at.unrealizedPL = st.unrealizedPL
at.marginUsed = st.marginUsed
def update_fields(self, state):
for field in state.fields():
self.update_attribute(self.account, field.name, field.value)
def update_attribute(self, dest, name, value):
if name in ('orders', 'trades', 'positions'):
return
if hasattr(dest, name) and getattr(dest, name) is not None:
setattr(dest, name, value)
def update_positions(self, state: v20.account.AccountChangesState):
for sp in state.positions:
for p in self.account.positions:
if p.instrument == sp.instrument:
p.unrealizedPL = sp.netUnrealizedPL
p.long.unrealizedPL = sp.longUnrealizedPL
p.short.unrealizedPL = sp.shortUnrealizedPL
p.marginUsed = sp.marginUsed
def update_orders(self, state):
for so in state.orders:
for o in self.account.orders:
if o.id == so.id:
o.trailingStopValue = so.trailingStopValue
o.distance = so.triggerDistance
if __name__ == '__main__':
config = ConfigParser()
config.read('config.ini')
API_KEY = config['OANDA']['API_KEY']
account_id = config['OANDA']['ACCOUNT_ID']
HOSTNAME = "api-fxpractice.oanda.com"
key = f'Bearer {API_KEY}'
ctx = v20.Context(hostname=HOSTNAME, token=key)
ctx.set_header(key='Authorization', value=key)
account = ctx.account.get(account_id).get('account')
event = threading.Event()
lock = threading.Lock()
ap = AccountPolling(account, event, lock, "Account", ctx)
ap.daemon = True
ap.start()
print(account.NAV)
try:
ap.join()
except KeyboardInterrupt as error:
print('KI error')