Skip to content

Commit

Permalink
ordermodel and sawp
Browse files Browse the repository at this point in the history
  • Loading branch information
jesusmzb committed Jan 16, 2023
1 parent 7da67ae commit c5f0bf0
Show file tree
Hide file tree
Showing 9 changed files with 254 additions and 14 deletions.
16 changes: 14 additions & 2 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,26 @@ import (
"gorm.io/gorm"
)

var db *gorm.DB
var err error

func InitDatabase(direction string) {
//para la base de datos usamos go orm, y por practicidad de este proyecto usamos el driver sql lite
//en go orm se puede remplazar el driver por otro
db, err := gorm.Open(sqlite.Open(direction), &gorm.Config{})
db, err = gorm.Open(sqlite.Open(direction), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
db.AutoMigrate(&models.Order{})
db.AutoMigrate(&models.OrderBookEntity{})
db.AutoMigrate(&models.OrderEntity{})

}

func OrderBookStore(model models.OrderBookEntity) {
db.Create(&model)
}

func OrderStore(model models.OrderEntity) {
db.Create(&model)
}
Binary file modified database/servertestgo.sqlite
Binary file not shown.
63 changes: 63 additions & 0 deletions handlers/estimate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package handlers

import (
"encoding/json"
"fmt"
"net/http"
"servertestgo/database"
"servertestgo/models"
"servertestgo/services"
"strings"
"time"

"github.com/labstack/echo/v4"
)

type responseEstimate struct {
ValorBuy string
ValorSell string
Vigency time.Time
error string
}

func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}

return false
}

func Estimate(c echo.Context) error {
fmt.Println("Se solicito la estimación")
nameEstimate := c.Param("name")
fmt.Println("nameEstimate:", nameEstimate)
var response responseEstimate
currecyaceptables := []string{"1INCH-USD", "1INCH-USDT", "AAVE-USDT", "ADA-USD", "ADA-USDT", "AGLD-USDT", "ALGO-USD", "ALGO-USDT", "ALPHA-USDT", "ANT-USDT", "APE-USDT", "API3-USDT", "APT-USDT", "ATOM-USD", "ATOM-USDT", "AVAX-USD", "AVAX-USDT", "AXS-USDT", "BADGER-USDT", "BAL-USDT", "BAND-USDT", "BAT-USDT", "BCH-USD", "BCH-USDT", "BICO-USDT", "BNB-USDT", "BNT-USDT", "BSV-USD", "BSV-USDT", "BTC-USDC", "BTC-USD", "BTC-USDT", "CELO-USDT", "CEL-USDT", "CFX-USDT", "CHZ-USDT", "COMP-USDT", "CRO-USDT", "CRV-USD", "CRV-USDT", "CSPR-USDT", "CVC-USDT", "DASH-USD", "DASH-USDT", "DOGE-USD", "DOGE-USDT", "DOME-USDT", "DORA-USDT", "DOT-USD", "DOT-USDT", "DYDX-USDT", "EGLD-USDT", "ENJ-USDT", "ENS-USDT", "EOS-USD", "EOS-USDT", "ETC-USD", "ETC-USDT", "ETH-USDC", "ETH-USD", "ETH-USDT", "ETHW-USDT", "FIL-USD", "FIL-USDT", "FITFI-USDT", "FLM-USDT", "FTM-USDT", "GALA-USDT", "GMT-USDT", "GODS-USDT", "GRT-USD", "GRT-USDT", "ICP-USDT", "IMX-USDT", "IOST-USDT", "IOTA-USDT", "JST-USDT", "KISHU-USDT", "KLAY-USDT", "KNC-USDT", "KSM-USD", "KSM-USDT", "LINK-USD", "LINK-USDT", "LOOKS-USDT", "LPT-USDT", "LRC-USDT", "LTC-USD", "LTC-USDT", "LUNA-USDT", "LUNC-USDT", "MANA-USD", "MANA-USDT", "MASK-USDT", "MATIC-USDT", "MINA-USDT", "MKR-USDT", "NEAR-USDT", "NEO-USD", "NEO-USDT", "NFT-USDT", "OMG-USDT", "ONT-USDT", "OP-USDT", "PEOPLE-USDT", "PERP-USDT", "QTUM-USDT", "REN-USDT", "RSR-USDT", "RVN-USDT", "SAND-USD", "SAND-USDT", "SHIB-USDT", "SLP-USDT", "SNX-USDT", "SOL-USD", "SOL-USDT", "STARL-USDT", "STORJ-USDT", "SUSHI-USD", "SUSHI-USDT", "SWEAT-USDT", "THETA-USD", "THETA-USDT", "TON-USDT", "TRB-USDT", "TRX-USD", "TRX-USDT", "UMA-USDT", "UNI-USD", "UNI-USDT", "USTC-USDT", "WAVES-USDT", "XCH-USDT", "XLM-USD", "XLM-USDT", "XMR-USD", "XMR-USDT", "XRP-USD", "XRP-USDT", "XTZ-USDT", "YFII-USDT", "YFI-USD", "YFI-USDT", "YGG-USDT", "ZEC-USD", "ZEC-USDT", "ZEN-USDT", "ZIL-USDT", "ZRX-USDT"}
if len(nameEstimate) < 5 {
response.error = "el par dado no es valido , debe estar entre " + strings.Join(currecyaceptables, " ")
u, _ := json.Marshal(response)
return c.String(http.StatusPartialContent, string(u))
}
if contains(currecyaceptables, nameEstimate) == false {
response.error = "el par dado no es valido , debe estar entre " + strings.Join(currecyaceptables, " ")
u, _ := json.Marshal(response)
return c.String(http.StatusPartialContent, string(u))
}
fmt.Println(nameEstimate)
myOrderBook := services.SolicitarBookOrder(nameEstimate)
response.ValorBuy = myOrderBook.Data[0].Asks[0][0]
response.ValorSell = myOrderBook.Data[0].Bids[0][0]
response.Vigency = time.Now().Add(time.Second * 10)
u, _ := json.Marshal(response)
datastorage := models.OrderBookEntity{
Currency: nameEstimate,
ValorBuy: response.ValorBuy,
ValorSell: response.ValorSell,
Vigency: response.Vigency,
}
database.OrderBookStore(datastorage)
return c.String(http.StatusOK, string(u))
}
95 changes: 95 additions & 0 deletions handlers/swap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package handlers

import (
"encoding/json"
"fmt"
"net/http"
"servertestgo/models"
"servertestgo/services"

"github.com/labstack/echo/v4"
)

type swapResponse struct {
request string
response string
}

func Swap(c echo.Context) error {

fmt.Println("Se solicito el swap")
var jsonmap map[string]interface{} = map[string]interface{}{}
if err := c.Bind(&jsonmap); err != nil {
return err
}

var id string
var ok bool
if x, found := jsonmap["id"]; found {
if id, ok = x.(string); !ok {
fmt.Println("id:", id)
}
} else {
return c.String(http.StatusBadRequest, `{"message": "Se requiere el Id"}`)
}

var side string
if x, found := jsonmap["side"]; found {
if side, ok = x.(string); !ok {
fmt.Println("side:", side)
}
} else {
return c.String(http.StatusBadRequest, `{"message": "Se requiere el side"}`)
}
var sz string
if x, found := jsonmap["sz"]; found {
if sz, ok = x.(string); !ok {
fmt.Println("sz:", sz)
}
} else {
return c.String(http.StatusBadRequest, `{"message": "Se requiere el sz"}`)
}
sideaceptables := []string{"buy", "sell"}
if contains(sideaceptables, side) == false {
return c.String(http.StatusBadRequest, `{"message": "Se requiere el side entre buy o sell"}`)
}
//datos validados creamos la orden
myorderarg := models.OrderArg{Side: side, InstId: "ETH-USD", TdMode: "isolated", OrdType: "market", Sz: sz}
myorder := models.Order{Id: id, Op: "order", Args: &myorderarg}

responseData := services.PlaceOrder(myorder)

requeststring, _ := json.Marshal(myorder)

responsestring, _ := json.Marshal(responseData)

u, _ := json.Marshal(swapResponse{request: string(requeststring), response: string(responsestring)})

return c.String(http.StatusOK, string(u))

}

func SwapAll(c echo.Context) error {
fmt.Println("Se solicito el swapAll")

// if len(id) < 5 || len(side) < 5 || len(sz) < 5 {
// response.ErrorResponse = "se requiere id , side , sz "
// u, _ := json.Marshal(response)
// return c.String(http.StatusPartialContent, string(u))
// }

// fmt.Println(nameEstimate)
// myOrderBook := services.PlaceOrder(nameEstimate)
// response.ValorBuy = myOrderBook.Data[0].Asks[0][0]
// response.ValorSell = myOrderBook.Data[0].Bids[0][0]
// response.Vigency = time.Now().Add(time.Second * 10)
// u, _ := json.Marshal(response)
// datastorage := models.OrderBookEntity{
// Currency: nameEstimate,
// ValorBuy: response.ValorBuy,
// ValorSell: response.ValorSell,
// Vigency: response.Vigency,
// }
// database.OrderBookStore(datastorage)
return c.String(http.StatusOK, " string(u)")
}
5 changes: 2 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"log"
"os"
"servertestgo/database"
"servertestgo/services"
"servertestgo/server"

"github.com/joho/godotenv"
)
Expand All @@ -25,8 +25,7 @@ func main() {
fmt.Println("API OKX:", OKX_API_URL)
DATABASE_NAME := os.Getenv("DATABASE_NAME")
database.InitDatabase(DATABASE_NAME)
services.SolicitarBookOrder("BTC-USDT")

server.InitServer(PORT)
}

// func MarketPrice() {
Expand Down
56 changes: 53 additions & 3 deletions models/order.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,58 @@
package models

import "gorm.io/gorm"
import (
"time"
)

type Order struct {
gorm.Model
Id string
Op string `json:"op" validate:"required"`
Id string `json:"id" validate:"required"`
Args *OrderArg `json:"args" validate:"required"`
expTime string
}

type OrderArg struct {
InstId string `json:"instId" validate:"required"`
TdMode string `json:"tdMode" validate:"required"`
Ccy string `json:"ccy"`
ClOrdId string `json:"clOrdId"`
Tag string `json:"tag"`
Side string `json:"side"`
PosSide string `json:"posSide"`
OrdType string `json:"ordType" validate:"required"`
Sz string `json:"sz"`
Px string `json:"px"`
ReduceOnly bool `json:"reduceOnly"`
TgtCcy string `json:"tgtCcy"`
BanAmend bool `json:"banAmend"`
QuickMgnType string `json:"quickMgnType"`
}

type OrderResponse struct {
Id string
Response string
Vigency time.Time
ValueCurrency string
errorResponse string
}

type OrderEntity struct {
InstId string `json:"instId"`
TdMode string `json:"tdMode"`
Ccy string `json:"ccy"`
ClOrdId string `json:"clOrdId"`
Tag string `json:"tag"`
Side string `json:"side"`
PosSide string `json:"posSide"`
OrdType string `json:"ordType"`
Sz string `json:"sz"`
Px string `json:"px"`
ReduceOnly bool `json:"reduceOnly"`
TgtCcy string `json:"tgtCcy"`
BanAmend bool `json:"banAmend"`
QuickMgnType string `json:"quickMgnType"`
Op string `json:"op"`
Id string `json:"id"`
Vigency time.Time
Response string
}
14 changes: 9 additions & 5 deletions models/orderBook.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package models

import "gorm.io/gorm"
import (
"time"

"gorm.io/gorm"
)

// para manejar las book order, creamos las estructuras
type (
Expand All @@ -18,9 +22,9 @@ type (

OrderBookEntity struct {
gorm.Model
DepthPrice float64
Size float64
LiquidatedOrder int
OrderNumbers int
Currency string
ValorBuy string
ValorSell string
Vigency time.Time
}
)
4 changes: 4 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,9 @@ func InitServer(PORT string) {
e := echo.New()
//registramos las rutas
e.GET("/", handlers.Home)
e.GET("/estimate/:name", handlers.Estimate)
e.POST("/swap/", handlers.Swap)
e.GET("/swap/", handlers.SwapAll)

e.Logger.Fatal(e.Start(PORT))
}
15 changes: 14 additions & 1 deletion services/okx.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func EjecutarConsulta(method, path, urlfilters, bodyJson string) (*http.Response
return resp, err
}

func SolicitarBookOrder(Currency string) {
func SolicitarBookOrder(Currency string) models.OrderBook {
resp, err := EjecutarConsulta("GET", "/api/v5/market/books", "?instId="+Currency, "")
if err != nil {
fmt.Print(err.Error())
Expand All @@ -71,4 +71,17 @@ func SolicitarBookOrder(Currency string) {
var dataorder models.OrderBook
json.NewDecoder(resp.Body).Decode(&dataorder)
fmt.Println(dataorder)
return dataorder
}

func PlaceOrder(miorden models.Order) models.OrderResponse {
resp, err := EjecutarConsulta("GET", "/api/v5/trade/order", "", "")
if err != nil {
fmt.Print(err.Error())
}
defer resp.Body.Close()
var dataOrderResponse models.OrderResponse
json.NewDecoder(resp.Body).Decode(&dataOrderResponse)
fmt.Println(dataOrderResponse)
return dataOrderResponse
}

0 comments on commit c5f0bf0

Please sign in to comment.