-
Notifications
You must be signed in to change notification settings - Fork 0
/
trade.go
250 lines (220 loc) · 7.22 KB
/
trade.go
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package ibsync
import (
"fmt"
"sync"
"time"
)
// Status represents the current state of an order in the trading system.
type Status string
// Order status constants define all possible states an order can be in.
const (
PendingSubmit Status = "PendingSubmit" // Order is pending submission to IB
PendingCancel Status = "PendingCancel" // Order cancellation is pending
PreSubmitted Status = "PreSubmitted" // Order has been sent but not yet confirmed
Submitted Status = "Submitted" // Order has been submitted to IB
ApiPending Status = "ApiPending" // Order is pending processing by the API
ApiCancelled Status = "ApiCancelled" // Order was cancelled through the API
Cancelled Status = "Cancelled" // Order has been cancelled
Filled Status = "Filled" // Order has been completely filled
Inactive Status = "Inactive" // Order is inactive
)
// IsActive returns true if the status indicates the order is still active in the market.
func (s Status) IsActive() bool {
switch s {
case PendingSubmit, ApiPending, PreSubmitted, Submitted:
return true
default:
return false
}
}
// IsDone returns true if the status indicates the order has reached a terminal state.
func (s Status) IsDone() bool {
switch s {
case Filled, Cancelled, ApiCancelled:
return true
default:
return false
}
}
// OrderStatus represents the current state and details of an order.
type OrderStatus struct {
OrderID int64 // Unique identifier for the order
Status Status // Current status of the order
Filled Decimal // Amount of order that has been filled
Remaining Decimal // Amount of order remaining to be filled
AvgFillPrice float64 // Average price of filled portions
PermID int64 // Permanent ID assigned by IB
ParentID int64 // ID of parent order if this is a child order
LastFillPrice float64 // Price of the last fill
ClientID int64 // Client identifier
WhyHeld string // Reason why order is being held
MktCapPrice float64 // Market cap price
}
// IsActive returns true if the order status indicates an active order.
func (os OrderStatus) IsActive() bool {
return os.Status.IsActive()
}
// IsDone returns true if the order status indicates the order has reached a terminal state.
func (os OrderStatus) IsDone() bool {
return os.Status.IsDone()
}
// Fill represents a single execution fill of an order, including contract details,
// execution information, and commission data.
type Fill struct {
Contract *Contract // Contract details for the filled order
Execution *Execution // Execution details of the fill
CommissionAndFeesReport CommissionAndFeesReport // Commission and fees information for the fill
Time time.Time // Timestamp of the fill
}
// PassesExecutionFilter checks if the fill matches the specified execution filter criteria.
func (f *Fill) Matches(filter ExecutionFilter) bool {
if f == nil {
return false
}
if filter.AcctCode != "" && filter.AcctCode != f.Execution.AcctNumber {
return false
}
if filter.ClientID != 0 && filter.ClientID != f.Execution.ClientID {
return false
}
if filter.Exchange != "" && filter.Exchange != f.Execution.Exchange {
return false
}
if filter.SecType != "" && filter.SecType != f.Contract.SecType {
return false
}
if filter.Side != "" && filter.Side != f.Execution.Side {
return false
}
if filter.Symbol != "" && filter.Symbol != f.Contract.Symbol {
return false
}
if filter.Time != "" {
filterTime, err := ParseIBTime(filter.Time)
if err != nil {
log.Error().Err(err).Msg("PassesExecutionFilter")
return false
}
if f.Time.Before(filterTime) {
return false
}
}
return true
}
// TradeLogEntry represents a single entry in the trade's log, recording status changes
// and other significant events.
type TradeLogEntry struct {
Time time.Time // Timestamp of the log entry
Status Status // Status at the time of the log entry
Message string // Descriptive message about the event
ErrorCode int64 // Error code if applicable
}
// Trade represents a complete trading operation, including the contract, order details,
// current status, and execution fills.
type Trade struct {
Contract *Contract
Order *Order
OrderStatus OrderStatus
mu sync.RWMutex
fills []*Fill
logs []TradeLogEntry
done chan struct{}
}
/* func (t* Trade) Equal(other Trade) bool{
t.Order
} */
// NewTrade creates a new Trade instance with the specified contract and order details.
// Optional initial order status can be provided.
func NewTrade(contract *Contract, order *Order, orderStatus ...OrderStatus) *Trade {
var os OrderStatus
if len(orderStatus) > 0 {
os = orderStatus[0]
} else {
os = OrderStatus{
OrderID: order.OrderID,
Status: PendingSubmit,
}
}
return &Trade{
Contract: contract,
Order: order,
OrderStatus: os,
fills: make([]*Fill, 0),
logs: []TradeLogEntry{{Time: time.Now().UTC(), Status: PendingSubmit}},
done: make(chan struct{}),
}
}
// IsActive returns true if the trade is currently active in the market.
func (t *Trade) IsActive() bool {
t.mu.RLock()
defer t.mu.RUnlock()
return t.isActive()
}
// isActive is an internal helper that checks if the trade is active without locking.
func (t *Trade) isActive() bool {
return t.OrderStatus.IsActive()
}
// IsDone returns true if the trade has reached a terminal state.
func (t *Trade) IsDone() bool {
t.mu.RLock()
defer t.mu.RUnlock()
return t.isDone()
}
// isDone is an internal helper that checks if the trade is done without locking.
func (t *Trade) isDone() bool {
return t.OrderStatus.IsDone()
}
// Done returns a channel that will be closed when the trade reaches a terminal state.
func (t *Trade) Done() <-chan struct{} {
return t.done
}
// markDone closes the done channel to signal trade completion.
// This is an internal method and should be called with appropriate locking.
func (t *Trade) markDone() {
// Ensure that the done channel is closed only once
select {
case <-t.done:
// Channel already closed
default:
close(t.done)
}
}
// markDoneSafe safely marks the trade as done with proper locking.
func (t *Trade) markDoneSafe() {
t.mu.RLock()
defer t.mu.RUnlock()
t.markDone()
}
// Fills returns a copy of all fills for this trade
func (t *Trade) Fills() []*Fill {
t.mu.RLock()
defer t.mu.RUnlock()
fills := make([]*Fill, len(t.fills))
copy(fills, t.fills)
return fills
}
// addFill adds a new fill to the trade's fill history
func (t *Trade) addFill(fill *Fill) {
t.fills = append(t.fills, fill)
}
// Logs returns a copy of all log entries for this trade
func (t *Trade) Logs() []TradeLogEntry {
t.mu.RLock()
defer t.mu.RUnlock()
logs := make([]TradeLogEntry, len(t.logs))
copy(logs, t.logs)
return logs
}
// addLog adds a new log entry to the trade's history
func (t *Trade) addLog(tradeLogEntry TradeLogEntry) {
t.logs = append(t.logs, tradeLogEntry)
}
func (t *Trade) Equal(other *Trade) bool {
return t.Order.HasSameID(other.Order)
}
func (t *Trade) String() string {
t.mu.RLock()
defer t.mu.RUnlock()
return fmt.Sprintf("Trade{Contract: %v, Order: %v, Status: %v, Fills: %d}",
t.Contract, t.Order, t.OrderStatus, len(t.fills))
}