Пример #1
0
func (w *Huobi) getOrderBook(symbol string) (ret bool, hbOrderBook OrderBook) {
	// init to false
	ret = false
	var huobisymbol string
	if symbol == "btc_cny" {
		huobisymbol = "huobibtccny"
	} else {
		huobisymbol = "huobiltccny"
		logger.Fatal("huobi does not support LTC by now, wait for huobi provide it.", huobisymbol)
		return
	}

	rnd := util.RandomString(20)

	now := time.Now().UnixNano() / 1000000

	req, err := http.NewRequest("GET", fmt.Sprintf(Config["hb_trade_detail"], rnd, now, now), nil)
	if err != nil {
		logger.Fatal(err)
		return
	}

	req.Header.Set("Referer", Config["base_url"])
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")
	req.Header.Add("Accept-Encoding", "identity")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logger.Traceln(err)
		logger.Traceln(req)
		logger.Traceln(resp)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		logger.Errorf("HTTP returned status %v", resp)
		return
	}

	var body string
	contentEncoding := resp.Header.Get("Content-Encoding")
	logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
	switch contentEncoding {
	case "gzip":
		body = util.DumpGZIP(resp.Body)
	default:
		bodyByte, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.Errorln("read the http stream failed")
			return
		} else {
			body = string(bodyByte)
			ioutil.WriteFile("cache/OrderBook.json", bodyByte, 0644)
		}
	}

	return w.analyzeOrderBook(body)
}
Пример #2
0
func (w *HuobiTrade) Get_account_info() (account_info Account_info, ret bool) {
	pParams := make(map[string]string)
	pParams["method"] = "get_account_info"
	pParams["access_key"] = w.access_key
	now := time.Now().Unix()
	pParams["created"] = strconv.FormatInt(now, 10)
	pParams["sign"] = w.createSign(pParams)

	ret = true

	body, err := w.httpRequest(pParams)
	if err != nil {
		ret = false
		return
	}

	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&account_info); err == io.EOF {
		logger.Fatal(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(account_info)

	return
}
Пример #3
0
func (w *BitvcTrade) GetAccount() (account_info Account_info, ret bool) {
	pParams := make(map[string]string)

	ret = true

	body, err := w.httpRequest(pParams)
	if err != nil {
		ret = false
		return
	}

	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&account_info); err == io.EOF {
		logger.Fatal(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(account_info)

	return
}
Пример #4
0
/*
{"code":0,"msg":"","ext":{"cny_balance":{"CNY":{"total":340062540230000,"available":340062540230000,"frozen":0},"BTC":{"total":177247000000,"available":177247000000,"frozen":0},"LTC":{"total":0,"available":0,"frozen":0},"now_btc_price":"38380100000000","now_ltc_price":"471500000000","LOAN_CNY":0,"LOAN_BTC":177247000000,"LOAN_LTC":0,"net_asset":340062540230000,"total":1020338298700000},"coin_saving_balance":{"btc_total":"0","ltc_total":"0"}}}
*/
func (w *BitvcTrade) GetAccount() (account_info Account_info, ret bool) {

	w.Login()

	pParams := make(map[string]string)

	ret = true

	body, err := w.httpRequest("https://www.bitvc.com/ajax/user_balance", pParams)
	if err != nil {
		ret = false
		return
	}

	fmt.Println(body)
	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&account_info); err == io.EOF {
		logger.Fatal(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(account_info)

	return
}
Пример #5
0
func (w *Huobi) AnalyzeKLinePeroid(symbol string, peroid int) (ret bool, records []Record) {
	ret = false
	var huobisymbol string
	if symbol == "btc_cny" {
		huobisymbol = "huobibtccny"
	} else {
		huobisymbol = "huobiltccny"
		logger.Fatal("huobi does not support LTC by now, wait for huobi provide it.", huobisymbol)
		return
	}

	req, err := http.NewRequest("GET", fmt.Sprintf(Config["hb_kline_url"], peroid), nil)
	if err != nil {
		logger.Fatal(err)
		return
	}

	req.Header.Set("Referer", Config["hb_base_url"])
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")

	logger.Traceln(req)

	c := util.NewTimeoutClient()

	logger.Tracef("HTTP req begin AnalyzeKLinePeroid")
	resp, err := c.Do(req)
	logger.Tracef("HTTP req end AnalyzeKLinePeroid")
	if err != nil {
		logger.Traceln(err)
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		logger.Tracef("HTTP returned status %v", resp)
		return
	}
	var body string

	contentEncoding := resp.Header.Get("Content-Encoding")
	logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
	logger.Traceln(resp.Header.Get("Content-Type"))
	switch contentEncoding {
	case "gzip":
		body = util.DumpGZIP(resp.Body)
	default:
		bodyByte, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.Errorln("read the http stream failed")
			return
		} else {
			body = string(bodyByte)
		}
	}

	ioutil.WriteFile(fmt.Sprintf("cache/hbKLine_%03d.data", peroid), []byte(body), 0644)

	return analyzePeroidLine(fmt.Sprintf("cache/hbKLine_%03d.data", peroid))
}
Пример #6
0
func (w *HuobiTrade) httpRequest(pParams map[string]string) (string, error) {
	v := url.Values{}
	for key, val := range pParams {
		v.Add(key, val)
	}

	req, err := http.NewRequest("POST", Config["api_url"], strings.NewReader(v.Encode()))
	if err != nil {
		logger.Fatal(err)
		return "", err
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Referer", "https://www.huobi.com/")
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")
	logger.Traceln(req)

	c := util.NewTimeoutClient()

	logger.Tracef("HTTP req begin HuobiTrade")
	resp, err := c.Do(req)
	logger.Tracef("HTTP req end HuobiTrade")
	if err != nil {
		logger.Fatal(err)
		return "", err
	}
	defer resp.Body.Close()

	logger.Tracef("api_url resp StatusCode=%v", resp.StatusCode)
	logger.Tracef("api_url resp=%v", resp)
	if resp.StatusCode == 200 {
		var body string

		contentEncoding := resp.Header.Get("Content-Encoding")
		logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
		logger.Traceln(resp.Header.Get("Content-Type"))

		switch contentEncoding {
		case "gzip":
			body = DumpGZIP(resp.Body)

		default:
			bodyByte, _ := ioutil.ReadAll(resp.Body)
			body = string(bodyByte)
			ioutil.WriteFile("cache/api_url.json", bodyByte, 0644)
		}

		logger.Traceln(body)

		return body, nil

	} else {
		logger.Tracef("resp %v", resp)
	}

	return "", nil
}
Пример #7
0
func parseMinuteCSV(filename string) (MinuteRecords []MinuteRecord) {

	// convert to standard csv file
	data2csv(filename, 3)

	file, err := os.Open(filename + ".csv")
	if err != nil {
		fmt.Println("ParseMinuteCSV Error:", err)
		return
	}
	defer file.Close()
	reader := csv.NewReader(file)
	/*
		record, err := reader.ReadAll()
		fmt.Println(record)
		return
	*/

	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			fmt.Println("Error:", err)
			return
		}

		if len(record) < 4 {
			fmt.Println("Error:", "record is zero, maybe it is not a cvs format!!!")
			return
		}

		var minRecord MinuteRecord
		minRecord.Time = record[0]
		minRecord.Price, err = strconv.ParseFloat(record[1], 64)
		if err != nil {
			logger.Fatalln(record)
			logger.Fatal("ParseMinuteCSV item price is not number")
		}
		minRecord.Volumn, err = strconv.ParseFloat(record[2], 64)
		if err != nil {
			logger.Fatal("ParseMinuteCSV item Volumn is not number")
		}
		minRecord.Amount, err = strconv.ParseFloat(record[3], 64)
		if err != nil {
			logger.Fatal("ParseMinuteCSV item Amount is not number")
		}

		MinuteRecords = append(MinuteRecords, minRecord)
	}

	return
}
Пример #8
0
func (w *BitvcTrade) Cancel_order(id string) bool {
	pParams := make(map[string]string)

	body, err := w.httpRequest(pParams)
	if err != nil {
		return false
	}
	_, ret := w.check_json_result(body)
	if ret == false {
		return false
	}

	doc := json.NewDecoder(strings.NewReader(body))

	type Msg struct {
		Result string
	}

	var m Msg
	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(m)

	if m.Result == "success" {
		return true
	} else {
		return false
	}
}
Пример #9
0
func (w *BitvcTrade) doTrade(method, price, amount string) int {
	pParams := make(map[string]string)

	body, err := w.httpRequest(pParams)
	if err != nil {
		return 0
	}
	_, ret := w.check_json_result(body)
	if ret == false {
		return 0
	}

	doc := json.NewDecoder(strings.NewReader(body))

	type Msg struct {
		Result string
		Id     int
	}

	var m Msg
	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Infoln(m)

	if m.Result == "success" {
		return m.Id
	} else {
		return 0
	}
}
Пример #10
0
func handleStaging(bbs bbs.StagerBBS, natsClient yagnats.NATSClient) {
	var task uint64

	natsClient.SubscribeWithQueue("stage", "stager", func(msg *yagnats.Message) {
		var message stagingMessage

		err := json.Unmarshal(msg.Payload, &message)
		if err != nil {
			logger.Fatal("staging-request.invalid", map[string]interface{}{
				"error":   err.Error(),
				"payload": string(msg.Payload),
			})
			return
		}

		for i := 0; i < message.Count; i++ {
			guid := atomic.AddUint64(&task, 1)

			task := &models.Task{
				Guid:     fmt.Sprintf("task-%d", guid),
				MemoryMB: message.MemoryMB,

				ReplyTo: msg.ReplyTo,
			}

			logger.Info("staging-request.desire", map[string]interface{}{
				"task": task,
			})

			go bbs.DesireTask(task)
		}
	})
}
Пример #11
0
func (w *OkcoinTrade) Get_account_info() (userInfo UserInfo, ret bool) {
	api_url := "https://www.okcoin.com/api/userinfo.do"
	pParams := make(map[string]string)
	pParams["partner"] = w.partner

	ret = true

	body, err := w.httpRequest(api_url, pParams)
	if err != nil {
		ret = false
		return
	}

	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	logger.Traceln(body)
	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&userInfo); err == io.EOF {
		ret = false
		logger.Traceln(err)
	} else if err != nil {
		ret = false
		logger.Fatal(err)
	}

	logger.Traceln(userInfo)

	return
}
Пример #12
0
func (w *OkcoinTrade) Get_order(symbol, order_id string) (m OrderTable, ret bool) {
	api_url := "https://www.okcoin.com/api/getorder.do"
	pParams := make(map[string]string)
	pParams["partner"] = w.partner
	pParams["symbol"] = symbol
	pParams["order_id"] = order_id

	ret = true

	body, err := w.httpRequest(api_url, pParams)
	if err != nil {
		ret = false
		return
	}

	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(m)

	return
}
Пример #13
0
func (w *OkcoinTrade) GetAccount() (userInfo UserInfo, ret bool) {
	pParams := make(map[string]string)
	pParams["partner"] = w.partner

	ret = true

	body, err := w.httpRequest(Config["ok_api_userinfo"], pParams)
	if err != nil {
		ret = false
		return
	}

	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	logger.Traceln(body)
	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&userInfo); err == io.EOF {
		ret = false
		logger.Traceln(err)
	} else if err != nil {
		ret = false
		logger.Fatal(err)
	}

	logger.Traceln(userInfo)

	return
}
Пример #14
0
func (w *BitvcTrade) Get_orders() (ret bool, m []HBOrderItem) {
	pParams := make(map[string]string)

	ret = true

	body, err := w.httpRequest(pParams)
	if err != nil {
		ret = false
		return
	}

	_, ret = w.check_json_result(body)
	if ret == false {
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(m)

	return
}
Пример #15
0
func (w *OkcoinTrade) check_json_result(body string) (errorMsg ErrorMsg, ret bool) {
	if strings.Contains(body, "result") != true {
		ret = false
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&errorMsg); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
		logger.Fatalln(body)
	}

	if errorMsg.Result != true {
		logger.Errorln(errorMsg)
		SetLastError(errorMsg.ErrorCode)
		ret = false
		return
	}

	ret = true
	return
}
Пример #16
0
func (w *Huobi) TradeKLinePeroid(peroid int) (ret bool) {
	req, err := http.NewRequest("GET", fmt.Sprintf(Config["trade_kline_url"], peroid, rand.Float64()), nil)
	if err != nil {
		logger.Fatal(err)
		return false
	}

	req.Header.Set("Referer", Config["trade_flash_url"])
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")

	logger.Traceln(req)

	if w.client == nil {
		w.client = &http.Client{nil, nil, nil}
	}
	resp, err := w.client.Do(req)
	if err != nil {
		logger.Errorln(err)
		return false
	}
	defer resp.Body.Close()
	if resp.StatusCode == 200 {
		var body string

		contentEncoding := resp.Header.Get("Content-Encoding")
		logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
		switch contentEncoding {
		case "gzip":
			body = DumpGZIP(resp.Body)

		default:
			bodyByte, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				logger.Errorln("read the http stream failed")
				return false
			} else {
				body = string(bodyByte)

				ioutil.WriteFile(fmt.Sprintf("cache/TradeKLine_%03d.data", peroid), bodyByte, os.ModeAppend)
			}
		}

		logger.Traceln(resp.Header.Get("Content-Type"))

		ret := strings.Contains(body, "您需要登录才能继续")
		if ret {
			logger.Traceln("您需要登录才能继续")
			return false
		} else {
			return w.AnalyzePeroidLine(fmt.Sprintf("cache/TradeKLine_%03d.data", peroid), body)
		}

	} else {
		logger.Tracef("HTTP returned status %v", resp)
	}

	return false
}
Пример #17
0
func getMonitorPath() (mpath string, err error) {
	cfg, err := goconfig.LoadConfigFile("./etc/live_box.conf")
	if err != nil {
		logger.Fatal("load config file live_box.conf failed!")
		return "", err
	}
	return cfg.GetValue("taskGenerator", "video_path")
}
Пример #18
0
func main() {
	install_logger()
	pid_file := "./var/run/video_merge.pid"
	pid_locker, err := pidlock.Lock_write_pid_file(pid_file)
	logger.Info("starting ...")
	//monitorpath := "/home/li_yun/Projects/test/go"
	monitorpath, err := getMonitorPath()
	if err != nil {
		logger.Fatal("get monitor path error: %s", err)
		os.Exit(1)
	}
	log.Println(monitorpath)
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		logger.Fatal("newWatcher error: %s", err)
	}

	done := make(chan bool)
	// Process events
	go func() {
		avfile_list := make(av_list)
		for {
			select {
			case ev := <-watcher.Event:
				(&avfile_list).process_in_moved_to(ev.Name)
			case err := <-watcher.Error:
				logger.Warn("errror: %s", err)
			}
		}
	}()

	// only monitor FSN_RENAME event
	err = watcher.WatchFlags(monitorpath, fsnotify.FSN_MOVEDTO)
	if err != nil {
		logger.Fatal("add watch flags error: %s", err)
	}

	<-done
	/* ... do stuff ... */
	watcher.Close()
	pid_locker.Close()
	logger.Info("done ...")

}
Пример #19
0
func handleTasks(bbs bbs.StagerBBS, natsClient yagnats.NATSClient, listenAddr string) {
	err := http.ListenAndServe(listenAddr, &Handler{
		bbs:        bbs,
		natsClient: natsClient,
	})

	logger.Fatal("handling.failed", map[string]interface{}{
		"error": err.Error(),
	})
}
Пример #20
0
func handleTasks(bbs bbs.ExecutorBBS, listenAddr string) {
	err := http.ListenAndServe(listenAddr, &Handler{
		bbs: bbs,

		currentMemory: *maxMemory,
		memoryMutex:   &sync.Mutex{},
	})

	logger.Fatal("handling.failed", map[string]interface{}{
		"error": err.Error(),
	})
}
Пример #21
0
func (w *Okcoin) getOrderBook(symbol string) (ret bool, orderBook OrderBook) {
	//init to false
	ret = false
	req, err := http.NewRequest("GET", fmt.Sprintf(Config["ok_depth_url"], symbol), nil)
	if err != nil {
		logger.Fatal(err)
		return
	}

	req.Header.Set("Referer", Config["ok_base_url"])
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36")

	logger.Traceln(req)

	c := util.NewTimeoutClient()
	logger.Tracef("HTTP req begin getOrderBook")
	resp, err := c.Do(req)
	logger.Tracef("HTTP req end getOrderBook")
	if err != nil {
		logger.Traceln(err)
		return
	}

	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		logger.Errorf("HTTP returned status %v", resp)
		return
	}

	var body string
	contentEncoding := resp.Header.Get("Content-Encoding")
	logger.Tracef("HTTP returned Content-Encoding %s", contentEncoding)
	switch contentEncoding {
	case "gzip":
		body = util.DumpGZIP(resp.Body)

	default:
		bodyByte, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.Errorln("read the http stream failed")
			return
		} else {
			body = string(bodyByte)

			ioutil.WriteFile("cache/okdepth.json", bodyByte, 0644)
		}
	}

	return w.analyzeOrderBook(body)
}
Пример #22
0
func (avl *av_list) process_in_moved_to(file string) error {
	var (
		f_a, f_v   string
		outf       string
		channel_id string
	)

	// check the file name is like ./1.1111111.1111111.a.mp4
	splitedfile := strings.Split(file, ".")
	if len(splitedfile) == 5 {
		channel_id = splitedfile[0]
	} else {
		logger.Warn("file %s is error", file)
	}

	if f, ok := (*avl)[channel_id]; ok {
		delete(*avl, channel_id)

		if string(splitedfile[3]) == "a" {
			f_a = file
			f_v = f
			outf = strings.Join(strings.Split(f, ".")[0:3], ".") + ".mp4"
		} else if string(splitedfile[3]) == "v" {
			f_v = file
			f_a = f
			outf = strings.Join(strings.Split(f, ".")[0:3], ".") + ".mp4"
		}
		logger.Info("f_v: " + f_v + ", f_a: " + f_a + ", outf: " + outf)

		time.Sleep(time.Duration(time.Second * 5))
		// merge video and audio
		cmd := exec.Command("ffmpeg", "-y", "-i", f_v, "-i", f_a, "-codec", "copy", outf)
		//cmd := exec.Command("ffmpeg", " -y -i ", f_v, "-i ", f_a, " -codec copy ", outf, " >/dev/null 2>&1 ")
		logger.Info("cmd's args is: ", cmd.Args)
		err := cmd.Run()
		if err != nil {
			logger.Fatal("ffmpeg merge video error:", err)
		} else {
			cmd = exec.Command("rm", "-f", f_v, " ", f_a)
			err = cmd.Run()
			if err != nil {
				logger.Warn("rm files error: %s", err)
			}
		}
	} else {
		(*avl)[channel_id] = file
	}
	return nil
}
Пример #23
0
func registerHandler(etcdAdapter *etcdstoreadapter.ETCDStoreAdapter, addr string, ready chan<- bool) error {
	node := storeadapter.StoreNode{
		Key: "/v1/routes/round-robin/executor/" + addr,
		TTL: 60,
	}

	status, clearNode, err := etcdAdapter.MaintainNode(node)
	if err != nil {
		return err
	}

	tasks.Add(1)

	go func() {
		for {
			select {
			case locked, ok := <-status:
				if locked && ready != nil {
					ready <- true
					ready = nil
				}

				if !locked && ok {
					tasks.Done()
					logger.Fatal("maintain.route.fatal", map[string]interface{}{})
				}

				if !ok {
					tasks.Done()
					return
				}

			case <-stop:
				close(clearNode)

				for _ = range status {
				}

				tasks.Done()

				return
			}
		}
	}()

	return nil
}
Пример #24
0
func maintainPresence(bbs bbs.ExecutorBBS, ready chan<- bool) error {
	p, statusChannel, err := bbs.MaintainExecutorPresence(*heartbeatInterval, executorID)
	if err != nil {
		ready <- false
		return err
	}

	tasks.Add(1)

	go func() {
		for {
			select {
			case locked, ok := <-statusChannel:
				if locked && ready != nil {
					ready <- true
					ready = nil
				}

				if !locked && ok {
					tasks.Done()
					logger.Fatal("maintain.presence.fatal", map[string]interface{}{})
				}

				if !ok {
					tasks.Done()
					return
				}

			case <-stop:
				p.Remove()

				for _ = range statusChannel {
				}

				tasks.Done()

				return
			}
		}
	}()

	return nil
}
Пример #25
0
func (w *HuobiTrade) doTrade(method, price, amount string) int {
	pParams := make(map[string]string)
	pParams["method"] = method
	pParams["access_key"] = w.access_key
	pParams["price"] = price
	pParams["amount"] = amount
	now := time.Now().Unix()
	pParams["created"] = strconv.FormatInt(now, 10)
	pParams["sign"] = w.createSign(pParams)

	body, err := w.httpRequest(pParams)
	if err != nil {
		return 0
	}
	_, ret := w.check_json_result(body)
	if ret == false {
		return 0
	}

	doc := json.NewDecoder(strings.NewReader(body))

	type Msg struct {
		Result string
		Id     int
	}

	var m Msg
	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Infoln(m)

	if m.Result == "success" {
		return m.Id
	} else {
		return 0
	}
}
Пример #26
0
func (w *OkcoinTrade) doTrade(symbol, method, rate, amount string) int {
	api_url := "https://www.okcoin.com/api/trade.do"
	pParams := make(map[string]string)
	pParams["partner"] = w.partner
	pParams["symbol"] = symbol
	pParams["type"] = method
	pParams["rate"] = rate
	pParams["amount"] = amount

	body, err := w.httpRequest(api_url, pParams)
	if err != nil {
		return 0
	}
	_, ret := w.check_json_result(body)
	if ret == false {
		return 0
	}

	doc := json.NewDecoder(strings.NewReader(body))

	type Msg struct {
		Result   bool
		Order_id int
	}

	var m Msg
	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(m)

	if m.Result == true {
		return m.Order_id
	} else {
		return 0
	}
}
Пример #27
0
func (w *HuobiTrade) Cancel_order(id string) bool {
	pParams := make(map[string]string)
	pParams["method"] = "cancel_order"
	pParams["access_key"] = w.access_key
	pParams["id"] = id
	now := time.Now().Unix()
	pParams["created"] = strconv.FormatInt(now, 10)
	pParams["sign"] = w.createSign(pParams)

	body, err := w.httpRequest(pParams)
	if err != nil {
		return false
	}
	_, ret := w.check_json_result(body)
	if ret == false {
		return false
	}

	doc := json.NewDecoder(strings.NewReader(body))

	type Msg struct {
		Result string
	}

	var m Msg
	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(m)

	if m.Result == "success" {
		return true
	} else {
		return false
	}
}
Пример #28
0
func (w *OkcoinTrade) Cancel_order(symbol, order_id string) bool {
	pParams := make(map[string]string)
	pParams["partner"] = w.partner
	pParams["symbol"] = symbol
	pParams["order_id"] = order_id

	body, err := w.httpRequest(Config["ok_api_cancelorder"], pParams)
	if err != nil {
		return false
	}
	_, ret := w.check_json_result(body)
	if ret == false {
		return false
	}

	doc := json.NewDecoder(strings.NewReader(body))

	type Msg struct {
		Result   bool
		Order_id int
	}

	var m Msg
	if err := doc.Decode(&m); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	logger.Traceln(m)

	if m.Result == true {
		return true
	} else {
		logger.Infoln(m)

		return false
	}
}
Пример #29
0
func convergeTasks(bbs bbs.ExecutorBBS) {
	statusChannel, releaseLock, err := bbs.MaintainConvergeLock(*convergenceInterval, executorID)
	if err != nil {
		logger.Fatal("converge-lock.acquire-failed", map[string]interface{}{
			"error": err.Error(),
		})
	}

	for {
		select {
		case locked, ok := <-statusChannel:
			if !ok {
				return
			}

			if locked {
				t := time.Now()

				logger.Info("converging", map[string]interface{}{})

				bbs.ConvergeTasks(*timeToClaimTask)

				logger.Info("converged", map[string]interface{}{
					"took": time.Since(t),
				})
			} else {
				logger.Info("converge-lock.lost", map[string]interface{}{})
			}
		case <-stop:
			close(releaseLock)

			for _ = range statusChannel {
			}

			return
		}
	}
}
Пример #30
0
func (w *HuobiTrade) check_json_result(body string) (errorMsg ErrorMsg, ret bool) {
	if strings.Contains(body, "code") != true {
		ret = true
		return
	}

	doc := json.NewDecoder(strings.NewReader(body))

	if err := doc.Decode(&errorMsg); err == io.EOF {
		logger.Traceln(err)
	} else if err != nil {
		logger.Fatal(err)
	}

	if errorMsg.Code != 0 {
		logger.Errorln(errorMsg)
		ret = false
		return
	}

	ret = true
	return
}