Advertisement
Guest User

Untitled

a guest
Jul 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // получили сообщение
  2. - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
  3.     NSError *jsonError;
  4.     NSData *objectData = [message dataUsingEncoding:NSUTF8StringEncoding];
  5.     id messageData = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
  6.  
  7.     if (jsonError) {
  8.         // ошибка сериализации json
  9.         return;
  10.     }
  11.  
  12.     if ([messageData isKindOfClass:[NSMutableDictionary class]]) {
  13.         // эвент
  14.         [self eventHandler:messageData];
  15.     }
  16.     if ([messageData isKindOfClass:[NSMutableArray class]]) {
  17.         // данные
  18.         [self dataHandler:messageData];
  19.     }
  20. }
  21.  
  22.  
  23. //-----------------------
  24. //эвенты
  25.  
  26. // обработчик событий
  27. - (void)eventHandler:(NSDictionary *)message {
  28.  
  29.     // info
  30.     if ([message[@"event"] isEqualToString:@"info"]) {
  31.         [self infoEvent:message];
  32.         return;
  33.     }
  34.  
  35.     // subscribed
  36.     if ([message[@"event"] isEqualToString:@"subscribed"]) {
  37.         [self subscribedEvent:message];
  38.         return;
  39.     }
  40.  
  41.     // error
  42.     if ([message[@"event"] isEqualToString:@"error"]) {
  43.         [self closeSocket];
  44.         [self openSocket];
  45.         return;
  46.     }
  47. }
  48.  
  49. - (void)infoEvent:(NSDictionary *)message {
  50.     if (![message[@"code"] isKindOfClass:[NSNull class]]) {
  51.         // достаем код ошибки
  52.         NSInteger code = [message[@"code"] integerValue];
  53.         if (code == 20051) {
  54.             // restart socket notify
  55.             NSLog(@"restart socket notify");
  56.             [self closeSocket];
  57.             [self openSocket];
  58.         }
  59.         if (code == 20060) {
  60.             // pause activity for 20061 code
  61.             NSLog(@"pause activity for 20061 code");
  62.         }
  63.         if (code == 20061) {
  64.             // resume activity
  65.             NSLog(@"resume activity");
  66.         }
  67.     }
  68. }
  69.  
  70. - (void)subscribedEvent:(NSDictionary *)message {
  71.     // ордера
  72.     if ([message[@"channel"] isEqualToString:@"book"]) {
  73.         self.channel = [message[@"chanId"] integerValue];
  74.     }
  75. }
  76.  
  77.  
  78.  
  79.  
  80. // ---------------------
  81. // данные
  82.  
  83. // обработчик данных
  84. - (void)dataHandler:(NSArray *)message {
  85.     // достаем канал
  86.     NSInteger chanelID = [message[0] integerValue];
  87.  
  88.     // стаканы
  89.     if (chanelID == self.channel) {
  90.         [self bookData:message];
  91.     }
  92. }
  93.  
  94. - (void)bookData:(NSArray *)message {
  95. //        Algorithm to create and keep a book instance updated
  96. //
  97. //    1.    subscribe to channel
  98. //    2.    receive the book snapshot and create your in-memory book structure
  99. //
  100.  
  101.     // смотрим не Heartbeating ли это
  102.     if ([message[1] isKindOfClass:[NSString class]]) {
  103.         NSString *hb = message[1];
  104.         if ([hb isEqualToString:@"hb"]) {
  105.             return;
  106.         }
  107.     }
  108.  
  109.  
  110.  
  111.     // снапшот приходит тока 1 раз по этому я его тока первый раз проверяю
  112.     // и при первом запуске или рестарте сокета self.snapshot = YES
  113.     // тип данных PBooksItem - собственно сам итем стакана массив
  114.     // @implementation PBooksItem
  115.     // - (instancetype)initWithArray:(NSArray *)item {
  116.     //    self = [super init];
  117.     //    if (self) {
  118.     //        self.price = [self floatItem:item[0]];    цена
  119.     //        self.count = [self integerItem:item[1]]; количество ордеров - не юзаем
  120.     //        self.amount = [self floatItem:item[2]]; обьем в битках
  121.     //    }
  122.     //    return self;
  123.     //}
  124.  
  125.     // определяем снапшот это или апдейт
  126.     if (self.snapshot) {
  127.         // snapshot
  128.         self.snapshot = NO;
  129.         for (NSArray *item in message[1]) {
  130.             PBooksItem *order = [[PBooksItem alloc] initWithArray:item];
  131.             if (order.amount > 0) {
  132.                 [self.bidTrades addObject:order];
  133.             }
  134.             if (order.amount < 0) {
  135.                 [self.askTrades addObject:order];
  136.             }
  137.         }
  138.     } else {
  139.         // update
  140.         //    3.    when count > 0 then you have to add or update the price level
  141.         //    3.1   if amount > 0 then add/update bidTrades
  142.         //    3.2   if amount < 0 then add/update askTrades
  143.         //
  144.         //    4.    when count = 0 then you have to delete the price level.
  145.         //    4.1 if amount = 1 then remove from bidTrades
  146.         //    4.2 if amount = -1 then remove from askTrades
  147.  
  148.  
  149.         // NSLog(@"update");
  150.         NSArray *item = message[1];
  151.         PBooksItem *order = [[PBooksItem alloc] initWithArray:item];
  152.  
  153.         // 3.    when count > 0 then you have to add or update the price level
  154.         if (order.count > 0) {
  155.             if (order.amount > 0) {
  156.                 // 3.1   if amount > 0 then add/update bidTrades
  157.                 [self addUpdateBids:order];
  158.             }
  159.             if (order.amount < 0) {
  160.                 // 3.2   if amount < 0 then add/update askTrades
  161.                 [self addUpdateAsks:order];
  162.             }
  163.         }
  164.         // 4.    when count = 0 then you have to delete the price level.
  165.         if (order.count == 0) {
  166.             if (order.amount == 1) {
  167.                 // 4.1 if amount = 1 then remove from bidTrades
  168.                 [self removeFromBids:order];
  169.             }
  170.             if (order.amount == -1) {
  171.                 // 4.2 if amount = -1 then remove from askTrades
  172.                 [self removeFromAsks:order];
  173.             }
  174.         }
  175.     }
  176. }
  177.  
  178.  
  179. - (void)addUpdateBids:(PBooksItem *)order {
  180.     if (self.bidTrades.count == 0) {
  181.         // добавляем если массив стакана bidTrades пуст
  182.         [self.bidTrades addObject:order];
  183.         return;
  184.     }
  185.     // проверяем первый
  186.     PBooksItem *bidFirst = self.bidTrades[0];
  187.     if (order.price == bidFirst.price) {
  188.         // replace
  189.         self.bidTrades[0] = order;
  190.         return;
  191.     }
  192.     if (order.price > bidFirst.price) {
  193.         // add order first
  194.         [self.bidTrades insertObject:order atIndex:0];
  195.         return;
  196.     }
  197.  
  198.     // проверяем последний
  199.     PBooksItem *bidLast = self.bidTrades[self.bidTrades.count - 1];
  200.     if (order.price == bidLast.price) {
  201.         // replace
  202.         self.bidTrades[self.bidTrades.count - 1] = order;
  203.         return;
  204.     }
  205.     if (order.price < bidLast.price) {
  206.         // add order last
  207.         [self.bidTrades addObject:order];
  208.         return;
  209.     }
  210.  
  211.     // находим куда вставить или заменить
  212.     for (NSUInteger index = 0; index <= self.bidTrades.count - 2; index++) {
  213.         PBooksItem *bid = self.bidTrades[index];
  214.         if (order.price == bid.price) {
  215.             // replace
  216.             self.bidTrades[index] = order;
  217.             return;
  218.         }
  219.  
  220.         PBooksItem *bidNext = self.bidTrades[index + 1];
  221.         if (order.price < bid.price && order.price > bidNext.price) {
  222.             // insert
  223.             [self.bidTrades insertObject:order atIndex:index + 1];
  224.             return;
  225.         }
  226.     }
  227. }
  228.  
  229. - (void)addUpdateAsks:(PBooksItem *)order {
  230.  
  231.     if (self.askTrades.count == 0) {
  232.         [self.askTrades addObject:order];
  233.         return;
  234.     }
  235.  
  236.  
  237.     PBooksItem *askFirst = self.askTrades[0];
  238.     if (order.price == askFirst.price) {
  239.         // replace
  240.         self.askTrades[0] = order;
  241.         return;
  242.     }
  243.     if (order.price < askFirst.price) {
  244.         // add order first
  245.         [self.askTrades insertObject:order atIndex:0];
  246.         return;
  247.     }
  248.  
  249.     PBooksItem *askLast = self.askTrades[self.askTrades.count - 1];
  250.     if (order.price == askLast.price) {
  251.         // replace
  252.         self.askTrades[self.askTrades.count - 1] = order;
  253.         return;
  254.     }
  255.     if (order.price > askLast.price) {
  256.         // add order last
  257.         [self.askTrades addObject:order];
  258.         return;
  259.     }
  260.     // находим куда вставить или заменить
  261.     for (NSUInteger index = 0; index <= self.askTrades.count - 2; index++) {
  262.         PBooksItem *ask = self.askTrades[index];
  263.         if (order.price == ask.price) {
  264.             // replace
  265.             self.askTrades[index] = order;
  266.             return;
  267.         }
  268.         PBooksItem *askNext = self.askTrades[index + 1];
  269.         if (order.price > ask.price && order.price < askNext.price) {
  270.             // insert
  271.             [self.askTrades insertObject:order atIndex:index + 1];
  272.             return;
  273.         }
  274.     }
  275.  
  276. }
  277.  
  278. - (void)removeFromBids:(PBooksItem *)order {
  279.  
  280.     for (NSUInteger index = 0; index <= self.bidTrades.count - 1; index++) {
  281.         PBooksItem *bid = self.bidTrades[index];
  282.         if (bid.price == order.price) {
  283.             [self.bidTrades removeObjectAtIndex:index];
  284.             return;
  285.         }
  286.     }
  287.  
  288. }
  289.  
  290. - (void)removeFromAsks:(PBooksItem *)order {
  291.  
  292.     for (NSUInteger index = 0; index <= self.askTrades.count - 1; index++) {
  293.         PBooksItem *ask = self.askTrades[index];
  294.         if (ask.price == order.price) {
  295.             [self.askTrades removeObjectAtIndex:index];
  296.             return;
  297.         }
  298.     }
  299.  
  300. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement