// PreFilter 执行 handler 之前的过滤方法 func (this *SensitiveFilter) PreFilter(rw http.ResponseWriter, req *http.Request) bool { logger.Debugln("SensitiveFilter PreFilter...") content := req.FormValue("content") title := req.FormValue("title") if title == "" && content == "" { return true } curUser, _ := CurrentUser(req) // 标题特殊处理 for _, s := range titleSensitives { if util.HasSensitiveChar(title, s) { // 把账号冻结 service.UpdateUserStatus(curUser["uid"].(int), model.StatusFreeze) logger.Infoln("user="******"uid"], "publish ad, title=", title, ";content=", content, ". freeze") return false } } sensitive := config.Config["sensitive"] if util.HasSensitive(title, sensitive) || util.HasSensitive(content, sensitive) { // 把账号冻结 service.UpdateUserStatus(curUser["uid"].(int), model.StatusFreeze) logger.Infoln("user="******"uid"], "publish ad, title=", title, ";content=", content, ". freeze") return false } return true }
func (w *PeatioTrade) Get_order(id string) (ret bool, m HBOrder) { pParams := make(map[string]string) pParams["method"] = "order_info" pParams["access_key"] = w.access_key pParams["id"] = id 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 logger.Infoln(err) return } _, ret = w.check_json_result(body) if ret == false { logger.Infoln(body) return } doc := json.NewDecoder(strings.NewReader(body)) if err := doc.Decode(&m); err == io.EOF { ret = false logger.Infoln(err) } else if err != nil { ret = false logger.Infoln(err) } return }
func Sell() string { if PrevTrade == "sell" { return "0" } // compute the price price, _, warning := getSellPrice() // compute the amount Available_coin := GetAvailable_coin() if Available_coin < 0.01 { warning = "没有足够的币" logger.Infoln(warning) PrevTrade = "sell" PrevBuyPirce = 0 return "0" } amount := Option["tradeAmount"] nAmount, err := strconv.ParseFloat(amount, 64) if err != nil { logger.Infoln("amount is not float") return "0" } if nAmount > Available_coin { nAmount = Available_coin amount = fmt.Sprintf("%02f", nAmount) } sellID := sell(price, amount) if sellID == "-1" { warning += " [模拟]" } else if sellID == "0" { warning += "[委托失败]" } else { warning += "[委托成功]" + sellID } logger.Infoln(warning) var coin string if Option["symbol"] == "btc_cny" { coin = "比特币" } else { coin = "莱特币" } if sellID != "0" { if !GetBacktest() { logger.Tradef("在%s,根据策略%s周期%s,以价格%s卖出%s个%s\n", Option["tradecenter"], Option["strategy"], Option["tick_interval"], price, amount, coin) go email.TriggerTrender(warning) } else { t := time.Unix(GetBtTime(), 0) logger.Backtestf("%s 在simulate,根据策略%s周期%s,以价格%s卖出%s个%s\n", t.Format("2006-01-02 15:04:05"), Option["strategy"], Option["tick_interval"], price, amount, coin) } } return sellID }
func (w Okcoin) Buy(tradePrice, tradeAmount string) bool { tradeAPI := NewOkcoinTrade(SecretOption["ok_partner"], SecretOption["ok_secret_key"]) var buyId string symbol := Option["symbol"] if symbol == "btc_cny" { buyId = tradeAPI.BuyBTC(tradePrice, tradeAmount) } else if symbol == "ltc_cny" { buyId = tradeAPI.BuyLTC(tradePrice, tradeAmount) } if buyId != "0" { logger.Infoln("执行买入委托成功", tradePrice, tradeAmount) } else { logger.Infoln("执行买入委托失败", tradePrice, tradeAmount) } time.Sleep(3 * time.Second) _, ret := w.Get_account_info() if !ret { logger.Infoln("Get_account_info failed") } if buyId != "0" { return true } else { return false } }
func (w *BitvcTrade) Get_order(id string) (ret bool, m HBOrder) { pParams := make(map[string]string) ret = true body, err := w.httpRequest(pParams) if err != nil { ret = false logger.Infoln(err) return } _, ret = w.check_json_result(body) if ret == false { logger.Infoln(body) return } doc := json.NewDecoder(strings.NewReader(body)) if err := doc.Decode(&m); err == io.EOF { ret = false logger.Infoln(err) } else if err != nil { ret = false logger.Infoln(err) } return }
func (w Huobi) Buy(tradePrice, tradeAmount string) bool { tradeAPI := NewHuobiTrade(SecretOption["huobi_access_key"], SecretOption["huobi_secret_key"]) var buyId string if Option["symbol"] == "btc_cny" { buyId = tradeAPI.BuyBTC(tradePrice, tradeAmount) } else if Option["symbol"] == "ltc_cny" { buyId = tradeAPI.BuyLTC(tradePrice, tradeAmount) } if buyId != "0" { logger.Infoln("执行买入委托成功", tradePrice, tradeAmount) } else { logger.Infoln("执行买入委托失败", tradePrice, tradeAmount) } time.Sleep(3 * time.Second) _, ret := w.Get_account_info() if !ret { logger.Infoln("Get_account_info failed") } if buyId != "0" { return true } else { return false } }
func Buy() string { if PrevTrade == "buy" { return "0" } //init isStoploss = false //compute the price price, nPrice, warning := getBuyPrice() //compute the amount amount := Option["tradeAmount"] nAmount, err := strconv.ParseFloat(amount, 64) if err != nil { logger.Infoln("amount is not float") return "0" } Available_cny := GetAvailable_cny() if Available_cny < nPrice*nAmount { var nMinTradeAmount float64 nAmount = Available_cny / nPrice symbol := Option["symbol"] if symbol == "btc_cny" { nMinTradeAmount = 0.1 } else { nMinTradeAmount = 0.01 } if nAmount < nMinTradeAmount { warning += "没有足够的法币余额" logger.Infoln(warning) PrevTrade = "buy" PrevBuyPirce = nPrice return "0" } amount = fmt.Sprintf("%02f", nAmount) } warning += "---->数量" + amount buyID := buy(price, amount) if buyID == "-1" { warning += " [模拟]" } else if buyID == "0" { warning += "[委托失败]" } else { warning += "[委托成功]" + buyID } logger.Infoln(warning) go email.TriggerTrender(warning) return buyID }
func indexing(isAll bool) { logger.Infoln("indexing start...") start := time.Now() defer func() { logger.Infoln("indexing spend time:", time.Now().Sub(start)) }() service.Indexing(isAll) }
func (w *Huobi) trade(emaShort, emaLong []float64, EMAMinThreshold float64, TresholdLevel int, length int, tradeOnlyAfterSwitch int, tradeAmount string) { currentTrend := getTrendAtIndex(emaShort, emaLong, EMAMinThreshold, TresholdLevel, length-1) logger.Debugln("currentTrend is ", currentTrend) if currentTrend > 1 { // Trend is up if currentTrend == 3 { // Trend is up, also according to the "Buy after X samples"-setting if (tradeOnlyAfterSwitch == 1) && (w.latestSolidTrend == 3) { // tradeOnlyAfterSwitch==true but the trend has not switched: Don't trade logger.Debugln("Trend has not switched (still up). The setting \"tradeOnlyAfterSwitch==true\", so do not trade...") return } w.latestSolidTrend = 3 if Option["disable_trading"] == "1" { logger.Debugln("Simulted BUY (Simulation only: no trade was made)") } else { logger.Infoln("Trend has switched, 探测到买入点") go service.TriggerTrender("探测到买入点") w.Do_buy(w.getTradePrice("buy"), tradeAmount) } //logger.Infoln("Trend is up, but no " + currency + " to spend..."); } else { logger.Debugf("Trend is up, but not for long enough (needs to be \"up\" for at least %d samples)\n", TresholdLevel) } } else if currentTrend < -1 { // Trend is down if currentTrend == -3 { // Trend is down, also according to the "Sell after X samples"-setting if (tradeOnlyAfterSwitch == 1) && (w.latestSolidTrend == -3) { // tradeOnlyAfterSwitch==true but the trend has not switched: Don't trade logger.Debugln("Trend has not switched (still down). The setting \"tradeOnlyAfterSwitch==true\", so do not trade...") return } w.latestSolidTrend = -3 if Option["disable_trading"] == "1" { logger.Infoln("Simulted SELL (Simulation only: no trade was made)") } else { logger.Infoln("Trend has switched, 探测到卖出点") go service.TriggerTrender("探测到卖出点") w.Do_sell(w.getTradePrice("sell"), tradeAmount) } //logger.Infoln("Trend is down, but no BTC to sell..."); } else { logger.Debugf("Trend is down, but not for long enough (needs to be \"down\" for at least t %d samples)\n", TresholdLevel) } } else { logger.Debugln("Trend is undefined/weak") } }
func supervisor(mess chan message) { for i := 0; i < worker_number; i++ { m := <-mess switch m.normal { case true: logger.Infoln("exit normal, nothing serious!") case false: logger.Infoln("exit abnormal, something went wrong") } } }
func sell(price, amount string) string { Available_coin := GetAvailable_coin() if Available_coin < 0.01 { warning = "没有足够的币" logger.Infoln(warning) PrevTrade = "sell" PrevBuyPirce = 0 return "0" } nAmount, err := strconv.ParseFloat(amount, 64) if err != nil { logger.Infoln("amount is not float") return "0" } if nAmount > Available_coin { nAmount = Available_coin amount = fmt.Sprintf("%02f", nAmount) } var sellID string if Option["enable_trading"] == "1" { sellID = gTradeAPI.Sell(price, amount) } else { sellID = "-1" } if sellID != "0" { timestamp := time.Now() magic += 1 if !GetBacktest() { err := db.SetTx("sell", sellID, timestamp.Unix(), price, amount, magic) if err != nil { fmt.Println("SetTx", err) } } sellOrders[timestamp] = sellID PrevTrade = "sell" PrevBuyPirce = 0 } if !GetBacktest() { cmd, id, timestamp, amount, price, magic, err := db.GetTx(sellID) if err != nil { fmt.Println("GetTx", err) } else { fmt.Println("sell items:", cmd, id, timestamp, amount, price, magic) } } return sellID }
func (w Huobi) GetOrders() (ret bool, orders []HBOrder) { tradeAPI := NewHuobiTrade(SecretOption["huobi_access_key"], SecretOption["huobi_secret_key"]) ret, orders = tradeAPI.Get_orders() if ret { logger.Infoln("Get orders ok", len(orders)) } else { logger.Infoln("Get orders failed") } return }
func doTradeDelegation() { huobi := huobiapi.NewHuobi() logger.Infoln("doTradeDelegation start....") if huobi.Login() == true { logger.Debugln("Login successfully.") huobi.TradeDelegation() } else { logger.Debugln("Login failed.") } logger.Infoln("doTradeDelegation end-----") }
func (w *BitvcTrade) Do_sell(tradePrice, tradeAmount string) bool { if w.Login() == true { if w.TradeAdd("do_sell", tradePrice, tradeAmount) == true { logger.Infoln("执行卖出委托成功", tradePrice, tradeAmount) return true } else { logger.Infoln("执行卖出失败,原因:卖出操作被服务器拒绝", tradePrice, tradeAmount) } } else { logger.Infoln("执行卖出失败,原因:登陆失败", tradePrice, tradeAmount) } return false }
func doTradeDelegation() { huobi := huobiapi.NewHuobi() logger.Infoln("doTradeDelegation start....") if huobi.Login() == true { console.SetColor(console.FOREGROUND_GREEN) logger.Debugln("Login successfully.") huobi.TradeDelegation() } else { logger.Debugln("Login failed.") } logger.Infoln("doTradeDelegation end-----") }
func (w *Huobi) OrderBook(body string) bool { body = strings.TrimPrefix(body, "view_detail(") body = strings.TrimSuffix(body, ")") ioutil.WriteFile("cache/OrderBook.json", []byte(body), 0644) var orderBook OrderBook if err := json.Unmarshal([]byte(body), &orderBook); err != nil { logger.Infoln(err) return false } logger.Infoln(orderBook) return true }
func main() { version := "0.19" fmt.Println("[ ---------------------------------------------------------->>> ") fmt.Println(" BTC robot version ", version) fmt.Println(" *BTC操盘手自动化交易引擎*") fmt.Println(" btcrobot is a Bitcoin trading bot for HUOBI.com written") fmt.Println(" in golang, it features multiple trading methods using") fmt.Println(" technical analysis.") fmt.Println(" ") fmt.Println(" Disclaimer:") fmt.Println(" ") fmt.Println(" USE AT YOUR OWN RISK!") fmt.Println("") fmt.Println(" The author of this project is NOT responsible for any damage or loss caused") fmt.Println(" by this software. There can be bugs and the bot may not perform as expected") fmt.Println(" or specified. Please consider testing it first with paper trading /") fmt.Println(" backtesting on historical data. Also understand what how it's working.") fmt.Println("") fmt.Println(" *@author [btcrobot Team]") fmt.Println(" *@feedback http://weibo.com/bocaicfa") if AuthLicence() { fmt.Println(" *Licence授权:", Licence["user_email"]) } else { fmt.Println(" *无效的授权:", Licence["user_email"], Licence["licence"]) } fmt.Println(" *@Open http://127.0.0.1:9090 in browser to config the robot") fmt.Println(" *@机器人运行中,请在浏览器中打开 http://127.0.0.1:9090 配置相关参数") fmt.Println(" *@警告:API key和密码存放在conf/secret.json文件内,共享给他人前请务必删除,注意账号安全!!") fmt.Println(" <<<----------------------------------------------------------] ") SavePid() //TestTradeAPI() go tradeService() // 服务静态文件 http.Handle("/static/", http.FileServer(http.Dir(ROOT))) router := initRouter() http.Handle("/", router) if Config["env"] == "test" { logger.Infoln(http.ListenAndServe("0.0.0.0:8080", nil)) } else { logger.Infoln(http.ListenAndServe(Config["host"], nil)) } time.Sleep(time.Millisecond * 100 * 60 * 60 * 1000) }
func (w Okcoin) GetAccount() (account Account, ret bool) { tradeAPI := NewOkcoinTrade(SecretOption["ok_partner"], SecretOption["ok_secret_key"]) userInfo, ret := tradeAPI.GetAccount() logger.Infoln("account:", userInfo) if !ret { logger.Traceln("okcoin GetAccount failed") return } else { logger.Traceln(userInfo) account.Available_cny = userInfo.Info.Funds.Free.CNY account.Available_btc = userInfo.Info.Funds.Free.BTC account.Available_ltc = userInfo.Info.Funds.Free.LTC account.Frozen_cny = userInfo.Info.Funds.Freezed.CNY account.Frozen_btc = userInfo.Info.Funds.Freezed.BTC account.Frozen_ltc = userInfo.Info.Funds.Freezed.LTC logger.Infof("okcoin资产: \n 可用cny:%-10s \tbtc:%-10s \tltc:%-10s \n 冻结cny:%-10s \tbtc:%-10s \tltc:%-10s\n", account.Available_cny, account.Available_btc, account.Available_ltc, account.Frozen_cny, account.Frozen_btc, account.Frozen_ltc) //logger.Infoln(Account) return } }
// 将所有 节点信息 加载到内存中:后台修改节点时,重新加载一次 func LoadNodes() error { nodeList, err := model.NewTopicNode().FindAll() if err != nil { logger.Errorln("获取节点数据失败:", err) return err } nodeNum := len(nodeList) tmpNodeList := make(map[int]*model.TopicNode, nodeNum) for _, node := range nodeList { tmpNodeList[node.Nid] = node } nodeRWMutex.Lock() defer nodeRWMutex.Unlock() AllNode = make([]map[string]interface{}, nodeNum) for i, node := range nodeList { nodeMap := make(map[string]interface{}, 5) nodeMap["pid"] = node.Parent if node.Parent == 0 { nodeMap["parent"] = "根节点" } else { nodeMap["parent"] = tmpNodeList[node.Parent].Name } nodeMap["nid"] = node.Nid nodeMap["name"] = node.Name nodeMap["intro"] = node.Intro nodeMap["ctime"] = node.Ctime AllNode[i] = nodeMap } logger.Infoln("LoadNodes successfully!") return nil }
// Find 查找单条数据 // colFieldMap 数据库表中列对应go中对象的字段 func (this *Dao) Find(colFieldMap map[string]interface{}, selectCol ...string) error { colNum := len(selectCol) if colNum == 0 || (colNum == 1 && selectCol[0] == "*") { selectCol = util.MapKeys(colFieldMap) } sort.Sort(sort.StringSlice(selectCol)) this.selectCols = "`" + strings.Join(selectCol, "`,`") + "`" strSql := util.SelectSql(this) logger.Debugln("Find sql:", strSql) err := this.Open() if err != nil { return err } defer this.Close() row := this.QueryRow(strSql, this.whereVal...) scanInterface := make([]interface{}, 0, colNum) for _, column := range selectCol { scanInterface = append(scanInterface, colFieldMap[column]) } err = row.Scan(scanInterface...) if err == sql.ErrNoRows { logger.Infoln("Find", strSql, ":no result ret") return nil } return err }
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 } }
func startWEBserver() { // 服务静态文件 http.Handle("/static/", http.FileServer(http.Dir(ROOT))) router := initRouter() http.Handle("/", router) if Config["env"] == "test" { logger.Infoln(http.ListenAndServe("0.0.0.0:9090", nil)) } else { logger.Infoln(http.ListenAndServe(Config["host"], nil)) } fmt.Println("[ ---------------------------------------------------------->>> ") fmt.Printf("start web server failed, please check if %s is already used.", Config["host"]) fmt.Println(" <<<----------------------------------------------------------] ") }
// 将所有 角色拥有的权限 加载到内存中;后台修改时,重新加载一次 func LoadRoleAuthorities() error { roleAuthorities, err := model.NewRoleAuthority().FindAll() if err != nil { logger.Errorln("LoadRoleAuthorities role_authority read fail:", err) return err } roleAuthLocker.Lock() defer roleAuthLocker.Unlock() RoleAuthorities = make(map[int][]int) for _, roleAuth := range roleAuthorities { roleId := roleAuth.Roleid if authorities, ok := RoleAuthorities[roleId]; ok { RoleAuthorities[roleId] = append(authorities, roleAuth.Aid) } else { RoleAuthorities[roleId] = []int{roleAuth.Aid} } } logger.Infoln("LoadRoleAuthorities successfully!") return nil }
// 将所有 角色 加载到内存中;后台修改角色时,重新加载一次 func LoadRoles() error { roles, err := model.NewRole().FindAll() if err != nil { logger.Errorln("LoadRoles role read fail:", err) return err } if len(roles) == 0 { logger.Errorln("LoadRoles role read fail: num is 0") return errors.New("no role") } roleLocker.Lock() defer roleLocker.Unlock() maxRoleid := roles[len(roles)-1].Roleid Roles = make([]*model.Role, maxRoleid) // 由于角色不多,而且一般角色id是连续自增的,因此这里以角色id当slice的index for _, role := range roles { Roles[role.Roleid-1] = role } logger.Infoln("LoadRoles successfully!") return nil }
// 保存晨读 func SaveReading(form url.Values, username string) (errMsg string, err error) { reading := model.NewMorningReading() err = util.ConvertAssign(reading, form) if err != nil { logger.Errorln("reading SaveReading error", err) errMsg = err.Error() return } reading.Moreurls = strings.TrimSpace(reading.Moreurls) if strings.Contains(reading.Moreurls, "\n") { reading.Moreurls = strings.Join(strings.Split(reading.Moreurls, "\n"), ",") } reading.Username = username logger.Infoln(reading.Rtype, "id=", reading.Id) if reading.Id != 0 { err = reading.Persist(reading) } else { _, err = reading.Insert() } if err != nil { errMsg = "内部服务器错误" logger.Errorln("reading save:", errMsg, ":", err) return } return }
func getOrderPrice() (sell1, buy1 float64, ret bool) { ret, orderBook := GetOrderBook() if !ret { logger.Infoln("get orderBook failed 1") ret, orderBook = GetOrderBook() //try again if !ret { logger.Infoln("get orderBook failed 2") return 0, 0, ret } } logger.Infoln("卖一", orderBook.Asks[len(orderBook.Asks)-1]) logger.Infoln("买一", orderBook.Bids[0]) return orderBook.Asks[len(orderBook.Asks)-1].Price, orderBook.Bids[0].Price, ret }
func init() { var err error gpdb, err = CreateDB("tx.db") if err != nil { fmt.Println(err) logger.Infoln("init db failed!") } }
// 给所有用户广播消息 func (this *book) BroadcastAllUsersMessage(message *Message) { logger.Infoln("BroadcastAllUsersMessage message", message) for _, userData := range this.users { for _, messageQueue := range userData.serverMsgQueue { messageQueue <- message } } }
// 给某个用户发送一条消息 func (this *book) PostMessage(uid int, message *Message) { if userData, ok := this.users[uid]; ok { logger.Infoln("post message to", uid, message) for _, messageQueue := range userData.serverMsgQueue { messageQueue <- message } } }
// 发送电子邮件功能 func SendMail(subject, content string, tos []string) error { message := `From: btc-robot To: ` + strings.Join(tos, ",") + ` Subject: ` + subject + ` Content-Type: text/html;charset=UTF-8 ` + content auth := smtp.PlainAuth("", SecretOption["smtp_username"], SecretOption["smtp_password"], SecretOption["smtp_host"]) err := smtp.SendMail(SecretOption["smtp_addr"], auth, Option["from_email"], tos, []byte(message)) if err != nil { logger.Infoln("Send Mail to", strings.Join(tos, ","), "error:", err) return err } logger.Infoln("Send Mail to", strings.Join(tos, ","), "Successfully") return nil }