Skip to content

Commit

Permalink
format log
Browse files Browse the repository at this point in the history
  • Loading branch information
hadrianl committed Mar 6, 2020
1 parent 71991a9 commit 4d90f67
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 127 deletions.
40 changes: 25 additions & 15 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type IbClient struct {
writer *bufio.Writer
wrapper IbWrapper
decoder *ibDecoder
connectOption []byte
connectOptions string
reqIDSeq int64
reqChan chan []byte
errChan chan error
Expand Down Expand Up @@ -68,7 +68,7 @@ func (ic *IbClient) ConnState() int {
func (ic *IbClient) setConnState(connState int) {
OldConnState := ic.conn.state
ic.conn.state = connState
log.Infof("connState: %v -> %v", OldConnState, connState)
log.Infof("ConnState: %v -> %v", OldConnState, connState)
}

// GetReqID before request data or place order
Expand All @@ -89,6 +89,11 @@ func (ic *IbClient) SetContext(ctx context.Context) {
ic.ctx = ctx
}

// Set the Connection Options to IbClient
func (ic *IbClient) SetConnectionOptions(opts string) {
ic.connectOptions = opts
}

// Connect try to connect the TWS or IB GateWay, after this, handshake should be call to get the connection done
func (ic *IbClient) Connect(host string, port int, clientID int64) error {

Expand Down Expand Up @@ -136,7 +141,7 @@ func (ic *IbClient) startAPI() error {
startAPI = makeMsgBytes(int64(mSTART_API), int64(v), ic.clientID)
}

log.Info("Start API:", startAPI)
log.Debug("Start API:", startAPI)
if _, err := ic.writer.Write(startAPI); err != nil {
return err
}
Expand All @@ -155,7 +160,12 @@ func (ic *IbClient) HandShake() error {
head := []byte("API\x00")
minVer := []byte(strconv.FormatInt(int64(MIN_CLIENT_VER), 10))
maxVer := []byte(strconv.FormatInt(int64(MAX_CLIENT_VER), 10))

connectOptions := []byte("")
if ic.connectOptions != "" {
connectOptions = []byte(" " + ic.connectOptions)
}

clientVersion := bytes.Join([][]byte{[]byte("v"), minVer, []byte(".."), maxVer, connectOptions}, []byte(""))
sizeofCV := make([]byte, 4)
binary.BigEndian.PutUint32(sizeofCV, uint32(len(clientVersion)))
Expand All @@ -171,7 +181,7 @@ func (ic *IbClient) HandShake() error {
return err
}

log.Info("Recv ServerInitInfo...")
log.Debug("Recv Server Init Info...")
if msgBytes, err = readMsgBytes(ic.reader); err != nil {
return err
}
Expand Down Expand Up @@ -229,7 +239,7 @@ comfirmReadyLoop:
}

func (ic *IbClient) reset() {
log.Info("reset IbClient.")
log.Info("Reset IbClient.")
ic.reqIDSeq = 0
ic.conn = &IbConnection{}
ic.conn.reset()
Expand Down Expand Up @@ -2585,8 +2595,8 @@ func (ic *IbClient) ReqCompletedOrders(apiOnly bool) {
//--------------------------three major goroutine -----------------------------------------------------
//goRequest will get the req from reqChan and send it to TWS
func (ic *IbClient) goRequest() {
log.Info("Start goRequest!")
defer log.Info("End goRequest!")
log.Info("Requester START!")
defer log.Info("Requester END!")
defer ic.wg.Done()

ic.wg.Add(1)
Expand Down Expand Up @@ -2618,11 +2628,11 @@ requestLoop:
//goReceive receive the msg from the socket, get the fields and put them into msgChan
//goReceive handle the msgBuf which is different from the offical.Not continuously read, but split first and then decode
func (ic *IbClient) goReceive() {
log.Info("Start goReceive!")
defer log.Info("End goReceive!")
log.Info("Receiver START!")
defer log.Info("Receiver END!")
defer func() {
if err := recover(); err != nil {
log.Errorf("goReceive has unexpected error: %v", err)
log.Errorf("Receiver got unexpected error: %v", err)
}
}()
defer ic.wg.Done()
Expand All @@ -2644,22 +2654,22 @@ scanLoop:

err := scanner.Err()
if err, ok := err.(*net.OpError); ok && !err.Temporary() {
log.Panicf("errgoReceive: %v", err)
log.Panicf("Receiver Panic: %v", err)
return
} else if err != nil {
log.Errorf("errgoReceive Temporary: %v", err)
log.Errorf("Receiver Temporary Error: %v", err)
ic.errChan <- err
ic.reader.Reset(ic.conn)
goto scanLoop
} else {
panic(scanner.Err())
log.Panicf("Scanner Panic: %v", scanner.Err())
}
}

//goDecode decode the fields received from the msgChan
func (ic *IbClient) goDecode() {
log.Info("Start goDecode!")
defer log.Info("End goDecode!")
log.Info("Decoder START!")
defer log.Info("Decoder END!")
defer ic.wg.Done()

ic.wg.Add(1)
Expand Down
5 changes: 3 additions & 2 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,21 @@ func TestClient(t *testing.T) {
return
}

ic.SetConnectionOptions("+PACEAPI")
err = ic.HandShake()
if err != nil {
log.Println("HandShake failed:", err)
return
}
ic.Run()

// ic.ReqCurrentTime()
ic.ReqCurrentTime()
// ic.ReqAutoOpenOrders(true)
// ic.ReqAccountUpdates(true, "")
// ic.ReqExecutions(ic.GetReqID(), ExecutionFilter{})

hsi2003 := Contract{ContractID: 376399002, Symbol: "HSI", SecurityType: "FUT", Exchange: "HKFE"}
// ic.ReqHistoricalData(ic.GetReqID(), &hsi1909, "", "4800 S", "1 min", "TRADES", false, 1, true, nil)
ic.ReqHistoricalData(ic.GetReqID(), &hsi2003, "", "4800 S", "1 min", "TRADES", false, 1, true, nil)
// ic.ReqMktDepth(ic.GetReqID(), &hsi1909, 5, true, nil)
ic.ReqContractDetails(ic.GetReqID(), &hsi2003)
// ic.ReqAllOpenOrders()
Expand Down
38 changes: 21 additions & 17 deletions common.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type TickAttrib struct {
}

func (t TickAttrib) String() string {
return fmt.Sprintf("CanAutoExecute: %t, PastLimit: %t, PreOpen: %t",
return fmt.Sprintf("TickAttrib<CanAutoExecute: %t, PastLimit: %t, PreOpen: %t>",
t.CanAutoExecute,
t.PastLimit,
t.PreOpen)
Expand All @@ -30,13 +30,17 @@ type TagValue struct {
}

func (tv TagValue) String() string {
return fmt.Sprintf("%s=%s;", tv.Tag, tv.Value)
return fmt.Sprintf("TagValue<%s=%s>", tv.Tag, tv.Value)
}

type OrderComboLeg struct {
Price float64 `default:"UNSETFLOAT"`
}

func (o OrderComboLeg) String() string {
return fmt.Sprintf("OrderComboLeg<Price:%f>;", o.Price)
}

// ------------ComboLeg--------------------
type ComboLegOpenClose int64
type ComboLegShortSaleSlot int64
Expand Down Expand Up @@ -64,7 +68,7 @@ type ComboLeg struct {
}

func (c ComboLeg) String() string {
return fmt.Sprintf("%d, %d, %s, %s, %d, %d, %s, %d",
return fmt.Sprintf("ComboLeg<%d, %d, %s, %s, %d, %d, %s, %d>",
c.ContractID,
c.Ratio,
c.Action,
Expand Down Expand Up @@ -99,7 +103,7 @@ type BarData struct {
}

func (b BarData) String() string {
return fmt.Sprintf("Date: %s, Open: %f, High: %f, Low: %f, Close: %f, Volume: %f, Average: %f, BarCount: %d",
return fmt.Sprintf("BarData<Date: %s, Open: %f, High: %f, Low: %f, Close: %f, Volume: %f, Average: %f, BarCount: %d>",
b.Date,
b.Open,
b.High,
Expand All @@ -123,7 +127,7 @@ type RealTimeBar struct {
}

func (rb RealTimeBar) String() string {
return fmt.Sprintf("Time: %d, Open: %f, High: %f, Low: %f, Close: %f, Volume: %d, Wap: %f, Count: %d",
return fmt.Sprintf("RealTimeBar<Time: %d, Open: %f, High: %f, Low: %f, Close: %f, Volume: %d, Wap: %f, Count: %d>",
rb.Time,
rb.Open,
rb.High,
Expand All @@ -144,7 +148,7 @@ type CommissionReport struct {
}

func (cr CommissionReport) String() string {
return fmt.Sprintf("ExecId: %v, Commission: %v, Currency: %v, RealizedPnL: %v, Yield: %v, YieldRedemptionDate: %v",
return fmt.Sprintf("CommissionReport<ExecId: %v, Commission: %v, Currency: %v, RealizedPnL: %v, Yield: %v, YieldRedemptionDate: %v>",
cr.ExecId,
cr.Commission,
cr.Currency,
Expand All @@ -159,7 +163,7 @@ type FamilyCode struct {
}

func (f FamilyCode) String() string {
return fmt.Sprintf("AccountId: %s, FamilyCodeStr: %s",
return fmt.Sprintf("FamilyCode<AccountId: %s, FamilyCodeStr: %s>",
f.AccountID,
f.FamilyCode)
}
Expand All @@ -171,7 +175,7 @@ type SmartComponent struct {
}

func (s SmartComponent) String() string {
return fmt.Sprintf("BitNumber: %d, Exchange: %s, ExchangeLetter: %s",
return fmt.Sprintf("SmartComponent<BitNumber: %d, Exchange: %s, ExchangeLetter: %s>",
s.BitNumber,
s.Exchange,
s.ExchangeLetter)
Expand All @@ -191,7 +195,7 @@ func (d DepthMktDataDescription) String() string {
aggGroup = string(d.AggGroup)
}

return fmt.Sprintf("Exchange: %s, SecType: %s, ListingExchange: %s, ServiceDataType: %s, AggGroup: %s ",
return fmt.Sprintf("DepthMktDataDescription<Exchange: %s, SecType: %s, ListingExchange: %s, ServiceDataType: %s, AggGroup: %s>",
d.Exchange,
d.SecurityType,
d.ListingExchange,
Expand All @@ -205,7 +209,7 @@ type NewsProvider struct {
}

func (np NewsProvider) String() string {
return fmt.Sprintf("Code: %s, Name: %s",
return fmt.Sprintf("NewsProvider<Code: %s, Name: %s>",
np.Code,
np.Name)
}
Expand All @@ -216,7 +220,7 @@ type HistogramData struct {
}

func (hgd HistogramData) String() string {
return fmt.Sprintf("Price: %f, Count: %d",
return fmt.Sprintf("HistogramData<Price: %f, Count: %d>",
hgd.Price,
hgd.Count)
}
Expand All @@ -227,7 +231,7 @@ type PriceIncrement struct {
}

func (p PriceIncrement) String() string {
return fmt.Sprintf("LowEdge: %f, Increment: %f",
return fmt.Sprintf("PriceIncrement<LowEdge: %f, Increment: %f>",
p.LowEdge,
p.Increment)
}
Expand All @@ -239,7 +243,7 @@ type HistoricalTick struct {
}

func (h HistoricalTick) String() string {
return fmt.Sprintf("Time: %d, Price: %f, Size: %d",
return fmt.Sprintf("Tick<Time: %d, Price: %f, Size: %d>",
h.Time,
h.Price,
h.Size)
Expand All @@ -255,7 +259,7 @@ type HistoricalTickBidAsk struct {
}

func (h HistoricalTickBidAsk) String() string {
return fmt.Sprintf("Time: %d, TickAttriBidAsk: %s, PriceBid: %f, PriceAsk: %f, SizeBid: %d, SizeAsk: %d",
return fmt.Sprintf("TickBidAsk<Time: %d, TickAttriBidAsk: %s, PriceBid: %f, PriceAsk: %f, SizeBid: %d, SizeAsk: %d>",
h.Time,
h.TickAttirbBidAsk,
h.PriceBid,
Expand All @@ -270,7 +274,7 @@ type TickAttribBidAsk struct {
}

func (t TickAttribBidAsk) String() string {
return fmt.Sprintf("BidPastLow: %t, AskPastHigh: %t",
return fmt.Sprintf("TickAttribBidAsk<BidPastLow: %t, AskPastHigh: %t>",
t.BidPastLow,
t.AskPastHigh)
}
Expand All @@ -285,7 +289,7 @@ type HistoricalTickLast struct {
}

func (h HistoricalTickLast) String() string {
return fmt.Sprintf("Time: %d, TickAttribLast: %s, Price: %f, Size: %d, Exchange: %s, SpecialConditions: %s",
return fmt.Sprintf("TickLast<Time: %d, TickAttribLast: %s, Price: %f, Size: %d, Exchange: %s, SpecialConditions: %s>",
h.Time,
h.TickAttribLast,
h.Price,
Expand All @@ -300,7 +304,7 @@ type TickAttribLast struct {
}

func (t TickAttribLast) String() string {
return fmt.Sprintf("PastLimit: %t, Unreported: %t",
return fmt.Sprintf("TickAttribLast<PastLimit: %t, Unreported: %t>",
t.PastLimit,
t.Unreported)
}
16 changes: 9 additions & 7 deletions contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ type Contract struct {
}

func (c Contract) String() string {
basicStr := fmt.Sprintf("CondID: %d , Symbol: %s, SecurityType: %s, Exchange: %s, Currency: %s, ",
basicStr := fmt.Sprintf("Contract<CondID: %d, Symbol: %s, SecurityType: %s, Exchange: %s, Currency: %s",
c.ContractID,
c.Symbol,
c.SecurityType,
Expand All @@ -38,17 +38,19 @@ func (c Contract) String() string {

switch c.SecurityType {
case "FUT":
basicStr += fmt.Sprintf("Expiry: %s, Multiplier: %s, SecurityID: %s, SecurityIDType:%s", c.Expiry, c.Multiplier, c.SecurityID, c.SecurityIDType)
basicStr += fmt.Sprintf(", Expiry: %s, Multiplier: %s, SecurityID: %s, SecurityIDType: %s>", c.Expiry, c.Multiplier, c.SecurityID, c.SecurityIDType)
case "OPT":
basicStr += fmt.Sprintf("Expiry: %s, Strike: %f, Right: %s, SecurityID: %s, SecurityIDType:%s", c.Expiry, c.Strike, c.Right, c.SecurityID, c.SecurityIDType)
basicStr += fmt.Sprintf(", Expiry: %s, Strike: %f, Right: %s, SecurityID: %s, SecurityIDType: %s>", c.Expiry, c.Strike, c.Right, c.SecurityID, c.SecurityIDType)
default:
basicStr += fmt.Sprint(">")
}

for i, leg := range c.ComboLegs {
basicStr += fmt.Sprintf(";Leg<%d>-%s", i, leg)
basicStr += fmt.Sprintf("-Leg<%d>: %s", i, leg)
}

if c.DeltaNeutralContract != nil {
basicStr += fmt.Sprintf(";DeltaNeutralContract-%s", c.DeltaNeutralContract)
basicStr += fmt.Sprintf("-%s", c.DeltaNeutralContract)
}

return basicStr
Expand All @@ -61,7 +63,7 @@ type DeltaNeutralContract struct {
}

func (c DeltaNeutralContract) String() string {
return fmt.Sprintf("CondID: %d , Delta: %f, Price: %f",
return fmt.Sprintf("DeltaNeutralContract<CondID: %d , Delta: %f, Price: %f>",
c.ContractID,
c.Delta,
c.Price)
Expand Down Expand Up @@ -116,7 +118,7 @@ type ContractDetails struct {
}

func (c ContractDetails) String() string {
return fmt.Sprintf("Contract: %s, MarketName: %s, UnderContractID: %d, TradingHours: %s", c.Contract, c.MarketName, c.UnderContractID, c.TradingHours)
return fmt.Sprintf("ContractDetails<Contract: %s, MarketName: %s, UnderContractID: %d, LongName: %s>", c.Contract, c.MarketName, c.UnderContractID, c.LongName)
}

type ContractDescription struct {
Expand Down
8 changes: 4 additions & 4 deletions order.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ type Order struct {
}

func (o Order) String() string {
s := fmt.Sprintf("%d, %d, %d: %s %s %.2f@%f %s ",
s := fmt.Sprintf("Order<OrderID: %d, ClientID: %d, PermID: %d> -- <%s %s %.2f@%f %s> --",
o.OrderID,
o.ClientID,
o.PermID,
Expand All @@ -213,11 +213,11 @@ func (o Order) String() string {
o.TIF)

for i, leg := range o.OrderComboLegs {
s += fmt.Sprintf(" CMB<%d>-%v)", i, leg)
s += fmt.Sprintf(" CMB<%d>-%s", i, leg)
}

for i, cond := range o.Conditions {
s += fmt.Sprintf(" COND<%d>-%v)", i, cond)
s += fmt.Sprintf(" COND<%d>-%s", i, cond)
}

return s
Expand Down Expand Up @@ -251,7 +251,7 @@ type SoftDollarTier struct {
}

func (s SoftDollarTier) String() string {
return fmt.Sprintf("Name: %s, Value: %s, DisplayName: %s",
return fmt.Sprintf("SoftDollarTier<Name: %s, Value: %s, DisplayName: %s>",
s.Name,
s.Value,
s.DisplayName)
Expand Down
Loading

0 comments on commit 4d90f67

Please sign in to comment.